{"version":3,"sources":["../../../node_modules/tsup/assets/cjs_shims.js","../src/auth.ts","../src/otel.ts","../src/security.ts","../src/security-card.ts","../src/advisories/match.ts","../src/advisories/pep440.ts","../src/extract/shared.ts","../src/advisories/fix-action.ts","../src/security-scan.ts","../src/advisories/index.ts","../src/advisories/normalize.ts","../src/advisories/source.ts","../src/advisories/release-fetch.ts","../src/advisories/fixdiff.ts","../src/extract/symbols.ts","../src/extract/errors.ts","../src/extract/calls/shared.ts","../src/extract/gitignore.ts","../src/security-diff.ts","../src/extract.ts","../src/extract/index.ts","../src/graph.ts","../src/ingest.ts","../src/durable-incident.ts","../src/credential-scrub.ts","../src/policy.ts","../src/compat.ts","../compat.json","../src/events.ts","../src/traverse.ts","../src/traffic-source.ts","../src/process-log.ts","../src/extract/routes.ts","../src/extract/imports.ts","../src/extract/go.ts","../src/extract/source-baseline.ts","../src/extract/infra/shared.ts","../src/columns.ts","../src/flags.ts","../src/latency-digest.ts","../src/stacktrace.ts","../src/extract/services.ts","../src/extract/python.ts","../src/extract/go-binaries.ts","../src/extract/ruby.ts","../src/extract/php.ts","../src/extract/csharp.ts","../src/extract/java.ts","../src/extract/kotlin.ts","../src/extract/rust.ts","../src/extract/cpp.ts","../src/extract/dockerfile-service.ts","../src/extract/owners.ts","../src/extract/aliases.ts","../src/extract/files.ts","../src/extract/symbol-edges.ts","../src/extract/go-symbol-edges.ts","../src/extract/java-symbol-edges.ts","../src/extract/actions.ts","../src/extract/databases/index.ts","../src/extract/databases/db-config-yaml.ts","../src/extract/databases/dotenv.ts","../src/extract/databases/shared.ts","../src/extract/databases/prisma.ts","../src/extract/databases/drizzle.ts","../src/extract/databases/knex.ts","../src/extract/databases/ormconfig.ts","../src/extract/databases/typeorm.ts","../src/extract/databases/sequelize.ts","../src/extract/databases/csharp.ts","../src/extract/databases/spring.ts","../src/extract/databases/docker-compose.ts","../src/extract/configs.ts","../src/extract/flags.ts","../src/extract/flags-configmap.ts","../src/extract/java-routes.ts","../src/extract/tornado-routes.ts","../src/extract/java-gateway.ts","../src/extract/proto.ts","../src/extract/calls/index.ts","../src/extract/calls/http.ts","../src/extract/calls/route-match.ts","../src/extract/calls/kafka.ts","../src/extract/calls/redis.ts","../src/extract/calls/aws.ts","../src/extract/calls/grpc.ts","../src/extract/calls/supabase.ts","../src/extract/calls/firestore.ts","../src/extract/calls/mongoose.ts","../src/extract/calls/sqlalchemy.ts","../src/extract/calls/socket.ts","../src/extract/calls/django-orm.ts","../src/extract/calls/drizzle.ts","../src/extract/calls/prisma.ts","../src/extract/calls/activerecord.ts","../src/extract/calls/eloquent.ts","../src/extract/calls/go.ts","../src/extract/calls/gorm.ts","../src/extract/calls/efcore.ts","../src/extract/calls/mysql-js.ts","../src/extract/calls/dbapi-python.ts","../src/extract/calls/jpa.ts","../src/extract/java-calls.ts","../src/extract/table-edges.ts","../src/extract/infra/index.ts","../src/extract/infra/docker-compose.ts","../src/extract/infra/dockerfile.ts","../src/extract/infra/terraform.ts","../src/extract/infra/k8s.ts","../src/extract/infra/cloudflare.ts","../src/extract/infra/vercel.ts","../src/extract/infra/railway.ts","../src/extract/infra/supabase.ts","../src/extract/infra/nginx.ts","../src/extract/zod-shapes.ts","../src/extract/firestore-rules.ts","../src/extract/dependencies/index.ts","../src/extract/dependencies/go-mod.ts","../src/extract/dependencies/npm-lock.ts","../src/extract/dependencies/resolved.ts","../src/extract/dependencies/pnpm-lock.ts","../src/extract/dependencies/yarn-lock.ts","../src/extract/dependencies/python-lock.ts","../src/extract/dependencies/imports-to-deps.ts","../src/extract/dependency-symbols/locate.ts","../src/extract/retire.ts","../src/security-apply.ts"],"sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n  typeof document === \"undefined\" \n    ? new URL(`file:${__filename}`).href \n    : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n      ? document.currentScript.src \n      : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","/**\n * Delegated auth at the daemon boundary (ADR-073 §3 + §4).\n *\n * NEAT does not issue, rotate, or distribute the token — that is the deploy\n * platform's job. This module provides the two surfaces the daemon needs:\n *\n *   - `assertBindAuthority(host, token)` — fail-loud pre-bind check. When no\n *     token is set, the daemon refuses to bind on any non-loopback address.\n *     Loopback-only without a token stays unauthenticated (laptop dev path).\n *\n *   - `mountBearerAuth(app, opts)` — Fastify `preHandler` that requires\n *     `Authorization: Bearer <token>` on every request other than the\n *     unauthenticated health/readiness probes. Constant-time comparison.\n *\n * The same shape covers both the REST host and the OTLP receivers; the OTLP\n * side passes a different token (`NEAT_OTEL_TOKEN ?? NEAT_AUTH_TOKEN`) so the\n * two surfaces rotate independently.\n */\n\nimport { timingSafeEqual } from 'node:crypto'\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'\n\n// Hosts that count as loopback for the bind-authority gate. `0.0.0.0` is\n// explicitly not loopback — it binds on every interface, including any\n// public one the operator's box happens to have.\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set([\n  '127.0.0.1',\n  'localhost',\n  '::1',\n  '::ffff:127.0.0.1',\n])\n\nexport function isLoopbackHost(host: string | undefined | null): boolean {\n  if (!host) return false\n  return LOOPBACK_HOSTS.has(host)\n}\n\nexport class BindAuthorityError extends Error {\n  constructor(host: string) {\n    super(\n      `NEAT refuses to bind on a public interface without \\`NEAT_AUTH_TOKEN\\` set (host=\"${host}\"). Set the token or bind to loopback only.`,\n    )\n    this.name = 'BindAuthorityError'\n  }\n}\n\nexport function assertBindAuthority(host: string, token: string | undefined): void {\n  if (token && token.length > 0) return\n  if (isLoopbackHost(host)) return\n  throw new BindAuthorityError(host)\n}\n\nexport interface AuthOptions {\n  // Bearer token required on every protected route. Undefined / empty → the\n  // middleware is not mounted and the route stays unauthenticated. The\n  // loopback-only gate above is what keeps that case from being public.\n  token?: string\n  // When `true`, trust an upstream reverse proxy and skip the request-side\n  // check. The fail-loud bind-authority gate still applies upstream. Wired\n  // to `NEAT_AUTH_PROXY=true` in production.\n  trustProxy?: boolean\n  // ADR-073 §3 amendment — public-read mode for reference deployments.\n  // When `true`, GET / HEAD / OPTIONS pass through without a bearer; every\n  // other verb still requires the token. OTLP ingest is excluded — that\n  // surface stays gated unconditionally (the receiver mounts its own\n  // middleware without this flag).\n  publicRead?: boolean\n  // Extra paths to leave unauthenticated, matched exactly (no suffix\n  // matching — see the note on DEFAULT_UNAUTH_PATHS below). Used by tests\n  // and by ad-hoc callers that mount their own probes.\n  extraUnauthenticatedSuffixes?: ReadonlyArray<string>\n  // Diagnostic hook fired whenever a request is rejected with 401 for a\n  // missing or invalid bearer. The REST host leaves this unset — a human\n  // running `curl` doesn't need a server-side line for their own 401. The\n  // OTLP receiver passes it so an app whose telemetry is being dropped for a\n  // bad token leaves a signal on the daemon side instead of failing silently.\n  // The hook does not change the response body or status; it only observes.\n  onReject?: () => void\n}\n\n// Verbs the public-read split treats as reads. Everything else is a write\n// and keeps the bearer requirement.\nconst PUBLIC_READ_METHODS: ReadonlySet<string> = new Set(['GET', 'HEAD', 'OPTIONS'])\n\n// Probes that always stay open. `/health` is dual-mounted under\n// `/projects/:project/` too (registerRoutes mounts it both unprefixed and\n// inside the `/projects/:project` plugin scope) — that's the one project-\n// scoped variant a real route relies on today. ADR-073 §3 names `/healthz`\n// and `/readyz` explicitly as reserved probe paths (no handler registers them\n// yet); `/health` is the existing endpoint the web shell and CI smoke already\n// lean on. `/api/config` is the public-read negotiation endpoint — the web\n// shell hits it before any authed call to learn which mode the daemon is\n// running in.\n//\n// Matching used to be `path === suffix || path.endsWith(suffix)`, which\n// exempts *any* path that merely ends with one of these strings — a future\n// protected route named e.g. `/admin/health` would slip through\n// unauthenticated by accident. Matching is now exact on the root path, plus\n// one explicit pattern for the `/projects/:project/<name>` shape. Nothing\n// else qualifies.\nconst DEFAULT_UNAUTH_PATHS: ReadonlyArray<string> = [\n  '/health',\n  '/healthz',\n  '/readyz',\n  '/api/config',\n]\n\n// `/projects/<one segment>/health` (or /healthz, /readyz, /api/config) —\n// exactly one path segment for the project name, nothing before `/projects`\n// and nothing after the probe name. Built from DEFAULT_UNAUTH_PATHS so the\n// two lists can't drift.\nconst PROJECT_SCOPED_UNAUTH_PATTERN = new RegExp(\n  `^/projects/[^/]+/(?:${DEFAULT_UNAUTH_PATHS.map((p) => p.slice(1)).join('|')})$`,\n)\n\n/** Route config marking a route as authenticated by its own handler. */\nexport const BEARER_DELEGATED = { bearerDelegated: true } as const\n\nfunction isBearerDelegated(req: FastifyRequest): boolean {\n  const config = req.routeOptions?.config as { bearerDelegated?: unknown } | undefined\n  return config?.bearerDelegated === true\n}\n\nexport function mountBearerAuth(app: FastifyInstance, opts: AuthOptions): void {\n  if (!opts.token || opts.token.length === 0) return\n  if (opts.trustProxy) return\n\n  const expected = Buffer.from(opts.token, 'utf8')\n  const exactUnauthPaths = new Set([\n    ...DEFAULT_UNAUTH_PATHS,\n    ...(opts.extraUnauthenticatedSuffixes ?? []),\n  ])\n  const publicRead = opts.publicRead === true\n\n  app.addHook('preHandler', (req: FastifyRequest, reply: FastifyReply, done: (err?: Error) => void) => {\n    const path = (req.url.split('?')[0] ?? '').replace(/\\/+$/, '')\n    if (exactUnauthPaths.has(path) || PROJECT_SCOPED_UNAUTH_PATTERN.test(path)) {\n      done()\n      return\n    }\n\n    // A route that checks a different bearer itself. The OTLP routes served on\n    // the REST listener are gated by the ingest token, not this one, so this\n    // hook stands aside and the receiver behind them decides (ADR-073 §4). The\n    // flag lives on the route, so no path string can claim it by resemblance.\n    if (isBearerDelegated(req)) {\n      done()\n      return\n    }\n\n    // Public-read split: GET / HEAD / OPTIONS pass through anonymously, every\n    // other verb keeps the bearer check. The token still authorizes writes,\n    // and the bind-authority gate above still demands a token for non-loopback\n    // binds — public-read enables anonymous reads on top of that, it doesn't\n    // replace either invariant.\n    if (publicRead && PUBLIC_READ_METHODS.has(req.method)) {\n      done()\n      return\n    }\n\n    const header = req.headers.authorization\n    if (typeof header !== 'string' || !header.startsWith('Bearer ')) {\n      opts.onReject?.()\n      void reply.code(401).send({ error: 'unauthorized' })\n      return\n    }\n    const provided = Buffer.from(header.slice('Bearer '.length).trim(), 'utf8')\n    if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {\n      opts.onReject?.()\n      void reply.code(401).send({ error: 'unauthorized' })\n      return\n    }\n    done()\n  })\n}\n\n// Read both tokens from the environment in one place so server.ts, daemon.ts,\n// and the OTel receivers all agree on precedence (ADR-073 §4). `publicRead`\n// rides the same shape so callers don't need a second env read.\nexport interface AuthEnv {\n  authToken: string | undefined\n  otelToken: string | undefined\n  trustProxy: boolean\n  publicRead: boolean\n}\n\nfunction parseBoolEnv(v: string | undefined): boolean {\n  if (!v) return false\n  return v === 'true' || v === '1'\n}\n\nexport function readAuthEnv(env: NodeJS.ProcessEnv = process.env): AuthEnv {\n  const t = env.NEAT_AUTH_TOKEN\n  const ot = env.NEAT_OTEL_TOKEN\n  return {\n    authToken: t && t.length > 0 ? t : undefined,\n    otelToken: ot && ot.length > 0 ? ot : t && t.length > 0 ? t : undefined,\n    trustProxy: env.NEAT_AUTH_PROXY === 'true',\n    publicRead: parseBoolEnv(env.NEAT_PUBLIC_READ),\n  }\n}\n","import path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport zlib from 'node:zlib'\nimport type { Transform } from 'node:stream'\nimport Fastify, { type FastifyInstance } from 'fastify'\nimport protobuf from 'protobufjs'\nimport { mountBearerAuth } from './auth.js'\n\n// OTLP/HTTP receiver. Listens on /v1/traces and decodes the JSON wire format\n// (collector's `otlphttp` exporter with `encoding: json`). Each span is\n// flattened into a ParsedSpan and handed to the configured handler. The\n// handler is the seam #8 wires its edge mapper into; #7 itself stays decoupled\n// from graph mutation.\n\nexport interface ParsedSpan {\n  service: string\n  // True when the resource carried a `service.name` attribute. False (or\n  // omitted, for legacy producers) routes the span to `service:unidentified`\n  // in the resolved project and trips a once-per-session-per-project warning\n  // on the ingest side (issue #374). OTel spec requires SDKs to set\n  // `service.name`, but customised exporters can omit it — diagnostic\n  // visibility beats silent drop. Field is optional so test fixtures that\n  // hand-construct ParsedSpan with a known service.name don't need to set\n  // a flag they don't care about; the receiver always sets it.\n  // See docs/contracts/otlp-routing.md §Fallback when `resource.service.name`\n  // is missing.\n  resourceServiceNamePresent?: boolean\n  traceId: string\n  spanId: string\n  parentSpanId?: string\n  name: string\n  kind?: number\n  startTimeUnixNano: string\n  endTimeUnixNano: string\n  // ISO8601 derived from startTimeUnixNano. Production paths (lastObserved on\n  // OBSERVED edges) read this so the recorded time reflects when the span fired,\n  // not when the receiver received it. Undefined only when startTimeUnixNano is\n  // missing or unparseable — handler falls back to wall-clock in that case.\n  // See docs/contracts/otel-ingest.md §lastObserved-from-span-time.\n  startTimeIso?: string\n  // How many per-message events the span carries (ADR-272): OTel's RPC\n  // instrumentations record one `message` event (with `message.type` SENT or\n  // RECEIVED) per message on the call. A unary call carries at most one each way;\n  // more than two is a stream. Undefined when the span carries none.\n  messageEventCount?: number\n  // bigint so the 9-digit-nanos arithmetic doesn't lose precision on long traces.\n  durationNanos: bigint\n  // Deployment environment from `deployment.environment(.name)`. Span attrs\n  // win over resource attrs (per-span overrides a resource-wide declaration);\n  // the canonical `deployment.environment.name` (OTel SC v1.27+) wins over\n  // the compat form `deployment.environment`. Literal `'unknown'` is the\n  // honest fallback when no env signal is present anywhere on the span or\n  // its resource. See ADR-074 §2 / docs/contracts/env-dimension.md.\n  env: string\n  // The k8s namespace off the span's resource (`k8s.namespace.name`), when the SDK\n  // or collector stamps it. The daemon uses it to scope ingest to a project's\n  // declared namespaces (connector-config.md §k8s): on a collector shared by several\n  // apps, a span from a neighbour app's namespace is dropped rather than fused into\n  // the wrong project's graph. Undefined keeps today's behaviour. See\n  // docs/contracts/otel-ingest.md §Namespace scoping.\n  k8sNamespace?: string\n  attributes: Record<string, AttributeValue>\n  // Convenience accessors for the attributes #8 cares about.\n  dbSystem?: string\n  dbName?: string\n  // The collection a `db.system: mongodb` span operated on (ADR-148). The\n  // mongodb / mongoose instrumentation sets `db.collection.name` in the stable\n  // convention, `db.mongodb.collection` in the older one — read the first, fall\n  // back to the second.\n  dbCollection?: string\n  // The table a SQL span operated on (ADR-152). The SQLAlchemy / dbapi\n  // instrumentation emits no table attribute — the table is only inside the\n  // `db.statement` SQL text — so this is parsed from it (`tableFromSqlStatement`),\n  // conservatively: a single FROM/INTO/UPDATE table, else undefined.\n  dbTable?: string\n  // The columns that same SQL span TOUCHED (ADR-157 §2), parsed from the\n  // `db.statement` alongside the table (`columnsFromSqlStatement`). Empty when\n  // the statement recovers no columns (a `SELECT *`, an aggregate, a JOIN /\n  // subquery degrade, or a shape the parser doesn't read). Merged onto the\n  // `sql-table` node as OBSERVED column attributes in handleSpan.\n  dbColumns?: string[]\n  // The served route + method off a SERVER span (#576). `http.route` is the\n  // templated path the router matched (`/users/{id}`); the method is the stable\n  // `http.request.method`, falling back to the legacy `http.method`. handleSpan\n  // matches these against the statically-extracted RouteNode to mint the OBSERVED\n  // twin of a declared route.\n  httpRoute?: string\n  httpMethod?: string\n  // Messaging semconv (OTel). `messaging.system` names the broker family\n  // (kafka, rabbitmq, redis, …); the destination is the topic/queue the span\n  // produced to or consumed from — the canonical `messaging.destination.name`\n  // (SC v1.24+) with the legacy `messaging.destination` as fallback. handleSpan\n  // reads these to mint a PUBLISHES_TO (PRODUCER) or CONSUMES_FROM (CONSUMER)\n  // OBSERVED edge to the destination node, fusing with the static extractor's\n  // topic node. See docs/contracts/otel-ingest.md §Queue producers and consumers.\n  messagingSystem?: string\n  messagingDestination?: string\n  // GraphQL semconv (OTel). `graphql.operation.name` is the client-supplied\n  // operation name the execution span resolved (`GetUser`); `graphql.operation.type`\n  // is the operation kind (`query` / `mutation` / `subscription`). handleSpan reads\n  // both to mint an OBSERVED `CONTAINS` edge from the serving service to a\n  // per-operation node, recovering the operation-level topology that HTTP grain\n  // collapses onto `POST /graphql`. See docs/contracts/otel-ingest.md §GraphQL\n  // operations.\n  graphqlOperationName?: string\n  graphqlOperationType?: string\n  // gRPC RPC semconv (OTel). `rpc.system` names the RPC framework (`grpc`);\n  // `rpc.service` is the fully-qualified proto service (`orders.OrderService`)\n  // and `rpc.method` the bare method (`GetOrder`). The serving (SERVER) and\n  // calling (CLIENT) sides both carry these. handleSpan reads them off the\n  // serving span to mint an OBSERVED `CONTAINS` edge from the serving service to\n  // a per-method node, recovering the method-level topology gRPC's service-grain\n  // edge collapses — and keyed so the static `.proto` definition fuses onto the\n  // same node. See docs/contracts/otel-ingest.md §gRPC methods.\n  rpcSystem?: string\n  rpcService?: string\n  rpcMethod?: string\n  // Opentracing / Jaeger datastore clients name the datastore in `peer.service` (the\n  // engine, e.g. `memcached`) and the host in `peer.hostname`, with no `db.system`\n  // (#1415). Set from those attributes so ingest can resolve the datastore the\n  // OTel-native db branch would miss.\n  peerService?: string\n  peerHostname?: string\n  // WebSocket channel (OTel HTTP semconv). A WebSocket connection opens with an\n  // HTTP upgrade handshake: a SERVER `GET` whose `Upgrade` request header names\n  // `websocket`. That single span is the only reliable OBSERVED signal a channel\n  // exists — the message frames afterwards ride the socket, not more spans. This\n  // field carries the channel path off that upgrade span (`http.route` when the\n  // router templated it, else `url.path` / `http.target`), and is set only when\n  // the upgrade header is present. handleSpan reads it to mint a\n  // WebSocketChannelNode and an OBSERVED `CONNECTS_TO` edge from the serving\n  // service to it. See docs/contracts/otel-ingest.md §WebSocket channels.\n  websocketChannel?: string\n  // 0 = UNSET, 1 = OK, 2 = ERROR per OTLP. We only care that 2 means error.\n  statusCode?: number\n  errorMessage?: string\n  // Pre-extracted from a span event with name=\"exception\". OTLP SDKs record\n  // exceptions this way (richer than status.message). handleSpan reads these\n  // first, falling back to status.message and span.name. See\n  // docs/contracts/otel-ingest.md §exception-data-from-span-events.\n  exception?: {\n    type?: string\n    message?: string\n    stacktrace?: string\n  }\n  // Feature-flag evaluations recorded on the span as `feature_flag.evaluation`\n  // events (OTel feature-flag semconv; ADR-242). Each is what one evaluation\n  // returned: the flag key, the variant, the provider, and the OpenFeature\n  // reason. The evaluation context is never read. handleSpan folds them onto the\n  // flag grain of the matching flag-store node.\n  flagEvaluations?: FlagEvaluation[]\n}\n\nexport interface FlagEvaluation {\n  key: string\n  variant?: string\n  provider?: string\n  reason?: string\n}\n\nexport type AttributeValue =\n  | string\n  | number\n  | boolean\n  | bigint\n  | string[]\n  | number[]\n  | boolean[]\n  | null\n\nexport type SpanHandler = (span: ParsedSpan) => void | Promise<void>\n// Variant that receives the project the URL already resolved to. Used by the\n// project-scoped route mounted at `/projects/:project/v1/traces` (issue #367):\n// the receiver hands the URL-path project to the daemon directly so the\n// daemon never has to guess via `service.name`-against-registry matching.\nexport type ProjectSpanHandler = (project: string, span: ParsedSpan) => void | Promise<void>\n\nexport interface BuildOtelReceiverOptions {\n  onSpan: SpanHandler\n  // Synchronous handler for spans with statusCode === 2. The receiver awaits\n  // it before replying, so a write failure can return 500 → OTel SDK retries.\n  // Optional — wiring is expected to plumb appendErrorEvent here when error\n  // durability matters; ad-hoc receivers leave it undefined.\n  // See docs/contracts/otel-ingest.md §Error events.\n  onErrorSpanSync?: (span: ParsedSpan) => Promise<void>\n  // Project-scoped variants — used by the `/projects/:project/v1/traces`\n  // route. When unset the route is still mounted but falls through to the\n  // legacy `onSpan` / `onErrorSpanSync` handlers (the project name is then\n  // available to the consumer via the `OTEL_PROJECT_OVERRIDE` attribute on\n  // each parsed span; ad-hoc receivers commonly leave both unset).\n  onProjectSpan?: ProjectSpanHandler\n  onProjectErrorSpanSync?: (project: string, span: ParsedSpan) => Promise<void>\n  // #881 — decides whether the `/projects/:project/v1/traces` route serves the\n  // named project. When it returns false the route replies 404 instead of a\n  // 200 + empty `partialSuccess` that silently drops the batch, so a\n  // misconfigured exporter (a wrong or wrong-cased project name in the URL)\n  // finds out. Optional: when unset the route accepts any name — the\n  // single-project `neat watch` receiver, where the URL name is advisory since\n  // there is only one project to land in.\n  isProjectRegistered?: (project: string) => boolean\n  // #881 — classifies a bare `/v1/traces` batch for routability before reply.\n  // The bare route replies 200 as soon as the body is parsed (§Non-blocking\n  // ingest) and only routes each span later, off the queue — so without this\n  // hook an unroutable span leaves on a 200 + empty `partialSuccess`, which an\n  // OTel exporter reads as \"everything accepted\" while the batch was dropped.\n  // The hook returns how many spans in the batch belong to no project this\n  // daemon hosts (and a human message); the receiver keeps the 200 but reports\n  // those as `partialSuccess.rejectedSpans` + `errorMessage` so a misconfigured\n  // exporter finds out. Pure and synchronous: it reads in-memory routing state,\n  // never mutates the graph or writes the unrouted ledger — the async `onSpan`\n  // path still owns the drop and the `errors.ndjson` record. Optional: an\n  // ad-hoc or single-consumer receiver leaves it unset and keeps the historical\n  // empty-`partialSuccess` reply for every batch.\n  classifyBareRoutability?: (spans: ParsedSpan[]) => { rejected: number; message?: string }\n  // Fastify body limit. OTLP batches can be large; default is 16 MB.\n  bodyLimit?: number\n  // ADR-073 §4 — bearer required on `/v1/traces`. Defaults to `NEAT_AUTH_TOKEN`\n  // when unset; `NEAT_OTEL_TOKEN` overrides at the call site so the REST and\n  // OTLP surfaces rotate on independent schedules.\n  authToken?: string\n  // Same shape as the REST middleware: skip the request-side check when an\n  // upstream reverse proxy already authenticated.\n  trustProxy?: boolean\n}\n\ninterface OtlpKeyValue {\n  key: string\n  value?: OtlpAnyValue\n}\n\ninterface OtlpAnyValue {\n  stringValue?: string\n  intValue?: string | number\n  doubleValue?: number\n  boolValue?: boolean\n  arrayValue?: { values?: OtlpAnyValue[] }\n  // kvlistValue / bytesValue are skipped — neither is on the demo path.\n}\n\ninterface OtlpStatus {\n  code?: number\n  message?: string\n}\n\ninterface OtlpEvent {\n  name?: string\n  timeUnixNano?: string\n  attributes?: OtlpKeyValue[]\n}\n\ninterface OtlpSpan {\n  traceId?: string\n  spanId?: string\n  parentSpanId?: string\n  name?: string\n  kind?: number\n  startTimeUnixNano?: string\n  endTimeUnixNano?: string\n  attributes?: OtlpKeyValue[]\n  events?: OtlpEvent[]\n  status?: OtlpStatus\n}\n\n// The per-message events an RPC span carries (ADR-272): named `message`, or\n// carrying `message.type` / `rpc.message.type`, whatever an instrumentation names\n// them.\nfunction messageEventCountOf(events: OtlpEvent[] | undefined): { messageEventCount?: number } {\n  if (!events || events.length === 0) return {}\n  let n = 0\n  for (const ev of events) {\n    if (ev.name === 'message' || (ev.attributes ?? []).some((a) => a.key === 'message.type' || a.key === 'rpc.message.type')) n++\n  }\n  return n > 0 ? { messageEventCount: n } : {}\n}\n\nfunction extractExceptionFromEvents(events: OtlpEvent[] | undefined): ParsedSpan['exception'] {\n  if (!events) return undefined\n  for (const ev of events) {\n    if (ev.name !== 'exception') continue\n    const attrs = attrsToRecord(ev.attributes)\n    const out: ParsedSpan['exception'] = {}\n    const t = attrs['exception.type']\n    const m = attrs['exception.message']\n    const s = attrs['exception.stacktrace']\n    if (typeof t === 'string') out.type = t\n    if (typeof m === 'string') out.message = m\n    if (typeof s === 'string') out.stacktrace = s\n    if (out.type || out.message || out.stacktrace) return out\n  }\n  return undefined\n}\n\n// Current semconv names first, then the legacy names OpenFeature's older\n// telemetry helpers still emit.\nfunction firstString(attrs: Record<string, AttributeValue>, names: string[]): string | undefined {\n  for (const n of names) {\n    const v = attrs[n]\n    if (typeof v === 'string' && v.length > 0) return v\n  }\n  return undefined\n}\n\nfunction extractFlagEvaluations(events: OtlpEvent[] | undefined): FlagEvaluation[] | undefined {\n  if (!events) return undefined\n  const out: FlagEvaluation[] = []\n  for (const ev of events) {\n    if (ev.name !== 'feature_flag.evaluation' && ev.name !== 'feature_flag') continue\n    const attrs = attrsToRecord(ev.attributes)\n    const key = firstString(attrs, ['feature_flag.key'])\n    if (!key) continue\n    const variant = firstString(attrs, ['feature_flag.result.variant', 'feature_flag.variant'])\n    const provider = firstString(attrs, ['feature_flag.provider.name', 'feature_flag.provider_name'])\n    const reason = firstString(attrs, ['feature_flag.result.reason', 'feature_flag.evaluation.reason'])\n    out.push({\n      key,\n      ...(variant ? { variant } : {}),\n      ...(provider ? { provider } : {}),\n      ...(reason ? { reason } : {}),\n    })\n  }\n  return out.length > 0 ? out : undefined\n}\n\ninterface OtlpScopeSpans {\n  spans?: OtlpSpan[]\n}\n\ninterface OtlpResourceSpans {\n  resource?: { attributes?: OtlpKeyValue[] }\n  scopeSpans?: OtlpScopeSpans[]\n}\n\nexport interface OtlpTracesRequest {\n  resourceSpans?: OtlpResourceSpans[]\n}\n\nfunction flattenAttribute(v: OtlpAnyValue | undefined): AttributeValue {\n  if (!v) return null\n  if (v.stringValue !== undefined) return v.stringValue\n  if (v.boolValue !== undefined) return v.boolValue\n  if (v.intValue !== undefined) {\n    return typeof v.intValue === 'string' ? Number(v.intValue) : v.intValue\n  }\n  if (v.doubleValue !== undefined) return v.doubleValue\n  if (v.arrayValue?.values) {\n    return v.arrayValue.values.map((x) => flattenAttribute(x)) as AttributeValue\n  }\n  return null\n}\n\nfunction attrsToRecord(attrs: OtlpKeyValue[] | undefined): Record<string, AttributeValue> {\n  const out: Record<string, AttributeValue> = {}\n  if (!attrs) return out\n  for (const kv of attrs) {\n    if (kv.key) out[kv.key] = flattenAttribute(kv.value)\n  }\n  return out\n}\n\nfunction durationNanos(start?: string, end?: string): bigint {\n  if (!start || !end) return 0n\n  try {\n    return BigInt(end) - BigInt(start)\n  } catch {\n    return 0n\n  }\n}\n\n// Convert OTLP's startTimeUnixNano (a base-10 string of nanoseconds since the\n// Unix epoch) to ISO8601. Returns undefined when the input is missing, zero,\n// or unparseable, so the caller can fall back to wall-clock without surfacing\n// a fake timestamp on the edge.\nexport function isoFromUnixNano(nanos: string | undefined): string | undefined {\n  if (!nanos || nanos === '0') return undefined\n  try {\n    const ms = Number(BigInt(nanos) / 1_000_000n)\n    if (!Number.isFinite(ms)) return undefined\n    return new Date(ms).toISOString()\n  } catch {\n    return undefined\n  }\n}\n\n// Resolve `deployment.environment` per ADR-074 §2. The four-step fallback\n// is: span-attr canonical form → span-attr compat form → resource-attr\n// canonical form → resource-attr compat form → literal `'unknown'`. The\n// literal `'unknown'` is the honest sentinel; defaulting to `'production'`\n// or `'development'` would bake an incorrect assumption into every span\n// from a workload that hasn't yet wired its env signal.\nconst ENV_ATTR_CANONICAL = 'deployment.environment.name'\nconst ENV_ATTR_COMPAT = 'deployment.environment'\nconst ENV_FALLBACK = 'unknown'\n\nfunction pickEnv(\n  spanAttrs: Record<string, AttributeValue>,\n  resourceAttrs: Record<string, AttributeValue>,\n): string {\n  for (const attrs of [spanAttrs, resourceAttrs]) {\n    for (const key of [ENV_ATTR_CANONICAL, ENV_ATTR_COMPAT]) {\n      const v = attrs[key]\n      if (typeof v === 'string' && v.length > 0) return v\n    }\n  }\n  return ENV_FALLBACK\n}\n\n// The datastore engine a `db.system` span names, normalized at the parse\n// boundary. The mongoose OTel instrumentation — the one that actually emits\n// per-operation collection spans on real apps — tags its spans\n// `db.system: 'mongoose'`, but mongoose is an ORM over mongodb: the datastore\n// IS mongodb, and `mongoose` on the span is an instrumentation detail. Rewrite\n// it to `mongodb` here so every downstream reader (the collection edge, the\n// database-node engine, ADR-141 fusion) sees one engine and none of them has to\n// know the ORM label. See ADR-150.\nfunction normalizeDbSystem(attrs: Record<string, AttributeValue>): string | undefined {\n  // `db.system` (semconv ≤ 1.10) or `db.system.name` (≥ 1.30) — read both so the\n  // mongodb guard and every dbSystem consumer see the system on the newer semconv.\n  const raw = attrs['db.system'] ?? attrs['db.system.name']\n  if (typeof raw !== 'string') return undefined\n  return raw === 'mongoose' ? 'mongodb' : raw\n}\n\n// The table a SQL statement targets, for the OBSERVED table-grain edge. The\n// SQLAlchemy / dbapi instrumentation emits no dedicated table attribute (verified\n// against a live app — ADR-152); the table lives only in the `db.statement` SQL.\n// Conservative by design: the single table after FROM / INTO / UPDATE, quote- and\n// schema-stripped. A joined or multi-`FROM` (subquery) statement degrades to\n// `null` — the database-grain edge stands, and the table is never guessed.\nexport function tableFromSqlStatement(sql: string): string | null {\n  if (typeof sql !== 'string' || sql.length === 0) return null\n  if (/\\bjoin\\b/i.test(sql)) return null\n  const froms = sql.match(/\\bfrom\\b/gi)\n  if (froms && froms.length > 1) return null // subquery / multi-table — degrade\n  const m = /\\b(?:from|into|update)\\s+(?:\"?[\\w$]+\"?\\s*\\.\\s*)?\"?([a-zA-Z_][\\w$]*)\"?/i.exec(sql)\n  return m ? m[1]! : null\n}\n\n// The columns a SQL statement TOUCHES, for the OBSERVED column-grain attributes\n// (ADR-157 §2) — the column sibling of `tableFromSqlStatement` above. Production\n// statements are parameterized (values redacted to `$1`), but the column NAMES\n// are still in the text: an INSERT names its column list, an UPDATE its SET\n// targets, a SELECT its projection, and each of those plus a DELETE names the\n// columns in its WHERE predicate. Real ORM SQL is quoted and schema-qualified,\n// and SQLAlchemy projects every column as `<table>.<col> AS <table>_<col>`, so\n// the parse strips quotes and the table/schema qualifier and drops the `AS`\n// alias to recover the REAL column name, never the alias (`orders.id AS\n// orders_id` → `id`). Aggregate / function / `*` projections yield no column.\n// It degrades to `[]` on the same JOIN / multi-`FROM` (subquery) shapes\n// `tableFromSqlStatement` degrades to `null` on — there the columns belong to\n// more than one table and can't be attributed honestly. Returned names are\n// lowercased and de-duplicated; an unparseable or empty statement yields `[]`.\n// Ported verbatim from the proven column-grain spike.\nexport function columnsFromSqlStatement(sql: string): string[] {\n  if (typeof sql !== 'string' || sql.length === 0) return []\n  const s = sql.replace(/\\s+/g, ' ').trim()\n  if (/\\bjoin\\b/i.test(s)) return []\n  if ((s.match(/\\bfrom\\b/gi) ?? []).length > 1) return [] // subquery / multi-table — degrade\n\n  // One projected/assigned term → its bare column name, or null to skip it (an\n  // aggregate / function / wildcard, or a token that isn't a plain identifier).\n  const bare = (raw: string): string | null => {\n    let t = raw.trim().replace(/\"/g, '')\n    if (/[()*]/.test(t)) return null // aggregate / func / wildcard — skip\n    t = t.split(/\\s+as\\s+/i)[0]!.trim() // drop \"AS alias\" — keep the real column\n    t = t.split('.').pop()! // drop table / schema qualifier\n    return /^[a-z_][\\w$]*$/i.test(t) ? t.toLowerCase() : null\n  }\n  const isCol = (c: string | null): c is string => c !== null\n  const cols = (list: string): string[] => [...new Set(list.split(',').map(bare).filter(isCol))]\n  const whereCols = (w: string | undefined): string[] =>\n    w\n      ? [\n          ...new Set(\n            [\n              ...w.matchAll(\n                /(?:\"?[\\w$]+\"?\\.)?\"?([a-z_][\\w$]*)\"?\\s*(?:=|<|>|<=|>=|<>|!=|\\bis\\b|\\bin\\b|\\blike\\b)/gi,\n              ),\n            ]\n              .map((match) => match[1]!.toLowerCase())\n              .filter((c) => !/^(and|or|not|null)$/i.test(c)),\n          ),\n        ]\n      : []\n\n  let m: RegExpExecArray | null\n  if ((m = /\\binsert\\s+into\\s+(?:\"?[\\w$]+\"?\\.)?\"?[\\w$]+\"?\\s*\\(([^)]*)\\)/i.exec(s))) {\n    return cols(m[1]!)\n  }\n  if ((m = /\\bupdate\\s+(?:\"?[\\w$]+\"?\\.)?\"?[\\w$]+\"?\\s+set\\s+(.+?)(?:\\bwhere\\b(.+))?$/i.exec(s))) {\n    const set = m[1]!\n      .split(',')\n      .map((p) => bare(p.split('=')[0]!))\n      .filter(isCol)\n    return [...new Set([...set, ...whereCols(m[2] ?? undefined)])]\n  }\n  if ((m = /\\bdelete\\s+from\\s+(?:\"?[\\w$]+\"?\\.)?\"?[\\w$]+\"?(?:\\s+where\\b(.+))?$/i.exec(s))) {\n    return whereCols(m[1] ?? undefined)\n  }\n  if ((m = /\\bselect\\s+(.+?)\\s+from\\s+(?:\"?[\\w$]+\"?\\.)?\"?[\\w$]+\"?(?:\\s+where\\b(.+))?$/i.exec(s))) {\n    if (m[1]!.trim() === '*') return [] // SELECT * — no column list to attribute\n    return [...new Set([...cols(m[1]!), ...whereCols(m[2] ?? undefined)])]\n  }\n  return []\n}\n\n// The messaging destination (topic / queue / stream) a producer or consumer\n// span names. `messaging.destination.name` is the canonical semconv key\n// (SC v1.24+); `messaging.destination` is the older form some instrumentations\n// still emit. Prefer the canonical one, fall back to the legacy, and treat an\n// empty string as absent so an anonymous destination never keys a node.\nfunction messagingDestinationOf(\n  attrs: Record<string, AttributeValue>,\n): string | undefined {\n  for (const key of ['messaging.destination.name', 'messaging.destination']) {\n    const v = attrs[key]\n    if (typeof v === 'string' && v.length > 0) return v\n  }\n  return undefined\n}\n\n// True when the span's `Upgrade` request header names `websocket`. OTel HTTP\n// instrumentation captures configured request headers as `http.request.header.<key>`\n// with the key lower-cased and the value an array of strings (one per header\n// occurrence); older SDKs may write a bare string. A WebSocket handshake carries\n// `Upgrade: websocket`, so any element equal to `websocket` (case-insensitive)\n// marks the upgrade. Returns false when the header is absent — a plain `GET`\n// route span never mints a channel.\nfunction hasWebsocketUpgradeHeader(attrs: Record<string, AttributeValue>): boolean {\n  const v = attrs['http.request.header.upgrade']\n  const matches = (s: unknown): boolean =>\n    typeof s === 'string' && s.trim().toLowerCase() === 'websocket'\n  if (Array.isArray(v)) return v.some(matches)\n  return matches(v)\n}\n\n// The channel path an upgrade span opens onto. Prefer the templated route\n// (`http.route`, e.g. `/ws/:room`) so high-cardinality connection paths collapse\n// onto one channel node; fall back to the concrete request path (`url.path`, the\n// SC v1.21+ name, or the legacy `http.target`) with any query string trimmed.\n// Returns undefined when nothing carries a path — the branch then falls through\n// rather than minting a channel keyed on an empty string.\nfunction websocketChannelPathOf(attrs: Record<string, AttributeValue>): string | undefined {\n  const route = attrs['http.route']\n  if (typeof route === 'string' && route.length > 0) return route\n  for (const key of ['url.path', 'http.target']) {\n    const v = attrs[key]\n    if (typeof v === 'string' && v.length > 0) {\n      const q = v.indexOf('?')\n      const path = q === -1 ? v : v.slice(0, q)\n      if (path.length > 0) return path\n    }\n  }\n  return undefined\n}\n\n// The WebSocket channel this span serves, or undefined. Set only on the HTTP\n// upgrade handshake span — a request carrying `Upgrade: websocket` — so a plain\n// HTTP route span is never mistaken for a channel. See docs/contracts/otel-ingest.md\n// §WebSocket channels.\nfunction websocketChannelOf(attrs: Record<string, AttributeValue>): string | undefined {\n  if (!hasWebsocketUpgradeHeader(attrs)) return undefined\n  return websocketChannelPathOf(attrs)\n}\n\n// Opentracing / Jaeger-converted gRPC spans carry the called method only in the\n// operation name (`/pkg.Service/Method`), not the `rpc.*` semconv attributes an\n// OTel-native gRPC span sets — the collector's jaeger receiver tags them with a\n// `component` of `gRPC` and nothing else (DeathStarBench hotelReservation, #1427).\n// Recover the method identity from the name so the gRPC method fusion — serving\n// `CONTAINS` (ADR-123 / #616) and calling `CALLS` (#1413) — reaches those spans too,\n// keyed the same way `grpcMethodId` and the `.proto` extractor key the node. Gated\n// tightly so it never misreads a non-gRPC span: only when no `rpc.*` attribute is\n// present (an OTel-native span keeps the attribute path), the `component` tag\n// lowercases to `grpc`, and the name is exactly `/<service>/<method>` — two non-empty,\n// slash-free segments.\nfunction grpcFromSpanName(\n  attrs: Record<string, AttributeValue>,\n  name: string | undefined,\n): { rpcService: string; rpcMethod: string } | undefined {\n  if (typeof attrs['rpc.service'] === 'string' || typeof attrs['rpc.method'] === 'string') {\n    return undefined\n  }\n  const component = attrs['component']\n  if (typeof component !== 'string' || component.toLowerCase() !== 'grpc') return undefined\n  if (typeof name !== 'string') return undefined\n  const m = /^\\/([^/\\s]+)\\/([^/\\s]+)$/.exec(name)\n  if (!m) return undefined\n  return { rpcService: m[1]!, rpcMethod: m[2]! }\n}\n\n// C# `Grpc.AspNetCore` records a *serving* gRPC call as an ASP.NET HTTP SERVER span,\n// not an rpc span: `http.route` is `/<package.Service>/<Method>` and no `rpc.service`\n// / `rpc.method` is set (the .NET server instrumentation is HTTP; the Grpc.Net.Client\n// *calling* side does carry rpc.*). So a C# service's own gRPC methods never fused —\n// the serving `CONTAINS` (ADR-123 / #616) keys on `rpc.service`. Recover the method\n// identity from that `http.route`, the same shape `grpcFromSpanName` recovers from a\n// Jaeger operation name (#1427), so the SERVER join reaches these spans too (#1460).\n// Gated tightly so a REST route is never misread as gRPC: no `rpc.*` attribute, a\n// SERVER span, and an `http.route` that is exactly\n// `/<lowercase.dotted.package>.<PascalCaseService>/<Method>` — the gRPC path shape a\n// REST template (`/api/users`, `/v1.0/orders`) does not match.\nconst GRPC_HTTP_ROUTE =\n  /^\\/([a-z0-9_]+(?:\\.[a-z0-9_]+)*\\.[A-Z][A-Za-z0-9_]*)\\/([A-Za-z_][A-Za-z0-9_]*)$/\n\nfunction grpcFromHttpRoute(\n  attrs: Record<string, AttributeValue>,\n  kind: number | undefined,\n): { rpcService: string; rpcMethod: string } | undefined {\n  if (typeof attrs['rpc.service'] === 'string' || typeof attrs['rpc.method'] === 'string') {\n    return undefined\n  }\n  // Serving side only — a SERVER span (wire kind 2). A .NET gRPC CLIENT call goes\n  // through Grpc.Net.Client, which emits rpc.* and never reaches here.\n  if (kind !== 2) return undefined\n  const route = attrs['http.route']\n  if (typeof route !== 'string') return undefined\n  const m = GRPC_HTTP_ROUTE.exec(route)\n  if (!m) return undefined\n  return { rpcService: m[1]!, rpcMethod: m[2]! }\n}\n\nexport function parseOtlpRequest(body: OtlpTracesRequest): ParsedSpan[] {\n  const out: ParsedSpan[] = []\n  for (const rs of body.resourceSpans ?? []) {\n    const resourceAttrs = attrsToRecord(rs.resource?.attributes)\n    // OTel spec requires SDKs to set `service.name`, but customised exporters\n    // can omit it. Missing `service.name` routes to `service:unidentified`\n    // in handleSpan + emits a once-per-session-per-project warning so the\n    // diagnostic stays visible (issue #374). Silent drop is not an option.\n    const rawServiceName = resourceAttrs['service.name']\n    const resourceServiceNamePresent =\n      typeof rawServiceName === 'string' && rawServiceName.length > 0\n    const service = resourceServiceNamePresent\n      ? (rawServiceName as string)\n      : 'unidentified'\n    // Resource-level k8s namespace (`k8s.namespace.name`), shared by every span on\n    // this resource. The daemon scopes ingest to a project's declared namespaces.\n    const k8sNamespace =\n      typeof resourceAttrs['k8s.namespace.name'] === 'string' &&\n      (resourceAttrs['k8s.namespace.name'] as string).length > 0\n        ? (resourceAttrs['k8s.namespace.name'] as string)\n        : undefined\n\n    for (const ss of rs.scopeSpans ?? []) {\n      for (const span of ss.spans ?? []) {\n        const attrs = attrsToRecord(span.attributes)\n        // Opentracing / Jaeger gRPC spans name the method in the operation name, not\n        // rpc.* — recover it so the gRPC method fusion reaches them (#1427).\n        const grpcFromName = grpcFromSpanName(attrs, span.name)\n        // C# Grpc.AspNetCore serving spans are HTTP-shaped (http.route), not rpc —\n        // recover the gRPC method from the route so the SERVER join reaches them (#1460).\n        const grpcDerived = grpcFromName ?? grpcFromHttpRoute(attrs, span.kind)\n        // SQL text is `db.statement` (semconv ≤ 1.10) or `db.query.text` (≥ 1.30,\n        // the rename the current GORM/pg OTel plugins emit) — read both so a span\n        // on the newer semconv still yields a table and columns.\n        const dbSqlText =\n          typeof attrs['db.statement'] === 'string'\n            ? (attrs['db.statement'] as string)\n            : typeof attrs['db.query.text'] === 'string'\n              ? (attrs['db.query.text'] as string)\n              : undefined\n        const dbSystemName = normalizeDbSystem(attrs)\n        // The ORM's own resolved table, emitted directly as `db.sql.table` (old\n        // semconv) or, for a relational system, `db.collection.name` (new semconv).\n        // Ground truth — no SELECT*/join/CTE parse degradation. mongodb keeps\n        // `db.collection.name` as its collection, never a table.\n        const directDbTable =\n          typeof attrs['db.sql.table'] === 'string'\n            ? (attrs['db.sql.table'] as string)\n            : dbSystemName !== 'mongodb' && typeof attrs['db.collection.name'] === 'string'\n              ? (attrs['db.collection.name'] as string)\n              : undefined\n        const parsed: ParsedSpan = {\n          service,\n          resourceServiceNamePresent,\n          k8sNamespace,\n          traceId: span.traceId ?? '',\n          spanId: span.spanId ?? '',\n          parentSpanId: span.parentSpanId || undefined,\n          name: span.name ?? '',\n          kind: span.kind,\n          startTimeUnixNano: span.startTimeUnixNano ?? '0',\n          endTimeUnixNano: span.endTimeUnixNano ?? '0',\n          startTimeIso: isoFromUnixNano(span.startTimeUnixNano),\n          durationNanos: durationNanos(span.startTimeUnixNano, span.endTimeUnixNano),\n          env: pickEnv(attrs, resourceAttrs),\n          attributes: attrs,\n          dbSystem: dbSystemName,\n          dbName: typeof attrs['db.name'] === 'string' ? (attrs['db.name'] as string) : undefined,\n          dbCollection:\n            typeof attrs['db.collection.name'] === 'string'\n              ? (attrs['db.collection.name'] as string)\n              : typeof attrs['db.mongodb.collection'] === 'string'\n                ? (attrs['db.mongodb.collection'] as string)\n                : undefined,\n          dbTable: directDbTable ?? (dbSqlText ? (tableFromSqlStatement(dbSqlText) ?? undefined) : undefined),\n          dbColumns: dbSqlText ? columnsFromSqlStatement(dbSqlText) : undefined,\n          httpRoute:\n            typeof attrs['http.route'] === 'string' ? (attrs['http.route'] as string) : undefined,\n          httpMethod:\n            typeof attrs['http.request.method'] === 'string'\n              ? (attrs['http.request.method'] as string)\n              : typeof attrs['http.method'] === 'string'\n                ? (attrs['http.method'] as string)\n                : undefined,\n          messagingSystem:\n            typeof attrs['messaging.system'] === 'string'\n              ? (attrs['messaging.system'] as string)\n              : undefined,\n          messagingDestination: messagingDestinationOf(attrs),\n          graphqlOperationName:\n            typeof attrs['graphql.operation.name'] === 'string' &&\n            (attrs['graphql.operation.name'] as string).length > 0\n              ? (attrs['graphql.operation.name'] as string)\n              : undefined,\n          graphqlOperationType:\n            typeof attrs['graphql.operation.type'] === 'string' &&\n            (attrs['graphql.operation.type'] as string).length > 0\n              ? (attrs['graphql.operation.type'] as string)\n              : undefined,\n          rpcSystem:\n            typeof attrs['rpc.system'] === 'string' &&\n            (attrs['rpc.system'] as string).length > 0\n              ? (attrs['rpc.system'] as string)\n              : grpcDerived\n                ? 'grpc'\n                : undefined,\n          rpcService:\n            typeof attrs['rpc.service'] === 'string' &&\n            (attrs['rpc.service'] as string).length > 0\n              ? (attrs['rpc.service'] as string)\n              : grpcDerived?.rpcService,\n          rpcMethod:\n            typeof attrs['rpc.method'] === 'string' &&\n            (attrs['rpc.method'] as string).length > 0\n              ? (attrs['rpc.method'] as string)\n              : grpcDerived?.rpcMethod,\n          peerService:\n            typeof attrs['peer.service'] === 'string' &&\n            (attrs['peer.service'] as string).length > 0\n              ? (attrs['peer.service'] as string)\n              : undefined,\n          peerHostname:\n            typeof attrs['peer.hostname'] === 'string' &&\n            (attrs['peer.hostname'] as string).length > 0\n              ? (attrs['peer.hostname'] as string)\n              : undefined,\n          websocketChannel: websocketChannelOf(attrs),\n          statusCode: span.status?.code,\n          errorMessage: span.status?.message,\n          exception: extractExceptionFromEvents(span.events),\n          ...messageEventCountOf(span.events),\n          flagEvaluations: extractFlagEvaluations(span.events),\n        }\n        out.push(parsed)\n      }\n    }\n  }\n  return out\n}\n\nexport interface OtelReceiver {\n  app: FastifyInstance\n  // Resolves once every span enqueued so far has been handed to opts.onSpan.\n  // Test seam — production code never awaits this.\n  flushPending: () => Promise<void>\n}\n\n// Lazy-loaded protobuf decoder for ExportTraceServiceRequest. The bundled\n// .proto tree at packages/core/proto/ is shared with the gRPC receiver\n// (ADR-020). Cached after first load so successive receiver builds reuse it.\nlet exportTraceServiceRequestType: protobuf.Type | null = null\nlet exportTraceServiceResponseType: protobuf.Type | null = null\n\nfunction loadProtoRoot(): protobuf.Root {\n  const here = path.dirname(fileURLToPath(import.meta.url))\n  const protoRoot = path.resolve(here, '..', 'proto')\n  const root = new protobuf.Root()\n  root.resolvePath = (_origin, target) => path.resolve(protoRoot, target)\n  root.loadSync(\n    'opentelemetry/proto/collector/trace/v1/trace_service.proto',\n    { keepCase: true },\n  )\n  return root\n}\n\nfunction loadProtobufDecoder(): protobuf.Type {\n  if (exportTraceServiceRequestType) return exportTraceServiceRequestType\n  const root = loadProtoRoot()\n  exportTraceServiceRequestType = root.lookupType(\n    'opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest',\n  )\n  return exportTraceServiceRequestType\n}\n\nfunction loadProtobufResponseEncoder(): protobuf.Type {\n  if (exportTraceServiceResponseType) return exportTraceServiceResponseType\n  const root = loadProtoRoot()\n  exportTraceServiceResponseType = root.lookupType(\n    'opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse',\n  )\n  return exportTraceServiceResponseType\n}\n\n// Empty-partial-success response, encoded once and cached — the hot path where\n// every span was accepted. Caching the bytes avoids re-running the protobuf\n// encoder per request.\nlet cachedProtobufResponseBody: Buffer | null = null\n\n// `rejected` omitted / 0 → the cached empty `ExportTraceServiceResponse`\n// (\"everything accepted\"). A positive `rejected` (the #881 unrouted-batch path)\n// encodes a populated `partial_success` — not cached, since the count and\n// message vary per batch. The proto is loaded `keepCase`, so the field names\n// stay snake_case (`partial_success`, `rejected_spans`, `error_message`).\nfunction encodeProtobufResponseBody(rejected?: number, message?: string): Buffer {\n  const Type = loadProtobufResponseEncoder()\n  if (!rejected) {\n    if (cachedProtobufResponseBody) return cachedProtobufResponseBody\n    // `partial_success` left unset = empty submessage = \"everything accepted\".\n    const msg = Type.create({})\n    cachedProtobufResponseBody = Buffer.from(Type.encode(msg).finish())\n    return cachedProtobufResponseBody\n  }\n  const msg = Type.fromObject({\n    partial_success: { rejected_spans: rejected, error_message: message ?? '' },\n  })\n  return Buffer.from(Type.encode(msg).finish())\n}\n\nasync function decodeProtobufBody(buf: Buffer): Promise<OtlpTracesRequest> {\n  const Type = loadProtobufDecoder()\n  // Decode keeps the proto field names verbatim (keepCase: true), matching the\n  // GrpcExportRequest shape that reshapeGrpcRequest already understands.\n  // toObject() options mirror the gRPC receiver's proto-loader config\n  // (otel-grpc.ts: longs: String, enums: Number, bytes left as Buffers) so\n  // both protobuf paths hand reshapeGrpcRequest the identical shape. The old\n  // .toJSON() here rendered bytes as base64 strings (bytesToHex returned ''\n  // → empty trace/span IDs) and enums as name strings (\"SPAN_KIND_CLIENT\"\n  // never matches the numeric mint gate) — every http/protobuf span was\n  // accepted and then silently minted nothing (#468).\n  // Dynamic import sidesteps the circular module dep with otel-grpc.ts.\n  const decoded = Type.toObject(Type.decode(buf), {\n    longs: String,\n    enums: Number,\n  }) as Record<string, unknown>\n  const { reshapeGrpcRequest } = await import('./otel-grpc.js')\n  return reshapeGrpcRequest(decoded as never)\n}\n\n// The OTLP/HTTP spec allows a request body to be gzip-compressed, and the\n// standard OpenTelemetry Collector's OTLP exporter does so by default\n// (`Content-Encoding: gzip`). The receiver must undo that before the body ever\n// reaches the JSON parser or the protobuf decoder — otherwise a compressed\n// batch is unparseable garbage and every \"bring your own collector\" deployment\n// silently fails to ingest. Returns the zlib transform stream for a supported\n// encoding, or null for `identity` / absent / anything we don't decode (which\n// then flows through untouched, exactly as before). `deflate` rides alongside\n// gzip since it's the same one-liner; `x-gzip` is the legacy alias some proxies\n// still emit. gRPC needs nothing here — @grpc/grpc-js decompresses at the\n// transport layer before `call.request` is ever materialized.\nfunction decompressorForEncoding(encoding: string): Transform | null {\n  switch (encoding) {\n    case 'gzip':\n    case 'x-gzip':\n      return zlib.createGunzip()\n    case 'deflate':\n      return zlib.createInflate()\n    default:\n      return null\n  }\n}\n\nexport async function buildOtelReceiver(\n  opts: BuildOtelReceiverOptions,\n): Promise<FastifyInstance & { flushPending: () => Promise<void> }> {\n  const app = Fastify({\n    logger: false,\n    bodyLimit: opts.bodyLimit ?? 16 * 1024 * 1024,\n  })\n\n  // Decompress a `Content-Encoding: gzip` (or `deflate`) body before Fastify's\n  // content-type parser runs, so the JSON parser and the protobuf decoder both\n  // see plaintext and the rest of the receiver stays oblivious to compression.\n  // Streaming (not buffer-then-inflate) so the content-type parser's bodyLimit\n  // is enforced on the *decompressed* bytes — a decompression bomb is capped at\n  // the same 16 MB ceiling an uncompressed batch is. A truncated or garbage\n  // body makes the zlib stream emit `error`, which Fastify turns into a clean\n  // 400 (the same shape a bad protobuf body gets); it never throws past the\n  // receiver or back-pressures the sender. An uncompressed request carries no\n  // `Content-Encoding`, so the hook is a pure pass-through and that path is\n  // byte-for-byte unchanged.\n  app.addHook('preParsing', (req, _reply, payload, done) => {\n    const encoding = (req.headers['content-encoding'] ?? '')\n      .toString()\n      .trim()\n      .toLowerCase()\n    if (encoding === '' || encoding === 'identity') {\n      done(null, payload)\n      return\n    }\n    const decompressor = decompressorForEncoding(encoding)\n    if (!decompressor) {\n      // An encoding we don't decode (e.g. `br`). Leave the body untouched — the\n      // content-type parser fails it just as it did before, no new behavior.\n      done(null, payload)\n      return\n    }\n    // Fastify checks the bytes it reads off the body stream against the\n    // `Content-Length` header. After decompression that count is the *plaintext*\n    // length, which never matches the compressed `Content-Length` — so Fastify\n    // would reject every batch with FST_ERR_CTP_INVALID_CONTENT_LENGTH unless\n    // the transformed stream reports how many *encoded* (wire) bytes it\n    // consumed. Track the source's byte count and expose it as\n    // `receivedEncodedLength`, the property Fastify reads for that comparison\n    // (mirrors @fastify/compress).\n    const tracked = decompressor as Transform & { receivedEncodedLength?: number }\n    tracked.receivedEncodedLength = 0\n    payload.on('data', (chunk: Buffer) => {\n      tracked.receivedEncodedLength = (tracked.receivedEncodedLength ?? 0) + chunk.length\n    })\n    // Forward a source read error onto the decompressor so the failure travels\n    // the same path a decode error does, rather than surfacing as an unhandled\n    // stream error that could dark the daemon.\n    payload.on('error', (err) => decompressor.destroy(err))\n    payload.pipe(decompressor)\n    done(null, decompressor)\n  })\n\n  // ADR-073 §4 — bearer on `/v1/traces`. `/health` stays unauthenticated via\n  // the default suffix list (the CI smoke and supervisors lean on it for\n  // liveness probes).\n  //\n  // A rejected OTLP POST is a silent failure on the sender's side — the app\n  // gets a bare 401 and its telemetry vanishes, so the operator sees an empty\n  // OBSERVED layer with no clue why. Emit a server-side warning when that\n  // happens, rate-limited to one line per interval so a chatty misconfigured\n  // exporter (they retry hard) can't flood the log. The plain REST 401 path\n  // stays quiet — that surface leaves this hook unset.\n  const REJECT_WARN_INTERVAL_MS = 60_000\n  let lastRejectWarnAt = 0\n  const warnRejectedOtlp = (): void => {\n    const now = Date.now()\n    if (now - lastRejectWarnAt < REJECT_WARN_INTERVAL_MS) return\n    lastRejectWarnAt = now\n    console.warn(\n      '[neatd] rejecting OTLP spans on /v1/traces — missing or invalid bearer token (set NEAT_OTEL_TOKEN on the instrumented app)',\n    )\n  }\n  mountBearerAuth(app, {\n    token: opts.authToken,\n    trustProxy: opts.trustProxy,\n    onReject: warnRejectedOtlp,\n  })\n\n  // Non-blocking ingest (ADR-033). The receiver replies 200 OK as soon as the\n  // body is parsed; mutation runs through this queue, drained on the next tick.\n  // OTel SDK exporters retry on timeout, so blocking ingest produces observable\n  // backpressure on the system being observed — ambient observation requires no\n  // observable effect.\n  const queue: ParsedSpan[] = []\n  let draining = false\n  let drainPromise: Promise<void> = Promise.resolve()\n\n  const drain = async (): Promise<void> => {\n    if (draining) return\n    draining = true\n    try {\n      while (queue.length > 0) {\n        const span = queue.shift()!\n        try {\n          await opts.onSpan(span)\n        } catch (err) {\n          console.warn(`[neat] otel handler error: ${(err as Error).message}`)\n        }\n      }\n    } finally {\n      draining = false\n    }\n  }\n\n  const enqueue = (spans: ParsedSpan[]): void => {\n    if (spans.length === 0) return\n    for (const s of spans) queue.push(s)\n    // Schedule on the next tick so the 200 response is on the wire before any\n    // mutation runs. Each call gets its own promise so flushPending() can wait\n    // on the latest drain cycle.\n    drainPromise = drainPromise.then(() => drain())\n  }\n\n  // Per-project queue is reusable across the project-scoped route — the\n  // project name rides in the URL, not on the span. Drain semantics mirror\n  // the global queue so flushPending() captures both.\n  const projectQueue: Array<{ project: string; span: ParsedSpan }> = []\n  let projectDraining = false\n  let projectDrainPromise: Promise<void> = Promise.resolve()\n  const drainProject = async (): Promise<void> => {\n    if (projectDraining) return\n    projectDraining = true\n    try {\n      while (projectQueue.length > 0) {\n        const { project, span } = projectQueue.shift()!\n        try {\n          if (opts.onProjectSpan) {\n            await opts.onProjectSpan(project, span)\n          } else {\n            await opts.onSpan(span)\n          }\n        } catch (err) {\n          console.warn(`[neat] otel handler error: ${(err as Error).message}`)\n        }\n      }\n    } finally {\n      projectDraining = false\n    }\n  }\n  const enqueueProject = (project: string, spans: ParsedSpan[]): void => {\n    if (spans.length === 0) return\n    for (const s of spans) projectQueue.push({ project, span: s })\n    projectDrainPromise = projectDrainPromise.then(() => drainProject())\n  }\n\n  // One-time-per-service-name deprecation warning for spans landing on the\n  // bare `/v1/traces` endpoint. Under one daemon per project (ADR-096) that\n  // route is the project's own ingest path and needs no migration, so the\n  // warning is gated on whether this receiver actually offers project-scoped\n  // routing: only a receiver wired with `onProjectSpan` (the multi-project\n  // daemon that mounts `/projects/<name>/v1/traces`) has somewhere to migrate\n  // an exporter to. A single-project receiver leaves the gate closed and never\n  // nags. Still once-per-name so a long-running daemon doesn't flood stderr\n  // while an operator migrates.\n  const offersProjectRouting = opts.onProjectSpan !== undefined\n  const legacyEndpointWarned = new Set<string>()\n  function warnLegacyEndpoint(serviceName: string): void {\n    if (!offersProjectRouting) return\n    if (legacyEndpointWarned.has(serviceName)) return\n    legacyEndpointWarned.add(serviceName)\n    console.warn(\n      `[neatd] received span on the global endpoint; migrate OTEL_EXPORTER_OTLP_TRACES_ENDPOINT to /projects/<name>/v1/traces (service.name=\"${serviceName}\").`,\n    )\n  }\n\n  // Shared body-decode + content-negotiation. Both `/v1/traces` and\n  // `/projects/:project/v1/traces` go through this so the protobuf/JSON\n  // dispatch stays in one place.\n  async function readOtlpBody(req: import('fastify').FastifyRequest): Promise<\n    | { ok: true; body: OtlpTracesRequest; flavor: 'json' | 'protobuf' }\n    | { ok: false; code: 400 | 415; error: string }\n  > {\n    const ct = (req.headers['content-type'] ?? '').toString().split(';')[0]!.trim().toLowerCase()\n    if (ct === 'application/x-protobuf') {\n      try {\n        const body = await decodeProtobufBody(req.body as Buffer)\n        return { ok: true, body, flavor: 'protobuf' }\n      } catch (err) {\n        return { ok: false, code: 400, error: `protobuf decode failed: ${(err as Error).message}` }\n      }\n    }\n    if (!ct || ct === 'application/json') {\n      return { ok: true, body: (req.body ?? {}) as OtlpTracesRequest, flavor: 'json' }\n    }\n    return { ok: false, code: 415, error: `unsupported content-type: ${ct}` }\n  }\n\n  function sendOtlpSuccess(reply: import('fastify').FastifyReply, flavor: 'json' | 'protobuf'): unknown {\n    if (flavor === 'protobuf') {\n      const buf = encodeProtobufResponseBody()\n      return reply\n        .code(200)\n        .header('content-type', 'application/x-protobuf')\n        .send(buf)\n    }\n    return reply\n      .code(200)\n      .header('content-type', 'application/json')\n      .send({ partialSuccess: {} })\n  }\n\n  // #881 — a 200 that honestly reports dropped spans. Still a 200 (the OTLP\n  // non-blocking discipline holds and the exporter isn't back-pressured), but\n  // `partialSuccess.rejectedSpans` + `errorMessage` are populated so an exporter\n  // aimed at a service this daemon can't place stops looking healthy. Encoding\n  // stays symmetric with the request: protobuf in → protobuf out, JSON in → JSON\n  // out (the OTLP spec requires it, per §HTTP receiver supports JSON and\n  // protobuf).\n  function sendOtlpPartial(\n    reply: import('fastify').FastifyReply,\n    flavor: 'json' | 'protobuf',\n    rejected: number,\n    message: string | undefined,\n  ): unknown {\n    if (flavor === 'protobuf') {\n      const buf = encodeProtobufResponseBody(rejected, message)\n      return reply\n        .code(200)\n        .header('content-type', 'application/x-protobuf')\n        .send(buf)\n    }\n    return reply\n      .code(200)\n      .header('content-type', 'application/json')\n      .send({ partialSuccess: { rejectedSpans: rejected, errorMessage: message } })\n  }\n\n  // Buffer application/x-protobuf bodies as raw bytes; the route handler\n  // decodes them via the bundled .proto tree (ADR-020).\n  app.addContentTypeParser(\n    'application/x-protobuf',\n    { parseAs: 'buffer', bodyLimit: opts.bodyLimit ?? 16 * 1024 * 1024 },\n    (_req, body, done) => {\n      done(null, body)\n    },\n  )\n\n  app.get('/health', async () => ({ ok: true }))\n\n  app.post('/v1/traces', async (req, reply) => {\n    // Legacy global endpoint. Spans land here when an OTel exporter hasn't\n    // migrated to the project-scoped URL yet (issue #367); the daemon still\n    // routes by `service.name` against the registry. Per-service-name\n    // deprecation warning fires once so an operator notices without their\n    // stderr flooding.\n    const result = await readOtlpBody(req)\n    if (!result.ok) {\n      return reply.code(result.code).send({ error: result.error })\n    }\n    const spans = parseOtlpRequest(result.body)\n    for (const s of spans) warnLegacyEndpoint(s.service)\n    if (opts.onErrorSpanSync) {\n      try {\n        for (const span of spans) {\n          if (span.statusCode === 2) await opts.onErrorSpanSync(span)\n        }\n      } catch (err) {\n        return reply.code(500).send({\n          error: `error-event write failed: ${(err as Error).message}`,\n        })\n      }\n    }\n    enqueue(spans)\n    // #881 — the routing decision runs off the queue (above), so by reply time\n    // we don't yet know a span will be dropped. Ask the pure classifier now:\n    // if any span in the batch belongs to no project this daemon hosts, report\n    // it as `partialSuccess.rejectedSpans` rather than a bare \"all accepted\".\n    // The async `onSpan` path still drops those spans and writes the unrouted\n    // ledger; this only makes the reply honest. Spans stay enqueued regardless,\n    // so a routable span in a mixed batch still lands.\n    if (opts.classifyBareRoutability) {\n      const { rejected, message } = opts.classifyBareRoutability(spans)\n      if (rejected > 0) return sendOtlpPartial(reply, result.flavor, rejected, message)\n    }\n    return sendOtlpSuccess(reply, result.flavor)\n  })\n\n  // Project-scoped route (issue #367). The URL `:project` carries the routing\n  // key, sidestepping the `service.name`-against-registry heuristic the legacy\n  // path uses. Spans get dispatched into the named project's ingest path\n  // directly; `OTEL_SERVICE_NAME` regains its proper semantic role of naming\n  // the ServiceNode inside the one project the URL already picked.\n  app.post<{ Params: { project: string } }>('/projects/:project/v1/traces', async (req, reply) => {\n    const project = req.params.project\n    // #881 — an exporter aimed at a project this receiver doesn't serve gets an\n    // honest 404, not a 200 that drops the batch. The bare `/v1/traces` route\n    // stays lenient (it routes by service.name); the project-scoped URL is an\n    // explicit assertion, so a wrong name is a real error worth surfacing.\n    if (opts.isProjectRegistered && !opts.isProjectRegistered(project)) {\n      return reply.code(404).send({ error: 'project not found', project })\n    }\n    const result = await readOtlpBody(req)\n    if (!result.ok) {\n      return reply.code(result.code).send({ error: result.error })\n    }\n    const spans = parseOtlpRequest(result.body)\n    if (opts.onProjectErrorSpanSync) {\n      try {\n        for (const span of spans) {\n          if (span.statusCode === 2) await opts.onProjectErrorSpanSync(project, span)\n        }\n      } catch (err) {\n        return reply.code(500).send({\n          error: `error-event write failed: ${(err as Error).message}`,\n        })\n      }\n    } else if (opts.onErrorSpanSync) {\n      try {\n        for (const span of spans) {\n          if (span.statusCode === 2) await opts.onErrorSpanSync(span)\n        }\n      } catch (err) {\n        return reply.code(500).send({\n          error: `error-event write failed: ${(err as Error).message}`,\n        })\n      }\n    }\n    enqueueProject(project, spans)\n    return sendOtlpSuccess(reply, result.flavor)\n  })\n\n  // Attach flushPending so tests can wait for the queue without exporting a\n  // separate handle. The cast goes through `unknown` because Fastify's typing\n  // is parameterised over the raw server type and the simple intersection\n  // confuses TS's structural narrowing.\n  const decorated = app as unknown as FastifyInstance & { flushPending: () => Promise<void> }\n  decorated.flushPending = async () => {\n    // Settle both drain chains, then loop until both queues are fully empty\n    // (a span enqueued mid-flush would otherwise be missed).\n    while (queue.length > 0 || draining || projectQueue.length > 0 || projectDraining) {\n      await Promise.all([drainPromise, projectDrainPromise])\n    }\n  }\n  return decorated\n}\n\n// How far the OTLP receiver steps before giving up, and the stride between\n// candidate ports. Matches the orchestrator's triple allocator (8 attempts,\n// stride 1) so the daemon's own bind and the pre-spawn allocation reach the\n// same free port under the same contention.\nconst OTLP_STEP_ATTEMPTS = 8\nconst OTLP_STEP_STRIDE = 1\n\n// Bind an OTLP receiver, stepping to the next free port when the requested one\n// is held (daemon.md §Binding — a held OTLP port steps, it does not crash the\n// daemon; project-daemon §3). The REST port is the daemon's identity and stays\n// fatal on collision, but every OTLP consumer resolves the port dynamically\n// from `daemon.json` `ports.otlp`, so stepping the receiver and recording the\n// port it actually bound keeps the OBSERVED layer alive instead of darking the\n// whole daemon on a foreign collector holding `:4318`. Returns the bound\n// address (host:port); callers read the real port back from it. A requested\n// port of `0` means \"let the kernel pick a free one\" — no collision is\n// possible, so no stepping happens. Non-`EADDRINUSE` failures (permission\n// denied) and an exhausted step window propagate to the caller unchanged.\nexport async function listenSteppingOtlp(\n  app: FastifyInstance,\n  requestedPort: number,\n  host: string,\n): Promise<string> {\n  let port = requestedPort\n  for (let attempt = 0; ; attempt++) {\n    try {\n      return await app.listen({ port, host })\n    } catch (err) {\n      const code = (err as NodeJS.ErrnoException).code\n      const canStep =\n        requestedPort !== 0 && code === 'EADDRINUSE' && attempt < OTLP_STEP_ATTEMPTS - 1\n      if (!canStep) throw err\n      console.warn(\n        `otel: OTLP port ${port} is in use, stepping to ${port + OTLP_STEP_STRIDE}`,\n      )\n      port += OTLP_STEP_STRIDE\n    }\n  }\n}\n\nexport function logSpanHandler(span: ParsedSpan): void {\n  const parent = span.parentSpanId ? span.parentSpanId.slice(0, 8) : '<root>'\n  const status = span.statusCode === 2 ? 'ERROR' : 'OK'\n  const db = span.dbSystem ? ` db=${span.dbSystem}/${span.dbName ?? '?'}` : ''\n  console.log(\n    `otel: ${span.service} ${span.name} parent=${parent} status=${status}${db}`,\n  )\n}\n","// The security engine's public entry (ADR-274), for callers outside core: the\n// PR gate in neat-action and the CLI. `@neat.is/core/security`.\nexport { buildSecurityCard, buildSecurityCards, highestLevel, rankSecurityCards } from './security-card.js'\nexport { isReachable, scanProjectCves, type ScanOptions } from './security-scan.js'\nexport {\n  diffSecurityCards,\n  materializeRef,\n  resolveRevision,\n  scanDiffGraphs,\n  scanDiffLocal,\n  type ScanDiffOptions,\n} from './security-diff.js'\nexport {\n  applyFixAction,\n  applyFixes,\n  applyAndReverify,\n  type ApplyOptions,\n  type ApplyOutcome,\n  type DepApplyResult,\n  type FileEdit,\n  type ReverifyResult,\n} from './security-apply.js'\n","import type { DependencyNode, GraphEdge, GraphNode, SecurityCard, SecurityFixAction, ServiceNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  SecurityCardSchema,\n  dependencySymbolId,\n  fileId,\n  isDependencySymbolId,\n  parseDependencySymbolId,\n  parseSymbolId,\n  securityCardId,\n} from '@neat.is/types'\nimport type { FixDiff } from './advisories/fixdiff.js'\nimport type { NeatGraph } from './graph.js'\nimport type { AdvisoryMatch, AdvisorySnapshot } from './advisories/match.js'\nimport { matchAdvisories } from './advisories/match.js'\nimport { isTestPath } from './extract/shared.js'\nimport { fixActionFor, rigorousFixAction } from './advisories/fix-action.js'\n\n// The security card (ADR-274, security-card.md). Pure composition: a function of\n// the graph, one advisory match and the snapshot it came from. No I/O, no clock,\n// no mutation, no model. The ladder goes as high as merged evidence supports\n// today: `present` from DEPENDS_ON, `imported` from first-party IMPORTS edges.\n// `reachable-static` (a CALLS path into the fix-diff's changed set) and\n// `reachable-observed` (instrumentation scope, stack frames) need producers that\n// haven't landed, so no card claims them yet.\n\ntype Importer = SecurityCard['reachability']['importers'][number]\n\nfunction dependsOnEdge(graph: NeatGraph, serviceId: string, depId: string): GraphEdge | null {\n  let found: GraphEdge | null = null\n  graph.forEachOutEdge(serviceId, (_e, attrs, _s, target) => {\n    const e = attrs as GraphEdge\n    if (!found && target === depId && e.type === EdgeType.DEPENDS_ON) found = e\n  })\n  return found\n}\n\n// First-party files of this service that import the package (non-test), one per\n// file, in file order.\nfunction importersOf(graph: NeatGraph, serviceName: string, depId: string): Importer[] {\n  const prefix = fileId(serviceName, '')\n  const out: Importer[] = []\n  graph.forEachInEdge(depId, (_e, attrs, source) => {\n    const e = attrs as GraphEdge\n    if (e.type !== EdgeType.IMPORTS || e.provenance !== Provenance.EXTRACTED) return\n    if (!source.startsWith(prefix)) return\n    const file = e.evidence?.file ?? source.slice(prefix.length)\n    if (isTestPath(file)) return\n    out.push({\n      file,\n      line: e.evidence?.line ?? 0,\n      ...(e.evidence?.bindings?.length ? { bindings: e.evidence.bindings } : {}),\n      provenance: Provenance.EXTRACTED,\n    })\n  })\n  return out.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line))\n}\n\n// Whether the service has ever spoken at runtime: any OBSERVED edge on the service\n// node or on one of its files or symbols. With none, the card says the service\n// isn't instrumented. With some, it can't yet say the package's own code is\n// covered (that needs the observed producers), so it stays `unknown`.\nfunction instrumented(graph: NeatGraph, serviceId: string, serviceName: string): 'no' | 'unknown' {\n  const files = fileId(serviceName, '')\n  const owned = (id: string) => id === serviceId || id.startsWith(files) || parseSymbolId(id)?.service === serviceName\n  let seen = false\n  graph.forEachEdge((_e, attrs, source, target) => {\n    if (seen) return\n    if ((attrs as GraphEdge).provenance === Provenance.OBSERVED && (owned(source) || owned(target))) seen = true\n  })\n  return seen ? 'unknown' : 'no'\n}\n\n// ── reachable-static (security-card.md §2) ─────────────────────────────────\n\ntype PathHop = NonNullable<SecurityCard['reachability']['path']>[number]\n\n// The symbols the fix changed, as this installed version's SymbolNodes. A symbol\n// new in the fixed release isn't in an affected version, and one whose file or\n// name moved since has no node here; neither can be a target.\nfunction changedTargets(graph: NeatGraph, dep: DependencyNode, fixDiff: FixDiff): Set<string> {\n  const out = new Set<string>()\n  for (const c of fixDiff.changed) {\n    if (c.status === 'new') continue\n    const id = dependencySymbolId(dep.ecosystem, dep.name, dep.version, c.file, c.symbol)\n    if (graph.hasNode(id)) out.add(id)\n  }\n  return out\n}\n\n// The service's own code: one of its files, or a first-party symbol of it.\nfunction isServiceCode(id: string, serviceName: string): boolean {\n  if (id.startsWith(fileId(serviceName, ''))) return true\n  return !isDependencySymbolId(id) && parseSymbolId(id)?.service === serviceName\n}\n\n/**\n * The shortest EXTRACTED CALLS path from the service's code into the package and\n * on to a changed symbol, or null. Multi-source BFS from the service's calls into\n * the package, then along the package's own calls only; ties break on edge id,\n * so the same graph always gives the same path.\n */\nexport function reachPath(graph: NeatGraph, serviceName: string, depId: string, targets: Set<string>): GraphEdge[] | null {\n  const owned = new Set(graph.outNeighbors(depId).filter(isDependencySymbolId))\n  const calls = (edges: string[]) =>\n    edges\n      .map((id) => graph.getEdgeAttributes(id) as GraphEdge)\n      .filter((e) => e.type === EdgeType.CALLS && e.provenance === Provenance.EXTRACTED)\n      .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))\n\n  const parent = new Map<string, GraphEdge>()\n  const queue: string[] = []\n  for (const sym of [...owned].sort()) {\n    for (const e of calls(graph.inboundEdges(sym))) {\n      if (!isServiceCode(e.source, serviceName) || parent.has(sym)) continue\n      parent.set(sym, e)\n    }\n  }\n  // Entries in edge-id order, so the BFS frontier is deterministic.\n  queue.push(...[...parent.entries()].sort(([, a], [, b]) => (a.id < b.id ? -1 : 1)).map(([n]) => n))\n  const pathTo = (end: string): GraphEdge[] => {\n    const hops: GraphEdge[] = []\n    let cur = end\n    for (;;) {\n      const e = parent.get(cur)!\n      hops.unshift(e)\n      if (!owned.has(e.source)) return hops\n      cur = e.source\n    }\n  }\n  for (let i = 0; i < queue.length; i++) {\n    const cur = queue[i]!\n    if (targets.has(cur)) return pathTo(cur)\n    const next = calls(graph.outboundEdges(cur))\n    // `new X()` lands on the class; constructing it runs X's constructor, whose\n    // body holds the calls. That step is certain, so the walk takes it.\n    const ctor = constructorOf(cur)\n    if (ctor && owned.has(ctor) && !parent.has(ctor)) {\n      parent.set(ctor, { id: `${cur}->${ctor}`, source: cur, target: ctor, type: EdgeType.CALLS, provenance: Provenance.EXTRACTED, confidence: 1 } as GraphEdge)\n      queue.push(ctor)\n    }\n    for (const e of next) {\n      if (!owned.has(e.target) || parent.has(e.target)) continue\n      parent.set(e.target, e)\n      queue.push(e.target)\n    }\n  }\n  return null\n}\n\n// The constructor SymbolNode of a class SymbolNode, when it has one.\nfunction constructorOf(id: string): string | null {\n  const p = parseDependencySymbolId(id)\n  if (!p) return null\n  return dependencySymbolId(p.ecosystem, p.name, p.version, p.relPath, `${p.qualname}.constructor`)\n}\n\nfunction shortName(id: string): string {\n  const dep = parseDependencySymbolId(id)\n  if (dep) return `${dep.qualname} (${dep.relPath})`\n  const sym = parseSymbolId(id)\n  if (sym) return `${sym.qualname} (${sym.relPath})`\n  return id.replace(/^file:[^:]+:/, '')\n}\n\nfunction plural(n: number, one: string, many: string): string {\n  return `${n} ${n === 1 ? one : many}`\n}\n\nfunction describeFixAction(\n  action: SecurityFixAction | undefined,\n  scope: 'direct' | 'transitive',\n  name: string,\n): string {\n  if (!action) return ''\n  if (action.kind === 'remove-or-replace') {\n    return action.majorTo\n      ? ` No non-breaking bump: a breaking fix exists at ${action.majorTo}, else remove or replace.`\n      : ' No safe bump: remove or replace.'\n  }\n  if (scope === 'direct') return ` Bump to ${action.to}.`\n  // A transitive dependency can't be bumped at its own version. Bumping the\n  // parent only helps if the parent's range admits the fixed version, which the\n  // graph doesn't know, so an override is the reliable move.\n  if (action.via.length) return ` Bump ${action.via.join(', ')} if its range allows, else override ${name} to ${action.to}.`\n  return ` Override ${name} to ${action.to} (transitive, parent unknown).`\n}\n\nfunction headlineFor(card: Omit<SecurityCard, 'headline'>): string {\n  const { dependency: d, advisory: a, reachability: r, fix, coverage } = card\n  const pkg = `${d.name} ${d.version}`\n  const adv = `${a.id}, ${a.severity.label}`\n  const how = d.scope === 'direct' ? 'direct' : `transitive via ${d.introducedBy.join(', ') || 'an unknown parent'}`\n  const dev = d.dev ? ', dev only' : ''\n  let exposure: string\n  if (r.level === 'reachable-static' && r.path?.length) {\n    const first = r.path[0]!\n    const last = r.path[r.path.length - 1]!\n    exposure =\n      `reachable from ${card.service}: ${shortName(first.from)} calls ${shortName(first.to)}` +\n      (r.path.length > 1 ? `, which reaches ${shortName(last.to)}` : '') +\n      `, changed in the fix release (${plural(r.path.length, 'call', 'calls')}, no dataflow claimed)`\n  } else if (r.level === 'imported') {\n    exposure =\n      r.grainSource === 'fix-diff'\n        ? `imported by ${plural(r.importers.length, 'file', 'files')} in ${card.service}, but no call path to code changed in the fix was found`\n        : `imported by ${plural(r.importers.length, 'file', 'files')} in ${card.service}; whether the vulnerable code is called is not yet analysed`\n  } else exposure = `in ${card.service}'s dependencies (${how}${dev}) but no first-party file imports it`\n  const fixed = fix.fixedIn?.length ? `Fixed in ${fix.fixedIn.join(', ')}.` : 'No fixed release.'\n  const runtime = coverage.instrumented === 'no' ? ' The service is not instrumented, so runtime use is unknown.' : ''\n  return `${pkg} (${adv}) is ${exposure}. ${fixed}${describeFixAction(fix.action, d.scope, d.name)}${runtime}`\n}\n\n/**\n * The card for one advisory match in one service, or null when the service\n * doesn't depend on that version or the advisory isn't in the snapshot.\n */\nexport function buildSecurityCard(\n  graph: NeatGraph,\n  match: AdvisoryMatch,\n  snapshot: AdvisorySnapshot,\n  serviceId: string,\n): SecurityCard | null {\n  const advisory = snapshot.advisories.find((a) => a.id === match.advisoryId)\n  if (!advisory || !graph.hasNode(match.dependencyId) || !graph.hasNode(serviceId)) return null\n  const dep = graph.getNodeAttributes(match.dependencyId) as GraphNode\n  const svc = graph.getNodeAttributes(serviceId) as GraphNode\n  if (dep.type !== NodeType.DependencyNode || svc.type !== NodeType.ServiceNode) return null\n  const edge = dependsOnEdge(graph, serviceId, match.dependencyId)\n  if (!edge) return null\n  const depNode = dep as DependencyNode\n  const serviceName = (svc as ServiceNode).name\n\n  const importers = importersOf(graph, serviceName, match.dependencyId)\n  const fixDiff = advisory.fixDiff\n  const codeInGraph = graph.outNeighbors(match.dependencyId).some(isDependencySymbolId)\n  const targets = fixDiff && codeInGraph ? changedTargets(graph, depNode, fixDiff) : new Set<string>()\n  const hops = importers.length > 0 && targets.size > 0 ? reachPath(graph, serviceName, match.dependencyId, targets) : null\n  const level = hops ? 'reachable-static' : importers.length > 0 ? 'imported' : 'present'\n  const limits: string[] = []\n  if (level === 'imported') {\n    if (!fixDiff) limits.push('The fix release has not been diffed, so there is no changed code to reach; reachability past the import is unknown.')\n    else if (!codeInGraph) limits.push(\"The package's own code is not in the graph, so reachability past the import is unknown.\")\n    else if (targets.size === 0) limits.push('None of the code the fix changed exists under the same file and name in the installed version.')\n    else {\n      limits.push(\n        'No call path from first-party code to code changed in the fix was found. Calls on objects (method dispatch), dynamic requires, re-exports from other packages and calls made from templates are not resolved, so this does not show the code is unreachable.',\n      )\n    }\n  }\n  const path: PathHop[] | null = hops\n    ? hops.map((e) => ({ from: e.source, to: e.target, provenance: Provenance.EXTRACTED }))\n    : null\n\n  const card: Omit<SecurityCard, 'headline'> = {\n    kind: 'security',\n    id: securityCardId(advisory.id, match.dependencyId, serviceId),\n    service: serviceName,\n    advisory: {\n      id: advisory.id,\n      aliases: [...advisory.aliases],\n      summary: advisory.summary,\n      severity: { label: advisory.severity.label, ...(advisory.severity.cvss ? { cvss: advisory.severity.cvss } : {}) },\n      cwe: [...advisory.cwe],\n      ...(advisory.published ? { published: advisory.published } : {}),\n      modified: advisory.modified,\n      asOf: match.asOf,\n    },\n    dependency: {\n      id: match.dependencyId,\n      ecosystem: depNode.ecosystem,\n      name: depNode.name,\n      version: depNode.version,\n      scope: edge.dependency?.scope ?? 'direct',\n      dev: edge.dependency?.dev ?? false,\n      introducedBy: [...(edge.dependency?.introducedBy ?? [])],\n      manifest: { file: edge.evidence?.file ?? '', ...(edge.evidence?.line !== undefined ? { line: edge.evidence.line } : {}) },\n    },\n    fix: {\n      fixedIn: match.fixedIn.length ? [...match.fixedIn] : null,\n      // Base action for this one advisory; reconcileDepFixActions aggregates a\n      // dependency's advisories into one shared target over the full card set.\n      action: fixActionFor({\n        fixedInByAdvisory: [match.fixedIn],\n        installed: depNode.version,\n        ecosystem: depNode.ecosystem,\n        scope: edge.dependency?.scope ?? 'direct',\n        introducedBy: [...(edge.dependency?.introducedBy ?? [])],\n      }),\n    },\n    reachability: {\n      level,\n      grain: fixDiff ? 'symbol' : 'package',\n      grainSource: fixDiff ? 'fix-diff' : 'package',\n      changedInFix: (fixDiff?.changed ?? []).map((c) => ({ symbol: c.symbol, file: c.file, namedInAdvisory: c.namedInAdvisory })),\n      importers,\n      path,\n      observed: [],\n      supporting: [],\n      method: 'call-graph, no dataflow',\n      limits,\n    },\n    coverage: { instrumented: instrumented(graph, serviceId, serviceName) },\n  }\n  return SecurityCardSchema.parse({ ...card, headline: headlineFor(card) })\n}\n\n/** One card per service that depends on the matched version, in service-id order. */\nexport function buildSecurityCards(graph: NeatGraph, match: AdvisoryMatch, snapshot: AdvisorySnapshot): SecurityCard[] {\n  if (!graph.hasNode(match.dependencyId)) return []\n  const services = new Set<string>()\n  graph.forEachInEdge(match.dependencyId, (_e, attrs, source) => {\n    if ((attrs as GraphEdge).type === EdgeType.DEPENDS_ON) services.add(source)\n  })\n  return [...services]\n    .sort()\n    .map((s) => buildSecurityCard(graph, match, snapshot, s))\n    .filter((c): c is SecurityCard => c !== null)\n}\n\n/**\n * Give every card for a dependency the same fix action (ADR-274 fix loop). When a\n * dependency matches several advisories whose fixed releases differ (lodash\n * 4.17.19 and 4.17.21), each card's `fix.action.to` becomes the one version that\n * clears all of them, so an agent bumps once rather than once per CVE. Pure, run\n * over the whole scan where every advisory for a dependency is present; `via` and\n * scope stay per-card (per service), only the target is shared.\n *\n * The target is the lowest fixed release at which the matcher, re-run against\n * `snapshot`, matches no advisory for the package. That is stricter than the\n * highest of the per-advisory minimal fixes, which can land back inside a later\n * affected range when an advisory re-affects one (affected [1.0, 1.5) and\n * [1.8, 2.0)), or inside the range of another advisory that did not hit the\n * installed version; re-matching catches both.\n */\nexport function reconcileDepFixActions(cards: SecurityCard[], snapshot: AdvisorySnapshot): SecurityCard[] {\n  const byDep = new Map<string, SecurityCard[]>()\n  for (const c of cards) {\n    const group = byDep.get(c.dependency.id)\n    if (group) group.push(c)\n    else byDep.set(c.dependency.id, [c])\n  }\n  return cards.map((c) => {\n    const group = byDep.get(c.dependency.id)!\n    if (group.length <= 1) return c\n    // Every fixed release the dependency's advisories list, as bump candidates.\n    const candidates = group.flatMap((g) => g.fix.fixedIn ?? [])\n    // A bump clears the dependency only when the matcher, re-run at that version,\n    // matches NO advisory in the snapshot for this package: not only the ones that\n    // hit the installed version, but any, so a bump never lands in a range an\n    // advisory NEAT knows re-affects (which would introduce a CVE). This is as\n    // strong as the snapshot allows. The snapshot is queried on the INSTALLED\n    // versions, so an advisory affecting only a candidate version usually is not in\n    // it; scan_diff re-queries at the bumped version and catches one that is not. So\n    // \"clears every advisory\" means every advisory NEAT knows for this package, not\n    // a guarantee the version is clean.\n    const clears = (version: string): boolean =>\n      matchAdvisories(\n        [{ dependencyId: c.dependency.id, ecosystem: c.dependency.ecosystem, name: c.dependency.name, version }],\n        snapshot,\n      ).length === 0\n    const action = rigorousFixAction({\n      candidates,\n      installed: c.dependency.version,\n      ecosystem: c.dependency.ecosystem,\n      scope: c.dependency.scope,\n      introducedBy: [...c.dependency.introducedBy],\n      clears,\n    })\n    return { ...c, fix: { ...c.fix, action } }\n  })\n}\n\nconst LEVEL_RANK: Record<SecurityCard['reachability']['level'], number> = {\n  'reachable-observed': 3,\n  'reachable-static': 2,\n  imported: 1,\n  present: 0,\n}\nconst SEVERITY_RANK: Record<SecurityCard['advisory']['severity']['label'], number> = {\n  critical: 4,\n  high: 3,\n  moderate: 2,\n  low: 1,\n  unknown: 0,\n}\n\n/** The highest ladder step among `cards`, or null for none. */\nexport function highestLevel(cards: SecurityCard[]): SecurityCard['reachability']['level'] | null {\n  let best: SecurityCard['reachability']['level'] | null = null\n  for (const c of cards) if (best === null || LEVEL_RANK[c.reachability.level] > LEVEL_RANK[best]) best = c.reachability.level\n  return best\n}\n\n/**\n * Ranking (security-card.md §5): level, then severity, then direct before\n * transitive, then card id so the order is total. A new array; the input is\n * untouched. Callers keep `present` cards out of a findings list.\n */\nexport function rankSecurityCards(cards: SecurityCard[]): SecurityCard[] {\n  return [...cards].sort(\n    (a, b) =>\n      LEVEL_RANK[b.reachability.level] - LEVEL_RANK[a.reachability.level] ||\n      SEVERITY_RANK[b.advisory.severity.label] - SEVERITY_RANK[a.advisory.severity.label] ||\n      (a.dependency.scope === b.dependency.scope ? 0 : a.dependency.scope === 'direct' ? -1 : 1) ||\n      (a.id < b.id ? -1 : a.id > b.id ? 1 : 0),\n  )\n}\n","import semver from 'semver'\nimport type { Advisory, AffectedPackage, AffectedRange } from './normalize.js'\nimport { comparePep440, parsePep440 } from './pep440.js'\n\n// Matching an inventory against an advisory snapshot (advisory-cache.md §3). A\n// pure function: no I/O, no clock, no mutation. The same inventory and the same\n// snapshot always give the same matches.\n\nexport interface InventoryItem {\n  // The DependencyNode id this item came from.\n  dependencyId: string\n  ecosystem: string\n  name: string\n  version: string\n}\n\nexport interface AdvisorySnapshot {\n  asOf: string\n  advisories: Advisory[]\n}\n\nexport interface AdvisoryMatch {\n  advisoryId: string\n  dependencyId: string\n  // Versions the advisory says fix this package, lowest first. Empty when no\n  // fix is released.\n  fixedIn: string[]\n  asOf: string\n}\n\n// PyPI names are compared PEP 503-normalized (the inventory already is); npm and\n// Go names are case-sensitive.\nfunction sameName(ecosystem: string, a: string, b: string): boolean {\n  if (ecosystem === 'PyPI') return a.replace(/[-_.]+/g, '-').toLowerCase() === b.replace(/[-_.]+/g, '-').toLowerCase()\n  return a === b\n}\n\nfunction parse(v: string): semver.SemVer | null {\n  return semver.parse(v.startsWith('v') ? v.slice(1) : v)\n}\n\n// One range, evaluated the way the OSV schema defines it: walk the events in\n// version order. `introduced` opens an affected span, `fixed` closes it before\n// that version, and `last_affected` closes it after that version. The ordering\n// is supplied by the caller: semver for npm and Go, PEP 440 for PyPI.\nfunction inRange<V>(version: V, range: AffectedRange, parseV: (raw: string) => V | null, cmp: (a: V, b: V) => number): boolean {\n  const events = range.events\n    .map((e) => {\n      const [kind, raw] = Object.entries(e)[0] ?? []\n      if (!kind || raw === undefined) return null\n      const at = raw === '0' ? null : parseV(raw)\n      if (raw !== '0' && at === null) return null\n      return { kind, at }\n    })\n    .filter((e): e is { kind: string; at: V | null } => e !== null)\n    .sort((a, b) => (a.at === null ? -1 : b.at === null ? 1 : cmp(a.at, b.at)))\n\n  let affected = false\n  for (const e of events) {\n    const c = e.at === null ? 1 : cmp(version, e.at)\n    if (e.kind === 'introduced' && c >= 0) affected = true\n    else if (e.kind === 'fixed' && c >= 0) affected = false\n    else if (e.kind === 'last_affected' && c > 0) affected = false\n    else if (e.kind === 'limit' && c >= 0) affected = false\n  }\n  return affected\n}\n\nfunction packageAffects(pkg: AffectedPackage, ecosystem: string, version: string): boolean {\n  if (ecosystem === 'PyPI') {\n    // PyPI records normally enumerate their affected versions, and when they do\n    // the list is authoritative. A record that gives only a range is evaluated\n    // with PEP 440 ordering, so it can't silently never match. (OSV PyPI ranges\n    // are ECOSYSTEM type, which semver doesn't order correctly.)\n    if (pkg.versions && pkg.versions.length > 0) return pkg.versions.includes(version)\n    const v = parsePep440(version)\n    if (!v) return false\n    return pkg.ranges.some((r) => r.type === 'ECOSYSTEM' && inRange(v, r, parsePep440, comparePep440))\n  }\n  if (pkg.versions && pkg.versions.includes(version)) return true\n  const v = parse(version)\n  if (!v) return false\n  return pkg.ranges.some(\n    (r) => (r.type === 'SEMVER' || r.type === 'ECOSYSTEM') && inRange(v, r, parse, (a, b) => semver.compare(a, b)),\n  )\n}\n\nfunction fixedVersions(pkg: AffectedPackage): string[] {\n  const out = new Set<string>()\n  for (const r of pkg.ranges) for (const e of r.events) if (e.fixed) out.add(e.fixed)\n  return [...out].sort((a, b) => {\n    const [pa, pb] = [parse(a), parse(b)]\n    return pa && pb ? semver.compare(pa, pb) : a.localeCompare(b)\n  })\n}\n\nexport function matchAdvisories(inventory: InventoryItem[], snapshot: AdvisorySnapshot): AdvisoryMatch[] {\n  const out: AdvisoryMatch[] = []\n  for (const item of inventory) {\n    for (const adv of snapshot.advisories) {\n      const hits = adv.affected.filter(\n        (p) => p.ecosystem === item.ecosystem && sameName(item.ecosystem, p.name, item.name),\n      )\n      const affecting = hits.filter((p) => packageAffects(p, item.ecosystem, item.version))\n      if (affecting.length === 0) continue\n      out.push({\n        advisoryId: adv.id,\n        dependencyId: item.dependencyId,\n        fixedIn: [...new Set(affecting.flatMap(fixedVersions))],\n        asOf: snapshot.asOf,\n      })\n    }\n  }\n  return out.sort((a, b) => a.dependencyId.localeCompare(b.dependencyId) || a.advisoryId.localeCompare(b.advisoryId))\n}\n","// PEP 440 version ordering, for PyPI records that give a range but no explicit\n// version list (advisory-cache.md §3). Covers the public version scheme: epoch,\n// release segments, pre (a/b/rc), post and dev releases, and local versions\n// (`+local`, which sort after the same public version). A string that isn't a valid PEP 440\n// version returns null, and the caller treats that as \"can't evaluate\".\n//\n// https://peps.python.org/pep-0440/#version-scheme\n\nexport interface Pep440 {\n  epoch: number\n  release: number[]\n  pre: [number, number] | null // [0=a 1=b 2=rc, n]\n  post: number | null\n  dev: number | null\n  local: Array<number | string> | null\n}\n\nconst RE =\n  /^v?(?:(\\d+)!)?(\\d+(?:\\.\\d+)*)(?:[-_.]?(a|alpha|b|beta|c|rc|pre|preview)[-_.]?(\\d*))?(?:-(\\d+)|[-_.]?(?:post|rev|r)[-_.]?(\\d*))?(?:[-_.]?dev[-_.]?(\\d*))?(?:\\+([a-z0-9]+(?:[-_.][a-z0-9]+)*))?$/i\n\nconst PRE_RANK: Record<string, number> = { a: 0, alpha: 0, b: 1, beta: 1, c: 2, rc: 2, pre: 2, preview: 2 }\n\nexport function parsePep440(raw: string): Pep440 | null {\n  const m = RE.exec(raw.trim())\n  if (!m) return null\n  return {\n    epoch: m[1] ? Number(m[1]) : 0,\n    release: m[2]!.split('.').map(Number),\n    pre: m[3] ? [PRE_RANK[m[3].toLowerCase()]!, Number(m[4] || 0)] : null,\n    post: m[5] !== undefined ? Number(m[5]) : m[6] !== undefined ? Number(m[6] || 0) : null,\n    dev: m[7] !== undefined ? Number(m[7] || 0) : null,\n    local: m[8] ? m[8].split(/[-_.]/).map((seg) => (/^\\d+$/.test(seg) ? Number(seg) : seg.toLowerCase())) : null,\n  }\n}\n\nfunction cmpNum(a: number, b: number): number {\n  return a < b ? -1 : a > b ? 1 : 0\n}\n\n// The PEP 440 sort key, compared field by field. Release segments compare with\n// trailing zeros ignored (1.0 == 1.0.0). For a release, dev < pre < (final) < post.\nexport function comparePep440(a: Pep440, b: Pep440): number {\n  if (a.epoch !== b.epoch) return cmpNum(a.epoch, b.epoch)\n  const len = Math.max(a.release.length, b.release.length)\n  for (let i = 0; i < len; i++) {\n    const c = cmpNum(a.release[i] ?? 0, b.release[i] ?? 0)\n    if (c !== 0) return c\n  }\n  // Pre-release slot: a dev-only release (1.0.dev1) sorts before any pre-release.\n  const preKey = (v: Pep440): [number, number] =>\n    v.pre ? [v.pre[0], v.pre[1]] : v.post === null && v.dev !== null ? [-1, 0] : [3, 0]\n  const [pa, pb] = [preKey(a), preKey(b)]\n  if (pa[0] !== pb[0]) return cmpNum(pa[0], pb[0])\n  if (pa[1] !== pb[1]) return cmpNum(pa[1], pb[1])\n  const postKey = (v: Pep440) => (v.post === null ? -1 : v.post)\n  if (postKey(a) !== postKey(b)) return cmpNum(postKey(a), postKey(b))\n  const devKey = (v: Pep440) => (v.dev === null ? Number.POSITIVE_INFINITY : v.dev)\n  if (devKey(a) !== devKey(b)) return cmpNum(devKey(a), devKey(b))\n  // Local: none sorts before any; segments compare numerically when both are\n  // numbers, a number sorts after a string, strings compare lexically, and a\n  // shorter label that is a prefix of a longer one sorts first.\n  if (a.local === null || b.local === null) return a.local === b.local ? 0 : a.local === null ? -1 : 1\n  for (let i = 0; i < Math.max(a.local.length, b.local.length); i++) {\n    const [x, y] = [a.local[i], b.local[i]]\n    if (x === undefined || y === undefined) return x === undefined ? -1 : 1\n    if (typeof x === 'number' && typeof y === 'number') {\n      if (x !== y) return cmpNum(x, y)\n    } else if (typeof x !== typeof y) {\n      return typeof x === 'number' ? 1 : -1\n    } else if (x !== y) {\n      return String(x) < String(y) ? -1 : 1\n    }\n  }\n  return 0\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { parse as parseYaml } from 'yaml'\nimport type { ServiceNode } from '@neat.is/types'\n\nexport interface PackageJson {\n  name: string\n  version?: string\n  dependencies?: Record<string, string>\n  devDependencies?: Record<string, string>\n  engines?: { node?: string }\n}\n\nexport interface DiscoveredService {\n  pkg: PackageJson\n  dir: string\n  node: ServiceNode\n  // ADR-200 — nearest-service-wins file ownership. Absolute directories of OTHER\n  // discovered services nested strictly under `dir`. A source file belongs to the\n  // deepest discovered service that contains it, so an ancestor's file walk skips\n  // these subtrees rather than re-minting a nested service's symbols/routes/ORM\n  // nodes under itself. Populated by `discoverServices` for every service (empty\n  // when nothing is nested — a single-service or leaf service walks its whole\n  // tree exactly as before). ADR-255 also lists individual files here: a Go binary\n  // that shares its module root with its siblings excludes the files it doesn't own,\n  // so every walker skips an entry whether it names a directory or a file.\n  excludeDirs?: string[]\n  // #1557: the manifest declared no name, so `node.name` is the directory basename.\n  // A service that declares its name wins that name over a fallback one.\n  nameFromDir?: boolean\n}\n\n// C++ (ADR-202) contributes only the unambiguous extensions — `.cpp`/`.cc`/`.cxx`/\n// `.c++` impl, `.hpp`/`.hh`/`.hxx`/`.h++` C++-only headers. `.h`/`.c` are omitted:\n// shared with C, they'd pull pure-C source into the C++ symbol walker (see\n// SYMBOL_GRAMMAR_BY_EXT in symbols.ts).\nexport const SERVICE_FILE_EXTENSIONS = new Set(['.js', '.mjs', '.cjs', '.ts', '.tsx', '.py', '.go', '.rb', '.php', '.cs', '.java', '.kt', '.rs', '.cpp', '.cc', '.cxx', '.c++', '.hpp', '.hh', '.hxx', '.h++'])\nexport const CONFIG_FILE_EXTENSIONS = new Set(['.yaml', '.yml'])\n\n// A curated allowlist of JSON build/app-config files that get a ConfigNode by\n// exact basename (ADR-185). `.json` is deliberately NOT recognized wholesale —\n// that would pull in `tsconfig.json`, `package-lock.json`, and every JSON\n// fixture as \"config\" and churn every project's graph. These three name real\n// build configuration a failure can point at: Expo's `app.json` / `app.config.json`\n// and EAS's `eas.json`. Like every ConfigNode they record file existence only,\n// never contents (ADR-016, CLAUDE.md § Don't do). `package.json` is intentionally\n// absent — it already materializes as a ServiceNode, so recognizing it here too\n// would twin that and churn every repo; a dependency-phase EAS incident anchors\n// to the ServiceNode instead (ADR-185).\nexport const JSON_CONFIG_FILENAMES = new Set(['app.json', 'app.config.json', 'eas.json'])\nexport const IGNORED_DIRS = new Set([\n  'node_modules',\n  '.git',\n  '.turbo',\n  'dist',\n  'build',\n  '.next',\n  // `_next` is the *emitted* half of the pair above — `next build`'s output as\n  // it is served or exported. `.next` was listed and `_next` wasn't, so an\n  // exported bundle walked in as first-party source: minified chunks, one file\n  // per line, hundreds of KB each (#1254).\n  '_next',\n  // Agent scratch space. `.claude/worktrees/` holds a full checkout per agent\n  // session, so walking it re-extracts the whole repo once per worktree — and\n  // pulls in whatever build output those checkouts happen to carry. It is\n  // gitignored in practice, but the file walk doesn't read .gitignore, so the\n  // name has to be listed here.\n  '.claude',\n  // Python virtualenv shapes (issue #344). Walking into a venv pulls in the\n  // entire CPython stdlib + every installed package as if it were first-party\n  // service code — 20k+ files, none of which the user wrote. The shape names\n  // cover the three common venv tools (`venv` / `python -m venv`,\n  // `virtualenv`) and the tox + PEP 582 conventions.\n  '.venv',\n  'venv',\n  '__pypackages__',\n  '.tox',\n  // `site-packages` shows up nested inside venvs that don't carry one of the\n  // outer names (system Python on macOS, in-place pyenv layouts). Listing it\n  // here means we stop the walk at the boundary even when the wrapper dir\n  // wasn't recognisable.\n  'site-packages',\n  // Checked-in third-party code: Go's `vendor/` (golang/dep and `go mod vendor`),\n  // PHP Composer's `vendor/`, Ruby's `vendor/bundle`. Never first-party, never a\n  // service (ADR-256): a Dockerfile under `vendor/golang.org/x/net/http2/` minted\n  // a phantom `http2` service.\n  'vendor',\n])\n\n// Marker file `python -m venv` and `virtualenv` both drop at the venv root.\n// Used by the walkers to recognise venvs whose top-level directory doesn't\n// happen to match one of the canonical `IGNORED_DIRS` names (issue #344).\n// Cached per process to keep the recursion hot path off the fs after the\n// first walk; venv contents don't change inside one extract pass.\nconst PYVENV_MARKER_CACHE = new Map<string, boolean>()\n\nexport async function isPythonVenvDir(dir: string): Promise<boolean> {\n  const cached = PYVENV_MARKER_CACHE.get(dir)\n  if (cached !== undefined) return cached\n  try {\n    const stat = await fs.stat(path.join(dir, 'pyvenv.cfg'))\n    const ok = stat.isFile()\n    PYVENV_MARKER_CACHE.set(dir, ok)\n    return ok\n  } catch {\n    PYVENV_MARKER_CACHE.set(dir, false)\n    return false\n  }\n}\n\nexport function isConfigFile(name: string): { match: boolean; fileType: string } {\n  const ext = path.extname(name)\n  if (CONFIG_FILE_EXTENSIONS.has(ext)) return { match: true, fileType: ext.slice(1) }\n  // Curated JSON build-config files (ADR-185) — exact basename only, never all\n  // `.json`. fileType 'json' so a consumer can tell them from yaml/env config.\n  if (JSON_CONFIG_FILENAMES.has(name)) return { match: true, fileType: 'json' }\n  // .env, .env.local, .env.production. Bare filename or any dotted-suffix\n  // variant; folder names get filtered upstream by walking files only.\n  // ADR-065 #4 filters .env.template / .env.example / .env.sample (and the\n  // dotted-suffix variants) at the producer level — those are documentation,\n  // not runtime config.\n  if (name === '.env' || name.startsWith('.env.')) {\n    if (isEnvTemplateFile(name)) return { match: false, fileType: '' }\n    // NEAT writes `.env.neat` itself during `--apply` (ADR-069 §4). Ingesting\n    // it would record our own instrumentation env as if it were the user's\n    // declared config — self-pollution. Skip it the same way the template\n    // filter skips onboarding docs.\n    if (isNeatAuthoredEnvFile(name)) return { match: false, fileType: '' }\n    return { match: true, fileType: 'env' }\n  }\n  return { match: false, fileType: '' }\n}\n\n// NEAT-authored artifacts the installer drops into the user's tree during\n// `--apply` (ADR-069). Extraction skips them: they're our own runtime hooks,\n// not first-party config or source. Ingesting them pollutes the graph with\n// NEAT's instrumentation as though the user had written it.\n//\n//   `.env.neat`         — per-package env carrying `OTEL_SERVICE_NAME`.\n//   `otel-init.{ext}`   — generated SDK bootstrap (js/cjs/mjs/ts), including\n//                         the framework variants (`src/otel-init.*`,\n//                         `server/plugins/otel-init.*`) — basename is stable.\nexport function isNeatAuthoredEnvFile(name: string): boolean {\n  return name === '.env.neat'\n}\n\nexport function isNeatAuthoredSourceFile(name: string): boolean {\n  return /^otel-init\\.(?:js|cjs|mjs|ts|tsx)$/i.test(name) || name === 'neat_otel.go'\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// ADR-065 precision-filter helpers. Pre-emit gates inside the producer pass.\n// Filtered candidates are never written to the graph (idempotency intact).\n// ─────────────────────────────────────────────────────────────────────────\n\n// ADR-065 #1 — test-scope exclusion. Returns true when the file path matches\n// any test-scope pattern. Path is normalised to forward slashes before\n// matching so callers can pass either form.\n//\n// Patterns:\n//   - any segment named __tests__, __fixtures__, or integration-tests\n//   - basename matches *.spec.{ts,tsx,js,jsx,mjs,cjs,py}\n//   - basename matches *.test.{ts,tsx,js,jsx,mjs,cjs,py}\nexport function isTestPath(filePath: string): boolean {\n  const normalised = filePath.replace(/\\\\/g, '/')\n  const segments = normalised.split('/')\n  for (const seg of segments) {\n    if (\n      seg === '__tests__' ||\n      seg === '__fixtures__' ||\n      seg === 'integration-tests' ||\n      // Cypress end-to-end specs (ADR-242): `cypress/e2e/*.cy.ts` drives the app\n      // from outside, so a flag key it names is not a reader of that flag.\n      seg === 'cypress'\n    ) {\n      return true\n    }\n  }\n  const base = segments[segments.length - 1] ?? ''\n  if (base.endsWith('_test.go')) return true\n  return /\\.(spec|test|cy)\\.(?:tsx?|jsx?|mjs|cjs|py)$/i.test(base)\n}\n\n// ADR-065 #4 — `.env.template` exclusion. Matches:\n//   .env.template / .env.example / .env.sample\n//   .env.*.template / .env.*.example / .env.*.sample\n// These are docs/onboarding artifacts, not runtime config. ConfigNodes are\n// bound to runtime existence (ADR-016); templates fail that test.\nexport function isEnvTemplateFile(name: string): boolean {\n  if (\n    name === '.env.template' ||\n    name === '.env.example' ||\n    name === '.env.sample'\n  ) {\n    return true\n  }\n  // `.env.*.template` / `.env.*.example` / `.env.*.sample`\n  return /^\\.env\\.[^.]+\\.(?:template|example|sample)$/i.test(name)\n}\n\n// ADR-065 #2 — comment-body exclusion. Replaces every JS/TS comment span in\n// the source with an equal-length run of spaces, preserving line/column for\n// downstream line-mapping. Strings that contain `//` sequences (URLs) are\n// preserved by tracking the string context as we scan.\n//\n// Not a full parser — good enough for the medusa-shape failures. The HTTP\n// extractor's AST walk already gets comment-awareness for free; this helper\n// is for the regex-based extractors (redis, kafka, aws, grpc).\nexport function maskCommentsInSource(src: string): string {\n  const len = src.length\n  const out: string[] = new Array(len)\n  let i = 0\n  // String context: ' \" ` (template) — open-quote char, 0 when not in a string.\n  let inString: string | 0 = 0\n  let escaped = false\n  while (i < len) {\n    const c = src[i]!\n    if (inString !== 0) {\n      out[i] = c\n      if (escaped) {\n        escaped = false\n      } else if (c === '\\\\') {\n        escaped = true\n      } else if (c === inString) {\n        inString = 0\n      }\n      i++\n      continue\n    }\n    if (c === '/' && i + 1 < len) {\n      const next = src[i + 1]!\n      if (next === '/') {\n        out[i] = ' '\n        out[i + 1] = ' '\n        let j = i + 2\n        while (j < len && src[j] !== '\\n') {\n          out[j] = ' '\n          j++\n        }\n        i = j\n        continue\n      }\n      if (next === '*') {\n        out[i] = ' '\n        out[i + 1] = ' '\n        let j = i + 2\n        while (j < len) {\n          if (src[j] === '\\n') {\n            out[j] = '\\n'\n            j++\n            continue\n          }\n          if (src[j] === '*' && j + 1 < len && src[j + 1] === '/') {\n            out[j] = ' '\n            out[j + 1] = ' '\n            j += 2\n            break\n          }\n          out[j] = ' '\n          j++\n        }\n        i = j\n        continue\n      }\n    }\n    out[i] = c\n    if (c === \"'\" || c === '\"' || c === '`') inString = c\n    i++\n  }\n  return out.join('')\n}\n\n// ADR-065 #5 — exact hostname match for cross-service URL inference. Returns\n// true if `urlString` looks like an actual URL — has an explicit `scheme://`\n// or starts with a scheme-relative `//` — and its hostname matches `host`\n// exactly (case-insensitive). No `.includes()` containment, and no bare-string\n// matching: a literal like `'admin-bundler'` would otherwise parse as\n// `http://admin-bundler` and match the basename of every service directory,\n// which is how the v0.3.3 medusa pre-check produced 279 false positives.\n//\n// Accepts a `host` that may include a port (`api.example.com:8080`); in that\n// case the URL's hostname AND port must both match.\nconst URL_LIKE = /^(?:[a-z][a-z0-9+.-]*:)?\\/\\//i\n\nexport function urlMatchesHost(urlString: string, host: string): boolean {\n  if (typeof urlString !== 'string' || urlString.length === 0) return false\n  // Require the literal to look like a URL — scheme + `://` or scheme-relative\n  // `//host`. Bare hostnames are rejected; they're the load-bearing source of\n  // false positives.\n  if (!URL_LIKE.test(urlString)) return false\n  const [wantedHost, wantedPort] = host.split(':')\n  let parsed: URL\n  try {\n    // For scheme-relative `//host/path`, prepend `http:` so URL accepts it.\n    const candidate = urlString.startsWith('//') ? `http:${urlString}` : urlString\n    parsed = new URL(candidate)\n  } catch {\n    return false\n  }\n  if (parsed.hostname.toLowerCase() !== (wantedHost ?? '').toLowerCase()) return false\n  if (wantedPort && parsed.port !== wantedPort) return false\n  return true\n}\n\n// Strip semver range prefixes (^, ~, >=, etc.) and bare \"v\" so the extracted\n// version is usable for compat checks. We don't try to resolve ranges to actual\n// installed versions — that's a published-lockfile concern, not extraction's job.\nexport function cleanVersion(raw: string | undefined): string | undefined {\n  if (!raw) return undefined\n  return raw.replace(/^[\\^~><=v\\s]+/, '').trim() || undefined\n}\n\nexport async function readJson<T>(filePath: string): Promise<T> {\n  const raw = await fs.readFile(filePath, 'utf8')\n  return JSON.parse(raw) as T\n}\n\nexport async function readYaml<T>(filePath: string): Promise<T> {\n  const raw = await fs.readFile(filePath, 'utf8')\n  return parseYaml(raw) as T\n}\n\nexport async function exists(p: string): Promise<boolean> {\n  try {\n    await fs.access(p)\n    return true\n  } catch {\n    return false\n  }\n}\n\n// Thin re-export so existing callers (calls/, configs.ts, databases/, infra/)\n// keep their import path. Wire format lives in @neat.is/types/identity.ts per\n// ADR-029.\nexport { extractedEdgeId as makeEdgeId } from '@neat.is/types'\n","// The fix loop (G2): propose a remediation for a dependency's matched advisories,\n// purely from the advisories' fixed releases and the installed version. No I/O,\n// no network, no clock. The security card composes this alongside `fixedIn`; G1's\n// scan_diff then verifies a proposed bump actually cleared the CVEs and introduced\n// none.\n//\n// The action is PER DEPENDENCY, not per advisory: one dependency can match several\n// advisories with different fixed releases (lodash 4.17.19 and 4.17.21), and two\n// per-advisory bumps would conflict. So `to` is the lowest version that clears ALL\n// of the dependency's advisories (the highest of their minimal fixes), and an\n// agent bumps once.\n//\n// \"Non-breaking\" means a SAME-MAJOR bump, not \"within your declared range\": the\n// manifest constraint (^1.2.3) isn't on the graph, so the card is honest and says\n// \"same major\". A transitive dependency can't be bumped at its own version, so the\n// renderers (security-card.ts, the MCP tool) say to bump the parent only if its\n// range admits the fix, else override; `via` names the direct parent(s).\n\nimport semver from 'semver'\nimport type { SecurityFixAction } from '@neat.is/types'\nimport { comparePep440, parsePep440 } from './pep440.js'\n\nexport interface FixActionInput {\n  // One fixed-release array per advisory matched on this dependency.\n  fixedInByAdvisory: string[][]\n  // The installed (vulnerable) version on the DependencyNode.\n  installed: string\n  // The DependencyNode ecosystem: 'npm', 'PyPI', 'Go', etc.\n  ecosystem: string\n  // Whether the service declares this dependency directly or pulls it in.\n  scope: 'direct' | 'transitive'\n  // The direct parent(s) that introduced a transitive dependency. Empty for a\n  // direct dependency, and also empty when a transitive parent can't be\n  // attributed (the renderers then say \"override, parent unknown\").\n  introducedBy: string[]\n}\n\nexport function fixActionFor(input: FixActionInput): SecurityFixAction {\n  // The lowest fixed release above the installed version, per advisory. A\n  // dependency is clear only when every advisory is: if any has no fix above the\n  // installed version, no single bump clears it. The target clears all of them:\n  // the highest of the per-advisory minimal fixes. Null when there's nothing to\n  // clear to (no advisory, or one has no fix above installed), which\n  // actionForTarget renders as remove-or-replace.\n  const minimals = input.fixedInByAdvisory.map((f) => minimalAbove(f, input.installed, input.ecosystem))\n  const target =\n    input.fixedInByAdvisory.length === 0 || minimals.some((m) => m === null)\n      ? null\n      : maxVersion(minimals as string[], input.ecosystem)\n  return actionForTarget({\n    target,\n    installed: input.installed,\n    ecosystem: input.ecosystem,\n    scope: input.scope,\n    introducedBy: input.introducedBy,\n    noClearReason: noClearReason(input.fixedInByAdvisory, input.installed),\n  })\n}\n\n// The rigorous per-dependency target: the LOWEST fixed release the advisory\n// matcher actually clears of EVERY one of the dependency's advisories.\n// fixActionFor's max-of-minimals assumes any version at or above each advisory's\n// fix is clear of it, which breaks when an advisory re-affects a later range\n// (affected [1.0, 1.5) AND [1.8, 2.0)): the max of the minimal fixes can land\n// back inside another advisory's affected range and not clear it. The caller\n// supplies `clears`, which re-runs the matcher at a candidate version (the\n// snapshot lives at the call site, so this stays pure), and we take the lowest\n// candidate that clears them all. Null when none does -> remove-or-replace.\nexport function rigorousFixAction(input: {\n  // Every fixed release the dependency's advisories list (duplicates are fine).\n  candidates: string[]\n  installed: string\n  ecosystem: string\n  scope: 'direct' | 'transitive'\n  introducedBy: string[]\n  // True when this version is clear, i.e. the caller's matcher finds nothing it\n  // should avoid at it. Injected so the matcher (and its snapshot) stays at the\n  // call site and this function stays pure.\n  clears: (version: string) => boolean\n}): SecurityFixAction {\n  const above = input.candidates.filter((v) => {\n    const c = compareVersions(v, input.installed, input.ecosystem)\n    return c !== null && c > 0\n  })\n  const sorted = [...new Set(above)].sort((a, b) => compareVersions(a, b, input.ecosystem) ?? 0)\n  const target = sorted.find((v) => input.clears(v)) ?? null\n  return actionForTarget({\n    target,\n    installed: input.installed,\n    ecosystem: input.ecosystem,\n    scope: input.scope,\n    introducedBy: input.introducedBy,\n    noClearReason:\n      input.candidates.length === 0\n        ? 'the advisories list no fixed release'\n        : 'no fixed release clears every advisory on this dependency',\n  })\n}\n\n// Build the action for a known clearing target, or remove-or-replace when\n// nothing clears every advisory (target null). A same-major step is a bump an\n// agent can take; otherwise the fix exists but is breaking, so remove-or-replace\n// still carries it as majorTo so the agent can choose it over removal. A Go major\n// is a new module import path, not just a higher version, so the reason says so.\nexport function actionForTarget(input: {\n  target: string | null\n  installed: string\n  ecosystem: string\n  scope: 'direct' | 'transitive'\n  introducedBy: string[]\n  noClearReason: string\n}): SecurityFixAction {\n  const via = input.scope === 'transitive' ? [...input.introducedBy] : []\n  if (input.target === null) {\n    return { kind: 'remove-or-replace', reason: input.noClearReason }\n  }\n  if (sameMajor(input.installed, input.target, input.ecosystem) === true) {\n    return { kind: 'bump-to-fixedIn', to: input.target, via }\n  }\n  const reason =\n    input.ecosystem === 'Go'\n      ? `clearing every advisory needs ${input.target}, a new major module path (the import path changes)`\n      : `clearing every advisory needs ${input.target}, a major-version bump`\n  return { kind: 'remove-or-replace', reason, majorTo: input.target }\n}\n\nfunction noClearReason(fixedInByAdvisory: string[][], installed: string): string {\n  if (fixedInByAdvisory.every((f) => f.length === 0)) return 'the advisories list no fixed release'\n  return `at least one advisory has no fixed release above the installed ${installed}`\n}\n\nfunction minimalAbove(fixedIn: string[], installed: string, ecosystem: string): string | null {\n  const newer = fixedIn.filter((f) => {\n    const c = compareVersions(f, installed, ecosystem)\n    return c !== null && c > 0\n  })\n  if (newer.length === 0) return null\n  return newer.reduce((lowest, f) => {\n    const c = compareVersions(f, lowest, ecosystem)\n    return c !== null && c < 0 ? f : lowest\n  })\n}\n\nfunction maxVersion(versions: string[], ecosystem: string): string {\n  return versions.reduce((highest, v) => {\n    const c = compareVersions(v, highest, ecosystem)\n    return c !== null && c > 0 ? v : highest\n  })\n}\n\n// Ecosystem-aware version ordering. PyPI uses PEP 440; everything else uses\n// semver, coercing a loose or v-prefixed version (v1.2 -> 1.2.0) so a comparison\n// still lands. Returns null when either side can't be parsed, and the caller stays\n// conservative.\nfunction compareVersions(a: string, b: string, ecosystem: string): number | null {\n  if (ecosystem === 'PyPI') {\n    const pa = parsePep440(a)\n    const pb = parsePep440(b)\n    return pa && pb ? comparePep440(pa, pb) : null\n  }\n  const sa = toSemver(a)\n  const sb = toSemver(b)\n  return sa && sb ? semver.compare(sa, sb) : null\n}\n\n// Same-major (non-breaking) for the installed -> fixed step, false when it's a\n// major bump, null when it can't be told. Go has no special case: a v2+ module is\n// a different import path (a different DependencyNode), so a fix that matched THIS\n// node is already same-path, while v0 -> v1 is a real breaking boundary that the\n// semver major check (and the 0.x rule) below catches.\nfunction sameMajor(installed: string, fixed: string, ecosystem: string): boolean | null {\n  if (ecosystem === 'PyPI') {\n    const pi = parsePep440(installed)\n    const pf = parsePep440(fixed)\n    if (!pi || !pf) return null\n    return (pi.release[0] ?? 0) === (pf.release[0] ?? 0)\n  }\n  const si = toSemver(installed)\n  const sf = toSemver(fixed)\n  if (!si || !sf) return null\n  if (semver.major(si) !== semver.major(sf)) return false\n  // 0.x: under caret rules a minor bump is breaking (0.2 -> 0.3), so only a\n  // same-minor change counts as non-breaking.\n  if (semver.major(si) === 0) return semver.minor(si) === semver.minor(sf)\n  return true\n}\n\nfunction toSemver(raw: string): string | null {\n  return semver.valid(raw) ?? semver.coerce(raw)?.version ?? null\n}\n","import type { ReachabilityAnswer, SecurityScanResult, ServiceNode } from '@neat.is/types'\nimport { NodeType, Provenance, isDependencySymbolId, parseDependencySymbolId } from '@neat.is/types'\nimport type { NeatGraph } from './graph.js'\nimport { inventoryFromGraph, loadAdvisorySnapshot, matchAdvisories } from './advisories/index.js'\nimport type { InventoryItem } from './advisories/index.js'\nimport { buildSecurityCards, highestLevel, rankSecurityCards, reachPath, reconcileDepFixActions } from './security-card.js'\n\n// The security scan behind the reachable-CVE surfaces (security-card.md §6):\n// inventory from the graph, an advisory snapshot (the one I/O step, through the\n// advisory cache), the pure matcher, then the pure card builder and ranking.\n\nexport interface ScanOptions {\n  fetchImpl?: typeof fetch\n  env?: NodeJS.ProcessEnv\n  now?: () => number\n  // Only cards for this service (its name or its node id).\n  service?: string\n}\n\n// A service filter given as a node id (`service:shop`) or a bare name (`shop`),\n// resolved to the name cards carry.\nfunction serviceName(graph: NeatGraph, service: string): string {\n  if (graph.hasNode(service)) {\n    const node = graph.getNodeAttributes(service) as ServiceNode\n    if (node.type === NodeType.ServiceNode) return node.name\n  }\n  return service\n}\n\nasync function scan(graph: NeatGraph, inventory: InventoryItem[], opts: ScanOptions): Promise<SecurityScanResult> {\n  const loaded = await loadAdvisorySnapshot(inventory, opts)\n  const base = { advisories: loaded.source, stale: loaded.stale, errors: loaded.errors, inventory: inventory.length }\n  if (!loaded.snapshot) return { ...base, asOf: null, findings: [], context: [] }\n  const snapshot = loaded.snapshot\n  const cards = matchAdvisories(inventory, snapshot)\n    .flatMap((m) => buildSecurityCards(graph, m, snapshot))\n    .filter((c) => !opts.service || c.service === serviceName(graph, opts.service))\n  // One shared fix target per dependency across its advisories, so an agent bumps\n  // once instead of once per CVE (ADR-274 fix loop).\n  const ranked = rankSecurityCards(reconcileDepFixActions(cards, snapshot))\n  return {\n    ...base,\n    asOf: snapshot.asOf,\n    findings: ranked.filter((c) => c.reachability.level !== 'present'),\n    context: ranked.filter((c) => c.reachability.level === 'present'),\n  }\n}\n\n/** Every matched advisory in the project, findings ranked, `present` as context. */\nexport async function scanProjectCves(graph: NeatGraph, opts: ScanOptions = {}): Promise<SecurityScanResult> {\n  return scan(graph, inventoryFromGraph(graph), opts)\n}\n\n/**\n * One package's answer: its cards and the highest level they reach. Matches the\n * package by name (PyPI names PEP 503-normalized), optionally pinned to a version\n * and an ecosystem. Only that package's versions are looked up.\n */\nexport async function isReachable(\n  graph: NeatGraph,\n  query: { package: string; version?: string; ecosystem?: string; symbol?: string },\n  opts: ScanOptions = {},\n): Promise<ReachabilityAnswer> {\n  const norm = (eco: string, n: string) => (eco === 'PyPI' ? n.replace(/[-_.]+/g, '-').toLowerCase() : n)\n  const inventory = inventoryFromGraph(graph).filter(\n    (i) =>\n      norm(i.ecosystem, i.name) === norm(i.ecosystem, query.package) &&\n      (!query.version || i.version === query.version) &&\n      (!query.ecosystem || i.ecosystem === query.ecosystem),\n  )\n  const result = await scan(graph, inventory, opts)\n  const level = highestLevel([...result.findings, ...result.context])\n  if (!query.symbol) {\n    return { ...result, package: query.package, grain: 'dependency', reachable: result.findings.length > 0, level }\n  }\n  // Symbol grain: a call path from a depending service's code to a function of\n  // that name in the package (its qualname, or the last segment of it).\n  const symbol = query.symbol\n  const want = opts.service ? serviceName(graph, opts.service) : undefined\n  const limits: string[] = []\n  let path: ReturnType<typeof reachPath> = null\n  let sawCode = false\n  for (const item of inventory) {\n    const owned = graph.outNeighbors(item.dependencyId).filter(isDependencySymbolId)\n    if (owned.length) sawCode = true\n    const targets = new Set(\n      owned.filter((n) => {\n        const p = parseDependencySymbolId(n)\n        return !!p && (p.qualname === symbol || p.qualname.endsWith(`.${symbol}`))\n      }),\n    )\n    if (targets.size === 0) continue\n    for (const svc of [...graph.inNeighbors(item.dependencyId)].sort()) {\n      const node = graph.getNodeAttributes(svc) as ServiceNode\n      if (node.type !== NodeType.ServiceNode || (want && node.name !== want)) continue\n      path = reachPath(graph, node.name, item.dependencyId, targets)\n      if (path) break\n    }\n    if (path) break\n  }\n  if (!path) {\n    limits.push(\n      !sawCode\n        ? `The code of ${query.package} is not in the graph (it is extracted only for versions with a known advisory), so symbol reachability can't be answered.`\n        : 'No EXTRACTED call path from first-party code reaches it. Calls on objects (method dispatch), dynamic requires and re-exports from other packages are not resolved, so this does not show it is unreachable.',\n    )\n  }\n  return {\n    ...result,\n    package: query.package,\n    grain: 'symbol',\n    symbol,\n    reachable: path !== null,\n    level,\n    ...(path ? { path: path.map((e) => ({ from: e.source, to: e.target, provenance: Provenance.EXTRACTED })) } : {}),\n    ...(limits.length ? { limits } : {}),\n  }\n}\n","import type { DependencyNode, GraphNode } from '@neat.is/types'\nimport { NodeType } from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport type { InventoryItem } from './match.js'\n\nexport { foldAliases, normalizeOsv } from './normalize.js'\nexport type { Advisory, AffectedPackage, OsvRecord, SeverityLabel } from './normalize.js'\nexport { matchAdvisories } from './match.js'\nexport type { AdvisoryMatch, AdvisorySnapshot, InventoryItem } from './match.js'\nexport { advisoryDisclosure, advisoryDisclosureFor, advisorySource, loadAdvisorySnapshot, OSV_API } from './source.js'\nexport type { AdvisorySource, SnapshotResult } from './source.js'\n\n// The project's resolved dependencies, as the matcher reads them. One item per\n// DependencyNode: the node is per version, so services sharing a version share it.\nexport function inventoryFromGraph(graph: NeatGraph): InventoryItem[] {\n  const out: InventoryItem[] = []\n  graph.forEachNode((id, attrs) => {\n    const a = attrs as GraphNode\n    if (a.type !== NodeType.DependencyNode) return\n    const d = a as DependencyNode\n    out.push({ dependencyId: id, ecosystem: d.ecosystem, name: d.name, version: d.version })\n  })\n  return out.sort((x, y) => x.dependencyId.localeCompare(y.dependencyId))\n}\nexport { computeFixDiff, fixDiffPair, isPackageSource, packageSymbols } from './fixdiff.js'\nexport type { ChangedSymbol, ChangeStatus, FixDiff, PackageSymbol } from './fixdiff.js'\nexport { buildFixDiff } from './release-fetch.js'\n","import type { FixDiff } from './fixdiff.js'\n\n// Normalized advisories (advisory-cache.md §1). One shape for every source, so\n// matching and the security card never read raw OSV.\n\nexport type SeverityLabel = 'critical' | 'high' | 'moderate' | 'low' | 'unknown'\n\nexport interface AffectedRange {\n  type: 'SEMVER' | 'ECOSYSTEM' | 'GIT'\n  events: Array<{ introduced?: string; fixed?: string; last_affected?: string; limit?: string }>\n}\n\nexport interface AffectedPackage {\n  ecosystem: string\n  name: string\n  ranges: AffectedRange[]\n  versions?: string[]\n  // Curated symbols where the source publishes them (vuln.go.dev).\n  symbols?: string[]\n}\n\nexport interface Advisory {\n  id: string\n  aliases: string[]\n  summary: string\n  details: string\n  severity: { cvss?: string; label: SeverityLabel }\n  cwe: string[]\n  published?: string\n  modified: string\n  affected: AffectedPackage[]\n  fixRefs: string[]\n  // What the fix release changed, at symbol grain (advisory-cache.md §4). NEAT's\n  // own derived data, absent until computed.\n  fixDiff?: FixDiff\n}\n\n// The subset of an OSV record this reads. https://ossf.github.io/osv-schema/\nexport interface OsvRecord {\n  id: string\n  aliases?: string[]\n  summary?: string\n  details?: string\n  modified: string\n  published?: string\n  severity?: Array<{ type: string; score: string }>\n  database_specific?: { severity?: string; cwe_ids?: string[] }\n  affected?: Array<{\n    package?: { ecosystem?: string; name?: string }\n    ranges?: Array<{ type: string; events: AffectedRange['events'] }>\n    versions?: string[]\n    ecosystem_specific?: { imports?: Array<{ path?: string; symbols?: string[] }> }\n  }>\n  references?: Array<{ type?: string; url?: string }>\n}\n\nfunction severityLabel(raw: string | undefined): SeverityLabel {\n  switch ((raw ?? '').toLowerCase()) {\n    case 'critical':\n      return 'critical'\n    case 'high':\n      return 'high'\n    case 'moderate':\n    case 'medium':\n      return 'moderate'\n    case 'low':\n      return 'low'\n    default:\n      return 'unknown'\n  }\n}\n\nexport function normalizeOsv(rec: OsvRecord): Advisory {\n  const cvss = rec.severity?.find((s) => s.type.startsWith('CVSS'))?.score\n  return {\n    id: rec.id,\n    aliases: [...(rec.aliases ?? [])].sort(),\n    summary: rec.summary ?? '',\n    details: rec.details ?? '',\n    severity: { ...(cvss ? { cvss } : {}), label: severityLabel(rec.database_specific?.severity) },\n    cwe: [...(rec.database_specific?.cwe_ids ?? [])].sort(),\n    ...(rec.published ? { published: rec.published } : {}),\n    modified: rec.modified,\n    affected: (rec.affected ?? [])\n      .filter((a) => a.package?.ecosystem && a.package?.name)\n      .map((a) => {\n        const symbols = (a.ecosystem_specific?.imports ?? []).flatMap((imp) =>\n          (imp.symbols ?? []).map((s) => (imp.path ? `${imp.path}.${s}` : s)),\n        )\n        return {\n          ecosystem: a.package!.ecosystem!,\n          name: a.package!.name!,\n          ranges: (a.ranges ?? [])\n            .filter((r) => r.type === 'SEMVER' || r.type === 'ECOSYSTEM' || r.type === 'GIT')\n            .map((r) => ({ type: r.type as AffectedRange['type'], events: r.events })),\n          ...(a.versions && a.versions.length > 0 ? { versions: a.versions } : {}),\n          ...(symbols.length > 0 ? { symbols } : {}),\n        }\n      }),\n    fixRefs: (rec.references ?? []).filter((r) => r.type === 'FIX' && r.url).map((r) => r.url!),\n  }\n}\n\n// Fold advisories that alias each other (a GHSA and a PYSEC for one issue) into\n// one entry (advisory-cache.md §1). The canonical id is the GHSA when the group\n// has one, otherwise the lowest id. The other ids go to `aliases`. Affected\n// packages are merged, so a range only one record lists isn't lost.\nexport function foldAliases(advisories: Advisory[]): Advisory[] {\n  const parent = new Map<string, string>()\n  const find = (x: string): string => {\n    let r = x\n    while (parent.get(r) !== undefined && parent.get(r) !== r) r = parent.get(r)!\n    parent.set(x, r)\n    return r\n  }\n  const union = (a: string, b: string) => {\n    const [ra, rb] = [find(a), find(b)]\n    if (ra !== rb) parent.set(ra, rb)\n  }\n  const byId = new Map(advisories.map((a) => [a.id, a]))\n  for (const a of advisories) {\n    if (!parent.has(a.id)) parent.set(a.id, a.id)\n    // Only fold through ids we actually hold: a CVE alias shared by two records\n    // joins them, but an alias alone never creates an entry.\n    for (const alias of a.aliases) {\n      if (!parent.has(alias)) parent.set(alias, alias)\n      union(a.id, alias)\n    }\n  }\n  const groups = new Map<string, Advisory[]>()\n  for (const a of advisories) {\n    const root = find(a.id)\n    const g = groups.get(root) ?? []\n    g.push(a)\n    groups.set(root, g)\n  }\n  const out: Advisory[] = []\n  for (const group of groups.values()) {\n    const ids = group.map((a) => a.id).sort()\n    const canonicalId = ids.find((id) => id.startsWith('GHSA-')) ?? ids[0]!\n    const primary = byId.get(canonicalId)!\n    const aliasSet = new Set<string>()\n    for (const a of group) {\n      for (const x of [a.id, ...a.aliases]) if (x !== canonicalId) aliasSet.add(x)\n    }\n    const affected: AffectedPackage[] = []\n    const seen = new Set<string>()\n    for (const a of [primary, ...group.filter((g) => g !== primary)]) {\n      for (const p of a.affected) {\n        const key = JSON.stringify(p)\n        if (!seen.has(key)) {\n          seen.add(key)\n          affected.push(p)\n        }\n      }\n    }\n    const best = group.find((a) => a.severity.label !== 'unknown') ?? primary\n    out.push({\n      ...primary,\n      aliases: [...aliasSet].sort(),\n      severity: primary.severity.label !== 'unknown' ? primary.severity : best.severity,\n      cwe: [...new Set(group.flatMap((a) => a.cwe))].sort(),\n      affected,\n      fixRefs: [...new Set(group.flatMap((a) => a.fixRefs))],\n      modified: group.map((a) => a.modified).sort().at(-1)!,\n    })\n  }\n  return out.sort((a, b) => a.id.localeCompare(b.id))\n}\n","import { promises as fs } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { foldAliases, normalizeOsv, type Advisory, type OsvRecord } from './normalize.js'\nimport type { AdvisorySnapshot, InventoryItem } from './match.js'\nimport { buildFixDiff } from './release-fetch.js'\nimport type { FixDiff } from './fixdiff.js'\n\n// Where advisories come from, and the local cache (advisory-cache.md §2).\n//\n//   1. a NEAT-hosted mirror (NEAT_ADVISORIES_URL), which serves OSV's query API\n//      so a project's inventory doesn't go to a third party;\n//   2. OSV itself (api.osv.dev), which does receive the package names and\n//      versions. `neat doctor` and every `neat security` run say so\n//      (advisoryDisclosure, below);\n//   3. the bulk export, for offline use. That arrives in a later pass.\n//\n// NEAT_ADVISORIES=off turns all of it off, and callers then report \"advisories\n// disabled\", never \"no vulnerabilities\".\n\nexport const OSV_API = 'https://api.osv.dev'\n\n/**\n * The one line that says where a project's dependency list goes when advisories\n * are looked up (advisory-cache.md §2). Shared by `neat doctor`, the `neat\n * security` commands and the daemon's dependency-code loop, so they never word it\n * differently. `sendsInventory` is true when the package names and versions leave\n * the machine for a third party (OSV queried directly).\n */\nexport function advisoryDisclosure(\n  source: AdvisorySource,\n  baseUrl?: string | null,\n): { source: AdvisorySource; sendsInventory: boolean; line: string } {\n  if (source === 'osv') {\n    return {\n      source,\n      sendsInventory: true,\n      line:\n        'Advisories: querying api.osv.dev directly; your dependency names and versions are sent to OSV. ' +\n        'Set NEAT_ADVISORIES_URL for a hosted mirror, or NEAT_ADVISORIES=off to disable.',\n    }\n  }\n  if (source === 'mirror') {\n    return {\n      source,\n      sendsInventory: false,\n      line: `Advisories: from the mirror at ${baseUrl ?? 'NEAT_ADVISORIES_URL'}; dependency names and versions go only there.`,\n    }\n  }\n  return { source, sendsInventory: false, line: 'Advisories: off (NEAT_ADVISORIES=off); no vulnerability check runs.' }\n}\n\n/** advisoryDisclosure for the source this environment selects. */\nexport function advisoryDisclosureFor(env: NodeJS.ProcessEnv = process.env): ReturnType<typeof advisoryDisclosure> {\n  const { source, baseUrl } = advisorySource(env)\n  return advisoryDisclosure(source, baseUrl)\n}\nconst TTL_MS = 24 * 60 * 60 * 1000\nconst BATCH = 1000\n\nexport type AdvisorySource = 'mirror' | 'osv' | 'disabled'\n\nexport function advisorySource(env: NodeJS.ProcessEnv = process.env): { source: AdvisorySource; baseUrl: string | null } {\n  if ((env.NEAT_ADVISORIES ?? '').toLowerCase() === 'off') return { source: 'disabled', baseUrl: null }\n  const mirror = env.NEAT_ADVISORIES_URL?.trim()\n  if (mirror) return { source: 'mirror', baseUrl: mirror.replace(/\\/+$/, '') }\n  return { source: 'osv', baseUrl: OSV_API }\n}\n\nfunction cacheDir(env: NodeJS.ProcessEnv = process.env): string {\n  const home = env.NEAT_HOME ? path.resolve(env.NEAT_HOME) : path.join(os.homedir(), '.neat')\n  return path.join(home, 'advisories')\n}\n\nfunction cacheFile(dir: string, item: Pick<InventoryItem, 'ecosystem' | 'name' | 'version'>): string {\n  return path.join(dir, item.ecosystem, `${encodeURIComponent(item.name)}@${encodeURIComponent(item.version)}.json`)\n}\n\ninterface CacheEntry {\n  fetchedAt: string\n  advisories: Advisory[]\n}\n\nasync function readCache(file: string): Promise<CacheEntry | null> {\n  try {\n    return JSON.parse(await fs.readFile(file, 'utf8')) as CacheEntry\n  } catch {\n    return null\n  }\n}\n\nasync function writeCache(file: string, entry: CacheEntry): Promise<void> {\n  await fs.mkdir(path.dirname(file), { recursive: true })\n  const tmp = `${file}.${process.pid}.tmp`\n  await fs.writeFile(tmp, JSON.stringify(entry))\n  await fs.rename(tmp, file)\n}\n\nasync function postJson(fetchImpl: typeof fetch, url: string, body: unknown): Promise<unknown> {\n  const res = await fetchImpl(url, {\n    method: 'POST',\n    headers: { 'content-type': 'application/json' },\n    body: JSON.stringify(body),\n    signal: AbortSignal.timeout(60_000),\n  })\n  if (!res.ok) throw new Error(`advisory query failed: ${res.status}`)\n  return res.json()\n}\n\nasync function getJson(fetchImpl: typeof fetch, url: string): Promise<unknown> {\n  const res = await fetchImpl(url, { signal: AbortSignal.timeout(60_000) })\n  if (!res.ok) throw new Error(`advisory fetch failed: ${res.status}`)\n  return res.json()\n}\n\n// querybatch returns ids only. Each id's full record is fetched once per call.\nasync function queryIds(\n  fetchImpl: typeof fetch,\n  baseUrl: string,\n  items: InventoryItem[],\n): Promise<Map<InventoryItem, string[]>> {\n  const out = new Map<InventoryItem, string[]>()\n  for (let i = 0; i < items.length; i += BATCH) {\n    const chunk = items.slice(i, i + BATCH)\n    let pending = chunk.map((it) => ({ item: it, page_token: undefined as string | undefined }))\n    while (pending.length > 0) {\n      const body = {\n        queries: pending.map(({ item, page_token }) => ({\n          package: { ecosystem: item.ecosystem, name: item.name },\n          version: item.version,\n          ...(page_token ? { page_token } : {}),\n        })),\n      }\n      const res = (await postJson(fetchImpl, `${baseUrl}/v1/querybatch`, body)) as {\n        results?: Array<{ vulns?: Array<{ id: string }>; next_page_token?: string }>\n      }\n      const next: typeof pending = []\n      pending.forEach(({ item }, k) => {\n        const r = res.results?.[k]\n        out.set(item, [...(out.get(item) ?? []), ...(r?.vulns ?? []).map((v) => v.id)])\n        if (r?.next_page_token) next.push({ item, page_token: r.next_page_token })\n      })\n      pending = next\n    }\n  }\n  return out\n}\n\nexport interface SnapshotResult {\n  source: AdvisorySource\n  snapshot: AdvisorySnapshot | null\n  // Packages served from a cache older than the TTL because a refresh failed.\n  stale: number\n  errors: string[]\n}\n\n/**\n * Build an advisory snapshot for an inventory. Fresh cache entries are used as\n * they are. Missing or stale ones are refreshed from the configured source, and\n * a failed refresh keeps serving the last good entry, counted in `stale`.\n */\nexport async function loadAdvisorySnapshot(\n  inventory: InventoryItem[],\n  opts: { fetchImpl?: typeof fetch; env?: NodeJS.ProcessEnv; now?: () => number } = {},\n): Promise<SnapshotResult> {\n  const env = opts.env ?? process.env\n  const { source, baseUrl } = advisorySource(env)\n  if (source === 'disabled' || !baseUrl) return { source, snapshot: null, stale: 0, errors: [] }\n  const fetchImpl = opts.fetchImpl ?? fetch\n  const now = opts.now ?? Date.now\n  const dir = cacheDir(env)\n\n  const unique = new Map<string, InventoryItem>()\n  for (const it of inventory) unique.set(`${it.ecosystem}\\u0000${it.name}\\u0000${it.version}`, it)\n  const items = [...unique.values()]\n\n  const collected: Advisory[] = []\n  // The snapshot is as old as the oldest data in it.\n  const fetchedTimes: string[] = []\n  const toRefresh: Array<{ item: InventoryItem; old: CacheEntry | null }> = []\n  for (const item of items) {\n    const cached = await readCache(cacheFile(dir, item))\n    if (cached && now() - Date.parse(cached.fetchedAt) < TTL_MS) {\n      collected.push(...cached.advisories)\n      fetchedTimes.push(cached.fetchedAt)\n    } else toRefresh.push({ item, old: cached })\n  }\n\n  let stale = 0\n  const errors: string[] = []\n  if (toRefresh.length > 0) {\n    try {\n      const ids = await queryIds(fetchImpl, baseUrl, toRefresh.map((r) => r.item))\n      const records = new Map<string, Advisory>()\n      for (const id of new Set([...ids.values()].flat())) {\n        records.set(id, normalizeOsv((await getJson(fetchImpl, `${baseUrl}/v1/vulns/${encodeURIComponent(id)}`)) as OsvRecord))\n      }\n      const fetchedAt = new Date(now()).toISOString()\n      // The fix-diff is NEAT's own derived data, cached with the advisory it\n      // belongs to (advisory-cache.md §4). It's computed once per (advisory,\n      // ecosystem, name): a package's two fix-diff releases don't depend on which\n      // installed version matched, so versions of one package share the result.\n      // buildFixDiff never throws, so a registry miss here can't stale a refresh.\n      const fixDiffs = new Map<string, FixDiff | undefined>()\n      for (const { item } of toRefresh) {\n        const base = (ids.get(item) ?? []).map((id) => records.get(id)!).filter(Boolean)\n        const advisories: Advisory[] = []\n        for (const adv of base) {\n          const key = `${adv.id}\\u0000${item.ecosystem}\\u0000${item.name}`\n          if (!fixDiffs.has(key)) {\n            fixDiffs.set(key, await buildFixDiff(adv, { ecosystem: item.ecosystem, name: item.name }, { fetchImpl }))\n          }\n          const fixDiff = fixDiffs.get(key)\n          // A fresh object, so one package's fix-diff never lands on the record\n          // shared with another package in the same refresh.\n          advisories.push(fixDiff ? { ...adv, fixDiff } : adv)\n        }\n        collected.push(...advisories)\n        fetchedTimes.push(fetchedAt)\n        await writeCache(cacheFile(dir, item), { fetchedAt, advisories })\n      }\n    } catch (err) {\n      errors.push((err as Error).message)\n      for (const { old } of toRefresh) {\n        if (old) {\n          collected.push(...old.advisories)\n          fetchedTimes.push(old.fetchedAt)\n          stale++\n        }\n      }\n    }\n  }\n\n  const byId = new Map<string, Advisory>()\n  for (const a of collected) byId.set(a.id, a)\n  return {\n    source,\n    snapshot: {\n      asOf: fetchedTimes.sort()[0] ?? new Date(now()).toISOString(),\n      advisories: foldAliases([...byId.values()]),\n    },\n    stale,\n    errors,\n  }\n}\n","import zlib from 'node:zlib'\nimport { Buffer } from 'node:buffer'\nimport semver from 'semver'\nimport { computeFixDiff, fixDiffPair, isPackageSource, type FixDiff } from './fixdiff.js'\nimport type { Advisory, AffectedPackage } from './normalize.js'\nimport { comparePep440, parsePep440 } from './pep440.js'\n\n// Fetching a package's releases and populating `advisory.fixDiff` (advisory-cache.md\n// §4). This is the I/O boundary for the fix-diff, the sibling of source.ts: the\n// pure compute lives in fixdiff.ts (computeFixDiff, fixDiffPair, packageSymbols),\n// and this module does the registry fetch and archive reading around it.\n//\n// Registry metadata and archives are untrusted input. Every request goes to an\n// allowlisted registry host over https and never follows a redirect, so a\n// crafted tarball/file URL in the metadata can't turn a fetch into an SSRF\n// against an internal address. Everything is read in memory and never written to\n// disk (no path from an archive entry reaches the filesystem, so an archive\n// can't escape a directory), every read is byte-capped as it streams so a large\n// response or a compression bomb raises rather than exhausting memory, requests\n// are time-bounded, and every failure falls open: a package that can't be\n// fetched or read gets no fixDiff, and the security card degrades to package\n// grain.\n\nconst NPM_REGISTRY = 'https://registry.npmjs.org'\nconst PYPI = 'https://pypi.org/pypi'\nconst GO_PROXY = 'https://proxy.golang.org'\n\n// The only hosts a fix-diff fetch ever talks to. The package's own public\n// registry is where the dependency came from, so this is no new disclosure\n// (advisory-cache.md §2). Tarball and file URLs that arrive in registry metadata\n// are checked against this before any request, and redirects are refused, so\n// neither can send a request anywhere else.\nconst ALLOWED_HOSTS = new Set(['registry.npmjs.org', 'files.pythonhosted.org', 'pypi.org', 'proxy.golang.org'])\n\nconst FETCH_TIMEOUT_MS = 30_000\nconst MAX_DOWNLOAD = 32 * 1024 * 1024 // archive bytes off the wire\nconst MAX_METADATA = 16 * 1024 * 1024 // registry JSON (abbreviated for npm)\nconst MAX_UNPACKED = 64 * 1024 * 1024 // total decompressed bytes per archive\nconst MAX_FILE = 4 * 1024 * 1024 // per-file source cap; a larger file is skipped\nconst MAX_ENTRIES = 20_000\n\nfunction pep440Cmp(a: string, b: string): number | null {\n  const [x, y] = [parsePep440(a), parsePep440(b)]\n  return x && y ? comparePep440(x, y) : null\n}\nfunction semverCmp(a: string, b: string): number | null {\n  const [x, y] = [semver.parse(a.replace(/^v/, '')), semver.parse(b.replace(/^v/, ''))]\n  return x && y ? semver.compare(x, y) : null\n}\nconst cmpFor = (ecosystem: string) => (ecosystem === 'PyPI' ? pep440Cmp : semverCmp)\n\n// PyPI compares names PEP 503-normalized; npm and Go are case-sensitive.\nconst pep503 = (s: string) => s.replace(/[-_.]+/g, '-').toLowerCase()\nfunction sameName(ecosystem: string, a: string, b: string): boolean {\n  return ecosystem === 'PyPI' ? pep503(a) === pep503(b) : a === b\n}\nconst ensureV = (v: string) => (/^v/.test(v) ? v : `v${v}`)\n// Go module proxy path encoding: an uppercase letter becomes `!` + its lowercase.\nconst goEscape = (s: string) => s.replace(/[A-Z]/g, (c) => `!${c.toLowerCase()}`)\n\n// Every (introduced, fixed) pair an affected package lists, walking each range's\n// events in order so a `fixed` is paired with the `introduced` that opened it.\nfunction fixEvents(pkg: AffectedPackage): Array<{ introduced: string; fixed: string }> {\n  const out: Array<{ introduced: string; fixed: string }> = []\n  for (const r of pkg.ranges) {\n    let introduced = '0'\n    for (const e of r.events) {\n      if (e.introduced !== undefined) introduced = e.introduced\n      else if (e.fixed !== undefined) out.push({ introduced, fixed: e.fixed })\n    }\n  }\n  return out\n}\n\n// The earliest fix across every affected entry for the package: `to` is the\n// first fixed version (advisory-cache.md §4), so a re-affected range doesn't move\n// the diff off the fix that landed first. Several entries are unioned the way the\n// matcher unions `fixedIn`, since folding can leave one package in more than one.\nfunction earliestFix(pkgs: AffectedPackage[], ecosystem: string): { introduced: string; fixed: string } | null {\n  const cmp = cmpFor(ecosystem)\n  const evs = pkgs.flatMap(fixEvents)\n  if (evs.length === 0) return null\n  evs.sort((a, b) => cmp(a.fixed, b.fixed) ?? a.fixed.localeCompare(b.fixed))\n  return evs[0]!\n}\n\n// An https URL on an allowlisted host. Anything else (another host, http, a\n// non-URL) is refused before a request is made, which is what keeps a\n// metadata-supplied tarball or file URL from reaching an internal address.\nfunction allowedUrl(url: string): boolean {\n  let u: URL\n  try {\n    u = new URL(url)\n  } catch {\n    return false\n  }\n  return u.protocol === 'https:' && ALLOWED_HOSTS.has(u.hostname)\n}\n\n// Fetch an allowlisted URL with redirects refused (an allowlisted host can't\n// bounce a request to a host that isn't), and read the body with a hard byte cap\n// applied as it streams, so an oversized response raises before it is buffered.\nasync function fetchCapped(fetchImpl: typeof fetch, url: string, accept: string, max: number): Promise<Uint8Array> {\n  if (!allowedUrl(url)) throw new Error(`disallowed fetch url: ${url}`)\n  const res = await fetchImpl(url, {\n    signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n    redirect: 'error',\n    headers: { accept },\n  })\n  if (!res.ok) throw new Error(`fetch failed: ${res.status}`)\n  const declared = Number(res.headers.get('content-length') ?? '')\n  if (Number.isFinite(declared) && declared > max) throw new Error('response too large')\n  const body = res.body\n  if (!body) {\n    const buf = new Uint8Array(await res.arrayBuffer())\n    if (buf.byteLength > max) throw new Error('response too large')\n    return buf\n  }\n  const reader = body.getReader()\n  const chunks: Uint8Array[] = []\n  let total = 0\n  for (;;) {\n    const { done, value } = await reader.read()\n    if (done) break\n    total += value.byteLength\n    if (total > max) {\n      await reader.cancel()\n      throw new Error('response too large')\n    }\n    chunks.push(value)\n  }\n  return Buffer.concat(chunks)\n}\n\nconst fetchBytes = (fetchImpl: typeof fetch, url: string) => fetchCapped(fetchImpl, url, '*/*', MAX_DOWNLOAD)\n\nasync function fetchJson(fetchImpl: typeof fetch, url: string, accept = 'application/json'): Promise<unknown> {\n  return JSON.parse(Buffer.from(await fetchCapped(fetchImpl, url, accept, MAX_METADATA)).toString('utf8'))\n}\n\n// A tar (already decompressed), read block by block. Regular files only; ustar\n// `prefix` and a PAX `path=` override are honored so long names aren't truncated.\n// Returns raw bytes per entry; the caller strips prefixes and filters to source.\nfunction readTar(tar: Uint8Array): Map<string, Uint8Array> {\n  const out = new Map<string, Uint8Array>()\n  const str = (start: number, len: number) => {\n    const slice = tar.subarray(start, start + len)\n    const nul = slice.indexOf(0)\n    return Buffer.from(nul === -1 ? slice : slice.subarray(0, nul)).toString('utf8')\n  }\n  let off = 0\n  let paxPath: string | null = null\n  while (off + 512 <= tar.length) {\n    // Two consecutive zero blocks end the archive.\n    if (tar.subarray(off, off + 512).every((b) => b === 0)) break\n    const sizeOctal = str(off + 124, 12).trim()\n    const size = parseInt(sizeOctal, 8)\n    if (!Number.isFinite(size) || size < 0) break\n    const typeflag = String.fromCharCode(tar[off + 156] ?? 0)\n    const dataStart = off + 512\n    const dataEnd = dataStart + size\n    if (dataEnd > tar.length) break\n    if (typeflag === 'x' || typeflag === 'g') {\n      // PAX header: records are \"<len> key=value\\n\". Only `path` is taken, and a\n      // global ('g') header is ignored for naming (treated like a per-file one is\n      // never wrong here because we only read `path`).\n      const body = Buffer.from(tar.subarray(dataStart, dataEnd)).toString('utf8')\n      const m = body.match(/\\d+ path=([^\\n]*)\\n/)\n      if (m && typeflag === 'x') paxPath = m[1] ?? null\n    } else if (typeflag === '0' || typeflag === '\\0' || typeflag === '') {\n      const prefix = str(off + 345, 155)\n      const name = str(off, 100)\n      const full = paxPath ?? (prefix ? `${prefix}/${name}` : name)\n      paxPath = null\n      out.set(full, tar.subarray(dataStart, dataEnd))\n      if (out.size > MAX_ENTRIES) break\n    } else {\n      paxPath = null\n    }\n    off = dataStart + Math.ceil(size / 512) * 512\n  }\n  return out\n}\n\nfunction gunzip(buf: Uint8Array): Uint8Array {\n  return zlib.gunzipSync(buf, { maxOutputLength: MAX_UNPACKED })\n}\n\n// A zip, read from its central directory (the authority on each entry's name,\n// method and compressed size). Entries are inflated in memory with a hard output\n// cap, so a crafted entry raises rather than exhausting memory. zip64 and\n// encrypted entries are not handled: such an archive raises and falls open.\nfunction readZip(zip: Uint8Array): Map<string, Uint8Array> {\n  const out = new Map<string, Uint8Array>()\n  const dv = new DataView(zip.buffer, zip.byteOffset, zip.byteLength)\n  // End of central directory: scan back for its signature.\n  let eocd = -1\n  for (let i = zip.length - 22; i >= 0 && i >= zip.length - 22 - 0x10000; i--) {\n    if (dv.getUint32(i, true) === 0x06054b50) {\n      eocd = i\n      break\n    }\n  }\n  if (eocd < 0) throw new Error('zip: no end-of-central-directory')\n  const count = dv.getUint16(eocd + 10, true)\n  let p = dv.getUint32(eocd + 16, true) // central directory offset\n  if (count === 0xffff || p === 0xffffffff) throw new Error('zip: zip64 unsupported')\n  let total = 0\n  for (let i = 0; i < count; i++) {\n    if (p + 46 > zip.length || dv.getUint32(p, true) !== 0x02014b50) throw new Error('zip: bad central record')\n    const method = dv.getUint16(p + 10, true)\n    const compSize = dv.getUint32(p + 20, true)\n    const nameLen = dv.getUint16(p + 28, true)\n    const extraLen = dv.getUint16(p + 30, true)\n    const commentLen = dv.getUint16(p + 32, true)\n    const localOff = dv.getUint32(p + 42, true)\n    const name = Buffer.from(zip.subarray(p + 46, p + 46 + nameLen)).toString('utf8')\n    p += 46 + nameLen + extraLen + commentLen\n    if (name.endsWith('/')) continue // directory entry\n    if (dv.getUint32(localOff, true) !== 0x04034b50) throw new Error('zip: bad local header')\n    const lNameLen = dv.getUint16(localOff + 26, true)\n    const lExtraLen = dv.getUint16(localOff + 28, true)\n    const dataStart = localOff + 30 + lNameLen + lExtraLen\n    const comp = zip.subarray(dataStart, dataStart + compSize)\n    let data: Uint8Array\n    if (method === 0) data = comp\n    else if (method === 8) data = zlib.inflateRawSync(comp, { maxOutputLength: MAX_UNPACKED - total })\n    else throw new Error(`zip: unsupported method ${method}`)\n    total += data.byteLength\n    if (total > MAX_UNPACKED) throw new Error('zip: unpacked too large')\n    out.set(name, data)\n    if (out.size > MAX_ENTRIES) throw new Error('zip: too many entries')\n  }\n  return out\n}\n\n// Decode entries to source, after stripping an archive's path prefix to the\n// package-relative paths the graph uses (dependency-symbols extract.ts). `strip`\n// returns the package-relative path, or null to drop the entry.\nfunction toSource(raw: Map<string, Uint8Array>, strip: (p: string) => string | null): Map<string, string> {\n  const out = new Map<string, string>()\n  for (const [rawPath, bytes] of raw) {\n    const rel = strip(rawPath.replace(/\\\\/g, '/'))\n    // A `..` segment or an absolute path never names a package's own source;\n    // drop it rather than let it become a key (these are map keys, never written,\n    // but a traversal-shaped path has no business in the diff).\n    if (rel === null || rel === '' || rel.startsWith('/') || rel.split('/').includes('..')) continue\n    if (!isPackageSource(rel)) continue\n    if (bytes.byteLength > MAX_FILE) continue\n    out.set(rel, Buffer.from(bytes).toString('utf8'))\n  }\n  return out\n}\n\n// npm tarballs root every entry at `package/`.\nconst npmStrip = (p: string) => (p.startsWith('package/') ? p.slice('package/'.length) : p)\n// A wheel is already import-rooted (`jinja2/filters.py`); its `.dist-info` and\n// `.data` entries carry no source extension, so isPackageSource drops them.\nconst wheelStrip = (p: string) => p\n// An sdist roots at `<name>-<version>/`, often over a `src/` layout. Strip the\n// single top directory, then a leading `src/`, to reach the import root.\nconst sdistStrip = (p: string): string | null => {\n  const i = p.indexOf('/')\n  if (i < 0) return null\n  const rest = p.slice(i + 1)\n  return rest.startsWith('src/') ? rest.slice(4) : rest\n}\n// A Go module zip roots at `<module>@<version>/`; the module path holds slashes,\n// so strip everything up to and including the first `@<version>/`.\nconst goStrip = (version: string) => (p: string): string | null => {\n  const marker = `@${version}/`\n  const idx = p.indexOf(marker)\n  return idx < 0 ? null : p.slice(idx + marker.length)\n}\n\ninterface ReleaseSource {\n  versions: string[]\n  // Package-relative source files for one version; throws on any fetch or read\n  // failure, which buildFixDiff turns into a fail-open (no fixDiff).\n  fetchSource: (version: string) => Promise<Map<string, string>>\n}\n\nasync function npmSource(name: string, fetchImpl: typeof fetch): Promise<ReleaseSource> {\n  // Abbreviated metadata: a fraction of a full packument (which runs to tens of\n  // MB for a big package) and it still carries each version's dist.tarball.\n  const doc = (await fetchJson(\n    fetchImpl,\n    `${NPM_REGISTRY}/${name.replace(/\\//g, '%2f')}`,\n    'application/vnd.npm.install-v1+json',\n  )) as {\n    versions?: Record<string, { dist?: { tarball?: string } }>\n  }\n  const versions = Object.keys(doc.versions ?? {})\n  return {\n    versions,\n    fetchSource: async (version) => {\n      const tarball = doc.versions?.[version]?.dist?.tarball\n      if (!tarball) throw new Error(`npm: no tarball for ${name}@${version}`)\n      return toSource(readTar(gunzip(await fetchBytes(fetchImpl, tarball))), npmStrip)\n    },\n  }\n}\n\nasync function pypiSource(name: string, fetchImpl: typeof fetch): Promise<ReleaseSource> {\n  const doc = (await fetchJson(fetchImpl, `${PYPI}/${encodeURIComponent(name)}/json`)) as {\n    releases?: Record<string, Array<{ filename?: string; url?: string; packagetype?: string; yanked?: boolean }>>\n  }\n  const releases = doc.releases ?? {}\n  return {\n    versions: Object.keys(releases),\n    fetchSource: async (version) => {\n      const files = (releases[version] ?? []).filter((f) => f.url && !f.yanked)\n      const wheel = files.find((f) => f.packagetype === 'bdist_wheel' || f.filename?.endsWith('.whl'))\n      if (wheel?.url) return toSource(readZip(await fetchBytes(fetchImpl, wheel.url)), wheelStrip)\n      const sdist = files.find((f) => f.packagetype === 'sdist' || /\\.(tar\\.gz|tgz|zip)$/.test(f.filename ?? ''))\n      if (!sdist?.url) throw new Error(`pypi: no distribution for ${name} ${version}`)\n      const bytes = await fetchBytes(fetchImpl, sdist.url)\n      if (sdist.filename?.endsWith('.zip')) return toSource(readZip(bytes), sdistStrip)\n      return toSource(readTar(gunzip(bytes)), sdistStrip)\n    },\n  }\n}\n\nasync function goSource(name: string, fetchImpl: typeof fetch): Promise<ReleaseSource> {\n  const esc = goEscape(name)\n  // Capped like the archives: the list is text, not a decompress path, but it's\n  // still untrusted, so no unbounded read anywhere in this module.\n  const listBytes = await fetchBytes(fetchImpl, `${GO_PROXY}/${esc}/@v/list`)\n  const versions = Buffer.from(listBytes).toString('utf8').split('\\n').map((v) => v.trim()).filter(Boolean)\n  return {\n    versions,\n    fetchSource: async (version) => {\n      const bytes = await fetchBytes(fetchImpl, `${GO_PROXY}/${esc}/@v/${goEscape(version)}.zip`)\n      return toSource(readZip(bytes), goStrip(version))\n    },\n  }\n}\n\nfunction releaseSource(ecosystem: string, name: string, fetchImpl: typeof fetch): Promise<ReleaseSource> | null {\n  if (ecosystem === 'npm') return npmSource(name, fetchImpl)\n  if (ecosystem === 'PyPI') return pypiSource(name, fetchImpl)\n  if (ecosystem === 'Go') return goSource(name, fetchImpl)\n  return null\n}\n\n/**\n * The fix-diff for one advisory on one package: the symbols its first fixed\n * release changed (advisory-cache.md §4), computed with NEAT's own extraction\n * (computeFixDiff) over the release before the fix and the fix itself. Returns\n * undefined, never throws, when there's no fixed version, no release pair to\n * diff, an unsupported ecosystem, or any fetch or archive failure. The caller\n * then leaves the advisory without a fixDiff and the card falls back to package\n * grain.\n */\nexport async function buildFixDiff(\n  advisory: Advisory,\n  pkg: { ecosystem: string; name: string },\n  opts: { fetchImpl?: typeof fetch } = {},\n): Promise<FixDiff | undefined> {\n  try {\n    const fetchImpl = opts.fetchImpl ?? fetch\n    const affected = advisory.affected.filter((p) => p.ecosystem === pkg.ecosystem && sameName(pkg.ecosystem, p.name, pkg.name))\n    if (affected.length === 0) return undefined\n    const fix = earliestFix(affected, pkg.ecosystem)\n    if (!fix) return undefined\n    const sourceP = releaseSource(pkg.ecosystem, pkg.name, fetchImpl)\n    if (!sourceP) return undefined\n    const source = await sourceP\n    const fixed = pkg.ecosystem === 'Go' ? ensureV(fix.fixed) : fix.fixed\n    const pair = fixDiffPair(pkg.ecosystem, source.versions, fixed, fix.introduced)\n    if (!pair) return undefined\n    const [from, to] = await Promise.all([source.fetchSource(pair.from), source.fetchSource(pair.to)])\n    if (from.size === 0 && to.size === 0) return undefined\n    const text = `${advisory.summary}\\n${advisory.details}`\n    return computeFixDiff({ version: pair.from, files: from }, { version: pair.to, files: to }, text)\n  } catch {\n    return undefined\n  }\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport semver from 'semver'\nimport {\n  SYMBOL_GRAMMAR_BY_EXT,\n  collectGoSymbolDefs,\n  collectPythonSymbolDefs,\n  collectSymbolDefs,\n  disambiguate,\n  parseSource,\n  type SymbolDef,\n} from '../extract/symbols.js'\nimport { comparePep440, parsePep440 } from './pep440.js'\n\n// The fix-diff (ADR-274, advisory-cache.md §4): what the release that fixed an\n// advisory changed, at symbol grain, computed with NEAT's own symbol extraction\n// (ADR-158) over the last affected and first fixed releases. This module is\n// pure: it takes the two releases' source files in memory and returns the set.\n// Fetching releases is the registry/cache module's job, not this one's.\n\nexport type ChangeStatus = 'modified' | 'new' | 'removed'\n\nexport interface ChangedSymbol {\n  // The symbol's qualname, as NEAT's extractor names it (`Parser.parse`, `template`).\n  symbol: string\n  // Package-relative path of the file it's in.\n  file: string\n  kind: string\n  status: ChangeStatus\n  // The symbol's name appears in the advisory's summary or details. A ranking\n  // hint only, never a filter (advisory-cache.md §4).\n  namedInAdvisory: boolean\n}\n\nexport interface FixDiff {\n  from: string\n  to: string\n  changed: ChangedSymbol[]\n}\n\n// What counts as the package's own source: no tests, examples, docs, vendored\n// copies or build output. Those either never run in a consumer or duplicate the\n// real source, and would inflate the changed set with noise.\nconst SKIP_DIRS = new Set([\n  'test', 'tests', '__tests__', 'testdata', 'testing', 'example', 'examples', '_examples', 'doc', 'docs',\n  'benchmark', 'benchmarks', 'bench', 'vendor', 'node_modules', 'dist', 'fixtures', '.github',\n])\nconst SOURCE_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.py', '.go'])\n\nexport function isPackageSource(relPath: string): boolean {\n  const parts = relPath.split('/')\n  if (parts.slice(0, -1).some((d) => SKIP_DIRS.has(d))) return false\n  const base = parts[parts.length - 1] ?? ''\n  if (!SOURCE_EXTS.has(path.extname(base))) return false\n  if (base.endsWith('.d.ts') || /\\.min\\.js$/.test(base) || /\\.bundle\\.js$/.test(base)) return false\n  if (/_test\\.go$/.test(base) || /\\.(test|spec)\\.[cm]?[jt]sx?$/.test(base)) return false\n  if (/^test_.*\\.py$/.test(base) || /_test\\.py$/.test(base) || base === 'conftest.py') return false\n  return true\n}\n\ninterface SymbolBody {\n  file: string\n  qualname: string\n  kind: string\n  // The symbol's own tokens: leaves inside its span that don't belong to a nested\n  // symbol, without comments or type annotations. Joined, so equality is a string\n  // compare and formatting-only churn doesn't count as a change.\n  tokens: string\n}\n\nconst parsers = new Map<string, Parser>()\nfunction parserFor(ext: string): Parser | null {\n  const grammar = SYMBOL_GRAMMAR_BY_EXT[ext]\n  if (!grammar) return null\n  let p = parsers.get(ext)\n  if (!p) {\n    p = new Parser()\n    p.setLanguage(grammar)\n    parsers.set(ext, p)\n  }\n  return p\n}\n\nfunction collect(ext: string, root: Parser.SyntaxNode): SymbolDef[] {\n  if (ext === '.py') return collectPythonSymbolDefs(root)\n  if (ext === '.go') return collectGoSymbolDefs(root)\n  return collectSymbolDefs(root)\n}\n\nfunction excluded(ext: string, n: Parser.SyntaxNode): boolean {\n  if (n.type === 'comment' || n.type === 'html_comment') return true\n  if ((ext === '.ts' || ext === '.tsx') && n.type === 'type_annotation') return true\n  if (ext === '.py') {\n    if (n.type === 'type') return true\n    // A docstring is a bare string statement: an expression_statement whose sole\n    // child is a string literal. Python's docstring is the leading such statement\n    // of a module/class/function body; a bare string elsewhere is inert, so\n    // excluding all of them never hides a behavioral change and keeps the diff off\n    // docstring churn (advisory-cache.md §4). JS/Go docstrings are comments,\n    // already handled above.\n    if (n.type === 'expression_statement' && n.namedChildCount === 1) {\n      const child = n.namedChild(0)!.type\n      if (child === 'string' || child === 'concatenated_string') return true\n    }\n  }\n  return false\n}\n\nfunction symbolsOfFile(file: string, source: string): SymbolBody[] {\n  const ext = path.extname(file)\n  const parser = parserFor(ext)\n  if (!parser) return []\n  const root = parseSource(parser, source).rootNode\n  const defs = disambiguate(collect(ext, root))\n  const bySpan = new Map<string, number>()\n  defs.forEach(({ def }, i) => bySpan.set(`${def.startIndex}:${def.endIndex}`, i))\n  const tokens: string[][] = defs.map(() => [])\n  // Each leaf goes to the innermost symbol whose span contains it.\n  const walk = (n: Parser.SyntaxNode, owner: number) => {\n    if (excluded(ext, n)) return\n    const own = bySpan.get(`${n.startIndex}:${n.endIndex}`)\n    const cur = own ?? owner\n    if (n.childCount === 0) {\n      if (cur >= 0) tokens[cur]!.push(n.text)\n      return\n    }\n    for (let i = 0; i < n.childCount; i++) walk(n.child(i)!, cur)\n  }\n  walk(root, -1)\n  return defs.map(({ def, disambiguator }, i) => ({\n    file,\n    qualname: disambiguator !== undefined ? `${def.qualname}~${disambiguator}` : def.qualname,\n    kind: def.kind,\n    tokens: tokens[i]!.join('\\u0001'),\n  }))\n}\n\nfunction symbolsOf(files: Map<string, string>): Map<string, SymbolBody> {\n  const out = new Map<string, SymbolBody>()\n  for (const [file, source] of [...files].sort(([a], [b]) => a.localeCompare(b))) {\n    if (!isPackageSource(file)) continue\n    for (const s of symbolsOfFile(file, source)) out.set(`${s.file}#${s.qualname}`, s)\n  }\n  return out\n}\n\n/** One symbol of a package's own source, as both the fix-diff and the graph see it. */\nexport interface PackageSymbol {\n  file: string\n  qualname: string\n  disambiguator?: number\n  kind: SymbolDef['kind']\n  startLine: number\n  endLine: number\n}\n\n/**\n * Every symbol in a package's own source (`isPackageSource`), from the same\n * parser, collector and disambiguation the fix-diff runs, so a changed symbol and\n * the graph's dependency SymbolNode for it name the same thing. Pure and\n * deterministic: files in path order, symbols in source order.\n */\nexport function packageSymbols(files: Map<string, string>): PackageSymbol[] {\n  const out: PackageSymbol[] = []\n  for (const [file, source] of [...files].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {\n    if (!isPackageSource(file)) continue\n    const ext = path.extname(file)\n    const parser = parserFor(ext)\n    if (!parser) continue\n    for (const { def, disambiguator } of disambiguate(collect(ext, parseSource(parser, source).rootNode))) {\n      out.push({\n        file,\n        qualname: def.qualname,\n        ...(disambiguator !== undefined ? { disambiguator } : {}),\n        kind: def.kind,\n        startLine: def.startLine,\n        endLine: def.endLine,\n      })\n    }\n  }\n  return out\n}\n\nfunction namedIn(qualname: string, text: string): boolean {\n  const name = qualname.replace(/~\\d+$/, '').split('.').pop() ?? qualname\n  if (name.length < 3) return false\n  return new RegExp(`(^|[^A-Za-z0-9_])${name.replace(/\\$/g, '\\\\$')}([^A-Za-z0-9_]|$)`).test(text)\n}\n\n/**\n * The symbols a fix release changed: modified (own tokens differ), new in `to`,\n * or removed in `to`. Class-kind symbols are left out, because their methods\n * carry the change. Deterministic: the same two file sets always give the same\n * result, in the same order.\n */\nexport function computeFixDiff(\n  from: { version: string; files: Map<string, string> },\n  to: { version: string; files: Map<string, string> },\n  advisoryText: string,\n): FixDiff {\n  const [a, b] = [symbolsOf(from.files), symbolsOf(to.files)]\n  const changed: ChangedSymbol[] = []\n  const push = (s: SymbolBody, status: ChangeStatus) => {\n    if (s.kind === 'class') return\n    changed.push({\n      symbol: s.qualname,\n      file: s.file,\n      kind: s.kind,\n      status,\n      namedInAdvisory: namedIn(s.qualname, advisoryText),\n    })\n  }\n  for (const [key, s] of b) {\n    const old = a.get(key)\n    if (!old) push(s, 'new')\n    else if (old.tokens !== s.tokens) push(s, 'modified')\n  }\n  for (const [key, s] of a) if (!b.has(key)) push(s, 'removed')\n  changed.sort(\n    (x, y) => x.file.localeCompare(y.file) || x.symbol.localeCompare(y.symbol) || x.status.localeCompare(y.status),\n  )\n  return { from: from.version, to: to.version, changed }\n}\n\n/**\n * The release pair to diff (advisory-cache.md §4): `to` is the first fixed\n * version, `from` is the newest stable release below it. Returns null when no\n * such release exists, or when it would fall below the range's `introduced`\n * bound (the fix landed in the first affected release, so there's nothing\n * unaffected to diff against).\n */\nexport function fixDiffPair(\n  ecosystem: string,\n  published: string[],\n  fixed: string,\n  introduced: string,\n): { from: string; to: string } | null {\n  const cmp = ecosystem === 'PyPI' ? pep440Cmp : semverCmp\n  const stable = ecosystem === 'PyPI' ? isStablePep440 : isStableSemver\n  const below = published.filter((v) => stable(v) && cmp(v, fixed) !== null && cmp(v, fixed)! < 0)\n  below.sort((x, y) => cmp(x, y) ?? 0)\n  const from = below[below.length - 1]\n  if (!from) return null\n  if (introduced !== '0' && (cmp(from, introduced) ?? -1) < 0) return null\n  return { from, to: fixed }\n}\n\nfunction semverCmp(a: string, b: string): number | null {\n  const [x, y] = [semver.parse(a.replace(/^v/, '')), semver.parse(b.replace(/^v/, ''))]\n  return x && y ? semver.compare(x, y) : null\n}\nfunction isStableSemver(v: string): boolean {\n  const p = semver.parse(v.replace(/^v/, ''))\n  return !!p && p.prerelease.length === 0\n}\nfunction pep440Cmp(a: string, b: string): number | null {\n  const [x, y] = [parsePep440(a), parsePep440(b)]\n  return x && y ? comparePep440(x, y) : null\n}\nfunction isStablePep440(v: string): boolean {\n  const p = parsePep440(v)\n  return !!p && p.pre === null && p.dev === null\n}\n","import path from 'node:path'\nimport { createRequire } from 'node:module'\nimport Parser from 'tree-sitter'\nimport JavaScript from 'tree-sitter-javascript'\nimport TypeScript from 'tree-sitter-typescript'\nimport Python from 'tree-sitter-python'\nimport Go from 'tree-sitter-go'\nimport Ruby from 'tree-sitter-ruby'\nimport Php from 'tree-sitter-php'\nimport CSharp from 'tree-sitter-c-sharp'\nimport Java from 'tree-sitter-java'\nimport Rust from 'tree-sitter-rust'\nimport Cpp from 'tree-sitter-cpp'\nimport type { GraphEdge, SymbolKind, SymbolNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  symbolId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport type { DiscoveredService } from './shared.js'\nimport { recordExtractionError } from './errors.js'\nimport { ensureFileNode, loadSourceFiles, snippet, toPosix } from './calls/shared.js'\n\n// Static symbol-node extraction (ADR-158 wired JS/TS; ADR-192 added Python and\n// Go; ADR-193 added Ruby; ADR-195 added PHP; ADR-196 added C#/.NET; ADR-197 added Java;\n// ADR-199 added Kotlin; ADR-201 added Rust; ADR-202 added C++). Parses each source file with the grammar that understands it and mints a\n// SymbolNode per function / method / constructor / class *definition*, owned by\n// its file through a `file ──CONTAINS──▶ symbol` edge — the same containment\n// spine files use under services (file-awareness.md §2), one level deeper.\n// Static-first: a symbol exists in the inventory whether or not runtime ever\n// exercised it, and it carries its `{ startLine, endLine }` definition span,\n// which is the fusion key ingest joins a span's `code.line` against to land an\n// OBSERVED edge on the calling symbol (observed-first edges, ingest.ts). The node\n// is language-neutral — `symbolId` carries no language token — so the per-language\n// walker below is the only adapter, and a Python or Go symbol fuses with an\n// observed span exactly as a JS/TS one does: line-in-span primary, `code.function`\n// (the qualname's terminal name) the tiebreaker. The span alone earns the node;\n// fusion also needs the observed span to carry the `code.*` anchor, which is a\n// property of the instrumentation, not of this extractor (ADR-192 consequences).\n//\n// Scope is definitions only — no CALLS/INHERITS symbol edges (that stays Phase 2 /\n// symbol-edges.ts, JS/TS). Each file is parsed with the grammar that understands\n// it: `.ts` / `.tsx` through tree-sitter-typescript, `.js` / `.jsx` / `.mjs` /\n// `.cjs` through tree-sitter-javascript, `.py` through tree-sitter-python, `.go`\n// through tree-sitter-go, `.rb` through tree-sitter-ruby, `.php` through\n// tree-sitter-php (the `php_only` variant, matching extract/routes.ts and\n// calls/eloquent.ts). Those grammars extract/routes.ts and the call producers\n// already load, so they added no dependency; C#, Java, Kotlin, and Rust are the\n// symbol-grain languages with no route / call producer yet, so `.cs` through\n// tree-sitter-c-sharp, `.java` through tree-sitter-java, `.kt` through\n// tree-sitter-kotlin, `.rs` through tree-sitter-rust, and the C++ extensions through\n// tree-sitter-cpp are the new grammar dependencies (each pinned at the ABI-14\n// ceiling, see SYMBOL_GRAMMAR_BY_EXT below).\n// The JS grammar cannot parse\n// TypeScript type annotations — it produces ERROR nodes that swallow most\n// definitions (an all-`.ts` core file yields 4 of 27 functions under the JS\n// grammar, 27 of 27 under the TS one) — and symbol extraction, unlike the string /\n// route matchers that survive a partial parse, needs a correct AST, so the grammar\n// is chosen per extension. `collectSymbolDefsForExt` dispatches to the JS/TS,\n// Python, Go, Ruby, PHP, C#, Java, Kotlin, or Rust walker on the extension. Evidence carries the real `file:line`,\n// never fabricated (file-awareness.md §6).\n\nconst PARSE_CHUNK = 16384\n\n// The grammar for the JS/TS extensions NEAT symbol-extracts. tree-sitter-\n// typescript is a superset grammar sharing the same definition node types\n// (function_declaration / class_declaration / method_definition /\n// variable_declarator), so `collectSymbolDefs` walks TS and JS trees identically.\n// This map stays JS/TS-only because the other AST producers that import it\n// (symbol-edges.ts, actions.ts, zod-shapes.ts, calls/drizzle.ts,\n// calls/firestore.ts) are JS/TS-scoped; symbol extraction extends the set to\n// Python, Go, Ruby, and PHP through `SYMBOL_GRAMMAR_BY_EXT` below without pulling\n// those producers onto languages they don't parse.\nexport const GRAMMAR_BY_EXT: Record<string, typeof JavaScript> = {\n  '.ts': TypeScript.typescript,\n  '.tsx': TypeScript.tsx,\n  '.js': JavaScript,\n  '.jsx': JavaScript,\n  '.mjs': JavaScript,\n  '.cjs': JavaScript,\n}\n\n// Symbol extraction alone reaches Python, Go, Ruby, PHP, C#, Java, Kotlin, and Rust\n// (ADR-192, ADR-193, ADR-195, ADR-196, ADR-197, ADR-199, ADR-201): `.py` →\n// tree-sitter-python, `.go` → tree-sitter-go, `.rb` → tree-sitter-ruby, `.php` →\n// tree-sitter-php's `php_only` variant (the same one extract/routes.ts and\n// calls/eloquent.ts parse Laravel with), `.cs` → tree-sitter-c-sharp, `.java` →\n// tree-sitter-java, `.kt` → tree-sitter-kotlin, `.rs` → tree-sitter-rust, layered\n// over the JS/TS set so the shared `GRAMMAR_BY_EXT` its sibling producers import\n// stays untouched. C#, Java, Kotlin, and Rust are the symbol-grain languages with no\n// route / call producer yet, so each brings its own grammar dependency pinned at the\n// ABI-14 ceiling: tree-sitter-c-sharp at 0.21.3 (its 0.23 line jumps to ABI-15 + an\n// ESM-top-level-await binding the CJS extractor can't `require()`), tree-sitter-java\n// at 0.21.0, tree-sitter-kotlin at 0.3.8, and tree-sitter-rust at 0.21.0. The Kotlin\n// grammar is the fwcd community grammar, whose versioning tracks its own line rather\n// than the official grammars, so its ABI was checked empirically rather than inferred\n// from the sibling pins: 0.3.8 generates a `LANGUAGE_VERSION 14` parser and ships a\n// `require()`-able node-addon-api binding — it was loaded against the pinned\n// tree-sitter@^0.21 runtime and parsed a `.kt` file with zero ERROR nodes before the\n// walker was written (ADR-199), the same ABI-14 discipline that pins tree-sitter-ruby\n// at 0.21.0 and tree-sitter-php at 0.22.8. tree-sitter-rust jumps from its lone\n// 0.21.0 release straight to the 0.23 (ABI-15, ESM-top-level-await) line with no\n// 0.22.x between, so 0.21.0 is the one release that both generates a\n// `LANGUAGE_VERSION 14` parser and `require()`s under the pinned runtime — verified\n// by loading it and parsing a `.rs` file with zero ERROR nodes before the walker was\n// written (ADR-201), the same exact-pin discipline the sibling grammars follow.\n// tree-sitter-cpp is pinned at 0.22.3 (ADR-202): unlike the sibling grammars whose\n// next line jumps to an ESM-top-level-await binding, tree-sitter-cpp keeps a\n// `require()`-able CJS `node-gyp-build` binding even on its 0.23.x line, but 0.22.3 is\n// chosen as the newest 0.22.x for parity with the tree-sitter-php@0.22.8 pin and to\n// stay on one ABI-14 generation — it generates a `LANGUAGE_VERSION 14` parser and,\n// loaded against the pinned runtime, parsed a `.cpp` file with zero ERROR nodes\n// (resolving function_definition / class_specifier / struct_specifier /\n// namespace_definition / template_declaration) before the walker was written. Only\n// the unambiguous C++ extensions map to it — `.h` / `.c` stay out (shared with C).\n// tree-sitter-kotlin ships no prebuilt binary for any platform, so installing it\n// compiles C. Where there's no compiler (Windows without Visual Studio's C++\n// tools, slim Linux images) that build fails, and as a hard dependency it failed\n// `npm i neat.is` outright. It is an optional dependency instead: when it isn't\n// there, .kt files keep their file grain, symbol grain skips them, and the run\n// says so once (KOTLIN_UNAVAILABLE) rather than dropping them silently.\nfunction loadOptionalGrammar(name: string): typeof JavaScript | undefined {\n  try {\n    return createRequire(import.meta.url)(name) as typeof JavaScript\n  } catch {\n    return undefined\n  }\n}\nconst Kotlin = loadOptionalGrammar('tree-sitter-kotlin')\nexport const KOTLIN_UNAVAILABLE =\n  'tree-sitter-kotlin is not installed (it has no prebuilt binary, and building it needs a C compiler); Kotlin symbols were skipped'\n\nexport const SYMBOL_GRAMMAR_BY_EXT: Record<string, typeof JavaScript> = {\n  ...GRAMMAR_BY_EXT,\n  '.py': Python,\n  '.go': Go,\n  '.rb': Ruby,\n  '.php': Php.php_only,\n  '.cs': CSharp,\n  '.java': Java,\n  ...(Kotlin ? { '.kt': Kotlin } : {}),\n  '.rs': Rust,\n  // C++ (ADR-202) — only the UNAMBIGUOUS extensions. `.cpp` / `.cc` / `.cxx` /\n  // `.c++` are implementation files; `.hpp` / `.hh` / `.hxx` / `.h++` are C++-only\n  // headers. `.h` and `.c` are deliberately absent: they are shared with C (a\n  // language NEAT does not add), and this map is global — the symbol grain\n  // dispatches on extension, not on the owning service's language — so claiming\n  // `.h` would parse every pure-C header in any repo with the C++ grammar and\n  // mislabel it. The otel-demo `currency` target's executable code lives in a\n  // `.cpp`, so nothing is lost.\n  '.cpp': Cpp,\n  '.cc': Cpp,\n  '.cxx': Cpp,\n  '.c++': Cpp,\n  '.hpp': Cpp,\n  '.hh': Cpp,\n  '.hxx': Cpp,\n  '.h++': Cpp,\n}\n\nexport function parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\n// A parsed definition, pre-identity. `qualname` is the source-declared name\n// (`OrderService.create`, `merge`); `node` carries the definition span.\nexport interface SymbolDef {\n  kind: SymbolKind\n  qualname: string\n  startLine: number\n  endLine: number\n  startIndex: number\n  endIndex: number\n}\n\nfunction methodName(node: Parser.SyntaxNode): string | null {\n  const name = node.childForFieldName('name')\n  return name ? name.text : null\n}\n\nconst FUNCTION_VALUE_TYPES = new Set(['arrow_function', 'function', 'function_expression', 'generator_function'])\n\n// Bare-identifier callees whose result is a value, not the function they are handed\n// (`const v = useMemo(() => …)`, `const t = setTimeout(() => …)`), so a binding to\n// their call is not a function definition. A short, closed list: it only ever drops.\nconst VALUE_RETURNING_CALLEES = new Set([\n  'useMemo', 'useState', 'useReducer', 'useEffect', 'useLayoutEffect', 'useRef', 'useSyncExternalStore',\n  'computed', 'watch', 'watchEffect', 'ref', 'reactive', 'createMemo', 'createSignal', 'createEffect',\n  'setTimeout', 'setInterval', 'setImmediate', 'queueMicrotask', 'requestAnimationFrame',\n])\n\n// The function a call wraps, when the call is a function-returning wrapper:\n// `flatRest(function (…) {})`, `memoize(debounce(() => …))`, `asyncHandler(async (req) => …)`.\n// The callee must be a bare identifier and the function its first argument, possibly\n// through nested wrappers. A method call (`items.map(x => …)`, a schema builder's `.refine(…)`)\n// returns whatever the method returns, so it is never read as a definition.\nfunction wrappedFunction(call: Parser.SyntaxNode, depth = 0): Parser.SyntaxNode | null {\n  if (depth > 3 || call.type !== 'call_expression') return null\n  const callee = call.childForFieldName('function')\n  if (!callee || callee.type !== 'identifier' || VALUE_RETURNING_CALLEES.has(callee.text)) return null\n  const first = call.childForFieldName('arguments')?.namedChild(0)\n  if (!first) return null\n  if (FUNCTION_VALUE_TYPES.has(first.type)) return first\n  return wrappedFunction(first, depth + 1)\n}\n\n// The source text of an assignment target that names one function: an identifier\n// (`handler = function …`) or a dotted member chain over identifiers / `this`\n// (`res.location`, `exports.handler`, `module.exports.helper`, `Foo.prototype.bar`).\n// A computed member (`handlers[name] = …`) names nothing fixed, so it returns null.\nfunction assignmentTarget(node: Parser.SyntaxNode): string | null {\n  if (node.type === 'identifier') return node.text\n  if (node.type !== 'member_expression') return null\n  const object = node.childForFieldName('object')\n  const property = node.childForFieldName('property')\n  if (!object || !property || property.type !== 'property_identifier') return null\n  if (object.type === 'this') return `this.${property.text}`\n  const base = assignmentTarget(object)\n  return base ? `${base}.${property.text}` : null\n}\n\n// Walk the AST once, emitting one SymbolDef per definition. A class carries its\n// method context so a method's qualname is `Class.method`; a plain (including\n// nested) function keeps its bare declared name. Anonymous definitions with no\n// declared name are skipped rather than given a fabricated one (§6).\n//\n// Beyond declarations, `const` arrows and class members, JS defines functions in\n// three more shapes, each named by what the source binds it to:\n//   - by assignment: `res.location = function location() {}` → `res.location`, the\n//     target's text. Assigning the whole module (`module.exports = function main() {}`)\n//     names the module rather than the function, so the function's own name wins\n//     there when it has one.\n//   - wrapped in a call: `var pick = flatRest(function () {})` → `pick`, the binding.\n//   - as a named callback: `router.get('/x', function namedHandler() {})` →\n//     `namedHandler`. An anonymous callback has no name and stays unminted (§6).\n// Ids are kept stable: these shapes never take a qualname a declaration, arrow,\n// method or class in the same file already holds, since sharing it would add an\n// ordinal to that existing symbol's id (identity.md, ADR-158). Such a collision\n// is left unminted instead.\nexport function collectSymbolDefs(root: Parser.SyntaxNode): SymbolDef[] {\n  const out: (SymbolDef & { bound?: true })[] = []\n  // Function nodes already named by a binding or assignment, so the callback rule\n  // doesn't mint them a second time under their own name.\n  const claimed = new Set<number>()\n\n  const push = (kind: SymbolKind, qualname: string, node: Parser.SyntaxNode, bound?: true): void => {\n    out.push({\n      kind,\n      qualname,\n      startLine: node.startPosition.row + 1,\n      endLine: node.endPosition.row + 1,\n      startIndex: node.startIndex,\n      endIndex: node.endIndex,\n      ...(bound ? { bound } : {}),\n    })\n  }\n\n  const visit = (node: Parser.SyntaxNode, classCtx: string | undefined): void => {\n    switch (node.type) {\n      case 'function_declaration':\n      case 'generator_function_declaration': {\n        const name = node.childForFieldName('name')?.text\n        if (name) push('function', name, node)\n        break\n      }\n      case 'class_declaration':\n      case 'abstract_class_declaration':\n      case 'class': {\n        // `abstract class Foo` parses as its own node type in the TS grammar,\n        // not `class_declaration` — miss it and every INHERITS/IMPLEMENTS to an\n        // abstract base (the most common heritage target) has no symbol to land\n        // on. It carries the same `name` / `body` fields, so it mints identically.\n        const name = node.childForFieldName('name')?.text\n        if (name) push('class', name, node)\n        const body = node.childForFieldName('body')\n        if (body) {\n          for (let i = 0; i < body.namedChildCount; i++) {\n            const child = body.namedChild(i)\n            if (child) visit(child, name ?? classCtx)\n          }\n        }\n        // Class children were walked with the class context above; skip the\n        // generic recurse so its body isn't visited twice.\n        return\n      }\n      case 'method_definition': {\n        const name = methodName(node)\n        if (name) {\n          const kind: SymbolKind = name === 'constructor' ? 'constructor' : 'method'\n          push(kind, classCtx ? `${classCtx}.${name}` : name, node)\n        }\n        break\n      }\n      case 'variable_declarator': {\n        // `const foo = () => {}` / `const foo = function () {}` — the common\n        // arrow/function-expression definition form. Only a plain identifier\n        // name yields a symbol; a destructuring pattern names no single symbol.\n        const value = node.childForFieldName('value')\n        const nameNode = node.childForFieldName('name')\n        if (value && nameNode && nameNode.type === 'identifier') {\n          if (FUNCTION_VALUE_TYPES.has(value.type)) {\n            push('function', nameNode.text, node)\n            claimed.add(value.startIndex)\n          } else {\n            const wrapped = wrappedFunction(value)\n            if (wrapped) {\n              push('function', nameNode.text, node, true)\n              claimed.add(wrapped.startIndex)\n            }\n          }\n        }\n        break\n      }\n      case 'assignment_expression': {\n        const right = node.childForFieldName('right')\n        const left = node.childForFieldName('left')\n        const fn = right && FUNCTION_VALUE_TYPES.has(right.type) ? right : right ? wrappedFunction(right) : null\n        const target = left ? assignmentTarget(left) : null\n        if (fn && target) {\n          const ownName = fn.childForFieldName('name')?.text\n          const wholeModule = target === 'module.exports' || target === 'exports'\n          push('function', wholeModule && ownName ? ownName : target, node, true)\n          claimed.add(fn.startIndex)\n        }\n        break\n      }\n      case 'function':\n      case 'function_expression':\n      case 'generator_function': {\n        // A named function expression handed to a call: `app.get('/x', function list() {})`.\n        if (!claimed.has(node.startIndex) && node.parent?.type === 'arguments') {\n          const name = node.childForFieldName('name')?.text\n          if (name) push('function', name, node, true)\n        }\n        break\n      }\n    }\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (child) visit(child, classCtx)\n    }\n  }\n\n  visit(root, undefined)\n  const held = new Set(out.filter((d) => !d.bound).map((d) => d.qualname))\n  return out.filter((d) => !d.bound || !held.has(d.qualname)).map(({ bound: _bound, ...def }) => def)\n}\n\n// Python: `def` is `function_definition`, `class` is `class_definition`, and a\n// decorated form wraps either in `decorated_definition`. A `function_definition`\n// whose direct owner is a class body is a method (its `__init__` the constructor,\n// the qualname `Class.__init__` so the terminal name still matches the runtime\n// `code.function`); a top-level or nested `def` is a plain function. Method-ness\n// comes from direct class-body membership, not ambient scope — a `def` nested in a\n// method is a function, mirroring the JS/TS walker where the node type decides.\n// `async def` is the same node type, so it needs no separate case.\nexport function collectPythonSymbolDefs(root: Parser.SyntaxNode): SymbolDef[] {\n  const out: SymbolDef[] = []\n\n  const push = (kind: SymbolKind, qualname: string, node: Parser.SyntaxNode): void => {\n    out.push({\n      kind,\n      qualname,\n      startLine: node.startPosition.row + 1,\n      endLine: node.endPosition.row + 1,\n      startIndex: node.startIndex,\n      endIndex: node.endIndex,\n    })\n  }\n\n  const visit = (node: Parser.SyntaxNode, classCtx: string | undefined): void => {\n    switch (node.type) {\n      case 'function_definition': {\n        const name = node.childForFieldName('name')?.text\n        if (name) {\n          if (classCtx) {\n            const kind: SymbolKind = name === '__init__' ? 'constructor' : 'method'\n            push(kind, `${classCtx}.${name}`, node)\n          } else {\n            push('function', name, node)\n          }\n        }\n        // The body is walked with no class context: a `def` inside this function\n        // is a plain function, never a method of the enclosing class.\n        const body = node.childForFieldName('body')\n        if (body) {\n          for (let i = 0; i < body.namedChildCount; i++) {\n            const child = body.namedChild(i)\n            if (child) visit(child, undefined)\n          }\n        }\n        return\n      }\n      case 'class_definition': {\n        const name = node.childForFieldName('name')?.text\n        if (name) push('class', name, node)\n        const body = node.childForFieldName('body')\n        if (body) {\n          for (let i = 0; i < body.namedChildCount; i++) {\n            const child = body.namedChild(i)\n            if (child) visit(child, name ?? classCtx)\n          }\n        }\n        return\n      }\n      case 'decorated_definition': {\n        // `@app.get(...)` etc. wrap the def/class in a `decorated_definition`;\n        // unwrap to the inner definition, keeping the class context so a decorated\n        // method in a class body still mints as a method.\n        const def = node.childForFieldName('definition')\n        if (def) visit(def, classCtx)\n        return\n      }\n    }\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (child) visit(child, classCtx)\n    }\n  }\n\n  visit(root, undefined)\n  return out\n}\n\n// Go: a `function_declaration` is a free function; a `method_declaration` carries\n// a receiver, so its qualname is `Receiver.method` — the terminal name matches the\n// runtime `code.function` whether the instrumentation stamps the bare method name\n// or a package-qualified `main.(*Server).Handle` (both reduce to `Handle` under\n// `terminalName`). The receiver type is read off the receiver parameter, unwrapping\n// a `*T` pointer and a `T[U]` generic to the base `type_identifier`. Go has no\n// classes; struct types are not symbols in this rung (mirrors the JS/TS scope of\n// callable-and-class definitions, without a Go analog for the class).\nfunction goReceiverType(node: Parser.SyntaxNode): string | undefined {\n  const receiver = node.childForFieldName('receiver')\n  if (!receiver) return undefined\n  for (let i = 0; i < receiver.namedChildCount; i++) {\n    const param = receiver.namedChild(i)\n    if (param?.type !== 'parameter_declaration') continue\n    let typeNode = param.childForFieldName('type')\n    if (typeNode?.type === 'pointer_type') typeNode = typeNode.namedChild(0) ?? typeNode\n    if (typeNode?.type === 'generic_type') {\n      typeNode = typeNode.childForFieldName('type') ?? typeNode.namedChild(0) ?? typeNode\n    }\n    if (typeNode?.type === 'type_identifier') return typeNode.text\n    return typeNode?.text\n  }\n  return undefined\n}\n\nexport function collectGoSymbolDefs(root: Parser.SyntaxNode): SymbolDef[] {\n  const out: SymbolDef[] = []\n\n  const push = (kind: SymbolKind, qualname: string, node: Parser.SyntaxNode): void => {\n    out.push({\n      kind,\n      qualname,\n      startLine: node.startPosition.row + 1,\n      endLine: node.endPosition.row + 1,\n      startIndex: node.startIndex,\n      endIndex: node.endIndex,\n    })\n  }\n\n  const visit = (node: Parser.SyntaxNode): void => {\n    switch (node.type) {\n      case 'function_declaration': {\n        const name = node.childForFieldName('name')?.text\n        if (name) push('function', name, node)\n        break\n      }\n      case 'method_declaration': {\n        const name = node.childForFieldName('name')?.text\n        if (name) {\n          const recv = goReceiverType(node)\n          push('method', recv ? `${recv}.${name}` : name, node)\n        }\n        break\n      }\n    }\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (child) visit(child)\n    }\n  }\n\n  visit(root)\n  return out\n}\n\n// Ruby: `method` is an instance method, `singleton_method` a class method\n// (`def self.x`), `class` a class, `module` a namespace. A `method` / `singleton_method`\n// inside a class or module body is a method (an instance `initialize` the\n// constructor, its qualname `Class.initialize` so the terminal name still matches\n// the runtime `code.function`); a top-level `def` is a plain function. Method-ness\n// comes from direct class/module-body membership, not ambient scope — a `def`\n// nested in a method is a function, mirroring the Python and JS/TS walkers where\n// the node type and its owner decide. Ruby writes a method as `Class#method` and a\n// namespace with `::` (`Shop::OrderMailer`); the qualname joins the nesting with a\n// plain `.` so it reduces under `terminalName` (last-`.` split) to the bare method\n// name — a runtime `OrderMailer#deliver` or a bare `deliver` both land via the\n// line-in-span primary, and the bare form also matches the `code.function`\n// tiebreaker. A class/module declared with a `::` scope-resolution name\n// (`class Shop::OrderMailer`) is normalized to the same dotted form.\nexport function collectRubySymbolDefs(root: Parser.SyntaxNode): SymbolDef[] {\n  const out: SymbolDef[] = []\n\n  const push = (kind: SymbolKind, qualname: string, node: Parser.SyntaxNode): void => {\n    out.push({\n      kind,\n      qualname,\n      startLine: node.startPosition.row + 1,\n      endLine: node.endPosition.row + 1,\n      startIndex: node.startIndex,\n      endIndex: node.endIndex,\n    })\n  }\n\n  // The declared name of a class/module, dot-joined so a `Shop::OrderMailer`\n  // scope-resolution name reduces cleanly under `terminalName`.\n  const nameText = (node: Parser.SyntaxNode): string | undefined =>\n    node.childForFieldName('name')?.text.replace(/::/g, '.')\n\n  const walkBody = (node: Parser.SyntaxNode, ctx: string | undefined): void => {\n    const body = node.childForFieldName('body')\n    if (!body) return\n    for (let i = 0; i < body.namedChildCount; i++) {\n      const child = body.namedChild(i)\n      if (child) visit(child, ctx)\n    }\n  }\n\n  const visit = (node: Parser.SyntaxNode, classCtx: string | undefined): void => {\n    switch (node.type) {\n      case 'method':\n      case 'singleton_method': {\n        const name = node.childForFieldName('name')?.text\n        if (name) {\n          if (classCtx) {\n            const kind: SymbolKind =\n              node.type === 'method' && name === 'initialize' ? 'constructor' : 'method'\n            push(kind, `${classCtx}.${name}`, node)\n          } else {\n            push('function', name, node)\n          }\n        }\n        // The body is walked with no class context: a `def` inside this method is a\n        // plain function, never a method of the enclosing class.\n        walkBody(node, undefined)\n        return\n      }\n      case 'class':\n      case 'module': {\n        const name = nameText(node)\n        if (name) push('class', classCtx ? `${classCtx}.${name}` : name, node)\n        walkBody(node, name ? (classCtx ? `${classCtx}.${name}` : name) : classCtx)\n        return\n      }\n    }\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (child) visit(child, classCtx)\n    }\n  }\n\n  visit(root, undefined)\n  return out\n}\n\n// PHP: a top-level `function_definition` is a plain (possibly namespaced)\n// function; a `method_declaration` inside a class / trait / interface body is a\n// method (its `__construct` the constructor); `class_declaration`,\n// `trait_declaration`, and `interface_declaration` all mint as `class`-kind nodes\n// (a trait and an interface are class-shaped heritage targets, so an INHERITS /\n// IMPLEMENTS to either has a symbol to land on). PHP writes namespaces with `\\`\n// (`App\\Quote`) and static members with `::` (`QuoteService::calculate`); the\n// qualname joins the namespace and class nesting with a plain `.`\n// (`App.Quote.QuoteService.calculate`) so it reduces under ingest's `terminalName`\n// (last-`.` split) to the bare method name (`calculate`) — a runtime\n// `App\\Quote\\QuoteService::calculate` or a bare `calculate` both land via the\n// line-in-span primary, and the bare form also matches the `code.function`\n// tiebreaker. A semicolon-form `namespace App\\Quote;` sets the ambient namespace\n// for every sibling that follows it; a braced `namespace App\\Quote { … }` scopes\n// it to its body — the walker threads both. Method-ness comes from direct\n// class-body membership, mirroring the Python and Ruby walkers.\nexport function collectPhpSymbolDefs(root: Parser.SyntaxNode): SymbolDef[] {\n  const out: SymbolDef[] = []\n\n  const push = (kind: SymbolKind, qualname: string, node: Parser.SyntaxNode): void => {\n    out.push({\n      kind,\n      qualname,\n      startLine: node.startPosition.row + 1,\n      endLine: node.endPosition.row + 1,\n      startIndex: node.startIndex,\n      endIndex: node.endIndex,\n    })\n  }\n\n  // PHP's `\\` namespace separator and `::` member separator both normalize to the\n  // `.` the qualname joins on, so a declared `App\\Quote` or `Billing::Invoice`\n  // reduces cleanly under `terminalName`; a leading separator (`\\App`) is dropped.\n  const dot = (s: string): string => s.replace(/\\\\/g, '.').replace(/::/g, '.').replace(/^\\.+/, '')\n  const join = (prefix: string | undefined, name: string): string =>\n    prefix ? `${prefix}.${name}` : name\n\n  // Walk a container's named children in order, threading the ambient namespace a\n  // semicolon-form `namespace X;` sets for every sibling after it.\n  const walkChildren = (\n    container: Parser.SyntaxNode,\n    nsCtx: string | undefined,\n    classCtx: string | undefined,\n  ): void => {\n    let ns = nsCtx\n    for (let i = 0; i < container.namedChildCount; i++) {\n      const child = container.namedChild(i)\n      if (!child) continue\n      if (child.type === 'namespace_definition' && !child.childForFieldName('body')) {\n        const nameNode = child.childForFieldName('name')\n        if (nameNode) ns = dot(nameNode.text)\n        continue\n      }\n      visit(child, ns, classCtx)\n    }\n  }\n\n  const walkBody = (\n    node: Parser.SyntaxNode,\n    nsCtx: string | undefined,\n    classCtx: string | undefined,\n  ): void => {\n    const body = node.childForFieldName('body')\n    if (body) walkChildren(body, nsCtx, classCtx)\n  }\n\n  const visit = (\n    node: Parser.SyntaxNode,\n    nsCtx: string | undefined,\n    classCtx: string | undefined,\n  ): void => {\n    switch (node.type) {\n      case 'function_definition': {\n        const name = node.childForFieldName('name')?.text\n        if (name) push('function', join(nsCtx, name), node)\n        // A function nested in a function is still a plain function, never a method.\n        walkBody(node, nsCtx, undefined)\n        return\n      }\n      case 'class_declaration':\n      case 'trait_declaration':\n      case 'interface_declaration': {\n        const name = node.childForFieldName('name')?.text\n        const full = name ? join(nsCtx, name) : classCtx\n        if (name) push('class', full!, node)\n        walkBody(node, nsCtx, full)\n        return\n      }\n      case 'method_declaration': {\n        const name = node.childForFieldName('name')?.text\n        if (name) {\n          const kind: SymbolKind = name === '__construct' ? 'constructor' : 'method'\n          push(kind, join(classCtx ?? nsCtx, name), node)\n        }\n        return\n      }\n      case 'namespace_definition': {\n        // A braced `namespace App\\Quote { … }`: scoped to its body. The\n        // semicolon form carries no body and is handled by walkChildren above.\n        const nameNode = node.childForFieldName('name')\n        const ns = nameNode ? dot(nameNode.text) : nsCtx\n        walkBody(node, ns, classCtx)\n        return\n      }\n    }\n    walkChildren(node, nsCtx, classCtx)\n  }\n\n  walkChildren(root, undefined, undefined)\n  return out\n}\n\n// C#/.NET: a `method_declaration` inside a type body is a method and a\n// `constructor_declaration` its constructor (the declared name of a C#\n// constructor is the type name); `class_declaration`, `interface_declaration`,\n// `struct_declaration`, and `record_declaration` all mint as `class`-kind nodes —\n// an interface, struct, or record is a class-shaped definition / heritage target,\n// so an INHERITS / IMPLEMENTS to any of them has a symbol to land on. C# already\n// writes namespaces and members with `.` (`Cart.Services.CartService.AddItem`), so\n// the qualname joins the namespace and type nesting with a plain `.` and reduces\n// under ingest's `terminalName` (last-`.` split) to the bare method name\n// (`AddItem`) — normalization is minimal, since there's no `::` or `\\` to rewrite.\n// A runtime `code.function` of `AddItem` matches the tiebreaker; a namespace- or\n// type-qualified form still lands via the line-in-span primary — the same keying\n// ADR-192 relies on for Go's package-qualified names. A block\n// `namespace Cart.Services { … }` scopes its name to its body; a C# 10 file-scoped\n// `namespace Cart.Services;` carries no body and threads its ambient namespace onto\n// every sibling that follows it — the same two forms PHP's braced / semicolon\n// namespaces take, threaded the same way (extract/symbols.ts collectPhpSymbolDefs).\n// Method-ness comes from direct type-body membership, mirroring the Python, Ruby,\n// and PHP walkers.\nexport function collectCsharpSymbolDefs(root: Parser.SyntaxNode): SymbolDef[] {\n  const out: SymbolDef[] = []\n\n  const push = (kind: SymbolKind, qualname: string, node: Parser.SyntaxNode): void => {\n    out.push({\n      kind,\n      qualname,\n      startLine: node.startPosition.row + 1,\n      endLine: node.endPosition.row + 1,\n      startIndex: node.startIndex,\n      endIndex: node.endIndex,\n    })\n  }\n\n  const join = (prefix: string | undefined, name: string): string =>\n    prefix ? `${prefix}.${name}` : name\n\n  // Walk a container's named children in order, threading the ambient namespace a\n  // file-scoped `namespace X;` (which carries no body) sets for every sibling after\n  // it — the C# analog of PHP's semicolon-form namespace.\n  const walkChildren = (\n    container: Parser.SyntaxNode,\n    nsCtx: string | undefined,\n    classCtx: string | undefined,\n  ): void => {\n    let ns = nsCtx\n    for (let i = 0; i < container.namedChildCount; i++) {\n      const child = container.namedChild(i)\n      if (!child) continue\n      if (child.type === 'file_scoped_namespace_declaration') {\n        const nameNode = child.childForFieldName('name')\n        if (nameNode) ns = join(nsCtx, nameNode.text)\n        continue\n      }\n      visit(child, ns, classCtx)\n    }\n  }\n\n  const walkBody = (\n    node: Parser.SyntaxNode,\n    nsCtx: string | undefined,\n    classCtx: string | undefined,\n  ): void => {\n    const body = node.childForFieldName('body')\n    if (body) walkChildren(body, nsCtx, classCtx)\n  }\n\n  const visit = (\n    node: Parser.SyntaxNode,\n    nsCtx: string | undefined,\n    classCtx: string | undefined,\n  ): void => {\n    switch (node.type) {\n      case 'namespace_declaration': {\n        // Block form `namespace Cart.Services { … }`: scoped to its body. The name\n        // is already dotted; nested block namespaces join with `.`.\n        const nameNode = node.childForFieldName('name')\n        const ns = nameNode ? join(nsCtx, nameNode.text) : nsCtx\n        walkBody(node, ns, classCtx)\n        return\n      }\n      case 'class_declaration':\n      case 'interface_declaration':\n      case 'struct_declaration':\n      case 'record_declaration': {\n        const name = node.childForFieldName('name')?.text\n        const full = name ? join(classCtx ?? nsCtx, name) : classCtx\n        if (name) push('class', full!, node)\n        // Members carry the full type path as their class context, so a nested\n        // type reads `Outer.Inner` and a method reads `Type.method`.\n        walkBody(node, nsCtx, full)\n        return\n      }\n      case 'method_declaration': {\n        const name = node.childForFieldName('name')?.text\n        if (name) push('method', join(classCtx ?? nsCtx, name), node)\n        // No descent into the method body: a local function is out of scope, the\n        // same boundary the JS/TS, Python, Ruby, and PHP walkers hold.\n        return\n      }\n      case 'constructor_declaration': {\n        const name = node.childForFieldName('name')?.text\n        if (name) push('constructor', join(classCtx ?? nsCtx, name), node)\n        return\n      }\n    }\n    walkChildren(node, nsCtx, classCtx)\n  }\n\n  walkChildren(root, undefined, undefined)\n  return out\n}\n\n// Java: a `method_declaration` inside a type body is a method and a\n// `constructor_declaration` its constructor (a Java constructor's declared name is\n// the type name); `class_declaration`, `interface_declaration`, `enum_declaration`,\n// and `record_declaration` all mint as `class`-kind nodes — an interface, enum, or\n// record is a class-shaped definition / heritage target, so an INHERITS / IMPLEMENTS\n// to any of them has a symbol to land on. Java's scoping is simpler than C#'s: a\n// file has at most one file-level `package com.a.b;` that prefixes every top-level\n// type, with no nested or block namespaces, so the package is read once from the\n// root and there is nothing to thread through siblings. The qualname joins that\n// package and the type nesting with `.` (`com.example.cart.CartService.addItem`) —\n// Java already writes packages and members with `.`, so normalization is minimal (no\n// `::` or `\\` to rewrite) and it reduces under ingest's `terminalName` (last-`.`\n// split) to the bare method name (`addItem`). A runtime `code.function` of `addItem`\n// matches the tiebreaker; a package- or type-qualified form still lands via the\n// line-in-span primary — the same keying ADR-192 relies on for Go's\n// package-qualified names. Method-ness comes from direct type-body membership,\n// mirroring the Python, Ruby, PHP, and C# walkers; a method body is not descended\n// into, so a local class is out of scope — the same boundary those walkers hold.\nexport function collectJavaSymbolDefs(root: Parser.SyntaxNode): SymbolDef[] {\n  const out: SymbolDef[] = []\n\n  const push = (kind: SymbolKind, qualname: string, node: Parser.SyntaxNode): void => {\n    out.push({\n      kind,\n      qualname,\n      startLine: node.startPosition.row + 1,\n      endLine: node.endPosition.row + 1,\n      startIndex: node.startIndex,\n      endIndex: node.endIndex,\n    })\n  }\n\n  const join = (prefix: string | undefined, name: string): string =>\n    prefix ? `${prefix}.${name}` : name\n\n  // Java allows at most one file-level `package com.a.b;`, and it applies to the\n  // whole compilation unit — no nesting, no scoping blocks. Read it once from the\n  // root; its name node is a `scoped_identifier` (or bare `identifier`) that already\n  // carries the dotted form.\n  let pkg: string | undefined\n  for (let i = 0; i < root.namedChildCount; i++) {\n    const child = root.namedChild(i)\n    if (child?.type === 'package_declaration') {\n      pkg = child.namedChild(0)?.text\n      break\n    }\n  }\n\n  const walkChildren = (container: Parser.SyntaxNode, classCtx: string | undefined): void => {\n    for (let i = 0; i < container.namedChildCount; i++) {\n      const child = container.namedChild(i)\n      if (child) visit(child, classCtx)\n    }\n  }\n\n  const walkBody = (node: Parser.SyntaxNode, classCtx: string | undefined): void => {\n    // `class_body` / `interface_body` / `enum_body` all sit under the `body` field.\n    const body = node.childForFieldName('body')\n    if (body) walkChildren(body, classCtx)\n  }\n\n  const visit = (node: Parser.SyntaxNode, classCtx: string | undefined): void => {\n    switch (node.type) {\n      case 'class_declaration':\n      case 'interface_declaration':\n      case 'enum_declaration':\n      case 'record_declaration': {\n        const name = node.childForFieldName('name')?.text\n        const full = name ? join(classCtx ?? pkg, name) : classCtx\n        if (name) push('class', full!, node)\n        // Members carry the full type path as their class context, so a nested type\n        // reads `Outer.Inner` and a method reads `Type.method`.\n        walkBody(node, full)\n        return\n      }\n      case 'method_declaration': {\n        const name = node.childForFieldName('name')?.text\n        if (name) push('method', join(classCtx ?? pkg, name), node)\n        return\n      }\n      case 'constructor_declaration': {\n        const name = node.childForFieldName('name')?.text\n        if (name) push('constructor', join(classCtx ?? pkg, name), node)\n        return\n      }\n    }\n    walkChildren(node, classCtx)\n  }\n\n  walkChildren(root, undefined)\n  return out\n}\n\n// Kotlin (ADR-199), the JVM sibling of Java. The fwcd tree-sitter-kotlin grammar\n// folds every type-shaped definition into `class_declaration` — a plain `class`, an\n// `interface`, an `enum class`, a `data class`, and a `sealed class` are all\n// `class_declaration` nodes, distinguished only by an anonymous keyword child — so\n// one case covers them all and each mints as a `class`-kind node (a heritage /\n// definition target an INHERITS/IMPLEMENTS can land on). `object_declaration`\n// (Kotlin's singleton) mints as `class` too, and a `companion_object` is descended\n// into without adding a name segment when anonymous, so its members read as members\n// of the enclosing type — `FraudService.threshold`, the shape Kotlin itself exposes\n// (`FraudService.threshold()`). A `function_declaration` is a `method` inside a type\n// body and a `function` at file scope — unlike Java, Kotlin has real top-level\n// functions, so method-ness is decided by the class context, mirroring the\n// Python/JS walkers rather than Java's always-a-method rule. A `secondary_constructor`\n// (`constructor(…)`) mints as a `constructor` named for its enclosing type, the way\n// a Java constructor's declared name is its type; the primary constructor is part of\n// the class header and carries no independent body, so it is left to the class node.\n//\n// The grammar exposes no `name` / `body` fields (unlike Java's), so navigation is by\n// child node type: a type's name is its `type_identifier`, a function's its\n// `simple_identifier`, and the body is the `class_body` / `enum_class_body` child.\n// Kotlin's scoping is Java-simple: at most one file-level `package a.b.c` prefixes\n// every top-level type — the `package_header`'s `identifier` child already carries\n// the dotted form — with no nested or block namespaces to thread. The qualname joins\n// that package and the type nesting with `.` (`com.example.fraud.FraudService.check`),\n// so it reduces under ingest's `terminalName` (last-`.` split) to the bare function\n// name (`check`) a runtime `code.function` matches, the same key the Java/C# walkers\n// rely on. A function body is not descended into, so a local function is out of\n// scope — the same boundary the sibling walkers hold.\nexport function collectKotlinSymbolDefs(root: Parser.SyntaxNode): SymbolDef[] {\n  const out: SymbolDef[] = []\n\n  const push = (kind: SymbolKind, qualname: string, node: Parser.SyntaxNode): void => {\n    out.push({\n      kind,\n      qualname,\n      startLine: node.startPosition.row + 1,\n      endLine: node.endPosition.row + 1,\n      startIndex: node.startIndex,\n      endIndex: node.endIndex,\n    })\n  }\n\n  const join = (prefix: string | undefined, name: string): string =>\n    prefix ? `${prefix}.${name}` : name\n\n  // The first named child of `node` whose type is one of `types`. The grammar has no\n  // field names, so a definition's name and body are found by type, not `childForFieldName`.\n  const firstChildOfType = (\n    node: Parser.SyntaxNode,\n    types: readonly string[],\n  ): Parser.SyntaxNode | undefined => {\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (child && types.includes(child.type)) return child\n    }\n    return undefined\n  }\n  const nameOf = (node: Parser.SyntaxNode, ...types: string[]): string | undefined =>\n    firstChildOfType(node, types)?.text\n  const bodyOf = (node: Parser.SyntaxNode): Parser.SyntaxNode | undefined =>\n    firstChildOfType(node, ['class_body', 'enum_class_body'])\n\n  // At most one file-level `package a.b.c` prefixes every top-level type; its\n  // `identifier` child already carries the dotted form. Read once from the root.\n  let pkg: string | undefined\n  for (let i = 0; i < root.namedChildCount; i++) {\n    const child = root.namedChild(i)\n    if (child?.type === 'package_header') {\n      pkg = child.namedChild(0)?.text\n      break\n    }\n  }\n\n  const walkChildren = (container: Parser.SyntaxNode, classCtx: string | undefined): void => {\n    for (let i = 0; i < container.namedChildCount; i++) {\n      const child = container.namedChild(i)\n      if (child) visit(child, classCtx)\n    }\n  }\n\n  const visit = (node: Parser.SyntaxNode, classCtx: string | undefined): void => {\n    switch (node.type) {\n      case 'class_declaration':\n      case 'object_declaration': {\n        // class / interface / enum class / data class / sealed class all parse as\n        // class_declaration; object is object_declaration. All mint as class-kind.\n        const name = nameOf(node, 'type_identifier')\n        const full = name ? join(classCtx ?? pkg, name) : classCtx\n        if (name) push('class', full!, node)\n        const body = bodyOf(node)\n        // Members carry the full type path as their class context, so a nested type\n        // reads `Outer.Inner` and a method reads `Type.method`.\n        if (body) walkChildren(body, full)\n        return\n      }\n      case 'companion_object': {\n        // `companion object` — anonymous by default, so it adds no name segment and\n        // its members read as members of the enclosing type (`FraudService.threshold`).\n        // A named companion (`companion object Factory`) threads its name.\n        const name = nameOf(node, 'type_identifier')\n        const full = name ? join(classCtx ?? pkg, name) : (classCtx ?? pkg)\n        const body = bodyOf(node)\n        if (body) walkChildren(body, full)\n        return\n      }\n      case 'function_declaration': {\n        // A method in a type body, a top-level function at file scope.\n        const name = nameOf(node, 'simple_identifier')\n        if (name) push(classCtx ? 'method' : 'function', join(classCtx ?? pkg, name), node)\n        return\n      }\n      case 'secondary_constructor': {\n        // `constructor(…)` — its name is the enclosing type's, the last segment of\n        // the class context, matching how a Java constructor's declared name is its type.\n        if (classCtx) {\n          const typeName = classCtx.slice(classCtx.lastIndexOf('.') + 1)\n          push('constructor', join(classCtx, typeName), node)\n        }\n        return\n      }\n    }\n    walkChildren(node, classCtx)\n  }\n\n  walkChildren(root, undefined)\n  return out\n}\n\n// Rust (ADR-201). A `function_item` is a `function` at module/file scope and a\n// `method` inside an `impl_item` (or a `trait_item` — a trait's `function_item`\n// default methods and its `function_signature_item` abstract declarations both mint\n// as `method`, the way Kotlin's abstract interface method does). `struct_item`,\n// `enum_item`, and `trait_item` mint as `class`-kind nodes — a struct, an enum, and\n// a trait are the class-shaped definition / heritage targets Rust has, mirroring how\n// Java maps interface/enum/record and C# maps struct/record/interface all to `class`.\n// Rust has no constructor keyword: an associated `fn new()` is just an associated\n// function, so everything inside an `impl` mints as `method` with no `constructor`\n// case (the SymbolKind vocabulary is reused, not extended).\n//\n// Rust addresses definitions with `::` path separators, and this walker keeps that\n// native form rather than rewriting it to `.` the way the Ruby/PHP walkers normalize\n// their separators: a module's items read `module::item`, an impl's methods read\n// `module::Type::method` (keyed on the impl's target type, not the file), and a\n// nested module threads `outer::inner::item`. A `mod_item` is a namespace only — it\n// scopes the qualname but is not itself a symbol, the way a Java `package` or a C#\n// `namespace` scopes without minting. Because the qualname carries `::`, ingest's\n// `terminalName` (a last-`.` split) does not reduce it to the bare function name, so\n// the `code.function` tiebreaker won't match a `::`-addressed Rust span — but that is\n// only the tiebreaker: fusion's primary key is line-in-span (the observed\n// `code.lineno` falling inside a SymbolNode's definition span), which is\n// language-agnostic and lands a Rust span on its symbol regardless of separator\n// (landObservedSymbol, ingest.ts — unchanged). A method body is not descended into,\n// so a local `fn` or item is out of scope — the same boundary the sibling walkers hold.\nexport function collectRustSymbolDefs(root: Parser.SyntaxNode): SymbolDef[] {\n  const out: SymbolDef[] = []\n\n  const push = (kind: SymbolKind, qualname: string, node: Parser.SyntaxNode): void => {\n    out.push({\n      kind,\n      qualname,\n      startLine: node.startPosition.row + 1,\n      endLine: node.endPosition.row + 1,\n      startIndex: node.startIndex,\n      endIndex: node.endIndex,\n    })\n  }\n\n  // Rust joins path segments with `::`, kept verbatim so a qualname reads the way\n  // Rust itself addresses the item (`shipping::Quote::price`).\n  const join = (prefix: string | undefined, name: string): string =>\n    prefix ? `${prefix}::${name}` : name\n\n  // Emit each `fn` in a type body (an `impl` or a `trait` `declaration_list`) as a\n  // method under the type: a `function_item` is a concrete method / associated\n  // function, a `function_signature_item` a trait's abstract method (no body — the\n  // node itself carries the span). Nested items other than functions (associated\n  // types, consts) are not symbols and are skipped.\n  const walkTypeBody = (body: Parser.SyntaxNode, typeCtx: string): void => {\n    for (let i = 0; i < body.namedChildCount; i++) {\n      const child = body.namedChild(i)\n      if (!child) continue\n      if (child.type === 'function_item' || child.type === 'function_signature_item') {\n        const name = child.childForFieldName('name')?.text\n        if (name) push('method', join(typeCtx, name), child)\n      }\n    }\n  }\n\n  const walkChildren = (container: Parser.SyntaxNode, modCtx: string | undefined): void => {\n    for (let i = 0; i < container.namedChildCount; i++) {\n      const child = container.namedChild(i)\n      if (child) visit(child, modCtx)\n    }\n  }\n\n  const visit = (node: Parser.SyntaxNode, modCtx: string | undefined): void => {\n    switch (node.type) {\n      case 'mod_item': {\n        // A module scopes the qualname but is not itself a symbol. An inline\n        // `mod name { … }` carries a `declaration_list` body its items nest under; a\n        // bare `mod name;` (the file-as-module declaration) has no body here.\n        const name = node.childForFieldName('name')?.text\n        const full = name ? join(modCtx, name) : modCtx\n        const body = node.childForFieldName('body')\n        if (body) walkChildren(body, full)\n        return\n      }\n      case 'struct_item':\n      case 'enum_item': {\n        // A struct / enum is a class-kind definition; its fields / variants are not\n        // symbols, and Rust methods live in separate `impl` blocks, so there is no\n        // body to descend for members.\n        const name = node.childForFieldName('name')?.text\n        if (name) push('class', join(modCtx, name), node)\n        return\n      }\n      case 'trait_item': {\n        // A trait is a class-kind heritage target; its body holds the method\n        // signatures / default methods that mint under it.\n        const name = node.childForFieldName('name')?.text\n        const full = name ? join(modCtx, name) : modCtx\n        if (name) push('class', full!, node)\n        const body = node.childForFieldName('body')\n        if (body && full) walkTypeBody(body, full)\n        return\n      }\n      case 'impl_item': {\n        // An `impl Type { … }` / `impl Trait for Type { … }` block is not a symbol;\n        // its methods mint under the target type, keyed on the impl's `type` field so\n        // `impl Priced for Quote` and the inherent `impl Quote` both address `Quote`.\n        const typeName = node.childForFieldName('type')?.text\n        const full = typeName ? join(modCtx, typeName) : modCtx\n        const body = node.childForFieldName('body')\n        if (body && full) walkTypeBody(body, full)\n        return\n      }\n      case 'function_item': {\n        // A free function at module / file scope. A `fn` inside an `impl` / `trait`\n        // is reached through `walkTypeBody` above, never here, so this is always a\n        // plain function. Its body is not descended — a local item is out of scope.\n        const name = node.childForFieldName('name')?.text\n        if (name) push('function', join(modCtx, name), node)\n        return\n      }\n    }\n    walkChildren(node, modCtx)\n  }\n\n  walkChildren(root, undefined)\n  return out\n}\n\n// C++ (ADR-202), the last OpenTelemetry-Demo language. A `function_definition` is a\n// `function` at namespace/file scope and a `method` inside a `class_specifier` /\n// `struct_specifier` body; a `function_definition` whose declarator name equals its\n// enclosing class name is a `constructor`, and a destructor (`~Name`) maps to\n// `method` (the SymbolKind vocabulary is reused, not extended). `class_specifier` and\n// `struct_specifier` mint as `class`-kind nodes — the class-shaped definition /\n// heritage targets, mirroring how Java maps interface/enum/record and Rust maps\n// struct/enum/trait. A `namespace_definition` is a namespace only — it scopes the\n// qualname but is not itself a symbol, the way a Rust `mod_item` scopes without\n// minting — and a `template_declaration` wraps a function/class, so the walker\n// descends to the inner definition (the generic recursion visits it with the same\n// context).\n//\n// C++'s shape is unlike the sibling walkers in two ways. First, a `function_definition`\n// carries NO `name` field — the name lives inside its `function_declarator`'s\n// `declarator` field, reached by unwrapping a `pointer_declarator` / `reference_declarator`\n// return type (`Money* clone()`). That name node is an `identifier` (free fn / in-class\n// ctor), a `field_identifier` (in-class method), a `destructor_name` (`~Money`), an\n// `operator_name` (`operator==`), or a `qualified_identifier`. Second, an OUT-OF-LINE\n// member definition at file/namespace scope (`Money Money::add(…) { … }`) carries a\n// `qualified_identifier` declarator (`Money::add`), so the class is read from the\n// qualified path itself and the method keys onto that class (`Money::Money` out-of-line\n// is still a constructor, `Money::~Money` a method).\n//\n// Like the Rust walker, this one KEEPS the native `::` in the qualname rather than\n// rewriting it to `.`: a namespace's items read `ns::item`, a class's methods read\n// `ns::Class::method`, a nested namespace threads `outer::inner::item`. Because the\n// qualname carries `::`, ingest's `terminalName` (a last-`.` split) leaves it whole,\n// so a `::`-addressed `code.function` misses the tiebreaker and the observed span\n// lands on line-in-span alone — the primary key (landObservedSymbol, ingest.ts —\n// unchanged), the same case Rust proved. A method/function body is not descended\n// into, so a local class or lambda is out of scope — the boundary the sibling walkers\n// hold.\nexport function collectCppSymbolDefs(root: Parser.SyntaxNode): SymbolDef[] {\n  const out: SymbolDef[] = []\n\n  const push = (kind: SymbolKind, qualname: string, node: Parser.SyntaxNode): void => {\n    out.push({\n      kind,\n      qualname,\n      startLine: node.startPosition.row + 1,\n      endLine: node.endPosition.row + 1,\n      startIndex: node.startIndex,\n      endIndex: node.endIndex,\n    })\n  }\n\n  // C++ joins path segments with `::`, kept verbatim so a qualname reads the way C++\n  // itself addresses the item (`shop::Money::add`).\n  const join = (prefix: string | undefined, name: string): string =>\n    prefix ? `${prefix}::${name}` : name\n\n  // A `function_definition`'s declarator field is the `function_declarator` carrying\n  // the name, but a pointer/reference return type wraps it first (`T* f()` →\n  // pointer_declarator; `const T& f()` → reference_declarator). Descend through those\n  // wrappers to the `function_declarator`, then return its own `declarator` (the name\n  // node). The inner declarator is exposed as the `declarator` field on a\n  // pointer_declarator but only as a plain named child on a reference_declarator, so\n  // the descent looks for the next declarator wrapper among named children by type\n  // rather than by field — stopping at the function_declarator so a function-pointer\n  // parameter (which lives under the parameter list) is never mistaken for the name.\n  const DECLARATOR_WRAPPERS = new Set([\n    'function_declarator',\n    'pointer_declarator',\n    'reference_declarator',\n    'parenthesized_declarator',\n  ])\n  const functionNameNode = (node: Parser.SyntaxNode): Parser.SyntaxNode | undefined => {\n    let decl: Parser.SyntaxNode | null | undefined = node.childForFieldName('declarator')\n    for (let guard = 0; decl && guard < 8; guard++) {\n      if (decl.type === 'function_declarator') {\n        return decl.childForFieldName('declarator') ?? undefined\n      }\n      let next: Parser.SyntaxNode | undefined\n      for (let i = 0; i < decl.namedChildCount; i++) {\n        const child = decl.namedChild(i)\n        if (child && DECLARATOR_WRAPPERS.has(child.type)) {\n          next = child\n          break\n        }\n      }\n      decl = next\n    }\n    return undefined\n  }\n\n  // Classify a definition from its declared name text and the enclosing class's\n  // simple name (undefined at namespace/file scope). The name text keeps `::`: an\n  // out-of-line `Money::add` names its own class in the segment before the last, so\n  // its class is read from the name rather than the enclosing scope; a bare `cents`\n  // takes the enclosing class. A member whose name equals the class name is a\n  // constructor; a destructor (`~Name`) differs from the class name, so it stays a\n  // method; anything at namespace scope with no class is a plain function.\n  const classify = (\n    nameText: string,\n    prefix: string | undefined,\n    enclosingClass: string | undefined,\n  ): { kind: SymbolKind; qualname: string } => {\n    const qualname = join(prefix, nameText)\n    let className: string | undefined\n    let memberName: string\n    const idx = nameText.lastIndexOf('::')\n    if (idx >= 0) {\n      memberName = nameText.slice(idx + 2)\n      const before = nameText.slice(0, idx)\n      const j = before.lastIndexOf('::')\n      className = j >= 0 ? before.slice(j + 2) : before\n    } else {\n      memberName = nameText\n      className = enclosingClass\n    }\n    let kind: SymbolKind\n    if (className && memberName === className) kind = 'constructor'\n    else if (className) kind = 'method'\n    else kind = 'function'\n    return { kind, qualname }\n  }\n\n  const walkChildren = (\n    container: Parser.SyntaxNode,\n    prefix: string | undefined,\n    enclosingClass: string | undefined,\n  ): void => {\n    for (let i = 0; i < container.namedChildCount; i++) {\n      const child = container.namedChild(i)\n      if (child) visit(child, prefix, enclosingClass)\n    }\n  }\n\n  const visit = (\n    node: Parser.SyntaxNode,\n    prefix: string | undefined,\n    enclosingClass: string | undefined,\n  ): void => {\n    switch (node.type) {\n      case 'namespace_definition': {\n        // A namespace scopes the qualname but is not itself a symbol. An anonymous\n        // namespace (`namespace { … }`) carries no name and leaves the prefix as-is.\n        const name = node.childForFieldName('name')?.text\n        const newPrefix = name ? join(prefix, name) : prefix\n        const body = node.childForFieldName('body')\n        // Inside a namespace the enclosing class resets to undefined.\n        if (body) walkChildren(body, newPrefix, undefined)\n        return\n      }\n      case 'class_specifier':\n      case 'struct_specifier': {\n        // A class / struct is a class-kind definition. An anonymous one (no `name`)\n        // is not minted and its members are not descended — there is no stable path\n        // to key them on.\n        const name = node.childForFieldName('name')?.text\n        const full = name ? join(prefix, name) : prefix\n        if (name) push('class', full!, node)\n        const body = node.childForFieldName('body')\n        // Members carry the full class path as their prefix and the simple class name\n        // as their enclosing class, so a method reads `ns::Class::method` and a\n        // constructor is recognized by name equality.\n        if (body && name) walkChildren(body, full, name)\n        return\n      }\n      case 'function_definition': {\n        const nameNode = functionNameNode(node)\n        if (nameNode) {\n          const { kind, qualname } = classify(nameNode.text, prefix, enclosingClass)\n          push(kind, qualname, node)\n        }\n        // The body is not descended into — a local definition is out of scope.\n        return\n      }\n    }\n    // Generic descent covers `translation_unit`, `template_declaration` (whose inner\n    // function/class definition is minted here with the same context),\n    // `linkage_specification` (`extern \"C\" { … }`), and preprocessor blocks. A\n    // `field_declaration` (a member declaration without a body) has no\n    // `function_definition` child, so a declaration-only method is correctly skipped.\n    walkChildren(node, prefix, enclosingClass)\n  }\n\n  walkChildren(root, undefined, undefined)\n  return out\n}\n\n// Dispatch to the walker that reads the file's language. `.py`, `.go`, `.rb`,\n// `.php`, `.cs`, `.java`, `.kt`, `.rs`, and the C++ extensions map to their own\n// definition node types; every other mapped extension is JS/TS and rides the shared\n// walker.\nexport function collectSymbolDefsForExt(ext: string, root: Parser.SyntaxNode): SymbolDef[] {\n  switch (ext) {\n    case '.py':\n      return collectPythonSymbolDefs(root)\n    case '.go':\n      return collectGoSymbolDefs(root)\n    case '.rb':\n      return collectRubySymbolDefs(root)\n    case '.php':\n      return collectPhpSymbolDefs(root)\n    case '.cs':\n      return collectCsharpSymbolDefs(root)\n    case '.java':\n      return collectJavaSymbolDefs(root)\n    case '.kt':\n      return collectKotlinSymbolDefs(root)\n    case '.rs':\n      return collectRustSymbolDefs(root)\n    case '.cpp':\n    case '.cc':\n    case '.cxx':\n    case '.c++':\n    case '.hpp':\n    case '.hh':\n    case '.hxx':\n    case '.h++':\n      return collectCppSymbolDefs(root)\n    default:\n      return collectSymbolDefs(root)\n  }\n}\n\n// Same-named siblings in one file (overloads, repeated anonymous-arrow names)\n// get an ordinal disambiguator in source order so the id stays collision-free\n// without inventing a name (ADR-158). A qualname that appears once keeps the\n// clean, disambiguator-free id.\nexport function disambiguate(defs: SymbolDef[]): { def: SymbolDef; disambiguator?: number }[] {\n  const counts = new Map<string, number>()\n  for (const def of defs) counts.set(def.qualname, (counts.get(def.qualname) ?? 0) + 1)\n  const seen = new Map<string, number>()\n  return defs.map((def) => {\n    if ((counts.get(def.qualname) ?? 0) <= 1) return { def }\n    const ordinal = seen.get(def.qualname) ?? 0\n    seen.set(def.qualname, ordinal + 1)\n    return { def, disambiguator: ordinal }\n  })\n}\n\nfunction utf8Offsets(content: string, defs: SymbolDef[]): Map<number, number> {\n  if (content.includes('\\uFFFD')) return new Map()\n  const indices = [...new Set(defs.flatMap(({ startIndex, endIndex }) => [startIndex, endIndex]))].sort(\n    (a, b) => a - b,\n  )\n  const offsets = new Map<number, number>()\n  let cursor = 0\n  let bytes = 0\n  for (const index of indices) {\n    if (index < cursor || index > content.length) return new Map()\n    bytes += Buffer.byteLength(content.slice(cursor, index), 'utf8')\n    offsets.set(index, bytes)\n    cursor = index\n  }\n  return offsets\n}\n\nexport async function addSymbols(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  const parsers = new Map<string, Parser>()\n  let kotlinNoted = false\n  const parserForExt = (ext: string, file?: string): Parser | null => {\n    const grammar = SYMBOL_GRAMMAR_BY_EXT[ext]\n    if (!grammar) {\n      if (ext === '.kt' && !kotlinNoted) {\n        kotlinNoted = true\n        recordExtractionError('symbols', file ?? '*.kt', new Error(KOTLIN_UNAVAILABLE))\n      }\n      return null\n    }\n    let parser = parsers.get(ext)\n    if (!parser) {\n      parser = new Parser()\n      parser.setLanguage(grammar)\n      parsers.set(ext, parser)\n    }\n    return parser\n  }\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n    for (const file of files) {\n      const ext = path.extname(file.path)\n      const parser = parserForExt(ext, file.path)\n      if (!parser) continue\n      const relPath = toPosix(path.relative(service.dir, file.path))\n\n      let defs: SymbolDef[]\n      let completeParse: boolean\n      try {\n        const tree = parseSource(parser, file.content)\n        defs = collectSymbolDefsForExt(ext, tree.rootNode)\n        completeParse = !tree.rootNode.hasError\n      } catch (err) {\n        recordExtractionError('symbol extraction', file.path, err)\n        continue\n      }\n      if (defs.length === 0) continue\n      const offsets = completeParse ? utf8Offsets(file.content, defs) : new Map<number, number>()\n\n      // The file owns its symbols; ensure the FileNode (and the owning\n      // `service ──CONTAINS──▶ file` edge) exists before a symbol hangs off it.\n      // Idempotent — addFiles already minted it on this pass.\n      const {\n        fileNodeId,\n        nodesAdded: fn,\n        edgesAdded: fe,\n      } = ensureFileNode(graph, service.pkg.name, service.node.id, relPath)\n      nodesAdded += fn\n      edgesAdded += fe\n\n      for (const { def, disambiguator } of disambiguate(defs)) {\n        const sid = symbolId(service.pkg.name, relPath, def.qualname, disambiguator)\n        // tree-sitter's JavaScript indices count UTF-16 code units. Convert the\n        // parsed definition's boundaries to byte positions in the UTF-8 file.\n        // Replacement characters may stand for undecodable input, so such files\n        // retain their line span but never claim edit-safe byte positions.\n        const startByte = offsets.get(def.startIndex)\n        const endByte = offsets.get(def.endIndex)\n        const precise =\n          startByte !== undefined && endByte !== undefined && endByte > startByte\n            ? { startByte, endByte }\n            : {}\n        const node: SymbolNode = {\n          id: sid,\n          type: NodeType.SymbolNode,\n          kind: def.kind,\n          qualname: def.qualname,\n          span: { startLine: def.startLine, endLine: def.endLine, ...precise },\n          service: service.pkg.name,\n          relPath,\n          discoveredVia: 'static',\n        }\n        if (!graph.hasNode(sid)) {\n          graph.addNode(sid, node)\n          nodesAdded++\n        } else {\n          const previous = graph.getNodeAttributes(sid) as SymbolNode\n          const discoveredVia =\n            previous.discoveredVia === 'otel' || previous.discoveredVia === 'merged'\n              ? 'merged'\n              : 'static'\n          const moved = previous.span.startLine !== node.span.startLine ||\n            previous.span.endLine !== node.span.endLine ||\n            previous.span.startByte !== node.span.startByte ||\n            previous.span.endByte !== node.span.endByte\n          if (moved || previous.kind !== node.kind || previous.qualname !== node.qualname ||\n            previous.discoveredVia !== discoveredVia || previous.service !== node.service ||\n            previous.relPath !== node.relPath) {\n            graph.replaceNodeAttributes(sid, { ...previous, ...node, discoveredVia })\n          }\n        }\n        // `file ──CONTAINS──▶ symbol` — structural ownership, the same tier and\n        // shape as `service ──CONTAINS──▶ file` (file-awareness.md §2), evidence\n        // pinned to the definition's file:line.\n        const containsId = extractedEdgeId(fileNodeId, sid, EdgeType.CONTAINS)\n        if (!graph.hasEdge(containsId)) {\n          const edge: GraphEdge = {\n            id: containsId,\n            source: fileNodeId,\n            target: sid,\n            type: EdgeType.CONTAINS,\n            provenance: Provenance.EXTRACTED,\n            confidence: confidenceForExtracted('structural'),\n            evidence: {\n              file: relPath,\n              line: def.startLine,\n              snippet: snippet(file.content, def.startLine),\n            },\n          }\n          graph.addEdgeWithKey(containsId, fileNodeId, sid, edge)\n          edgesAdded++\n        }\n      }\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","// ADR-065 — loud failure mode for static extraction.\n//\n// Per-file extraction failures used to land as a single `console.warn` line\n// with no aggregate count and no on-disk record. The 2026-05-12 medusa\n// experiment ran `neat init` against ~90 files that all silently failed\n// extraction with \"Invalid argument\"; the snapshot shipped with those files\n// missing, the user had no signal it had happened, and the divergence query\n// couldn't surface gaps it didn't know it had.\n//\n// This module is the failure-mode plumbing: a process-local sink that every\n// producer appends to when a per-file parse fails, with helpers to drain the\n// sink to `<projectDir>/neat-out/errors.ndjson` and to surface the aggregate\n// count in init / watch banners.\n\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { EdgeEvidence, ExtractionCoverage } from '@neat.is/types'\n\nexport interface ExtractionError {\n  // Producer name (e.g. \"http\", \"services\", \"infra docker-compose\"). Stable\n  // human-readable identifier for logs and contract assertions.\n  producer: string\n  // Absolute or relative path of the file that failed. Stored verbatim from\n  // the call site; no normalisation here.\n  file: string\n  // The error's `.message`. Stringified if the throw value wasn't an Error.\n  error: string\n  // Optional stack trace (captured at the call site). Useful for diagnosing\n  // tree-sitter \"Invalid argument\" cases where the message alone is generic.\n  stack?: string\n  // ISO timestamp of when the error was recorded.\n  ts: string\n  // Discriminator for `errors.ndjson` consumers — separates extract failures\n  // from OTel error events that share the same file (ADR-033).\n  source: 'extract'\n}\n\nconst sink: ExtractionError[] = []\n\n// Record a per-file extraction failure. Preserves the visible warn line so\n// existing scripts/CI consumers still see a per-file message; appends to the\n// process-local sink so the aggregate count + sidecar write can fire later.\nexport function recordExtractionError(\n  producer: string,\n  file: string,\n  err: unknown,\n): void {\n  const e = err instanceof Error ? err : new Error(String(err))\n  sink.push({\n    producer,\n    file,\n    error: e.message,\n    stack: e.stack,\n    ts: new Date().toISOString(),\n    source: 'extract',\n  })\n  // Visible warn preserved (pre-ADR-065 callers logged this). Banners\n  // aggregate, but per-file context still useful for tail -f sessions.\n  console.warn(`[neat] ${producer} skipped ${file}: ${e.message}`)\n}\n\n// Drain all queued errors. Idempotent — subsequent calls return an empty\n// array until new errors land. Callers (extractFromDirectory) drain at start\n// to clear stale state from prior runs, then drain again at end to collect\n// the pass's failures.\nexport function drainExtractionErrors(): ExtractionError[] {\n  return sink.splice(0, sink.length)\n}\n\n// Read-only count of currently-queued errors. Used by callers that want the\n// count without consuming the sink (the banner case — we want the count for\n// display and the entries for `errors.ndjson`).\nexport function pendingExtractionErrors(): number {\n  return sink.length\n}\n\n// Append the drained entries to `<projectDir>/neat-out/errors.ndjson`. The\n// file is shared with OTel error events (per ADR-033); the `source: 'extract'`\n// discriminator separates them for consumers. Creates the directory if\n// missing. Append-only — never rewritten.\nexport async function writeExtractionErrors(\n  errors: ExtractionError[],\n  errorsPath: string,\n): Promise<void> {\n  if (errors.length === 0) return\n  await fs.mkdir(path.dirname(errorsPath), { recursive: true })\n  const lines = errors.map((e) => JSON.stringify(e)).join('\\n') + '\\n'\n  await fs.appendFile(errorsPath, lines, 'utf8')\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// #883 — extraction coverage in the query surface.\n//\n// errors.ndjson is append-only and shared with OTel error events, so it can't\n// answer \"is the CURRENT graph complete?\" — its extract lines accumulate across\n// every pass. This sidecar is overwritten each full pass (zero included), so it\n// always reflects the latest coverage, and a daemon reads it to put the count on\n// /health. Without it, a partial extraction is invisible to anything querying\n// the graph.\n// ─────────────────────────────────────────────────────────────────────────\n\n// The health sidecar sits beside errors.ndjson and mirrors its per-project\n// naming: errors.ndjson → extraction-health.json;\n// errors.<project>.ndjson → extraction-health.<project>.json.\nexport function extractionHealthPathFor(errorsPath: string): string {\n  const dir = path.dirname(errorsPath)\n  const suffix = path.basename(errorsPath).replace(/^errors/, '').replace(/\\.ndjson$/, '')\n  return path.join(dir, `extraction-health${suffix}.json`)\n}\n\n// Up to this many failed-file paths are sampled into the sidecar; the count is\n// always exact, the list is a bounded aid.\nconst HEALTH_FILE_SAMPLE = 100\n\n// Overwrite the sidecar with this pass's coverage. Called on every full pass so\n// a clean re-run clears a prior gap (skippedFiles: 0). Best-effort at the call\n// site; failure to write never fails extraction.\nexport async function writeExtractionHealth(\n  errors: ExtractionError[],\n  healthPath: string,\n  now: string = new Date().toISOString(),\n): Promise<void> {\n  const byProducer: Record<string, number> = {}\n  for (const e of errors) byProducer[e.producer] = (byProducer[e.producer] ?? 0) + 1\n  const coverage: ExtractionCoverage = {\n    skippedFiles: errors.length,\n    byProducer,\n    files: errors.slice(0, HEALTH_FILE_SAMPLE).map((e) => e.file),\n    updatedAt: now,\n  }\n  await fs.mkdir(path.dirname(healthPath), { recursive: true })\n  await fs.writeFile(healthPath, JSON.stringify(coverage), 'utf8')\n}\n\n// Read the coverage sidecar. Returns undefined when absent or malformed —\n// discovery is convenience, never fatal, so a missing/garbled file just means\n// \"no recorded coverage,\" not an error.\nexport async function readExtractionHealth(\n  healthPath: string,\n): Promise<ExtractionCoverage | undefined> {\n  let raw: string\n  try {\n    raw = await fs.readFile(healthPath, 'utf8')\n  } catch {\n    return undefined\n  }\n  try {\n    const obj = JSON.parse(raw) as ExtractionCoverage\n    if (typeof obj?.skippedFiles !== 'number' || !obj.byProducer || !Array.isArray(obj.files)) {\n      return undefined\n    }\n    return obj\n  } catch {\n    return undefined\n  }\n}\n\n// ADR-065 — `NEAT_STRICT_EXTRACTION=1` makes any per-file extraction failure\n// cause the calling command to exit non-zero. Default is forgiving (banner\n// only). The check is at the caller (cli.ts / server.ts / watch.ts) so the\n// extraction phase itself stays library-shaped.\nexport function isStrictExtractionEnabled(): boolean {\n  const raw = process.env.NEAT_STRICT_EXTRACTION\n  return raw === '1' || raw === 'true'\n}\n\n// Format the unconditional summary banner. Zero errors is a positive signal\n// (\"0 files skipped\") so callers print this even on clean runs.\nexport function formatExtractionBanner(count: number): string {\n  if (count === 1) return `[neat] 1 file skipped due to parse errors`\n  return `[neat] ${count} files skipped due to parse errors`\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// ADR-066 — precision-floor drop accounting.\n//\n// EXTRACTED candidates whose graded confidence falls below\n// NEAT_EXTRACTED_PRECISION_FLOOR (default 0.7) are computed but never added\n// to the graph. The drop count surfaces on the extraction banner;\n// NEAT_EXTRACTED_REJECTED_LOG=1 routes the per-candidate detail to\n// `<projectDir>/neat-out/rejected.ndjson`. The default keeps the sidecar\n// surface quiet.\n// ─────────────────────────────────────────────────────────────────────────\n\nexport interface DroppedExtractedEdge {\n  source: string\n  target: string\n  type: string\n  confidence: number\n  confidenceKind: string\n  evidence: EdgeEvidence\n}\n\nconst droppedSink: DroppedExtractedEdge[] = []\n\nexport function noteExtractedDropped(edge: DroppedExtractedEdge): void {\n  droppedSink.push(edge)\n}\n\nexport function drainDroppedExtracted(): DroppedExtractedEdge[] {\n  return droppedSink.splice(0, droppedSink.length)\n}\n\nexport function pendingDroppedExtracted(): number {\n  return droppedSink.length\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n// #1258 — files read but deliberately not parsed.\n//\n// A minified bundle is machine output: thousands of one-character declarations\n// on a single line, each of which would mint a SymbolNode nobody can navigate\n// to. The file still exists in the graph — its FileNode is a true fact about\n// the repo — but nothing is extracted *from* it. Silently doing that would be\n// worse than the symbols, so the skip is counted and named the way a parse\n// error or a precision-floor drop is.\n\nexport interface SkippedSourceFile {\n  path: string\n  reason: 'minified'\n  detail: string\n}\n\n// Keyed by path, because every producer reads the tree separately: symbols,\n// calls, routes, imports, actions, zod and the edge builders each come through\n// `loadSourceFiles`, so one skipped file is noted once per producer. Counting\n// reads instead of files reported six minified files in a repo that had one.\nconst skippedSink = new Map<string, SkippedSourceFile>()\n\nexport function noteSkippedFile(file: SkippedSourceFile): void {\n  if (!skippedSink.has(file.path)) skippedSink.set(file.path, file)\n}\n\nexport function drainSkippedFiles(): SkippedSourceFile[] {\n  const out = [...skippedSink.values()]\n  skippedSink.clear()\n  return out\n}\n\nexport function pendingSkippedFiles(): number {\n  return skippedSink.size\n}\n\n// Silent on zero — unlike the parse banner, which reports a clean run as\n// evidence it ran. A repo with no minified files should say nothing about them.\nexport function formatSkippedBanner(count: number): string | null {\n  if (count <= 0) return null\n  if (count === 1) return `[neat] 1 minified file read but not parsed (FileNode kept, no symbols or calls)`\n  return `[neat] ${count} minified files read but not parsed (FileNodes kept, no symbols or calls)`\n}\n\nexport function isRejectedLogEnabled(): boolean {\n  const raw = process.env.NEAT_EXTRACTED_REJECTED_LOG\n  return raw === '1' || raw === 'true'\n}\n\nexport async function writeRejectedExtracted(\n  drops: DroppedExtractedEdge[],\n  rejectedPath: string,\n): Promise<void> {\n  if (drops.length === 0) return\n  await fs.mkdir(path.dirname(rejectedPath), { recursive: true })\n  const lines = drops.map((d) => JSON.stringify({ ...d, ts: new Date().toISOString() })).join('\\n') + '\\n'\n  await fs.appendFile(rejectedPath, lines, 'utf8')\n}\n\nexport function formatPrecisionFloorBanner(count: number): string {\n  if (count === 1) return `[neat] 1 extracted edge dropped below precision floor`\n  return `[neat] ${count} extracted edges dropped below precision floor`\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { EdgeEvidence, ExtractedConfidenceKind, FileNode, GraphEdge } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  fileId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { noteSkippedFile } from '../errors.js'\nimport { loadIgnoreChain, extendIgnoreChain, isIgnored, decide, type IgnoreChain } from '../gitignore.js'\nimport {\n  IGNORED_DIRS,\n  SERVICE_FILE_EXTENSIONS,\n  isNeatAuthoredSourceFile,\n  isPythonVenvDir,\n  type DiscoveredService,\n} from '../shared.js'\n\n// Host → owning ServiceNode id, the cross-service resolution the HTTP call-site\n// producers share (ADR-065 #5, ADR-119). A service is reachable by either its\n// directory basename or its manifest name; both map to the same node id. Reused\n// by http.ts (host-level CALLS edges) and route-match.ts (client↔route\n// matching) so the two producers resolve a URL's host to a service identically.\nexport interface ServiceHostIndex {\n  knownHosts: Set<string>\n  hostToNodeId: Map<string, string>\n}\n\nexport function buildServiceHostIndex(services: DiscoveredService[]): ServiceHostIndex {\n  const knownHosts = new Set<string>()\n  const hostToNodeId = new Map<string, string>()\n  for (const service of services) {\n    const base = path.basename(service.dir)\n    knownHosts.add(base)\n    knownHosts.add(service.pkg.name)\n    hostToNodeId.set(base, service.node.id)\n    hostToNodeId.set(service.pkg.name, service.node.id)\n  }\n  return { knownHosts, hostToNodeId }\n}\n\nexport interface SourceFile {\n  path: string\n  content: string\n}\n\nexport interface ExternalEndpoint {\n  // Stable id of the InfraNode this evidence implies. Format\n  // `infra:<kind>:<name>` so the orchestrator can dedupe across services.\n  infraId: string\n  // Display name on the InfraNode (e.g., \"orders\" for kafka-topic:orders).\n  name: string\n  kind: string\n  edgeType: 'CALLS' | 'PUBLISHES_TO' | 'CONSUMES_FROM'\n  evidence: EdgeEvidence\n  // Confidence grade per ADR-066 — set by the per-shape detector. The\n  // orchestrator (calls/index.ts) writes this onto the EXTRACTED edge and\n  // applies the precision floor before adding the edge to the graph.\n  confidenceKind: ExtractedConfidenceKind\n  // Declared schema columns for a `sql-table` endpoint (ADR-157 §3), at\n  // database-name fidelity. Set only by a schema-column producer (the Drizzle\n  // recognizer today); the orchestrator folds these onto the table node's\n  // `columns` list with EXTRACTED provenance. Absent on every other endpoint.\n  columns?: string[]\n  // Per-written-field SDK tags for a `firestore-collection` endpoint (ADR-167):\n  // which SDK (`client` = firebase/firestore, `admin` = firebase-admin/firestore)\n  // wrote each field. Set only by calls/firestore.ts; the orchestrator folds these\n  // onto the collection node's columns via `foldSdkWrites` (the parallel of the\n  // `columns` fold — `foldColumns` stays untouched). The write-SDK dimension is the\n  // seam the field-guard policy (ADR-169) joins on. Absent on every other endpoint.\n  sdkWrites?: Record<string, ('client' | 'admin')[]>\n}\n\n// A foreign-key relationship between two SQL tables (ADR-161) — the data-axis\n// sibling of a symbol INHERITS edge. `childTable` declares the FK, `parentTable`\n// is the referenced table; both are the DATABASE table name (the fusion key\n// `infra:sql-table:<name>` the column/table extractors and OTLP already target),\n// reproduced verbatim the way the ORM names the table, not the code model name.\n// A schema-FK producer (Drizzle / Prisma / SQLAlchemy) emits one per resolved\n// reference; a computed or unresolvable parent is left unclaimed (the producer\n// returns nothing), never guessed. `table-edges.ts` mints the EXTRACTED\n// `child ──REFERENCES──▶ parent` edge from these, with `evidence` pinned to the\n// FK declaration site.\nexport interface TableReference {\n  childTable: string\n  parentTable: string\n  evidence: EdgeEvidence\n}\n\n// ADR-200 — nearest-service-wins ownership. `excludeDirs` names the subtrees this\n// walk must not descend into: the dirs of other discovered services nested under\n// `dir`. Skipping the subtree at its root drops every file beneath it, so an\n// ancestor service never re-enumerates a nested service's source. Default empty —\n// a single-service or leaf walk is unchanged.\n// A gitignored path is absent from the graph, not present-but-unextracted\n// (#1255): the walk never yields it, so no FileNode is minted and no recogniser\n// runs over it. Directory-level pruning is how git thinks about it and the\n// cheaper shape — skipping `dist/` at its root costs one test, not one per file\n// underneath.\n// `extensions` defaults to the source languages; the flag-file walk (ADR-242)\n// passes `.json` to reuse the same gitignore-aware traversal.\nexport async function walkSourceFiles(\n  dir: string,\n  excludeDirs: string[] = [],\n  extensions: ReadonlySet<string> = SERVICE_FILE_EXTENSIONS,\n): Promise<string[]> {\n  const excluded = new Set(excludeDirs.map((d) => path.resolve(d)))\n  const out: string[] = []\n  // The rules governing `dir` itself: every `.gitignore` from the repo root\n  // down. A service nested in a monorepo inherits its ancestors' rules the same\n  // way it would on the command line.\n  const rootChain = await loadIgnoreChain(dir)\n  async function walk(current: string, inherited: IgnoreChain): Promise<void> {\n    const entries = await fs.readdir(current, { withFileTypes: true }).catch(() => [])\n    // This directory's own `.gitignore` governs everything below it. Reading the\n    // listing we already have beats probing for the file: a blind `readFile` per\n    // directory is a failed open on almost every one of them, and on a repo the\n    // size of this one that alone doubled the walk.\n    const chain = entries.some((e) => e.isFile() && e.name === '.gitignore')\n      ? await extendIgnoreChain(inherited, current)\n      : inherited\n    for (const entry of entries) {\n      const full = path.join(current, entry.name)\n      if (entry.isDirectory()) {\n        if (IGNORED_DIRS.has(entry.name)) continue\n        if (excluded.has(path.resolve(full))) continue\n        // `subtree` is the chain minus anything a deeper rule overrode for this\n        // directory, so a re-included dir isn't re-excluded file by file.\n        const verdict = decide(chain, full, true)\n        if (verdict.ignored) continue\n        if (await isPythonVenvDir(full)) continue\n        await walk(full, verdict.subtree)\n      } else if (\n        entry.isFile() &&\n        extensions.has(path.extname(entry.name)) &&\n        // Skip NEAT's own generated `otel-init.*` bootstrap — extracting it\n        // would attribute our instrumentation imports to the user's service.\n        !isNeatAuthoredSourceFile(entry.name) &&\n        !excluded.has(path.resolve(full)) &&\n        !isIgnored(chain, full, false)\n      ) {\n        out.push(full)\n      }\n    }\n  }\n  // `loadIgnoreChain` already includes `dir`'s own file, and `walk` would add it\n  // a second time from the listing — harmless but pointless, so start from the\n  // chain above it and let the walk pick `dir`'s up like every other directory.\n  await walk(dir, rootChain.filter((l) => path.resolve(l.dir) !== path.resolve(dir)))\n  return out\n}\n\n// Hand-written source does not put five thousand characters on one line.\n// Measured across this repo — 632 source files — the longest legitimate line is\n// 2,977 characters, an inline SVG path, and nothing else exceeds 3,000. A\n// minified chunk runs to 100,000+ on a single line. The threshold sits between\n// the two with room on both sides rather than at either edge (#1258).\nconst MINIFIED_LINE_CHARS = 5_000\n\n/** `*.min.js` and friends — the convention, checked before the content. */\nfunction hasMinifiedName(filePath: string): boolean {\n  return /\\.min\\.(js|mjs|cjs|jsx|ts|tsx)$/i.test(filePath)\n}\n\n/**\n * Is this machine output rather than something a person wrote?\n *\n * Two signals, either sufficient: the `.min.` naming convention, and a line too\n * long to have been typed. The line test is what catches an unnamed bundle —\n * `main-4f2a.js` under a build directory follows no convention at all — and is\n * measured without splitting the file, so a 200 KB one-liner costs one scan and\n * not a 200 KB array.\n */\nexport function isMinifiedSource(\n  filePath: string,\n  content: string,\n): { minified: boolean; detail: string } {\n  if (hasMinifiedName(filePath)) return { minified: true, detail: 'named *.min.js' }\n  let longest = 0\n  let start = 0\n  for (;;) {\n    const nl = content.indexOf('\\n', start)\n    const len = (nl === -1 ? content.length : nl) - start\n    if (len > longest) longest = len\n    if (nl === -1) break\n    start = nl + 1\n  }\n  if (longest > MINIFIED_LINE_CHARS) {\n    return { minified: true, detail: `longest line ${longest} chars` }\n  }\n  return { minified: false, detail: '' }\n}\n\n// The one place every producer reads file *contents* — symbols, calls, routes,\n// imports, actions, zod and the edge builders all come through here, while\n// `addFiles` takes paths from `walkSourceFiles`. So skipping a minified file\n// here leaves its FileNode standing, which is a true fact about the repo, and\n// stops anything being extracted from it. That is exactly the split #1258 asks\n// for, in one place rather than eleven.\nexport async function loadSourceFiles(\n  dir: string,\n  excludeDirs: string[] = [],\n): Promise<SourceFile[]> {\n  const paths = await walkSourceFiles(dir, excludeDirs)\n  const out: SourceFile[] = []\n  for (const p of paths) {\n    try {\n      const content = await fs.readFile(p, 'utf8')\n      const verdict = isMinifiedSource(p, content)\n      if (verdict.minified) {\n        noteSkippedFile({ path: p, reason: 'minified', detail: verdict.detail })\n        continue\n      }\n      out.push({ path: p, content })\n    } catch {\n      // unreadable, skip\n    }\n  }\n  return out\n}\n\n// Locate the line of the first occurrence of `needle` in `text`, 1-indexed.\n// Falls back to line 1 if the needle isn't found verbatim — better to point at\n// the file than to drop the evidence entirely.\nexport function lineOf(text: string, needle: string): number {\n  const idx = text.indexOf(needle)\n  if (idx < 0) return 1\n  return text.slice(0, idx).split('\\n').length\n}\n\n// static-extraction.md §evidence: `snippet?: string // small source fragment,\n// max ~120 chars`. The cap is the contract's, not a new rule — evidence is a\n// pointer to the source, and the source is already on disk at `file:line`.\n//\n// Uncapped, the snippet is the whole line, and one line is not bounded by\n// anything: a minified bundle can put a 227 KB file on a single line, and every\n// edge into that file then carries the entire file. A real repo reached 1,012 MB\n// of edges that way and the snapshot could not be written at all (#1254).\nconst SNIPPET_MAX_CHARS = 120\n\nexport function snippet(text: string, line: number): string {\n  const lines = text.split('\\n')\n  const raw = (lines[line - 1] ?? '').trim()\n  if (raw.length <= SNIPPET_MAX_CHARS) return raw\n  // Say it was cut and by how much, so a reader can tell a truncated fragment\n  // from a genuinely short line — and spot a minified file for what it is.\n  return `${raw.slice(0, SNIPPET_MAX_CHARS)}… (+${raw.length - SNIPPET_MAX_CHARS} chars)`\n}\n\n// Forward-slash a path so a FileNode id is byte-stable across platforms (the\n// `relPath` segment of `file:<service>:<relPath>` must not vary by OS).\nexport function toPosix(p: string): string {\n  return p.split('\\\\').join('/')\n}\n\n// Extension → language tag for a FileNode. Returns undefined for extensions we\n// don't name rather than guessing — evidence is never fabricated (§6).\nexport function languageForPath(relPath: string): string | undefined {\n  switch (path.extname(relPath).toLowerCase()) {\n    case '.py':\n      return 'python'\n    case '.go':\n      return 'go'\n    case '.rb':\n      return 'ruby'\n    case '.php':\n      return 'php'\n    case '.cs':\n      return 'csharp'\n    case '.java':\n      return 'java'\n    case '.kt':\n      return 'kotlin'\n    case '.rs':\n      return 'rust'\n    case '.cpp':\n    case '.cc':\n    case '.cxx':\n    case '.c++':\n    case '.hpp':\n    case '.hh':\n    case '.hxx':\n    case '.h++':\n      return 'cpp'\n    case '.ts':\n    case '.tsx':\n      return 'typescript'\n    case '.js':\n    case '.jsx':\n    case '.mjs':\n    case '.cjs':\n      return 'javascript'\n    default:\n      return undefined\n  }\n}\n\n// File-first emission (file-awareness.md §1–2). Ensure the FileNode for\n// `relPath` and the owning `service ──CONTAINS──▶ file` edge both exist, then\n// return the FileNode id so the caller can originate a relationship from it.\n// `relPath` must already be service-relative and forward-slashed (use toPosix).\n// CONTAINS is structural ownership — graded at the 'structural' tier like\n// CONFIGURED_BY, never a flat value. Idempotent: re-running extraction over an\n// unchanged file is a no-op.\n/**\n * What this pass is extracting FROM (ADR-233) — a token that outlives the\n * directory being read: the bound repo hosted, the project name locally.\n *\n * Pass-scoped module state, like the ignore chain and the skipped-file sink in\n * this file. `extractFromDirectory` sets it at the start of a pass and clears it\n * at the end, so every producer stamps the same source without threading an\n * argument through all of them. Unset means no source was named, and the retire\n * sweep then behaves exactly as it always has.\n */\nlet currentSource: string | undefined\n\nexport function setExtractionSource(source: string | undefined): void {\n  currentSource = source\n}\n\nexport function extractionSource(): string | undefined {\n  return currentSource\n}\n\nexport function ensureFileNode(\n  graph: NeatGraph,\n  serviceName: string,\n  serviceNodeId: string,\n  relPath: string,\n): { fileNodeId: string; nodesAdded: number; edgesAdded: number } {\n  let nodesAdded = 0\n  let edgesAdded = 0\n  const fileNodeId = fileId(serviceName, relPath)\n  if (!graph.hasNode(fileNodeId)) {\n    const language = languageForPath(relPath)\n    const node: FileNode = {\n      id: fileNodeId,\n      type: NodeType.FileNode,\n      service: serviceName,\n      path: relPath,\n      ...(language ? { language } : {}),\n      ...(currentSource ? { source: currentSource } : {}),\n      discoveredVia: 'static',\n    }\n    graph.addNode(fileNodeId, node)\n    nodesAdded++\n  } else if (currentSource) {\n    // A file this pass just read belongs to this pass's source, whoever minted\n    // the node — a snapshot restored from before sources existed, or a repo\n    // re-bound under a different name. Claiming it here is what keeps the next\n    // pass from reading it as another source's and leaving it untouched forever.\n    const existing = graph.getNodeAttributes(fileNodeId) as FileNode\n    if (existing.source !== currentSource) {\n      graph.replaceNodeAttributes(fileNodeId, { ...existing, source: currentSource })\n    }\n  }\n  const containsId = extractedEdgeId(serviceNodeId, fileNodeId, EdgeType.CONTAINS)\n  if (!graph.hasEdge(containsId)) {\n    const edge: GraphEdge = {\n      id: containsId,\n      source: serviceNodeId,\n      target: fileNodeId,\n      type: EdgeType.CONTAINS,\n      provenance: Provenance.EXTRACTED,\n      confidence: confidenceForExtracted('structural'),\n      evidence: { file: relPath },\n    }\n    graph.addEdgeWithKey(containsId, serviceNodeId, fileNodeId, edge)\n    edgesAdded++\n  }\n  return { fileNodeId, nodesAdded, edgesAdded }\n}\n","// `.gitignore`, the way git reads it: the file in every directory from the repo\n// root down to the one being walked, with a deeper file able to override a\n// shallower one.\n//\n// Service discovery honoured the root `.gitignore` and file enumeration honoured\n// nothing (#1255), so a gitignored directory was skipped when looking for\n// services and then walked in full when collecting one service's files. A built\n// bundle under an ignored path came into the graph as first-party source, and\n// the first anyone knew was a snapshot too large to write (#1254).\n//\n// Root *and* nested matters for the shape NEAT is usually pointed at: a monorepo\n// whose packages carry their own `.gitignore`, and a service directory that sits\n// well below the repo root. Walking up to the repo root is what makes an\n// ancestor's rules apply to a service nested under it, with no scan-root\n// plumbing through `addFiles` → `walkSourceFiles`.\n\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport ignore, { type Ignore } from 'ignore'\n\n/** One `.gitignore`, and the directory its patterns are relative to. */\nexport interface IgnoreLayer {\n  dir: string\n  ig: Ignore\n}\n\n/** Layers outermost first — the order git resolves them in. */\nexport type IgnoreChain = readonly IgnoreLayer[]\n\n// One process-lifetime cache of \"what does this directory's .gitignore say\".\n// The walk asks per directory, and a miss is a failed `readFile`; without this\n// a deep tree pays that on every descent. `null` records \"no file here\", which\n// is the common answer and worth remembering too.\nconst LAYER_CACHE = new Map<string, IgnoreLayer | null>()\n\n/** Reset between scans in tests; the cache is keyed by absolute path. */\nexport function clearIgnoreCache(): void {\n  LAYER_CACHE.clear()\n}\n\nasync function layerFor(dir: string): Promise<IgnoreLayer | null> {\n  const cached = LAYER_CACHE.get(dir)\n  if (cached !== undefined) return cached\n  let layer: IgnoreLayer | null = null\n  try {\n    const raw = await fs.readFile(path.join(dir, '.gitignore'), 'utf8')\n    layer = { dir, ig: ignore().add(raw) }\n  } catch {\n    layer = null\n  }\n  LAYER_CACHE.set(dir, layer)\n  return layer\n}\n\nasync function isRepoRoot(dir: string): Promise<boolean> {\n  try {\n    // `.git` is a directory in a normal clone and a file in a worktree or\n    // submodule, so existence is the test, not `isDirectory()`.\n    await fs.stat(path.join(dir, '.git'))\n    return true\n  } catch {\n    return false\n  }\n}\n\n/**\n * The chain governing `startDir`: every `.gitignore` from the repo root down to\n * it, outermost first.\n *\n * Stops at the directory holding `.git`, or at the filesystem root when there\n * isn't one — a scan of a plain directory still honours whatever `.gitignore`\n * files it contains, and never climbs into a parent project that has nothing to\n * do with it.\n */\nexport async function loadIgnoreChain(startDir: string): Promise<IgnoreChain> {\n  const dirs: string[] = []\n  let current = path.resolve(startDir)\n  for (;;) {\n    dirs.push(current)\n    if (await isRepoRoot(current)) break\n    const parent = path.dirname(current)\n    if (parent === current) break\n    current = parent\n  }\n  dirs.reverse() // outermost first\n  const layers: IgnoreLayer[] = []\n  for (const dir of dirs) {\n    const layer = await layerFor(dir)\n    if (layer) layers.push(layer)\n  }\n  return layers\n}\n\n/** The chain plus `dir`'s own `.gitignore`, if it has one. */\nexport async function extendIgnoreChain(chain: IgnoreChain, dir: string): Promise<IgnoreChain> {\n  const layer = await layerFor(path.resolve(dir))\n  return layer ? [...chain, layer] : chain\n}\n\n/**\n * Whether git would ignore this path.\n *\n * Layers are applied outermost first so a deeper `.gitignore` can re-include\n * something an ancestor excluded — `ignore`'s `test()` reports an explicit\n * un-ignore, which a plain boolean `ignores()` cannot. A path outside a layer's\n * directory is not that layer's business and is skipped.\n */\nexport function isIgnored(chain: IgnoreChain, fullPath: string, isDir: boolean): boolean {\n  return decide(chain, fullPath, isDir).ignored\n}\n\n/**\n * The verdict, plus the chain that governs this path's subtree.\n *\n * git prunes at the directory: an excluded directory is never descended into, so\n * a pattern like `build/` excludes what's underneath by never looking rather\n * than by matching each file. That distinction is load-bearing once a deeper\n * `.gitignore` re-includes such a directory — git then walks it, and the\n * ancestor's `build/` does not apply to the files inside, because it matches a\n * directory named `build` and not `build/keep.js`. Testing each file against the\n * whole chain independently would re-exclude them and quietly lose the\n * re-include, so a layer that explicitly un-ignores a directory also ends the\n * reach of everything above it for that subtree.\n */\nexport function decide(\n  chain: IgnoreChain,\n  fullPath: string,\n  isDir: boolean,\n): { ignored: boolean; subtree: IgnoreChain } {\n  if (chain.length === 0) return { ignored: false, subtree: chain }\n  const abs = path.resolve(fullPath)\n  let ignored = false\n  let unignoredAt = -1\n  for (let i = 0; i < chain.length; i++) {\n    const layer = chain[i]!\n    const rel = path.relative(layer.dir, abs)\n    // A path outside this layer's directory is not its business.\n    if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) continue\n    // Trailing slash so a directory pattern (`dist/`) matches; `ignore`\n    // distinguishes the file and directory tests.\n    const candidate = rel.split(path.sep).join('/') + (isDir ? '/' : '')\n    const result = layer.ig.test(candidate)\n    if (result.ignored) ignored = true\n    else if (result.unignored) {\n      ignored = false\n      unignoredAt = i\n    }\n  }\n  return {\n    ignored,\n    subtree: unignoredAt >= 0 ? chain.slice(unignoredAt) : chain,\n  }\n}\n","import { promises as fs } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport git from 'isomorphic-git'\nimport type { SecurityCard, SecurityDiff, SecurityDiffEntry, ServiceNode } from '@neat.is/types'\nimport { NodeType } from '@neat.is/types'\nimport { inventoryFromGraph, loadAdvisorySnapshot, matchAdvisories } from './advisories/index.js'\nimport type { InventoryItem } from './advisories/index.js'\nimport { extractFromDirectory } from './extract.js'\nimport { makeGraph, type NeatGraph } from './graph.js'\nimport { buildSecurityCards, rankSecurityCards, reconcileDepFixActions } from './security-card.js'\n\n// scan_diff (security-card.md §6): the known vulnerabilities a change introduced,\n// removed and left in place. It is the check behind \"the fix removed the CVE and\n// introduced none\": the PR gate and a remediation run both read it.\n//\n// Both sides are judged against ONE advisory snapshot, loaded for the union of\n// their inventories, so every difference comes from the change, never from the\n// feed moving between two scans. The diff itself is pure.\n\ntype Side = 'before' | 'after'\n\nconst keyOf = (c: SecurityCard) =>\n  [c.advisory.id, c.dependency.ecosystem, c.dependency.name, c.service].join('\\u0000')\n\nfunction entry(before: SecurityCard | undefined, after: SecurityCard | undefined): SecurityDiffEntry {\n  const c = (after ?? before)!\n  return {\n    advisoryId: c.advisory.id,\n    ecosystem: c.dependency.ecosystem,\n    package: c.dependency.name,\n    service: c.service,\n    before: before ?? null,\n    after: after ?? null,\n  }\n}\n\n// Ranked by the card that matters for the bucket (the after side for what's\n// there now, the before side for what went), so the most exposed comes first.\nfunction ordered(entries: SecurityDiffEntry[], side: Side): SecurityDiffEntry[] {\n  const pick = (e: SecurityDiffEntry) => (side === 'after' ? (e.after ?? e.before) : (e.before ?? e.after))!\n  const rank = new Map(rankSecurityCards(entries.map(pick)).map((c, i) => [c.id, i]))\n  return entries.sort((a, b) => rank.get(pick(a).id)! - rank.get(pick(b).id)!)\n}\n\n/**\n * The before/after comparison of two sets of cards. An advisory, package and\n * service is one entry whatever the version on each side; with several versions\n * of a package in one service, the most exposed card stands for it.\n *\n * - `introduced`: a finding after (`imported` or above) that wasn't one before,\n *   including a package that was only in the lockfile and is now imported.\n * - `removed`: a finding before that isn't one after, whether the package went,\n *   moved to an unaffected version, or is no longer imported.\n * - `stillPresent`: a finding on both sides.\n * - `context`: matches that are only in the lockfile, appearing or going.\n */\nexport function diffSecurityCards(before: SecurityCard[], after: SecurityCard[]): Omit<\n  SecurityDiff,\n  'advisories' | 'asOf' | 'stale' | 'errors' | 'base' | 'head'\n> {\n  const best = (cards: SecurityCard[]) => {\n    const m = new Map<string, SecurityCard>()\n    for (const c of rankSecurityCards(cards)) if (!m.has(keyOf(c))) m.set(keyOf(c), c)\n    return m\n  }\n  const b = best(before)\n  const a = best(after)\n  const finding = (c: SecurityCard | undefined) => !!c && c.reachability.level !== 'present'\n\n  const introduced: SecurityDiffEntry[] = []\n  const removed: SecurityDiffEntry[] = []\n  const stillPresent: SecurityDiffEntry[] = []\n  const ctxIntroduced: SecurityDiffEntry[] = []\n  const ctxRemoved: SecurityDiffEntry[] = []\n  for (const key of new Set([...b.keys(), ...a.keys()])) {\n    const [x, y] = [b.get(key), a.get(key)]\n    if (finding(x) && finding(y)) stillPresent.push(entry(x, y))\n    else if (finding(y)) introduced.push(entry(x, y))\n    else if (finding(x)) removed.push(entry(x, y))\n    else if (y && !x) ctxIntroduced.push(entry(x, y))\n    else if (x && !y) ctxRemoved.push(entry(x, y))\n  }\n  return {\n    introduced: ordered(introduced, 'after'),\n    removed: ordered(removed, 'before'),\n    stillPresent: ordered(stillPresent, 'after'),\n    context: { introduced: ordered(ctxIntroduced, 'after'), removed: ordered(ctxRemoved, 'before') },\n  }\n}\n\nexport interface ScanDiffOptions {\n  fetchImpl?: typeof fetch\n  env?: NodeJS.ProcessEnv\n  now?: () => number\n  // Only this service (its name or its node id).\n  service?: string\n}\n\nfunction serviceName(graph: NeatGraph, service: string): string {\n  if (graph.hasNode(service)) {\n    const node = graph.getNodeAttributes(service) as ServiceNode\n    if (node.type === NodeType.ServiceNode) return node.name\n  }\n  return service\n}\n\n/** The comparison of two already-extracted graphs, judged against one snapshot. */\nexport async function scanDiffGraphs(\n  before: NeatGraph,\n  after: NeatGraph,\n  refs: { base: string; head: string },\n  opts: ScanDiffOptions = {},\n): Promise<SecurityDiff> {\n  const invB = inventoryFromGraph(before)\n  const invA = inventoryFromGraph(after)\n  const union = new Map<string, InventoryItem>()\n  for (const i of [...invB, ...invA]) union.set(i.dependencyId, i)\n  const loaded = await loadAdvisorySnapshot([...union.values()], opts)\n  const head = {\n    advisories: loaded.source,\n    stale: loaded.stale,\n    errors: loaded.errors,\n    base: { ref: refs.base, inventory: invB.length },\n    head: { ref: refs.head, inventory: invA.length },\n  }\n  if (!loaded.snapshot) {\n    return { ...head, asOf: null, introduced: [], removed: [], stillPresent: [], context: { introduced: [], removed: [] } }\n  }\n  const snapshot = loaded.snapshot\n  const cardsOf = (graph: NeatGraph, inv: InventoryItem[]) => {\n    const want = opts.service ? serviceName(graph, opts.service) : undefined\n    // One fix target per dependency across its advisories, as scanProjectCves\n    // gives it, so a diff and a scan never suggest different bumps for one package.\n    return reconcileDepFixActions(matchAdvisories(inv, snapshot).flatMap((m) => buildSecurityCards(graph, m, snapshot)), snapshot)\n      .filter((c) => !want || c.service === want)\n  }\n  return { ...head, asOf: snapshot.asOf, ...diffSecurityCards(cardsOf(before, invB), cardsOf(after, invA)) }\n}\n\nconst MAX_BLOB_BYTES = 2 * 1024 * 1024\n\n// Where a checkout's git data is. A linked worktree (`git worktree add`) has a\n// `.git` FILE naming its own gitdir, which holds its HEAD; its objects and refs\n// live in the main repository's common dir. isomorphic-git reads one gitdir, so\n// HEAD is read by hand there and everything else from the common dir.\ninterface Repo {\n  gitdir: string\n  headFile: string\n}\n\nasync function openRepo(root: string): Promise<Repo> {\n  const dotGit = path.join(root, '.git')\n  const st = await fs.stat(dotGit)\n  if (st.isDirectory()) return { gitdir: dotGit, headFile: path.join(dotGit, 'HEAD') }\n  const m = /^gitdir:\\s*(.+)$/m.exec(await fs.readFile(dotGit, 'utf8'))\n  if (!m) throw new Error(`${dotGit} is not a git directory or a gitdir pointer`)\n  const own = path.resolve(root, m[1]!.trim())\n  let common = own\n  try {\n    common = path.resolve(own, (await fs.readFile(path.join(own, 'commondir'), 'utf8')).trim())\n  } catch {\n    // no commondir: a submodule-style pointer, the gitdir is complete\n  }\n  return { gitdir: common, headFile: path.join(own, 'HEAD') }\n}\n\nasync function resolveName(repo: Repo, name: string): Promise<string> {\n  if (name === 'HEAD') {\n    const head = (await fs.readFile(repo.headFile, 'utf8')).trim()\n    const ref = /^ref:\\s*(.+)$/.exec(head)\n    return ref ? git.resolveRef({ fs, gitdir: repo.gitdir, ref: ref[1]! }) : head\n  }\n  return git.resolveRef({ fs, gitdir: repo.gitdir, ref: name }).catch(() => git.expandOid({ fs, gitdir: repo.gitdir, oid: name }))\n}\n\n/**\n * A commit for a ref name, a full or short sha, or either followed by `~N` /\n * `^` (first parents), the forms a PR or an agent writes: `main`, `HEAD~1`,\n * `abc123^`. isomorphic-git resolves names and shas but not the suffixes.\n */\nexport async function resolveRevision(repoRoot: string, rev: string): Promise<string> {\n  return resolveIn(await openRepo(repoRoot), rev)\n}\n\nasync function resolveIn(repo: Repo, rev: string): Promise<string> {\n  const m = /^(.*?)((?:~\\d*|\\^)*)$/.exec(rev.trim())!\n  const name = m[1]!\n  const suffix = m[2] ?? ''\n  if (!name) throw new Error(`not a revision: ${rev}`)\n  let oid = await resolveName(repo, name)\n  let back = 0\n  for (const step of suffix.match(/~\\d*|\\^/g) ?? []) back += step === '^' || step === '~' ? 1 : Number(step.slice(1))\n  for (let i = 0; i < back; i++) {\n    const { commit } = await git.readCommit({ fs, gitdir: repo.gitdir, oid })\n    const parent = commit.parent[0]\n    if (!parent) throw new Error(`${rev}: ${name} has fewer than ${back} ancestors`)\n    oid = parent\n  }\n  return oid\n}\n\n/**\n * Write the tree of `ref` under `subdir` of the repository at `repoRoot` into\n * `outDir`, from the local object store (no network). Blobs over 2MB are left\n * out; extraction doesn't read them.\n */\nexport async function materializeRef(repoRoot: string, ref: string, subdir: string, outDir: string): Promise<void> {\n  const repo = await openRepo(repoRoot)\n  const oid = await resolveIn(repo, ref)\n  const prefix = subdir ? `${subdir.split(path.sep).join('/')}/` : ''\n  await git.walk({\n    fs,\n    gitdir: repo.gitdir,\n    trees: [git.TREE({ ref: oid })],\n    map: async (filepath, [entry]) => {\n      if (!entry || filepath === '.') return true\n      // Only descend into the scan root's own subtree.\n      if (prefix && !(filepath + '/').startsWith(prefix) && !prefix.startsWith(filepath + '/')) return null\n      if ((await entry.type()) !== 'blob') return true\n      if (prefix && !filepath.startsWith(prefix)) return null\n      const content = await entry.content()\n      if (!content || content.byteLength > MAX_BLOB_BYTES) return null\n      const dest = path.join(outDir, ...filepath.slice(prefix.length).split('/'))\n      await fs.mkdir(path.dirname(dest), { recursive: true })\n      await fs.writeFile(dest, content)\n      return null\n    },\n  })\n}\n\n/**\n * scan_diff on a local checkout: `base` (a ref or commit) against `head` (a ref\n * or commit, or the working tree when omitted). Each side is extracted into its\n * own scratch graph, never the project's. The scratch copies take the scan\n * root's directory name, so a service named after its directory (a nameless\n * package.json) is the same service on both sides.\n */\nexport async function scanDiffLocal(\n  scanPath: string,\n  refs: { base: string; head?: string },\n  opts: ScanDiffOptions & { tmpRoot?: string } = {},\n): Promise<SecurityDiff> {\n  const repoRoot = await git.findRoot({ fs, filepath: path.resolve(scanPath) })\n  const subdir = path.relative(repoRoot, path.resolve(scanPath))\n  const tmp = await fs.mkdtemp(path.join(opts.tmpRoot ?? os.tmpdir(), 'neat-scan-diff-'))\n  const name = path.basename(path.resolve(scanPath))\n  try {\n    const baseDir = path.join(tmp, 'base', name)\n    await materializeRef(repoRoot, refs.base, subdir, baseDir)\n    let headDir = path.resolve(scanPath)\n    if (refs.head) {\n      headDir = path.join(tmp, 'head', name)\n      await materializeRef(repoRoot, refs.head, subdir, headDir)\n    }\n    const before = makeGraph()\n    const after = makeGraph()\n    await extractFromDirectory(before, baseDir, { announce: false })\n    await extractFromDirectory(after, headDir, { announce: false })\n    return await scanDiffGraphs(before, after, { base: refs.base, head: refs.head ?? 'working tree' }, opts)\n  } finally {\n    await fs.rm(tmp, { recursive: true, force: true })\n  }\n}\n","export { extractFromDirectory, type ExtractResult } from './extract/index.js'\n","// Static-extraction pipeline. Phase order is load-bearing:\n//   services → aliases → databases (+ compat) → configs → routes → grpc → calls → infra → frontier promotion.\n//   Routes precede calls so the cross-service matcher (ADR-119) sees the full\n//   RouteNode table when it resolves client call sites to server routes. gRPC\n//   `.proto` extraction (ADR-123) mints the method nodes an OBSERVED span fuses onto.\n//\n// Contract anchors (see /docs/contracts.md):\n//   * Rule 1 — Every emitted edge carries Provenance.EXTRACTED from @neat.is/types.\n//   * Rule 2 — EXTRACTED edges use the plain `${type}:src->tgt` id pattern.\n//     Never write under the OBSERVED id pattern; that's ingest.ts's territory.\n//   * Rule 5 — Nodes/edges constructed against schemas in @neat.is/types; no\n//     local interface redefinitions in this tree.\n//   * Rule 8 — No demo-name hardcoding. Driver names come from package.json\n//     dependencies; engine names from compat.json via compatPairs().\n//   * Rule 14 — ConfigNodes record file existence only; never the contents.\nimport type { NeatGraph } from '../graph.js'\nimport { DEFAULT_PROJECT } from '../graph.js'\nimport { promoteFrontierNodes } from '../ingest.js'\nimport { ensureCompatLoaded } from '../compat.js'\nimport { emitNeatEvent } from '../events.js'\nimport { addServiceNodes, discoverServices } from './services.js'\nimport { addServiceAliases } from './aliases.js'\nimport { addFiles } from './files.js'\nimport { addSymbols } from './symbols.js'\nimport { addSymbolEdges } from './symbol-edges.js'\nimport { addGoSymbolEdges } from './go-symbol-edges.js'\nimport { addJavaSymbolEdges } from './java-symbol-edges.js'\nimport { addImports } from './imports.js'\nimport { addServerActions } from './actions.js'\nimport { addDatabasesAndCompat } from './databases/index.js'\nimport { addConfigNodes } from './configs.js'\nimport { addFlagStores } from './flags.js'\nimport { addRoutes } from './routes.js'\nimport { addJavaRoutes } from './java-routes.js'\nimport { addTornadoRoutes } from './tornado-routes.js'\nimport { addGatewayRoutes } from './java-gateway.js'\nimport { addGrpcMethods } from './proto.js'\nimport { addCallEdges } from './calls/index.js'\nimport { addJavaCallEdges } from './java-calls.js'\nimport { addTableEdges } from './table-edges.js'\nimport { addInfra } from './infra/index.js'\nimport { addZodShapes } from './zod-shapes.js'\nimport { addFirestoreRules } from './firestore-rules.js'\nimport { addDependencies } from './dependencies/index.js'\nimport { addDependencyImports } from './dependencies/imports-to-deps.js'\nimport {\n  drainExtractionErrors,\n  writeExtractionErrors,\n  writeExtractionHealth,\n  extractionHealthPathFor,\n  drainDroppedExtracted,\n  drainSkippedFiles,\n  type SkippedSourceFile,\n  isRejectedLogEnabled,\n  writeRejectedExtracted,\n  type ExtractionError,\n  type DroppedExtractedEdge,\n} from './errors.js'\nimport path from 'node:path'\nimport { retireExtractedEdgesByMissingFile } from './retire.js'\nimport { setExtractionSource } from './calls/shared.js'\nimport {\n  beginSourceExtraction,\n  finishSourceExtraction,\n  invalidateSourceBaseline,\n  type SourceCommit,\n} from './source-baseline.js'\n\nexport interface ExtractResult {\n  nodesAdded: number\n  edgesAdded: number\n  frontiersPromoted: number\n  // ADR-065 — per-file extraction failures collected during the pass.\n  // `extractionErrors` is the count; `errorEntries` is the drained list,\n  // available for callers that want to surface per-file context. Both are\n  // present on every pass (zero is observable as a positive signal).\n  extractionErrors: number\n  errorEntries: ExtractionError[]\n  // #140 — count of EXTRACTED edges retired this pass because their\n  // evidence.file no longer exists on disk. Zero on a clean pass; non-zero\n  // means the snapshot was carrying ghosts from deleted source.\n  ghostsRetired: number\n  // #1258 — files read but deliberately not parsed (minified machine output).\n  // Their FileNodes stand; nothing was extracted from them. Counted so the skip\n  // is visible rather than silent.\n  skippedFiles: number\n  skippedEntries: SkippedSourceFile[]\n  // ADR-066 — count of EXTRACTED candidates dropped at emit time because\n  // their graded confidence fell below NEAT_EXTRACTED_PRECISION_FLOOR.\n  // Always reported (zero is observable). Detail entries surface in\n  // `droppedEntries` and route to rejected.ndjson when\n  // NEAT_EXTRACTED_REJECTED_LOG=1.\n  extractedDropped: number\n  droppedEntries: DroppedExtractedEdge[]\n}\n\nexport interface ExtractOptions {\n  // Actual resolved Git HEAD of the hosted clone this pass reads. Evidence\n  // only when its repository is this pass's `source`. Never inferred from a\n  // branch name or restored from a snapshot.\n  sourceCommit?: SourceCommit\n  // Post-extract policy trigger (ADR-043). Awaited after frontier promotion\n  // so policies see the final post-pass graph state. Daemons wire this to\n  // evaluateAllPolicies + PolicyViolationsLog.append.\n  onPolicyTrigger?: (graph: NeatGraph) => Promise<void> | void\n  // Project tag for the extraction-complete event (ADR-051). Defaults to\n  // DEFAULT_PROJECT when omitted.\n  project?: string\n  // ADR-065 — when set, drained extraction errors are appended to this\n  // path as ndjson with `source: 'extract'`. Daemons / `neat init` /\n  // `neat watch` wire this to `<projectDir>/neat-out/errors.ndjson`. When\n  // omitted, errors are still drained and returned in the result, just\n  // not persisted.\n  errorsPath?: string\n  // What this pass is extracting FROM (ADR-233) — a token that outlives the\n  // directory being read: `owner/name` for a bound repo on a hosted daemon, the\n  // project name locally. The retire sweep uses it to stay inside its own\n  // source, so a project with two bound repos stops having each pass retire the\n  // other's files (#1294) and a boot pass over a source-less root stops\n  // retiring the restored layer (#1291).\n  //\n  // Omitted means no source is named, and every sweep behaves exactly as it did\n  // before — which is what keeps a single-source local daemon unchanged.\n  source?: string\n  // Emit the `extraction-complete` event (ADR-051). Default true. A pass into a\n  // scratch graph that belongs to no project (pr-verdict.ts) turns it off, so\n  // subscribers don't see a completed extraction for a project that didn't have one.\n  announce?: boolean\n}\n\n// Extraction passes run one at a time, process-wide. A pass's working state is\n// module-level, not per call: the error, dropped-edge and skipped-file sinks it\n// drains, and the source it stamps on every FileNode it mints (ADR-233). Two\n// passes interleaving would drain each other's errors into the wrong project's\n// log and stamp one pass's FileNodes with the other's source — or with none,\n// which puts them outside every sourced retire sweep for good. A hosted daemon\n// runs passes from more than one place (boot, repo-sync, the PR verdict), so\n// overlap is real, not theoretical. The cost is that passes queue.\nlet passQueue: Promise<unknown> = Promise.resolve()\n\nexport function extractFromDirectory(\n  graph: NeatGraph,\n  scanPath: string,\n  opts: ExtractOptions = {},\n): Promise<ExtractResult> {\n  // Old evidence stops counting the moment another pass is asked for. The pass\n  // itself begins only when its turn comes: one waiting in the queue overlaps\n  // nothing, so it must not leave the running pass's successor conflicted (#1331).\n  invalidateSourceBaseline(graph, opts.source, 'syncing')\n  const pass = passQueue.then(async () => {\n    const sourceGeneration = beginSourceExtraction(graph, opts.source, opts.sourceCommit)\n    let result: ExtractResult | undefined\n    try {\n      result = await runExtractionPass(graph, scanPath, opts)\n      return result\n    } finally {\n      finishSourceExtraction(graph, sourceGeneration, opts.source, opts.sourceCommit,\n        result ?? { extractionErrors: 1, skippedFiles: 0 })\n    }\n  })\n  passQueue = pass.catch(() => {})\n  return pass\n}\n\nasync function runExtractionPass(\n  graph: NeatGraph,\n  scanPath: string,\n  opts: ExtractOptions,\n): Promise<ExtractResult> {\n  await ensureCompatLoaded()\n  // Clear any stale entries from a prior pass (the producer-side sink is\n  // process-local). Per ADR-065, every pass collects its own errors; we drain\n  // again at the end to capture this pass's failures.\n  drainExtractionErrors()\n  drainSkippedFiles()\n  // Pass-scoped, like the error and skipped-file sinks above: every FileNode\n  // this pass mints is stamped with it, and it is cleared before returning so a\n  // later pass that names no source can't inherit this one's (ADR-233).\n  setExtractionSource(opts.source)\n\n  const services = await discoverServices(scanPath)\n\n  const phase1Nodes = addServiceNodes(graph, services)\n  await addServiceAliases(graph, scanPath, services)\n  const fileEnum = await addFiles(graph, services)\n  // Symbol nodes under files (ADR-158). Runs after addFiles so the FileNodes it\n  // hangs symbols off already exist; before calls so a future Phase-2 symbol→\n  // symbol CALLS producer has the symbol inventory to resolve against.\n  const symbolEnum = await addSymbols(graph, services)\n  const importGraph = await addImports(graph, services)\n  // Static symbol edges (ADR-158 §3). Runs after addSymbols (the inventory it\n  // resolves targets against) and after addImports (so the import graph is in\n  // place). Confident heritage + call edges only, symbol→symbol, never guessed.\n  const symbolEdges = await addSymbolEdges(graph, services)\n  // Go symbol→symbol CALLS (ADR-158 §3, the Go rung symbol-edges.ts names as a\n  // follow-on). A separate producer because Go's AST node types and its absent\n  // ES-import resolver don't ride the JS/TS walker; same precision discipline,\n  // same-file resolution only. Runs after addSymbols (the inventory it resolves against).\n  const goSymbolEdges = await addGoSymbolEdges(graph, services)\n  // Java symbol→symbol CALLS, the same rung for Java: same-file, unambiguous only.\n  const javaSymbolEdges = await addJavaSymbolEdges(graph, services)\n  // Next.js Server Actions (ADR-168). Runs after addImports so its client-stitch\n  // can resolve an imported action binding through the same import graph. Mints a\n  // ServerActionNode per exported `\"use server\"` function (owned by its file via\n  // CONTAINS) and a `file ──CALLS──▶ action` edge on any client reference. Gated\n  // on the `next` dependency; a no-op for every other service.\n  const actionPhase = await addServerActions(graph, services)\n  const phase2 = await addDatabasesAndCompat(graph, services, scanPath)\n  const phase3 = await addConfigNodes(graph, services, scanPath)\n  // Flag grain (ADR-242): the committed flag definitions and the code that reads\n  // each key, onto one flag-store node per provider.\n  const flagPhase = await addFlagStores(graph, services, scanPath)\n  // Route extraction (ADR-119) runs before calls so the RouteNodes exist when\n  // addCallEdges' cross-service matcher (route-match.ts) looks them up.\n  const routePhase = await addRoutes(graph, services)\n  // Spring MVC routes (Java), the same RouteNode shape from annotations; before\n  // calls for the same reason.\n  const javaRoutePhase = await addJavaRoutes(graph, services)\n  // Tornado's literal handler table (Python), same RouteNode shape.\n  const tornadoRoutePhase = await addTornadoRoutes(graph, services)\n  // Spring Cloud Gateway's routing table (config as a source): gateway routes and\n  // the config file's CALLS to each routed service.\n  const gatewayPhase = await addGatewayRoutes(graph, services)\n  // gRPC `.proto` service/method extraction (ADR-123). Independent of the call\n  // phase — it reads the proto contract surface, not JS/TS call sites — and mints\n  // the same method nodes an OBSERVED gRPC span lands on, so declared and observed\n  // methods fuse.\n  const grpcPhase = await addGrpcMethods(graph, services, scanPath)\n  const phase4 = await addCallEdges(graph, services)\n  // Java RestTemplate / WebClient calls, after routes so a call can land on the\n  // RouteNode it names.\n  const javaCallPhase = await addJavaCallEdges(graph, services)\n  // Foreign-key table→table edges (ADR-161). Runs after addCallEdges so the\n  // column/table read has already minted both endpoints' `infra:sql-table:<name>`\n  // InfraNodes; it mints the `child ──REFERENCES──▶ parent` edges the data-axis\n  // traversal walks. The data-axis sibling of symbol-edges (ADR-158 §3).\n  const tableEdges = await addTableEdges(graph, services)\n  const phase5 = await addInfra(graph, scanPath, services)\n  // Zod declared shapes (ADR-170). A standalone, self-contained phase (it reads\n  // its own files, gated per service on the `zod` dep) minting an\n  // `infra:zod-schema:<name>` InfraNode + EXTRACTED columns per top-level\n  // `z.object` / `z.enum` literal. Independent of the other phases — it neither\n  // reads nor mutates their nodes — so order is not load-bearing; it runs here,\n  // after infra, before the ghost-retire sweep so its file-relative edges are\n  // dropped like any other producer's when their source disappears.\n  const zodPhase = await addZodShapes(graph, services)\n  // Dependency inventory (ADR-274): each service's lockfile becomes DependencyNodes\n  // and service→dep DEPENDS_ON edges. Self-contained: it reads only lockfiles and\n  // manifests, and every first-party query skips the layer it builds.\n  const depPhase = await addDependencies(graph, services, scanPath)\n  // First-party imports of those packages (dependency-inventory.md §4): file→dep\n  // IMPORTS edges, matched against the DependencyNodes addDependencies just minted.\n  const depImportPhase = await addDependencyImports(graph, services, scanPath)\n  // firestore.rules guard sets (ADR-169). A standalone phase — not a calls\n  // producer — that reads each service's checked-in `firestore.rules` and folds\n  // `guardedFields` onto the `firestore-collection` InfraNodes the F1 recognizer\n  // (ADR-167) mints in the calls phase, so it must run after addCallEdges. It\n  // adds no nodes or edges (it only enriches existing nodes), and is inert until\n  // firestore-collection nodes exist.\n  const firestoreRulesPhase = await addFirestoreRules(graph, services)\n  // #140 — drop EXTRACTED edges whose evidence.file no longer exists on disk.\n  // Catches the deleted-file ghost case for the full-pass entry point\n  // (init / daemon bootstrap). The edited-file case is handled per-mtime by\n  // watch.ts's `retireEdgesByFile`. Service dirs are passed alongside scanPath\n  // because CALLS-family producers store service-dir-relative paths while\n  // configs / databases / infra store scanPath-relative.\n  //\n  // A pass that found no source retires nothing (#1291). The sweep reads a\n  // file's absence under this scan root as the file being gone, which only\n  // holds when the root is where the graph's source lives. A root with no\n  // service in it — a hosted tenant's data directory before its repos are\n  // synced, a checkout that isn't mounted yet — says nothing about the files a\n  // loaded snapshot describes, and sweeping against it would empty the graph's\n  // whole EXTRACTED layer.\n  const ghostsRetired =\n    services.length === 0\n      ? 0\n      : retireExtractedEdgesByMissingFile(\n          graph,\n          scanPath,\n          services.map((s) => s.dir),\n          opts.source,\n        )\n  const frontiersPromoted = promoteFrontierNodes(graph)\n\n  // Post-extract policy trigger (ADR-043). Fires after frontier promotion so\n  // policies see the post-pass graph (including any FRONTIER → OBSERVED edge\n  // upgrades that just landed).\n  if (opts.onPolicyTrigger) await opts.onPolicyTrigger(graph)\n\n  // ADR-065 — drain the per-file extraction errors collected during the pass.\n  // If a sidecar path was supplied, append the entries; otherwise return them\n  // for the caller to surface.\n  const errorEntries = drainExtractionErrors()\n  if (opts.errorsPath && errorEntries.length > 0) {\n    try {\n      await writeExtractionErrors(errorEntries, opts.errorsPath)\n    } catch (err) {\n      console.warn(\n        `[neat] failed to write extraction errors to ${opts.errorsPath}: ${(err as Error).message}`,\n      )\n    }\n  }\n  // #883 — overwrite the coverage sidecar every pass (even zero, to clear a\n  // prior gap) so a daemon can put this pass's skipped-file count on /health.\n  // errors.ndjson is append-only and can't answer \"is the current graph\n  // complete?\"; this can. Best-effort — a failed write never fails extraction.\n  if (opts.errorsPath) {\n    try {\n      await writeExtractionHealth(errorEntries, extractionHealthPathFor(opts.errorsPath))\n    } catch (err) {\n      console.warn(\n        `[neat] failed to write extraction health sidecar: ${(err as Error).message}`,\n      )\n    }\n  }\n\n  // ADR-066 — drain the precision-floor drops. Always returned; only\n  // persisted when NEAT_EXTRACTED_REJECTED_LOG=1 (opt-in to keep the\n  // default sidecar surface quiet).\n  const droppedEntries = drainDroppedExtracted()\n  const skippedEntries = drainSkippedFiles()\n  if (\n    isRejectedLogEnabled() &&\n    opts.errorsPath &&\n    droppedEntries.length > 0\n  ) {\n    // rejected.ndjson lives alongside errors.ndjson under neat-out/. Derive\n    // from errorsPath rather than re-plumbing a new option.\n    const rejectedPath = path.join(path.dirname(opts.errorsPath), 'rejected.ndjson')\n    try {\n      await writeRejectedExtracted(droppedEntries, rejectedPath)\n    } catch (err) {\n      console.warn(\n        `[neat] failed to write rejected extracted edges to ${rejectedPath}: ${(err as Error).message}`,\n      )\n    }\n  }\n\n  // Every producer and the sweep have run; nothing below mints a FileNode. A\n  // pass always sets this on entry, so a leak could never reach the next one —\n  // clearing it just keeps the module's state honest between passes (ADR-233).\n  setExtractionSource(undefined)\n\n  const result: ExtractResult = {\n    nodesAdded:\n      phase1Nodes +\n      fileEnum.nodesAdded +\n      symbolEnum.nodesAdded +\n      importGraph.nodesAdded +\n      symbolEdges.nodesAdded +\n      goSymbolEdges.nodesAdded +\n      javaSymbolEdges.nodesAdded +\n      actionPhase.nodesAdded +\n      phase2.nodesAdded +\n      phase3.nodesAdded +\n      flagPhase.nodesAdded +\n      routePhase.nodesAdded +\n      javaRoutePhase.nodesAdded +\n      tornadoRoutePhase.nodesAdded +\n      gatewayPhase.nodesAdded +\n      grpcPhase.nodesAdded +\n      phase4.nodesAdded +\n      javaCallPhase.nodesAdded +\n      tableEdges.nodesAdded +\n      phase5.nodesAdded +\n      zodPhase.nodesAdded +\n      depPhase.nodesAdded +\n      firestoreRulesPhase.nodesAdded,\n    edgesAdded:\n      fileEnum.edgesAdded +\n      symbolEnum.edgesAdded +\n      importGraph.edgesAdded +\n      symbolEdges.edgesAdded +\n      goSymbolEdges.edgesAdded +\n      javaSymbolEdges.edgesAdded +\n      actionPhase.edgesAdded +\n      phase2.edgesAdded +\n      phase3.edgesAdded +\n      flagPhase.edgesAdded +\n      routePhase.edgesAdded +\n      javaRoutePhase.edgesAdded +\n      tornadoRoutePhase.edgesAdded +\n      gatewayPhase.edgesAdded +\n      grpcPhase.edgesAdded +\n      phase4.edgesAdded +\n      javaCallPhase.edgesAdded +\n      tableEdges.edgesAdded +\n      phase5.edgesAdded +\n      zodPhase.edgesAdded +\n      depPhase.edgesAdded +\n      depImportPhase.edgesAdded +\n      firestoreRulesPhase.edgesAdded,\n    frontiersPromoted,\n    extractionErrors: errorEntries.length,\n    errorEntries,\n    ghostsRetired,\n    extractedDropped: droppedEntries.length,\n    droppedEntries,\n    skippedFiles: skippedEntries.length,\n    skippedEntries,\n  }\n\n  // extraction-complete (ADR-051). fileCount is the number of services\n  // discovered — the closest proxy we have for \"how much source did this\n  // pass touch\" without a per-phase file accountant.\n  if (opts.announce !== false) emitNeatEvent({\n    type: 'extraction-complete',\n    project: opts.project ?? DEFAULT_PROJECT,\n    payload: {\n      project: opts.project ?? DEFAULT_PROJECT,\n      fileCount: services.length,\n      nodesAdded: result.nodesAdded,\n      edgesAdded: result.edgesAdded,\n    },\n  })\n\n  return result\n}\n","import GraphDefault from 'graphology'\nimport type { MultiDirectedGraph as MDGType } from 'graphology'\nimport type { GraphEdge, GraphNode } from '@neat.is/types'\n\n// graphology ships as a CJS bundle that does `module.exports = Graph` with\n// the other constructors attached as properties (`Graph.MultiDirectedGraph =\n// ...`). cjs-module-lexer can't see through that attachment, so a named\n// import like `import { MultiDirectedGraph } from 'graphology'` fails under\n// strict Node ESM (Node 22+ via tsx in particular). Pull the constructor off\n// the default export instead — same shape under tsx and tsup-bundled output.\ntype MultiDirectedGraphCtor = typeof MDGType\nconst MultiDirectedGraph: MultiDirectedGraphCtor = (\n  GraphDefault as unknown as { MultiDirectedGraph: MultiDirectedGraphCtor }\n).MultiDirectedGraph\n\n// Multi because two nodes can have edges of different types simultaneously\n// (e.g. CALLS and DEPENDS_ON between the same pair of services).\nexport type NeatGraph = MDGType<GraphNode, GraphEdge>\n\nexport const DEFAULT_PROJECT = 'default'\n\n// One graph per project. The map is the source of truth; getGraph() with no\n// arg or with 'default' hits the legacy single-project path so existing\n// callers keep working byte-for-byte (ADR-026).\nconst graphs = new Map<string, NeatGraph>()\n\n// A graph that belongs to no project — scratch space for a one-off extraction\n// (pr-verdict.ts) that must never be reachable through getGraph().\nexport function makeGraph(): NeatGraph {\n  return new MultiDirectedGraph<GraphNode, GraphEdge>({ allowSelfLoops: false })\n}\n\nexport function getGraph(project: string = DEFAULT_PROJECT): NeatGraph {\n  let g = graphs.get(project)\n  if (!g) {\n    g = makeGraph()\n    graphs.set(project, g)\n  }\n  return g\n}\n\nexport function hasProject(project: string): boolean {\n  return graphs.has(project)\n}\n\nexport function listProjects(): string[] {\n  return [...graphs.keys()].sort()\n}\n\n// Reset a single project, or all of them when the arg is omitted. Tests use\n// the no-arg form between cases; runtime never calls it.\nexport function resetGraph(project?: string): void {\n  if (project === undefined) {\n    graphs.clear()\n    return\n  }\n  graphs.delete(project)\n}\n","import { promises as fs, existsSync, readFileSync } from 'node:fs'\nimport path from 'node:path'\nimport { isIP } from 'node:net'\nimport { appendRuntimeIncident } from './durable-incident.js'\nimport * as sourceMapJs from 'source-map-js'\nimport type {\n  DatabaseNode,\n  ErrorEvent,\n  FileNode,\n  FrontierNode,\n  GraphEdge,\n  GraphNode,\n  GraphQLOperationNode,\n  GrpcMethodNode,\n  InfraNode,\n  Policy,\n  ServiceNode,\n  StaleEvent,\n  SymbolNode,\n  WebSocketChannelNode,\n} from '@neat.is/types'\nimport type { PersistedGraph } from './persist.js'\nimport type { EvaluationContext as PolicyEvaluationContext } from './policy.js'\nimport { canPromoteFrontier } from './policy.js'\nimport {\n  EdgeType,\n  GraphEdgeSchema,\n  GraphNodeSchema,\n  NodeType,\n  Provenance,\n  confidenceForObservedSignal,\n  databaseId,\n  localDatabaseId,\n  extractedEdgeId,\n  fileId,\n  frontierId,\n  graphqlOperationId,\n  grpcMethodId,\n  incidentKindOf,\n  inferredEdgeId,\n  infraId,\n  observedEdgeId,\n  frontierEdgeId,\n  serviceId,\n  symbolId,\n  websocketChannelId,\n  type EdgeErrorExemplar,\n  type EdgeTypeValue,\n  type FlagDefinition,\n  type ProvenanceValue,\n  type RouteNode,\n  type DeployContext,\n  type ObservedDeployContext,\n} from '@neat.is/types'\nimport { normalizePathTemplate } from './extract/routes.js'\nimport { invalidateSourceBaseline } from './extract/source-baseline.js'\nimport { knownDatastoreEngine } from './extract/infra/shared.js'\nimport { foldColumns, OBSERVED_COLUMN_CONFIDENCE } from './columns.js'\nimport { FLAG_STORE_KIND, foldObservedFlags, foldObservedVariant } from './flags.js'\nimport { recordLatency, latencyPercentiles } from './latency-digest.js'\nimport type { NeatGraph } from './graph.js'\nimport { DEFAULT_PROJECT } from './graph.js'\nimport type { AttributeValue, FlagEvaluation, ParsedSpan } from './otel.js'\nimport { emitNeatEvent } from './events.js'\nimport { deepestApplicationFrame } from './stacktrace.js'\nimport { sanitizeAttributes, scrubIncidentEvent } from './credential-scrub.js'\n\n// Maps OTel spans to graph signal:\n//   * Cross-service span → upsert CALLS edge.\n//   * Database span (db.system attr present) → upsert CONNECTS_TO edge to a\n//     DatabaseNode resolved by host, or a service-scoped local DatabaseNode when\n//     the span carries no peer host (an in-process / embedded DB, ADR-118).\n//   * Span with status.code === 2 → ErrorEvent appended to errors.ndjson.\n//\n// Contract anchors (see /docs/contracts.md):\n//   * Rule 1 — Provenance: every edge here carries Provenance.X from @neat.is/types.\n//   * Rule 2 — Coexistence: OBSERVED edges live alongside EXTRACTED ones with a\n//     distinct id pattern (`${type}:OBSERVED:src->tgt`). Never write OBSERVED\n//     under the EXTRACTED id; that erases the gap NEAT exists to surface.\n//   * Rule 4 — Per-edge-type staleness (ADR-024): STALE_THRESHOLDS_BY_EDGE_TYPE\n//     governs decay; never hardcode a flat 24h threshold.\n//   * Rule 8 — No demo names: derive driver/engine identifiers from node\n//     properties, not literals.\n\nexport interface IngestContext {\n  graph: NeatGraph\n  errorsPath: string\n  // Absolute scan root the daemon is watching for this project. When set, a\n  // runtime `code.filepath` is made service-root-relative against it before the\n  // FileNode is keyed (file-awareness.md §4) — the service's absolute root is\n  // `scanPath/<repoPath>`, which recovers `dist/foo.js` even for a single-\n  // package service whose `repoPath` is empty (issue #430). Omitted by ad-hoc\n  // callers and most tests, which rely on the repoPath-segment anchor instead.\n  scanPath?: string\n  // Project name for event-bus routing (ADR-051). Defaults to DEFAULT_PROJECT\n  // when omitted — keeps single-project tests / scripts wire-compatible.\n  project?: string\n  now?: () => number\n  // Set to false when the receiver already wrote the ErrorEvent synchronously\n  // (production daemons via watch.ts wire this). When true or omitted, handleSpan\n  // appends the ErrorEvent itself — the path used by ad-hoc scripts and tests\n  // that don't go through buildOtelReceiver. ADR-033 §Error events.\n  writeErrorEventInline?: boolean\n  // Post-mutation policy trigger (ADR-043). Fires after handleSpan finishes\n  // and the queue is drained. Daemons wire this to evaluateAllPolicies +\n  // PolicyViolationsLog.append. Ad-hoc callers leave it undefined; their tests\n  // don't need policy side effects.\n  onPolicyTrigger?: (graph: NeatGraph) => Promise<void> | void\n  // 4xx-burst coalescing state, keyed by `${source}->${peer}` (issue #481).\n  // Lazily created the first time handleSpan sees a 4xx CLIENT/PRODUCER span.\n  // Carried on the context so each project/daemon keeps its own bursts and a\n  // long-lived handler accumulates across spans; ad-hoc callers reuse one ctx\n  // across a batch and get the same coalescing.\n  burstState?: Map<string, BurstState>\n}\n\nconst HOUR_MS = 60 * 60 * 1000\nconst DAY_MS = 24 * HOUR_MS\n\n// Per-edge-type stale thresholds. HTTP CALLS at 24h is meaningless because\n// healthy traffic recurs in seconds; infra DEPENDS_ON is the opposite — a\n// docker-compose service can sit idle overnight without anything being wrong.\n// Override via NEAT_STALE_THRESHOLDS (JSON, ms-per-edge-type).\nconst DEFAULT_STALE_THRESHOLDS: Record<string, number> = {\n  CALLS: HOUR_MS,\n  CONNECTS_TO: 4 * HOUR_MS,\n  PUBLISHES_TO: 4 * HOUR_MS,\n  CONSUMES_FROM: 4 * HOUR_MS,\n  DEPENDS_ON: DAY_MS,\n  CONFIGURED_BY: DAY_MS,\n  RUNS_ON: DAY_MS,\n}\n// Fallback for any edge type not in the map (forward compat — adding a new\n// EdgeType shouldn't break staleness sweeps).\nconst FALLBACK_STALE_THRESHOLD_MS = DAY_MS\n\nfunction loadStaleThresholdsFromEnv(): Record<string, number> {\n  const raw = process.env.NEAT_STALE_THRESHOLDS\n  if (!raw) return DEFAULT_STALE_THRESHOLDS\n  try {\n    const overrides = JSON.parse(raw) as Record<string, unknown>\n    const merged = { ...DEFAULT_STALE_THRESHOLDS }\n    for (const [k, v] of Object.entries(overrides)) {\n      if (typeof v === 'number' && Number.isFinite(v) && v >= 0) merged[k] = v\n    }\n    return merged\n  } catch (err) {\n    console.warn(\n      `[neat] NEAT_STALE_THRESHOLDS could not be parsed (${(err as Error).message}); using defaults`,\n    )\n    return DEFAULT_STALE_THRESHOLDS\n  }\n}\n\nexport function thresholdForEdgeType(\n  edgeType: string,\n  overrides?: Record<string, number>,\n): number {\n  const map = overrides ?? loadStaleThresholdsFromEnv()\n  return map[edgeType] ?? FALLBACK_STALE_THRESHOLD_MS\n}\n\n// Failing-response incident tuning. A span that completes 5xx, carries an\n// ERROR status, or an exception event records an incident on its own — those\n// are unambiguous failures. A 4xx CLIENT/PRODUCER span doesn't: a single 404 is\n// often correct app behavior (auth probe, conditional fetch). 4xx becomes a\n// signal only when it repeats — N consecutive 4xx against the same (source,\n// peer) pair inside a window record ONE coalesced incident carrying the count\n// and the dominant status code, rather than N separate lines that would drown\n// the history. Mirrors the NEAT_STALE_THRESHOLDS override shape.\n//   threshold — how many consecutive 4xx against one peer trip the burst.\n//   windowMs  — the gap that ends a burst; a 4xx more than this after the\n//               previous one starts a fresh burst rather than extending it.\nconst DEFAULT_INCIDENT_THRESHOLDS = {\n  threshold: 5,\n  windowMs: 60_000,\n}\n\nfunction loadIncidentThresholdsFromEnv(): { threshold: number; windowMs: number } {\n  const raw = process.env.NEAT_INCIDENT_THRESHOLDS\n  if (!raw) return DEFAULT_INCIDENT_THRESHOLDS\n  try {\n    const overrides = JSON.parse(raw) as Record<string, unknown>\n    const merged = { ...DEFAULT_INCIDENT_THRESHOLDS }\n    if (\n      typeof overrides.threshold === 'number' &&\n      Number.isFinite(overrides.threshold) &&\n      overrides.threshold >= 1\n    ) {\n      merged.threshold = Math.floor(overrides.threshold)\n    }\n    if (\n      typeof overrides.windowMs === 'number' &&\n      Number.isFinite(overrides.windowMs) &&\n      overrides.windowMs >= 0\n    ) {\n      merged.windowMs = overrides.windowMs\n    }\n    return merged\n  } catch (err) {\n    console.warn(\n      `[neat] NEAT_INCIDENT_THRESHOLDS could not be parsed (${(err as Error).message}); using defaults`,\n    )\n    return DEFAULT_INCIDENT_THRESHOLDS\n  }\n}\n\n// ── Streaming / long-lived span guard for the latency digest (ADR-208) ────────\n// `latencyMs: { p50, p95 }` is a per-request measurement (ADR-190). A streaming\n// or otherwise long-lived span carries a duration equal to the whole stream's\n// lifetime — not a per-request latency — so folding it into the per-edge latency\n// histogram (latency-digest.ts) poisons p95 and false-fires the saturation\n// classifier (traverse.ts `SATURATION_P95_MS`, ADR-189): flagd's gRPC\n// server-stream `EventStream` ran ~10 minutes and read as a 606208ms inbound p95,\n// which steered `get_root_cause` to a phantom \"load-generator overloads\n// everything\" verdict. The guard withholds these spans from the latency feed\n// only — spanCount, errorCount, and lastObserved still record like any other\n// observation, and no other edge property is touched.\n//\n// Span-shape signals come first, because they name the stream directly:\n//   • WebSocket upgrade span — the upgrade span lives for the whole connection\n//     (otel-ingest.md §WebSocket channels); `websocketChannel` is already parsed.\n//   • Server-Sent Events — an SSE response streams for its whole lifetime and\n//     names itself `content-type: text/event-stream` on the response header,\n//     when the HTTP instrumentation captured response headers.\n// A duration ceiling is the documented fallback: the base gRPC semconv carries no\n// streaming marker NEAT parses — a bidi / server-streaming RPC looks like a unary\n// one on the wire but for its per-message span events — so a span longer than the\n// ceiling is treated as long-lived. This is what catches flagd's `EventStream`.\n// Override via NEAT_LATENCY_STREAM_CEILING_MS (a positive number of ms).\nconst DEFAULT_LATENCY_STREAM_CEILING_MS = 60_000\n\nfunction latencyStreamCeilingMs(): number {\n  const raw = process.env.NEAT_LATENCY_STREAM_CEILING_MS\n  if (!raw) return DEFAULT_LATENCY_STREAM_CEILING_MS\n  const n = Number(raw)\n  if (Number.isFinite(n) && n > 0) return n\n  console.warn(\n    `[neat] NEAT_LATENCY_STREAM_CEILING_MS could not be parsed (${raw}); using default`,\n  )\n  return DEFAULT_LATENCY_STREAM_CEILING_MS\n}\n\n// True when a captured response header names the SSE content type\n// (`text/event-stream`). OTel HTTP instrumentation records captured response\n// headers as `http.response.header.<name>`; SDKs differ on whether the header\n// name keeps its dash or normalises it to `_`, and the value can arrive as a\n// string or a single-element array — read both spellings and both shapes,\n// honestly absent otherwise.\nfunction spanServesEventStream(attrs: Record<string, AttributeValue>): boolean {\n  for (const key of [\n    'http.response.header.content-type',\n    'http.response.header.content_type',\n  ]) {\n    const v = attrs[key]\n    const values = Array.isArray(v) ? v : v !== undefined && v !== null ? [v] : []\n    for (const item of values) {\n      if (typeof item === 'string' && item.toLowerCase().includes('text/event-stream')) {\n        return true\n      }\n    }\n  }\n  return false\n}\n\n// A span whose duration is the whole stream's lifetime rather than a per-request\n// latency. Such a span is kept out of the latency digest only (ADR-208) — every\n// other part of its signal records normally.\nexport function spanIsStreaming(\n  span: ParsedSpan,\n  ceilingMs = latencyStreamCeilingMs(),\n): boolean {\n  if (span.websocketChannel !== undefined) return true\n  if (spanServesEventStream(span.attributes)) return true\n  // More than one message each way is a stream, however short it lived (ADR-272).\n  if ((span.messageEventCount ?? 0) > 2) return true\n  // durationNanos is a bigint; compare in nanos so no float round-trip is needed.\n  return span.durationNanos > BigInt(Math.round(ceilingMs)) * 1_000_000n\n}\n\n// When a method is first found to stream, the latency already recorded from its\n// earlier, shorter streams (cut off before the ceiling) is not a per-request\n// latency either. The digest is aggregated, so those samples can't be picked out:\n// clear the latency on the edges that carried the method — callers' edges into it,\n// its serving CONTAINS, and those callers' service-level edges to its owner — and\n// let them rebuild from calls that are not streams. Counts, errors and\n// lastObserved are untouched (ADR-272).\nfunction clearStreamLatency(graph: NeatGraph, methodId: string): void {\n  const clear = (edgeId: string): void => {\n    const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n    if (!e.signal || (e.signal.latencyHist === undefined && e.signal.latencyMs === undefined)) return\n    const { latencyHist: _h, latencyMs: _m, ...rest } = e.signal\n    graph.mergeEdgeAttributes(edgeId, { signal: rest })\n  }\n  const owners = new Set<string>()\n  for (const id of graph.inboundEdges(methodId)) {\n    const e = graph.getEdgeAttributes(id) as GraphEdge\n    if (e.type === EdgeType.CONTAINS) {\n      owners.add(e.source)\n      clear(id)\n    }\n  }\n  for (const id of graph.inboundEdges(methodId)) {\n    const e = graph.getEdgeAttributes(id) as GraphEdge\n    if (e.type !== EdgeType.CALLS) continue\n    clear(id)\n    for (const owner of owners) {\n      for (const sid of graph.edges(e.source, owner)) {\n        if ((graph.getEdgeAttributes(sid) as GraphEdge).type === EdgeType.CALLS) clear(sid)\n      }\n    }\n  }\n}\n\n/**\n * The span is part of a stream (ADR-272): it shows one itself (spanIsStreaming),\n * or its gRPC method is known to stream, from its `.proto` or an earlier span. A\n * stream cut short (a reset at 25 s, under the ceiling, from a client that records\n * no message events) is still a stream, so it is judged by its method, not by its\n * own duration. A span that shows a stream marks its method, OBSERVED.\n */\nexport function spanStreams(graph: NeatGraph, span: ParsedSpan, ceilingMs?: number): boolean {\n  const mid = span.rpcService && span.rpcMethod ? grpcMethodId(span.rpcService, span.rpcMethod) : undefined\n  if (spanIsStreaming(span, ceilingMs)) {\n    if (mid && graph.hasNode(mid) && (graph.getNodeAttributes(mid) as { streaming?: boolean }).streaming !== true) {\n      graph.mergeNodeAttributes(mid, { streaming: true })\n      clearStreamLatency(graph, mid)\n    }\n    return true\n  }\n  return mid !== undefined && graph.hasNode(mid) && (graph.getNodeAttributes(mid) as { streaming?: boolean }).streaming === true\n}\n\n// An attribute bag — either a live span's `attributes` or the passthrough set a\n// recorded ErrorEvent carries. The message helpers read from both, so the same\n// \"what failed here\" logic that names an incident at record time can re-derive\n// it at read time (dedupeIncidents).\ntype AttrBag = Record<string, unknown>\n\n// Read the HTTP response status off an attribute bag. OTel semconv renamed this\n// attribute — modern SDKs write `http.response.status_code`, older ones\n// `http.status_code`. Returns undefined when neither is present or parseable, so\n// a span with no response status is never misclassified as a failure.\nfunction httpResponseStatusFromAttrs(attrs: AttrBag): number | undefined {\n  for (const key of ['http.response.status_code', 'http.status_code']) {\n    const v = attrs[key]\n    if (typeof v === 'number' && Number.isFinite(v)) return v\n    if (typeof v === 'string') {\n      const n = Number(v)\n      if (Number.isFinite(n)) return n\n    }\n  }\n  return undefined\n}\n\nfunction httpResponseStatus(span: ParsedSpan): number | undefined {\n  return httpResponseStatusFromAttrs(span.attributes)\n}\n\n// A human incident line built from the HTTP context a server span carries even\n// when no exception event was recorded — an Express error handler that answers\n// 500 cleanly leaves `span.exception` empty but still carries the route and\n// status. \"500 on GET /users/:id\" reads better than the literal 'unknown\n// error'. Returns undefined when the bag has no usable HTTP context, so a\n// non-HTTP failure falls through to nonHttpFailureMessage / 'unknown error'.\n// Method/route follow the OTel semconv rename (modern `http.request.method` /\n// legacy `http.method`; `http.route` matched template, `http.target` / `url.path`\n// concrete-path fallback).\nfunction httpFailureMessageFromAttrs(attrs: AttrBag): string | undefined {\n  const status = httpResponseStatusFromAttrs(attrs)\n  const route = pickAttrFrom(attrs, 'http.route', 'http.target', 'url.path')\n  const method = pickAttrFrom(attrs, 'http.request.method', 'http.method')\n  const where = route ? `${method ? `${method} ` : ''}${route}` : undefined\n  if (status !== undefined && where) return `${status} on ${where}`\n  if (status !== undefined) return `HTTP ${status}`\n  if (where) return `error on ${where}`\n  return undefined\n}\n\n// Canonical gRPC status code → name (grpc/status.proto). Fixed protocol\n// constants shared by every gRPC implementation — not driver/engine data, so\n// they don't belong in compat.json (Rule 8 governs the latter, not a wire enum).\nconst GRPC_STATUS_NAMES: Record<number, string> = {\n  1: 'CANCELLED',\n  2: 'UNKNOWN',\n  3: 'INVALID_ARGUMENT',\n  4: 'DEADLINE_EXCEEDED',\n  5: 'NOT_FOUND',\n  6: 'ALREADY_EXISTS',\n  7: 'PERMISSION_DENIED',\n  8: 'RESOURCE_EXHAUSTED',\n  9: 'FAILED_PRECONDITION',\n  10: 'ABORTED',\n  11: 'OUT_OF_RANGE',\n  12: 'UNIMPLEMENTED',\n  13: 'INTERNAL',\n  14: 'UNAVAILABLE',\n  15: 'DATA_LOSS',\n  16: 'UNAUTHENTICATED',\n}\n\nfunction grpcStatusCodeFromAttrs(attrs: AttrBag): number | undefined {\n  const v = attrs['rpc.grpc.status_code']\n  if (typeof v === 'number' && Number.isFinite(v)) return v\n  if (typeof v === 'string') {\n    const n = Number(v)\n    if (Number.isFinite(n)) return n\n  }\n  return undefined\n}\n\n// What counts as an OBSERVED error on a span — the boolean that increments an\n// edge's `errorCount`, the signal get_root_cause roots its failing-CALLS chain\n// on (ADR-209). Span status ERROR is the explicit marker, but most gRPC and HTTP\n// microservice SDKs leave the span status UNSET and put the outcome in an\n// attribute instead (issue #1065): a non-OK gRPC status (`rpc.grpc.status_code`\n// != 0; 0 is OK) or an HTTP 5xx server response. Reading all three keeps a\n// gRPC-based stack's failures from being invisible to RCA — a status-only gate\n// recorded zero errors on an otel-demo `checkout` whose 3,349 failing spans were\n// all `rpc.grpc.status_code=13` with UNSET status, so RCA had nothing to root on.\n// HTTP 4xx is deliberately excluded here: a client error is not the callee\n// failing, and a 4xx run is coalesced into its own incident separately\n// (advance4xxBurst) rather than counted as an edge error.\nfunction spanRecordsError(span: ParsedSpan): boolean {\n  if (span.statusCode === 2) return true\n  const grpc = grpcStatusCodeFromAttrs(span.attributes)\n  if (grpc !== undefined && grpc !== 0) return true\n  const httpStatus = httpResponseStatusFromAttrs(span.attributes)\n  if (httpStatus !== undefined && httpStatus >= 500) return true\n  return false\n}\n\n// A non-HTTP failure still carries its cause in span attributes — a non-OK gRPC\n// status, or a transport-level connection error (ECONNREFUSED reaching a peer).\n// Reading them keeps the incident from degrading to the literal 'unknown error'\n// when the span has no exception event and no HTTP response code. Returns\n// undefined for a span carrying neither, so the 'unknown error' floor still\n// applies to a genuinely opaque failure (issue #624).\nfunction nonHttpFailureMessageFromAttrs(attrs: AttrBag): string | undefined {\n  const grpc = grpcStatusCodeFromAttrs(attrs)\n  if (grpc !== undefined && grpc !== 0) {\n    const name = GRPC_STATUS_NAMES[grpc] ?? `status ${grpc}`\n    const detail = pickAttrFrom(attrs, 'rpc.grpc.status_message')\n    return detail ? `gRPC ${name}: ${detail}` : `gRPC ${name}`\n  }\n  // Transport/connection failure — OTel's `error.type` carries the errno\n  // (ECONNREFUSED, ETIMEDOUT, …) or the exception class for a call that never\n  // got a response. Skip the HTTP status-class forms (\"500\", \"_OTHER\") that\n  // http semconv also writes there; the HTTP path above owns those.\n  const errType = pickAttrFrom(attrs, 'error.type')\n  if (errType && errType !== '_OTHER' && !/^\\d+$/.test(errType)) {\n    const peer = pickAttrFrom(attrs, 'server.address', 'net.peer.name', 'net.host.name')\n    return peer ? `${errType} connecting to ${peer}` : errType\n  }\n  return undefined\n}\n\n// The incident's human message: the recorded exception first, then the HTTP\n// context a server span still carries, then a non-HTTP (gRPC / connection)\n// failure read from attributes, and only then the 'unknown error' floor. Shared\n// by every incident write path so the fallback chain can't drift between the\n// receiver's synchronous write and handleSpan's inline write.\nfunction incidentMessage(span: ParsedSpan): string {\n  return (\n    span.exception?.message ??\n    httpFailureMessageFromAttrs(span.attributes) ??\n    nonHttpFailureMessageFromAttrs(span.attributes) ??\n    'unknown error'\n  )\n}\n\n// In-flight 4xx burst against one (source, peer) pair. Lives on IngestContext so\n// it survives across spans without leaking into module state shared by every\n// project. firstTs/lastTs are the span timestamps (ADR-033 — span time, not\n// wall clock); codes counts each 4xx by status so the dominant one can be named\n// when the burst flushes.\ninterface BurstState {\n  count: number\n  firstTs: string\n  lastTs: string\n  lastMs: number\n  codes: Map<number, number>\n}\n\nfunction nowIso(ctx: IngestContext): string {\n  return new Date(ctx.now ? ctx.now() : Date.now()).toISOString()\n}\n\n// One-time-per-session-per-project warning for spans whose resource omits\n// `service.name`. The OTel spec requires SDKs to set it; customised exporters\n// occasionally don't. Routing the span to `service:unidentified` keeps\n// diagnostic visibility intact (silent drop hides a real SDK misconfiguration);\n// the warning gives an operator one line of stderr per project to act on.\n// See docs/contracts/otlp-routing.md §Fallback when `resource.service.name`\n// is missing.\nconst unidentifiedWarnedProjects = new Set<string>()\nfunction warnUnidentifiedSpan(project: string): void {\n  if (unidentifiedWarnedProjects.has(project)) return\n  unidentifiedWarnedProjects.add(project)\n  console.warn(\n    `[neatd] span lacked service.name; routed to 'unidentified' in project ${project}; check your OTel SDK config.`,\n  )\n}\n\n// Test seam — production code never calls this. Tests that exercise the\n// once-per-session contract reset between cases so each assertion sees a\n// fresh warned-set.\nexport function resetUnidentifiedSpanWarnings(): void {\n  unidentifiedWarnedProjects.clear()\n}\n\n// One-time-per-session-per-service audit for a compiled `dist/...js` call site\n// that carried no adjacent source map (file-awareness.md §4 + §6). Without a\n// map, ingest can't reconcile the observed dist file to the static `src/...ts`\n// the extractor parsed — the dist path is the honest answer, never a fabricated\n// src path. The leak this surfaces (issue #430) was hiding behind an absolute\n// path prefix; once the path is service-root-relative the mismatch is legible,\n// and this line tells the operator how to close it.\nconst noSourceMapWarnedServices = new Set<string>()\nfunction warnNoSourceMaps(serviceName: string): void {\n  if (noSourceMapWarnedServices.has(serviceName)) return\n  noSourceMapWarnedServices.add(serviceName)\n  console.warn(\n    `[neat] ${serviceName}: no .map files found under dist/; observed file edges will land on dist paths, not src. Set sourceMap: true in tsconfig to enable file-level reconciliation.`,\n  )\n}\n\n// Test seam — mirrors resetUnidentifiedSpanWarnings for the once-per-service\n// audit above.\nexport function resetNoSourceMapWarnings(): void {\n  noSourceMapWarnedServices.clear()\n}\n\nfunction pickAttrFrom(attrs: AttrBag, ...keys: string[]): string | undefined {\n  for (const k of keys) {\n    const v = attrs[k]\n    if (typeof v === 'string' && v.length > 0) return v\n  }\n  return undefined\n}\n\nfunction pickAttr(span: ParsedSpan, ...keys: string[]): string | undefined {\n  return pickAttrFrom(span.attributes, ...keys)\n}\n\nfunction hostFromUrl(u: string | undefined): string | undefined {\n  if (!u) return undefined\n  try {\n    return new URL(u).hostname\n  } catch {\n    return undefined\n  }\n}\n\n// OTel HTTP/db semconv has gone through several names for \"the host on the\n// other end of this call.\" Try the modern ones first, fall back to the legacy\n// ones, then last resort parse out of a full URL.\nfunction pickAddress(span: ParsedSpan): string | undefined {\n  return (\n    pickAttr(span, 'server.address', 'net.peer.name', 'net.host.name') ??\n    hostFromUrl(pickAttr(span, 'url.full', 'http.url'))\n  )\n}\n\n// The callee host for the cross-service CALLS path (ADR-251, #1424). A span with no kind\n// (undefined / UNSPECIFIED, the OpenTracing and OpenCensus bridges) says nothing\n// about which side of the call it sits on, and its request URL names where the\n// request went: on the receiving side that is the span's own address (nginx's\n// request span carries `http.url` at its own ClusterIP). So for a kindless span\n// only an attribute that names the peer stands in as the callee, never the URL.\n// A kinded CLIENT/PRODUCER span is the caller, so its URL host is the callee.\nfunction calleeAddress(span: ParsedSpan): string | undefined {\n  if (span.kind === undefined || span.kind === 0) {\n    return pickAttr(span, 'server.address', 'net.peer.name')\n  }\n  return pickAddress(span)\n}\n\n// A loopback peer address is this host talking to itself, never a distinct\n// upstream service. Cross-service correlation on the callee's SERVER span (the\n// parent-span fallback, ADR-033) recovers the real peer, so a loopback address\n// on a CLIENT span must not mint a standalone frontier:localhost /\n// frontier:127.0.0.1 that duplicates that resolved edge (issues #590, #577).\n// Scoped to the cross-service CALLS path — a loopback database is a real local\n// dependency and keeps its CONNECTS_TO edge.\nfunction isLoopbackHost(host: string): boolean {\n  const h = host.toLowerCase()\n  return (\n    h === 'localhost' ||\n    h === 'ip6-localhost' ||\n    h === '::1' ||\n    h === '[::1]' ||\n    /^127(?:\\.\\d{1,3}){3}$/.test(h)\n  )\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Call-site capture (file-awareness.md §4)\n//\n// The call-site processor stamps the source location on CLIENT/PRODUCER spans.\n// OpenTelemetry stabilized the code attributes at semconv v1.33 —\n// `code.file.path` / `code.line.number` / `code.function.name` — renaming the\n// prior `code.filepath` / `code.lineno` / `code.function`. NEAT's own emit\n// templates (installers/templates.ts, and the Python processor, ADR-151) and any\n// third-party instrumentation may carry either generation, so the read accepts\n// BOTH, stable-name first. When present, an OBSERVED relationship originates from\n// the file rather than the service; a span with neither stays service-level, and\n// evidence is never fabricated (§6).\nconst CODE_FILE_PATH_ATTR = 'code.file.path' // semconv ≥1.33 (stable)\nconst CODE_FILEPATH_ATTR = 'code.filepath' // prior convention\nconst CODE_LINE_NUMBER_ATTR = 'code.line.number'\nconst CODE_LINENO_ATTR = 'code.lineno'\nconst CODE_FUNCTION_NAME_ATTR = 'code.function.name'\nconst CODE_FUNCTION_ATTR = 'code.function'\n\n// Read the source call site off an attribute bag, accepting the stable\n// (semconv ≥1.33) and prior attribute names. Exported so every code.* reader —\n// edge attribution here, incident localization in traverse.ts — shares one\n// definition and the names can't drift across sites.\nexport function codeFilepathOf(attrs: Record<string, AttributeValue>): string | undefined {\n  const stable = attrs[CODE_FILE_PATH_ATTR]\n  if (typeof stable === 'string' && stable.length > 0) return stable\n  const prior = attrs[CODE_FILEPATH_ATTR]\n  return typeof prior === 'string' && prior.length > 0 ? prior : undefined\n}\nexport function codeLinenoOf(attrs: Record<string, AttributeValue>): number | undefined {\n  const stable = attrs[CODE_LINE_NUMBER_ATTR]\n  if (typeof stable === 'number' && Number.isFinite(stable)) return stable\n  const prior = attrs[CODE_LINENO_ATTR]\n  return typeof prior === 'number' && Number.isFinite(prior) ? prior : undefined\n}\nexport function codeFunctionOf(attrs: Record<string, AttributeValue>): string | undefined {\n  const stable = attrs[CODE_FUNCTION_NAME_ATTR]\n  if (typeof stable === 'string' && stable.length > 0) return stable\n  const prior = attrs[CODE_FUNCTION_ATTR]\n  return typeof prior === 'string' && prior.length > 0 ? prior : undefined\n}\n\nfunction toPosix(p: string): string {\n  return p.split('\\\\').join('/')\n}\n\nfunction languageForExt(relPath: string): string | undefined {\n  const dot = relPath.lastIndexOf('.')\n  if (dot === -1) return undefined\n  switch (relPath.slice(dot).toLowerCase()) {\n    case '.py':\n      return 'python'\n    case '.go':\n      return 'go'\n    case '.ts':\n    case '.tsx':\n      return 'typescript'\n    case '.js':\n    case '.jsx':\n    case '.mjs':\n    case '.cjs':\n      return 'javascript'\n    default:\n      return undefined\n  }\n}\n\n// Join the runtime `code.filepath` against the service root so the OBSERVED\n// relPath lines up with the EXTRACTED service-relative path (file-awareness.md\n// §4 + §7). ServiceNode.repoPath is the scanPath-relative package dir; its\n// segments appear inside the absolute runtime path, so anchoring on it recovers\n// the package-relative tail. With no usable anchor, the real runtime path is\n// returned in a relative-looking form — honest, even if it doesn't align with a\n// static src path. Never fabricated.\nfunction relPathForRuntimeFile(\n  filepath: string,\n  serviceNode?: ServiceNode,\n  scanPath?: string,\n): string | null {\n  let p = toPosix(filepath).replace(/^file:\\/\\//, '')\n  // When ingest knows the absolute scan root, the service's absolute root is\n  // `scanPath/<repoPath>`. Stripping it directly recovers the service-relative\n  // tail (`dist/foo.js`) even for a single-package service whose `repoPath` is\n  // empty — the segment anchor below has nothing to grab in that case, so the\n  // absolute path used to leak into the FileNode key (issue #430).\n  if (scanPath && scanPath.length > 0) {\n    const absRoot = toPosix(path.resolve(scanPath, serviceNode?.repoPath ?? ''))\n    const anchor = absRoot.endsWith('/') ? absRoot : `${absRoot}/`\n    if (p.startsWith(anchor)) return p.slice(anchor.length)\n  }\n  const root = serviceNode?.repoPath\n  if (root && root !== '.' && root.length > 0) {\n    const rootPosix = toPosix(root)\n    const anchor = `/${rootPosix}/`\n    const idx = p.lastIndexOf(anchor)\n    if (idx !== -1) return p.slice(idx + anchor.length)\n    const base = rootPosix.split('/').filter(Boolean).pop()\n    if (base) {\n      const baseAnchor = `/${base}/`\n      const bidx = p.lastIndexOf(baseAnchor)\n      if (bidx !== -1) return p.slice(bidx + baseAnchor.length)\n    }\n  }\n  p = p.replace(/^[A-Za-z]:/, '').replace(/^\\/+/, '')\n  return p.length > 0 ? p : null\n}\n\n// Exported so the connectors plane (packages/core/src/connectors/index.ts,\n// docs/contracts/connectors.md) can build one from a signal's own callSite —\n// a connector's file:line comes from the provider's telemetry rather than an\n// OTel span's code.* attributes, but reconciles onto the same EXTRACTED\n// FileNode through the same primitives below.\nexport interface CallSite {\n  relPath: string\n  line?: number\n  fn?: string\n  // The service-relative dist path the call site was captured on, when ingest\n  // resolved it through a source map to a different (source) `relPath`\n  // (file-awareness.md §4). Surfaces as FileNode.originalPath. Absent when the\n  // captured frame was already source-grained.\n  originalRelPath?: string\n}\n\n// dist→src source-map resolution (file-awareness.md §4). A runtime call site in\n// a compiled `dist/...js` is resolved through a disk-adjacent `.map` to the\n// original `src/...ts`, so an OBSERVED edge lands on the source file an agent\n// can open. Same-host only — when the daemon's filesystem doesn't carry the map\n// (a service that ran on a different machine) the dist frame is kept, honestly,\n// never fabricated (§6). Each dist file is read from disk once: a present map\n// caches its consumer, an absent one caches `null`. Synchronous reads keep\n// callSiteFromSpan synchronous; the cost is amortised across a file's spans.\nconst sourceMapCache = new Map<\n  string,\n  { consumer: sourceMapJs.SourceMapConsumer; dir: string } | null\n>()\n\ninterface ResolvedSrc {\n  filepath: string\n  line?: number\n}\n\nfunction resolveDistToSrc(absFilepath: string, line?: number): ResolvedSrc | null {\n  if (!absFilepath.endsWith('.js')) return null\n  let entry = sourceMapCache.get(absFilepath)\n  if (entry === undefined) {\n    entry = null\n    const mapPath = `${absFilepath}.map`\n    try {\n      if (existsSync(mapPath)) {\n        const raw = JSON.parse(readFileSync(mapPath, 'utf8')) as unknown\n        const consumer = new sourceMapJs.SourceMapConsumer(raw as never)\n        entry = { consumer, dir: path.dirname(mapPath) }\n      }\n    } catch {\n      entry = null\n    }\n    sourceMapCache.set(absFilepath, entry)\n  }\n  if (!entry) return null\n  try {\n    const queryLine = line !== undefined && Number.isFinite(line) ? line : 1\n    // tsc anchors every mapping at the token's real (indented) column, so a\n    // column-0 lookup under the default GREATEST_LOWER_BOUND bias finds no\n    // mapping on any indented statement — which is exactly the call site an\n    // OBSERVED CLIENT span reports for compiled Nest/TS code (issue #915). The\n    // map is on disk and read fine; only the position lookup came back empty,\n    // so the whole dist frame used to fall through to the raw path. Retry the\n    // lookup biased to the LEAST_UPPER_BOUND — the first mapping at or after\n    // column 0 on that generated line — so the line resolves to its source.\n    let pos = entry.consumer.originalPositionFor({ line: queryLine, column: 0 })\n    if (!pos || !pos.source) {\n      pos = entry.consumer.originalPositionFor({\n        line: queryLine,\n        column: 0,\n        bias: sourceMapJs.SourceMapConsumer.LEAST_UPPER_BOUND,\n      })\n    }\n    if (!pos || !pos.source) return null\n    const root = entry.consumer.sourceRoot ?? ''\n    const resolved = path.resolve(entry.dir, root, pos.source)\n    return { filepath: resolved, ...(pos.line ? { line: pos.line } : {}) }\n  } catch {\n    return null\n  }\n}\n\n// Whether a disk-adjacent `.map` was found for a compiled `dist/...js` frame.\n// Reuses the module-level cache resolveDistToSrc already warmed — a non-null\n// entry means the map is present (resolution may still have missed a specific\n// line), a null entry means none was on disk. Lets the missing-map audit stay\n// honest: it must not claim \"no .map files found\" when a map exists but a lone\n// line failed to resolve (file-awareness.md §6, issue #915).\nfunction hasAdjacentSourceMap(absFilepath: string): boolean {\n  return sourceMapCache.get(absFilepath) != null\n}\n\n// Read the call-site attributes off a span. Returns null when the span carries\n// no `code.filepath` (SERVER spans, un-instrumented peers, callee side) so the\n// caller falls back to a service-level edge.\nfunction callSiteFromSpan(\n  span: ParsedSpan,\n  serviceNode?: ServiceNode,\n  scanPath?: string,\n): CallSite | null {\n  const filepath = codeFilepathOf(span.attributes)\n  if (filepath === undefined) return null\n  let line = codeLinenoOf(span.attributes)\n  // Resolve a compiled dist frame to its source before computing the service-\n  // relative path, so the FileNode lands on the original `src/...ts`.\n  const abs = toPosix(filepath).replace(/^file:\\/\\//, '')\n  const resolved = resolveDistToSrc(abs, line)\n  let effectivePath = filepath\n  let originalRelPath: string | undefined\n  if (resolved) {\n    originalRelPath = relPathForRuntimeFile(filepath, serviceNode, scanPath) ?? undefined\n    effectivePath = resolved.filepath\n    if (resolved.line !== undefined) line = resolved.line\n  }\n  const relPath = relPathForRuntimeFile(effectivePath, serviceNode, scanPath)\n  if (!relPath) return null\n  // A compiled `dist/...js` call site that didn't resolve through a map keeps\n  // the (honest) dist path. Surface the absence once per service so the\n  // operator can enable source maps and recover src-level reconciliation\n  // (file-awareness.md §4 + §6, issue #430). Only warn when no `.map` is\n  // actually on disk — a present-but-unresolved line must not masquerade as a\n  // missing map, the misdiagnosis issue #915 called out.\n  if (\n    !resolved &&\n    abs.endsWith('.js') &&\n    relPath.startsWith('dist/') &&\n    !hasAdjacentSourceMap(abs) &&\n    serviceNode?.name\n  ) {\n    warnNoSourceMaps(serviceNode.name)\n  }\n  const fn = codeFunctionOf(span.attributes)\n  return {\n    relPath,\n    ...(line !== undefined ? { line } : {}),\n    ...(fn ? { fn } : {}),\n    ...(originalRelPath && originalRelPath !== relPath ? { originalRelPath } : {}),\n  }\n}\n\n// Reconcile a runtime-derived relPath onto the service-relative path the\n// extractor already minted, so OBSERVED and EXTRACTED FileNodes for the same\n// source file fuse into ONE node instead of two disjoint subgraphs\n// (file-awareness.md §4 — ingest joins the runtime path against the service\n// root to land the edge on a FileNode).\n//\n// relPathForRuntimeFile anchors the absolute `code.filepath` against scanPath /\n// repoPath. When that anchor can't be found — no scanPath wired, or the span\n// was emitted from a service whose absolute root differs from the daemon's\n// checkout (a container image rooted at `/app`, a relocated clone) — the\n// leftover relPath still carries the unanchored leading segments\n// (`app/src/foo.ts`, `Users/me/repo/src/foo.ts`) and forks a parallel FileNode\n// keyed off the absolute path. That splits the graph: the OBSERVED layer never\n// lands on the EXTRACTED `src/foo.ts` node, and divergence/traversal see two\n// half-graphs for one file.\n//\n// The extractor's FileNode paths are ground truth for which service-relative\n// paths exist. Recover the right one by matching the longest EXTRACTED (non-\n// OTel) FileNode path that is a trailing segment-suffix of the runtime relPath.\n// A match means the runtime path is the same file the extractor parsed, just\n// carrying extra leading directories the anchor couldn't strip — reuse the\n// extractor's path so both layers key the same node. No match means the file is\n// genuinely OTel-only; the honest runtime path stands (never fabricated, §6).\nexport function reconcileObservedRelPath(\n  graph: NeatGraph,\n  serviceName: string,\n  relPath: string,\n): string {\n  // Already lands on a known node (the anchor resolved cleanly, or a prior span\n  // created this node) — fused, nothing to recover.\n  if (graph.hasNode(fileId(serviceName, relPath))) return relPath\n  let best: string | null = null\n  graph.forEachNode((_id, attrs) => {\n    const a = attrs as FileNode & { type?: string }\n    if (a.type !== NodeType.FileNode || a.service !== serviceName) return\n    // Only fuse onto a statically-known file. An existing OTel-only node would\n    // already have matched the hasNode short-circuit above.\n    if (a.discoveredVia === 'otel') return\n    const p = a.path\n    if (!p) return\n    if ((relPath === p || relPath.endsWith(`/${p}`)) && (!best || p.length > best.length)) {\n      best = p\n    }\n  })\n  return best ?? relPath\n}\n\n// Ensure the FileNode for an observed call site and the owning service's\n// OBSERVED `CONTAINS` edge both exist, returning the FileNode id so the caller\n// can originate the relationship from it (file-awareness.md §1–2 + §4). The\n// CONTAINS edge carries no `lastObserved` — structural ownership doesn't go\n// STALE when traffic quiets (markStaleEdges skips edges without lastObserved),\n// and divergence detection skips CONTAINS so an OTel-only file node doesn't\n// surface as a missing-extracted finding.\nexport function ensureObservedFileNode(\n  graph: NeatGraph,\n  serviceName: string,\n  serviceNodeId: string,\n  callSite: CallSite,\n): string {\n  // Key the file node on the service the span already FUSED onto, not the raw\n  // span service.name. ensureServiceNode resolves a differently-cased or\n  // env-tagged OTEL_SERVICE_NAME onto the extracted service (`proofrun` → the\n  // ServiceNode named `ProofRun`, #880). Keying the file on the raw name here\n  // forks a `file:proofrun:…` twin off the extracted `file:ProofRun:…` — the\n  // file-level sibling of #880. Reading the canonical name back off the fused\n  // service node also lets reconcileObservedRelPath recover the extractor's\n  // relative path from a runtime absolute path: its file scan filters by an\n  // exact-cased `service`, so the raw name skipped every extracted file before\n  // the suffix match could run. Both forks — case and absolute path — close here.\n  const svcAttrs = graph.hasNode(serviceNodeId) ? (graph.getNodeAttributes(serviceNodeId) as ServiceNode) : undefined\n  const canonicalService =\n    svcAttrs && svcAttrs.type === NodeType.ServiceNode && typeof svcAttrs.name === 'string'\n      ? svcAttrs.name\n      : serviceName\n  const relPath = reconcileObservedRelPath(graph, canonicalService, callSite.relPath)\n  const fileNodeId = fileId(canonicalService, relPath)\n  if (!graph.hasNode(fileNodeId)) {\n    const language = languageForExt(relPath)\n    const node: FileNode = {\n      id: fileNodeId,\n      type: NodeType.FileNode,\n      service: canonicalService,\n      path: relPath,\n      ...(language ? { language } : {}),\n      ...(callSite.originalRelPath ? { originalPath: callSite.originalRelPath } : {}),\n      discoveredVia: 'otel',\n    }\n    graph.addNode(fileNodeId, node)\n  }\n  const containsId = makeObservedEdgeId(EdgeType.CONTAINS, serviceNodeId, fileNodeId)\n  if (!graph.hasEdge(containsId)) {\n    const edge: GraphEdge = {\n      id: containsId,\n      source: serviceNodeId,\n      target: fileNodeId,\n      type: EdgeType.CONTAINS,\n      provenance: Provenance.OBSERVED,\n    }\n    graph.addEdgeWithKey(containsId, serviceNodeId, fileNodeId, edge)\n  }\n  // Observed-first edges land one grain finer than the file when the call site\n  // falls inside a symbol's definition span (ADR-158, file-awareness.md §4).\n  return landObservedSymbol(graph, fileNodeId, canonicalService, relPath, callSite)\n}\n\n// The terminal name of a source-declared qualname (`OrderService.create` →\n// `create`) — what `code.function` carries on a span, and the tiebreaker that\n// picks the intended symbol when nested definition spans both contain the line.\nfunction terminalName(qualname: string): string {\n  const dot = qualname.lastIndexOf('.')\n  return dot === -1 ? qualname : qualname.slice(dot + 1)\n}\n\n// Given the symbols whose definition span contains the observed `code.line`,\n// pick the one the edge lands on. Line-in-span is primary (every candidate\n// already contains the line); `code.function` is the tiebreaker and drift check —\n// when it names one of the candidates, that symbol wins; otherwise the innermost\n// (smallest) span wins, since a call site inside nested definitions belongs to\n// the tightest one enclosing it (ADR-158 point 4).\nfunction pickContainingSymbol(\n  candidates: { id: string; symbol: SymbolNode }[],\n  fn: string | undefined,\n): string {\n  const bySpan = (a: { symbol: SymbolNode }, b: { symbol: SymbolNode }): number => {\n    const sizeA = a.symbol.span.endLine - a.symbol.span.startLine\n    const sizeB = b.symbol.span.endLine - b.symbol.span.startLine\n    if (sizeA !== sizeB) return sizeA - sizeB\n    // Deterministic tiebreak on an exact-size tie: the later-starting span is the\n    // more deeply nested one.\n    return b.symbol.span.startLine - a.symbol.span.startLine\n  }\n  if (fn) {\n    const named = candidates.filter((c) => terminalName(c.symbol.qualname) === fn)\n    if (named.length > 0) return [...named].sort(bySpan)[0]!.id\n  }\n  return [...candidates].sort(bySpan)[0]!.id\n}\n\n// Mint the OBSERVED symbol a runtime call landed on that static never produced —\n// the symbol-grain missing-extracted signal (ADR-158 point 5, lifecycle.md\n// auto-create-and-merge). `code.function` names it, so the symbol is honest, not\n// guessed; the span is the single observed line NEAT can vouch for, and static\n// fields override it on the next extract pass if the definition later resolves.\n// The file owns it through an OBSERVED `file ──CONTAINS──▶ symbol` edge.\nfunction ensureObservedSymbolNode(\n  graph: NeatGraph,\n  fileNodeId: string,\n  service: string,\n  relPath: string,\n  fn: string,\n  line: number,\n): string {\n  const sid = symbolId(service, relPath, fn)\n  if (!graph.hasNode(sid)) {\n    const node: SymbolNode = {\n      id: sid,\n      type: NodeType.SymbolNode,\n      kind: 'function',\n      qualname: fn,\n      span: { startLine: line, endLine: line },\n      service,\n      relPath,\n      discoveredVia: 'otel',\n    }\n    graph.addNode(sid, node)\n  }\n  const containsId = makeObservedEdgeId(EdgeType.CONTAINS, fileNodeId, sid)\n  if (!graph.hasEdge(containsId)) {\n    const edge: GraphEdge = {\n      id: containsId,\n      source: fileNodeId,\n      target: sid,\n      type: EdgeType.CONTAINS,\n      provenance: Provenance.OBSERVED,\n    }\n    graph.addEdgeWithKey(containsId, fileNodeId, sid, edge)\n  }\n  return sid\n}\n\n// Resolve the observed edge's origin to a symbol under the file when the call\n// site's line falls inside a symbol's definition span; otherwise land on the file\n// (ADR-158, file-awareness.md §4–§5). Boundary-grained, not a full call graph:\n// the returned node is what the edge originates from.\n//\n// Degrade to the file honestly when there is no line, or the line is inside no\n// symbol span and either the file was never symbol-extracted (no symbols to be\n// \"missing\" from) or the span carries no function name. When the file *was*\n// symbol-extracted, the line is in no static symbol, and `code.function` names\n// the executing function, mint an `otel` symbol — the missing-extracted signal at\n// symbol grain (point 5), never a degrade that hides the dynamic wiring.\nfunction landObservedSymbol(\n  graph: NeatGraph,\n  fileNodeId: string,\n  service: string,\n  relPath: string,\n  callSite: CallSite,\n  // Whether to MINT an observed-only symbol when the line is in no static symbol\n  // span (the missing-extracted-at-symbol-grain signal, ADR-158 §5). The edge\n  // mint path leaves it true; the incident resolver (ADR-191) passes false so it\n  // reads the containing static symbol without mutating — safe at the receiver,\n  // which runs before reply and off the mutation queue (otel-ingest §Non-blocking).\n  mint = true,\n): string {\n  const line = callSite.line\n  if (line === undefined) return fileNodeId\n\n  let sawSymbol = false\n  const candidates: { id: string; symbol: SymbolNode }[] = []\n  graph.forEachOutboundEdge(fileNodeId, (_edge, edgeAttrs, _source, target) => {\n    if (edgeAttrs.type !== EdgeType.CONTAINS) return\n    const t = graph.getNodeAttributes(target) as GraphNode\n    if (t.type !== NodeType.SymbolNode) return\n    sawSymbol = true\n    if (line >= t.span.startLine && line <= t.span.endLine) {\n      candidates.push({ id: target, symbol: t })\n    }\n  })\n\n  if (candidates.length > 0) return pickContainingSymbol(candidates, callSite.fn)\n\n  if (mint && sawSymbol && callSite.fn) {\n    return ensureObservedSymbolNode(graph, fileNodeId, service, relPath, callSite.fn, line)\n  }\n  return fileNodeId\n}\n\n// Edge id helpers live in @neat.is/types/identity.ts (ADR-029). The local\n// signatures below preserve the (type, source, target) argument order ingest.ts\n// has used historically while delegating to the canonical wire-format helpers.\nfunction makeObservedEdgeId(type: EdgeTypeValue, source: string, target: string): string {\n  return observedEdgeId(source, target, type)\n}\n\nfunction makeInferredEdgeId(type: EdgeTypeValue, source: string, target: string): string {\n  return inferredEdgeId(source, target, type)\n}\n\nconst INFERRED_CONFIDENCE = 0.6\nconst STITCH_MAX_DEPTH = 2\n\n// The trace stitcher only reasons about runtime *dependency* edges — the ones an\n// error actually propagates along (a service calling a service, connecting to a\n// datastore, a declared runtime dependency). Structural edges (CONTAINS a file,\n// IMPORTS a module, CONFIGURED_BY a ConfigNode, RUNS_ON a host) are static facts\n// learned by extraction; a 500 says nothing new about them. Minting an INFERRED\n// twin of a structural EXTRACTED edge would corrupt the trust signal — the twin\n// (conf 0.6) outranks the ground-truth EXTRACTED edge (0.85) under PROV_RANK, so\n// consumer queries would surface the inference in place of the hard fact\n// (docs/contracts/trace-stitcher.md — dependency-edge-type allowlist).\nconst STITCH_EDGE_TYPES = new Set<EdgeTypeValue>([\n  EdgeType.CALLS,\n  EdgeType.CONNECTS_TO,\n  EdgeType.DEPENDS_ON,\n])\n\n// OTLP-wire SpanKind values. The receiver decodes the raw wire integer onto\n// `ParsedSpan.kind` (otel.ts), and the wire enum is offset by one from the\n// `@opentelemetry/api` SpanKind the SDK uses in-process — UNSPECIFIED 0,\n// INTERNAL 1, SERVER 2, CLIENT 3, PRODUCER 4, CONSUMER 5. So we must NOT import\n// `@opentelemetry/api` here: its CLIENT is 2 (= wire SERVER) and PRODUCER is 3\n// (= wire CLIENT), which would gate the wrong kinds. Cross-referenced with the\n// wire fixtures in otel.test.ts (kind 2 = SERVER, kind 3 = CLIENT) and the\n// CLIENT call-site spans in ingest.test.ts (kind 3).\nconst WIRE_SPAN_KIND_CLIENT = 3\nconst WIRE_SPAN_KIND_PRODUCER = 4\nconst WIRE_SPAN_KIND_CONSUMER = 5\n\n// The caller-side gate for the CALLS / CONNECTS_TO paths. A CLIENT or PRODUCER\n// span is the caller/producer side of a service-to-service call or a datastore\n// read; INTERNAL / SERVER spans are not — a SERVER span is the callee, and its\n// edge is minted from its parent CLIENT via the parent-span fallback. Without\n// this gate every INTERNAL span that happens to carry a peer address — e.g. a\n// `tcp.connect` / `tls.connect` to an AWS endpoint — mints a spurious\n// service-level edge (issue #429), because no §4 capture layer stamps `code.*`\n// on INTERNAL spans.\n//\n// CONSUMER spans are handled by the messaging branch in handleSpan, not here:\n// a queue consumer isn't calling a service, it's reading a topic, so it mints a\n// CONSUMES_FROM edge to the destination node (spanMintsMessagingEdge below) —\n// the observed mirror of the static consumer→topic edge, the queue-side pair of\n// the PRODUCER→topic PUBLISHES_TO edge.\n//\n// A span that reports no kind (undefined) or UNSPECIFIED (0) carries no\n// caller/callee signal, so it falls back to the historical unconditional\n// behavior — hand-built and legacy producers keep minting. The leak this gates\n// is always an explicitly-kinded INTERNAL span.\nfunction spanMintsObservedEdge(kind: number | undefined): boolean {\n  if (kind === undefined || kind === 0) return true\n  return kind === WIRE_SPAN_KIND_CLIENT || kind === WIRE_SPAN_KIND_PRODUCER\n}\n\n// The messaging counterpart to the caller-side gate. A PRODUCER span publishes\n// to a destination; a CONSUMER span reads from one. Both sides mint an OBSERVED\n// edge to the topic/queue node — the PRODUCER a PUBLISHES_TO, the CONSUMER a\n// CONSUMES_FROM — so declared and observed queue topology fuse. Only spans that\n// actually carry a messaging destination reach this (handleSpan checks the\n// semconv attrs first), so a stray CONSUMER span with no destination stays inert.\nfunction spanMintsMessagingEdge(kind: number | undefined): boolean {\n  return kind === WIRE_SPAN_KIND_PRODUCER || kind === WIRE_SPAN_KIND_CONSUMER\n}\n\n// The GraphQL execution span is emitted by the service that RESOLVES the\n// operation — a SERVER or INTERNAL span (the instrumentation's `graphql.execute`),\n// never the CLIENT side that only ever sees an opaque `POST /graphql`. Gating out\n// the caller/producer/consumer kinds keeps a client-side operation span from\n// attributing the operation to the caller (client-side operation attribution is\n// deferred, ADR-122); an unkinded / UNSET span still mints, mirroring the\n// caller-side gate's legacy-producer fallback.\nfunction spanServesGraphqlOperation(kind: number | undefined): boolean {\n  return (\n    kind !== WIRE_SPAN_KIND_CLIENT &&\n    kind !== WIRE_SPAN_KIND_PRODUCER &&\n    kind !== WIRE_SPAN_KIND_CONSUMER\n  )\n}\n\n// A GraphQL operation node keyed on (service, operationType, operationName) via\n// graphqlOperationId (ADR-122). Minted observed-first from the execution span so\n// operation-level topology is legible even before any static GraphQL extractor\n// exists; a later static extractor fuses onto the same id. `operationType` is\n// stored lower-cased to match the id's normalisation, so a `query` observed and a\n// `Query` static resolver land on one node. Idempotent — a high-volume operation\n// upserts, never grows the node set.\nfunction ensureGraphqlOperationNode(\n  graph: NeatGraph,\n  serviceName: string,\n  operationType: string,\n  operationName: string,\n): string {\n  const id = graphqlOperationId(serviceName, operationType, operationName)\n  if (graph.hasNode(id)) return id\n  const node: GraphQLOperationNode = {\n    id,\n    type: NodeType.GraphQLOperationNode,\n    name: operationName,\n    service: serviceName,\n    operationType: operationType.toLowerCase(),\n    operationName,\n    discoveredVia: 'otel',\n  }\n  graph.addNode(id, node)\n  return id\n}\n\n// The gRPC execution span carrying `rpc.service` / `rpc.method` is emitted on\n// both sides of a call — the SERVER that resolves the method and the CLIENT that\n// invokes it. Only the serving side owns the method (ADR-123): gating out the\n// caller/producer/consumer kinds keeps a CLIENT gRPC span from attributing\n// ownership to the caller (that client span still falls through to the\n// cross-service resolver below, so the caller→callee edge is unaffected).\n// Client→method attribution is deferred. An unkinded / UNSET span still mints,\n// mirroring the graphql and caller-side gates' legacy fallbacks.\nfunction spanServesGrpcMethod(kind: number | undefined): boolean {\n  return (\n    kind !== WIRE_SPAN_KIND_CLIENT &&\n    kind !== WIRE_SPAN_KIND_PRODUCER &&\n    kind !== WIRE_SPAN_KIND_CONSUMER\n  )\n}\n\n// A gRPC method node keyed on (rpcService, rpcMethod) via grpcMethodId (ADR-123).\n// `rpcService` is the fully-qualified `rpc.service` the wire carries verbatim\n// (`orders.OrderService`), so an OBSERVED span and a static `.proto` definition\n// fuse onto one node rather than twinning. Idempotent — a high-volume method\n// upserts, never grows the node set.\nfunction ensureGrpcMethodNode(\n  graph: NeatGraph,\n  rpcService: string,\n  rpcMethod: string,\n): string {\n  const id = grpcMethodId(rpcService, rpcMethod)\n  if (graph.hasNode(id)) return id\n  const node: GrpcMethodNode = {\n    id,\n    type: NodeType.GrpcMethodNode,\n    name: `${rpcService}/${rpcMethod}`,\n    rpcService,\n    rpcMethod,\n    discoveredVia: 'otel',\n  }\n  graph.addNode(id, node)\n  return id\n}\n\n// The HTTP upgrade span that opens a WebSocket is emitted by the service that\n// SERVES the channel — a SERVER span (the framework's inbound `GET`), or an\n// unkinded / INTERNAL span from a hand-built handshake. The CLIENT that dials the\n// socket carries the same upgrade header, but the channel belongs to the server\n// (ADR-125), so gating out the caller/producer/consumer kinds keeps a client-side\n// upgrade span from attributing the channel to the caller. An unkinded / UNSET\n// span still mints, mirroring the graphql and gRPC serving-side gates.\nfunction spanServesWebsocketChannel(kind: number | undefined): boolean {\n  return (\n    kind !== WIRE_SPAN_KIND_CLIENT &&\n    kind !== WIRE_SPAN_KIND_PRODUCER &&\n    kind !== WIRE_SPAN_KIND_CONSUMER\n  )\n}\n\n// A WebSocket channel node keyed on (service, channel) via websocketChannelId\n// (ADR-125). Minted OBSERVED-only from the upgrade span — a WebSocket channel is\n// known from observation, never from static extraction, so there is no declared\n// twin to fuse with and no static producer to fill in `path` / `line` (those stay\n// absent, never fabricated — file-awareness.md §6). Idempotent — every reconnect\n// on the same channel upserts, never grows the node set.\nfunction ensureWebsocketChannelNode(\n  graph: NeatGraph,\n  serviceName: string,\n  channel: string,\n): string {\n  const id = websocketChannelId(serviceName, channel)\n  if (graph.hasNode(id)) return id\n  const node: WebSocketChannelNode = {\n    id,\n    type: NodeType.WebSocketChannelNode,\n    name: channel,\n    service: serviceName,\n    channel,\n    discoveredVia: 'otel',\n  }\n  graph.addNode(id, node)\n  return id\n}\n\n// A messaging destination node (Kafka topic, queue, stream) keyed exactly the\n// way the static extractor keys it, so the OBSERVED and EXTRACTED edges fuse\n// onto one node instead of twinning. The Kafka static side names its topic\n// `infra:kafka-topic:<topic>` (extract/calls/kafka.ts), so the kind is\n// `<messaging.system>-topic` — `kafka` → `kafka-topic` — and the same shape\n// generalises to every messaging system the semconv names. `provider: 'self'`\n// mirrors the static extractor's non-AWS provider so an observed-first node\n// merges cleanly when static analysis later reaches the same destination.\nfunction messagingDestinationKind(system: string): string {\n  return `${system}-topic`\n}\n\nfunction ensureMessagingDestinationNode(\n  graph: NeatGraph,\n  system: string,\n  destination: string,\n): string {\n  const id = infraId(messagingDestinationKind(system), destination)\n  if (graph.hasNode(id)) return id\n  const node: InfraNode = {\n    id,\n    type: NodeType.InfraNode,\n    name: destination,\n    provider: 'self',\n    kind: messagingDestinationKind(system),\n  }\n  graph.addNode(id, node)\n  return id\n}\n\n// Parent-span TTL cache (ADR-033). Address-based peer resolution (server.address /\n// net.peer.name / url.full) misses non-HTTP RPCs and any span with an opaque\n// peer. The cache stores each span's service keyed by `${traceId}:${spanId}` so\n// a child span whose address resolution fails can fall back to its parent's\n// service, identifying a cross-service CALLS edge from parent → current.\n//\n// Bounded size + TTL — out-of-order arrival (child before parent) drops the\n// child rather than buffering. We accept that loss because the cache is best-\n// effort: for every cross-service call, the CLIENT span on the caller side\n// covers the same edge via address-based resolution, so missing one direction\n// is recoverable.\nconst PARENT_SPAN_CACHE_SIZE = 10_000\nconst PARENT_SPAN_CACHE_TTL_MS = 5 * 60 * 1000\n\ninterface ParentSpanCacheEntry {\n  service: string\n  // Env discriminator from the parent span (ADR-074 §2). The parent-span\n  // fallback in handleSpan uses this so the auto-created parent ServiceNode\n  // lands on the same env-tagged id the OTel emitter advertised.\n  env: string\n  // The parent span's own `code.*` call site, when its SpanProcessor captured\n  // one (file-awareness.md §4). The parent-span fallback below originates its\n  // edge from the parent's FileNode instead of the bare parent ServiceNode when\n  // this is present, so the fallback edge anchors to file:line rather than\n  // pinning to a service node (issue #536). Undefined when the parent carried no\n  // call site — never fabricated (§6), so the service-level fallback stands.\n  callSite?: CallSite\n  expiresAt: number\n}\n\nconst parentSpanCache = new Map<string, ParentSpanCacheEntry>()\n\nfunction parentSpanKey(traceId: string, spanId: string): string {\n  return `${traceId}:${spanId}`\n}\n\nfunction cacheSpanService(span: ParsedSpan, now: number, callSite: CallSite | null): void {\n  if (!span.traceId || !span.spanId) return\n  const key = parentSpanKey(span.traceId, span.spanId)\n  // Map preserves insertion order, so deleting + re-inserting bumps an entry to\n  // the back. Eviction is \"drop oldest\" once size exceeds the cap.\n  parentSpanCache.delete(key)\n  parentSpanCache.set(key, {\n    service: span.service,\n    env: span.env ?? 'unknown',\n    ...(callSite ? { callSite } : {}),\n    expiresAt: now + PARENT_SPAN_CACHE_TTL_MS,\n  })\n  while (parentSpanCache.size > PARENT_SPAN_CACHE_SIZE) {\n    const oldest = parentSpanCache.keys().next().value\n    if (!oldest) break\n    parentSpanCache.delete(oldest)\n  }\n}\n\nfunction lookupParentSpan(\n  traceId: string,\n  parentSpanId: string,\n  now: number,\n): { service: string; env: string; callSite?: CallSite } | null {\n  const entry = parentSpanCache.get(parentSpanKey(traceId, parentSpanId))\n  if (!entry) return null\n  if (entry.expiresAt <= now) {\n    parentSpanCache.delete(parentSpanKey(traceId, parentSpanId))\n    return null\n  }\n  return {\n    service: entry.service,\n    env: entry.env,\n    ...(entry.callSite ? { callSite: entry.callSite } : {}),\n  }\n}\n\n// Test seam: lets unit tests start from a clean slate.\nexport function resetParentSpanCache(): void {\n  parentSpanCache.clear()\n}\n\n// Peer host → ServiceNode id resolution. With env-dimension (ADR-074 §2),\n// the same `name` may live across multiple ServiceNodes — one per env, plus\n// the env-less form from static extraction. When `env` is known (the source\n// span's env), prefer a same-env match; fall back to the env-less node so\n// EXTRACTED edges from static analysis remain reachable until OBSERVED\n// traffic from the same env promotes them.\n//\n// Match passes:\n//   1. Exact id lookup for `(host, env)` — `serviceId(host, env)`.\n//   2. Exact id lookup for env-less `serviceId(host)`.\n//   3. Name/alias scan across every ServiceNode, preferring same-env then\n//      env-less then any other env.\nfunction resolveServiceId(\n  graph: NeatGraph,\n  host: string,\n  env: string,\n): string | null {\n  const envTagged = serviceId(host, env)\n  if (graph.hasNode(envTagged)) return envTagged\n  const envLess = serviceId(host)\n  if (envLess !== envTagged && graph.hasNode(envLess)) return envLess\n\n  let sameEnv: string | null = null\n  let envLessMatch: string | null = null\n  let anyMatch: string | null = null\n  graph.forEachNode((id, attrs) => {\n    if (sameEnv) return\n    const a = attrs as ServiceNode & { type?: string }\n    if (a.type !== NodeType.ServiceNode) return\n    const matchesByName = a.name === host\n    const matchesByAlias = a.aliases ? a.aliases.includes(host) : false\n    if (!matchesByName && !matchesByAlias) return\n    const nodeEnv = a.env ?? 'unknown'\n    if (nodeEnv === env) {\n      sameEnv = id\n      return\n    }\n    if (nodeEnv === 'unknown' && !envLessMatch) envLessMatch = id\n    else if (!anyMatch) anyMatch = id\n  })\n  return sameEnv ?? envLessMatch ?? anyMatch\n}\n\n// The service a bare-IP peer address belongs to, read off the OBSERVED addresses\n// the k8s substrate stamped on ServiceNodes (ADR-248). A client span that dials a\n// Service by its ClusterIP names the callee only as that IP; this is the one\n// lookup ingest makes before it mints a frontier for it. A hostname never takes\n// this path, and an address on more than one service resolves to none.\nexport function serviceIdForObservedAddress(graph: NeatGraph, host: string): string | null {\n  if (isIP(host) === 0) return null\n  let found: string | null = null\n  let ambiguous = false\n  graph.forEachNode((id, attrs) => {\n    if (ambiguous) return\n    const a = attrs as ServiceNode & { type?: string }\n    if (a.type !== NodeType.ServiceNode || !a.observedAddresses?.includes(host)) return\n    if (found !== null && found !== id) ambiguous = true\n    else found = id\n  })\n  return ambiguous ? null : found\n}\n\nexport function frontierIdFor(host: string): string {\n  return frontierId(host)\n}\n\n// Auto-create a minimal ServiceNode for span.service when no such node exists.\n// Used at the top of handleSpan so subsequent edge upserts always have endpoints\n// — without it, OBSERVED edges silently drop for any service the static\n// extractor hasn't reached yet (and never reaches at all in OTel-only setups).\n// `language: 'unknown'` is the contract's specified placeholder (ADR-033). When\n// static extraction later produces a ServiceNode at the same id, addServiceNodes\n// merges and flips discoveredVia to 'merged' rather than overwriting.\n// Exported for the connectors plane (connectors/index.ts) — a connector\n// signal needs the same auto-vivified ServiceNode any OTel span gets before\n// an edge upsert, since a connector-sourced service may never have been\n// statically extracted or seen a span yet.\n// Pure, read-only resolution of an observed `service.name` + `env` onto the id\n// of the ServiceNode it fuses with. This is the #880 matching, factored out of\n// ensureServiceNode so the incident/error path can share it without mutating\n// the graph.\n//\n// Two things push the observed id away from the extracted `service:<name>`:\n// `deployment.environment` (standard OTel semconv, commonly set) tags it\n// `service:<name>:<env>`, and OTEL_SERVICE_NAME is routinely a differently-\n// cased form of the manifest name the extractor used (`casetest` vs the\n// registered `CaseTest`). Either one alone splits the fused graph in two. So:\n// first an exact `(name, env)` id lookup, then a case-insensitive `name` match\n// against a statically extracted (non-otel) ServiceNode, ignoring env — env is\n// a dimension, not identity.\n//\n// When neither matches, the raw `serviceId(name, env)` is returned and the\n// caller decides: ensureServiceNode mints a node at that id, the incident path\n// (incidentAffectedNode) just attributes against it — the honest fallback for\n// an OTel-only service the graph hasn't materialised yet.\n//\n// Exported (ADR-185) so an incident-emitting connector's `resolveTarget` can\n// share the exact fused-service lookup — landing a build-failure incident on\n// the same extracted ServiceNode a span would, never a connector twin.\nexport function resolveFusedServiceId(\n  graph: NeatGraph,\n  serviceName: string,\n  env: string,\n): string {\n  const id = serviceId(serviceName, env)\n  if (graph.hasNode(id)) return id\n  const wanted = serviceName.toLowerCase()\n  const extractedId = graph.findNode((_nid, attrs) => {\n    if (attrs.type !== NodeType.ServiceNode) return false\n    const svc = attrs as ServiceNode\n    // Skip observed twins (discoveredVia 'otel') — only fuse onto a statically\n    // extracted (or already-merged) service, never onto another observed node.\n    if (svc.discoveredVia === 'otel') return false\n    return typeof svc.name === 'string' && svc.name.toLowerCase() === wanted\n  })\n  return extractedId ?? id\n}\n\nexport function ensureServiceNode(\n  graph: NeatGraph,\n  serviceName: string,\n  env: string,\n): string {\n  // Fuse an observed span onto the service the static extractor already minted\n  // (#880), rather than forking a twin that never joins the extracted graph —\n  // without it `observed-dependencies` reports \"no traffic\" on the extracted\n  // node while the traffic sits on the twin, and every divergence doubles.\n  const resolved = resolveFusedServiceId(graph, serviceName, env)\n  if (graph.hasNode(resolved)) return resolved\n  // Nothing matched — `resolved` is the raw serviceId, so this is a genuinely\n  // new OTel-only service. Mint it (the env-tagged or differently-cased spans\n  // that DID match an extracted node already returned above).\n  const node: ServiceNode = {\n    id: resolved,\n    type: NodeType.ServiceNode,\n    name: serviceName,\n    language: 'unknown',\n    discoveredVia: 'otel',\n    ...(env !== 'unknown' ? { env } : {}),\n  }\n  graph.addNode(resolved, node)\n  return resolved\n}\n\n// Exported so a connector's generic pipeline (connectors/index.ts) can create\n// an honest placeholder InfraNode for a provider-named resource no static\n// extractor has (yet) declared — a provider module has no mutation authority\n// of its own (ADR-030), so `resolveTarget` declares this need instead of\n// creating the node itself (ADR-133 §4a, docs/contracts/connectors.md).\n// Idempotent, same shape as `ensureServiceNode`.\nexport function ensureInfraNode(\n  graph: NeatGraph,\n  kind: string,\n  name: string,\n  provider: string,\n): string {\n  const id = infraId(kind, name)\n  if (graph.hasNode(id)) return id\n  const node: InfraNode = {\n    id,\n    type: NodeType.InfraNode,\n    name,\n    provider,\n    kind,\n  }\n  graph.addNode(id, node)\n  return id\n}\n\n// InfraNode kinds that carry columns — a database table read at column grain\n// (ADR-157 §1). `sql-table` is the canonical table node the OTel `db.statement`\n// mint and the Neon connector both land on; `supabase-table` is the same table\n// grain on the Supabase pull path. A project-level or non-table InfraNode (a\n// `supabase` project node, a `mongodb-collection`, a queue/route node) carries no\n// columns, so a merge onto one is a no-op.\nconst COLUMN_BEARING_INFRA_KINDS = new Set(['sql-table', 'supabase-table'])\n\n// Fold columns onto a table InfraNode at the given provenance (ADR-157 §1-2).\n// Columns are provenanced attributes on the table node, never their own nodes. A\n// column records each side it has been seen with in its `provenances` set — a\n// declared column production also touches ends up `[EXTRACTED, OBSERVED]`, not one\n// side clobbering the other — so column drift (ADR-157 §4) can read the declared\n// set and the observed set off one node. A no-op for a non-table node or an empty\n// column set, so a wildcard / join / DDL statement (which recovers no columns)\n// grows nothing. Mutation lives here in ingest.ts per the lifecycle authority\n// (ADR-030); the pure fold is columns.ts so extract/* can call it without a cycle.\nfunction mergeColumnsAt(\n  graph: NeatGraph,\n  tableNodeId: string,\n  columns: readonly string[] | undefined,\n  provenance: ProvenanceValue,\n  confidence: number,\n): void {\n  if (!columns || columns.length === 0 || !graph.hasNode(tableNodeId)) return\n  const node = graph.getNodeAttributes(tableNodeId) as InfraNode\n  if (node.type !== NodeType.InfraNode || !node.kind || !COLUMN_BEARING_INFRA_KINDS.has(node.kind)) {\n    return\n  }\n  graph.replaceNodeAttributes(tableNodeId, {\n    ...node,\n    columns: foldColumns(node.columns, columns, provenance, confidence),\n  })\n}\n\n// Merge the columns a production statement touched onto a table InfraNode as\n// OBSERVED (ADR-157 §1-2). OTel ingest and the connector mint path both call in.\nexport function mergeObservedColumns(\n  graph: NeatGraph,\n  tableNodeId: string,\n  columns: readonly string[] | undefined,\n): void {\n  mergeColumnsAt(graph, tableNodeId, columns, Provenance.OBSERVED, OBSERVED_COLUMN_CONFIDENCE)\n}\n\n// Merge the observed k8s deploy state — the container image the cluster's pods\n// actually run and the count of ready replicas — onto a `service:<name>` node as\n// OBSERVED (ADR-225). The observed half of the k8s deployment substrate: the\n// manifest extractor stamps `declaredImage`/`declaredReplicas` on this same node,\n// and the compare between the two names a `deploy-mismatch` divergence — the stuck\n// rollout that mints no incident because the service is still up on the old image.\n// Node attributes carry provenance in the name (`observed*` vs `declared*`), so\n// this is a plain attribute merge, not an edge; it never clobbers the declared\n// side. A no-op when the service node isn't in the graph yet, the same honest\n// missing-target discipline the connector pipeline holds.\nexport function mergeObservedDeployState(\n  graph: NeatGraph,\n  serviceNodeId: string,\n  state: { image?: string; readyReplicas?: number; addresses?: string[] },\n): void {\n  if (!graph.hasNode(serviceNodeId)) return\n  const attrs: Record<string, unknown> = {}\n  if (typeof state.image === 'string' && state.image.length > 0) attrs['observedImage'] = state.image\n  if (typeof state.readyReplicas === 'number') attrs['observedReadyReplicas'] = state.readyReplicas\n  // Addresses are replaced whole by each read (ADR-248): a Service that went away\n  // takes its address with it. Absent means the substrate didn't read them this\n  // time, so the last read stands.\n  if (Array.isArray(state.addresses)) {\n    if (state.addresses.length > 0) attrs['observedAddresses'] = [...state.addresses].sort()\n    else if ((graph.getNodeAttributes(serviceNodeId) as { observedAddresses?: unknown }).observedAddresses !== undefined) {\n      graph.removeNodeAttribute(serviceNodeId, 'observedAddresses' as never)\n    }\n  }\n  if (Object.keys(attrs).length === 0) return\n  graph.mergeNodeAttributes(serviceNodeId, attrs)\n}\n\n// Stamp a live infrastructure object's spec onto its InfraNode as OBSERVED\n// `observedSpec` (#1481) — a k8s Service's selector, ports and traffic policies,\n// a Deployment's container ports. Replaced whole by each read, so a field the\n// object dropped goes with it; the namespace rides beside it, as the manifest\n// extractor records it. A no-op when the node isn't in the graph.\nexport function mergeObservedInfraSpec(\n  graph: NeatGraph,\n  nodeId: string,\n  state: { namespace?: string; spec: Record<string, unknown> },\n): void {\n  if (!graph.hasNode(nodeId)) return\n  const attrs: Record<string, unknown> = { observedSpec: state.spec }\n  const current = graph.getNodeAttributes(nodeId) as { namespace?: string }\n  if (state.namespace && current.namespace === undefined) attrs['namespace'] = state.namespace\n  graph.mergeNodeAttributes(nodeId, attrs)\n}\n\n// Clear `observedSpec` off the InfraNodes of one kind whose object a full read no\n// longer returned (#1484): a deleted NetworkPolicy or quota stops reading as\n// live. Scoped to the read's namespace (or, for a cluster-scoped kind, to nodes\n// with none), so one namespace's read never clears another's. The node stays —\n// a manifest may still declare it — only the observed spec goes.\nexport function retireObservedInfraSpecs(\n  graph: NeatGraph,\n  inventory: { kind: string; provider: string; namespace?: string; present: string[] },\n): void {\n  const present = new Set(inventory.present)\n  const stale: string[] = []\n  graph.forEachNode((id, attrs) => {\n    const n = attrs as { type?: string; kind?: string; provider?: string; name?: string; namespace?: string; observedSpec?: unknown }\n    if (n.type !== NodeType.InfraNode || n.kind !== inventory.kind || n.provider !== inventory.provider) return\n    if (n.observedSpec === undefined || present.has(n.name ?? '')) return\n    if ((n.namespace ?? undefined) !== inventory.namespace) return\n    stale.push(id)\n  })\n  for (const id of stale) graph.removeNodeAttribute(id, 'observedSpec' as never)\n}\n\n// Fuse a faulted workload's deploy/process/config context onto its node as OBSERVED\n// (ADR-243, amending ADR-237/240). The one copy: the incident card, `neat incidents`\n// and MCP read it from here, never from the incident. Tagged with the incident it\n// was observed with, so a card shows it only for that incident; a newer fault on the\n// same workload replaces it. Already redacted and bounded upstream\n// (process-context.ts). A no-op when the node isn't in the graph.\nexport function mergeObservedDeployContext(\n  graph: NeatGraph,\n  nodeId: string,\n  incidentId: string,\n  observedAt: string,\n  context: DeployContext,\n): void {\n  if (!graph.hasNode(nodeId)) return\n  if (Object.keys(context).length === 0) return\n  const value: ObservedDeployContext = { ...context, incidentId, observedAt }\n  graph.mergeNodeAttributes(nodeId, { observedDeployContext: value })\n}\n\n// Merge what a flag store is serving onto its flag grain as OBSERVED (ADR-242).\n// The store's sync reader calls in each poll with the full served set. Only a flag\n// the code base declares takes the observed definition; a served flag with no\n// committed twin mints nothing and comes back in `undeclared` for the reader's\n// poll status. A no-op (everything undeclared) when the store node isn't in the\n// graph, because then nothing declares a flag yet.\nexport function mergeObservedFlags(\n  graph: NeatGraph,\n  provider: string,\n  served: ReadonlyMap<string, FlagDefinition>,\n  at: string,\n): { undeclared: string[] } {\n  const storeId = infraId(FLAG_STORE_KIND, provider)\n  if (!graph.hasNode(storeId)) return { undeclared: [...served.keys()].sort() }\n  const node = graph.getNodeAttributes(storeId) as InfraNode\n  const { flags, undeclared } = foldObservedFlags(node.flags, served, at)\n  graph.mergeNodeAttributes(storeId, { flags })\n  return { undeclared }\n}\n\n// The flag store an evaluation came from: the one its provider names, else the\n// only flag store in the graph. Null when neither picks exactly one.\nfunction flagStoreFor(graph: NeatGraph, provider: string | undefined): string | null {\n  if (provider) {\n    const id = infraId(FLAG_STORE_KIND, provider)\n    return graph.hasNode(id) ? id : null\n  }\n  const stores: string[] = []\n  graph.forEachNode((id, attrs) => {\n    const n = attrs as GraphNode\n    if (n.type === NodeType.InfraNode && n.kind === FLAG_STORE_KIND) stores.push(id)\n  })\n  return stores.length === 1 ? stores[0]! : null\n}\n\n// Fold one service-side flag evaluation (a `feature_flag.evaluation` span event)\n// onto the flag grain, and record that the evaluating code reads the store: an\n// OBSERVED CONNECTS_TO from the span's origin, the twin of the EXTRACTED edge the\n// literal join mints. Only a flag the code base declares is recorded. Returns\n// whether it landed.\nfunction recordFlagEvaluation(\n  graph: NeatGraph,\n  source: () => string,\n  ev: FlagEvaluation,\n  ts: string,\n  callSiteEvidence: { file: string; line?: number } | undefined,\n): boolean {\n  if (!ev.variant) return false\n  const storeId = flagStoreFor(graph, ev.provider)\n  if (!storeId) return false\n  const node = graph.getNodeAttributes(storeId) as InfraNode\n  const flags = foldObservedVariant(node.flags, ev.key, ev.variant, ev.reason, ts)\n  if (!flags) return false\n  graph.mergeNodeAttributes(storeId, { flags })\n  upsertObservedEdge(graph, EdgeType.CONNECTS_TO, source(), storeId, ts, false, callSiteEvidence)\n  return true\n}\n\n// Merge the columns a schema/ORM declares onto a table InfraNode as EXTRACTED\n// (ADR-157 §3). The declared side of column grain: the static extractor recovers\n// each column at database-name fidelity and calls in from extract/calls/*.\nexport function mergeDeclaredColumns(\n  graph: NeatGraph,\n  tableNodeId: string,\n  columns: readonly string[] | undefined,\n  confidence: number,\n): void {\n  mergeColumnsAt(graph, tableNodeId, columns, Provenance.EXTRACTED, confidence)\n}\n\n// Same shape for unseen db.system + host pairs. Engine comes off the OTel\n// attribute as a string per Rule 8 — no hardcoded engine list. compatibleDrivers\n// is empty until static extraction merges in the matrix-derived drivers.\nfunction ensureDatabaseNode(graph: NeatGraph, host: string, engine: string): string {\n  const id = databaseId(host)\n  if (graph.hasNode(id)) return id\n  const node: DatabaseNode = {\n    id,\n    type: NodeType.DatabaseNode,\n    name: host,\n    engine,\n    engineVersion: 'unknown',\n    compatibleDrivers: [],\n    host,\n    discoveredVia: 'otel',\n  }\n  graph.addNode(id, node)\n  return id\n}\n\n// An in-process / embedded database (SQLite, better-sqlite3, an in-memory\n// store) crosses no network boundary, so its span carries no peer host to key a\n// DatabaseNode on. Key it on a service-scoped local identity instead so two\n// services each reading their own `app.db` stay distinct nodes rather than\n// collapsing onto one (ADR-118). `name` is the logical database from the span\n// (db.name) when present, the engine string otherwise. `host` is intentionally\n// omitted — an embedded database has no network host, and evidence is never\n// fabricated (file-awareness.md §6); host-mismatch divergence skips a hostless\n// DatabaseNode. Returns the node id so the caller can point the CONNECTS_TO edge\n// at it. Idempotent — high-volume DB spans upsert, never grow the node set.\nfunction ensureLocalDatabaseNode(\n  graph: NeatGraph,\n  serviceName: string,\n  name: string,\n  engine: string,\n): string {\n  const id = localDatabaseId(serviceName, name)\n  if (graph.hasNode(id)) return id\n  const node: DatabaseNode = {\n    id,\n    type: NodeType.DatabaseNode,\n    name,\n    engine,\n    engineVersion: 'unknown',\n    compatibleDrivers: [],\n    discoveredVia: 'otel',\n  }\n  graph.addNode(id, node)\n  return id\n}\n\n// ADR-141 — an ORM such as Prisma emits a `db.system` span with no peer host\n// (its query engine backdates the span off the connection), so a host-less span\n// would mint a fresh service-local DatabaseNode and leave the service's\n// statically declared database — the one parsed from its connection string / ORM\n// schema — with no OBSERVED twin: a false `missing-observed` divergence for a DB\n// the service demonstrably hammers. Before minting a local node, fuse onto the\n// service's already-declared database of the same engine when there is exactly\n// one. Ambiguous (two-plus same-engine declared DBs) or none falls back to the\n// ADR-118 service-local node — the fusion never guesses which of several it is.\nfunction findDeclaredDatabaseForService(\n  graph: NeatGraph,\n  serviceNodeId: string,\n  engine: string,\n): string | null {\n  if (!graph.hasNode(serviceNodeId)) return null\n  // A declared database CONNECTS_TO is file-grained by design — it originates\n  // from the config file that named the connection (databases/index.ts,\n  // file-awareness §7), not the service node. So scan the service node and every\n  // file it CONTAINS for a same-engine EXTRACTED CONNECTS_TO target.\n  const sources = [serviceNodeId]\n  for (const edgeId of graph.outboundEdges(serviceNodeId)) {\n    const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n    if (e.type === EdgeType.CONTAINS) sources.push(e.target)\n  }\n  const matches = new Set<string>()\n  for (const src of sources) {\n    if (!graph.hasNode(src)) continue\n    for (const edgeId of graph.outboundEdges(src)) {\n      const edge = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (edge.type !== EdgeType.CONNECTS_TO || edge.provenance !== Provenance.EXTRACTED) continue\n      if (!graph.hasNode(edge.target)) continue\n      const target = graph.getNodeAttributes(edge.target) as DatabaseNode\n      if (target.type !== NodeType.DatabaseNode || target.engine !== engine) continue\n      matches.add(edge.target)\n    }\n  }\n  return matches.size === 1 ? [...matches][0]! : null\n}\n\nfunction ensureFrontierNode(graph: NeatGraph, host: string, ts: string): string {\n  const id = frontierIdFor(host)\n  if (graph.hasNode(id)) {\n    const existing = graph.getNodeAttributes(id) as FrontierNode\n    graph.replaceNodeAttributes(id, { ...existing, lastObserved: ts })\n    return id\n  }\n  const node: FrontierNode = {\n    id,\n    type: NodeType.FrontierNode,\n    name: host,\n    host,\n    firstObserved: ts,\n    lastObserved: ts,\n  }\n  graph.addNode(id, node)\n  return id\n}\n\n// Exported so the connectors plane (connectors/index.ts) mints edges through\n// the identical primitive OTel ingest uses — a connector-sourced edge and a\n// span-sourced edge are meant to be indistinguishable to traversal,\n// divergence, and staleness (docs/connectors/README.md).\nexport interface UpsertResult {\n  edge: GraphEdge\n  created: boolean\n}\n\n// Bounded ceiling for an edge exemplar's message (ADR-236). The full exception\n// text lives in the incident ledger; the edge carries only enough to name the\n// failure's nature, so a pathological stack-dump message never bloats the edge.\nexport const EDGE_ERROR_MESSAGE_MAX = 512\n\n// Build the bounded last-error exemplar written onto `signal.lastError`\n// (ADR-236). `at` is the span's own observation time (ts), mirroring\n// `lastObserved`. Only fields the caller actually resolved are set — a failure\n// may carry a type, a message, a status, or only some of these — and `message`\n// is trimmed defensively here too, so no caller can route an unbounded string\n// onto the edge.\nfunction buildEdgeErrorExemplar(\n  detail: { exceptionType?: string; message?: string; httpStatusCode?: number },\n  ts: string,\n): EdgeErrorExemplar {\n  return {\n    ...(detail.exceptionType !== undefined ? { exceptionType: detail.exceptionType } : {}),\n    ...(detail.message !== undefined\n      ? { message: detail.message.slice(0, EDGE_ERROR_MESSAGE_MAX) }\n      : {}),\n    ...(detail.httpStatusCode !== undefined ? { httpStatusCode: detail.httpStatusCode } : {}),\n    at: ts,\n  }\n}\n\n// The detail for a failing span's edge exemplar (ADR-236): the real span\n// exception type/message (the `exception` event, parsed in `otel.ts`) plus the\n// HTTP response status when the failure is an HTTP one (`httpResponseStatus`,\n// the same helper the incident path reads). Returns `undefined` when the span\n// carries none of these — a failure with no detail leaves any prior exemplar\n// untouched (`upsertObservedEdge`). A non-exception, non-HTTP failure (a bare\n// gRPC status with no exception event) resolves to no detail here and rides as a\n// plain error count, honestly — the exemplar never fabricates a reason.\nfunction edgeErrorDetailFromSpan(\n  span: ParsedSpan,\n): { exceptionType?: string; message?: string; httpStatusCode?: number } | undefined {\n  const exceptionType = span.exception?.type\n  const message = span.exception?.message\n  const httpStatusCode = httpResponseStatus(span)\n  if (exceptionType === undefined && message === undefined && httpStatusCode === undefined) {\n    return undefined\n  }\n  return {\n    ...(exceptionType !== undefined ? { exceptionType } : {}),\n    ...(message !== undefined ? { message } : {}),\n    ...(httpStatusCode !== undefined ? { httpStatusCode } : {}),\n  }\n}\n\nexport function upsertObservedEdge(\n  graph: NeatGraph,\n  type: EdgeTypeValue,\n  source: string,\n  target: string,\n  ts: string,\n  isError = false,\n  evidence?: { file: string; line?: number },\n  // Span duration in ms (ADR-190). Present on span-derived edges; absent on a\n  // connector edge with no provider latency, which then carries no latency.\n  durationMs?: number,\n  // The failing observation's exception detail (ADR-236). When `isError` and\n  // this is present, it is written/overwritten onto `signal.lastError` as a\n  // bounded exemplar (last-write-wins, no history) so the edge carries WHAT\n  // failed. A non-error call, or an error without detail, leaves any prior\n  // exemplar untouched — mirrors the latency \"absent leaves prior untouched\"\n  // rule above. The caller trims `message` before passing it.\n  errorDetail?: { exceptionType?: string; message?: string; httpStatusCode?: number },\n): UpsertResult | null {\n  if (!graph.hasNode(source) || !graph.hasNode(target)) return null\n\n  // ADR-142 — grain is a stored fact, not a re-derivation. A `file:` source means\n  // a call site was captured (observedSource / the connector's callSite path both\n  // mint a FileNode only when they have one), so the edge is file-grained;\n  // anything else (service:/infra:/frontier:) is the coarse service-grained\n  // fallback. Set on both the OTel and the connector path — they share this mint.\n  // A `symbol:` source is finer still (ADR-158) — the call site landed on the\n  // calling symbol under its file — and belongs in the same call-site-captured\n  // bucket as `file:`, never the coarse service fallback.\n  const grain: 'file' | 'service' =\n    source.startsWith('file:') || source.startsWith('symbol:') ? 'file' : 'service'\n\n  const id = makeObservedEdgeId(type, source, target)\n  if (graph.hasEdge(id)) {\n    const existing = graph.getEdgeAttributes(id) as GraphEdge\n    const newSpanCount = (existing.signal?.spanCount ?? existing.callCount ?? 0) + 1\n    const newErrorCount = (existing.signal?.errorCount ?? 0) + (isError ? 1 : 0)\n    // Fold this span's duration into the bounded per-edge latency histogram and\n    // re-derive p50/p95 (latency-digest.ts, ADR-190). A call with no duration\n    // (a connector signal) leaves the prior latency untouched, never clears it.\n    const latencyHist =\n      durationMs !== undefined\n        ? recordLatency({ ...(existing.signal?.latencyHist ?? {}) }, durationMs)\n        : existing.signal?.latencyHist\n    const latencyMs = latencyPercentiles(latencyHist) ?? existing.signal?.latencyMs\n    // Bounded last-error exemplar (ADR-236): a failing observation that carries\n    // detail overwrites it (last-write-wins, O(1)); a clean call or a failure\n    // without detail leaves the prior exemplar untouched, mirroring latency.\n    const lastError =\n      isError && errorDetail\n        ? buildEdgeErrorExemplar(errorDetail, ts)\n        : existing.signal?.lastError\n    const newSignal = {\n      spanCount: newSpanCount,\n      errorCount: newErrorCount,\n      lastObservedAgeMs: 0,\n      ...(latencyHist ? { latencyHist } : {}),\n      ...(latencyMs ? { latencyMs } : {}),\n      ...(existing.signal?.anomalous !== undefined\n        ? { anomalous: existing.signal.anomalous }\n        : {}),\n      ...(lastError ? { lastError } : {}),\n    }\n    // ADR-066 §2 — confidence grades from the signal block. PROV_RANK stays;\n    // the grade reflects volume + recency + error ratio within the OBSERVED\n    // tier.\n    const updated: GraphEdge = {\n      ...existing,\n      provenance: Provenance.OBSERVED,\n      lastObserved: ts,\n      callCount: newSpanCount,\n      signal: newSignal,\n      confidence: confidenceForObservedSignal(newSignal),\n      grain, // backfills legacy edges that predate ADR-142\n    }\n    graph.replaceEdgeAttributes(id, updated)\n    return { edge: updated, created: false }\n  }\n\n  const latencyHist = durationMs !== undefined ? recordLatency({}, durationMs) : undefined\n  const latencyMs = latencyHist ? latencyPercentiles(latencyHist) : undefined\n  const lastError = isError && errorDetail ? buildEdgeErrorExemplar(errorDetail, ts) : undefined\n  const signal = {\n    spanCount: 1,\n    errorCount: isError ? 1 : 0,\n    lastObservedAgeMs: 0,\n    ...(latencyHist ? { latencyHist } : {}),\n    ...(latencyMs ? { latencyMs } : {}),\n    ...(lastError ? { lastError } : {}),\n  }\n  const edge: GraphEdge = {\n    id,\n    source,\n    target,\n    type,\n    provenance: Provenance.OBSERVED,\n    confidence: confidenceForObservedSignal(signal),\n    lastObserved: ts,\n    callCount: 1,\n    signal,\n    grain,\n    // Call-site evidence from span code.* semconv (file-awareness.md §4 + §6).\n    // Only set when code.filepath was present on the span — never fabricated.\n    ...(evidence ? { evidence } : {}),\n  }\n  graph.addEdgeWithKey(id, source, target, edge)\n  return { edge, created: true }\n}\n\n// When a span errors, the system is exercising its dependencies right now even\n// if some of them aren't auto-instrumented (pg 7.4.0 in the demo, see ADR-014).\n// Walk EXTRACTED edges out from the erroring service for a couple of hops and\n// promote them to INFERRED twins so traversal can prefer them over the bare\n// static edges without claiming OBSERVED-grade certainty.\nfunction stitchTrace(graph: NeatGraph, sourceServiceId: string, ts: string): void {\n  if (!graph.hasNode(sourceServiceId)) return\n\n  const visited = new Set<string>([sourceServiceId])\n  const queue: { nodeId: string; depth: number }[] = [{ nodeId: sourceServiceId, depth: 0 }]\n\n  while (queue.length > 0) {\n    const { nodeId, depth } = queue.shift()!\n    if (depth >= STITCH_MAX_DEPTH) continue\n\n    const outbound = graph.outboundEdges(nodeId)\n    for (const edgeId of outbound) {\n      const edge = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (edge.provenance !== Provenance.EXTRACTED) continue\n\n      // Only runtime dependency edges get stitched. Structural edges (CONTAINS /\n      // IMPORTS / CONFIGURED_BY / RUNS_ON) are never mirrored into INFERRED twins\n      // and the BFS does not recurse through them — an error propagates along\n      // dependencies, not static containment (trace-stitcher.md allowlist).\n      if (!STITCH_EDGE_TYPES.has(edge.type)) continue\n\n      // OBSERVED twin already covers this hop with ground truth — no inference\n      // needed (ADR-034). Stomping it with INFERRED erases the gap NEAT exists\n      // to surface; skipping it keeps the OBSERVED edge as the authoritative\n      // record and avoids cluttering the graph with a redundant INFERRED twin.\n      if (graph.hasEdge(observedEdgeId(edge.source, edge.target, edge.type))) continue\n\n      upsertInferredEdge(graph, edge.type, edge.source, edge.target, ts)\n\n      if (!visited.has(edge.target)) {\n        visited.add(edge.target)\n        queue.push({ nodeId: edge.target, depth: depth + 1 })\n      }\n    }\n  }\n}\n\nfunction upsertInferredEdge(\n  graph: NeatGraph,\n  type: EdgeTypeValue,\n  source: string,\n  target: string,\n  ts: string,\n): void {\n  const id = makeInferredEdgeId(type, source, target)\n  if (graph.hasEdge(id)) {\n    const existing = graph.getEdgeAttributes(id) as GraphEdge\n    const updated: GraphEdge = { ...existing, lastObserved: ts }\n    graph.replaceEdgeAttributes(id, updated)\n    return\n  }\n\n  const edge: GraphEdge = {\n    id,\n    source,\n    target,\n    type,\n    provenance: Provenance.INFERRED,\n    confidence: INFERRED_CONFIDENCE,\n    lastObserved: ts,\n  }\n  graph.addEdgeWithKey(id, source, target, edge)\n}\n\n// Announce a freshly-recorded incident on the event bus (ADR-221). A lean\n// trigger — the affected node, service, and kind — that wakes `neat monitor`;\n// the full incident card is a REST read (GET /graph/incident-card/:nodeId). The\n// monitor dedupes on the incident id, so a stray double-emit is harmless. Fired\n// from every incident write path that knows its project: the OTel paths (this\n// one, plus the receiver's synchronous writer for status-error spans) and\n// connector incidents (ADR-185) through appendConnectorIncident, which threads\n// the project from its poll caller.\nfunction emitIncidentEvent(project: string, ev: ErrorEvent): void {\n  emitNeatEvent({\n    type: 'incident',\n    project,\n    payload: {\n      incidentId: ev.id,\n      affectedNode: ev.affectedNode,\n      service: ev.service,\n      incidentKind: incidentKindOf(ev),\n      at: ev.timestamp,\n    },\n  })\n}\n\nasync function appendErrorEvent(ctx: IngestContext, ev: ErrorEvent): Promise<void> {\n  await appendRuntimeIncident(ctx.errorsPath, ctx.project ?? DEFAULT_PROJECT, ev)\n  emitIncidentEvent(ctx.project ?? DEFAULT_PROJECT, ev)\n}\n\n// The semantic fields an incident-emitting connector's failure carries, minus\n// the ErrorEvent bookkeeping this function fills in (ADR-185, connectors.md §10).\nexport interface ConnectorIncidentInput {\n  // Stable dedupe key for the one failure (e.g. `eas:build:<buildId>`).\n  id: string\n  // The failure's own event time (ISO8601).\n  timestamp: string\n  // The NEAT service the failure belongs to.\n  service: string\n  // Short stable classifier (e.g. 'eas-build-failure'), the connector analog of\n  // the 'http-failure' errorType the response-code incidents carry.\n  errorType: string\n  // The human-readable failure line the incident surface shows.\n  errorMessage: string\n  // Provider context passed through verbatim (phase, commit, capped logs, docs\n  // URL). Same JSON-safe shape ErrorEvent.attributes carries.\n  attributes?: ErrorEvent['attributes']\n  // The graph node the failure implicates — already resolved by the connector's\n  // resolveTarget through the fused-node lookup, so this lands on the extracted\n  // node get_incident_history / get_root_cause query, never a twin.\n  affectedNode: string\n}\n\n// Write one connector-sourced incident to the project's incident ledger\n// (`errors.ndjson`) — the SAME store OTLP-derived incidents use, so\n// get_incident_history / get_root_cause read it with no special-casing (ADR-185,\n// connectors.md §10). The connectors plane has no mutation authority (ADR-030),\n// so it calls this ingest.ts primitive rather than writing the ledger itself.\n//\n// A connector failure carries no OTel trace, but the ErrorEvent shape requires\n// traceId/spanId. They are derived deterministically from the stable `id` so a\n// re-poll of the same failure collapses on them the same way `dedupeIncidents`\n// collapses on `id`, and two distinct failures never share a (traceId,\n// affectedNode) group. errorType is always set, so the incident is never mistaken\n// for a synthesized-HTTP echo and dropped.\nexport async function appendConnectorIncident(\n  errorsPath: string,\n  input: ConnectorIncidentInput,\n  project?: string,\n): Promise<void> {\n  const ev: ErrorEvent = {\n    id: input.id,\n    timestamp: input.timestamp,\n    service: input.service,\n    traceId: input.id,\n    spanId: input.id,\n    errorType: input.errorType,\n    errorMessage: input.errorMessage,\n    ...(input.attributes && Object.keys(input.attributes).length > 0\n      ? { attributes: input.attributes }\n      : {}),\n    affectedNode: input.affectedNode,\n  }\n  await appendRuntimeIncident(errorsPath, project ?? DEFAULT_PROJECT, ev)\n  // Push it onto the bus (ADR-221) exactly as the OTLP paths do, so a\n  // connector-sourced failure reaches an agent's monitor too — same event, same\n  // lean payload. Only when the caller threaded a project; a programmatic caller\n  // that passes none still writes the ledger, it just doesn't push.\n  if (project) emitIncidentEvent(project, ev)\n}\n\n// The node an incident is attributed to, plus a code locus RECOVERED from the\n// stacktrace when the span carried no `code.*` attributes of its own. The\n// recovered locus is set only on the stacktrace-fallback path (ADR-216); the\n// incident builders synthesize it onto the record so `symbolLocus`, root-cause,\n// and the incidents surface all read the declaring file:line the same way a span\n// that stamped `code.*` already does.\ninterface IncidentLocus {\n  affectedNode: string\n  codeFilepath?: string\n  codeLineno?: number\n}\n\n// Land a resolved runtime call site on the finest code node the graph carries —\n// the SYMBOL the line falls inside, else its FileNode, else the honest raw\n// service-relative file id. `trusted` distinguishes the two entry paths: a\n// span's own `code.*` call site is authoritative and lands on the file id even\n// when the graph has no matching node yet (the file:line is real, unchanged\n// pre-ADR-216 behavior); a stacktrace-recovered frame is a heuristic join, so it\n// attributes to code ONLY when it resolves to a FileNode the graph already\n// holds, and otherwise recovers nothing (never fabricated). Returns null to mean\n// \"keep the service attribution\".\nfunction landIncidentCallSite(\n  span: ParsedSpan,\n  callSite: CallSite,\n  trusted: boolean,\n  graph?: NeatGraph,\n): IncidentLocus | null {\n  const relPath = graph\n    ? reconcileObservedRelPath(graph, span.service, callSite.relPath)\n    : callSite.relPath\n  // Descend one grain finer to the SYMBOL the failure surfaced in — the same\n  // span-containment resolution OBSERVED edges use (landObservedSymbol, ADR-158\n  // §4) — so an in-process throw attributes to the function, not just its file\n  // (ADR-191). Keyed on the fused service name so the symbol id matches the\n  // statically-extracted symbol it fuses onto. Read-only (mint=false): it lands\n  // on an existing static symbol whose span contains the line, and degrades to\n  // the file honestly when no static symbol contains the line.\n  const canonicalService = serviceNodeName(graph, span) ?? span.service\n  const recovered = !trusted\n  if (graph) {\n    const fusedFileId = fileId(canonicalService, relPath)\n    if (graph.hasNode(fusedFileId)) {\n      const node = landObservedSymbol(\n        graph,\n        fusedFileId,\n        canonicalService,\n        relPath,\n        { ...callSite, relPath },\n        false,\n      )\n      return {\n        affectedNode: node,\n        ...(recovered\n          ? {\n              codeFilepath: relPath,\n              ...(callSite.line !== undefined ? { codeLineno: callSite.line } : {}),\n            }\n          : {}),\n      }\n    }\n    // A recovered frame that joins to no graph node is not attributed to code —\n    // that would fabricate a locus the graph can't vouch for. The trusted\n    // `code.*` path keeps its honest file id.\n    if (recovered) return null\n  }\n  return { affectedNode: fileId(span.service, relPath) }\n}\n\n// The fused ServiceNode's canonical name, so a differently-cased or env-tagged\n// `service.name` keys the same node the extractor minted (#880 / #988).\nfunction serviceNodeName(graph: NeatGraph | undefined, span: ParsedSpan): string | undefined {\n  if (!graph) return undefined\n  const sid = resolveFusedServiceId(graph, span.service, span.env)\n  if (!graph.hasNode(sid)) return undefined\n  const node = graph.getNodeAttributes(sid) as ServiceNode\n  return typeof node.name === 'string' ? node.name : undefined\n}\n\n// Recover a call site from the exception stacktrace's deepest application frame\n// (ADR-216) — the fallback for a span that carries a stacktrace but no `code.*`\n// attributes, the dominant shape of Python (and other) auto-instrumented\n// exception spans. The frame's absolute deploy path runs through the same\n// runtime-path → service-relative join a `code.*` call site uses, so it lands on\n// the FileNode the extractor already minted. Returns null when the stacktrace\n// names no application frame.\nfunction stacktraceCallSite(\n  span: ParsedSpan,\n  serviceNode: ServiceNode | undefined,\n  scanPath?: string,\n): CallSite | null {\n  const frame = deepestApplicationFrame(span.exception?.stacktrace)\n  if (!frame) return null\n  const relPath = relPathForRuntimeFile(frame.file, serviceNode, scanPath)\n  if (!relPath) return null\n  return { relPath, line: frame.line, ...(frame.fn ? { fn: frame.fn } : {}) }\n}\n\n// Resolve the incident's affectedNode (and any recovered code locus). When the\n// span carries a `code.filepath` call site, the incident attributes to the\n// FileNode/SymbolNode the failure surfaced in — the same file grain OBSERVED\n// CALLS edges land on (file-awareness.md §4) — resolving a compiled `dist/…js`\n// frame through its disk-adjacent source map when one is present. When the span\n// carries no call site but does carry an exception stacktrace, the deepest\n// application frame is parsed and run through the same runtime-path → graph-node\n// join (ADR-216), so a stacktrace-only exception span (Python\n// auto-instrumentation, the prime case) is attributed to code instead of\n// degrading to the service. Without either, or when a recovered frame joins to\n// no graph node, it stays at the originating service, the honest fallback (§2).\n//\n// The runtime paths are deploy-absolute (`/usr/src/app/…` in a container image,\n// `/var/task/…` on Lambda) and need not match the daemon's checkout; when the\n// graph is available they're reconciled onto the service-relative path the\n// extractor already minted (reconcileObservedRelPath), so the incident lands on\n// the ONE fused FileNode instead of a phantom keyed off the absolute path — the\n// node root-cause actually walks.\nfunction incidentLocus(\n  span: ParsedSpan,\n  graph?: NeatGraph,\n  scanPath?: string,\n): IncidentLocus {\n  // Resolve onto the fused ServiceNode the same way handleSpan's edge upserts\n  // do (ensureServiceNode / resolveFusedServiceId) — a case-insensitive,\n  // env-ignoring match against the extracted node — so an errored span carrying\n  // `deployment.environment` (or a differently-cased service.name) and no call\n  // site attributes to the ONE `service:<name>` the graph holds, not a phantom\n  // `service:<name>:<env>` twin that's absent from it, which get_incident_history\n  // and get_root_cause then miss (#988). Without a graph (the ad-hoc receiver\n  // surface, no fusion target) the honest raw serviceId stands.\n  const sid = graph\n    ? resolveFusedServiceId(graph, span.service, span.env)\n    : serviceId(span.service, span.env)\n  const serviceNode =\n    graph && graph.hasNode(sid)\n      ? (graph.getNodeAttributes(sid) as ServiceNode)\n      : undefined\n\n  const callSite = callSiteFromSpan(span, serviceNode, scanPath)\n  if (callSite) {\n    const landed = landIncidentCallSite(span, callSite, true, graph)\n    if (landed) return landed\n  } else {\n    const recovered = stacktraceCallSite(span, serviceNode, scanPath)\n    if (recovered) {\n      const landed = landIncidentCallSite(span, recovered, false, graph)\n      if (landed) return landed\n    }\n  }\n  return { affectedNode: sid }\n}\n\nfunction incidentAffectedNode(\n  span: ParsedSpan,\n  graph?: NeatGraph,\n  scanPath?: string,\n): string {\n  return incidentLocus(span, graph, scanPath).affectedNode\n}\n\n// Merge a stacktrace-recovered code locus onto an incident's attributes so the\n// synthesized `code.filepath`/`code.lineno` ride the record the same way a\n// span's own `code.*` would — `symbolLocus` (divergences.ts), root-cause, and\n// the incidents surface all read them. A no-op when the span already carried\n// `code.*` (locus.codeFilepath unset): the real attributes stand untouched.\nfunction withRecoveredCodeAttrs(\n  attrs: ReturnType<typeof sanitizeAttributes>,\n  locus: IncidentLocus,\n): ReturnType<typeof sanitizeAttributes> {\n  if (locus.codeFilepath === undefined) return attrs\n  attrs[CODE_FILEPATH_ATTR] = locus.codeFilepath\n  if (locus.codeLineno !== undefined) attrs[CODE_LINENO_ATTR] = locus.codeLineno\n  return attrs\n}\n\n// Build the minimal ErrorEvent the receiver writes synchronously before\n// replying (ADR-033 §Error events, amended). affectedNode attributes to the\n// FileNode when the span carries a `code.filepath` call site, else to the\n// originating service (incidentAffectedNode above).\n//\n// errorMessage reads from the exception event's `exception.message` (OTel\n// semconv) so the incident surface shows the actual thrown error string.\n// When the span carries no exception event the field falls back to the HTTP\n// context the span still holds — \"500 on GET /users/:id\" (httpFailureMessage)\n// — and only then to the literal 'unknown error'. `span.name` is never in the\n// chain: OTel HTTP server instrumentation routinely populates it with the HTTP\n// method, which produces incidents that read 'GET' or 'POST' instead of the\n// underlying failure. `span.status.message` is intentionally out for the same\n// reason.\n\nexport function buildErrorEventForReceiver(\n  span: ParsedSpan,\n  graph?: NeatGraph,\n  scanPath?: string,\n): ErrorEvent | null {\n  if (span.statusCode !== 2) return null\n  const ts = span.startTimeIso ?? new Date().toISOString()\n  const locus = incidentLocus(span, graph, scanPath)\n  const attrs = withRecoveredCodeAttrs(sanitizeAttributes(span.attributes), locus)\n  // #1118 — an ERROR-status span can also carry an HTTP response status: an\n  // ingress/proxy (Envoy) returns a 504 with status=Error and the code in the\n  // old-semconv `http.status_code` (a string). httpResponseStatus reads both\n  // semconv keys and coerces the string, so surface it here — otherwise the 504\n  // is dropped and the incident reads as a generic exception. incidentKindOf\n  // reads httpStatusCode to classify a 5xx, and the #1114 boundary-timeout\n  // classifier reads it to recognise a gateway timeout. Deliberately NOT tagging\n  // errorType: the SERVER-5xx echo of a downstream failure is identified by an\n  // absent errorType (isSynthesizedHttpIncident) so the trace-dedupe (#624) can\n  // drop it — tagging it would defeat that collapse.\n  const httpStatus = httpResponseStatus(span)\n  return {\n    id: `${span.traceId}:${span.spanId}`,\n    timestamp: ts,\n    service: span.service,\n    traceId: span.traceId,\n    spanId: span.spanId,\n    errorMessage: incidentMessage(span),\n    ...(span.exception?.type ? { exceptionType: span.exception.type } : {}),\n    ...(span.exception?.stacktrace\n      ? { exceptionStacktrace: span.exception.stacktrace }\n      : {}),\n    ...(httpStatus !== undefined ? { httpStatusCode: httpStatus } : {}),\n    ...(Object.keys(attrs).length > 0 ? { attributes: attrs } : {}),\n    affectedNode: locus.affectedNode,\n  }\n}\n\n// Synchronous file-write helper bound to a receiver. The receiver awaits this\n// before replying, so a write failure surfaces as 500 → OTel SDK retries.\nexport function makeErrorSpanWriter(\n  errorsPath: string,\n  graph?: NeatGraph,\n  scanPath?: string,\n  project: string = DEFAULT_PROJECT,\n): (span: ParsedSpan) => Promise<void> {\n  return async (span) => {\n    const ev = buildErrorEventForReceiver(span, graph, scanPath)\n    if (!ev) return\n    await appendRuntimeIncident(errorsPath, project, ev)\n    emitIncidentEvent(project, ev)\n  }\n}\n\n// Write one failing-response incident (issue #481) to errors.ndjson. Used for\n// an unambiguous 5xx (count 1) and for a flushed 4xx burst (count N). The\n// dominant status code names the failure; `incidentCount` carries N so the\n// incident surface shows \"5× 404\" without the per-span flood. Span attributes\n// pass through verbatim, same as the statusCode === 2 path, so source\n// attribution (`code.*`) and the response code survive to the consumer.\nasync function recordFailingResponseIncident(\n  ctx: IngestContext,\n  span: ParsedSpan,\n  affectedNode: string,\n  timestamp: string,\n  statusCode: number,\n  count: number,\n  firstTimestamp?: string,\n): Promise<void> {\n  const attrs = sanitizeAttributes(span.attributes)\n  const first = firstTimestamp ?? timestamp\n  const peer = pickAddress(span)\n  const message =\n    count > 1\n      ? `${count} consecutive HTTP ${statusCode} responses` +\n        (peer ? ` to ${peer}` : '')\n      : `HTTP ${statusCode} response` + (peer ? ` from ${peer}` : '')\n  const ev: ErrorEvent = {\n    id: `${span.traceId}:${span.spanId}`,\n    timestamp,\n    service: span.service,\n    traceId: span.traceId,\n    spanId: span.spanId,\n    errorType: 'http-failure',\n    errorMessage: message,\n    ...(Object.keys(attrs).length > 0 ? { attributes: attrs } : {}),\n    affectedNode,\n    httpStatusCode: statusCode,\n    incidentCount: count,\n    firstTimestamp: first,\n    lastTimestamp: timestamp,\n  }\n  await appendErrorEvent(ctx, ev)\n}\n\n// Record one incident for a span that carries an exception event but no ERROR\n// status and no HTTP failure code — an async / queue / background worker\n// (bullmq, Redis Streams, a scheduled task) whose job threw (ADR-117). Incident\n// recording keys on the failure signal, not on HTTP context: the message\n// follows the shared incidentMessage chain and the record attributes to the\n// handler file:line when the span carries `code.filepath`, else to the\n// originating service (incidentAffectedNode). handleSpan owns this write — the\n// receiver's synchronous error-writer fires only for statusCode === 2, so an\n// exception-only worker span reaches durability here, the same way the\n// response-code incidents below do.\nasync function recordExceptionIncident(\n  ctx: IngestContext,\n  span: ParsedSpan,\n  ts: string,\n): Promise<void> {\n  const locus = incidentLocus(span, ctx.graph, ctx.scanPath)\n  const attrs = withRecoveredCodeAttrs(sanitizeAttributes(span.attributes), locus)\n  const ev: ErrorEvent = {\n    id: `${span.traceId}:${span.spanId}`,\n    timestamp: ts,\n    service: span.service,\n    traceId: span.traceId,\n    spanId: span.spanId,\n    errorMessage: incidentMessage(span),\n    ...(span.exception?.type ? { exceptionType: span.exception.type } : {}),\n    ...(span.exception?.stacktrace\n      ? { exceptionStacktrace: span.exception.stacktrace }\n      : {}),\n    ...(Object.keys(attrs).length > 0 ? { attributes: attrs } : {}),\n    affectedNode: locus.affectedNode,\n  }\n  await appendErrorEvent(ctx, ev)\n}\n\n// Record one incident for a non-OK gRPC span (issue #1065). OTel's gRPC\n// instrumentation leaves the span status UNSET and carries the outcome in\n// `rpc.grpc.status_code` (0 = OK), so both the ERROR-status path and the HTTP\n// response-code path above miss it — the dominant failure representation on a\n// gRPC microservice stack, and the reason get_incident_history read empty over a\n// service whose calls were all failing INTERNAL (13). Recorded immediately, the\n// same as an unambiguous 5xx: gRPC has no numeric 4xx/5xx split to coalesce on,\n// and the errorCount signal already counts every non-OK code, so the incident\n// ledger agrees with it. The message names the canonical gRPC status\n// (incidentMessage → nonHttpFailureMessage) and the raw `rpc.grpc.status_code`\n// rides along in the passed-through attributes; attribution matches the\n// exception path — the handler `file:line` when the span carries `code.filepath`,\n// the failing service otherwise (incidentAffectedNode).\nasync function recordGrpcFailureIncident(\n  ctx: IngestContext,\n  span: ParsedSpan,\n  ts: string,\n): Promise<void> {\n  const attrs = sanitizeAttributes(span.attributes)\n  const ev: ErrorEvent = {\n    id: `${span.traceId}:${span.spanId}`,\n    timestamp: ts,\n    service: span.service,\n    traceId: span.traceId,\n    spanId: span.spanId,\n    errorType: 'grpc-failure',\n    errorMessage: incidentMessage(span),\n    ...(Object.keys(attrs).length > 0 ? { attributes: attrs } : {}),\n    affectedNode: incidentAffectedNode(span, ctx.graph, ctx.scanPath),\n  }\n  await appendErrorEvent(ctx, ev)\n}\n\n// Advance the 4xx burst for this (source, peer) pair (issue #481). A burst\n// accumulates silently; only when it crosses the threshold inside the window\n// does it flush ONE coalesced incident. A 4xx that arrives more than windowMs\n// after the previous one resets the burst — a slow trickle of probes never\n// coalesces. The dominant code is the most frequent 4xx seen across the burst.\nasync function advance4xxBurst(\n  ctx: IngestContext,\n  span: ParsedSpan,\n  affectedNode: string,\n  ts: string,\n  nowMs: number,\n  status: number,\n): Promise<void> {\n  const { threshold, windowMs } = loadIncidentThresholdsFromEnv()\n  if (!ctx.burstState) ctx.burstState = new Map()\n  const peer = pickAddress(span) ?? span.spanId\n  const key = `${span.service}->${peer}`\n  const existing = ctx.burstState.get(key)\n  let state: BurstState\n  if (existing && nowMs - existing.lastMs <= windowMs) {\n    existing.count += 1\n    existing.lastTs = ts\n    existing.lastMs = nowMs\n    existing.codes.set(status, (existing.codes.get(status) ?? 0) + 1)\n    state = existing\n  } else {\n    state = {\n      count: 1,\n      firstTs: ts,\n      lastTs: ts,\n      lastMs: nowMs,\n      codes: new Map([[status, 1]]),\n    }\n    ctx.burstState.set(key, state)\n  }\n\n  if (state.count < threshold) return\n\n  // Threshold met — flush one incident carrying the count, the dominant code,\n  // and the burst's first/last timestamps, then clear the burst so the next\n  // run of failures records its own incident rather than re-flushing every span.\n  let dominant = status\n  let max = 0\n  for (const [code, n] of state.codes) {\n    if (n > max) {\n      max = n\n      dominant = code\n    }\n  }\n  await recordFailingResponseIncident(\n    ctx,\n    span,\n    affectedNode,\n    state.lastTs,\n    dominant,\n    state.count,\n    state.firstTs,\n  )\n  ctx.burstState.delete(key)\n}\n\n// Next.js API-route serving spans name the matched route in `next.span_name`\n// (mirrored on the span's own name), NOT in `http.route`: the Pages Router emits\n// `executing api route (pages) /api/products/[productId]` and the App Router\n// `executing api route (app) /api/products/[productId]`. That phrase carries the\n// *templated* route — `[productId]` brackets and all — which is what fuses onto a\n// declared RouteNode; the same request's `http.target` carries only the concrete\n// path (`/api/products/L9ECAV7KIM`), which no param template ever matches. Pull\n// the template out of that phrase so a Next route earns its OBSERVED twin the way\n// an Express `http.route` already does (ADR-204). Returns undefined for any span\n// without the phrase, so the caller falls back to `http.route` and every other\n// framework fuses exactly as before — the source is additive, never a swap.\nconst NEXT_API_ROUTE_SPAN_NAME = /^executing api route \\((?:pages|app)\\) (\\/\\S*)$/\n\nfunction nextApiRouteTemplate(span: ParsedSpan): string | undefined {\n  const raw = pickAttr(span, 'next.span_name') ?? span.name\n  const match = raw ? NEXT_API_ROUTE_SPAN_NAME.exec(raw) : null\n  return match ? match[1] : undefined\n}\n\n// Match a SERVER span's `http.route` to the RouteNode the static extractor\n// minted, by normalized (method, template) so param-syntax differences\n// (`{id}` vs `:id` vs `<int:id>`) don't block the fusion. Returns the node id or\n// undefined; an unmatched route mints nothing here — a route NEAT never extracted\n// has no declared twin to fuse, and the served-but-undeclared case is a follow-on.\nfunction findRouteNodeByHttpRoute(\n  graph: NeatGraph,\n  serviceName: string,\n  method: string | undefined,\n  httpRoute: string,\n): string | undefined {\n  const target = normalizePathTemplate(httpRoute)\n  const m = method?.toUpperCase()\n  let found: string | undefined\n  graph.forEachNode((id, attrs) => {\n    if (found) return\n    const a = attrs as RouteNode & { type?: string }\n    if (a.type !== NodeType.RouteNode || a.service !== serviceName) return\n    if (m && a.method !== 'ALL' && a.method !== m) return\n    if (normalizePathTemplate(a.pathTemplate) === target) found = id\n  })\n  return found\n}\n\n// The request path of a SERVER span that names no route template (ADR-253, #1420):\n// `url.path`, else `http.target`, else the path of `url.full` / `http.url`, with\n// the query and fragment dropped. Jaeger-era and OpenTracing HTTP instrumentation\n// records the concrete request and never the matched template.\nfunction serverRequestPath(span: ParsedSpan): string | undefined {\n  let raw = pickAttr(span, 'url.path', 'http.target')\n  if (!raw) {\n    const url = pickAttr(span, 'url.full', 'http.url')\n    if (!url) return undefined\n    try {\n      raw = new URL(url).pathname\n    } catch {\n      return undefined\n    }\n  }\n  const path = raw.split('?')[0]!.split('#')[0]!\n  return path.startsWith('/') ? path : undefined\n}\n\n// A declared template segment that names a parameter: `:id`, `{id}`, `<id>` /\n// `<int:id>`, `[id]`.\nfunction isTemplateParam(seg: string): boolean {\n  return seg.startsWith(':') || seg.startsWith('{') || seg.startsWith('<') || seg.startsWith('[')\n}\n\n// Match a SERVER span's concrete request path against the RouteNodes the static\n// extractor minted for its service. A param segment matches exactly one path\n// segment, a literal matches itself (case-insensitive), and the method must agree\n// when the span names one. Exactly one matching route joins; none or several join\n// nothing, so a request that two declared routes could serve is never guessed at.\n// RouteNodes only come from extraction, so a URL never mints one.\nfunction findRouteNodeByRequestPath(\n  graph: NeatGraph,\n  serviceName: string,\n  method: string | undefined,\n  requestPath: string,\n): string | undefined {\n  const segs = requestPath.split('/').filter((x) => x.length > 0)\n  const m = method?.toUpperCase()\n  const matches: string[] = []\n  graph.forEachNode((id, attrs) => {\n    const a = attrs as RouteNode & { type?: string }\n    if (a.type !== NodeType.RouteNode || a.service !== serviceName) return\n    if (m && a.method !== 'ALL' && a.method !== m) return\n    const tpl = a.pathTemplate.split('?')[0]!.split('/').filter((x) => x.length > 0)\n    if (tpl.length !== segs.length) return\n    for (let i = 0; i < tpl.length; i++) {\n      if (isTemplateParam(tpl[i]!)) continue\n      if (tpl[i]!.toLowerCase() !== segs[i]!.toLowerCase()) return\n    }\n    matches.push(id)\n  })\n  return matches.length === 1 ? matches[0] : undefined\n}\n\nexport async function handleSpan(ctx: IngestContext, span: ParsedSpan): Promise<void> {\n  // lastObserved derives from the span's own startTime per ADR-033 — replayed\n  // traces and out-of-order spans get a timestamp that reflects when the call\n  // actually fired, not when the receiver received it. Wall-clock is only the\n  // fallback for spans whose startTimeUnixNano is missing or unparseable.\n  const ts = span.startTimeIso ?? nowIso(ctx)\n  const nowMs = ctx.now ? ctx.now() : Date.now()\n  // Env discriminator from `deployment.environment(.name)` (ADR-074 §2).\n  // Older ParsedSpan producers may omit it — fall back to the literal\n  // `'unknown'` so the env-less wire format is preserved on auto-creation.\n  const env = span.env ?? 'unknown'\n  // Issue #374 — spans whose resource omits `service.name` route to\n  // `service:unidentified` in the URL-resolved project (the parser already\n  // substitutes the fallback). One warning per project per session names\n  // the project so an operator can fix the SDK config without grepping.\n  if (span.resourceServiceNamePresent === false) {\n    warnUnidentifiedSpan(ctx.project ?? DEFAULT_PROJECT)\n  }\n  // Auto-create a minimal ServiceNode for unseen span.service so OBSERVED\n  // edges land instead of silently dropping. Static extraction merges richer\n  // fields when it later finds the same id (ADR-033). The node is env-tagged\n  // when the span carries an env signal.\n  const sourceId = ensureServiceNode(ctx.graph, span.service, env)\n  // Fires on the span's own ERROR status AND on the attribute forms most gRPC/HTTP\n  // SDKs actually use — a non-OK gRPC status or an HTTP 5xx left on an UNSET span\n  // (spanRecordsError, issue #1065). This is the sole feed for the edge's\n  // errorCount signal, so the failing-CALLS chain get_root_cause walks now sees a\n  // gRPC-based stack's failures instead of reading them as clean traffic.\n  const isError = spanRecordsError(span)\n  // Span duration in ms for the OBSERVED latency signal (ADR-190). Only a real,\n  // positive duration is recorded; a span with missing/degenerate times\n  // contributes no latency rather than a fabricated zero (file-awareness.md §6).\n  // A streaming / long-lived span (WebSocket, SSE, a gRPC stream past the\n  // duration ceiling) carries the stream's whole lifetime as its duration, not a\n  // per-request latency, so it is withheld from the latency feed — the digest\n  // stays a per-request p95 and the saturation classifier does not false-fire\n  // (ADR-208). Every other signal on the span still records; `undefined` here\n  // leaves any prior latency on the edge untouched, never cleared (upsertObservedEdge).\n  const durationMs =\n    span.durationNanos > 0n && !spanStreams(ctx.graph, span)\n      ? Number(span.durationNanos) / 1e6\n      : undefined\n  // The bounded last-error exemplar's detail (ADR-236). Resolved once from the\n  // span's exception event + HTTP status and passed into every OBSERVED edge\n  // minted on this span's error path, so a failing edge carries WHAT failed —\n  // the real span exception type/message — not just an error count. Only built\n  // on a failing span; a clean span passes `undefined` and never disturbs a\n  // prior exemplar. The ledger still records the full exception independently\n  // (§Error events); this is the edge-level complement, not a replacement.\n  const errorDetail = isError ? edgeErrorDetailFromSpan(span) : undefined\n\n  // File-first OBSERVED origin (file-awareness.md §4). When the injected\n  // SpanProcessor captured a call site on this outbound (CLIENT/PRODUCER) span,\n  // the relationship originates from the file; without one it stays\n  // service-level. `observedSource()` creates the FileNode + CONTAINS lazily so\n  // they only land when an edge actually does — and never for the inbound\n  // (SERVER) parent-fallback side, which carries no call site.\n  const sourceServiceNode = ctx.graph.getNodeAttributes(sourceId) as ServiceNode\n  const callSite = callSiteFromSpan(span, sourceServiceNode, ctx.scanPath)\n\n  // Stash this span in the parent-span cache so any later child whose address\n  // resolution misses can still resolve the cross-service edge via parentSpanId.\n  // The call site rides along so the fallback edge anchors to this span's\n  // file:line when this span turns out to be a parent (issue #536).\n  cacheSpanService(span, nowMs, callSite)\n  const observedSource = (): string =>\n    callSite ? ensureObservedFileNode(ctx.graph, span.service, sourceId, callSite) : sourceId\n  // Evidence for the OBSERVED edge — populated from the span's code.* semconv\n  // when the call site resolved (file-awareness.md §4 + §6). Never fabricated:\n  // absent call site → undefined evidence. The path is reconciled the same way\n  // the edge's origin node is (reconcileObservedRelPath), so evidence.file names\n  // the fused EXTRACTED path the edge lands on rather than the raw deployed\n  // absolute path — otherwise the edge node and its own evidence disagree.\n  const callSiteEvidence: { file: string; line?: number } | undefined = callSite\n    ? {\n        file: reconcileObservedRelPath(ctx.graph, span.service, callSite.relPath),\n        ...(callSite.line !== undefined ? { line: callSite.line } : {}),\n      }\n    : undefined\n\n  let affectedNode = sourceId\n\n  // Feature-flag evaluations on this span (ADR-242): the second OBSERVED source\n  // for the flag grain, beside the store's own sync reader.\n  for (const ev of span.flagEvaluations ?? []) {\n    recordFlagEvaluation(ctx.graph, observedSource, ev, ts, callSiteEvidence)\n  }\n\n  // Only the caller/producer side of a call mints an OBSERVED edge directly\n  // (issue #429). INTERNAL / SERVER / CONSUMER spans don't: a SERVER/CONSUMER\n  // span is the callee, and its edge is minted from its parent via the\n  // parent-span fallback below (left ungated). Gating here keeps INTERNAL\n  // connection spans (`tcp.connect` / `tls.connect` with a peer address) from\n  // minting spurious service-level edges.\n  const mintsFromCallerSide = spanMintsObservedEdge(span.kind)\n\n  if (span.dbSystem) {\n    // Database span. A networked database resolves its DatabaseNode by peer\n    // host; an in-process / embedded one (SQLite, better-sqlite3, an in-memory\n    // store) crosses no network boundary and carries no peer address, so it\n    // keys on a service-scoped local identity instead (ADR-118). Both mint the\n    // same file-grained service→database CONNECTS_TO OBSERVED edge — the edge\n    // that makes a leaf service's datastore reads legible (#576, #546).\n    if (mintsFromCallerSide) {\n      const host = pickAddress(span)\n      // Engine comes off the OTel attribute as a string per Rule 8 — no\n      // hardcoded engine list on either branch.\n      let targetId: string\n      if (host) {\n        ensureDatabaseNode(ctx.graph, host, span.dbSystem)\n        targetId = databaseId(host)\n      } else {\n        // No peer host. Prefer fusing onto the service's declared database of\n        // the same engine (ADR-141) so an ORM's host-less span confirms the\n        // static dependency instead of minting a divergent twin. Falls back to a\n        // service-local node (ADR-118) for a genuinely embedded DB (SQLite) or an\n        // ambiguous declaration. Name the local node by its logical database\n        // (db.name) when the span carries one, the engine otherwise.\n        const declared = findDeclaredDatabaseForService(ctx.graph, sourceId, span.dbSystem)\n        if (declared) {\n          targetId = declared\n        } else {\n          const localName = span.dbName ?? span.dbSystem\n          targetId = ensureLocalDatabaseNode(\n            ctx.graph,\n            span.service,\n            localName,\n            span.dbSystem,\n          )\n        }\n      }\n      const result = upsertObservedEdge(\n        ctx.graph,\n        EdgeType.CONNECTS_TO,\n        observedSource(),\n        targetId,\n        ts,\n        isError,\n        callSiteEvidence,\n        durationMs,\n        errorDetail,\n      )\n      if (result) affectedNode = targetId\n\n      // ADR-148 — a mongodb span also names the collection it operated on, one\n      // grain finer than the database node above. Mint an additive OBSERVED\n      // CALLS edge to `infra:mongodb-collection:<name>` — the same node id the\n      // mongoose extractor emits (ensureInfraNode + infraId match calls/index.ts\n      // exactly) — so the declared and observed collection edges fuse instead of\n      // twinning. The collection is read straight off the span (dbCollection:\n      // db.collection.name / db.mongodb.collection), so it is ground truth where\n      // the extractor's Mongoose-pluralized derivation is quirk-wrong. Additive:\n      // a mongodb span with no collection still mints only the db-grain edge\n      // above.\n      if (span.dbSystem === 'mongodb' && span.dbCollection) {\n        const collectionId = ensureInfraNode(ctx.graph, 'mongodb-collection', span.dbCollection, 'self')\n        upsertObservedEdge(\n          ctx.graph,\n          EdgeType.CALLS,\n          observedSource(),\n          collectionId,\n          ts,\n          isError,\n          callSiteEvidence,\n          durationMs,\n          errorDetail,\n        )\n      }\n      // A SQL span's table (ADR-152), recovered from `db.statement` because the\n      // SQLAlchemy / dbapi instrumentation carries no table attribute. It mints\n      // onto the same `infra:sql-table:<name>` node the SQLAlchemy extractor\n      // produces, so the declared and observed table access fuse rather than\n      // twin. `db.statement`-derived, so it is ground truth where the extractor's\n      // model→table derivation is unresolved; additive to the db-grain edge.\n      if (span.dbTable) {\n        const tableId = ensureInfraNode(ctx.graph, 'sql-table', span.dbTable, 'self')\n        upsertObservedEdge(\n          ctx.graph,\n          EdgeType.CALLS,\n          observedSource(),\n          tableId,\n          ts,\n          isError,\n          callSiteEvidence,\n          durationMs,\n          errorDetail,\n        )\n        // ADR-157 — the same `db.statement` that named the table also names the\n        // columns it touched. Merge them onto the table node as OBSERVED column\n        // attributes (parsed in `parseOtlpRequest` via `columnsFromSqlStatement`).\n        // A statement that recovers no columns (`SELECT *`, a join/subquery\n        // degrade) grows nothing.\n        mergeObservedColumns(ctx.graph, tableId, span.dbColumns)\n      }\n    }\n  } else if (\n    span.messagingSystem &&\n    span.messagingDestination &&\n    spanMintsMessagingEdge(span.kind)\n  ) {\n    // Messaging span. The semantic destination is the topic / queue / stream the\n    // code talks to — not the broker host, which is transport. A PRODUCER span\n    // publishes; a CONSUMER span consumes. Both mint an OBSERVED edge to the same\n    // destination node the static extractor names (extract/calls/kafka.ts), so\n    // the declared and observed queue edges fuse into one (→ divergence) instead\n    // of twinning. File-grained through the same call-site path as any other\n    // OBSERVED edge (file-awareness.md §4): when the span carries `code.*`, the\n    // edge originates from the caller's FileNode at the exact call site,\n    // reconciled onto the EXTRACTED service-relative path (`reconcileObservedRelPath`,\n    // ADR-118); without a call site it stays service-level, honestly. This is the\n    // consumer-side pair of the producer edge — the queue topology the OBSERVED\n    // layer used to leave dark on the consumer side (issue #614).\n    const targetId = ensureMessagingDestinationNode(\n      ctx.graph,\n      span.messagingSystem,\n      span.messagingDestination,\n    )\n    const edgeType =\n      span.kind === WIRE_SPAN_KIND_CONSUMER\n        ? EdgeType.CONSUMES_FROM\n        : EdgeType.PUBLISHES_TO\n    const result = upsertObservedEdge(\n      ctx.graph,\n      edgeType,\n      observedSource(),\n      targetId,\n      ts,\n      isError,\n      callSiteEvidence,\n      durationMs,\n      errorDetail,\n    )\n    if (result) affectedNode = targetId\n  } else if (\n    span.graphqlOperationName &&\n    span.graphqlOperationType &&\n    spanServesGraphqlOperation(span.kind)\n  ) {\n    // GraphQL execution span (issue #615). Every GraphQL request rides one HTTP\n    // endpoint (`POST /graphql`), so at HTTP grain the whole API collapses to a\n    // single edge and the operation-level topology is invisible. The execution\n    // span carries the operation the client actually named — `graphql.operation.name`\n    // with `graphql.operation.type` — so mint an OBSERVED `CONTAINS` edge from the\n    // serving service to a per-operation node, the same ownership shape a service\n    // has over a route (ADR-119) and a file (file-awareness.md §2). OBSERVED-only:\n    // the SDL / resolver map is not parsed statically in this cut; the node is\n    // minted observed-first and a future static GraphQL extractor fuses onto the\n    // same id (ADR-122). File-grained through the same call-site path as any other\n    // OBSERVED edge (file-awareness.md §4): when the span carries `code.*` (the\n    // resolver call site) the edge originates from that `FileNode` at the exact\n    // `file:line`, reconciled onto the EXTRACTED service-relative path; without a\n    // call site it stays service-level, honestly. Both operation name and type\n    // must be present to key a stable id — a nameless/typeless execution span\n    // falls through rather than minting a fabricated operation.\n    const targetId = ensureGraphqlOperationNode(\n      ctx.graph,\n      span.service,\n      span.graphqlOperationType,\n      span.graphqlOperationName,\n    )\n    const result = upsertObservedEdge(\n      ctx.graph,\n      EdgeType.CONTAINS,\n      observedSource(),\n      targetId,\n      ts,\n      isError,\n      callSiteEvidence,\n      durationMs,\n      errorDetail,\n    )\n    if (result) affectedNode = targetId\n  } else if (\n    span.rpcSystem === 'grpc' &&\n    span.rpcService &&\n    span.rpcMethod &&\n    spanServesGrpcMethod(span.kind)\n  ) {\n    // gRPC execution span (issue #616). gRPC used to engage only at service\n    // grain: every method collapsed onto one service→service edge, so the\n    // per-method topology was invisible and one-sided. The serving span carries\n    // the method the caller actually invoked — `rpc.service` (the fully-qualified\n    // `orders.OrderService`) with `rpc.method` (`GetOrder`) — so mint an OBSERVED\n    // `CONTAINS` edge from the serving service to a per-method node, the same\n    // ownership shape a service has over a route (ADR-119), a GraphQL operation\n    // (ADR-122), and a file (file-awareness.md §2). The node is keyed on the\n    // fully-qualified `rpc.service` — the wire contract both the span and the\n    // `.proto` carry verbatim — so the static `.proto` extractor's declared\n    // method fuses onto this same id into a two-sided divergence (ADR-123).\n    // File-grained through the same call-site path as any other OBSERVED edge\n    // (file-awareness.md §4): when the span carries `code.*` (the handler call\n    // site) the edge originates from that `FileNode` at the exact `file:line`,\n    // reconciled onto the EXTRACTED service-relative path; without a call site it\n    // stays service-level, honestly. The gate admits only the serving side —\n    // SERVER / INTERNAL / unkinded — so a CLIENT span mints no ownership\n    // (client→method attribution is deferred) and instead falls through to the\n    // cross-service resolver, leaving the caller→callee edge intact. Both service\n    // and method must be present to key a stable id.\n    const targetId = ensureGrpcMethodNode(ctx.graph, span.rpcService, span.rpcMethod)\n    const result = upsertObservedEdge(\n      ctx.graph,\n      EdgeType.CONTAINS,\n      observedSource(),\n      targetId,\n      ts,\n      isError,\n      callSiteEvidence,\n      durationMs,\n      errorDetail,\n    )\n    if (result) affectedNode = targetId\n  } else if (span.websocketChannel && spanServesWebsocketChannel(span.kind)) {\n    // WebSocket upgrade span (issue #617). A WebSocket app used to produce no\n    // OBSERVED topology at all: only message-handler errors surfaced, as\n    // incidents, and the channels themselves stayed invisible — the frames after\n    // the handshake ride the socket, not more spans. The one span that reliably\n    // marks a channel is the HTTP upgrade that opens it: a SERVER `GET` carrying\n    // `Upgrade: websocket` and the connection path. So mint an OBSERVED\n    // `CONNECTS_TO` edge from the serving service to a per-channel node —\n    // reusing the same connection edge a service has to a datastore (#576), not a\n    // new edge type. Unlike the structural `CONTAINS` a service has over a route /\n    // operation / method — durably declared artifacts whose edge never goes\n    // stale — a channel's whole meaning is liveness, so `CONNECTS_TO` is the right\n    // shape: it carries `lastObserved` and decays OBSERVED → STALE on\n    // CONNECTS_TO's own threshold when the channel goes quiet (the daemon\n    // staleness loop, #532). OBSERVED-only: a WebSocket channel is known from\n    // observation, never from static extraction, so the node has no declared twin\n    // and is excluded from `missing-extracted` (divergences.ts). File-grained\n    // through the same call-site path as any other OBSERVED edge\n    // (file-awareness.md §4): when the span carries `code.*` the edge originates\n    // from that `FileNode` at the exact `file:line`, reconciled onto the EXTRACTED\n    // service-relative path; without a call site it stays service-level, honestly.\n    // The gate admits only the serving side — SERVER / INTERNAL / unkinded — so a\n    // CLIENT upgrade span mints no channel (client→channel attribution is\n    // deferred, ADR-125).\n    const targetId = ensureWebsocketChannelNode(\n      ctx.graph,\n      span.service,\n      span.websocketChannel,\n    )\n    const result = upsertObservedEdge(\n      ctx.graph,\n      EdgeType.CONNECTS_TO,\n      observedSource(),\n      targetId,\n      ts,\n      isError,\n      callSiteEvidence,\n      durationMs,\n      errorDetail,\n    )\n    if (result) affectedNode = targetId\n  } else {\n    // Possibly a cross-service call. Resolve the peer; if it matches a known\n    // ServiceNode, record an OBSERVED CALLS edge to the typed target. If it\n    // matches nothing — pod IP, ingress hostname, AWS PrivateLink endpoint —\n    // create a FrontierNode placeholder and record an OBSERVED edge to that\n    // FrontierNode so the call carries the same provenance + signal-block +\n    // graded confidence as any other OBSERVED edge (ADR-068). The target ref\n    // identifies the node-type; provenance describes how the edge was learned.\n    // promoteFrontierNodes (run by the extract orchestrator) rewrites the\n    // target ref once a later round resolves the host; the edge's provenance\n    // stays OBSERVED across promotion.\n    // A loopback host (localhost / 127.0.0.0/8 / ::1) is skipped here: it never\n    // resolves to a distinct peer, and minting frontier:localhost would double\n    // the edge that the callee's parent-span fallback already records for this\n    // same call (issues #590, #577). Leaving resolvedViaAddress false hands the\n    // call to that fallback instead.\n    const host = calleeAddress(span)\n    let resolvedViaAddress = false\n\n    // An opentracing datastore client (#1415). A Jaeger-converted datastore span\n    // carries no `db.system` — it names the engine in `peer.service` and the host in\n    // `peer.hostname` (DeathStarBench `memcached_get_profile`: peer.service=memcached,\n    // peer.hostname=memcached-profile). The OTel-native db branch above never fires on\n    // it, so resolve it the same way that branch does — a DatabaseNode keyed on the\n    // host, engine from `peer.service`, `CONNECTS_TO` — fusing onto the datastore node\n    // an OTel-native span would land on. Gated on `peer.service` naming an engine NEAT\n    // already recognizes (`knownDatastoreEngine`, the one list `classifyImage` reads),\n    // so a `peer.service` that is a service name mints nothing rather than a bogus\n    // DatabaseNode; a genuine service-name peer tier stays an unclaimed slot\n    // (otel-ingest §peer). Caller-side only, matching the db branch.\n    const datastoreEngine = mintsFromCallerSide\n      ? knownDatastoreEngine(span.peerService)\n      : undefined\n    if (datastoreEngine && span.peerHostname) {\n      const datastoreId = ensureDatabaseNode(ctx.graph, span.peerHostname, datastoreEngine)\n      upsertObservedEdge(\n        ctx.graph,\n        EdgeType.CONNECTS_TO,\n        observedSource(),\n        datastoreId,\n        ts,\n        isError,\n        callSiteEvidence,\n        durationMs,\n        errorDetail,\n      )\n      affectedNode = datastoreId\n      resolvedViaAddress = true\n    }\n\n    // Callee resolution is additive across grains, the way the db branch above mints\n    // a mongodb-collection / sql-table CALLS alongside the datastore edge, not instead\n    // of it:\n    //   • gRPC method (#1413) — a CLIENT span names the method it invoked via\n    //     `rpc.service` (the fully-qualified FQN) + `rpc.method`, the same pair the\n    //     serving branch (#616) and the static `.proto` key their `grpc:<service>/<method>`\n    //     node on. Mint an OBSERVED `CALLS` onto it — the invocation dual of the serving\n    //     side's `CONTAINS` ownership — a method-grain callee finer than the peer service.\n    //   • peer host — `server.address` / `net.peer.name` / url → ServiceNode, else a\n    //     bare-host FrontierNode. [#1415 peer.service/peer.hostname and #1411 ClusterIP→\n    //     ServiceNode via the k8s connector extend this host tier.]\n    // Both edges are minted, so the service→service reachability the host tier records\n    // is preserved. The one interaction: when the method node already captured the\n    // callee, an in-cluster ClusterIP on `server.address` needs no FrontierNode — the\n    // method node (owned by the serving service through its #616 / `.proto` CONTAINS\n    // edge) is the better-resolved callee, so caller→method→owner reaches it where an IP\n    // placeholder never would.\n    let grpcMethodNodeId: string | undefined\n    if (\n      mintsFromCallerSide &&\n      span.rpcSystem === 'grpc' &&\n      span.rpcService &&\n      span.rpcMethod\n    ) {\n      grpcMethodNodeId = ensureGrpcMethodNode(ctx.graph, span.rpcService, span.rpcMethod)\n      upsertObservedEdge(\n        ctx.graph,\n        EdgeType.CALLS,\n        observedSource(),\n        grpcMethodNodeId,\n        ts,\n        isError,\n        callSiteEvidence,\n        durationMs,\n        errorDetail,\n      )\n      affectedNode = grpcMethodNodeId\n      resolvedViaAddress = true\n    }\n\n    if (mintsFromCallerSide && host && host !== span.service && !isLoopbackHost(host)) {\n      const targetId =\n        resolveServiceId(ctx.graph, host, env) ?? serviceIdForObservedAddress(ctx.graph, host)\n      if (targetId && targetId !== sourceId) {\n        upsertObservedEdge(\n          ctx.graph,\n          EdgeType.CALLS,\n          observedSource(),\n          targetId,\n          ts,\n          isError,\n          callSiteEvidence,\n          durationMs,\n          errorDetail,\n        )\n        affectedNode = targetId\n        resolvedViaAddress = true\n      } else if (!targetId && !grpcMethodNodeId) {\n        // No gRPC method node captured this callee, so a bare host (pod IP, ingress\n        // hostname, a ClusterIP) still mints a FrontierNode placeholder (ADR-068).\n        const frontierNodeId = ensureFrontierNode(ctx.graph, host, ts)\n        upsertObservedEdge(\n          ctx.graph,\n          EdgeType.CALLS,\n          observedSource(),\n          frontierNodeId,\n          ts,\n          isError,\n          callSiteEvidence,\n          durationMs,\n          errorDetail,\n        )\n        affectedNode = frontierNodeId\n        resolvedViaAddress = true\n      }\n    }\n\n    // Parent-span fallback (ADR-033): when address-based resolution didn't\n    // produce an edge and the span has a parentSpanId we've cached, the\n    // parent's service identifies the caller. The current span is the server\n    // side of the call, so the edge direction is parent.service → current.\n    // The cached entry carries the parent span's env, so the auto-created\n    // parent ServiceNode lands on the env-tagged id the parent advertised.\n    if (!resolvedViaAddress && span.parentSpanId) {\n      const parent = lookupParentSpan(span.traceId, span.parentSpanId, nowMs)\n      if (parent && parent.service !== span.service) {\n        const parentId = ensureServiceNode(ctx.graph, parent.service, parent.env)\n        // When the parent span carried a `code.*` call site, originate the edge\n        // from the parent's FileNode so it anchors to file:line instead of the\n        // bare parent ServiceNode (issue #536). Without a cached call site the\n        // edge stays service-coarse — never fabricated (file-awareness.md §6).\n        const fallbackSource = parent.callSite\n          ? ensureObservedFileNode(ctx.graph, parent.service, parentId, parent.callSite)\n          : parentId\n        const fallbackEvidence: { file: string; line?: number } | undefined =\n          parent.callSite\n            ? {\n                file: reconcileObservedRelPath(\n                  ctx.graph,\n                  parent.service,\n                  parent.callSite.relPath,\n                ),\n                ...(parent.callSite.line !== undefined\n                  ? { line: parent.callSite.line }\n                  : {}),\n              }\n            : undefined\n        upsertObservedEdge(\n          ctx.graph,\n          EdgeType.CALLS,\n          fallbackSource,\n          sourceId,\n          ts,\n          isError,\n          fallbackEvidence,\n          durationMs,\n          errorDetail,\n        )\n      }\n    }\n  }\n\n  // A SERVER span's route fuses onto the declared RouteNode, giving an inbound\n  // route its OBSERVED twin the way GraphQL/gRPC serving spans do (#576). Matched\n  // by normalized (method, template) so a route NEAT extracted gets its observed\n  // counterpart; an unmatched route mints nothing here, honestly. Next.js names\n  // the template in `next.span_name` rather than `http.route`, so prefer that\n  // templated form over the concrete path when it's present (ADR-204); a span\n  // carrying neither falls through with no edge, as before.\n  // With no template at all, the concrete request path joins a declared route only\n  // when exactly one route of this service matches it (ADR-253).\n  const fusionRoute = nextApiRouteTemplate(span) ?? span.httpRoute\n  const requestPath = fusionRoute ? undefined : serverRequestPath(span)\n  if (\n    (fusionRoute || requestPath) &&\n    (span.kind === 2 || span.kind === 1 || span.kind === 0 || span.kind === undefined)\n  ) {\n    const routeNodeId = fusionRoute\n      ? findRouteNodeByHttpRoute(ctx.graph, span.service, span.httpMethod, fusionRoute)\n      : findRouteNodeByRequestPath(ctx.graph, span.service, span.httpMethod, requestPath!)\n    if (routeNodeId) {\n      const routeSvc = (ctx.graph.getNodeAttributes(routeNodeId) as RouteNode).service\n      upsertObservedEdge(ctx.graph, EdgeType.CONTAINS, serviceId(routeSvc), routeNodeId, ts, isError, undefined, durationMs, errorDetail)\n    }\n  }\n\n  if (span.statusCode === 2) {\n    stitchTrace(ctx.graph, sourceId, ts)\n    // The durable ErrorEvent write moved to the receiver so the file write\n    // happens synchronously before the 200 reply (ADR-033 §Error events,\n    // amended). watch.ts wires makeErrorSpanWriter into onErrorSpanSync.\n    // handleSpan still runs the in-graph error effects (stitchTrace above);\n    // it just doesn't append to errors.ndjson anymore. ctx.errorsPath stays\n    // for the optional opt-in path below — daemon-less callers (CLI tests,\n    // ad-hoc scripts) that skip the receiver hook still get a write here.\n    if (ctx.writeErrorEventInline !== false) {\n      // Daemon-less callers (CLI tests, ad-hoc scripts) that skip the receiver\n      // hook get their write here — through the same builder the receiver uses\n      // (buildErrorEventForReceiver), so the incident shape is one source of\n      // truth: the source-based ADR-191/216 attribution and the #1118 HTTP-status\n      // enrichment live in one place, not two drifting copies.\n      const ev = buildErrorEventForReceiver(span, ctx.graph, ctx.scanPath)\n      if (ev) await appendErrorEvent(ctx, ev)\n    }\n  }\n\n  // Failing-response incidents (issue #481). OTel semconv leaves a CLIENT span's\n  // status UNSET on a 4xx/5xx response, so the status-only path above is blind\n  // to a service whose outbound calls are failing en masse — the exact gap a\n  // debugging session hits (80× HTTP 404 against one peer surfacing nothing).\n  // A response status is read from the span here regardless of statusCode:\n  //   * 5xx → record an incident immediately (unambiguous failure, even with\n  //     UNSET status). Skipped when statusCode === 2 already recorded above so\n  //     a 5xx that also carries ERROR status isn't double-counted.\n  //   * 4xx on a CLIENT/PRODUCER span → coalesce. The burst against this\n  //     (source, peer) pair advances; when it reaches the threshold inside the\n  //     window it records ONE incident carrying the count and dominant code.\n  //   * a lone 4xx, or any 2xx/3xx → no incident.\n  // Always written here (not gated on writeErrorEventInline): the daemon's\n  // receiver only fires its synchronous error-writer for statusCode === 2, so\n  // these spans never reach that durability handoff — handleSpan owns them.\n  if (span.statusCode !== 2) {\n    const status = httpResponseStatus(span)\n    const grpcStatus = grpcStatusCodeFromAttrs(span.attributes)\n    // ADR-117 — an exception event on a span that left its status UNSET is\n    // still an unambiguous failure: a bullmq / Redis-Streams / background\n    // worker whose job threw carries the exception and no HTTP response\n    // context, so the status-only and response-code paths both miss it. Record\n    // it independent of HTTP, attributed to the handler file:line (or the\n    // service) the same way the statusCode === 2 path is. Ordered first because\n    // the exception is the unambiguous signal; the response-code branches below\n    // carry the exception-less HTTP failures.\n    if (span.exception) {\n      await recordExceptionIncident(ctx, span, ts)\n    } else if (status !== undefined && status >= 500) {\n      // A failing-response incident is attributed to the SOURCE service — the\n      // caller whose outbound calls are failing is the node a debugger asks\n      // about (\"why is my service erroring\"). The peer it failed against is\n      // carried in the message and in attributes. This is deliberately not the\n      // edge target (frontier/peer) the OBSERVED edge above resolved to: the\n      // signal is \"this service's calls to X are failing\", not \"X failed\".\n      await recordFailingResponseIncident(ctx, span, sourceId, ts, status, 1)\n    } else if (grpcStatus !== undefined && grpcStatus !== 0) {\n      // A non-OK gRPC status with UNSET span status (issue #1065) — the case the\n      // HTTP branches above can't see. Record it immediately, mirroring the 5xx\n      // path. The branches are mutually exclusive in practice (a span is a gRPC\n      // call or an HTTP one, not both), and the else-if chain records at most one\n      // incident per span, so this never double-counts against the 4xx-burst path\n      // below (a pure gRPC span carries no HTTP status to reach it anyway).\n      await recordGrpcFailureIncident(ctx, span, ts)\n    } else if (\n      status !== undefined &&\n      status >= 400 &&\n      spanMintsObservedEdge(span.kind)\n    ) {\n      await advance4xxBurst(ctx, span, sourceId, ts, nowMs, status)\n    }\n  }\n  void affectedNode\n\n  // Post-ingest policy trigger (ADR-043). The hook is awaited so failures\n  // surface; daemons wrap it in a try/catch that logs without throwing.\n  if (ctx.onPolicyTrigger) await ctx.onPolicyTrigger(ctx.graph)\n}\n\nexport { stitchTrace }\n\n// Promote any frontier:<host> placeholder whose host matches an alias on a\n// real ServiceNode: re-link inbound/outbound edges to the service, then drop\n// the placeholder. Returns the count of nodes promoted, for tests + logs.\n//\n// Called at the end of every extraction round. Static rounds are when new\n// aliases land (compose names, k8s metadata.name, Dockerfile labels), so\n// running it there picks up the case the issue describes: ingest fills in a\n// frontier when traffic arrives for an unknown host, and the next extraction\n// round resolves it.\n// Optional gate for block-action policies (ADR-044). When `policies` is\n// non-empty, each candidate FrontierNode runs through `canPromoteFrontier`\n// before its incident edges are rewired. Block-action policies that fire on\n// the frontier veto the promotion — the FrontierNode persists; the next\n// extract pass tries again.\nexport interface PromoteFrontierOptions {\n  policies?: Policy[]\n  policyCtx?: PolicyEvaluationContext\n}\n\nexport function promoteFrontierNodes(\n  graph: NeatGraph,\n  opts: PromoteFrontierOptions = {},\n): number {\n  const aliasIndex = new Map<string, string>()\n  graph.forEachNode((id, attrs) => {\n    const a = attrs as ServiceNode & { type?: string }\n    if (a.type !== NodeType.ServiceNode) return\n    aliasIndex.set(a.name, id)\n    if (a.aliases) {\n      for (const alias of a.aliases) aliasIndex.set(alias, id)\n    }\n  })\n  // A frontier minted for a ClusterIP before the k8s substrate read the Services\n  // (ADR-248) promotes to the service the address now names.\n  graph.forEachNode((_id, attrs) => {\n    const a = attrs as FrontierNode & { type?: string }\n    if (a.type !== NodeType.FrontierNode || aliasIndex.has(a.host)) return\n    const owner = serviceIdForObservedAddress(graph, a.host)\n    if (owner) aliasIndex.set(a.host, owner)\n  })\n\n  const toPromote: { frontierId: string; serviceId: string }[] = []\n  graph.forEachNode((id, attrs) => {\n    const a = attrs as FrontierNode & { type?: string }\n    if (a.type !== NodeType.FrontierNode) return\n    const target = aliasIndex.get(a.host)\n    if (!target) return\n    if (target === id) return\n    toPromote.push({ frontierId: id, serviceId: target })\n  })\n\n  let promoted = 0\n  for (const { frontierId, serviceId } of toPromote) {\n    if (opts.policies && opts.policies.length > 0 && opts.policyCtx) {\n      const gate = canPromoteFrontier(graph, frontierId, opts.policies, opts.policyCtx)\n      if (!gate.allowed) {\n        // Block-action policy fired on this frontier — skip the rewire and\n        // leave the FrontierNode in place. Violations already surfaced via\n        // the policy log on the same evaluation pass.\n        continue\n      }\n    }\n    rewireFrontierEdges(graph, frontierId, serviceId)\n    graph.dropNode(frontierId)\n    promoted++\n  }\n  return promoted\n}\n\n// ADR-226 — a staged FRONTIER surface graduates to OBSERVED by PROMOTION when its\n// real twin arrives. An OBSERVED edge with the same (source, target, type) means\n// NEAT can now see the hop it had only reached toward — a hung service came back,\n// a proposed edge became real — so the placeholder is dropped and the settled\n// OBSERVED edge stands in its place. This is the edge-level twin of\n// promoteFrontierNodes (ADR-044): a placeholder replaced once the real thing\n// resolves. Never gated — a settled fact is not blockable (the gate is the future\n// face, ADR-093). Returns the number of surfaces graduated; runs in the same\n// reconciliation sweep as promoteFrontierNodes.\n// ADR-226 — stage a FRONTIER surface edge. The hang sensor (hang-sensor.ts) does\n// the detection and resolves the hop; the graph write belongs here per the\n// lifecycle authority (ADR-030). Returns false when the hop is already OBSERVED\n// (production can see it — not a hang), already staged, or an endpoint is missing;\n// true when a new surface was added.\nexport function stageFrontierEdge(\n  graph: NeatGraph,\n  source: string,\n  target: string,\n  type: EdgeTypeValue,\n): boolean {\n  if (!graph.hasNode(source) || !graph.hasNode(target)) return false\n  if (graph.hasEdge(observedEdgeId(source, target, type))) return false\n  const key = frontierEdgeId(source, target, type)\n  if (graph.hasEdge(key)) return false\n  graph.addEdgeWithKey(key, source, target, {\n    id: key,\n    source,\n    target,\n    type,\n    provenance: Provenance.FRONTIER,\n  } as GraphEdge)\n  return true\n}\n\nexport function promoteFrontierEdges(graph: NeatGraph): number {\n  const graduated: string[] = []\n  graph.forEachEdge((edgeId, attrs) => {\n    const e = attrs as GraphEdge\n    if (e.provenance !== Provenance.FRONTIER) return\n    if (graph.hasEdge(observedEdgeId(e.source, e.target, e.type))) {\n      graduated.push(edgeId)\n    }\n  })\n  for (const edgeId of graduated) graph.dropEdge(edgeId)\n  return graduated.length\n}\n\nfunction rewireFrontierEdges(graph: NeatGraph, frontierId: string, serviceId: string): void {\n  const inbound = [...graph.inboundEdges(frontierId)]\n  const outbound = [...graph.outboundEdges(frontierId)]\n\n  for (const edgeId of inbound) {\n    const edge = graph.getEdgeAttributes(edgeId) as GraphEdge\n    rebuildEdge(graph, edge, edge.source, serviceId, edgeId)\n  }\n  for (const edgeId of outbound) {\n    const edge = graph.getEdgeAttributes(edgeId) as GraphEdge\n    rebuildEdge(graph, edge, serviceId, edge.target, edgeId)\n  }\n}\n\nfunction rebuildEdge(\n  graph: NeatGraph,\n  edge: GraphEdge,\n  newSource: string,\n  newTarget: string,\n  oldEdgeId: string,\n): void {\n  graph.dropEdge(oldEdgeId)\n  // ADR-068 — promotion rewrites the target ref; provenance carries forward.\n  // An OBSERVED edge to a FrontierNode promotes to an OBSERVED edge to the\n  // matched typed node; an INFERRED edge stays INFERRED; etc.\n  const newId =\n    edge.provenance === Provenance.OBSERVED\n      ? observedEdgeId(newSource, newTarget, edge.type)\n      : edge.provenance === Provenance.INFERRED\n        ? inferredEdgeId(newSource, newTarget, edge.type)\n        : extractedEdgeId(newSource, newTarget, edge.type)\n\n  if (graph.hasEdge(newId)) {\n    const existing = graph.getEdgeAttributes(newId) as GraphEdge\n    const merged: GraphEdge = {\n      ...existing,\n      callCount: (existing.callCount ?? 0) + (edge.callCount ?? 0),\n      lastObserved: pickLater(existing.lastObserved, edge.lastObserved),\n    }\n    graph.replaceEdgeAttributes(newId, merged)\n    return\n  }\n\n  const rebuilt: GraphEdge = {\n    ...edge,\n    id: newId,\n    source: newSource,\n    target: newTarget,\n  }\n  graph.addEdgeWithKey(newId, newSource, newTarget, rebuilt)\n}\n\nfunction pickLater(a: string | undefined, b: string | undefined): string | undefined {\n  if (!a) return b\n  if (!b) return a\n  return new Date(a).getTime() >= new Date(b).getTime() ? a : b\n}\n\nexport function makeSpanHandler(ctx: IngestContext): (span: ParsedSpan) => Promise<void> {\n  return (span) => handleSpan(ctx, span)\n}\n\nexport type { StaleEvent }\n\nexport interface MarkStaleOptions {\n  // Per-edge-type override map. Defaults to DEFAULT_STALE_THRESHOLDS, merged\n  // with NEAT_STALE_THRESHOLDS if the env var is set.\n  thresholds?: Record<string, number>\n  now?: number\n  // ndjson path. When set, every OBSERVED → STALE transition appends one\n  // line. Skipped if undefined — tests and embedded use cases don't need a\n  // log.\n  staleEventsPath?: string\n  // Project tag for event-bus routing (ADR-051). Defaults to DEFAULT_PROJECT.\n  project?: string\n}\n\n// Demote OBSERVED edges that haven't been seen in a while. Per-edge-type\n// thresholds: HTTP CALLS go stale fast; infra DEPENDS_ON is patient. Returns\n// the count of demotions and the events appended to the log.\nexport async function markStaleEdges(\n  graph: NeatGraph,\n  options: MarkStaleOptions = {},\n): Promise<{ count: number; events: StaleEvent[] }> {\n  const thresholds = options.thresholds ?? loadStaleThresholdsFromEnv()\n  const now = options.now ?? Date.now()\n  const events: StaleEvent[] = []\n\n  const project = options.project ?? DEFAULT_PROJECT\n  graph.forEachEdge((id, attrs) => {\n    const e = attrs as GraphEdge\n    if (e.provenance !== Provenance.OBSERVED) return\n    if (!e.lastObserved) return\n    const threshold = thresholdForEdgeType(e.type, thresholds)\n    const age = now - new Date(e.lastObserved).getTime()\n    if (age > threshold) {\n      const updated: GraphEdge = { ...e, provenance: Provenance.STALE, confidence: 0.3 }\n      graph.replaceEdgeAttributes(id, updated)\n      events.push({\n        edgeId: id,\n        source: e.source,\n        target: e.target,\n        edgeType: e.type,\n        thresholdMs: threshold,\n        ageMs: age,\n        lastObserved: e.lastObserved,\n        transitionedAt: new Date(now).toISOString(),\n      })\n      // Stale-transition fires through the bus (ADR-051). The graph\n      // subscription in events.ts can't see the OBSERVED→STALE semantic on\n      // its own — a provenance flip is just an attribute update from\n      // graphology's view.\n      emitNeatEvent({\n        type: 'stale-transition',\n        project,\n        payload: {\n          edgeId: id,\n          from: Provenance.OBSERVED,\n          to: Provenance.STALE,\n        },\n      })\n    }\n  })\n\n  if (options.staleEventsPath && events.length > 0) {\n    await appendStaleEvents(options.staleEventsPath, events)\n  }\n\n  return { count: events.length, events }\n}\n\nasync function appendStaleEvents(staleEventsPath: string, events: StaleEvent[]): Promise<void> {\n  await fs.mkdir(path.dirname(staleEventsPath), { recursive: true })\n  const lines = events.map((e) => JSON.stringify(e)).join('\\n') + '\\n'\n  await fs.appendFile(staleEventsPath, lines, 'utf8')\n}\n\nexport async function readStaleEvents(staleEventsPath: string): Promise<StaleEvent[]> {\n  try {\n    const raw = await fs.readFile(staleEventsPath, 'utf8')\n    return raw\n      .split('\\n')\n      .filter((line) => line.length > 0)\n      .map((line) => JSON.parse(line) as StaleEvent)\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []\n    throw err\n  }\n}\n\nexport interface StalenessLoopOptions {\n  thresholds?: Record<string, number>\n  intervalMs?: number\n  staleEventsPath?: string\n  // Project tag for event-bus routing (ADR-051).\n  project?: string\n  // Post-stale-transition policy trigger (ADR-043). Fires after each tick of\n  // markStaleEdges so policies see the new STALE state. Daemons wire this to\n  // evaluateAllPolicies + PolicyViolationsLog.append.\n  onPolicyTrigger?: (graph: NeatGraph) => Promise<void> | void\n  // Post-ingest reconciliation (ADR-226). Fires after each tick, the periodic\n  // point where OBSERVED state has settled. Daemons wire this to graduate FRONTIER\n  // surfaces whose twin has arrived (promoteFrontierEdges) and stage new hang\n  // surfaces (the hang sensor). Kept as a callback so ingest.ts never imports the\n  // sensor/traverse (which would cycle) — the daemon owns those wires.\n  onReconcile?: (graph: NeatGraph) => Promise<void> | void\n}\n\nexport function startStalenessLoop(\n  graph: NeatGraph,\n  options: StalenessLoopOptions = {},\n): () => void {\n  let stopped = false\n  const intervalMs = options.intervalMs ?? 60_000\n  const tick = (): void => {\n    if (stopped) return\n    void (async () => {\n      try {\n        await markStaleEdges(graph, {\n          thresholds: options.thresholds,\n          staleEventsPath: options.staleEventsPath,\n          project: options.project,\n        })\n        if (options.onPolicyTrigger) await options.onPolicyTrigger(graph)\n        if (options.onReconcile) await options.onReconcile(graph)\n      } catch (err) {\n        console.error('staleness tick failed', err)\n      }\n    })()\n  }\n  const interval = setInterval(tick, intervalMs)\n  if (typeof interval.unref === 'function') interval.unref()\n  return () => {\n    stopped = true\n    clearInterval(interval)\n  }\n}\n\n// errors.ndjson is append-only and unbounded, so on a long-running daemon with\n// a busy erroring service it grows without limit. Reading the whole file into\n// one utf8 string then throws `RangeError: Invalid string length` once it crosses\n// V8's ~2^29-char ceiling, which took down every incident-backed query\n// (get_incident_history / get_root_cause / ask) with a 500 (#1083). Two bounds\n// keep the read safe regardless of store size: never pull more than this many\n// bytes into a string, and never return more than INCIDENT_READ_MAX_EVENTS\n// parsed incidents. The newest incidents sit at the tail of the append-only file\n// and are the ones every consumer wants, so when the file is larger than the\n// byte budget we tail-read the most recent slice instead of the whole thing.\nconst INCIDENT_READ_MAX_BYTES = 32 * 1024 * 1024\n\n// Hard ceiling on how many incidents a single read hands back. Bounds both memory\n// and the size of any response built from the result, well under the string ceiling\n// even with large per-incident stacktraces. A caller can ask for fewer via `limit`.\nexport const INCIDENT_READ_MAX_EVENTS = 5000\n\n// Read at most `maxBytes` from the end of the file. When the file is larger than\n// the budget the first line in the window is almost certainly a partial record\n// (we cut mid-line), so drop everything up to and including the first newline —\n// every remaining line is whole, and the writer always terminates records with a\n// newline so the tail never ends mid-record.\nasync function readErrorFileTail(errorsPath: string, maxBytes: number): Promise<string> {\n  const handle = await fs.open(errorsPath, 'r')\n  try {\n    const { size } = await handle.stat()\n    if (size <= maxBytes) {\n      return (await handle.readFile()).toString('utf8')\n    }\n    const buf = Buffer.alloc(maxBytes)\n    await handle.read(buf, 0, maxBytes, size - maxBytes)\n    const raw = buf.toString('utf8')\n    const firstNewline = raw.indexOf('\\n')\n    return firstNewline === -1 ? '' : raw.slice(firstNewline + 1)\n  } finally {\n    await handle.close()\n  }\n}\n\n// A record persisted before the write-path scrub (#1184) can still carry\n// credential headers in its `attributes`: the sidecar is append-only, so the\n// bytes on disk predate the fix. Every reader (incident cards, get_divergences,\n// the web) gets the same scrub on load, without rewriting the file.\nexport async function readErrorEvents(\n  errorsPath: string,\n  opts?: { limit?: number },\n): Promise<ErrorEvent[]> {\n  let raw: string\n  try {\n    raw = await readErrorFileTail(errorsPath, INCIDENT_READ_MAX_BYTES)\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []\n    throw err\n  }\n  const events = raw\n    .split('\\n')\n    .filter((line) => line.length > 0)\n    .map((line) => scrubIncidentEvent(JSON.parse(line) as ErrorEvent))\n  const deduped = dedupeIncidents(events)\n  const cap =\n    opts?.limit !== undefined && opts.limit > 0\n      ? Math.min(opts.limit, INCIDENT_READ_MAX_EVENTS)\n      : INCIDENT_READ_MAX_EVENTS\n  // Keep the most-recent `cap`. dedupeIncidents preserves append order, so the\n  // tail is newest.\n  return deduped.length > cap ? deduped.slice(deduped.length - cap) : deduped\n}\n\n/** Resolve a pinned incident without the 5000-event list cap. Hosted replay can\n * name an older event, while ordinary incident reads remain bounded to the\n * newest window. The byte bound still prevents an unbounded ledger read.\n */\nexport async function readErrorEventById(errorsPath: string, id: string): Promise<ErrorEvent | undefined> {\n  let raw: string\n  try {\n    raw = await readErrorFileTail(errorsPath, INCIDENT_READ_MAX_BYTES)\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n    throw err\n  }\n  const lines = raw.split('\\n')\n  for (let i = lines.length - 1; i >= 0; i--) {\n    const line = lines[i]\n    if (!line) continue\n    const event = JSON.parse(line) as ErrorEvent\n    if (event.id === id) return scrubIncidentEvent(event)\n  }\n  return undefined\n}\n\n// A synthesized HTTP-status incident carries no failure of its own — it's the\n// \"500 on GET /users/:id\" line handleSpan mints for a server span that answered\n// 5xx with no exception event of its own (httpFailureMessage). When the real\n// failure surfaced deeper in the same trace (a DB driver threw, a downstream\n// gRPC returned UNAVAILABLE), that exception is recorded as its own incident on\n// the same node, and the server's HTTP echo is a duplicate of it. A record is\n// \"synthesized HTTP\" when it carries no exception data, no explicit errorType\n// (the coalesced http-failure incidents set one and carry their own count), and\n// its message is exactly the HTTP line re-derived from its own attributes.\nfunction isSynthesizedHttpIncident(ev: ErrorEvent): boolean {\n  if (ev.exceptionType || ev.exceptionStacktrace) return false\n  if (ev.errorType) return false\n  if (!ev.attributes) return false\n  const synth = httpFailureMessageFromAttrs(ev.attributes)\n  return synth !== undefined && synth === ev.errorMessage\n}\n\n// Make the incident surface idempotent per failure. Two passes:\n//\n// Pass 1 — collapse exact `(traceId, spanId)` re-deliveries. The ndjson sidecar\n// is append-only (persistence contract), so a re-delivered span — OTel\n// BatchSpanProcessor retries, or a receiver + handler both writing one POST —\n// leaves duplicate lines on disk. The deterministic incident `id` already\n// encodes the pair (`${traceId}:${spanId}`); we dedupe on it directly, falling\n// back to the raw pair for any record that predates the id. Records that carry\n// neither (extract parse-failure rows, `source: 'extract'`) pass through\n// untouched — they aren't span incidents. First write wins so the original\n// timestamp is preserved.\n//\n// Pass 2 — collapse one failure recorded from two spans of the same trace. A\n// failing request lands one incident from the span that actually threw (the DB\n// child's exception, a downstream gRPC error) and a second, synthesized one from\n// the HTTP server span that echoed it as a 5xx. Both key to the same\n// `(traceId, affectedNode)`; the exact-id pass can't see it because the spanIds\n// differ. When a real failure shares a trace and node with a synthesized HTTP\n// echo, drop the echo so the request counts once (issue #624). A cross-service\n// failure keeps both sides: the caller's failing-response incident and the\n// callee's exception land on different `affectedNode`s (separate ledgers per the\n// otel-ingest contract), so they never share a group.\nfunction dedupeIncidents(events: ErrorEvent[]): ErrorEvent[] {\n  const seen = new Set<string>()\n  const once: ErrorEvent[] = []\n  for (const ev of events) {\n    const key =\n      ev.id ??\n      (ev.traceId && ev.spanId ? `${ev.traceId}:${ev.spanId}` : undefined)\n    if (key === undefined) {\n      once.push(ev)\n      continue\n    }\n    if (seen.has(key)) continue\n    seen.add(key)\n    once.push(ev)\n  }\n\n  const groupKey = (ev: ErrorEvent): string => `${ev.traceId}\\u0000${ev.affectedNode}`\n  const hasRealFailure = new Set<string>()\n  for (const ev of once) {\n    if (ev.traceId && !isSynthesizedHttpIncident(ev)) hasRealFailure.add(groupKey(ev))\n  }\n  return once.filter((ev) => {\n    if (!ev.traceId || !isSynthesizedHttpIncident(ev)) return true\n    return !hasRealFailure.has(groupKey(ev))\n  })\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Snapshot merge (ADR-074 §1)\n//\n// `neat sync` (local) and `neat sync --to <url>` (remote) feed snapshots into\n// a live graph through this helper. It lives in ingest.ts because mutation\n// authority sits with ingest + extract per the lifecycle contract (ADR-030);\n// the merge is ingestion of an external snapshot, no different in shape from\n// the way handleSpan ingests an OTel span.\n//\n// The merge preserves EXTRACTED + OBSERVED coexistence per Rule 2 — each\n// provenance variant has its own edge id, so the incoming EXTRACTED edges\n// can't stomp the daemon's accumulated OBSERVED edges and vice versa. Rule of\n// thumb: incoming wins for nodes/edges the live graph hasn't seen yet;\n// everything already present keeps its current attributes.\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface MergeSnapshotResult {\n  nodesAdded: number\n  edgesAdded: number\n}\n\n// A pushed snapshot is untrusted input — it can arrive from `neat sync --to`\n// against a daemon the operator doesn't fully control, or from anything else\n// that can reach the `/snapshot` route. Before #693, every entry's\n// `attributes` went straight from `JSON.parse` to `graph.addNode` /\n// `graph.addEdgeWithKey` with only a schemaVersion check upstream in api.ts —\n// a malformed or hostile payload (wrong `type` literal, missing required\n// field, wrong field type) landed on the live graph as-is. This error\n// collects every entry that fails `GraphNodeSchema` / `GraphEdgeSchema` — the\n// same canonical shapes the rest of the API validates responses against\n// (packages/types) — so the caller gets back exactly what was wrong instead\n// of a generic parse failure or, worse, a silently corrupted graph.\nexport class SnapshotValidationError extends Error {\n  constructor(public readonly issues: string[]) {\n    super(`snapshot failed validation (${issues.length} invalid ${issues.length === 1 ? 'entry' : 'entries'})`)\n    this.name = 'SnapshotValidationError'\n  }\n}\n\nfunction describeZodIssues(error: { issues: Array<{ path: PropertyKey[]; message: string }> }): string {\n  return error.issues\n    .map((issue) => (issue.path.length > 0 ? `${issue.path.join('.')}: ${issue.message}` : issue.message))\n    .join('; ')\n}\n\nexport function mergeSnapshot(\n  graph: NeatGraph,\n  snapshot: PersistedGraph,\n): MergeSnapshotResult {\n  invalidateSourceBaseline(graph)\n  const exported = snapshot.graph as {\n    nodes?: Array<{ key: string; attributes?: unknown }>\n    edges?: Array<{ key?: string; source: string; target: string; attributes?: unknown }>\n  }\n  const incomingNodes = Array.isArray(exported.nodes) ? exported.nodes : []\n  const incomingEdges = Array.isArray(exported.edges) ? exported.edges : []\n\n  // Validate everything up front and merge nothing until every entry checks\n  // out — a snapshot that's partly hostile or partly corrupt is rejected\n  // whole rather than landing its valid entries and silently dropping the\n  // rest (matching how the schemaVersion check upstream already treats a\n  // bad snapshot as all-or-nothing).\n  const issues: string[] = []\n  const validNodes: Array<{ key: string; attributes: GraphNode }> = []\n  const validEdges: Array<{ key: string; source: string; target: string; attributes: GraphEdge }> = []\n\n  for (const node of incomingNodes) {\n    // No attributes at all is a no-op skip, not a malformed entry — mirrors\n    // the pre-#693 behaviour for this specific (empty) shape.\n    if (node.attributes === undefined) continue\n    const parsed = GraphNodeSchema.safeParse(node.attributes)\n    if (!parsed.success) {\n      issues.push(`node \"${node.key}\": ${describeZodIssues(parsed.error)}`)\n      continue\n    }\n    validNodes.push({ key: node.key, attributes: parsed.data })\n  }\n\n  for (const edge of incomingEdges) {\n    if (edge.attributes === undefined) continue\n    const parsed = GraphEdgeSchema.safeParse(edge.attributes)\n    if (!parsed.success) {\n      const label = edge.key ?? `${edge.source}->${edge.target}`\n      issues.push(`edge \"${label}\": ${describeZodIssues(parsed.error)}`)\n      continue\n    }\n    const id = edge.key ?? parsed.data.id\n    validEdges.push({ key: id, source: edge.source, target: edge.target, attributes: parsed.data })\n  }\n\n  if (issues.length > 0) {\n    throw new SnapshotValidationError(issues)\n  }\n\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const node of validNodes) {\n    if (graph.hasNode(node.key)) continue\n    graph.addNode(node.key, node.attributes)\n    nodesAdded++\n  }\n\n  for (const edge of validEdges) {\n    if (graph.hasEdge(edge.key)) continue\n    // Skip when either endpoint is missing — can happen if the snapshot\n    // names a node the live graph already evicted and the incoming nodes\n    // array didn't include.\n    if (!graph.hasNode(edge.source) || !graph.hasNode(edge.target)) continue\n    graph.addEdgeWithKey(edge.key, edge.source, edge.target, edge.attributes)\n    edgesAdded++\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { ErrorEvent } from '@neat.is/types'\nimport { scrubIncidentEvent } from './credential-scrub.js'\n\n/**\n * Hosted runtime incidents are committed to the local sidecar's encrypted GCS\n * archive before the producer can acknowledge or publish the trigger. The\n * sidecar then appends the same record to the daemon's local ledger. Non-hosted\n * callers keep the existing append-only filesystem path. Either way the record\n * is scrubbed of credential-bearing attributes first (credential-scrub.ts).\n */\nexport async function appendRuntimeIncident(\n  errorsPath: string,\n  project: string,\n  event: ErrorEvent,\n  options: { token?: string; fetchImpl?: typeof fetch } = {},\n): Promise<void> {\n  // The sink, so the scrub holds for every producer: a connector incident never\n  // passed through the span builders that used to apply it.\n  event = scrubIncidentEvent(event)\n  const token = options.token ?? process.env.NEAT_INCIDENT_DURABLE_TOKEN\n  if (token !== undefined) {\n    if (Buffer.byteLength(token, 'utf8') < 32) throw new Error('durable incident sink unavailable')\n    const response = await (options.fetchImpl ?? fetch)('http://127.0.0.1:8081/incident-append', {\n      method: 'POST',\n      headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },\n      body: JSON.stringify({ project, event }),\n      signal: AbortSignal.timeout(30_000),\n    })\n    if (response.status !== 204) throw new Error('durable incident sink unavailable')\n    return\n  }\n  await fs.mkdir(path.dirname(errorsPath), { recursive: true })\n  await fs.appendFile(errorsPath, JSON.stringify(event) + '\\n', 'utf8')\n}\n","import type { ErrorEvent } from '@neat.is/types'\n\n// The credential scrub for incident records (#1182, #1184, #1187). One\n// definition, applied where a record is written (appendRuntimeIncident, which\n// every runtime incident goes through: OTel spans and connector incidents\n// alike) and again where one is read, so neither a new producer nor a record\n// written before the scrub existed can put a credential header into\n// errors.ndjson or in front of an agent.\n\n// Header attributes that carry credentials. Some auto-instrumentation copies\n// request/response headers into span attributes wholesale — a `...req.headers`\n// spread — which would otherwise persist a caller's session cookie or bearer\n// token into the incident record at rest. NEAT's own instrumentation never\n// emits these; the exposure rides in from a target's over-broad SDK, and NEAT\n// is the store, so it drops them here (#1182).\nconst SENSITIVE_HEADER_NAMES = new Set([\n  'authorization',\n  'proxy-authorization',\n  'cookie',\n  'set-cookie',\n  'x-api-key',\n  'api-key',\n  'x-auth-token',\n  'x-amz-security-token',\n  'x-csrf-token',\n])\n\n// The header name an attribute key carries — the segment after `.header.` for the\n// OTel `http.request.header.<name>` / `http.response.header.<name>` forms, or the\n// bare key itself for an SDK that names the header without a prefix.\nfunction attrHeaderName(key: string): string {\n  const lower = key.toLowerCase()\n  const marker = '.header.'\n  const at = lower.lastIndexOf(marker)\n  return at >= 0 ? lower.slice(at + marker.length) : lower\n}\n\nfunction isSensitiveAttrKey(key: string): boolean {\n  return SENSITIVE_HEADER_NAMES.has(attrHeaderName(key))\n}\n\n// Span attributes pass through so consumers can read source attribution\n// (`code.filepath`, `code.lineno`, `code.function`) and other SDK-emitted\n// context without ingest enumerating every key it cares about — with one\n// exception: credential-bearing header attributes are dropped (see above), so\n// a span that arrived carrying a cookie or bearer token doesn't persist it.\n// Coerce the survivors to a JSON-safe shape — bigint values from the parsed\n// span (long ids, high-cardinality counters) become strings so the record can\n// be serialised to the ErrorEvent shape and round-tripped through\n// ErrorEventSchema. All other types pass through unchanged.\nexport function sanitizeAttributes(\n  attrs: Record<string, unknown>,\n): Record<string, string | number | boolean | null | string[] | number[] | boolean[]> {\n  const out: Record<string, string | number | boolean | null | string[] | number[] | boolean[]> = {}\n  for (const [k, v] of Object.entries(attrs)) {\n    if (isSensitiveAttrKey(k)) continue\n    if (typeof v === 'bigint') out[k] = v.toString()\n    else out[k] = v as string | number | boolean | null | string[] | number[] | boolean[]\n  }\n  return out\n}\n\n// Credentials that ride inside a value rather than under a header name: a\n// signed URL in a log line, a bearer token echoed into an exception message, a\n// `NPM_TOKEN=...` line in an EAS build log. Each pattern keeps the name or the\n// scheme and replaces only the secret, so the record still says what failed.\n// Every pattern is idempotent (a redacted value never matches again), which\n// the at-rest rewrite (ledger-scrub.ts) relies on to tell a clean ledger from\n// one that needs rewriting.\nexport const REDACTED = '[REDACTED]'\n\nconst VALUE_PATTERNS: ReadonlyArray<readonly [RegExp, string]> = [\n  // PEM private key blocks, through the END line or the end of a truncated log.\n  [/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\\s\\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g, REDACTED],\n  // JWTs (header.payload.signature, both base64url JSON objects).\n  [/\\beyJ[A-Za-z0-9_-]{8,}\\.eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]*/g, REDACTED],\n  // Provider tokens with a fixed, recognisable prefix.\n  [\n    /\\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{22,}|glpat-[A-Za-z0-9_-]{20,}|xox[abprs]-[A-Za-z0-9-]{10,}|(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}|sk-(?=[A-Za-z0-9_-]*[0-9])[A-Za-z0-9_-]{20,}|AIza[0-9A-Za-z_-]{35}|npm_[A-Za-z0-9]{36}|(?:AKIA|ASIA)[0-9A-Z]{16})\\b/g,\n    REDACTED,\n  ],\n  // The password in a URL's userinfo: scheme://user:secret@host.\n  [/(\\b[a-z][a-z0-9+.-]*:\\/\\/[^\\s:@/?#\"'<>]+:)[^\\s@/?#\"'<>]+@/gi, `$1${REDACTED}@`],\n  // Query parameters that carry a credential: ?token=, &access_token=, presigned\n  // S3/GCS signatures. `key` covers Google's `?key=` API keys.\n  [\n    /([?&](?:access_token|refresh_token|id_token|token|api_key|apikey|api-key|key|secret|client_secret|password|passwd|pwd|auth|sig|signature|x-amz-signature|x-amz-credential|x-amz-security-token|x-goog-signature|x-goog-credential)=)[^&#\\s\"'<>]+/gi,\n    `$1${REDACTED}`,\n  ],\n  // `Bearer <token>` / `Basic <base64>`. The value must contain a digit, so\n  // prose like \"Basic authentication failed\" is left alone.\n  [/\\b(Bearer|Basic)\\s+(?=[A-Za-z0-9._~+/=-]*[0-9])[A-Za-z0-9._~+/-]{8,}=*/g, `$1 ${REDACTED}`],\n  // JSON-shaped credential fields: \"password\": \"...\".\n  [\n    /(\"(?:password|passwd|secret|token|access_token|refresh_token|id_token|api_key|apiKey|client_secret|clientSecret|private_key|privateKey)\"\\s*:\\s*\")(?:[^\"\\\\]|\\\\.)*\"/gi,\n    `$1${REDACTED}\"`,\n  ],\n  // Env-style assignments of upper-case credential names, as a build log prints\n  // them: NPM_TOKEN=..., AWS_SECRET_ACCESS_KEY=...\n  [\n    /\\b([A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PASSWD|API_?KEY|PRIVATE_KEY|ACCESS_KEY|CREDENTIALS?)[A-Z0-9_]*)(\\s*=\\s*)([\"']?)[^\\s\"']+\\3/g,\n    `$1$2$3${REDACTED}$3`,\n  ],\n]\n\n/** A string with any credential-shaped value inside it replaced by `[REDACTED]`. */\nexport function redactSecretValues(text: string): string {\n  let out = text\n  for (const [pattern, replacement] of VALUE_PATTERNS) out = out.replace(pattern, replacement)\n  return out\n}\n\ntype AttrValue = ReturnType<typeof sanitizeAttributes>[string]\n\nfunction redactAttrValue(v: AttrValue): AttrValue {\n  if (typeof v === 'string') return redactSecretValues(v)\n  if (Array.isArray(v) && v.some((x) => typeof x === 'string')) {\n    return (v as unknown[]).map((x) => (typeof x === 'string' ? redactSecretValues(x) : x)) as AttrValue\n  }\n  return v\n}\n\n/**\n * An incident record with its credential-bearing attributes dropped and any\n * credential-shaped value in its message, stack trace, or remaining attributes\n * redacted. Returns the record itself when there is nothing to change, so a\n * clean record costs no copy.\n */\nexport function scrubIncidentEvent<T extends ErrorEvent>(ev: T): T {\n  let changed = false\n  const out: T = { ...ev }\n\n  if (ev.attributes) {\n    const kept = sanitizeAttributes(ev.attributes)\n    if (Object.keys(kept).length !== Object.keys(ev.attributes).length) changed = true\n    for (const [k, v] of Object.entries(kept)) {\n      const red = redactAttrValue(v)\n      if (red !== v && JSON.stringify(red) !== JSON.stringify(v)) {\n        kept[k] = red\n        changed = true\n      }\n    }\n    if (Object.keys(kept).length > 0) out.attributes = kept\n    else delete out.attributes\n  }\n\n  if (typeof ev.errorMessage === 'string') {\n    const msg = redactSecretValues(ev.errorMessage)\n    if (msg !== ev.errorMessage) {\n      out.errorMessage = msg\n      changed = true\n    }\n  }\n  if (typeof ev.exceptionStacktrace === 'string') {\n    const st = redactSecretValues(ev.exceptionStacktrace)\n    if (st !== ev.exceptionStacktrace) {\n      out.exceptionStacktrace = st\n      changed = true\n    }\n  }\n\n  return changed ? out : ev\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type {\n  ApplicablePolicy,\n  GraphEdge,\n  GraphNode,\n  Policy,\n  PolicyAction,\n  PolicyFile,\n  PolicyRule,\n  PolicySeverity,\n  PolicyViolation,\n  ServiceNode,\n} from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  PolicyFileSchema,\n  isDependencyNodeId,\n} from '@neat.is/types'\nimport type { NeatGraph } from './graph.js'\nimport { DEFAULT_PROJECT } from './graph.js'\nimport {\n  checkCompatibility,\n  checkDeprecatedApi,\n  checkNodeEngineConstraint,\n  checkPackageConflict,\n  compatPairs,\n  deprecatedApis,\n  nodeEngineConstraints,\n  packageConflicts,\n} from './compat.js'\nimport { emitNeatEvent } from './events.js'\nimport { getBlastRadius } from './traverse.js'\n\n// Policy evaluation engine (ADR-043). The entry point evaluateAllPolicies is\n// pure: same graph + same policies → same violations. Per-rule-type dispatch\n// via the policyEvaluators table. Adding a new rule type means one new\n// evaluator entry plus the schema entry in @neat.is/types/policy.ts.\n//\n// Deterministic violation ids per ADR-043: ${policy.id}:${context}. The\n// context is shape-specific (nodeId, edgeId, or composite). The\n// policy-violations.ndjson writer skips on duplicate ids.\n\nexport interface EvaluationContext {\n  // Wall-clock provider. Tests pin this; production uses Date.now.\n  now: () => number\n}\n\ninterface RuleEvaluatorArgs<T extends PolicyRule = PolicyRule> {\n  graph: NeatGraph\n  policy: Policy\n  rule: T\n  ctx: EvaluationContext\n}\n\ntype RuleEvaluator<T extends PolicyRule = PolicyRule> = (\n  args: RuleEvaluatorArgs<T>,\n) => PolicyViolation[]\n\n// Severity-driven default action per ADR-044.\nconst DEFAULT_ACTION_BY_SEVERITY: Record<PolicySeverity, PolicyAction> = {\n  info: 'log',\n  warning: 'alert',\n  error: 'alert',\n  critical: 'block',\n}\n\nexport function resolveOnViolation(policy: Policy): PolicyAction {\n  return policy.onViolation ?? DEFAULT_ACTION_BY_SEVERITY[policy.severity]\n}\n\nfunction makeViolation(\n  policy: Policy,\n  rule: PolicyRule,\n  contextSuffix: string,\n  message: string,\n  subject: PolicyViolation['subject'],\n  ctx: EvaluationContext,\n): PolicyViolation {\n  return {\n    id: `${policy.id}:${contextSuffix}`,\n    policyId: policy.id,\n    policyName: policy.name,\n    severity: policy.severity,\n    onViolation: resolveOnViolation(policy),\n    ruleType: rule.type,\n    subject,\n    message,\n    observedAt: new Date(ctx.now()).toISOString(),\n  }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Per-rule-type evaluators\n// ──────────────────────────────────────────────────────────────────────────\n\nconst evaluateStructural: RuleEvaluator<Extract<PolicyRule, { type: 'structural' }>> = ({\n  graph,\n  policy,\n  rule,\n  ctx,\n}) => {\n  const violations: PolicyViolation[] = []\n  graph.forEachNode((id, attrs) => {\n    const a = attrs as GraphNode\n    if (a.type !== rule.fromNodeType) return\n    let satisfied = false\n    for (const edgeId of graph.outboundEdges(id)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (e.type !== rule.edgeType) continue\n      const target = graph.getNodeAttributes(e.target) as GraphNode\n      // FrontierNodes are unresolved peers (ADR-068) — skip; the rule\n      // counts edges that resolve to a real typed node only.\n      if (target.type === NodeType.FrontierNode) continue\n      if (target.type === rule.toNodeType) {\n        satisfied = true\n        break\n      }\n    }\n    if (!satisfied) {\n      violations.push(\n        makeViolation(\n          policy,\n          rule,\n          id,\n          `${rule.fromNodeType} ${id} has no ${rule.edgeType} edge to a ${rule.toNodeType}`,\n          { nodeId: id },\n          ctx,\n        ),\n      )\n    }\n  })\n  return violations\n}\n\nconst evaluateOwnership: RuleEvaluator<Extract<PolicyRule, { type: 'ownership' }>> = ({\n  graph,\n  policy,\n  rule,\n  ctx,\n}) => {\n  const violations: PolicyViolation[] = []\n  graph.forEachNode((id, attrs) => {\n    const a = attrs as GraphNode & Record<string, unknown>\n    if (a.type !== rule.nodeType) return\n    const value = a[rule.field]\n    if (typeof value !== 'string' || value.length === 0) {\n      violations.push(\n        makeViolation(\n          policy,\n          rule,\n          id,\n          `${rule.nodeType} ${id} is missing required field \"${rule.field}\"`,\n          { nodeId: id },\n          ctx,\n        ),\n      )\n    }\n  })\n  return violations\n}\n\nconst evaluateProvenance: RuleEvaluator<Extract<PolicyRule, { type: 'provenance' }>> = ({\n  graph,\n  policy,\n  rule,\n  ctx,\n}) => {\n  const required = Array.isArray(rule.required) ? new Set(rule.required) : new Set([rule.required])\n  const violations: PolicyViolation[] = []\n  graph.forEachEdge((edgeId, attrs) => {\n    const e = attrs as GraphEdge\n    if (e.type !== rule.edgeType) return\n    // A service's DEPENDS_ON edge to a resolved package (ADR-274) is lockfile\n    // inventory, not architecture; a provenance rule about DEPENDS_ON keeps\n    // meaning the edges it meant before the dependency layer existed.\n    if (isDependencyNodeId(e.source) || isDependencyNodeId(e.target)) return\n    if (rule.targetNodeId && e.target !== rule.targetNodeId) return\n    if (!required.has(e.provenance)) {\n      const requiredList = [...required].join(' | ')\n      violations.push(\n        makeViolation(\n          policy,\n          rule,\n          edgeId,\n          `${rule.edgeType} edge ${edgeId} has provenance ${e.provenance}; required ${requiredList}`,\n          { edgeId },\n          ctx,\n        ),\n      )\n    }\n  })\n  return violations\n}\n\nconst evaluateBlastRadius: RuleEvaluator<Extract<PolicyRule, { type: 'blast-radius' }>> = ({\n  graph,\n  policy,\n  rule,\n  ctx,\n}) => {\n  const violations: PolicyViolation[] = []\n  const depth = rule.depth\n  graph.forEachNode((id, attrs) => {\n    const a = attrs as GraphNode\n    if (a.type !== rule.nodeType) return\n    const result = depth !== undefined ? getBlastRadius(graph, id, depth) : getBlastRadius(graph, id)\n    if (result.totalAffected > rule.maxAffected) {\n      violations.push(\n        makeViolation(\n          policy,\n          rule,\n          id,\n          `${rule.nodeType} ${id} has blast radius ${result.totalAffected} > ${rule.maxAffected}`,\n          { nodeId: id, path: [id] },\n          ctx,\n        ),\n      )\n    }\n  })\n  return violations\n}\n\nconst evaluateCompatibility: RuleEvaluator<Extract<PolicyRule, { type: 'compatibility' }>> = ({\n  graph,\n  policy,\n  rule,\n  ctx,\n}) => {\n  const violations: PolicyViolation[] = []\n  // Iterate every ServiceNode and re-run the compat shapes the static\n  // extractor runs at extract time. Catches OBSERVED-vs-EXTRACTED divergence:\n  // a service whose dep manifest changed since the last extract gets re-flagged\n  // here on every evaluation cycle.\n  const wantsKind = (kind: NonNullable<typeof rule.kind>): boolean =>\n    rule.kind === undefined || rule.kind === kind\n\n  graph.forEachNode((svcId, attrs) => {\n    const a = attrs as GraphNode\n    if (a.type !== NodeType.ServiceNode) return\n    const svc = a as ServiceNode\n    const deps = svc.dependencies ?? {}\n\n    if (wantsKind('driver-engine')) {\n      // Walk every CONNECTS_TO edge from this service to a DatabaseNode,\n      // then run the driver-engine compat for each (driver, declared, engine,\n      // engineVersion) tuple.\n      for (const edgeId of graph.outboundEdges(svcId)) {\n        const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n        if (e.type !== EdgeType.CONNECTS_TO) continue\n        const dbAttrs = graph.getNodeAttributes(e.target) as GraphNode\n        // FrontierNodes are unresolved peers (ADR-068) — skip; compat\n        // checking needs a typed DatabaseNode.\n        if (dbAttrs.type === NodeType.FrontierNode) continue\n        if (dbAttrs.type !== NodeType.DatabaseNode) continue\n        const db = dbAttrs as { engine: string; engineVersion: string }\n        for (const pair of compatPairs()) {\n          if (pair.engine !== db.engine) continue\n          const declared = deps[pair.driver]\n          if (!declared) continue\n          const result = checkCompatibility(pair.driver, declared, db.engine, db.engineVersion)\n          if (!result.compatible && result.reason) {\n            violations.push(\n              makeViolation(\n                policy,\n                rule,\n                `${svcId}:driver-engine:${pair.driver}@${declared}:${db.engine}@${db.engineVersion}`,\n                result.reason,\n                { nodeId: svcId, edgeId },\n                ctx,\n              ),\n            )\n          }\n        }\n      }\n    }\n\n    if (wantsKind('node-engine')) {\n      const serviceNodeRange = svc.nodeEngine\n      for (const constraint of nodeEngineConstraints()) {\n        const declared = deps[constraint.package]\n        if (!declared) continue\n        const result = checkNodeEngineConstraint(constraint, declared, serviceNodeRange)\n        if (!result.compatible && result.reason) {\n          violations.push(\n            makeViolation(\n              policy,\n              rule,\n              `${svcId}:node-engine:${constraint.package}@${declared}`,\n              result.reason,\n              { nodeId: svcId },\n              ctx,\n            ),\n          )\n        }\n      }\n    }\n\n    if (wantsKind('package-conflict')) {\n      for (const conflict of packageConflicts()) {\n        const declared = deps[conflict.package]\n        if (!declared) continue\n        const requiredDeclared = deps[conflict.requires.name]\n        const result = checkPackageConflict(conflict, declared, requiredDeclared)\n        if (!result.compatible && result.reason) {\n          violations.push(\n            makeViolation(\n              policy,\n              rule,\n              `${svcId}:package-conflict:${conflict.package}@${declared}`,\n              result.reason,\n              { nodeId: svcId },\n              ctx,\n            ),\n          )\n        }\n      }\n    }\n\n    if (wantsKind('deprecated-api')) {\n      for (const dep of deprecatedApis()) {\n        const declared = deps[dep.package]\n        if (!declared) continue\n        const result = checkDeprecatedApi(dep, declared)\n        if (!result.compatible && result.reason) {\n          violations.push(\n            makeViolation(\n              policy,\n              rule,\n              `${svcId}:deprecated-api:${dep.package}@${declared}`,\n              result.reason,\n              { nodeId: svcId },\n              ctx,\n            ),\n          )\n        }\n      }\n    }\n  })\n\n  return violations\n}\n\n// ADR-169 — the generic declared-set-subset rule. For every node of the rule's\n// type (optionally narrowed to an InfraNode `kind`), every member of set A (the\n// named `subjectSet`) must appear in set B (the node's `guardSet` string[]\n// attribute). A member of A absent from B is one violation. A node whose\n// `guardSet` attribute is absent (or not an array) is INDETERMINATE — skipped,\n// never a false positive; this is what keeps condition-based / unparseable\n// firestore.rules silent. The Firestore instance's set A is client-written\n// columns, whose `sdkWrites` tag is F1's (ADR-167) declared interface — read\n// defensively (absent ⇒ set A empty ⇒ no violation).\nconst evaluateFieldGuard: RuleEvaluator<Extract<PolicyRule, { type: 'field-guard' }>> = ({\n  graph,\n  policy,\n  rule,\n  ctx,\n}) => {\n  const violations: PolicyViolation[] = []\n  graph.forEachNode((id, attrs) => {\n    const a = attrs as GraphNode & Record<string, unknown>\n    if (a.type !== rule.nodeType) return\n    if (rule.nodeKind !== undefined && a.kind !== rule.nodeKind) return\n    // Set B — the covering guard set. Absent / non-array ⇒ indeterminate ⇒ silent.\n    const guardRaw = a[rule.guardSet]\n    if (!Array.isArray(guardRaw)) return\n    const covering = new Set(guardRaw.map((g) => String(g)))\n    // Set A — resolved from the named selector.\n    for (const field of resolveFieldGuardSubject(rule.subjectSet, a)) {\n      if (!covering.has(field)) {\n        violations.push(\n          makeViolation(\n            policy,\n            rule,\n            `${id}:${field}`,\n            `${a.type}${rule.nodeKind !== undefined ? ` (${rule.nodeKind})` : ''} ${id} writes \"${field}\" but it is absent from ${rule.guardSet}`,\n            { nodeId: id },\n            ctx,\n          ),\n        )\n      }\n    }\n  })\n  return violations\n}\n\n// Resolves a `field-guard` rule's set A off a node. A new named selector is a new\n// case here (ADR-043 growth) — the RuleEvaluator interface is untouched.\nfunction resolveFieldGuardSubject(\n  selector: Extract<PolicyRule, { type: 'field-guard' }>['subjectSet'],\n  node: Record<string, unknown>,\n): string[] {\n  switch (selector) {\n    case 'client-written-columns': {\n      const columns = node.columns\n      if (!Array.isArray(columns)) return []\n      const out: string[] = []\n      for (const col of columns) {\n        // F1's ColumnAttr.sdkWrites (ADR-167). Read defensively so this compiles\n        // and behaves before F1 lands: absent ⇒ not a client write ⇒ the column\n        // is not in set A ⇒ no false positive. Admin-only writes bypass the\n        // rules and are excluded.\n        const sdkWrites = (col as { sdkWrites?: unknown }).sdkWrites\n        const name = (col as { name?: unknown }).name\n        if (Array.isArray(sdkWrites) && sdkWrites.includes('client') && typeof name === 'string') {\n          out.push(name)\n        }\n      }\n      return out\n    }\n  }\n}\n\nconst policyEvaluators: { [K in PolicyRule['type']]: RuleEvaluator<Extract<PolicyRule, { type: K }>> } = {\n  structural: evaluateStructural,\n  ownership: evaluateOwnership,\n  provenance: evaluateProvenance,\n  'blast-radius': evaluateBlastRadius,\n  compatibility: evaluateCompatibility,\n  'field-guard': evaluateFieldGuard,\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Public entry point\n// ──────────────────────────────────────────────────────────────────────────\n\n// Block-action gating for FrontierNode promotion (ADR-044 §block, MVP scope).\n// Runs the policy evaluator and returns the subset of block-action violations\n// that mention the candidate FrontierNode. Callers (ingest.ts\n// promoteFrontierNodes) check `allowed` before rewiring; when false, the\n// promotion is skipped and the violations surface through the standard\n// policy-violations.ndjson channel.\n//\n// Block scope is tightly bounded per the contract: FrontierNode promotion\n// only. Other gating points (deploy, codemod, OTel auto-create) need their\n// own ADRs before this function expands.\nexport function canPromoteFrontier(\n  graph: NeatGraph,\n  frontierId: string,\n  policies: Policy[],\n  ctx: EvaluationContext,\n): { allowed: boolean; violations: PolicyViolation[] } {\n  if (policies.length === 0) return { allowed: true, violations: [] }\n  const all = evaluateAllPolicies(graph, policies, ctx)\n  const blocking = all.filter((v) => {\n    if (v.onViolation !== 'block') return false\n    return (\n      v.subject.nodeId === frontierId ||\n      v.subject.path?.includes(frontierId) === true\n    )\n  })\n  return { allowed: blocking.length === 0, violations: blocking }\n}\n\nexport function evaluateAllPolicies(\n  graph: NeatGraph,\n  policies: Policy[],\n  ctx: EvaluationContext,\n): PolicyViolation[] {\n  const out: PolicyViolation[] = []\n  for (const policy of policies) {\n    const evaluator = policyEvaluators[policy.rule.type] as RuleEvaluator\n    const violations = evaluator({ graph, policy, rule: policy.rule, ctx })\n    for (const v of violations) out.push(v)\n  }\n  return out\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Soft guardrail — applicable-policy selection (ADR-108)\n// ──────────────────────────────────────────────────────────────────────────\n\n// The launch form of \"every agent stays inside the lines\": policies INFORM,\n// they never block. selectApplicablePolicies answers \"which policies govern the\n// node I'm about to edit?\" so the rules can ride into the agent's context.\n//\n// Matching is a subject/region match:\n//   - subject — the node's type is the rule's declared subject (the rule\n//     governs every node of that type).\n//   - region — for most rule types, the node sits one hop inside the rule's\n//     region: the target end of a structural edge, the database a compat rule\n//     reaches across a CONNECTS_TO, or a node sitting on an edge a provenance\n//     rule governs. For blast-radius rules the region is the subject's real\n//     blast radius — its dependents: we walk getBlastRadius (to the rule's\n//     declared depth) and surface the rule on every dependent it reaches, so a\n//     far-away node that breaks when the subject changes still sees the\n//     invariant that governs it.\n//\n// The general scope×distance injection over the policy overlay (ADR-105 §5),\n// which would carry this reachability behaviour to every rule type rather than\n// just blast-radius, is still unbuilt; the gap is written up in\n// docs/quirks/policies-soft-guardrail.md. selectApplicablePolicies never\n// evaluates a violation and never returns a verdict — surfacing a policy is not\n// gating it.\nexport function selectApplicablePolicies(\n  graph: NeatGraph,\n  policies: Policy[],\n  nodeId: string,\n): ApplicablePolicy[] {\n  // Without the node in the graph there's no type to match against, so we\n  // can't decide applicability. A not-yet-created node (a brand-new edit) is\n  // exactly the case the unbuilt overlay would handle; here we return empty\n  // rather than guess.\n  if (!graph.hasNode(nodeId)) return []\n  const node = graph.getNodeAttributes(nodeId) as GraphNode\n  const out: ApplicablePolicy[] = []\n  for (const policy of policies) {\n    const m = matchPolicyToNode(graph, policy, nodeId, node)\n    if (!m) continue\n    out.push({\n      policyId: policy.id,\n      policyName: policy.name,\n      ...(policy.description !== undefined ? { description: policy.description } : {}),\n      severity: policy.severity,\n      onViolation: resolveOnViolation(policy),\n      ruleType: policy.rule.type,\n      match: m.match,\n      reason: m.reason,\n    })\n  }\n  return out\n}\n\ninterface PolicyMatch {\n  match: ApplicablePolicy['match']\n  reason: string\n}\n\nfunction requiredProvenanceList(required: string | readonly string[]): string {\n  // required is ProvenanceRule['required'] — a single value or a non-empty\n  // array. Normalize to a readable \"A | B\" string.\n  if (Array.isArray(required)) return required.join(' | ')\n  return String(required)\n}\n\nfunction nodeTouchesEdgeType(\n  graph: NeatGraph,\n  nodeId: string,\n  edgeType: string,\n  requiredOtherEnd?: string,\n): boolean {\n  const incident = [...graph.outboundEdges(nodeId), ...graph.inboundEdges(nodeId)]\n  for (const edgeId of incident) {\n    const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n    if (e.type !== edgeType) continue\n    // A provenance rule with a targetNodeId only governs edges that touch that\n    // target. Without one, any edge of the type counts.\n    if (requiredOtherEnd === undefined) return true\n    if (e.source === requiredOtherEnd || e.target === requiredOtherEnd) return true\n  }\n  return false\n}\n\n// Reverse-reachability for blast-radius rules. Returns the id of a subject-type\n// node whose blast radius (its dependents, to the rule's declared depth)\n// contains nodeId, or null if none does. This is what lets a blast-radius rule\n// surface on the dependents it actually governs, not only on its subject.\nfunction blastRadiusSubjectReaching(\n  graph: NeatGraph,\n  rule: Extract<PolicyRule, { type: 'blast-radius' }>,\n  nodeId: string,\n): string | null {\n  let found: string | null = null\n  graph.forEachNode((subjId, attrs) => {\n    if (found !== null) return\n    if (subjId === nodeId) return\n    if ((attrs as GraphNode).type !== rule.nodeType) return\n    const radius =\n      rule.depth !== undefined\n        ? getBlastRadius(graph, subjId, rule.depth)\n        : getBlastRadius(graph, subjId)\n    if (radius.affectedNodes.some((n) => n.nodeId === nodeId)) found = subjId\n  })\n  return found\n}\n\nfunction matchPolicyToNode(\n  graph: NeatGraph,\n  policy: Policy,\n  nodeId: string,\n  node: GraphNode,\n): PolicyMatch | null {\n  const rule = policy.rule\n  switch (rule.type) {\n    case 'structural': {\n      if (node.type === rule.fromNodeType) {\n        return {\n          match: 'subject',\n          reason: `every ${rule.fromNodeType} must have a ${rule.edgeType} edge to a ${rule.toNodeType}`,\n        }\n      }\n      // The target end is one hop inside the rule's region — editing it can\n      // make a sibling fromNodeType pass or fail the rule.\n      if (node.type === rule.toNodeType) {\n        return {\n          match: 'region',\n          reason: `${rule.fromNodeType} nodes must reach a ${rule.toNodeType} like this one via a ${rule.edgeType} edge`,\n        }\n      }\n      return null\n    }\n    case 'ownership': {\n      if (node.type === rule.nodeType) {\n        return {\n          match: 'subject',\n          reason: `every ${rule.nodeType} must declare a non-empty \"${rule.field}\" field`,\n        }\n      }\n      return null\n    }\n    case 'blast-radius': {\n      const depthLabel = rule.depth !== undefined ? ` at depth ${rule.depth}` : ''\n      if (node.type === rule.nodeType) {\n        return {\n          match: 'subject',\n          reason: `no ${rule.nodeType} may exceed a blast radius of ${rule.maxAffected}${depthLabel}`,\n        }\n      }\n      // Dependent surfacing. The whole point of a blast-radius rule is \"this\n      // subject has too many things depending on it\" — so the agent who most\n      // needs the warning is the one editing one of those dependents, the nodes\n      // that break if the subject changes. We compute the subject's actual\n      // blast radius with getBlastRadius (to the rule's own declared depth) and\n      // surface the rule on any dependent inside it. This is the buildable slice\n      // of ADR-105 §5's scope×distance injection: a real reverse-reachability\n      // walk, not the general overlay, so a far-away node still surfaces the\n      // invariant.\n      const subject = blastRadiusSubjectReaching(graph, rule, nodeId)\n      if (subject) {\n        return {\n          match: 'region',\n          reason: `this node is in the blast radius of ${subject} (a ${rule.nodeType} held to a blast radius of ${rule.maxAffected}${depthLabel}) — it breaks if that ${rule.nodeType} changes`,\n        }\n      }\n      return null\n    }\n    case 'compatibility': {\n      const kindLabel = rule.kind ?? 'all compat shapes'\n      // The evaluator iterates every ServiceNode, so a ServiceNode is the\n      // direct subject.\n      if (node.type === NodeType.ServiceNode) {\n        return {\n          match: 'subject',\n          reason: `this service's dependencies are compatibility-checked (${kindLabel})`,\n        }\n      }\n      // A DatabaseNode one CONNECTS_TO hop from a service is in the region of\n      // the driver-engine shape — its engine version feeds that check.\n      const reachesDriverEngine = rule.kind === undefined || rule.kind === 'driver-engine'\n      if (\n        reachesDriverEngine &&\n        node.type === NodeType.DatabaseNode &&\n        nodeTouchesEdgeType(graph, nodeId, EdgeType.CONNECTS_TO)\n      ) {\n        return {\n          match: 'region',\n          reason: 'services connecting to this database have their driver/engine compatibility checked against it',\n        }\n      }\n      return null\n    }\n    case 'provenance': {\n      const requiredList = requiredProvenanceList(rule.required)\n      // The named target is the direct subject — every governed edge points at\n      // it.\n      if (rule.targetNodeId !== undefined && nodeId === rule.targetNodeId) {\n        return {\n          match: 'subject',\n          reason: `every ${rule.edgeType} edge into ${rule.targetNodeId} must carry ${requiredList} provenance`,\n        }\n      }\n      // Otherwise the node is in the region if it sits on a governed edge.\n      if (nodeTouchesEdgeType(graph, nodeId, rule.edgeType, rule.targetNodeId)) {\n        return {\n          match: 'region',\n          reason:\n            rule.targetNodeId !== undefined\n              ? `this node sits on a ${rule.edgeType} edge to ${rule.targetNodeId}, which must carry ${requiredList} provenance`\n              : `this node sits on a ${rule.edgeType} edge, which must carry ${requiredList} provenance`,\n        }\n      }\n      return null\n    }\n    case 'field-guard': {\n      // The governed node is the rule's direct subject — its type (and, when\n      // narrowed, its `kind`) is what the rule checks. The rule reads two attribute\n      // sets on the one node, so there is no region hop to surface.\n      const kindLabel = rule.nodeKind !== undefined ? ` (kind ${rule.nodeKind})` : ''\n      if (\n        node.type === rule.nodeType &&\n        (rule.nodeKind === undefined || (node as { kind?: string }).kind === rule.nodeKind)\n      ) {\n        return {\n          match: 'subject',\n          reason: `every ${rule.subjectSet} on this ${rule.nodeType}${kindLabel} must appear in ${rule.guardSet}`,\n        }\n      }\n      return null\n    }\n  }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Loader\n// ──────────────────────────────────────────────────────────────────────────\n\n// Reads <projectRoot>/policy.json. Returns [] when the file doesn't exist —\n// a project without policies is a perfectly fine state. Failures to parse\n// throw with the Zod error so the daemon surfaces malformed files loudly\n// instead of silently dropping rules.\nexport async function loadPolicyFile(policyPath: string): Promise<Policy[]> {\n  let raw: string\n  try {\n    raw = await fs.readFile(policyPath, 'utf8')\n  } catch (err) {\n    if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []\n    throw err\n  }\n  const json = JSON.parse(raw) as unknown\n  const file: PolicyFile = PolicyFileSchema.parse(json)\n  return file.policies\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Append-only ndjson writer with id-based dedup\n// ──────────────────────────────────────────────────────────────────────────\n\n// Keeps an in-memory Set of seen violation ids so re-evaluation cycles don't\n// produce duplicate ndjson lines. The set hydrates from disk on first append\n// — startups that load an existing log don't lose dedup state.\nexport class PolicyViolationsLog {\n  private readonly path: string\n  private readonly project: string\n  private seen: Set<string> | null = null\n\n  constructor(logPath: string, project: string = DEFAULT_PROJECT) {\n    this.path = logPath\n    this.project = project\n  }\n\n  async append(v: PolicyViolation): Promise<boolean> {\n    if (!this.seen) await this.hydrate()\n    if (this.seen!.has(v.id)) return false\n    this.seen!.add(v.id)\n    await fs.mkdir(path.dirname(this.path), { recursive: true })\n    await fs.appendFile(this.path, JSON.stringify(v) + '\\n', 'utf8')\n    // Emit policy-violation only on first sighting (post-dedup) so SSE\n    // consumers don't see the same violation again on every evaluation\n    // cycle (ADR-051 #2).\n    emitNeatEvent({\n      type: 'policy-violation',\n      project: this.project,\n      payload: { violation: v },\n    })\n    return true\n  }\n\n  async readAll(): Promise<PolicyViolation[]> {\n    try {\n      const raw = await fs.readFile(this.path, 'utf8')\n      return raw\n        .split('\\n')\n        .filter(Boolean)\n        .map((line) => JSON.parse(line) as PolicyViolation)\n    } catch (err) {\n      if ((err as NodeJS.ErrnoException).code === 'ENOENT') return []\n      throw err\n    }\n  }\n\n  private async hydrate(): Promise<void> {\n    this.seen = new Set()\n    const existing = await this.readAll()\n    for (const v of existing) this.seen.add(v.id)\n  }\n}\n","import { promises as fs } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport semver from 'semver'\nimport compatData from '../compat.json' with { type: 'json' }\n\nexport interface CompatibilityResult {\n  compatible: boolean\n  reason?: string\n  minDriverVersion?: string\n}\n\nexport interface CompatPair {\n  kind?: 'driver-engine'\n  driver: string\n  engine: string\n  minDriverVersion: string\n  // The driver constraint only kicks in once the engine is at this major or higher.\n  // Older engines (e.g. PostgreSQL 13) accept the older driver fine.\n  minEngineVersion?: string\n  reason: string\n}\n\nexport interface NodeEngineConstraint {\n  kind?: 'node-engine'\n  package: string\n  packageMinVersion?: string\n  minNodeVersion: string\n  reason: string\n}\n\nexport interface PackageConflict {\n  kind?: 'package-conflict'\n  package: string\n  packageMinVersion?: string\n  requires: { name: string; minVersion: string }\n  reason: string\n}\n\nexport interface DeprecatedApi {\n  kind?: 'deprecated-api'\n  package: string\n  packageMaxVersion?: string\n  reason: string\n}\n\n// A feature-flag store provider (ADR-242). The flag grain is provider-neutral; a\n// provider's name is data, read here, and never a branch in the reasoning core.\n// `schemaPattern` is the substring of a flag file's `$schema` that names it.\nexport interface FlagStoreProvider {\n  provider: string\n  schemaPattern: string\n  reason?: string\n}\n\nexport interface CompatMatrix {\n  pairs: CompatPair[]\n  nodeEngineConstraints?: NodeEngineConstraint[]\n  packageConflicts?: PackageConflict[]\n  deprecatedApis?: DeprecatedApi[]\n  flagStores?: FlagStoreProvider[]\n}\n\nconst bundledMatrix = compatData as CompatMatrix\nlet mergedMatrix: CompatMatrix | null = null\nlet remoteLoadAttempted = false\n\nconst REMOTE_CACHE_DIR = path.join(os.homedir(), '.neat')\nconst REMOTE_CACHE_PATH = path.join(REMOTE_CACHE_DIR, 'compat-cache.json')\nconst REMOTE_TTL_MS = 24 * 60 * 60 * 1000\n\ninterface RemoteCacheFile {\n  fetchedAt: string\n  url: string\n  matrix: CompatMatrix\n}\n\n// Engines like Postgres/MySQL only carry a major in the version field, so semver\n// won't always parse them cleanly. Compare as integers when both sides look like\n// majors; otherwise fall back to semver.coerce.\nfunction engineMeetsThreshold(engineVersion: string, threshold: string): boolean {\n  const e = parseInt(engineVersion, 10)\n  const t = parseInt(threshold, 10)\n  if (Number.isFinite(e) && Number.isFinite(t)) return e >= t\n\n  const ec = semver.coerce(engineVersion)\n  const tc = semver.coerce(threshold)\n  if (ec && tc) return semver.gte(ec, tc)\n\n  return false\n}\n\nexport function checkCompatibility(\n  driver: string,\n  driverVersion: string,\n  engine: string,\n  engineVersion: string,\n): CompatibilityResult {\n  const matrix = currentMatrix()\n  const pair = matrix.pairs.find((p) => p.driver === driver && p.engine === engine)\n  if (!pair) return { compatible: true }\n\n  if (pair.minEngineVersion && !engineMeetsThreshold(engineVersion, pair.minEngineVersion)) {\n    return { compatible: true }\n  }\n\n  const driverCoerced = semver.coerce(driverVersion)\n  if (!driverCoerced) return { compatible: true }\n\n  if (semver.lt(driverCoerced, pair.minDriverVersion)) {\n    return {\n      compatible: false,\n      reason: pair.reason,\n      minDriverVersion: pair.minDriverVersion,\n    }\n  }\n\n  return { compatible: true }\n}\n\nexport interface NodeEngineCheck {\n  compatible: boolean\n  reason?: string\n  requiredNodeVersion?: string\n}\n\n// True when `serviceNodeRange` (a service's `engines.node`) is guaranteed to\n// admit `requiredNodeVersion`. We use a permissive semver compare via `coerce`\n// — exact ranges like \">=20\" parse fine, exotic ones like \"^20 || ^22\" pass as\n// long as semver can resolve them. If the range can't be parsed at all, we\n// don't claim a conflict — under-flag rather than over-flag.\nfunction rangeAdmitsVersion(serviceNodeRange: string, requiredNodeVersion: string): boolean {\n  try {\n    const required = semver.coerce(requiredNodeVersion)\n    if (!required) return true\n    // Is every version that satisfies the service's range >= required? If yes,\n    // the service guarantees the requirement; if not, there's at least one\n    // admissible Node version that won't satisfy the dep — that's the\n    // conflict.\n    return semver.subset(serviceNodeRange, `>=${required.version}`, {\n      includePrerelease: false,\n    })\n  } catch {\n    return true\n  }\n}\n\nexport function checkNodeEngineConstraint(\n  constraint: NodeEngineConstraint,\n  declaredPackageVersion: string | undefined,\n  serviceNodeRange: string | undefined,\n): NodeEngineCheck {\n  if (constraint.packageMinVersion && declaredPackageVersion) {\n    const v = semver.coerce(declaredPackageVersion)\n    if (v && semver.lt(v, constraint.packageMinVersion)) {\n      return { compatible: true }\n    }\n  }\n  if (!serviceNodeRange) {\n    return { compatible: true }\n  }\n  if (rangeAdmitsVersion(serviceNodeRange, constraint.minNodeVersion)) {\n    return { compatible: true }\n  }\n  return {\n    compatible: false,\n    reason: constraint.reason,\n    requiredNodeVersion: constraint.minNodeVersion,\n  }\n}\n\nexport interface PackageConflictCheck {\n  compatible: boolean\n  reason?: string\n  requires?: { name: string; minVersion: string }\n  foundVersion?: string\n}\n\nexport function checkPackageConflict(\n  conflict: PackageConflict,\n  declaredPackageVersion: string | undefined,\n  declaredRequiredVersion: string | undefined,\n): PackageConflictCheck {\n  if (!declaredPackageVersion) return { compatible: true }\n  if (conflict.packageMinVersion) {\n    const v = semver.coerce(declaredPackageVersion)\n    if (v && semver.lt(v, conflict.packageMinVersion)) {\n      return { compatible: true }\n    }\n  }\n  if (!declaredRequiredVersion) {\n    return {\n      compatible: false,\n      reason: conflict.reason,\n      requires: conflict.requires,\n    }\n  }\n  const requiredCoerced = semver.coerce(declaredRequiredVersion)\n  if (!requiredCoerced) return { compatible: true }\n  if (semver.lt(requiredCoerced, conflict.requires.minVersion)) {\n    return {\n      compatible: false,\n      reason: conflict.reason,\n      requires: conflict.requires,\n      foundVersion: declaredRequiredVersion,\n    }\n  }\n  return { compatible: true }\n}\n\nexport function checkDeprecatedApi(\n  rule: DeprecatedApi,\n  declaredVersion: string | undefined,\n): { compatible: boolean; reason?: string } {\n  if (declaredVersion === undefined) return { compatible: true }\n  if (rule.packageMaxVersion) {\n    const v = semver.coerce(declaredVersion)\n    const max = semver.coerce(rule.packageMaxVersion)\n    if (v && max && semver.gt(v, max)) return { compatible: true }\n  }\n  return { compatible: false, reason: rule.reason }\n}\n\nfunction currentMatrix(): CompatMatrix {\n  return mergedMatrix ?? bundledMatrix\n}\n\nfunction mergeMatrices(a: CompatMatrix, b: CompatMatrix): CompatMatrix {\n  return {\n    pairs: [...a.pairs, ...(b.pairs ?? [])],\n    nodeEngineConstraints: [\n      ...(a.nodeEngineConstraints ?? []),\n      ...(b.nodeEngineConstraints ?? []),\n    ],\n    packageConflicts: [...(a.packageConflicts ?? []), ...(b.packageConflicts ?? [])],\n    deprecatedApis: [...(a.deprecatedApis ?? []), ...(b.deprecatedApis ?? [])],\n    flagStores: [...(a.flagStores ?? []), ...(b.flagStores ?? [])],\n  }\n}\n\nasync function readRemoteCache(url: string): Promise<CompatMatrix | null> {\n  try {\n    const raw = await fs.readFile(REMOTE_CACHE_PATH, 'utf8')\n    const parsed = JSON.parse(raw) as RemoteCacheFile\n    if (parsed.url !== url) return null\n    const age = Date.now() - new Date(parsed.fetchedAt).getTime()\n    if (age > REMOTE_TTL_MS) return null\n    return parsed.matrix\n  } catch {\n    return null\n  }\n}\n\nasync function writeRemoteCache(url: string, matrix: CompatMatrix): Promise<void> {\n  const file: RemoteCacheFile = {\n    fetchedAt: new Date().toISOString(),\n    url,\n    matrix,\n  }\n  try {\n    await fs.mkdir(REMOTE_CACHE_DIR, { recursive: true })\n    await fs.writeFile(REMOTE_CACHE_PATH, JSON.stringify(file), 'utf8')\n  } catch (err) {\n    console.warn(`[neat] failed to cache compat matrix: ${(err as Error).message}`)\n  }\n}\n\n// Loads the bundled matrix and, if `NEAT_COMPAT_URL` is set, merges in a\n// remote extension. Falls back to a fresh fetch when the on-disk cache is\n// stale (24h TTL) or missing. Returns the merged matrix; subsequent calls are\n// memoised.\n//\n// Async because the fetch happens lazily on first use. Extract phase 2 awaits\n// this before iterating pairs; everything else goes through the sync\n// `currentMatrix()` view, which is fine because by the time CLI / traversal\n// runs, extraction has already loaded.\nexport async function ensureCompatLoaded(): Promise<CompatMatrix> {\n  if (mergedMatrix) return mergedMatrix\n  if (remoteLoadAttempted) {\n    mergedMatrix = bundledMatrix\n    return mergedMatrix\n  }\n  remoteLoadAttempted = true\n\n  const url = process.env.NEAT_COMPAT_URL\n  if (!url) {\n    mergedMatrix = bundledMatrix\n    return mergedMatrix\n  }\n\n  const cached = await readRemoteCache(url)\n  if (cached) {\n    mergedMatrix = mergeMatrices(bundledMatrix, cached)\n    return mergedMatrix\n  }\n\n  try {\n    const res = await fetch(url)\n    if (!res.ok) throw new Error(`${res.status} ${res.statusText}`)\n    const remote = (await res.json()) as CompatMatrix\n    await writeRemoteCache(url, remote)\n    mergedMatrix = mergeMatrices(bundledMatrix, remote)\n    return mergedMatrix\n  } catch (err) {\n    console.warn(\n      `[neat] NEAT_COMPAT_URL fetch failed (${(err as Error).message}); using bundled matrix only`,\n    )\n    mergedMatrix = bundledMatrix\n    return mergedMatrix\n  }\n}\n\n// Reset the merged-matrix memo. Intended for tests so each test starts with a\n// freshly loaded matrix.\nexport function resetCompatMatrix(): void {\n  mergedMatrix = null\n  remoteLoadAttempted = false\n}\n\nexport function compatPairs(): readonly CompatPair[] {\n  return currentMatrix().pairs\n}\n\nexport function nodeEngineConstraints(): readonly NodeEngineConstraint[] {\n  return currentMatrix().nodeEngineConstraints ?? []\n}\n\nexport function packageConflicts(): readonly PackageConflict[] {\n  return currentMatrix().packageConflicts ?? []\n}\n\nexport function deprecatedApis(): readonly DeprecatedApi[] {\n  return currentMatrix().deprecatedApis ?? []\n}\n\nexport function flagStoreProviders(): readonly FlagStoreProvider[] {\n  return currentMatrix().flagStores ?? []\n}\n","{\n  \"pairs\": [\n    {\n      \"kind\": \"driver-engine\",\n      \"driver\": \"pg\",\n      \"engine\": \"postgresql\",\n      \"minDriverVersion\": \"8.0.0\",\n      \"minEngineVersion\": \"14\",\n      \"reason\": \"PostgreSQL 14+ requires scram-sha-256 auth by default; pg < 8.0.0 only speaks md5.\"\n    },\n    {\n      \"kind\": \"driver-engine\",\n      \"driver\": \"mysql2\",\n      \"engine\": \"mysql\",\n      \"minDriverVersion\": \"3.0.0\",\n      \"minEngineVersion\": \"8\",\n      \"reason\": \"MySQL 8 defaults to caching_sha2_password; mysql2 < 3.0.0 doesn't negotiate it.\"\n    },\n    {\n      \"kind\": \"driver-engine\",\n      \"driver\": \"mongoose\",\n      \"engine\": \"mongodb\",\n      \"minDriverVersion\": \"7.0.0\",\n      \"minEngineVersion\": \"7\",\n      \"reason\": \"MongoDB 7 drops legacy wire-protocol opcodes that mongoose < 7.0.0 still emits.\"\n    },\n    {\n      \"kind\": \"driver-engine\",\n      \"driver\": \"psycopg2\",\n      \"engine\": \"postgresql\",\n      \"minDriverVersion\": \"2.9.0\",\n      \"minEngineVersion\": \"14\",\n      \"reason\": \"PostgreSQL 14+ requires scram-sha-256 auth by default; psycopg2 < 2.9.0 only speaks md5.\"\n    },\n    {\n      \"kind\": \"driver-engine\",\n      \"driver\": \"pymongo\",\n      \"engine\": \"mongodb\",\n      \"minDriverVersion\": \"4.0.0\",\n      \"minEngineVersion\": \"7\",\n      \"reason\": \"MongoDB 7 drops legacy wire-protocol opcodes that pymongo < 4.0.0 still emits.\"\n    },\n    {\n      \"kind\": \"driver-engine\",\n      \"driver\": \"mysql-connector-python\",\n      \"engine\": \"mysql\",\n      \"minDriverVersion\": \"8.0.0\",\n      \"minEngineVersion\": \"8\",\n      \"reason\": \"MySQL 8 defaults to caching_sha2_password; mysql-connector-python < 8.0.0 doesn't negotiate it.\"\n    }\n  ],\n  \"nodeEngineConstraints\": [\n    {\n      \"kind\": \"node-engine\",\n      \"package\": \"vitest\",\n      \"packageMinVersion\": \"2.0.0\",\n      \"minNodeVersion\": \"18.0.0\",\n      \"reason\": \"vitest >= 2.0 drops Node 16 support; requires Node 18+.\"\n    },\n    {\n      \"kind\": \"node-engine\",\n      \"package\": \"next\",\n      \"packageMinVersion\": \"14.0.0\",\n      \"minNodeVersion\": \"18.17.0\",\n      \"reason\": \"Next 14+ requires Node 18.17+ (uses APIs introduced in that minor).\"\n    },\n    {\n      \"kind\": \"node-engine\",\n      \"package\": \"@modelcontextprotocol/sdk\",\n      \"packageMinVersion\": \"1.0.0\",\n      \"minNodeVersion\": \"18.0.0\",\n      \"reason\": \"@modelcontextprotocol/sdk >= 1 requires Node 18+ (web-streams polyfill removed).\"\n    }\n  ],\n  \"packageConflicts\": [\n    {\n      \"kind\": \"package-conflict\",\n      \"package\": \"@tanstack/react-query\",\n      \"packageMinVersion\": \"5.0.0\",\n      \"requires\": {\n        \"name\": \"react\",\n        \"minVersion\": \"18.0.0\"\n      },\n      \"reason\": \"@tanstack/react-query 5+ uses useSyncExternalStore — only available in React 18+.\"\n    },\n    {\n      \"kind\": \"package-conflict\",\n      \"package\": \"react-router-dom\",\n      \"packageMinVersion\": \"7.0.0\",\n      \"requires\": {\n        \"name\": \"react\",\n        \"minVersion\": \"18.0.0\"\n      },\n      \"reason\": \"react-router-dom 7+ requires React 18+.\"\n    },\n    {\n      \"kind\": \"package-conflict\",\n      \"package\": \"next\",\n      \"packageMinVersion\": \"14.0.0\",\n      \"requires\": {\n        \"name\": \"react\",\n        \"minVersion\": \"18.2.0\"\n      },\n      \"reason\": \"Next.js 14+ requires React 18.2+.\"\n    }\n  ],\n  \"deprecatedApis\": [\n    {\n      \"kind\": \"deprecated-api\",\n      \"package\": \"request\",\n      \"packageMaxVersion\": \"2.88.2\",\n      \"reason\": \"request is deprecated; use undici, node-fetch, or axios instead.\"\n    },\n    {\n      \"kind\": \"deprecated-api\",\n      \"package\": \"node-uuid\",\n      \"reason\": \"node-uuid is deprecated; use the `uuid` package.\"\n    }\n  ],\n  \"flagStores\": [\n    {\n      \"provider\": \"flagd\",\n      \"schemaPattern\": \"flagd.dev/schema\",\n      \"reason\": \"flagd flag definition files name flagd's JSON schema in `$schema`; flagd serves the live definitions on its sync service (FlagSyncService/FetchAllFlags).\"\n    }\n  ]\n}\n","// Frontend-facing event bus (ADR-051). The single in-process EventEmitter\n// every producer (ingest / extract / watch / policy) emits through and the\n// only thing the SSE handler in streaming.ts subscribes to.\n//\n// Direct producer-to-handler coupling is a contract violation — every event\n// goes through `eventBus.emit('event', envelope)` so the SSE layer is the\n// only consumer that has to know the wire taxonomy.\n//\n// The taxonomy was locked at eight types (ADR-051 #2) and grew by one —\n// `incident` — under ADR-221, on the principle that only an append-only,\n// non-reconstructable fact earns a type (a re-derivable query like divergence\n// stays off the bus). A tenth type requires a further successor ADR.\n\nimport { EventEmitter } from 'node:events'\nimport type {\n  GraphEdge,\n  GraphNode,\n  IncidentEventPayload,\n  PolicyViolation,\n  Provenance,\n} from '@neat.is/types'\nimport type { NeatGraph } from './graph.js'\n\n// Locked event taxonomy. Nine values. Tests assert the array shape\n// directly, so adding here without updating the contract is a regression.\nexport const NEAT_EVENT_TYPES = [\n  'node-added',\n  'node-updated',\n  'node-removed',\n  'edge-added',\n  'edge-removed',\n  'extraction-complete',\n  'policy-violation',\n  'stale-transition',\n  'incident',\n] as const\n\nexport type NeatEventType = (typeof NEAT_EVENT_TYPES)[number]\n\n// Per-type payload shapes. The wire layer (SSE) writes the payload as the\n// `data` field; producers use `emit*` helpers below for type safety.\nexport interface NodeAddedPayload {\n  node: GraphNode\n}\nexport interface NodeUpdatedPayload {\n  id: string\n  changes: Partial<GraphNode>\n}\nexport interface NodeRemovedPayload {\n  id: string\n}\nexport interface EdgeAddedPayload {\n  edge: GraphEdge\n}\nexport interface EdgeRemovedPayload {\n  id: string\n}\nexport interface ExtractionCompletePayload {\n  project: string\n  fileCount: number\n  nodesAdded: number\n  edgesAdded: number\n}\nexport interface PolicyViolationPayload {\n  violation: PolicyViolation\n}\nexport interface StaleTransitionPayload {\n  edgeId: string\n  from: typeof Provenance.OBSERVED\n  to: typeof Provenance.STALE\n}\n\nexport type NeatEventPayload = {\n  'node-added': NodeAddedPayload\n  'node-updated': NodeUpdatedPayload\n  'node-removed': NodeRemovedPayload\n  'edge-added': EdgeAddedPayload\n  'edge-removed': EdgeRemovedPayload\n  'extraction-complete': ExtractionCompletePayload\n  'policy-violation': PolicyViolationPayload\n  'stale-transition': StaleTransitionPayload\n  // A lean trigger (ADR-221) — the full incident card is a REST read. Emitted\n  // directly by ingest.ts when an ErrorEvent is appended, not via the\n  // graph-mutation re-emitter.\n  incident: IncidentEventPayload\n}\n\n// What the bus carries internally. Project is metadata used by the SSE\n// handler to route between /events and /projects/:project/events; it never\n// lands in the wire payload.\nexport interface NeatEventEnvelope<T extends NeatEventType = NeatEventType> {\n  type: T\n  project: string\n  payload: NeatEventPayload[T]\n}\n\n// Single event channel — listeners filter by `envelope.type` and\n// `envelope.project`. Using one channel keeps the contract surface narrow\n// and matches the SSE handler's needs (one subscription, fan out).\nexport const EVENT_BUS_CHANNEL = 'event'\n\nclass NeatEventBus extends EventEmitter {}\n\n// Singleton. Process-wide so producers in ingest / extract / watch / policy\n// can emit without threading a bus instance through every call site.\nexport const eventBus: NeatEventBus = new NeatEventBus()\n\n// EventEmitter defaults to 10 listeners; SSE clients add up quickly under a\n// browser refresh storm, so lift the cap.\neventBus.setMaxListeners(0)\n\nexport function emitNeatEvent<T extends NeatEventType>(envelope: NeatEventEnvelope<T>): void {\n  eventBus.emit(EVENT_BUS_CHANNEL, envelope)\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Graph subscription — one place to wire graphology mutation events into\n// the bus so producers don't have to instrument every addNode/addEdge.\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface AttachOptions {\n  project: string\n}\n\n// Subscribes to a NeatGraph and re-emits node/edge add/remove + node/edge\n// attribute updates as bus envelopes scoped to `project`. Returns a detach\n// fn that removes every listener it installed.\n//\n// Stale-transition is NOT routed through here — a provenance flip is just an\n// attribute update from graphology's view, and we'd lose the OBSERVED→STALE\n// semantic. ingest.ts emits stale-transition itself.\nexport function attachGraphToEventBus(graph: NeatGraph, opts: AttachOptions): () => void {\n  const { project } = opts\n\n  const onNodeAdded = (payload: { key: string; attributes: GraphNode }): void => {\n    emitNeatEvent({\n      type: 'node-added',\n      project,\n      payload: { node: payload.attributes },\n    })\n  }\n  const onNodeDropped = (payload: { key: string }): void => {\n    emitNeatEvent({\n      type: 'node-removed',\n      project,\n      payload: { id: payload.key },\n    })\n  }\n  const onEdgeAdded = (payload: { key: string; attributes: GraphEdge }): void => {\n    emitNeatEvent({\n      type: 'edge-added',\n      project,\n      payload: { edge: payload.attributes },\n    })\n  }\n  const onEdgeDropped = (payload: { key: string }): void => {\n    emitNeatEvent({\n      type: 'edge-removed',\n      project,\n      payload: { id: payload.key },\n    })\n  }\n  const onNodeAttrsUpdated = (payload: { key: string; attributes: GraphNode }): void => {\n    emitNeatEvent({\n      type: 'node-updated',\n      project,\n      payload: { id: payload.key, changes: payload.attributes },\n    })\n  }\n\n  graph.on('nodeAdded', onNodeAdded)\n  graph.on('nodeDropped', onNodeDropped)\n  graph.on('edgeAdded', onEdgeAdded)\n  graph.on('edgeDropped', onEdgeDropped)\n  graph.on('nodeAttributesUpdated', onNodeAttrsUpdated)\n\n  return () => {\n    graph.off('nodeAdded', onNodeAdded)\n    graph.off('nodeDropped', onNodeDropped)\n    graph.off('edgeAdded', onEdgeAdded)\n    graph.off('edgeDropped', onEdgeDropped)\n    graph.off('nodeAttributesUpdated', onNodeAttrsUpdated)\n  }\n}\n","import type {\n  BlastRadiusAffectedNode,\n  BlastRadiusResult,\n  DatabaseNode,\n  DeployContext,\n  ErrorEvent,\n  ExpandNeighbour,\n  ExpandResult,\n  GraphEdge,\n  GraphNode,\n  NodeClassification,\n  NodeContext,\n  ObservedDependenciesResult,\n  RelatePath,\n  RelateResult,\n  RootCauseCandidate,\n  RootCauseResult,\n  ServiceNode,\n  TransitiveDependenciesResult,\n  TransitiveDependency,\n} from '@neat.is/types'\nimport { codeFilepathOf, codeLinenoOf } from './ingest.js'\nimport {\n  BlastRadiusResultSchema,\n  EdgeType,\n  ExpandResultSchema,\n  NodeType,\n  ObservedDependenciesResultSchema,\n  ObservedDeployContextSchema,\n  PROV_RANK,\n  Provenance,\n  RelateResultSchema,\n  RootCauseResultSchema,\n  TransitiveDependenciesResultSchema,\n  fileId,\n  frontierEdgeId,\n  isDependencyNodeId,\n  parseSymbolId,\n} from '@neat.is/types'\nimport type { NeatGraph } from './graph.js'\nimport { trafficSourceOf } from './traffic-source.js'\nimport { dependencyNamedInLog, firstErrorLine, type DependencyCandidate, type LogErrorLine, type NamedDependency } from './process-log.js'\nimport {\n  checkCompatibility,\n  checkNodeEngineConstraint,\n  checkPackageConflict,\n  compatPairs,\n  nodeEngineConstraints,\n  packageConflicts,\n} from './compat.js'\n\n// Contract anchors (see /docs/contracts.md + docs/contracts/provenance.md):\n//   * Rule 2 — Coexistence: walk by provenance priority, never collapse edges.\n//   * Rule 3 — FrontierNodes terminate traversal — edges to/from FrontierNodes\n//     are skipped, not merely deprioritized. If a node's only neighbour is a\n//     FrontierNode, traversal stops there. ADR-068 makes node-type the gating\n//     property, independent of edge provenance.\n//   * Rule 5 — Validate results against RootCauseResultSchema /\n//     BlastRadiusResultSchema before returning.\n//   * Rule 8 — No demo-name hardcoding: driver/engine identifiers come from\n//     node properties + compatPairs(), never literals.\n//   * ADR-029 — PROV_RANK is the canonical provenance ranking, imported\n//     from @neat.is/types so consumers (traversal, MCP, policies) all agree.\n\nconst ROOT_CAUSE_MAX_DEPTH = 5\nconst BLAST_RADIUS_DEFAULT_DEPTH = 10\n\n// The interface a service serves: the gRPC methods, routes, GraphQL operations,\n// WebSocket channels and server actions it owns through `service ──CONTAINS──▶`.\n// A caller's OBSERVED CALLS lands on that interface node, not on the service\n// (otel-ingest.md §gRPC: `caller → method → owner`), so the blast radius of the\n// owner reaches its callers through it (ADR-263).\n//\n// These membership tests are functions, not module-level `new Set([Enum.X])`\n// constants: an enum member read at module load can run before @neat.is/types has\n// initialized under vitest's parallel module init (the CI \"is not defined\" flake\n// #1508 traced), and a call-time read never does.\nfunction isServedSurface(type: string): boolean {\n  return (\n    type === NodeType.GrpcMethodNode ||\n    type === NodeType.RouteNode ||\n    type === NodeType.GraphQLOperationNode ||\n    type === NodeType.WebSocketChannelNode ||\n    type === NodeType.ServerActionNode\n  )\n}\n\n// The interface nodes `nodeId` serves, keyed by node id, each with the best\n// CONTAINS edge to it (a .proto-declared method carries both an EXTRACTED and an\n// OBSERVED ownership edge; the OBSERVED one wins).\n// True when the walk reached `n` by stepping from its owner into the interface it\n// serves, rather than along an inbound edge.\nfunction servedViaContains(graph: NeatGraph, n: BlastRadiusAffectedNode): boolean {\n  const owner = n.path[n.path.length - 2]\n  if (owner === undefined || !graph.hasNode(n.nodeId)) return false\n  if (!isServedSurface((graph.getNodeAttributes(n.nodeId) as GraphNode).type)) return false\n  return graph.outboundEdges(owner).some((id) => {\n    const e = graph.getEdgeAttributes(id) as GraphEdge\n    return e.type === EdgeType.CONTAINS && e.target === n.nodeId\n  })\n}\n\nfunction servedSurface(graph: NeatGraph, nodeId: string): Map<string, GraphEdge> {\n  const owned = graph.outboundEdges(nodeId).filter((id) => {\n    const e = graph.getEdgeAttributes(id) as GraphEdge\n    if (e.type !== EdgeType.CONTAINS || !graph.hasNode(e.target)) return false\n    return isServedSurface((graph.getNodeAttributes(e.target) as GraphNode).type)\n  })\n  return bestEdgeByTarget(graph, owned)\n}\n\nfunction isFrontierNode(graph: NeatGraph, nodeId: string): boolean {\n  if (!graph.hasNode(nodeId)) return false\n  const attrs = graph.getNodeAttributes(nodeId) as GraphNode\n  return attrs.type === NodeType.FrontierNode\n}\n\n// Resolve a node on the walk path to the ServiceNode that carries the compat\n// evidence (declared dependencies + node engine). A ServiceNode resolves to\n// itself; a FileNode resolves to its owning service via the inbound\n// `service ──CONTAINS──▶ file` edge (file-awareness.md §2); a SymbolNode\n// resolves one containment level deeper, up the inbound CONTAINS chain\n// `symbol ◀─CONTAINS─ file ◀─CONTAINS─ service` (file-awareness.md §3, ADR-158\n// §7). In a file-first, symbol-deep graph the caller on the path is a File- or\n// SymbolNode, but the dependency declaration lives on the service that owns it —\n// the file or symbol stays on the traversal path, the service is only named as\n// the compat carrier. Anything else has no service to resolve to. Returns the\n// resolved ServiceNode's id + attributes, or null.\nfunction resolveOwningService(\n  graph: NeatGraph,\n  nodeId: string,\n): { id: string; svc: ServiceNode } | null {\n  if (!graph.hasNode(nodeId)) return null\n  const attrs = graph.getNodeAttributes(nodeId) as GraphNode\n  if (attrs.type === NodeType.ServiceNode) {\n    return { id: nodeId, svc: attrs as ServiceNode }\n  }\n  // A FileNode is owned by its service directly; a SymbolNode is owned by its\n  // file, which is in turn owned by the service. Walk the inbound CONTAINS edge\n  // either way — the owner is a ServiceNode for a file (return it), or a FileNode\n  // for a symbol (resolve that file the same way, one hop further).\n  if (attrs.type === NodeType.FileNode || attrs.type === NodeType.SymbolNode) {\n    for (const edgeId of graph.inboundEdges(nodeId)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (e.type !== EdgeType.CONTAINS) continue\n      const owner = graph.getNodeAttributes(e.source) as GraphNode\n      if (owner.type === NodeType.ServiceNode) {\n        return { id: e.source, svc: owner as ServiceNode }\n      }\n      if (owner.type === NodeType.FileNode) {\n        return resolveOwningService(graph, e.source)\n      }\n    }\n  }\n  return null\n}\n\n// A FRONTIER edge is a staged surface (ADR-226), not part of the settled graph:\n// it is never ranked (PROV_RANK has no FRONTIER entry) and never traversed — the\n// edge-level twin of the node-level \"stop at FrontierNodes\" gating (Rule 3). Every\n// ranking / traversal site skips it, so a proposal never contests a settled edge.\nfunction isFrontierEdge(e: GraphEdge): boolean {\n  return e.provenance === Provenance.FRONTIER\n}\n\n// FRONTIER is excluded from PROV_RANK (ADR-226): a staged surface never contests a\n// settled edge, and every ranking site skips it via `isFrontierEdge`. This keeps\n// the floor honest for the type system and as defence-in-depth — an unranked\n// provenance sorts below STALE (PROVENANCE.md's `STALE ≥ FRONTIER`), so even a\n// stray FRONTIER edge that slips a skip can never be picked as the best edge.\nfunction rankOf(p: GraphEdge['provenance']): number {\n  return p === Provenance.FRONTIER ? -1 : PROV_RANK[p]\n}\n\n// Multiple edges between the same pair coexist by provenance (EXTRACTED next to\n// OBSERVED next to INFERRED). Traversal walks the system as the graph \"sees it\n// best\", so for any neighbour pair we pick the highest-provenance edge.\n// Edges connecting to FrontierNodes are skipped at the node level (ADR-068):\n// FrontierNodes are unresolved peers, traversal terminates at them rather than\n// pretending the path continues into unknown territory. FRONTIER-provenance edges\n// are skipped at the edge level (ADR-226): a staged surface is not settled graph.\n// Edges into the dependency layer (ADR-274) are skipped too: third-party packages\n// are answered by the security card, and every first-party walk stays the same\n// whether or not the project's dependencies are in the graph.\nfunction bestEdgeBySource(graph: NeatGraph, edgeIds: string[]): Map<string, GraphEdge> {\n  const best = new Map<string, GraphEdge>()\n  for (const id of edgeIds) {\n    const e = graph.getEdgeAttributes(id) as GraphEdge\n    if (isFrontierNode(graph, e.source) || isFrontierEdge(e) || isDependencyNodeId(e.source)) continue\n    const cur = best.get(e.source)\n    if (!cur || rankOf(e.provenance) > rankOf(cur.provenance)) {\n      best.set(e.source, e)\n    }\n  }\n  return best\n}\n\nfunction bestEdgeByTarget(graph: NeatGraph, edgeIds: string[]): Map<string, GraphEdge> {\n  const best = new Map<string, GraphEdge>()\n  for (const id of edgeIds) {\n    const e = graph.getEdgeAttributes(id) as GraphEdge\n    if (isFrontierNode(graph, e.target) || isFrontierEdge(e) || isDependencyNodeId(e.target)) continue\n    const cur = best.get(e.target)\n    if (!cur || rankOf(e.provenance) > rankOf(cur.provenance)) {\n      best.set(e.target, e)\n    }\n  }\n  return best\n}\n\n// Per-edge confidence is provenance × volume × recency × cleanliness.\n//   * provenance gives a ceiling: OBSERVED 1.0, INFERRED 0.7, EXTRACTED 0.5,\n//     STALE 0.3.\n//   * volume: log-scaled span count, saturating quickly so 1 span ≈ 0.55 and\n//     ~1k spans ≈ 1.0.\n//   * recency: 1.0 within an hour; decays toward 0.5 by 24h, toward 0.3 past.\n//   * cleanliness: error rate above ~10% pulls the score down — a flapping\n//     edge with thousands of spans shouldn't outrank a clean low-traffic one.\n// Bounded to [0, 1]. Walks of multiple edges multiply per-edge confidences.\nconst PROVENANCE_CEILING: Record<string, number> = {\n  OBSERVED: 1.0,\n  INFERRED: 0.7,\n  EXTRACTED: 0.5,\n  STALE: 0.3,\n  // A FRONTIER surface (ADR-226) is a proposal about a cause NEAT could not observe\n  // — the least-trusted claim it makes, below STALE (which was at least once seen).\n  FRONTIER: 0.2,\n}\n\nfunction volumeWeight(spanCount: number | undefined): number {\n  if (!spanCount || spanCount <= 0) return 0.5\n  // log10 saturating around ~1000 spans → ~1.0.\n  const w = 0.5 + Math.log10(spanCount + 1) / 3\n  return Math.min(1, w)\n}\n\nfunction recencyWeight(ageMs: number | undefined): number {\n  if (ageMs === undefined) return 0.8\n  const hour = 60 * 60 * 1000\n  if (ageMs <= hour) return 1.0\n  if (ageMs <= 24 * hour) {\n    const t = (ageMs - hour) / (23 * hour)\n    return 1.0 - 0.5 * t\n  }\n  return 0.3\n}\n\nfunction cleanlinessWeight(spanCount: number | undefined, errorCount: number | undefined): number {\n  if (!spanCount || spanCount <= 0) return 1\n  const rate = (errorCount ?? 0) / spanCount\n  if (rate <= 0.01) return 1\n  if (rate >= 0.5) return 0.3\n  return 1 - rate * 1.4\n}\n\nexport function confidenceForEdge(edge: GraphEdge, now = Date.now()): number {\n  const ceiling = PROVENANCE_CEILING[edge.provenance] ?? 0.5\n\n  // No runtime signal yet → the provenance ceiling is all we have. This keeps\n  // EXTRACTED-only graphs returning the same coarse 0.3/0.5/0.7/1.0 ladder\n  // they always have, while letting OBSERVED edges with real OTel data move\n  // off the ceiling once ingest starts populating signal counters.\n  const spanCount = edge.signal?.spanCount ?? edge.callCount\n  const ageMs = edge.signal?.lastObservedAgeMs ?? lastObservedAge(edge, now)\n  if (spanCount === undefined && ageMs === undefined && edge.signal === undefined) {\n    return ceiling\n  }\n\n  const v = volumeWeight(spanCount)\n  const r = recencyWeight(ageMs)\n  const c = cleanlinessWeight(spanCount, edge.signal?.errorCount)\n  return Math.max(0, Math.min(1, ceiling * v * r * c))\n}\n\nfunction lastObservedAge(edge: GraphEdge, now: number): number | undefined {\n  if (!edge.lastObserved) return undefined\n  const t = Date.parse(edge.lastObserved)\n  if (!Number.isFinite(t)) return undefined\n  return Math.max(0, now - t)\n}\n\n// Path-level confidence is the *product* of per-edge confidences (ADR-036).\n// Each hop is independent evidence and uncertainty compounds — a 3-hop path\n// of edges at confidence 0.8 each gives 0.512, not 0.8. Multiplying punishes\n// long walks accordingly, which is the contract's intent: traversal should\n// surface the cumulative trust the graph actually has, not the weakest link\n// alone.\nfunction confidenceFromMix(edges: GraphEdge[], now = Date.now()): number {\n  if (edges.length === 0) return 1.0\n  let product = 1\n  for (const e of edges) {\n    product *= confidenceForEdge(e, now)\n  }\n  return Math.max(0, Math.min(1, product))\n}\n\ninterface Walk {\n  path: string[]\n  edges: GraphEdge[]\n}\n\n// DFS along incoming edges from start, depth-bounded. Returns the longest path\n// reachable, picking best-provenance edges per neighbour pair so the walk\n// reflects the system as the graph knows it most reliably.\nfunction longestIncomingWalk(graph: NeatGraph, start: string, maxDepth: number): Walk {\n  let best: Walk = { path: [start], edges: [] }\n  const visited = new Set<string>([start])\n\n  function step(node: string, path: string[], edges: GraphEdge[]): void {\n    if (path.length > best.path.length) {\n      best = { path: [...path], edges: [...edges] }\n    }\n    if (path.length - 1 >= maxDepth) return\n\n    const incoming = bestEdgeBySource(graph, graph.inboundEdges(node))\n    for (const [srcId, edge] of incoming) {\n      if (visited.has(srcId)) continue\n      visited.add(srcId)\n      path.push(srcId)\n      edges.push(edge)\n      step(srcId, path, edges)\n      path.pop()\n      edges.pop()\n      visited.delete(srcId)\n    }\n  }\n\n  step(start, [start], [])\n  return best\n}\n\n// Per-shape match result. Each shape walks the same incoming `walk.path` but\n// looks for a different class of incompatibility. Adding a new shape (e.g. a\n// future ConfigNode \"missing required env var\" rule) is one entry in\n// `rootCauseShapeFor` plus its match function — no restructure to getRootCause.\ninterface RootCauseMatch {\n  rootCauseNode: string\n  rootCauseReason: string\n  fixRecommendation?: string\n}\n\ntype RootCauseShape = (\n  graph: NeatGraph,\n  origin: GraphNode,\n  walk: Walk,\n) => RootCauseMatch | null\n\n// DatabaseNode origin → driver/engine compat (the original v0.1.x behavior,\n// preserved verbatim). The walk ignores non-ServiceNodes; the first upstream\n// service whose declared driver fails compat against the origin DB's\n// (engine, engineVersion) wins.\nfunction databaseRootCauseShape(\n  graph: NeatGraph,\n  origin: GraphNode,\n  walk: Walk,\n): RootCauseMatch | null {\n  const targetDb = origin as DatabaseNode\n  // Pairs that could possibly hit on this engine — narrowed once outside the\n  // walk so we don't re-scan the matrix for every service we visit.\n  const candidatePairs = compatPairs().filter((p) => p.engine === targetDb.engine)\n  if (candidatePairs.length === 0) return null\n\n  for (const id of walk.path) {\n    // The compat carrier is a service: a ServiceNode resolves to itself, a\n    // FileNode on the path resolves to its owning service via CONTAINS\n    // (file-awareness.md §2). In a file-first graph the caller on the walk is\n    // the FileNode that holds the CALLS edge, but the declared driver lives on\n    // the service that owns it.\n    const owner = resolveOwningService(graph, id)\n    if (!owner) continue\n    const { id: serviceId, svc } = owner\n    const deps = svc.dependencies ?? {}\n    for (const pair of candidatePairs) {\n      const declared = deps[pair.driver]\n      if (!declared) continue\n      const result = checkCompatibility(\n        pair.driver,\n        declared,\n        targetDb.engine,\n        targetDb.engineVersion,\n      )\n      if (!result.compatible) {\n        return {\n          rootCauseNode: serviceId,\n          rootCauseReason: result.reason ?? 'incompatible driver',\n          ...(result.minDriverVersion\n            ? {\n                fixRecommendation: `Upgrade ${svc.name} ${pair.driver} driver to >= ${result.minDriverVersion}`,\n              }\n            : {}),\n        }\n      }\n    }\n  }\n  return null\n}\n\n// ServiceNode origin → node-engine + package-conflict shapes from compat.ts.\n// The check is over each ServiceNode along the incoming walk (the origin\n// itself + any upstream callers): a node-engine constraint failing against\n// the service's `engines.node`, or a package-conflict where a declared dep\n// requires a peer at a higher version than the service has.\nfunction serviceRootCauseShape(\n  graph: NeatGraph,\n  _origin: GraphNode,\n  walk: Walk,\n): RootCauseMatch | null {\n  for (const id of walk.path) {\n    // ServiceNode → itself; FileNode → owning service via CONTAINS\n    // (file-awareness.md §2). The compat evidence (declared deps, node engine)\n    // lives on the service, even when the caller on the walk is a file.\n    const owner = resolveOwningService(graph, id)\n    if (!owner) continue\n    const { id: serviceId, svc } = owner\n    const deps = svc.dependencies ?? {}\n    const serviceNodeEngine = svc.nodeEngine\n\n    for (const constraint of nodeEngineConstraints()) {\n      const declared = deps[constraint.package]\n      if (!declared) continue\n      const result = checkNodeEngineConstraint(constraint, declared, serviceNodeEngine)\n      if (!result.compatible && result.reason) {\n        return {\n          rootCauseNode: serviceId,\n          rootCauseReason: result.reason,\n          ...(result.requiredNodeVersion\n            ? {\n                fixRecommendation: `Bump ${svc.name}'s engines.node to >= ${result.requiredNodeVersion}`,\n              }\n            : {}),\n        }\n      }\n    }\n\n    for (const conflict of packageConflicts()) {\n      const declared = deps[conflict.package]\n      if (!declared) continue\n      const requiredDeclared = deps[conflict.requires.name]\n      const result = checkPackageConflict(conflict, declared, requiredDeclared)\n      if (!result.compatible && result.reason) {\n        return {\n          rootCauseNode: serviceId,\n          rootCauseReason: result.reason,\n          fixRecommendation: `Upgrade ${svc.name}'s ${conflict.requires.name} to >= ${conflict.requires.minVersion}`,\n        }\n      }\n    }\n  }\n  return null\n}\n\n// FileNode origin → resolve the file to its owning service (file-awareness.md\n// §2) and run the service shape. In a file-first graph an error can land on a\n// FileNode (the file that holds the failing CALLS edge); the incompatibility,\n// if any, is still a property of the service that owns the file's declared\n// dependencies. The owning service is folded into the origin's position so the\n// service shape scans it alongside the upstream walk.\nfunction fileRootCauseShape(\n  graph: NeatGraph,\n  origin: GraphNode,\n  walk: Walk,\n): RootCauseMatch | null {\n  const owner = resolveOwningService(graph, origin.id)\n  if (!owner) return null\n  return serviceRootCauseShape(graph, owner.svc, walk)\n}\n\n// SymbolNode origin → resolve the symbol to its owning service through the\n// inbound CONTAINS chain (symbol ◀─CONTAINS─ file ◀─CONTAINS─ service,\n// file-awareness.md §3 / ADR-158 §7) and run the service shape — one grain finer\n// than the FileNode case. A failure can land on a SymbolNode (the function that\n// holds the failing edge); the incompatibility, if any, is still a property of\n// the service that owns the symbol's declared dependencies. The symbol stays the\n// origin on the traversal path; the service is only the resolved carrier.\nfunction symbolRootCauseShape(\n  graph: NeatGraph,\n  origin: GraphNode,\n  walk: Walk,\n): RootCauseMatch | null {\n  const owner = resolveOwningService(graph, origin.id)\n  if (!owner) return null\n  return serviceRootCauseShape(graph, owner.svc, walk)\n}\n\n// Dispatch by origin node type per ADR-037. Origin types not present here\n// (InfraNode, ConfigNode, FrontierNode) cleanly return null — getRootCause\n// needs an explicit shape to know what an \"incompatibility\" looks like for\n// that origin, and those types don't have one yet. Adding the SymbolNode shape\n// (ADR-158 §7) is one entry: symbols ride the same service-carrier resolution\n// files do, one containment level deeper.\n// A call-time lookup, not a module-level object keyed by enum members (see\n// isServedSurface).\nfunction rootCauseShapeFor(type: GraphNode['type']): RootCauseShape | undefined {\n  switch (type) {\n    case NodeType.DatabaseNode:\n      return databaseRootCauseShape\n    case NodeType.ServiceNode:\n      return serviceRootCauseShape\n    case NodeType.FileNode:\n      return fileRootCauseShape\n    case NodeType.SymbolNode:\n      return symbolRootCauseShape\n    default:\n      return undefined\n  }\n}\n\n// Which branch of the single-verdict walk produced a seed. The navigation reads\n// this so it never second-guesses an edge- or compat-backed cause (ADR-209): only\n// an `incident` seed — the failure localized to the queried node itself, no causal\n// edge walked — is a candidate for the STALE-chain fallback.\ntype LegacyCauseSource = 'compat' | 'cross-service' | 'incident'\ninterface TaggedRootCause {\n  result: RootCauseResult\n  source: LegacyCauseSource\n}\n\n// The single-verdict root cause (ADR-037 / ADR-114): the compat shape, the\n// cross-service failing-CALLS chain, then the incident store. This is the seed\n// the navigation classifies and, when the seed is a saturated/stale victim,\n// overrides. Retained verbatim so the deprecation escape hatch (ADR-189,\n// NEAT_RCA_NAVIGATION=0) returns exactly the pre-navigation result; the `source`\n// tag rides alongside and is dropped for that escape hatch.\nfunction legacyRootCause(\n  graph: NeatGraph,\n  errorNodeId: string,\n  errorEvent?: ErrorEvent,\n  incidents?: ErrorEvent[],\n): TaggedRootCause | null {\n  if (!graph.hasNode(errorNodeId)) return null\n  const origin = graph.getNodeAttributes(errorNodeId) as GraphNode\n  const shape = rootCauseShapeFor(origin.type)\n\n  if (shape) {\n    const walk = longestIncomingWalk(graph, errorNodeId, ROOT_CAUSE_MAX_DEPTH)\n    const match = shape(graph, origin, walk)\n    if (match) {\n      const reason = errorEvent\n        ? `${match.rootCauseReason} (observed error: ${errorEvent.errorMessage})`\n        : match.rootCauseReason\n\n      // Schema-validate before return (ADR-036, #139). A drift in the result\n      // shape becomes a runtime throw at the call site rather than a silently\n      // malformed payload reaching MCP / REST consumers.\n      return {\n        source: 'compat',\n        result: RootCauseResultSchema.parse({\n          rootCauseNode: match.rootCauseNode,\n          rootCauseReason: reason,\n          traversalPath: walk.path,\n          edgeProvenances: walk.edges.map((e) => e.provenance),\n          confidence: confidenceFromMix(walk.edges),\n          fixRecommendation: match.fixRecommendation,\n        }),\n      }\n    }\n  }\n\n  // A service surfacing a failure may be the entry point of a cross-service\n  // 500 that actually originates downstream. Nothing calls the entry service,\n  // so the incoming walk above is empty — but its own OBSERVED CALLS edge to\n  // the callee carries the failure. Follow that outbound failing CALLS chain to\n  // the real culprit's handler before self-attributing the caller's mislabelled\n  // CLIENT span (#589). Only null-returns here when no downstream call is\n  // failing, i.e. the failure is in process at the origin.\n  if (origin.type === NodeType.ServiceNode) {\n    const crossService = crossServiceRootCause(graph, errorNodeId, incidents, errorEvent)\n    if (crossService) return { result: crossService, source: 'cross-service' }\n  }\n\n  // No graph edge carried an incompatibility and no downstream call is failing —\n  // but a service can fail in process (a 500 thrown inside its own handler)\n  // without that failure ever crossing an edge, so the walk above sees a\n  // healthy-looking node. The recorded incident store is the OBSERVED evidence\n  // the graph can't carry: it localizes the failure to the file:line / route the\n  // failing span captured. Consulting it here keeps root-cause useful for the\n  // in-process case instead of reporting \"healthy\" over a pile of 500s (#584).\n  const incident = rootCauseFromIncidents(errorNodeId, incidents, errorEvent)\n  return incident ? { result: incident, source: 'incident' } : null\n}\n\n// OBSERVED-grade confidence for an incident-localized cause. The incident is a\n// real captured runtime fact (where the failure surfaced), but it names the\n// surface, not a proven upstream incompatibility — so it sits below an\n// edge-walked compat result yet well above an EXTRACTED guess.\nconst INCIDENT_ROOT_CAUSE_CONFIDENCE = 0.6\n\n// Match an incident to the queried node the same way the REST incident-history\n// read does (api.ts): an exact affectedNode hit, or a service match when the\n// node is the service the incident was recorded against. A file-grained\n// affectedNode (file:<svc>:<path>) still matches the owning service this way.\nfunction incidentMatchesNode(ev: ErrorEvent, nodeId: string): boolean {\n  if (ev.affectedNode === nodeId) return true\n  if (ev.service === nodeId.replace(/^service:/, '')) return true\n  // A symbol-grained incident (ADR-191) also matches its owning FILE, so a\n  // file-grained query still surfaces a failure the finer node localized —\n  // querying the function returns the function, querying its file still hits.\n  const sym = parseSymbolId(ev.affectedNode)\n  if (sym && fileId(sym.service, sym.relPath) === nodeId) return true\n  return false\n}\n\n// A failure localized to a node through the incident store: which node carries\n// the cause, the human reason, the file the failure surfaced in (when the\n// incident captured a `code.*` call site), and the derived fix.\ninterface IncidentLocalization {\n  rootCauseNode: string\n  rootCauseReason: string\n  // The finer node the failure surfaced in — a FileNode, or one grain deeper the\n  // SymbolNode `code.function` named (ADR-191) — present only when the incident\n  // localized below the queried node. Callers walk node → finer node as a single\n  // OBSERVED hop when this is set.\n  fileNode?: string\n  fixRecommendation?: string\n}\n\n// Pick the most recent incident affecting `nodeId` and localize the failure to\n// the file:line / route it captured. Returns null when no incident touches the\n// node. Shared by the in-process fallback and the cross-service chain (#589) so\n// both describe a culprit's handler the same way.\nfunction localizeFromIncidents(\n  nodeId: string,\n  incidents: ErrorEvent[] | undefined,\n  errorEvent: ErrorEvent | undefined,\n): IncidentLocalization | null {\n  const pool = incidents && incidents.length > 0 ? incidents : errorEvent ? [errorEvent] : []\n  const relevant = pool.filter((ev) => incidentMatchesNode(ev, nodeId))\n  if (relevant.length === 0) return null\n\n  // Most recent incident is the representative; ISO timestamps sort lexically.\n  const latest = [...relevant].sort((a, b) => b.timestamp.localeCompare(a.timestamp))[0]!\n  const attrs = latest.attributes ?? {}\n  // Read the call site through the shared dual-name helper (semconv ≥1.33 stable\n  // names + the prior ones), so incident localization survives either generation.\n  const filepath = codeFilepathOf(attrs)\n  const lineno = codeLinenoOf(attrs)\n  const route = typeof attrs['http.route'] === 'string' ? attrs['http.route'] : undefined\n  const location = filepath ? `${filepath}${lineno !== undefined ? `:${lineno}` : ''}` : undefined\n\n  // Count the incidents of *this* failure mode, not every incident on the node.\n  // The reason names one message (`latest.errorMessage`); pairing it with the\n  // node's total incident count reads as though that one error happened N times\n  // when the node may be failing several different ways. Scope the count to the\n  // records sharing this message so \"3 recorded incidents\" means three of the\n  // failure the reason actually describes (issue #624).\n  const sameMode = relevant.filter((ev) => ev.errorMessage === latest.errorMessage)\n  const count = sameMode.length\n  const tail = count > 1 ? ` (${count} recorded incidents)` : ' (1 recorded incident)'\n  const reasonParts = [`${latest.service}: ${latest.errorMessage}`]\n  if (location) reasonParts.push(`surfaced at ${location}`)\n  const rootCauseReason = `${reasonParts.join(' — ')}${tail}`\n\n  // When the incident localized to a finer node — a file, or one grain deeper the\n  // SYMBOL the failing span named via `code.function` (ADR-191) — name that node\n  // as the root cause, so a query at any grain descends to the exact function the\n  // failure surfaced in. OBSERVED is honest: the node came from a real `code.*` on\n  // the failing span. Otherwise the cause sits on the queried node itself.\n  const localizesFiner =\n    latest.affectedNode !== nodeId &&\n    (latest.affectedNode.startsWith('file:') || latest.affectedNode.startsWith('symbol:'))\n  const fileNode = localizesFiner ? latest.affectedNode : undefined\n\n  const fixRecommendation = location\n    ? `Inspect ${location}${route ? ` handling ${route}` : ''}`\n    : route\n      ? `Inspect ${latest.service}'s handler for ${route}`\n      : undefined\n\n  return {\n    rootCauseNode: fileNode ?? nodeId,\n    rootCauseReason,\n    ...(fileNode ? { fileNode } : {}),\n    ...(fixRecommendation ? { fixRecommendation } : {}),\n  }\n}\n\n// Build a root-cause result from the recorded incident store when the graph\n// walk found nothing. Localizes the failure to the queried node itself (or the\n// file it surfaced in). Returns null when no incident touches the node — the\n// honest \"nothing to say\" answer.\nfunction rootCauseFromIncidents(\n  nodeId: string,\n  incidents: ErrorEvent[] | undefined,\n  errorEvent: ErrorEvent | undefined,\n): RootCauseResult | null {\n  const loc = localizeFromIncidents(nodeId, incidents, errorEvent)\n  if (!loc) return null\n\n  const traversalPath = loc.fileNode ? [nodeId, loc.fileNode] : [nodeId]\n  const edgeProvenances = loc.fileNode ? [Provenance.OBSERVED] : []\n\n  return RootCauseResultSchema.parse({\n    rootCauseNode: loc.rootCauseNode,\n    rootCauseReason: loc.rootCauseReason,\n    traversalPath,\n    edgeProvenances,\n    confidence: INCIDENT_ROOT_CAUSE_CONFIDENCE,\n    ...(loc.fixRecommendation ? { fixRecommendation: loc.fixRecommendation } : {}),\n  })\n}\n\n// A CALLS edge counts as failing when its OBSERVED signal recorded at least one\n// error. This is the signal the cross-service chain follows: the caller's call\n// to the callee returned a 5xx (#589).\nfunction isFailingCallEdge(e: GraphEdge): boolean {\n  return e.type === EdgeType.CALLS && !isFrontierEdge(e) && (e.signal?.errorCount ?? 0) > 0\n}\n\n// Every node id that can originate an outbound CALLS edge on a service's behalf:\n// the service itself, each FileNode it CONTAINS, and each SymbolNode those files\n// CONTAIN. A file-first graph anchors the caller's CALLS edge on the call-site\n// file (file-awareness.md §4); one grain finer, an OBSERVED CALLS edge lands on\n// the calling SymbolNode (ADR-158 §4), so an entry service's failing call may\n// hang off a file it owns or a symbol that file owns, not the bare service node.\n// Descending the two CONTAINS levels keeps the cross-service chain symbol-aware\n// without the reasoning ever branching on grain.\nfunction callSourcesForService(graph: NeatGraph, serviceId: string): string[] {\n  const ids = [serviceId]\n  for (const edgeId of graph.outboundEdges(serviceId)) {\n    const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n    if (e.type !== EdgeType.CONTAINS) continue\n    const tgt = graph.getNodeAttributes(e.target) as GraphNode\n    if (tgt.type !== NodeType.FileNode) continue\n    ids.push(e.target)\n    for (const symEdgeId of graph.outboundEdges(e.target)) {\n      const se = graph.getEdgeAttributes(symEdgeId) as GraphEdge\n      if (se.type !== EdgeType.CONTAINS) continue\n      const sym = graph.getNodeAttributes(se.target) as GraphNode\n      if (sym.type === NodeType.SymbolNode) ids.push(se.target)\n    }\n  }\n  return ids\n}\n\n// Did edge `e` to service `id` beat the current best failing call? Most recorded\n// errors win; ties break on PROV_RANK, then target id — deterministic.\nfunction failingCallDominates(\n  e: GraphEdge,\n  id: string,\n  curEdge: GraphEdge,\n  curId: string,\n): boolean {\n  const ec = e.signal?.errorCount ?? 0\n  const cc = curEdge.signal?.errorCount ?? 0\n  if (ec !== cc) return ec > cc\n  if (rankOf(e.provenance) !== rankOf(curEdge.provenance)) {\n    return rankOf(e.provenance) > rankOf(curEdge.provenance)\n  }\n  return id < curId\n}\n\n// The dominant failing outbound CALLS from a service: among the service's own\n// edges and those of the files it owns, the failing CALLS edge to another\n// service with the most recorded errors. Returns the next-hop service id and the\n// edge, or null when no downstream call is failing — meaning the failure is in\n// process here, not relayed from deeper.\nfunction dominantFailingCall(\n  graph: NeatGraph,\n  serviceId: string,\n  visited: Set<string>,\n): { nextService: string; edge: GraphEdge } | null {\n  let best: { nextService: string; edge: GraphEdge } | null = null\n  for (const src of callSourcesForService(graph, serviceId)) {\n    for (const edgeId of graph.outboundEdges(src)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (!isFailingCallEdge(e)) continue\n      if (isFrontierNode(graph, e.target)) continue\n      const owner = resolveOwningService(graph, e.target)\n      if (!owner || visited.has(owner.id)) continue\n      if (!best || failingCallDominates(e, owner.id, best.edge, best.nextService)) {\n        best = { nextService: owner.id, edge: e }\n      }\n    }\n  }\n  return best\n}\n\n// Walk the failing CALLS chain outbound from an entry service to the deepest\n// still-failing callee — the service whose own downstream calls are clean and\n// whose handler therefore threw (#589). Returns the path of service ids, the\n// failing edges along it, and the culprit, or null when nothing downstream is\n// failing.\nfunction followFailingCallChain(\n  graph: NeatGraph,\n  originServiceId: string,\n  maxDepth: number,\n): { path: string[]; edges: GraphEdge[]; culprit: string } | null {\n  const path = [originServiceId]\n  const edges: GraphEdge[] = []\n  const visited = new Set<string>([originServiceId])\n  let current = originServiceId\n\n  for (let depth = 0; depth < maxDepth; depth++) {\n    const hop = dominantFailingCall(graph, current, visited)\n    if (!hop) break\n    path.push(hop.nextService)\n    edges.push(hop.edge)\n    visited.add(hop.nextService)\n    current = hop.nextService\n  }\n\n  if (edges.length === 0) return null\n  return { path, edges, culprit: current }\n}\n\n// A CALLS edge whose live signal has gone quiet: STALE provenance (ADR-209). The\n// topology was OBSERVED once and remains in the graph, but the error signal\n// `isFailingCallEdge` reads is gone — a stale snapshot lost it — so the failing\n// chain above finds nothing to follow even though the causal chain is still here.\nfunction isStaleCallEdge(e: GraphEdge): boolean {\n  return e.type === EdgeType.CALLS && e.provenance === Provenance.STALE\n}\n\n// Did stale edge `e` to service `id` beat the current best stale hop? There is no\n// error signal left to rank on — that is exactly what went quiet — so rank by the\n// last-observed call volume (the hotter known path is the likelier carrier), then\n// target id, deterministic like `failingCallDominates`.\nfunction staleCallDominates(e: GraphEdge, id: string, curEdge: GraphEdge, curId: string): boolean {\n  const ev = e.signal?.spanCount ?? e.callCount ?? 0\n  const cv = curEdge.signal?.spanCount ?? curEdge.callCount ?? 0\n  if (ev !== cv) return ev > cv\n  return id < curId\n}\n\n// The dominant STALE outbound CALLS from a service, used only as the fallback when\n// no fresh failing chain exists (ADR-209). Among the service's own edges and those\n// of the files/symbols it owns, take the best-provenance CALLS edge PER callee\n// service first — so a callee reachable by any fresher (OBSERVED/INFERRED/\n// EXTRACTED) edge is represented by that fresher edge — then keep only the callees\n// whose best edge is STALE. That PROV_RANK gate is the \"nothing fresher is\n// reachable\" guard: a target the graph still knows freshly is never walked stalely.\nfunction dominantStaleCall(\n  graph: NeatGraph,\n  serviceId: string,\n  visited: Set<string>,\n): { nextService: string; edge: GraphEdge } | null {\n  const bestByCallee = new Map<string, GraphEdge>()\n  for (const src of callSourcesForService(graph, serviceId)) {\n    for (const edgeId of graph.outboundEdges(src)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (e.type !== EdgeType.CALLS) continue\n      if (isFrontierNode(graph, e.target) || isFrontierEdge(e)) continue\n      const owner = resolveOwningService(graph, e.target)\n      if (!owner || visited.has(owner.id)) continue\n      const cur = bestByCallee.get(owner.id)\n      if (!cur || rankOf(e.provenance) > rankOf(cur.provenance)) {\n        bestByCallee.set(owner.id, e)\n      }\n    }\n  }\n  let best: { nextService: string; edge: GraphEdge } | null = null\n  for (const [id, edge] of bestByCallee) {\n    if (!isStaleCallEdge(edge)) continue\n    if (!best || staleCallDominates(edge, id, best.edge, best.nextService)) {\n      best = { nextService: id, edge }\n    }\n  }\n  return best\n}\n\n// Walk the STALE CALLS chain outbound from a service to its deepest stale-only\n// callee — the last node the last-observed topology still reaches (ADR-209). The\n// stale analogue of `followFailingCallChain`: same shape, but each hop is a target\n// the graph knows ONLY stalely, so the whole chain is a low-confidence, honestly-\n// provenanced hypothesis rather than a signal-backed verdict. Returns null when no\n// stale-only outbound CALLS exists — a node with only fresh or no downstream edges.\nfunction followStaleCallChain(\n  graph: NeatGraph,\n  originServiceId: string,\n  maxDepth: number,\n): { path: string[]; edges: GraphEdge[]; culprit: string } | null {\n  const path = [originServiceId]\n  const edges: GraphEdge[] = []\n  const visited = new Set<string>([originServiceId])\n  let current = originServiceId\n\n  for (let depth = 0; depth < maxDepth; depth++) {\n    const hop = dominantStaleCall(graph, current, visited)\n    if (!hop) break\n    path.push(hop.nextService)\n    edges.push(hop.edge)\n    visited.add(hop.nextService)\n    current = hop.nextService\n  }\n\n  if (edges.length === 0) return null\n  return { path, edges, culprit: current }\n}\n\n// Localize a cross-service failure (#589). An entry ServiceNode surfaces a 500\n// that originates downstream: follow the failing CALLS chain to the culprit and\n// describe its handler, never the caller's mis-attributed CLIENT span. Returns\n// null when no outbound call is failing — the failure is in process here and the\n// caller falls through to the origin's own incident store.\nfunction crossServiceRootCause(\n  graph: NeatGraph,\n  originId: string,\n  incidents: ErrorEvent[] | undefined,\n  errorEvent: ErrorEvent | undefined,\n): RootCauseResult | null {\n  const chain = followFailingCallChain(graph, originId, ROOT_CAUSE_MAX_DEPTH)\n  if (!chain) return null\n\n  const culprit = chain.culprit\n  const path = [...chain.path]\n  const edgeProvenances = chain.edges.map((e) => e.provenance)\n\n  // Cross-service confidence cascades over the failing CALLS edges and the\n  // incident-localization hop, so it lands below an edge-walked compat result.\n  const baseConfidence = confidenceFromMix(chain.edges)\n  const confidence = Math.max(0, Math.min(1, baseConfidence * INCIDENT_ROOT_CAUSE_CONFIDENCE))\n\n  const loc = localizeFromIncidents(culprit, incidents, errorEvent)\n  if (loc) {\n    let rootCauseNode = culprit\n    if (loc.fileNode) {\n      path.push(loc.fileNode)\n      edgeProvenances.push(Provenance.OBSERVED)\n      rootCauseNode = loc.fileNode\n    }\n    return RootCauseResultSchema.parse({\n      rootCauseNode,\n      rootCauseReason: loc.rootCauseReason,\n      traversalPath: path,\n      edgeProvenances,\n      confidence,\n      ...(loc.fixRecommendation ? { fixRecommendation: loc.fixRecommendation } : {}),\n    })\n  }\n\n  // No recorded incident for the culprit — still better than blaming the caller.\n  // Name the culprit service and read the reason off the failing edge.\n  const lastEdge = chain.edges[chain.edges.length - 1]!\n  const errs = lastEdge.signal?.errorCount ?? 0\n  const culpritName = culprit.replace(/^service:/, '')\n  return RootCauseResultSchema.parse({\n    rootCauseNode: culprit,\n    rootCauseReason: `${culpritName} is failing downstream calls (${errs} observed error${errs === 1 ? '' : 's'})`,\n    traversalPath: path,\n    edgeProvenances,\n    confidence,\n    fixRecommendation: `Inspect ${culpritName}'s failing handler`,\n  })\n}\n\n// BFS along *inbound* edges from origin — the origin's dependents, i.e. what\n// breaks if the origin changes or fails (get-blast-radius.md, superseding\n// ADR-038's outbound direction). An edge `A ──depends-on──▶ B` means A breaks\n// when B changes, so the blast radius of B walks back along inbound edges to A\n// and everything that transitively depends on it. For an inbound edge the\n// neighbour is the edge's `source` (the dependent), so selection uses\n// bestEdgeBySource — the same machinery getRootCause walks inbound with.\n// Records each reachable dependent with the shortest distance back to origin\n// and the provenance of the edge that brought us to it. A sink (a database,\n// shared lib, leaf util) has no outbound edges but does have inbound ones, so\n// this is what makes its blast radius non-empty.\nexport function getBlastRadius(\n  graph: NeatGraph,\n  nodeId: string,\n  maxDepth = BLAST_RADIUS_DEFAULT_DEPTH,\n): BlastRadiusResult {\n  if (!graph.hasNode(nodeId)) {\n    return BlastRadiusResultSchema.parse({ origin: nodeId, affectedNodes: [], totalAffected: 0 })\n  }\n\n  // Each frame carries its full predecessor chain so the affected-node payload\n  // can surface `path` (origin → ... → nodeId) and `confidence` (cascaded over\n  // every edge along that path). The BFS visits each reachable node once on\n  // its shortest-distance path; later frames at greater distance are dropped.\n  interface Frame {\n    nodeId: string\n    distance: number\n    path: string[]\n    pathEdges: GraphEdge[]\n  }\n\n  const seen = new Map<string, BlastRadiusAffectedNode>()\n  const queue: Frame[] = [{ nodeId, distance: 0, path: [nodeId], pathEdges: [] }]\n  const enqueued = new Set<string>([nodeId])\n\n  while (queue.length > 0) {\n    const frame = queue.shift()!\n    if (frame.distance > 0 && frame.pathEdges.length > 0) {\n      const lastEdge = frame.pathEdges[frame.pathEdges.length - 1]!\n      // Blast radius KEEPS CONTAINS: walked inbound, `file ◀─CONTAINS─ service`\n      // means the service owns an affected file, so the service is genuinely in\n      // the blast radius (file-awareness §36 — file-grained dependents plus the\n      // owning service). Only get_dependencies filters CONTAINS (ADR-140), where\n      // it's walked outbound and a service doesn't depend on its own files.\n      seen.set(frame.nodeId, {\n        nodeId: frame.nodeId,\n        distance: frame.distance,\n        edgeProvenance: lastEdge.provenance,\n        path: frame.path,\n        confidence: confidenceFromMix(frame.pathEdges),\n      })\n    }\n    if (frame.distance >= maxDepth) continue\n\n    // Dependents point at the node itself, or at the interface it serves: a gRPC\n    // caller's CALLS lands on `grpc:<svc>/<method>`, which the service CONTAINS.\n    // The served node breaks with its owner, and the walk goes on from it to its\n    // callers (ADR-263).\n    const next = [\n      ...bestEdgeBySource(graph, graph.inboundEdges(frame.nodeId)),\n      ...servedSurface(graph, frame.nodeId),\n    ]\n    for (const [srcId, edge] of next) {\n      if (enqueued.has(srcId)) continue\n      enqueued.add(srcId)\n      queue.push({\n        nodeId: srcId,\n        distance: frame.distance + 1,\n        path: [...frame.path, srcId],\n        pathEdges: [...frame.pathEdges, edge],\n      })\n    }\n  }\n\n  // A dependent's own interface is walked through only to find its callers; the\n  // rest of it (frontend's /cinema when geo fails) is not shown to break. The\n  // origin's interface does break with it, so it stays (ADR-263).\n  const onPath = new Set<string>()\n  for (const n of seen.values()) for (const id of n.path.slice(1, -1)) onPath.add(id)\n  const affectedNodes = [...seen.values()]\n    .filter((n) => n.distance === 1 || !servedViaContains(graph, n) || onPath.has(n.nodeId))\n    .sort((a, b) => a.distance - b.distance || a.nodeId.localeCompare(b.nodeId))\n  return BlastRadiusResultSchema.parse({\n    origin: nodeId,\n    affectedNodes,\n    totalAffected: affectedNodes.length,\n  })\n}\n\n// Default + max depth for transitive get_dependencies (issue #144). Default\n// 3 keeps the output legible at the agent layer; the contract caps the\n// caller-supplied value at 10 to prevent BFS blow-up on dense graphs.\nexport const TRANSITIVE_DEPENDENCIES_DEFAULT_DEPTH = 3\nexport const TRANSITIVE_DEPENDENCIES_MAX_DEPTH = 10\n\n// Transitive get_dependencies (ADR-039 / #144). BFS outbound from origin to\n// `depth` hops, returning a flat list with distance, edgeType, and provenance\n// per dependency. Origin is never in the list. Direct-only consumers pass\n// depth=1; the MCP get_dependencies tool defaults to 3.\n//\n// Reuses bestEdgeByTarget (FRONTIER filtered, PROV_RANK-best per pair) so\n// dedup behavior matches the rest of traversal. Result is schema-validated\n// before return per ADR-036 §Result schema validation.\nexport function getTransitiveDependencies(\n  graph: NeatGraph,\n  nodeId: string,\n  depth: number = TRANSITIVE_DEPENDENCIES_DEFAULT_DEPTH,\n): TransitiveDependenciesResult {\n  if (!graph.hasNode(nodeId)) {\n    return TransitiveDependenciesResultSchema.parse({\n      origin: nodeId,\n      depth,\n      dependencies: [],\n      total: 0,\n    })\n  }\n\n  interface Frame {\n    nodeId: string\n    distance: number\n    edge: GraphEdge | null\n  }\n\n  const seen = new Map<string, TransitiveDependency>()\n  const queue: Frame[] = [{ nodeId, distance: 0, edge: null }]\n  const enqueued = new Set<string>([nodeId])\n\n  while (queue.length > 0) {\n    const frame = queue.shift()!\n    // Traverse THROUGH CONTAINS to reach a service's file-grained targets, but\n    // never REPORT a CONTAINS edge as a dependency: a service doesn't depend on\n    // its own files (file-awareness §36 refinement, ADR-140). The real target\n    // reached via a genuine dependency edge downstream still surfaces.\n    if (frame.distance > 0 && frame.edge && frame.edge.type !== EdgeType.CONTAINS) {\n      seen.set(frame.nodeId, {\n        nodeId: frame.nodeId,\n        distance: frame.distance,\n        edgeType: frame.edge.type,\n        provenance: frame.edge.provenance,\n      })\n    }\n    if (frame.distance >= depth) continue\n\n    const outgoing = bestEdgeByTarget(graph, graph.outboundEdges(frame.nodeId))\n    for (const [tgtId, edge] of outgoing) {\n      if (enqueued.has(tgtId)) continue\n      enqueued.add(tgtId)\n      queue.push({ nodeId: tgtId, distance: frame.distance + 1, edge })\n    }\n  }\n\n  const dependencies = [...seen.values()].sort(\n    (a, b) => a.distance - b.distance || a.nodeId.localeCompare(b.nodeId),\n  )\n  return TransitiveDependenciesResultSchema.parse({\n    origin: nodeId,\n    depth,\n    dependencies,\n    total: dependencies.length,\n  })\n}\n\n// Observed-only dependencies (issue #578). \"What does this node actually call at\n// runtime?\" — its OBSERVED outbound edges, file-grained.\n//\n// The subtlety the previous edges-only query missed: the call-site processor\n// lands OBSERVED CALLS on the FileNode that made the call, not on the owning\n// ServiceNode (file-awareness §4). So a query that starts at a ServiceNode sees\n// only its structural `CONTAINS` edges and reports \"no runtime traffic,\" while\n// the real dependency sits one hop away on a file it owns. When the origin is a\n// ServiceNode we therefore also read the OBSERVED outbound of the FileNodes it\n// `CONTAINS` and surface those file→target edges. This is not a service rollup\n// (file-awareness §3): the edges stay file-grained with the owning file as the\n// source; the service is only the grouping the query entered through.\n//\n// `observed` and `inboundObservedCount` separate two cases the old copy\n// conflated: a pure receiver — a node runtime hits but which calls nothing\n// downstream — has zero dependencies yet is plainly seen by OTel, so the caller\n// must not ask \"is OTel running?\" at it. That question is honest only when there\n// is no OBSERVED traffic at all and EXTRACTED outbound edges exist\n// (`hasExtractedOutbound`).\nexport function getObservedDependencies(\n  graph: NeatGraph,\n  nodeId: string,\n): ObservedDependenciesResult {\n  if (!graph.hasNode(nodeId)) {\n    return ObservedDependenciesResultSchema.parse({\n      origin: nodeId,\n      dependencies: [],\n      observed: false,\n      inboundObservedCount: 0,\n      hasExtractedOutbound: false,\n      inboundVolume: 0,\n      window: 'lifetime',\n    })\n  }\n\n  const attrs = graph.getNodeAttributes(nodeId) as GraphNode\n\n  // The origin plus, when it's a service, the files it owns — the set of nodes\n  // whose OBSERVED edges belong to \"what this thing does at runtime.\"\n  const scope: string[] = [nodeId]\n  if (attrs.type === NodeType.ServiceNode) {\n    for (const edgeId of graph.outboundEdges(nodeId)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (e.type !== EdgeType.CONTAINS) continue\n      const owned = graph.getNodeAttributes(e.target) as GraphNode\n      if (owned.type === NodeType.FileNode) scope.push(e.target)\n    }\n  }\n\n  const dependencies: GraphEdge[] = []\n  const seenEdge = new Set<string>()\n  let hasExtractedOutbound = false\n  for (const src of scope) {\n    for (const edgeId of graph.outboundEdges(src)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      // CONTAINS is structural ownership, never a runtime dependency. An edge into\n      // the dependency layer (a file importing a package, ADR-274) isn't one of the\n      // system's own dependencies either.\n      if (e.type === EdgeType.CONTAINS || isDependencyNodeId(e.target)) continue\n      if (e.provenance === Provenance.OBSERVED) {\n        if (!seenEdge.has(e.id)) {\n          seenEdge.add(e.id)\n          dependencies.push(e)\n        }\n      } else if (e.provenance === Provenance.EXTRACTED) {\n        hasExtractedOutbound = true\n      }\n    }\n  }\n\n  // Was this node (or a file it owns) seen receiving traffic? Counting OBSERVED\n  // inbound edges is the pure-receiver signal — the \"hit N times, calls nothing\"\n  // shape that must read differently from \"never observed.\" Alongside the count,\n  // the node-level inbound block (ADR-190): inboundVolume sums those edges' call\n  // counts (how hard production hits this node — distinct from the edge count),\n  // and inboundLastObserved is the most-recent inbound observation (when it was\n  // last hit), raw, so a consumer formats recency itself.\n  let inboundObservedCount = 0\n  let inboundVolume = 0\n  let inboundLastObserved: string | undefined\n  for (const tgt of scope) {\n    for (const edgeId of graph.inboundEdges(tgt)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (e.type === EdgeType.CONTAINS) continue\n      if (e.provenance === Provenance.OBSERVED) {\n        inboundObservedCount += 1\n        inboundVolume += e.callCount ?? e.signal?.spanCount ?? 1\n        if (e.lastObserved && (!inboundLastObserved || e.lastObserved > inboundLastObserved)) {\n          inboundLastObserved = e.lastObserved\n        }\n      }\n    }\n  }\n\n  dependencies.sort(\n    (a, b) =>\n      a.target.localeCompare(b.target) ||\n      a.source.localeCompare(b.source) ||\n      a.id.localeCompare(b.id),\n  )\n\n  return ObservedDependenciesResultSchema.parse({\n    origin: nodeId,\n    dependencies,\n    observed: dependencies.length > 0 || inboundObservedCount > 0,\n    inboundObservedCount,\n    hasExtractedOutbound,\n    // The signal is cumulative, so the honest window label is \"lifetime\" (ADR-190).\n    inboundVolume,\n    window: 'lifetime',\n    ...(inboundLastObserved ? { inboundLastObserved } : {}),\n  })\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Agent-driven navigation (ADR-189): Expand, Relate, per-node classification, and\n// the candidate set that turns getRootCause from one verdict into navigation.\n// Composes the traversal primitives above — no new engine. Branches only on\n// node.type / edge.type / provenance / signal, never a provider, platform,\n// framework, or language name (traversal.md agnosticity invariant).\n// ─────────────────────────────────────────────────────────────────────────────\n\n// A node's outbound p95 counts as saturated above this absolute latency. Absolute,\n// not baseline-relative — matching how the signal is read (ADR-190) and how\n// PRAXIS's classifier consumes pre-thresholded alerts. A hardcoded contract\n// constant like ROOT_CAUSE_MAX_DEPTH.\nconst SATURATION_P95_MS = 1000\n\n// The node plus, when it is a service, the files it owns — the set whose edges\n// belong to \"what this thing does at runtime\" (the scope getObservedDependencies\n// walks). A service's runtime signal lands on its files (file-awareness.md §4).\nfunction nodeScope(graph: NeatGraph, nodeId: string): string[] {\n  const scope = [nodeId]\n  if (!graph.hasNode(nodeId)) return scope\n  const attrs = graph.getNodeAttributes(nodeId) as GraphNode\n  if (attrs.type === NodeType.ServiceNode) {\n    for (const edgeId of graph.outboundEdges(nodeId)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (e.type !== EdgeType.CONTAINS) continue\n      const owned = graph.getNodeAttributes(e.target) as GraphNode\n      if (owned.type === NodeType.FileNode) scope.push(e.target)\n    }\n  }\n  return scope\n}\n\n// How many recorded incidents localize to this node — errors emitted here.\nfunction incidentCountForNode(nodeId: string, incidents: ErrorEvent[] | undefined): number {\n  if (!incidents || incidents.length === 0) return 0\n  return incidents.filter((ev) => incidentMatchesNode(ev, nodeId)).length\n}\n\n// #1114 — the dependency edge types that count as a node's real outbound deps.\n// Mirrors the monitor's OBSERVED_DEP_EDGE_TYPES: CALLS + the connection/queue\n// families. CONTAINS ownership is not a dependency.\n// A call-time test, not a module-level set (see isServedSurface).\nfunction isDepEdgeType(type: string): boolean {\n  return (\n    type === EdgeType.CALLS ||\n    type === EdgeType.CONNECTS_TO ||\n    type === EdgeType.PUBLISHES_TO ||\n    type === EdgeType.CONSUMES_FROM\n  )\n}\n\n// #1114 — is this incident a gateway/TIMEOUT-class failure, the observable\n// shadow of a downstream that hung and exported nothing? A 504 gateway timeout,\n// a gRPC DEADLINE_EXCEEDED, an ETIMEDOUT / \"timed out\". Mirrors ADR-220's\n// deadline-exceeded/timeout families (kept local to avoid a divergences↔traverse\n// import cycle) and deliberately EXCLUDES the fast-fails (UNAVAILABLE /\n// ECONNREFUSED / other 5xx) that export an erroring edge NEAT can root-cause.\nconst TIMEOUT_ERROR_PATTERNS: readonly RegExp[] = [\n  /\\bDEADLINE_EXCEEDED\\b/i,\n  /\\bdeadline exceeded\\b/i,\n  /\\bETIMEDOUT\\b/i,\n  /\\btimed[\\s-]?out\\b/i,\n  /\\btimeout\\b/i,\n]\nfunction isBoundaryTimeoutError(ev: ErrorEvent): boolean {\n  if (ev.httpStatusCode === 504) return true\n  const haystack = [ev.errorType, ev.exceptionType, ev.errorMessage]\n    .filter((s): s is string => typeof s === 'string')\n    .join(' \\n ')\n  return TIMEOUT_ERROR_PATTERNS.some((re) => re.test(haystack))\n}\n\n// The separated classification inputs for a node (ADR-189). Reads real edge +\n// incident signal only — nothing synthesized (file-awareness.md §6).\nexport function nodeContext(\n  graph: NeatGraph,\n  nodeId: string,\n  incidents?: ErrorEvent[],\n  now = Date.now(),\n): NodeContext {\n  const scope = nodeScope(graph, nodeId)\n  let errorsFromCallers = 0\n  let inboundVolume = 0\n  let outboundVolume = 0\n  let outboundErrors = 0\n  let latestInboundMs: number | undefined\n  let latencyP95Ms: number | undefined\n  let servedLatencyP95Ms: number | undefined\n  let stale = false\n  let observedErroringDownstream = false\n  let hasOutboundDeps = false\n\n  for (const n of scope) {\n    if (!graph.hasNode(n)) continue\n    for (const edgeId of graph.inboundEdges(n)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (e.type === EdgeType.CONTAINS) continue\n      // A FRONTIER edge is a staged surface, not settled signal (ADR-226): it\n      // carries no observed traffic and must not feed classification context.\n      if (isFrontierEdge(e)) continue\n      // Nor does the dependency layer (ADR-274): a package's code is answered by\n      // the security card, and classification reads the same without it.\n      if (isDependencyNodeId(e.source)) continue\n      errorsFromCallers += e.signal?.errorCount ?? 0\n      inboundVolume += e.callCount ?? e.signal?.spanCount ?? 0\n      if (e.provenance === Provenance.STALE) stale = true\n      const p95 = e.signal?.latencyMs?.p95\n      if (p95 !== undefined) latencyP95Ms = Math.max(latencyP95Ms ?? 0, p95)\n      if (e.lastObserved) {\n        const t = Date.parse(e.lastObserved)\n        if (Number.isFinite(t)) latestInboundMs = Math.max(latestInboundMs ?? 0, t)\n      }\n    }\n    for (const edgeId of graph.outboundEdges(n)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (e.type === EdgeType.CONTAINS) {\n        // What the node itself served, read off its own server spans (ADR-264).\n        if (\n          e.provenance === Provenance.OBSERVED &&\n          (e.signal?.spanCount ?? 0) > 0 &&\n          graph.hasNode(e.target) &&\n          isServedSurface((graph.getNodeAttributes(e.target) as GraphNode).type)\n        ) {\n          const p95 = e.signal?.latencyMs?.p95\n          if (p95 !== undefined) servedLatencyP95Ms = Math.max(servedLatencyP95Ms ?? 0, p95)\n        }\n        continue\n      }\n      if (isFrontierEdge(e)) continue\n      if (isDependencyNodeId(e.target)) continue\n      outboundVolume += e.callCount ?? e.signal?.spanCount ?? 0\n      if (e.type === EdgeType.CALLS) outboundErrors += e.signal?.errorCount ?? 0\n      if (e.provenance === Provenance.STALE) stale = true\n      if (isDepEdgeType(e.type)) {\n        hasOutboundDeps = true\n        if ((e.signal?.errorCount ?? 0) > 0) observedErroringDownstream = true\n      }\n    }\n  }\n\n  const errorsEmittedHere = incidentCountForNode(nodeId, incidents) + outboundErrors\n  const lastObservedAgeMs =\n    latestInboundMs !== undefined ? Math.max(0, now - latestInboundMs) : undefined\n  const boundaryTimeout = (incidents ?? []).some(\n    (ev) => incidentMatchesNode(ev, nodeId) && isBoundaryTimeoutError(ev),\n  )\n\n  return {\n    errorsEmittedHere,\n    errorsFromCallers,\n    callCount: inboundVolume,\n    outboundVolume,\n    ...(lastObservedAgeMs !== undefined ? { lastObservedAgeMs } : {}),\n    ...(latencyP95Ms !== undefined ? { latencyP95Ms } : {}),\n    ...(servedLatencyP95Ms !== undefined ? { servedLatencyP95Ms } : {}),\n    stale,\n    boundaryTimeout,\n    observedErroringDownstream,\n    hasOutboundDeps,\n  }\n}\n\nfunction isSaturated(ctx: NodeContext): boolean {\n  return ctx.latencyP95Ms !== undefined && ctx.latencyP95Ms >= SATURATION_P95_MS\n}\n\n// #1114 — a boundary timeout is the observable shadow of an unobservable\n// downstream: a symptom, not the fault. It emits a timeout-class error, fronts a\n// downstream (has outbound deps), no caller is erroring into it, and — the\n// load-bearing guard — nothing it can see downstream is erroring. A fast-fail\n// (scaled-to-0 UNAVAILABLE, ECONNREFUSED) exports an erroring edge, so\n// `observedErroringDownstream` is true there and this does NOT fire — the\n// existing walk keeps root-causing the real culprit. A hang exports nothing, so\n// there is no erroring downstream edge and the boundary 504 is the only signal.\nexport function isBoundaryTimeoutSymptom(ctx: NodeContext): boolean {\n  return (\n    ctx.errorsEmittedHere > 0 &&\n    ctx.boundaryTimeout === true &&\n    ctx.errorsFromCallers === 0 &&\n    ctx.hasOutboundDeps === true &&\n    ctx.observedErroringDownstream !== true\n  )\n}\n\n// #1123 — the \"unreachable\" shape: a node that RECEIVED calls which predominantly\n// failed but produced NO telemetry of its own — no incidents, no outbound calls.\n// It never served: the requests never reached a running handler (a startup\n// failure, a crash before the first span, an unschedulable / unhealthy pod). Its\n// failure is real and OBSERVED (the erroring inbound edges), but the CAUSE is not\n// in the trace, so it must be named honestly (\"unreachable, cause unobserved\")\n// rather than as a primary-failure that invites an agent to hunt a nonexistent\n// code fault. A node that actually ran leaves a trace — an own incident, or an\n// outbound call of its own — so `errorsEmittedHere === 0 && outboundVolume === 0`\n// is what separates \"never served\" from \"served and failed\".\nconst UNREACHABLE_INBOUND_ERROR_RATE = 0.5\nconst UNREACHABLE_MIN_INBOUND = 3\nfunction isUnreachableSeed(ctx: NodeContext): boolean {\n  return (\n    ctx.callCount >= UNREACHABLE_MIN_INBOUND &&\n    ctx.errorsFromCallers > 0 &&\n    ctx.errorsFromCallers >= UNREACHABLE_INBOUND_ERROR_RATE * ctx.callCount &&\n    ctx.errorsEmittedHere === 0 &&\n    ctx.outboundVolume === 0\n  )\n}\n\n// ADR-264 / #1481 — the failure is on the way to the node, not in it and not load.\n// Its callers see it saturated (their p95, timeouts included, at the saturation\n// bar) and their calls fail, yet what does reach it is served fast and it reports\n// no error of its own. A drowning node is slow at its own handler; this one isn't,\n// so the time is spent before its handler: a Service routing traffic nowhere, a\n// network policy, a partition, a delayed network path. Read only when the node\n// has served spans of its own; without them the inbound view is all there is.\nfunction isPathFault(ctx: NodeContext): boolean {\n  return (\n    ctx.errorsEmittedHere === 0 &&\n    ctx.errorsFromCallers > 0 &&\n    isSaturated(ctx) &&\n    ctx.servedLatencyP95Ms !== undefined &&\n    ctx.servedLatencyP95Ms < SATURATION_P95_MS\n  )\n}\n\n// Classify a node from its separated context (ADR-189). A node that emits errors\n// of its own is a primary-failure — unless it is stale/saturated and absorbs at\n// least as much failure as it emits, i.e. it is drowning in load, a symptom; or\n// it is a boundary timing out on an unobservable downstream (#1114). A node with\n// errors arriving but none emitted is a downstream symptom. No signal → unrelated.\nexport function classifyNode(ctx: NodeContext): NodeClassification {\n  if (ctx.errorsEmittedHere > 0) {\n    if ((ctx.stale || isSaturated(ctx)) && ctx.errorsFromCallers >= ctx.errorsEmittedHere) {\n      return 'symptom-only'\n    }\n    if (isBoundaryTimeoutSymptom(ctx)) return 'symptom-only'\n    return 'primary-failure'\n  }\n  // #1123 — received failing calls but produced nothing of its own: never served.\n  if (isUnreachableSeed(ctx)) return 'unreachable'\n  // ADR-264 — callers time out on it while it serves fast: unreachable in part.\n  if (isPathFault(ctx)) return 'unreachable'\n  if (ctx.errorsFromCallers > 0) return 'symptom-only'\n  return 'unrelated'\n}\n\n// The seed is a saturated/stale victim — a starved downstream node the load hit,\n// not the fault. When it is, navigation walks up to the load origin instead of\n// naming it (ADR-189): errors arrive, the node emits no more than it receives,\n// and it has gone stale or saturated.\nfunction isVictimSeed(ctx: NodeContext): boolean {\n  return (\n    !isPathFault(ctx) &&\n    ctx.errorsFromCallers > 0 &&\n    (ctx.stale || isSaturated(ctx)) &&\n    ctx.errorsEmittedHere <= ctx.errorsFromCallers\n  )\n}\n\n// Generic connection-failure phrases that mark a node's failure as an outbound\n// one in its own incident text — a name-resolution failure, a refused or reset\n// connection, an \"unable to connect\", a lookup that never resolved. These are\n// error *semantics*, never provider or datastore names: the reasoning core never\n// learns what any particular data store is (traversal.md agnosticity), only that\n// the node reported it could not reach something downstream. Matched\n// case-insensitively against the incident's message / type / stacktrace.\nconst OUTBOUND_CONNECTION_FAILURE_PATTERNS = [\n  'name resolution',\n  'resolve host',\n  'getaddrinfo',\n  'enotfound',\n  'connection refused',\n  'econnrefused',\n  'connection reset',\n  'econnreset',\n  'able to connect',\n  'failed to connect',\n  'cannot connect',\n  'could not connect',\n  'unable to connect',\n  'connection timed out',\n  'etimedout',\n  'no route to host',\n  'host unreachable',\n  'network is unreachable',\n  'connection closed',\n]\n\n// Does this incident's own error text read as a failure to reach an outbound\n// dependency (a datastore connection, a name lookup, a downstream call) rather\n// than an in-process throw? The fallback signal when the outbound edge carries\n// no error count of its own — the connection died before a span could record it,\n// so the edge looks clean while the incident holds the real story.\nfunction incidentTextIndicatesOutboundFailure(ev: ErrorEvent): boolean {\n  const haystack = [ev.errorMessage, ev.errorType, ev.exceptionType, ev.exceptionStacktrace]\n    .filter((s): s is string => typeof s === 'string')\n    .join(' ')\n    .toLowerCase()\n  return OUTBOUND_CONNECTION_FAILURE_PATTERNS.some((p) => haystack.includes(p))\n}\n\n// Does the node fail because of its OWN outbound dependency rather than the load\n// hitting it? A downstream edge that recorded errors — a CALLS to another service\n// OR a CONNECTS_TO a datastore — means the fault originates in a dependency this\n// node drives, so the victim → load-origin move must not bury it behind the\n// traffic source (#1075). Scans every outbound edge type, not just CALLS:\n// isFailingCallEdge is CALLS-only, so a datastore auth/connection failure riding\n// a CONNECTS_TO edge would otherwise be invisible to the victim gate. When the\n// seed came from the incident store and carries no failing outbound edge (the\n// connection died before a span landed), its error text is the fallback signal —\n// an outbound connection failure in the message counts the same as a failing edge.\nfunction hasFailingOutbound(\n  graph: NeatGraph,\n  nodeId: string,\n  seedSource: LegacyCauseSource,\n  incidents: ErrorEvent[] | undefined,\n): boolean {\n  for (const n of nodeScope(graph, nodeId)) {\n    if (!graph.hasNode(n)) continue\n    for (const edgeId of graph.outboundEdges(n)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (e.type === EdgeType.CONTAINS) continue\n      if ((e.signal?.errorCount ?? 0) > 0) return true\n    }\n  }\n  if (seedSource === 'incident' && incidents) {\n    for (const ev of incidents) {\n      if (incidentMatchesNode(ev, nodeId) && incidentTextIndicatesOutboundFailure(ev)) return true\n    }\n  }\n  return false\n}\n\n// The node's own deploy fault, read off its OBSERVED deploy context (ADR-243,\n// #1400). A workload that dies at startup on a bad config exits before it opens a\n// single connection, so it leaves no failing outbound edge and no outbound-failure\n// text: its callers hold the connection-refused, and by its inbound signal alone it\n// reads as a starved victim. The deploy context is the one place its own failure\n// shows. It counts as the node's own fault when the image never pulled, or when the\n// process exited non-zero on its own (exit 1..127). A process killed by a signal\n// (exit 128+: out of memory, a failed liveness probe, an eviction) may have been\n// killed by the load itself, so it is left to the victim gate, as is a fault with\n// no pod-level cause. The context counts only while the incident it was observed\n// with is on record for the node.\nfunction ownDeployFault(\n  graph: NeatGraph,\n  nodeId: string,\n  incidents: ErrorEvent[] | undefined,\n): DeployContext | null {\n  if (!graph.hasNode(nodeId)) return null\n  const parsed = ObservedDeployContextSchema.safeParse(\n    (graph.getNodeAttributes(nodeId) as { observedDeployContext?: unknown }).observedDeployContext,\n  )\n  if (!parsed.success) return null\n  const { incidentId, observedAt: _observedAt, ...ctx } = parsed.data\n  if (incidents && !incidents.some((ev) => ev.id === incidentId && incidentMatchesNode(ev, nodeId))) {\n    return null\n  }\n  if (ctx.fault === 'image-pull') return ctx\n  if (ctx.exitCode !== undefined) return ctx.exitCode >= 1 && ctx.exitCode <= 127 ? ctx : null\n  return ctx.fault === 'crash-loop' ? ctx : null\n}\n\n// One phrase for a deploy fault inside a reason sentence.\nfunction deployFaultPhrase(ctx: DeployContext): string {\n  const bits: string[] = []\n  if (ctx.waitingReason) bits.push(ctx.waitingReason)\n  if (ctx.restartCount !== undefined) bits.push(`restarts ${ctx.restartCount}`)\n  if (ctx.exitCode !== undefined) bits.push(`last exit ${ctx.exitCode}`)\n  if (ctx.terminatedReason) bits.push(ctx.terminatedReason)\n  const fault = ctx.fault ?? 'deploy fault'\n  return bits.length > 0 ? `${fault} (${bits.join(', ')})` : fault\n}\n\n// What the seed's fused process log says about its own deploy fault (ADR-262): the\n// first error line, and the dependency it names. Candidates are bounded to the\n// seed's own outbound dependencies (its service and the files it owns), so the log\n// can only point at something the graph already has the seed reaching, never at the\n// seed and never at an unrelated node that happens to share a word with the line.\ninterface LogCause {\n  error: LogErrorLine\n  named: NamedDependency | null\n}\n\nfunction isLogDepEdgeType(type: string): boolean {\n  return isDepEdgeType(type) || type === EdgeType.DEPENDS_ON\n}\n\nfunction logDependencyRank(type: string): number {\n  if (type === NodeType.DatabaseNode) return 0\n  if (type === NodeType.ServiceNode) return 1\n  if (type === NodeType.InfraNode) return 2\n  return 3\n}\n\nfunction logDependencyCandidates(graph: NeatGraph, seedNode: string): DependencyCandidate[] {\n  const scope = new Set(nodeScope(graph, seedNode))\n  const seedName = displayNameOf(seedNode).toLowerCase()\n  const out = new Map<string, DependencyCandidate>()\n  for (const n of scope) {\n    if (!graph.hasNode(n)) continue\n    for (const edgeId of graph.outboundEdges(n)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (!isLogDepEdgeType(e.type) || isFrontierEdge(e)) continue\n      if (scope.has(e.target) || out.has(e.target) || isFrontierNode(graph, e.target)) continue\n      const a = graph.getNodeAttributes(e.target) as GraphNode & { name?: unknown; host?: unknown; aliases?: unknown }\n      // A name the seed itself goes by (`geo` for service:geo) says nothing about\n      // which dependency the line means.\n      const names = [a.name, a.host, ...(Array.isArray(a.aliases) ? a.aliases : [])].filter(\n        (v): v is string => typeof v === 'string' && v.toLowerCase() !== seedName,\n      )\n      out.set(e.target, { id: e.target, names, rank: logDependencyRank(a.type) })\n    }\n  }\n  return [...out.values()]\n}\n\nfunction logCause(graph: NeatGraph, seedNode: string, ctx: DeployContext): LogCause | null {\n  if (!ctx.processLog) return null\n  const error = firstErrorLine(ctx.processLog)\n  if (!error) return null\n  return { error, named: dependencyNamedInLog(ctx.processLog, error, logDependencyCandidates(graph, seedNode)) }\n}\n\n// The grain of a node, for a Relate path annotation.\nfunction grainOf(graph: NeatGraph, nodeId: string): string {\n  if (!graph.hasNode(nodeId)) return 'unknown'\n  const t = (graph.getNodeAttributes(nodeId) as GraphNode).type\n  if (t === NodeType.ServiceNode) return 'service'\n  if (t === NodeType.FileNode) return 'file'\n  if (t === NodeType.SymbolNode) return 'symbol'\n  return t\n}\n\ninterface FoundPath {\n  nodes: string[]\n  edges: GraphEdge[]\n}\n\n// Shortest directed path from `from` to `to`, depth-bounded, in one direction.\n// 'up' walks inbound (bestEdgeBySource — callers/dependents), 'down' walks\n// outbound (bestEdgeByTarget — callees/dependencies): the same PROV_RANK-best,\n// FRONTIER-terminating primitives the rest of traversal uses, deterministic in\n// neighbour order. Returns null when `to` is unreachable within maxDepth — a\n// depth-bounded absence, honestly.\nfunction findPath(\n  graph: NeatGraph,\n  from: string,\n  to: string,\n  direction: 'up' | 'down',\n  maxDepth: number,\n): FoundPath | null {\n  if (!graph.hasNode(from) || !graph.hasNode(to)) return null\n  if (from === to) return { nodes: [from], edges: [] }\n\n  interface Frame {\n    nodeId: string\n    depth: number\n    nodes: string[]\n    edges: GraphEdge[]\n  }\n  const queue: Frame[] = [{ nodeId: from, depth: 0, nodes: [from], edges: [] }]\n  const enqueued = new Set<string>([from])\n\n  while (queue.length > 0) {\n    const frame = queue.shift()!\n    if (frame.depth >= maxDepth) continue\n    const best =\n      direction === 'up'\n        ? bestEdgeBySource(graph, graph.inboundEdges(frame.nodeId))\n        : bestEdgeByTarget(graph, graph.outboundEdges(frame.nodeId))\n    const neighbours = [...best.entries()].sort((a, b) => a[0].localeCompare(b[0]))\n    for (const [nid, edge] of neighbours) {\n      if (nid === to) return { nodes: [...frame.nodes, nid], edges: [...frame.edges, edge] }\n      if (enqueued.has(nid)) continue\n      enqueued.add(nid)\n      queue.push({\n        nodeId: nid,\n        depth: frame.depth + 1,\n        nodes: [...frame.nodes, nid],\n        edges: [...frame.edges, edge],\n      })\n    }\n  }\n  return null\n}\n\nconst EMPTY_CONTEXT: NodeContext = {\n  errorsEmittedHere: 0,\n  errorsFromCallers: 0,\n  callCount: 0,\n  outboundVolume: 0,\n  stale: false,\n}\n\n// Expand(node, up | down) — one bidirectional neighbourhood step (ADR-189).\n// `up` = inbound (callers/dependents), `down` = outbound (callees/dependencies).\n// Returns the stepped node's own classification + context and its immediate\n// runtime neighbours', so a caller navigates one legible hop at a time.\nexport function expandNode(\n  graph: NeatGraph,\n  nodeId: string,\n  direction: 'up' | 'down',\n  incidents?: ErrorEvent[],\n  now = Date.now(),\n): ExpandResult {\n  if (!graph.hasNode(nodeId)) {\n    return ExpandResultSchema.parse({\n      origin: nodeId,\n      direction,\n      node: { id: nodeId, classification: 'unrelated', context: EMPTY_CONTEXT },\n      neighbours: [],\n    })\n  }\n  const ctx = nodeContext(graph, nodeId, incidents, now)\n  const best =\n    direction === 'up'\n      ? bestEdgeBySource(graph, graph.inboundEdges(nodeId))\n      : bestEdgeByTarget(graph, graph.outboundEdges(nodeId))\n  const neighbours: ExpandNeighbour[] = []\n  for (const [nid, edge] of best) {\n    // CONTAINS is structural ownership, not a runtime caller/callee.\n    if (edge.type === EdgeType.CONTAINS) continue\n    const nctx = nodeContext(graph, nid, incidents, now)\n    neighbours.push({\n      node: nid,\n      edgeType: edge.type,\n      provenance: edge.provenance,\n      classification: classifyNode(nctx),\n      context: nctx,\n    })\n  }\n  neighbours.sort((a, b) => a.node.localeCompare(b.node))\n  return ExpandResultSchema.parse({\n    origin: nodeId,\n    direction,\n    node: { id: nodeId, classification: classifyNode(ctx), context: ctx },\n    neighbours,\n  })\n}\n\n// Relate(a, b) — pairwise directed link-confirmation (ADR-189). Searches both\n// ways but labels the direction it found, preferring a→b (cause→symptom). Each\n// path carries per-hop provenance + grain and a carriesSignal summary — whether\n// the failure runs end to end. No path within maxDepth → related: false with the\n// honest \"no path within N hops\" note, never \"unrelated.\"\nexport function relate(\n  graph: NeatGraph,\n  a: string,\n  b: string,\n  maxDepth = ROOT_CAUSE_MAX_DEPTH,\n): RelateResult {\n  const buildPath = (fp: FoundPath): RelatePath => ({\n    nodes: fp.nodes,\n    edgeTypes: fp.edges.map((e) => e.type),\n    provenance: fp.edges.map((e) => e.provenance),\n    grain: fp.nodes.map((n) => grainOf(graph, n)),\n    // The failure runs end to end when every hop carries error / latency / alert\n    // signal — that is what turns reachability into cause-confirmation.\n    carriesSignal:\n      fp.edges.length > 0 &&\n      fp.edges.every(\n        (e) =>\n          (e.signal?.errorCount ?? 0) > 0 ||\n          e.signal?.latencyMs !== undefined ||\n          e.signal?.anomalous !== undefined,\n      ),\n  })\n\n  if (!graph.hasNode(a) || !graph.hasNode(b)) {\n    return RelateResultSchema.parse({\n      a,\n      b,\n      related: false,\n      direction: null,\n      paths: [],\n      note: !graph.hasNode(a) ? `node not found: ${a}` : `node not found: ${b}`,\n    })\n  }\n\n  // a→b means a is upstream (its outbound chain reaches b); b→a means b is\n  // upstream (a's inbound chain reaches b).\n  const down = findPath(graph, a, b, 'down', maxDepth)\n  const up = findPath(graph, a, b, 'up', maxDepth)\n\n  if (!down && !up) {\n    return RelateResultSchema.parse({\n      a,\n      b,\n      related: false,\n      direction: null,\n      paths: [],\n      note: `no path within ${maxDepth} hops`,\n    })\n  }\n\n  const paths: RelatePath[] = []\n  const direction: 'a->b' | 'b->a' = down ? 'a->b' : 'b->a'\n  if (down) paths.push(buildPath(down))\n  if (up) paths.push(buildPath(up))\n\n  // Grain gap: a and b are both finer than service, but the connecting path only\n  // links through a service-grain hop — the fine link was never observed, so the\n  // coarser path is returned and the gap flagged (file-awareness.md §6).\n  const endpointsFine = grainOf(graph, a) !== 'service' && grainOf(graph, b) !== 'service'\n  const grainGap = endpointsFine && paths[0]!.grain.some((g) => g === 'service')\n\n  return RelateResultSchema.parse({\n    a,\n    b,\n    related: true,\n    direction,\n    paths,\n    ...(grainGap ? { grainGap: true } : {}),\n  })\n}\n\n// The load origin feeding a saturated/stale subgraph: among the nodes upstream of\n// the alert (its inbound-reachable dependents, the get_blast_radius set), the pure\n// source — nothing observed drives it — that itself drives the most outbound\n// volume. This is the topology move ADR-189 names (\"walk up to the highest-volume\n// feeder\"), selected by graph shape, never by a provider or service name.\nfunction findLoadOrigin(\n  graph: NeatGraph,\n  alertNodeId: string,\n  incidents: ErrorEvent[] | undefined,\n  now: number,\n): LoadOrigin | null {\n  const upstream = getBlastRadius(graph, alertNodeId).affectedNodes.map((n) => n.nodeId)\n  let best: { node: string; ctx: NodeContext; isSource: boolean } | null = null\n  // A traffic source is never the origin (ADR-264): it is the client sending the\n  // load. Kept apart, so the verdict can say the load comes from a client.\n  let client: { node: string; ctx: NodeContext; callees: string[] } | null = null\n  for (const nid of upstream) {\n    if (nid === alertNodeId) continue\n    const ctx = nodeContext(graph, nid, incidents, now)\n    if (ctx.outboundVolume === 0) continue // drives nothing — not a feeder\n    const callees = trafficSourceOf(graph, nid, incidents)\n    if (callees) {\n      if (!client || ctx.outboundVolume > client.ctx.outboundVolume) client = { node: nid, ctx, callees }\n      continue\n    }\n    const isSource = ctx.callCount === 0 // nothing observed calls it — a pure driver\n    const better =\n      !best ||\n      (isSource !== best.isSource\n        ? isSource\n        : ctx.outboundVolume !== best.ctx.outboundVolume\n          ? ctx.outboundVolume > best.ctx.outboundVolume\n          : nid < best.node)\n    if (better) best = { node: nid, ctx, isSource }\n  }\n  // A pure source that is a service drives the load. Failing one, a client does:\n  // the services between it and the victim only relay its traffic, so none of\n  // them is the origin either. Only with no source of either kind does the\n  // highest-volume feeder stand as before.\n  if (best?.isSource) return { kind: 'origin', node: best.node, ctx: best.ctx }\n  if (client) return { kind: 'client', ...client }\n  return best ? { kind: 'origin', node: best.node, ctx: best.ctx } : null\n}\n\n// The client's edge into `target`: straight to it, or to an interface it serves.\nfunction clientEdgeTo(graph: NeatGraph, client: string, target: string): GraphEdge | undefined {\n  let best: GraphEdge | undefined\n  for (const id of graph.outboundEdges(client)) {\n    const e = graph.getEdgeAttributes(id) as GraphEdge\n    const owner = e.target === target ? target : ownerViaContains(graph, e.target)\n    if (owner !== target) continue\n    if (!best || (e.signal?.errorCount ?? 0) > (best.signal?.errorCount ?? 0)) best = e\n  }\n  return best\n}\n\nfunction ownerViaContains(graph: NeatGraph, id: string): string | undefined {\n  if (!graph.hasNode(id)) return undefined\n  for (const eid of graph.inboundEdges(id)) {\n    const e = graph.getEdgeAttributes(eid) as GraphEdge\n    if (e.type === EdgeType.CONTAINS) return e.source\n  }\n  return undefined\n}\n\ntype LoadOrigin =\n  | { kind: 'origin'; node: string; ctx: NodeContext }\n  // Only a traffic source drives the subgraph: the callees its failing calls hit.\n  | { kind: 'client'; node: string; ctx: NodeContext; callees: string[] }\n\n// An OBSERVED-grade ceiling on the promoted load origin's confidence. The cause is\n// inferred from several converging runtime signals rather than one captured\n// incident, so it earns a high but never-certain score — honest for a multi-signal\n// OBSERVED inference, which never claims 1.0.\nconst LOAD_ORIGIN_CONFIDENCE_CEILING = 0.9\n\n// Confidence for the promoted load origin (ADR-189), graded by the strength of the\n// separated evidence the navigation already computed — the ADR-189 classification\n// inputs and the ADR-190 latency signal — rather than a flat floor. Each\n// corroborating signal lifts it toward the OBSERVED ceiling: a clean cause/symptom\n// split (errors arrive from the victim's callers, none originate there), the victim\n// gone STALE under load, its inbound latency saturated, and the volume of load the\n// origin drives. Bounded [0, LOAD_ORIGIN_CONFIDENCE_CEILING].\nfunction loadOriginConfidence(originCtx: NodeContext, seedCtx: NodeContext): number {\n  // The core signal: how cleanly the victim reads as a symptom. Errors arrive from\n  // its callers, and none (a clean split) — or fewer (a partial one) — originate\n  // locally.\n  const cleanSplit = seedCtx.errorsFromCallers > 0 && seedCtx.errorsEmittedHere === 0\n  const partialSplit = seedCtx.errorsFromCallers > seedCtx.errorsEmittedHere\n\n  let evidence = 0\n  evidence += cleanSplit ? 0.45 : partialSplit ? 0.2 : 0\n  evidence += seedCtx.stale ? 0.2 : 0\n  evidence += isSaturated(seedCtx) ? 0.15 : 0\n  // A high-volume driver is a stronger load origin than a trickle. volumeWeight maps\n  // a call/span count into [0.5, 1]; rescale its headroom into [0, 0.2].\n  evidence += (volumeWeight(originCtx.outboundVolume) - 0.5) * 0.4\n\n  // An anchor keeps a single signal from ever reading as certainty; the evidence\n  // then climbs toward the ceiling. isVictimSeed already guarantees real victim\n  // signal (errors from callers, plus STALE or saturation) before we reach here.\n  const anchor = 0.45\n  const confidence = anchor + Math.min(1, evidence) * (LOAD_ORIGIN_CONFIDENCE_CEILING - anchor)\n  return Math.max(0, Math.min(LOAD_ORIGIN_CONFIDENCE_CEILING, confidence))\n}\n\n// Human display name for a node id inside a reason sentence — strips the `type:`\n// prefix the same way the cross-service reason does.\nfunction displayNameOf(nodeId: string): string {\n  return nodeId.replace(/^[a-z]+:/, '')\n}\n\n// getRootCause (ADR-189): navigation over the fused graph. Seeds from the single\n// verdict (legacyRootCause), classifies that seed, and — when the seed is a\n// saturated/stale victim — walks up to the load origin instead of naming the\n// victim. Returns a ranked candidate set with per-node classification + evidence\n// alongside the legacy verdict fields, which stay populated (candidates[0] is the\n// top cause and rootCauseNode tracks it) for one deprecation cycle.\n// NEAT_RCA_NAVIGATION=0 (or opts.navigation === false) returns the pre-navigation\n// single verdict verbatim.\nexport function getRootCause(\n  graph: NeatGraph,\n  errorNodeId: string,\n  errorEvent?: ErrorEvent,\n  incidents?: ErrorEvent[],\n  opts?: { navigation?: boolean; now?: number },\n): RootCauseResult | null {\n  const tagged = legacyRootCause(graph, errorNodeId, errorEvent, incidents)\n  if (!tagged) return null\n  const navigation = opts?.navigation ?? process.env.NEAT_RCA_NAVIGATION !== '0'\n  if (!navigation) return tagged.result\n  return enrichWithNavigation(graph, errorNodeId, tagged, incidents, opts?.now ?? Date.now())\n}\n\n// #1114 — the failing request's route, from the boundary's own incident. Used to\n// narrow the structural walk to the declared edge that serves THAT route, not the\n// boundary's whole fan-out.\nfunction boundaryIncidentRoute(\n  nodeId: string,\n  incidents: ErrorEvent[] | undefined,\n): string | undefined {\n  for (const ev of incidents ?? []) {\n    if (!incidentMatchesNode(ev, nodeId)) continue\n    const r =\n      ev.attributes?.['http.route'] ?? ev.attributes?.['http.target'] ?? ev.attributes?.['url.path']\n    if (typeof r === 'string' && r.length > 0) return r\n  }\n  return undefined\n}\n\n// A node's DECLARED (EXTRACTED) outbound dependency callees, each with the route\n// its declared edge serves when the extractor captured one. Declared, because a\n// hang leaves no observed edge — the declared call graph is the only path left.\nfunction declaredOutboundCallees(\n  graph: NeatGraph,\n  nodeId: string,\n): Array<{ target: string; route?: string }> {\n  const byTarget = new Map<string, { target: string; route?: string }>()\n  for (const n of nodeScope(graph, nodeId)) {\n    if (!graph.hasNode(n)) continue\n    for (const edgeId of graph.outboundEdges(n)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (!isDepEdgeType(e.type)) continue\n      if (e.provenance !== Provenance.EXTRACTED) continue\n      if (e.target === nodeId || byTarget.has(e.target)) continue\n      const route = e.evidence?.pathTemplate\n      byTarget.set(\n        e.target,\n        route !== undefined ? { target: e.target, route } : { target: e.target },\n      )\n    }\n  }\n  return [...byTarget.values()]\n}\n\nfunction normalizeRoute(s: string): string {\n  return s.replace(/\\/+$/, '').toLowerCase()\n}\nfunction routeMatches(declared: string, incident: string): boolean {\n  const a = normalizeRoute(declared)\n  const b = normalizeRoute(incident)\n  return a === b || a.startsWith(b) || b.startsWith(a)\n}\n\n// The single declared (EXTRACTED) callee a node serves for a route, or null when\n// the route doesn't narrow to one (or the node declares nothing). The first\n// unobservable hop on the declared serving path.\nfunction firstDeclaredCallee(\n  graph: NeatGraph,\n  node: string,\n  route: string | undefined,\n): string | null {\n  const callees = declaredOutboundCallees(graph, node)\n  if (callees.length === 0) return null\n  const narrowed =\n    route !== undefined\n      ? callees.filter((c) => c.route !== undefined && routeMatches(c.route, route))\n      : callees\n  const chosen = narrowed.length === 1 ? narrowed[0]! : callees.length === 1 ? callees[0]! : null\n  return chosen ? chosen.target : null\n}\n\n// The OBSERVED outbound next-services of a node (the runtime dependency families,\n// not CONTAINS). Used to cross ONE observed hop when an infra boundary declares\n// nothing for the failing route — the observed layer reached the next service even\n// though the hung culprit beyond it exported no span.\nfunction observedOutboundNextServices(graph: NeatGraph, nodeId: string): string[] {\n  const targets = new Set<string>()\n  for (const n of nodeScope(graph, nodeId)) {\n    if (!graph.hasNode(n)) continue\n    for (const edgeId of graph.outboundEdges(n)) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (!isDepEdgeType(e.type)) continue\n      if (e.provenance !== Provenance.OBSERVED) continue\n      if (e.target !== nodeId) targets.add(e.target)\n    }\n  }\n  return [...targets]\n}\n\n// #1114b / ADR-226 — the unobservable hop the hang sensor stages a FRONTIER surface\n// on: the edge NEAT reached toward but cannot see because its far end hung. Route-\n// driven — resolve the failing route (from the boundary's incident) against the\n// boundary's OWN declared callees; when the boundary declares nothing for that\n// route (an infra proxy like frontend-proxy), cross ONE observed hop into the next\n// service and resolve there. The crossing is taken only when exactly one observed\n// next-service yields a resolving declared callee — never a fan-out, never an\n// observed healthy branch mistaken for the hang path. Returns the hop\n// `{ source, target }` to stage, or null (honest-coarse — propose nothing).\nexport function resolveHangHop(\n  graph: NeatGraph,\n  boundaryNode: string,\n  incidents: ErrorEvent[] | undefined,\n): { source: string; target: string; route?: string } | null {\n  const route = boundaryIncidentRoute(boundaryNode, incidents)\n  // 1) the boundary's own declared first callee.\n  const own = firstDeclaredCallee(graph, boundaryNode, route)\n  if (own) {\n    return route !== undefined\n      ? { source: boundaryNode, target: own, route }\n      : { source: boundaryNode, target: own }\n  }\n  // 2) cross one observed hop; resolve the route at the single observed next-service.\n  const resolved = observedOutboundNextServices(graph, boundaryNode)\n    .map((n) => ({ source: n, target: firstDeclaredCallee(graph, n, route) }))\n    .filter((r): r is { source: string; target: string } => r.target !== null)\n  if (resolved.length === 1) {\n    const hop = resolved[0]!\n    return route !== undefined ? { ...hop, route } : hop\n  }\n  return null\n}\n\n// ADR-226 — read the staged FRONTIER surface for a boundary-timeout hang: the hop\n// the sensor staged (hang-sensor.ts), located by the same resolver and confirmed to\n// exist as a FRONTIER edge in the graph. Returns the proposed culprit (the surface's\n// target) + route, or null when no surface is staged — honest-coarse (the sensor\n// hasn't seen this hang yet, or nothing resolved). The reader reads the surface; it\n// does not re-invent a cause the graph does not carry.\nfunction stagedHangProposal(\n  graph: NeatGraph,\n  boundaryNode: string,\n  incidents: ErrorEvent[] | undefined,\n): { node: string; route?: string } | null {\n  const hop = resolveHangHop(graph, boundaryNode, incidents)\n  if (!hop) return null\n  if (!graph.hasEdge(frontierEdgeId(hop.source, hop.target, EdgeType.CALLS))) return null\n  return hop.route !== undefined ? { node: hop.target, route: hop.route } : { node: hop.target }\n}\n\nfunction enrichWithNavigation(\n  graph: NeatGraph,\n  errorNodeId: string,\n  tagged: TaggedRootCause,\n  incidents: ErrorEvent[] | undefined,\n  now: number,\n): RootCauseResult {\n  const legacy = tagged.result\n  const seedNode = legacy.rootCauseNode\n  const seedCtx = graph.hasNode(seedNode) ? nodeContext(graph, seedNode, incidents, now) : null\n  const lastProv = legacy.edgeProvenances[legacy.edgeProvenances.length - 1]\n  const candidates: RootCauseCandidate[] = []\n\n  // The dead-end the STALE-chain fallback exists to fix (ADR-209): the single\n  // verdict localized the failure to the queried node itself (`source === 'incident'`,\n  // no causal edge walked), yet a STALE-only outbound CALLS chain runs downstream —\n  // the topology is still in the graph, only its live signal went quiet. Walking\n  // nothing and naming the queried node hands the agent the symptom. `isVictimSeed`\n  // (errors arriving) takes precedence; a compat / cross-service seed is never\n  // second-guessed; a genuinely isolated node (no stale chain) stays primary-failure.\n  const deadEndOnSymptom =\n    tagged.source === 'incident' &&\n    seedNode === errorNodeId &&\n    legacy.traversalPath.length === 1\n  const staleChain =\n    deadEndOnSymptom && !(seedCtx && isVictimSeed(seedCtx))\n      ? followStaleCallChain(graph, errorNodeId, ROOT_CAUSE_MAX_DEPTH)\n      : null\n\n  // The seed reads as a saturated/stale victim by its inbound signal alone, but\n  // that gate never looks downstream (#1075). Before demoting it to a symptom and\n  // promoting the load origin, check whether the seed genuinely fails because of\n  // its OWN outbound dependency — a failing CONNECTS_TO datastore, a failing\n  // downstream call, or an incident whose text is an outbound connection failure.\n  // When it does, the load-origin verdict would bury the real cause behind the\n  // traffic source, so keep the seed. We check the seed, not the queried node: in\n  // a genuine cross-service overload the queried entry relays load down a failing\n  // CALLS chain to the starved victim, so its own outbound is failing by design —\n  // it is the seed (the victim itself) that must have no downstream fault for the\n  // load-origin move to be right. A deploy fault of the seed's own (#1400) counts\n  // the same: a workload that crashed at startup never reached its dependencies,\n  // so its deploy context is the only place its own failure shows.\n  const seedDeployFault = seedCtx !== null ? ownDeployFault(graph, seedNode, incidents) : null\n  const seedLogCause = seedDeployFault ? logCause(graph, seedNode, seedDeployFault) : null\n  // Set when only a client drives the subgraph (ADR-264): the fix names what its\n  // calls fail against.\n  let clientFix: string | undefined\n  const seedFailsOutbound =\n    seedCtx !== null &&\n    (seedDeployFault !== null || hasFailingOutbound(graph, seedNode, tagged.source, incidents))\n\n  if (seedCtx && isVictimSeed(seedCtx) && !seedFailsOutbound) {\n    // The seed is a starved/saturated downstream victim — do not name it. Walk up\n    // to the load origin and lead with that.\n    const origin = findLoadOrigin(graph, errorNodeId, incidents, now)\n    const staleNote = seedCtx.stale ? '; it has gone STALE under load' : ''\n    const satNote = isSaturated(seedCtx)\n      ? `; its inbound p95 ${Math.round(seedCtx.latencyP95Ms!)}ms is saturated`\n      : ''\n    if (origin?.kind === 'client') {\n      // Only a client drives this subgraph (ADR-264): it is the traffic, never the\n      // origin. Point at what its failing calls hit: the seed when the client calls\n      // it, else the callee it fails against most, with the error it gets back.\n      const clientName = displayNameOf(origin.node)\n      const target = origin.callees.includes(seedNode) ? seedNode : (origin.callees[0] ?? seedNode)\n      const targetName = displayNameOf(target)\n      const edge = clientEdgeTo(graph, origin.node, target)\n      const errs = edge?.signal?.errorCount ?? 0\n      const last = edge?.signal?.lastError?.message\n      const lastNote = last ? `, latest: ${last.replace(/\\s+/g, ' ').slice(0, 200)}` : ''\n      clientFix = `Check why ${targetName} fails ${clientName}'s calls${lastNote ? ` (${lastNote.slice(2)})` : ''}. ${clientName} is a client sending traffic, not the fault; throttling it would only hide the failure.`\n      candidates.push({\n        node: target,\n        classification: 'primary-failure',\n        reason: `No service drives this load: it comes from a client, ${clientName} (${origin.ctx.outboundVolume} observed outbound calls), and ${clientName}'s calls fail against ${targetName} (${errs} error${errs === 1 ? '' : 's'}${lastNote}). A client is the traffic, not the fault; look at why ${targetName} fails those calls.`,\n        context: target === seedNode ? seedCtx : nodeContext(graph, target, incidents, now),\n        confidence: Math.min(legacy.confidence, 0.4),\n        provenance: Provenance.OBSERVED,\n      })\n    } else if (origin) {\n      // Lead the headline reason with the causal relation, not the raw call count:\n      // the named origin is the fault *because* it overloads the subgraph, and the\n      // alerting node is its downstream symptom (errors arrive from callers, none\n      // originate there). The volume is corroborating evidence, so it comes last.\n      const originName = displayNameOf(origin.node)\n      const seedName = displayNameOf(seedNode)\n      candidates.push({\n        node: origin.node,\n        classification: 'primary-failure',\n        reason: `${originName} is the root cause: it overloads the failing subgraph, and the alerting node ${seedName} is a downstream symptom, not the fault — errors reach ${seedName} from its callers (${seedCtx.errorsFromCallers}), none originate there${staleNote}${satNote}. ${originName} is the upstream source driving that load (${origin.ctx.outboundVolume} observed outbound calls).`,\n        context: origin.ctx,\n        confidence: loadOriginConfidence(origin.ctx, seedCtx),\n        provenance: Provenance.OBSERVED,\n      })\n    }\n    if (!(origin?.kind === 'client' && candidates[0]?.node === seedNode)) candidates.push({\n      node: seedNode,\n      classification: 'symptom-only',\n      reason: `Errors arrive from callers (${seedCtx.errorsFromCallers}) but none originate here${staleNote}${satNote} — a downstream victim of load, not the fault.`,\n      context: seedCtx,\n      confidence: Math.min(legacy.confidence, 0.4),\n      ...(lastProv ? { provenance: lastProv } : {}),\n    })\n  } else if (seedCtx && isUnreachableSeed(seedCtx)) {\n    // #1123 — the seed is a target that received calls which predominantly failed\n    // but produced no telemetry of its own: no incidents, no outbound calls. It\n    // never served — it is unreachable. Name it as such, and say the cause is NOT\n    // in the trace (a startup failure, a crash before the first span, or an\n    // unschedulable / unhealthy pod), so an agent inspects deploy state / logs\n    // instead of hunting a nonexistent code fault here. The unreachability is\n    // OBSERVED; only the WHY is unknown — kept honest-coarse, never fabricated.\n    const name = displayNameOf(seedNode)\n    candidates.push({\n      node: seedNode,\n      classification: 'unreachable',\n      reason: `${name} is unreachable: its callers' requests fail (${seedCtx.errorsFromCallers} erroring inbound calls) and it produced no telemetry of its own — no server spans, no outbound calls — so it never served. The failure is observed, but its cause is not in the trace: a startup failure, a crash before the first span, or an unschedulable / unhealthy pod. Inspect ${name}'s deploy state and logs — there is no code fault to find in the graph here.`,\n      context: seedCtx,\n      confidence: legacy.confidence,\n      provenance: Provenance.OBSERVED,\n    })\n  } else if (seedCtx && isPathFault(seedCtx)) {\n    // ADR-264 / #1481 — callers time out on the seed while it serves fast and\n    // reports nothing of its own. \"Errors arrive from callers, none originate here\"\n    // reads as a load victim, but a node traffic cannot reach can't emit errors\n    // either; the time is spent before its handler. Name the seed as where the\n    // failure is, and point at the way to it, never at the load.\n    const name = displayNameOf(seedNode)\n    candidates.push({\n      node: seedNode,\n      classification: 'unreachable',\n      reason: `${name} is unreachable in part: its callers' calls fail (${seedCtx.errorsFromCallers} erroring) and they wait ${Math.round(seedCtx.latencyP95Ms!)}ms at p95, while what reaches ${name} is served in ${Math.round(seedCtx.servedLatencyP95Ms!)}ms and it reports no error of its own. The time is lost on the way to ${name}, not in its handler and not to load. Check how traffic reaches it — its Service and endpoints, traffic policy, network policy, the network path — not its code, and not the traffic source.`,\n      context: seedCtx,\n      confidence: legacy.confidence,\n      provenance: Provenance.OBSERVED,\n    })\n  } else if (seedCtx && isBoundaryTimeoutSymptom(seedCtx)) {\n    // #1114 / ADR-226 — the seed is a boundary that timed out on an unobservable\n    // downstream. Its timeout is the only span that exported; the real culprit hung\n    // and emitted nothing, so there is no observed edge to walk and no settled cause\n    // to name. The settled verdict LEADS: the boundary is candidates[0] and the\n    // rootCauseNode, a symptom. BELOW it, when the hang sensor has staged a FRONTIER\n    // surface on the unobservable hop, read it back and surface the proposed culprit\n    // at FRONTIER provenance — a claim outside the settled graph, ranked below every\n    // settled cause, a hypothesis to graduate (it turns OBSERVED when the service\n    // recovers) or cull. Never laundered as a settled INFERRED cause. No surface\n    // staged → honest-coarse: name no cause, say it is downstream and unobserved.\n    const seedName = displayNameOf(seedNode)\n    const proposal = stagedHangProposal(graph, seedNode, incidents)\n    const routeNote = proposal?.route ? ` serving ${proposal.route}` : ''\n    // Settled verdict first: the boundary is the symptom, and the rootCauseNode.\n    candidates.push({\n      node: seedNode,\n      classification: 'symptom-only',\n      reason: proposal\n        ? `${seedName} timed out waiting on a downstream that hung and exported no span — a boundary reporting an upstream fault, not the fault itself. The cause is unobservable; NEAT proposes the staged FRONTIER surface below, a hypothesis to confirm, not an observed cause.`\n        : `${seedName} timed out but nothing it can see downstream is erroring — the cause is downstream and unobserved (the culprit hung and exported no span). No FRONTIER surface${routeNote} is staged, so no cause is proposed; inspect ${seedName}'s declared downstream and restore instrumentation.`,\n      context: seedCtx,\n      confidence: Math.min(legacy.confidence, 0.3),\n      ...(lastProv ? { provenance: lastProv } : {}),\n    })\n    // The staged surface, read back as a FRONTIER proposal, ranked below the symptom.\n    if (proposal) {\n      const causeName = displayNameOf(proposal.node)\n      candidates.push({\n        node: proposal.node,\n        classification: 'primary-failure',\n        reason: `${causeName} is the proposed hang cause (FRONTIER — a hypothesis, not observed): the boundary ${seedName} only timed out waiting and the culprit hung without exporting a span, so NEAT staged a FRONTIER surface on the unobservable hop${routeNote}. It graduates to OBSERVED when ${causeName} comes back; until then, inspect it / restore instrumentation to confirm, or it is culled.`,\n        context: nodeContext(graph, proposal.node, incidents, now),\n        confidence: Math.min(legacy.confidence, PROVENANCE_CEILING.FRONTIER!),\n        provenance: Provenance.FRONTIER,\n      })\n    }\n  } else if (staleChain) {\n    // Stale-only causal chain (ADR-209). Fresh signal has gone quiet, but the\n    // last-observed topology still traces from the symptom down to a deepest\n    // stale-only callee. Lead with that callee as a low-confidence, STALE-\n    // provenanced hypothesis — honest about the uncertainty — instead of naming\n    // the symptom with no edges walked. The seed becomes the surface it is.\n    const culprit = staleChain.culprit\n    const culpritName = displayNameOf(culprit)\n    const seedName = displayNameOf(seedNode)\n    // Confidence rides the STALE ceiling (≤ 0.3) through confidenceFromMix — the\n    // provenance itself caps how far it can climb, so the number reads as the low\n    // trust it is without a hand-set floor.\n    const staleConfidence = confidenceFromMix(staleChain.edges, now)\n    candidates.push({\n      node: culprit,\n      classification: 'primary-failure',\n      reason: `${culpritName} is the stale-derived root cause (low confidence): live telemetry for this subgraph has gone quiet, but the last-observed topology traces the failure surfacing at ${seedName} downstream through a STALE call chain to ${culpritName}. Provenance is STALE, so confidence is capped low — restore instrumentation and re-run to confirm before acting.`,\n      context: nodeContext(graph, culprit, incidents, now),\n      confidence: staleConfidence,\n      provenance: Provenance.STALE,\n    })\n    candidates.push({\n      node: seedNode,\n      classification: 'symptom-only',\n      reason: `The failure surfaced here, but the only causal chain the graph still holds is STALE and runs downstream — ${seedName} is the surface of a stale-traced failure, not a proven origin.`,\n      context: seedCtx ?? EMPTY_CONTEXT,\n      confidence: Math.min(legacy.confidence, PROVENANCE_CEILING.STALE!),\n      ...(lastProv ? { provenance: lastProv } : {}),\n    })\n  } else if (seedDeployFault && seedLogCause?.named) {\n    // The seed's own deploy is failing, and its process log names a dependency it\n    // reaches as what it failed on (ADR-262): point at that dependency as the\n    // origin, OBSERVED, with the log lines as the evidence. The seed stays in the\n    // ranking with its deploy fault, as the workload that shows the failure.\n    const seedName = displayNameOf(seedNode)\n    const { error, named } = seedLogCause\n    const depName = displayNameOf(named.id)\n    const evidence = named.inErrorLine\n      ? `\"${error.line}\"`\n      : `\"${error.line}\", after \"${named.line}\"`\n    candidates.push({\n      node: named.id,\n      classification: 'primary-failure',\n      reason: `${seedName}'s deploy is failing on ${depName}: its process log reads ${evidence}. ${depName} is where the failure starts; ${seedName}'s ${deployFaultPhrase(seedDeployFault)} and the errors its callers see (${seedCtx?.errorsFromCallers ?? 0}) follow from it.`,\n      context: nodeContext(graph, named.id, incidents, now),\n      confidence: legacy.confidence,\n      provenance: Provenance.OBSERVED,\n    })\n    candidates.push({\n      node: seedNode,\n      classification: 'symptom-only',\n      reason: `${seedName}'s own deploy is failing — ${deployFaultPhrase(seedDeployFault)} — because of what it hit on ${depName}; its process log reads ${evidence}.`,\n      context: seedCtx ?? EMPTY_CONTEXT,\n      confidence: legacy.confidence,\n      provenance: Provenance.OBSERVED,\n    })\n  } else {\n    // The seed originates the failure (or its node isn't in the graph — an\n    // incident-only localization). Confirm it as the primary cause. When its own\n    // deploy fault is what kept it here, the reason names that fault, and the\n    // claim is OBSERVED: the fault was read off the running workload. Its process\n    // log's first error line, when it has one, is the why (ADR-262).\n    const seedName = displayNameOf(seedNode)\n    const why = seedLogCause\n      ? `Its process log reads \"${seedLogCause.error.line}\"; its deploy context (env, args) has the rest.`\n      : 'Its deploy context (env, args, process log) holds the why.'\n    candidates.push({\n      node: seedNode,\n      classification: 'primary-failure',\n      reason: seedDeployFault\n        ? `${seedName} is the root cause: its own deploy is failing — ${deployFaultPhrase(seedDeployFault)}. The errors its callers see (${seedCtx?.errorsFromCallers ?? 0}) follow from that, not from load. ${why}`\n        : legacy.rootCauseReason,\n      context: seedCtx ?? EMPTY_CONTEXT,\n      confidence: legacy.confidence,\n      ...(seedDeployFault\n        ? { provenance: Provenance.OBSERVED }\n        : lastProv\n          ? { provenance: lastProv }\n          : {}),\n    })\n  }\n\n  const top = candidates[0]!\n  // The legacy verdict tracks the top candidate so old consumers get the fixed\n  // answer too; when the top is the promoted origin, retrace the path up to it so\n  // traversalPath still ends at rootCauseNode (get-root-cause.md invariant).\n  let traversalPath = legacy.traversalPath\n  let edgeProvenances = legacy.edgeProvenances\n  if (staleChain && top.node === staleChain.culprit) {\n    // The stale chain already IS the origin → ... → culprit path, walked outbound;\n    // use it verbatim so traversalPath ends at the named cause and every hop's\n    // STALE provenance is on the path (get-root-cause.md invariant).\n    traversalPath = staleChain.path\n    edgeProvenances = staleChain.edges.map((e) => e.provenance)\n  } else if (seedLogCause?.named && top.node === seedLogCause.named.id) {\n    // The log-named dependency is one hop past the seed, read off the seed's own log.\n    const toSeed = legacy.traversalPath[legacy.traversalPath.length - 1] === seedNode\n    traversalPath = toSeed ? [...legacy.traversalPath, top.node] : [seedNode, top.node]\n    edgeProvenances = toSeed ? [...legacy.edgeProvenances, Provenance.OBSERVED] : [Provenance.OBSERVED]\n  } else if (top.node !== seedNode) {\n    const path = findPath(graph, errorNodeId, top.node, 'up', ROOT_CAUSE_MAX_DEPTH)\n    if (path) {\n      traversalPath = path.nodes\n      edgeProvenances = path.edges.map((e) => e.provenance)\n    } else {\n      traversalPath = [errorNodeId, top.node]\n      edgeProvenances = [top.provenance ?? Provenance.OBSERVED]\n    }\n  }\n\n  // fixRecommendation has to name the node we hand back as rootCauseNode (top),\n  // not the downstream victim the legacy verdict walked to.\n  const fixRecommendation = clientFix ??\n    (seedLogCause?.named && top.node === seedLogCause.named.id\n      ? `${displayNameOf(seedNode)} fails on ${displayNameOf(top.node)}: \"${seedLogCause.error.line}\". Check ${displayNameOf(top.node)} for what that line reports before changing ${displayNameOf(seedNode)}'s code; ${displayNameOf(seedNode)}'s deploy context holds the address and credential references it uses.`\n      : fixRecommendationForTop(top, seedNode, legacy))\n\n  return RootCauseResultSchema.parse({\n    rootCauseNode: top.node,\n    rootCauseReason: top.reason,\n    traversalPath,\n    edgeProvenances,\n    confidence: top.confidence,\n    ...(fixRecommendation ? { fixRecommendation } : {}),\n    candidates,\n  })\n}\n\n// The fix recommendation must point at whichever node getRootCause returns as\n// rootCauseNode — the top candidate — never at a symptom-only victim. When the\n// seed is itself the primary failure, the legacy verdict already derived a\n// recommendation aimed at it, so keep it. When navigation promoted an upstream\n// load origin (the seed turned out to be a starved symptom-only victim), the\n// legacy recommendation still targets that victim, so rebuild it to name the\n// overloading source. A symptom-only top — the case where no load origin was\n// found — is sent to its inbound load, never to its own handler.\nfunction fixRecommendationForTop(\n  top: RootCauseCandidate,\n  seedNode: string,\n  legacy: RootCauseResult,\n): string | undefined {\n  if (top.classification === 'primary-failure' && top.node === seedNode) {\n    return legacy.fixRecommendation\n  }\n  const name = top.node.replace(/^service:/, '')\n  // An unreachable node is never a load victim (#1123, ADR-264): send the agent to\n  // how traffic reaches it, or to its deploy state when it never served at all.\n  if (top.classification === 'unreachable') {\n    return isPathFault(top.context)\n      ? `Check how traffic reaches ${name}: its Service selector and endpoints, traffic policy, network policy and the network path. Its handler serves fast and reports no error, so neither its code nor the load is the fault.`\n      : `${name} never served: inspect its deploy state and logs (scheduling, startup, readiness); there is no code fault to find in the graph.`\n  }\n  // ADR-226 — a boundary that timed out is a symptom-only top whose cause is\n  // unobservable. It is not a load victim, so it never gets the inbound-load\n  // wording; send the agent to the FRONTIER surface proposed in the candidates.\n  if (top.classification === 'symptom-only' && top.context.boundaryTimeout === true) {\n    return `${name} timed out waiting on a downstream that hung and exported no span — the cause is unobservable from traces. Inspect the FRONTIER surface NEAT staged on the unobservable hop (see candidates); it graduates to OBSERVED when that service recovers. Restore instrumentation on that path to confirm, rather than treating ${name} as the fault.`\n  }\n  // A stale-derived promotion (ADR-209) isn't an overload — the signal simply went\n  // quiet — so it gets its own recommendation, never the throttle-the-load wording.\n  if (top.provenance === Provenance.STALE) {\n    return `Live telemetry for this path has gone quiet; the last-observed topology traces the failure downstream to ${name}. Restore instrumentation (or re-run with live traces) to confirm, then inspect ${name}.`\n  }\n  if (top.classification === 'primary-failure') {\n    return `Reduce or throttle the load from ${name} (or scale the saturated downstream capacity it drives) — the failure originates at this overloading source, not the starved callee.`\n  }\n  return `${name} is a saturated/starved downstream victim; investigate its inbound load and upstream callers, not its own handler.`\n}\n","import { EdgeType, NodeType, Provenance, type ErrorEvent, type GraphEdge, type GraphNode } from '@neat.is/types'\nimport type { NeatGraph } from './graph.js'\n\n// A traffic source (ADR-264): a service nothing calls at runtime, that consumes\n// from no queue, and whose errors are all on its own outbound calls. A load\n// generator, a synthetic client, a browser. Its errors are responses it received,\n// so it is never a culprit: the incident lead lists it apart, and root cause never\n// names it as the origin of the load it sends. Structural (runtime in-degree and\n// edge direction), never a name list. One predicate, read by both (#1373).\n\n// Kept as functions, not module-level `new Set([Enum.X])` constants: the enum\n// values are read at call time, never at module load, so this module's body\n// dereferences no imported binding before it is initialized — which keeps it safe\n// under the parallel module initialization the test runner does.\nfunction isRuntimeProvenance(p: string): boolean {\n  return p === Provenance.OBSERVED || p === Provenance.INFERRED || p === Provenance.STALE\n}\n// Edges that carry no traffic: ownership and placement.\nfunction isStructuralEdge(t: string): boolean {\n  return t === EdgeType.CONTAINS || t === EdgeType.RUNS_ON || t === EdgeType.CONFIGURED_BY\n}\n\nexport function isTrafficEdge(e: GraphEdge): boolean {\n  return isRuntimeProvenance(e.provenance) && !isStructuralEdge(e.type)\n}\n\nexport function nodeType(graph: NeatGraph, id: string): string | undefined {\n  return graph.hasNode(id) ? (graph.getNodeAttributes(id) as GraphNode).type : undefined\n}\n\n\n// A method or route callee is reported as the service that serves it, when the\n// graph knows one: that is the callee a reader acts on.\nexport function owningService(graph: NeatGraph, id: string): string {\n  if (nodeType(graph, id) === NodeType.ServiceNode) return id\n  for (const eid of graph.inboundEdges(id)) {\n    const e = graph.getEdgeAttributes(eid) as GraphEdge\n    if (e.type === EdgeType.CONTAINS && nodeType(graph, e.source) === NodeType.ServiceNode) return e.source\n  }\n  return id\n}\n\n/**\n * The callees a traffic source's failing calls went to, or null when `nodeId` is\n * not a traffic source. A traffic source has no runtime caller (and consumes from\n * no queue, whose messages would be its inbound work), sends traffic, and has at\n * least as many errors on its outbound calls as incidents of its own, so every\n * error it recorded can be one it received.\n */\nexport function trafficSourceCallees(\n  graph: NeatGraph | undefined,\n  nodeId: string,\n  incidentCount: number,\n): string[] | null {\n  if (!graph || nodeType(graph, nodeId) !== NodeType.ServiceNode) return null\n  for (const id of graph.inboundEdges(nodeId)) {\n    if (isTrafficEdge(graph.getEdgeAttributes(id) as GraphEdge)) return null\n  }\n  let outboundErrors = 0\n  const callees = new Map<string, number>()\n  for (const id of graph.outboundEdges(nodeId)) {\n    const e = graph.getEdgeAttributes(id) as GraphEdge\n    if (!isTrafficEdge(e)) continue\n    if (e.type === EdgeType.CONSUMES_FROM) return null\n    const errs = e.signal?.errorCount ?? 0\n    if (errs === 0) continue\n    outboundErrors += errs\n    const callee = owningService(graph, e.target)\n    callees.set(callee, (callees.get(callee) ?? 0) + errs)\n  }\n  if (outboundErrors === 0 || outboundErrors < incidentCount) return null\n  return [...callees.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([id]) => id)\n}\n\n/**\n * `trafficSourceCallees` for a service, counting its incidents from the store:\n * every incident recorded against the service or a node it owns.\n */\nexport function trafficSourceOf(\n  graph: NeatGraph | undefined,\n  serviceNodeId: string,\n  incidents: readonly ErrorEvent[] | undefined,\n): string[] | null {\n  const svc = serviceNodeId.replace(/^service:/, '')\n  const n = (incidents ?? []).filter((e) => e.service === svc || e.affectedNode === serviceNodeId).length\n  return trafficSourceCallees(graph, serviceNodeId, n)\n}\n","// Reading a faulted workload's fused process log (ADR-243 `observedDeployContext.processLog`)\n// for the line that names its failure, and for the dependency that line points at\n// (ADR-262). Pure functions over the log text and a caller-supplied candidate list:\n// no graph, no provider knowledge. A line is an error by its log level or by the\n// shape of an exception, never by what product printed it.\n\n// Terminal colour and cursor sequences. Go's zerolog console writer, among others,\n// colours its level and caller fields, and the k8s log API returns the bytes as written.\nconst ANSI_RE = /\\x1b\\[[0-9;?]*[A-Za-z]/g\n\nconst MAX_LINE_CHARS = 300\n\nexport function stripAnsi(text: string): string {\n  return text.replace(ANSI_RE, '')\n}\n\nconst ERROR_LEVELS = new Set(['error', 'err', 'fatal', 'ftl', 'panic', 'critical', 'crit', 'severe', 'emerg', 'emergency', 'alert'])\n\n// A level token standing alone in a text line: `FTL`, `[ERROR]`, `E1017 …` is not\n// matched (too ambiguous), `level=error` is.\nconst LEVEL_TOKEN_RE = /(?:^|[\\s[|(])(FTL|FATAL|PANIC|CRIT|CRITICAL|ERR|ERROR|SEVERE|EMERG)(?=[\\s\\]|):]|$)/\nconst LEVEL_KV_RE = /\\b(?:level|lvl|severity)=[\"']?(error|err|fatal|panic|critical|crit)\\b/i\n// A runtime's own failure line: `panic: …`, `fatal error: …`, `Error: …`,\n// `Exception in thread \"main\" …`, `pkg.SomeError: …`, `SomeException: …`.\nconst EXCEPTION_RE =\n  /^(?:panic:|fatal error:|error:|Exception in thread\\b|(?:[A-Za-z_$][\\w$]*\\.)*[A-Za-z_$][\\w$]*(?:Error|Exception)(?::|$))/i\nconst TRACEBACK_RE = /^Traceback \\(most recent call last\\):/\nconst LEADING_TIMESTAMP_RE = /^\\[?\\d{4}-\\d{2}-\\d{2}[T ][\\d:.,]+(?:Z|[+-]\\d{2}:?\\d{2})?\\]?\\s*/\n\nexport interface LogErrorLine {\n  // The error line as shown: escapes stripped, a leading timestamp dropped, bounded.\n  line: string\n  // Index of the line within the stripped log, so the lines before it can be read.\n  index: number\n}\n\nfunction display(line: string): string {\n  const s = line.replace(LEADING_TIMESTAMP_RE, '').replace(/\\s+/g, ' ').trim()\n  return s.length > MAX_LINE_CHARS ? `${s.slice(0, MAX_LINE_CHARS - 1)}…` : s\n}\n\n// A JSON log record's level and message, when the line is one.\nfunction jsonRecord(line: string): { level?: string; message?: string } | null {\n  if (!line.startsWith('{')) return null\n  try {\n    const rec = JSON.parse(line) as Record<string, unknown>\n    const level = [rec.level, rec.severity, rec.lvl, rec.levelname].find((v) => typeof v === 'string') as\n      | string\n      | undefined\n    const message = [rec.message, rec.msg, rec.error, rec.err].find((v) => typeof v === 'string') as\n      | string\n      | undefined\n    return { level, message }\n  } catch {\n    return null\n  }\n}\n\n/** The stripped log, split into lines. */\nexport function logLines(log: string): string[] {\n  return stripAnsi(log).split(/\\r?\\n/)\n}\n\n/**\n * The first line of the log that reports an error, by level or by exception shape.\n * A Python traceback reports at its last line (the exception), so a traceback header\n * resolves to the exception line that closes it.\n */\nexport function firstErrorLine(log: string): LogErrorLine | null {\n  const lines = logLines(log)\n  for (let i = 0; i < lines.length; i++) {\n    const raw = lines[i]!.trim()\n    if (raw.length === 0) continue\n    const rec = jsonRecord(raw)\n    if (rec) {\n      if (rec.level && ERROR_LEVELS.has(rec.level.toLowerCase())) {\n        return { line: display(rec.message ?? raw), index: i }\n      }\n      continue\n    }\n    if (TRACEBACK_RE.test(raw)) {\n      for (let j = i + 1; j < lines.length; j++) {\n        const l = lines[j]!\n        if (l.length > 0 && !/^\\s/.test(l)) return { line: display(l), index: j }\n      }\n      return { line: display(raw), index: i }\n    }\n    if (LEVEL_TOKEN_RE.test(raw) || LEVEL_KV_RE.test(raw) || EXCEPTION_RE.test(raw)) {\n      return { line: display(raw), index: i }\n    }\n  }\n  return null\n}\n\nexport interface DependencyCandidate {\n  id: string\n  // Names the node goes by in text: its name, host, aliases. Shorter than three\n  // characters is dropped by the matcher.\n  names: string[]\n  // Lower ranks first when two candidates are named equally well.\n  rank: number\n}\n\nexport interface NamedDependency {\n  id: string\n  // The line that named it, as shown.\n  line: string\n  // True when the error line itself named it; false when a line before it did.\n  inErrorLine: boolean\n}\n\nfunction escapeRe(s: string): string {\n  return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n// The longest name of `c` found in `text` as a whole token: not run into by a word\n// character or a hyphen on either side, so `mongodb-geo` matches in\n// `mongodb-geo:27017` and `mongodb-geo.ns.svc`, and `geo` does not match in it.\nfunction matchLength(text: string, c: DependencyCandidate): number {\n  let best = 0\n  for (const name of c.names) {\n    if (name.length < 3 || name.length <= best) continue\n    const re = new RegExp(`(?<![\\\\w-])${escapeRe(name)}(?![\\\\w-])`, 'i')\n    if (re.test(text)) best = name.length\n  }\n  return best\n}\n\nfunction bestIn(text: string, candidates: DependencyCandidate[]): DependencyCandidate | null {\n  let best: { c: DependencyCandidate; len: number } | null = null\n  for (const c of candidates) {\n    const len = matchLength(text, c)\n    if (len === 0) continue\n    if (\n      !best ||\n      len > best.len ||\n      (len === best.len && (c.rank < best.c.rank || (c.rank === best.c.rank && c.id < best.c.id)))\n    ) {\n      best = { c, len }\n    }\n  }\n  return best?.c ?? null\n}\n\n/**\n * The dependency the log names for its error: the error line first; when it names\n * none of the candidates, the nearest line before it that does. Candidates are the\n * caller's to bound (ADR-262: the seed's own outbound dependencies), so nothing\n * outside them can be named.\n */\nexport function dependencyNamedInLog(\n  log: string,\n  error: LogErrorLine,\n  candidates: DependencyCandidate[],\n): NamedDependency | null {\n  if (candidates.length === 0) return null\n  const lines = logLines(log)\n  const own = bestIn(lines[error.index] ?? '', candidates)\n  if (own) return { id: own.id, line: error.line, inErrorLine: true }\n  for (let i = error.index - 1; i >= 0; i--) {\n    const hit = bestIn(lines[i]!, candidates)\n    if (hit) return { id: hit.id, line: display(lines[i]!), inErrorLine: false }\n  }\n  return null\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport JavaScript from 'tree-sitter-javascript'\nimport Python from 'tree-sitter-python'\nimport Go from 'tree-sitter-go'\nimport Ruby from 'tree-sitter-ruby'\nimport Php from 'tree-sitter-php'\nimport Rust from 'tree-sitter-rust'\nimport type { GraphEdge, RouteNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  routeId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport { isTestPath, type DiscoveredService } from './shared.js'\nimport { recordExtractionError } from './errors.js'\nimport { loadSourceFiles, snippet, toPosix, type SourceFile } from './calls/shared.js'\nimport { resolveJsImport, loadTsPathConfig, type TsPathConfig } from './imports.js'\n\n// Server-route extraction (ADR-119). Reads a mainstream router's route table —\n// Express (`app.get`/`router.post`/…), Fastify (`fastify.get`, `fastify.route`),\n// Next.js (app-router `route.*` handlers, pages `api/` handlers) — and\n// materialises each route as a RouteNode at (method, path-template) grain, owned\n// by its service through a `service ──CONTAINS──▶ route` edge. This is the\n// server half of the static contract-matching in calls/route-match.ts: a\n// client call site is matched to the route it names, bridging the two static\n// islands into a route-grained cross-service CALLS edge.\n//\n// Scope is mainstream routers only, gated by manifest dependency (the extensible\n// registry pattern — coverage grows one router at a time, not by exhaustive\n// heuristics). A service with none of these deps is skipped.\n\nconst PARSE_CHUNK = 16384\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nfunction makeJsParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(JavaScript)\n  return p\n}\n\nfunction makePyParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Python)\n  return p\n}\n\nfunction makeGoParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Go)\n  return p\n}\n\nfunction makeRubyParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Ruby)\n  return p\n}\n\n// Laravel's route files are pure PHP (a controller + route definitions, no HTML\n// islands), so the grammar's `php_only` variant is the right parser — `.php`\n// would accept `?>`-delimited HTML the route files never carry (ADR-177).\nfunction makePhpParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Php.php_only)\n  return p\n}\n\nfunction makeRustParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Rust)\n  return p\n}\n\n// The HTTP verbs an Express / Fastify router registers a route under. `all`\n// registers a method-agnostic route; it normalises to the `ALL` method token.\nconst ROUTER_METHODS = new Set([\n  'get',\n  'post',\n  'put',\n  'patch',\n  'delete',\n  'options',\n  'head',\n  'all',\n])\n\n// The exported handler names a Next.js app-router `route.*` file uses, one per\n// HTTP method it serves.\nconst NEXT_APP_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])\n\n// The HTTP methods a Go 1.22 `net/http` ServeMux pattern may lead with\n// (`\"GET /orders/{id}\"`). This precise set is half the structural gate: the\n// leading token must be one of these AND the remainder must start with `/`,\n// which is what keeps a generic `HandleFunc(\"literal\", h)` — or a pre-1.22\n// bare-prefix registration — from minting a route (ADR-182).\nconst NET_HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'])\n\nconst JS_ROUTE_EXTENSIONS = new Set(['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx'])\n\nexport interface ExtractedRoute {\n  method: string // upper-cased HTTP method, or 'ALL' for a method-agnostic route\n  pathTemplate: string // canonicalised declared template, e.g. '/users/:id'\n  line: number // 1-indexed line the route is declared on\n  framework: string // Router registry label; NestJS joins the existing JS/Python set in ADR-155.\n  // The route's `controller#action` handler, when the recogniser knows it —\n  // Rails' resourceful expansion derives it (ADR-173). RouteNode carries no\n  // handler field today, so `addRoutes` keeps this off the graph; it exists so\n  // the recogniser tests can assert the module/pluralisation logic the path\n  // template alone can't show (a `scope module:` route differs only here).\n  controller?: string\n}\n\n// Gin, Echo, and Fiber all declare their route table the same way — a router\n// value carries an HTTP-verb method (`r.GET(...)`, `e.GET(...)`, `app.Get(...)`)\n// whose first argument is the path, and `<router>.Group(\"/prefix\")` returns a\n// sub-router that composes a prefix onto everything registered on it. At the Go\n// AST that is one grammar: a `call_expression` on a `selector_expression`, the\n// verb differing only in casing (Gin/Echo upper-case `GET`, Fiber title-case\n// `Get`) which the lower-cased method check already absorbs. So one walker reads\n// all three; they differ only in the framework label and the manifest dependency\n// that gates them (`addRoutes`). A group variable is tracked the way the receiver\n// var is: `admin := r.Group(\"/admin\")` records `admin → /admin`, and a group\n// opened off another group (`v1 := admin.Group(\"/v1\")`) composes onto its\n// parent's prefix, so nested groups reach `/admin/v1`. Both `:=` and `var x = …`\n// forms are read. Route-param constraints and middleware-only / `Static` mounts\n// are deferred.\nfunction goRouterRoutesFromSource(\n  source: string,\n  parser: Parser,\n  framework: string,\n): ExtractedRoute[] {\n  const tree = parseSource(parser, source)\n  const prefixes = new Map<string, string>()\n  const out: ExtractedRoute[] = []\n  walk(tree.rootNode, (node) => {\n    if (node.type === 'short_var_declaration' || node.type === 'var_spec') {\n      const name =\n        node.childForFieldName('left')?.namedChild(0)?.text ?? node.childForFieldName('name')?.text\n      const value =\n        node.childForFieldName('right')?.namedChild(0) ?? node.childForFieldName('value')\n      if (name && value?.type === 'call_expression') {\n        const fn = value.childForFieldName('function')\n        if (fn?.childForFieldName('field')?.text === 'Group') {\n          const leaf = goStringLiteral(value.childForFieldName('arguments')?.namedChild(0))\n          if (leaf !== null) {\n            const parent = fn.childForFieldName('operand')?.text ?? ''\n            prefixes.set(name, (prefixes.get(parent) ?? '') + leaf)\n          }\n        }\n      }\n      return\n    }\n    if (node.type !== 'call_expression') return\n    const fn = node.childForFieldName('function')\n    if (fn?.type !== 'selector_expression') return\n    const method = fn.childForFieldName('field')?.text?.toUpperCase()\n    if (!method || !ROUTER_METHODS.has(method.toLowerCase())) return\n    const receiver = fn.childForFieldName('operand')?.text ?? ''\n    const leaf = goStringLiteral(node.childForFieldName('arguments')?.namedChild(0))\n    if (leaf === null) return\n    out.push({\n      method,\n      pathTemplate: canonicalizeTemplate((prefixes.get(receiver) ?? '') + leaf),\n      line: node.startPosition.row + 1,\n      framework,\n    })\n  })\n  return out\n}\n\n// Read a Go string literal's inner text. Both the double-quoted\n// (`interpreted_string_literal`) and back-quoted (`raw_string_literal`) forms\n// carry their delimiters in `.text`, so slicing one char off each end yields the\n// path; a non-literal argument (a computed path) returns null and is skipped.\nfunction goStringLiteral(node: Parser.SyntaxNode | null | undefined): string | null {\n  if (node?.type === 'interpreted_string_literal' || node?.type === 'raw_string_literal') {\n    return node.text.slice(1, -1)\n  }\n  return null\n}\n\n// Gin (`github.com/gin-gonic/gin`).\nexport function ginRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  return goRouterRoutesFromSource(source, parser, 'gin')\n}\n\n// Echo (`github.com/labstack/echo/v4`, also plain `.../echo`). `otelecho` sets\n// `http.route` from `c.Path()` — the group-composed template — so the extracted\n// node fuses through `normalizePathTemplate` with no ingest change.\nexport function echoRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  return goRouterRoutesFromSource(source, parser, 'echo')\n}\n\n// Fiber (`github.com/gofiber/fiber/v2`, also `/v3`). Both the v2 `otelfiber` and\n// the v3 middleware set `http.route` from `c.Route().Path` — the group-composed\n// template — so the node fuses with no ingest change. Fiber's optional-param\n// `:id?` reduces to `:param` like `:id`; a bare `*` / `+` wildcard stays literal\n// on both the extracted template and `c.Route().Path`, so it still matches.\nexport function fiberRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  return goRouterRoutesFromSource(source, parser, 'fiber')\n}\n\n// ── Chi (`github.com/go-chi/chi/v5`, also pre-modules `.../chi`) ─────────────\n//\n// Chi declares verbs the Fiber way — title-cased `r.Get/Post/Put/Patch/Delete`\n// on a router value, first argument the path — so the verb read is the same one\n// the Gin/Echo/Fiber walker does. What Chi does differently is prefix\n// composition. Gin/Echo/Fiber name a sub-router (`admin := r.Group(\"/admin\")`)\n// and the prefix follows that variable; Chi's `Route(\"/articles\", func(r\n// chi.Router){ … })` has no assignment — the prefix is lexically scoped to the\n// closure body and the inner `r` shadows the outer. So a variable Map can't\n// track it; a prefix STACK can. This walker recurses the tree carrying the\n// accumulated prefix: a `Route(strLit, funcLit)` pushes the literal and recurses\n// into the `func_literal` body, nested `Route`s compose (`/articles` +\n// `/{articleID}`), and the prefix pops on return (the recursion frame). A\n// `Group(funcLit)` — first argument a closure, not a string — is middleware\n// grouping: it contributes no prefix, just recurses. A `Mount(\"/admin\", h)` is\n// deferred: the mounted sub-router is usually built in another func or file, the\n// same cross-func/cross-file resolution Express `app.use` needed before ADR-160,\n// so it's skipped here (costing one fused edge, since otelchi emits the full\n// composed path).\n//\n// Inline regex constraints (`{id:[0-9]+}`) are stripped to `{id}` so the stored\n// template stays clean and `canonicalizeTemplate` can't read a `?` inside the\n// regex as a query delimiter; either way `normalizePathTemplate` collapses a\n// `{…}` segment to `:param`, so fusion is unaffected.\n//\n// FUSION CAVEAT (ADR-182): Chi fuses only under `otelchi`\n// (`github.com/riandyrn/otelchi`), which reads `chi.RouteContext(r).RoutePattern()`\n// — the composed template — and sets `http.route` to it (path-only), the same\n// shape echo's `c.Path()` / fiber's `c.Route().Path` produce. Under bare\n// `otelhttp` a Chi app sets NO `http.route` (Chi never populates `r.Pattern`),\n// so these RouteNodes stay EXTRACTED-only with nothing to fuse onto.\nexport function chiRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  const tree = parseSource(parser, source)\n  const out: ExtractedRoute[] = []\n  chiWalk(tree.rootNode, '', out)\n  return out\n}\n\n// Strip a Chi inline-regex constraint from each param segment: `{id:[0-9]+}` →\n// `{id}`. Handles the common single-level case (a regex with no nested braces);\n// a regex carrying its own `{n,m}` quantifier is left as-is, and still collapses\n// to `:param` at match time.\nfunction stripChiRegex(path: string): string {\n  return path.replace(/\\{([^{}:]+):[^{}]*\\}/g, '{$1}')\n}\n\n// Recurse the tree carrying the accumulated route prefix. A `Route`/`Group` call\n// is handled specially (its closure body is recursed with the pushed/unchanged\n// prefix and the generic descent stops there); a verb call emits; everything\n// else descends with the same prefix.\nfunction chiWalk(node: Parser.SyntaxNode, prefix: string, out: ExtractedRoute[]): void {\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (child) chiHandle(child, prefix, out)\n  }\n}\n\nfunction chiHandle(node: Parser.SyntaxNode, prefix: string, out: ExtractedRoute[]): void {\n  if (node.type === 'call_expression') {\n    const fn = node.childForFieldName('function')\n    if (fn?.type === 'selector_expression') {\n      const field = fn.childForFieldName('field')?.text\n      const args = node.childForFieldName('arguments')\n      if (field === 'Route') {\n        const leaf = goStringLiteral(args?.namedChild(0))\n        const closure = args?.namedChild(1)\n        if (leaf !== null && closure?.type === 'func_literal') {\n          const body = closure.childForFieldName('body')\n          if (body) chiWalk(body, prefix + leaf, out)\n        }\n        return // handled — the string arg and closure carry no other routes\n      }\n      if (field === 'Group') {\n        // Chi's `Group(func(r chi.Router){ … })` is middleware grouping: the\n        // first argument is a closure, not a path, so it adds no prefix.\n        const closure = args?.namedChild(0)\n        if (closure?.type === 'func_literal') {\n          const body = closure.childForFieldName('body')\n          if (body) chiWalk(body, prefix, out)\n        }\n        return\n      }\n      if (field === 'Mount') {\n        return // deferred (ADR-182) — the mounted router is resolved elsewhere\n      }\n      if (field && ROUTER_METHODS.has(field.toLowerCase())) {\n        const leaf = goStringLiteral(args?.namedChild(0))\n        if (leaf !== null) {\n          out.push({\n            method: field.toUpperCase(),\n            pathTemplate: canonicalizeTemplate(stripChiRegex(prefix + leaf)),\n            line: node.startPosition.row + 1,\n            framework: 'chi',\n          })\n        }\n        return\n      }\n    }\n  }\n  // Not a Chi routing call — descend into its children at the same prefix.\n  chiWalk(node, prefix, out)\n}\n\n// ── net/http (Go 1.22+ ServeMux method patterns) ────────────────────────────\n//\n// Go 1.22's `ServeMux` carries the method and the path template in ONE string\n// literal: `mux.HandleFunc(\"GET /orders/{id}\", h)`, `http.HandleFunc(…)`,\n// `mux.Handle(…)`, `http.Handle(…)`. Read the first string-literal argument and\n// split on the first space; emit a RouteNode ONLY when the leading token is an\n// HTTP method AND the remainder starts with `/`. That precision is the whole\n// gate: net/http is stdlib, so there's no go.mod dependency to key on the way\n// Gin/Echo/Fiber/Chi are. Instead this recogniser self-gates STRUCTURALLY — the\n// file must `import \"net/http\"`, and only the method-prefixed pattern shape\n// mints a route, which is what keeps a generic `HandleFunc(\"literal\", h)` or a\n// pre-1.22 bare-prefix `HandleFunc(\"/orders/\", h)` (no method, coarse subtree —\n// the biggest false-positive source) from being read (ADR-182). A pre-1.22 exact\n// path (`HandleFunc(\"/hotels\", h)`, no trailing slash) is read as method ALL\n// (ADR-254): ServeMux matches it exactly, so it is as precise as a template.\n//\n// `{id}` (single segment), `{path...}` (multi-segment wildcard), and `{$}` (the\n// end-of-path anchor) all sit under `normalizePathTemplate` unchanged — each is a\n// `{…}` segment that collapses to `:param` — so fusion needs no special casing.\n//\n// Fusion is automatic on a modern stack (ADR-182): Go 1.23's `Request.Pattern` +\n// otelhttp ≥ v1.36 set `http.route` to the path-only template (method stripped),\n// exactly the template stored here. On an older stack `http.route` is absent and\n// the node stays EXTRACTED-only — an honest version gate, documented not guessed.\nexport function netHttpRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  const tree = parseSource(parser, source)\n  if (!goImportsNetHttp(tree.rootNode)) return []\n  const out: ExtractedRoute[] = []\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'call_expression') return\n    const fn = node.childForFieldName('function')\n    if (fn?.type !== 'selector_expression') return\n    const field = fn.childForFieldName('field')?.text\n    if (field !== 'HandleFunc' && field !== 'Handle') return\n    const leaf = goStringLiteral(node.childForFieldName('arguments')?.namedChild(0))\n    if (leaf === null) return\n    const sp = leaf.indexOf(' ')\n    if (sp < 0) {\n      // No method token (ADR-254). ServeMux matches a pattern with no trailing\n      // slash exactly, so `\"/hotels\"` is one route serving every method; a\n      // trailing-slash pattern (`\"/orders/\"`) is a subtree and `\"/\"` matches\n      // everything, so both stay skipped (ADR-182).\n      if (!leaf.startsWith('/') || leaf === '/' || leaf.endsWith('/')) return\n      out.push({\n        method: 'ALL',\n        pathTemplate: canonicalizeTemplate(leaf),\n        line: node.startPosition.row + 1,\n        framework: 'net/http',\n      })\n      return\n    }\n    const method = leaf.slice(0, sp)\n    const rest = leaf.slice(sp + 1)\n    if (!NET_HTTP_METHODS.has(method)) return\n    if (!rest.startsWith('/')) return // a host-prefixed pattern isn't composed\n    out.push({\n      method,\n      pathTemplate: canonicalizeTemplate(rest),\n      line: node.startPosition.row + 1,\n      framework: 'net/http',\n    })\n  })\n  return out\n}\n\n// Whether the file imports the `net/http` package — the structural half of the\n// net/http gate. Reads both the grouped `import ( … )` and the single\n// `import \"net/http\"` forms (each yields an `import_spec` with a string path).\nfunction goImportsNetHttp(root: Parser.SyntaxNode): boolean {\n  let found = false\n  walk(root, (node) => {\n    if (found || node.type !== 'import_spec') return\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (goStringLiteral(child) === 'net/http') found = true\n    }\n  })\n  return found\n}\n\n// The HTTP verbs FastAPI/Starlette register a route decorator under\n// (`@router.get(...)`, `@app.post(...)`, …). `api_route` is handled separately —\n// it carries its methods in a `methods=[…]` keyword argument.\nconst FASTAPI_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'options', 'head', 'trace'])\n\nconst NESTJS_METHODS = new Map([\n  ['Get', 'GET'],\n  ['Post', 'POST'],\n  ['Put', 'PUT'],\n  ['Patch', 'PATCH'],\n  ['Delete', 'DELETE'],\n  ['Options', 'OPTIONS'],\n  ['Head', 'HEAD'],\n  ['All', 'ALL'],\n])\n\n// ── path-template canonicalisation ──────────────────────────────────────────\n\n// Canonicalise a declared route path for use as a RouteNode's stable template:\n// drop any query/hash, ensure a leading slash, drop a trailing slash (except\n// root). The template keeps its declared params verbatim (`:id`, `{id}`) so an\n// OBSERVED server span carrying the same `http.route` lands on the same node.\nexport function canonicalizeTemplate(raw: string): string {\n  let p = raw.split('?')[0]!.split('#')[0]!\n  if (!p.startsWith('/')) p = '/' + p\n  if (p.length > 1 && p.endsWith('/')) p = p.slice(0, -1)\n  return p\n}\n\n// A path segment is dynamic when it names a parameter rather than a literal.\n// Covers the router param syntaxes (`:id`, `{id}`, `[id]`, `[...slug]`), a\n// reconstructed client interpolation (`:param`), and a concrete value a client\n// URL carries in a param position (all-digits, uuid, long hex / Mongo id).\nfunction isDynamicSegment(seg: string): boolean {\n  if (seg.length === 0) return false\n  if (seg.includes(':')) return true // :id (express/fastify) or reconstructed :param\n  if (seg.startsWith('{') || seg.startsWith('[')) return true // {id} openapi; Next [id]/[...slug]/[[...slug]]\n  if (/^\\d+$/.test(seg)) return true // concrete numeric id\n  if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(seg)) return true // uuid\n  if (/^[0-9a-f]{24,}$/i.test(seg)) return true // mongo objectid / long hex token\n  return false\n}\n\n// Normalise a path-template to a param-agnostic matching key: every dynamic\n// segment collapses to `:param`, every literal segment lowercases. This is the\n// comparison form both a server route's declared template and a client call's\n// URL path reduce to, so `/users/:id` (server) matches `/users/123` and\n// `/users/${userId}` (client). The declared template is kept intact on the\n// node; only matching uses this reduction.\nexport function normalizePathTemplate(raw: string): string {\n  const canonical = canonicalizeTemplate(raw)\n  const segments = canonical.split('/').filter((s) => s.length > 0)\n  const normalised = segments.map((seg) => (isDynamicSegment(seg) ? ':param' : seg.toLowerCase()))\n  return '/' + normalised.join('/')\n}\n\n// ── AST helpers ─────────────────────────────────────────────────────────────\n\nfunction walk(node: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (child) walk(child, visit)\n  }\n}\n\n// The interior text of a string literal, stripped of quotes. Returns null for a\n// template string carrying interpolation (a route path is a static literal).\nfunction staticStringText(node: Parser.SyntaxNode): string | null {\n  if (node.type === 'string') {\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (child?.type === 'string_fragment') return child.text\n    }\n    // Empty string literal ('' — no fragment child).\n    return ''\n  }\n  if (node.type === 'template_string') {\n    // Only a template with no substitution is a usable static path.\n    for (let i = 0; i < node.namedChildCount; i++) {\n      if (node.namedChild(i)?.type === 'template_substitution') return null\n    }\n    const raw = node.text\n    return raw.length >= 2 ? raw.slice(1, -1) : ''\n  }\n  return null\n}\n\n// Read a string-valued property off an object-expression node (`{ url: '/x' }`).\nfunction objectStringProp(objNode: Parser.SyntaxNode, key: string): string | null {\n  for (let i = 0; i < objNode.namedChildCount; i++) {\n    const pair = objNode.namedChild(i)\n    if (!pair || pair.type !== 'pair') continue\n    const k = pair.childForFieldName('key')\n    if (!k) continue\n    const kText = k.type === 'string' ? staticStringText(k) : k.text\n    if (kText !== key) continue\n    const v = pair.childForFieldName('value')\n    if (v) return staticStringText(v)\n  }\n  return null\n}\n\n// Read the `method` property off a Fastify route-options object. Accepts a\n// single string (`method: 'GET'`) or an array (`method: ['GET','POST']`).\nfunction fastifyRouteMethods(objNode: Parser.SyntaxNode): string[] {\n  for (let i = 0; i < objNode.namedChildCount; i++) {\n    const pair = objNode.namedChild(i)\n    if (!pair || pair.type !== 'pair') continue\n    const k = pair.childForFieldName('key')\n    const kText = k ? (k.type === 'string' ? staticStringText(k) : k.text) : null\n    if (kText !== 'method') continue\n    const v = pair.childForFieldName('value')\n    if (!v) return []\n    if (v.type === 'string' || v.type === 'template_string') {\n      const s = staticStringText(v)\n      return s ? [s.toUpperCase()] : []\n    }\n    if (v.type === 'array') {\n      const out: string[] = []\n      for (let j = 0; j < v.namedChildCount; j++) {\n        const el = v.namedChild(j)\n        if (el && (el.type === 'string' || el.type === 'template_string')) {\n          const s = staticStringText(el)\n          if (s) out.push(s.toUpperCase())\n        }\n      }\n      return out\n    }\n  }\n  return []\n}\n\n// ── NestJS decorator routes ────────────────────────────────────────────────\n\n// Collect only route decorators imported by name from `@nestjs/common`.\n// The local name is the key, so `Get as Read` remains deterministic without\n// admitting an unrelated decorator that happens to be named `Get`.\nfunction nestDecoratorImports(root: Parser.SyntaxNode): Map<string, string> {\n  const imports = new Map<string, string>()\n  walk(root, (node) => {\n    if (node.type !== 'import_statement') return\n    const source = node.childForFieldName('source')\n    if (!source || staticStringText(source) !== '@nestjs/common') return\n    walk(node, (child) => {\n      if (child.type !== 'import_specifier') return\n      const imported = child.childForFieldName('name')?.text\n      const local = child.childForFieldName('alias')?.text ?? imported\n      if (!imported || !local) return\n      if (imported === 'Controller' || NESTJS_METHODS.has(imported)) {\n        imports.set(local, imported)\n      }\n    })\n  })\n  return imports\n}\n\nfunction decoratorCall(node: Parser.SyntaxNode): Parser.SyntaxNode | null {\n  if (node.type !== 'decorator') return null\n  const expression = node.namedChild(0)\n  return expression?.type === 'call_expression' ? expression : null\n}\n\nfunction decoratorCanonicalName(\n  decorator: Parser.SyntaxNode,\n  imports: Map<string, string>,\n): string | null {\n  const call = decoratorCall(decorator)\n  const fn = call?.childForFieldName('function')\n  if (!fn || fn.type !== 'identifier') return null\n  return imports.get(fn.text) ?? null\n}\n\n// Nest accepts one path or an array of paths on both Controller and method\n// decorators. Keep only static alternatives; a computed member contributes no\n// guessed route. No argument is the empty path segment.\nfunction nestStaticPaths(call: Parser.SyntaxNode): string[] {\n  const args = call.childForFieldName('arguments')\n  const first = args?.namedChild(0)\n  if (!first) return ['']\n  const single = staticStringText(first)\n  if (single !== null) return [single]\n  if (first.type !== 'array') return []\n  const paths: string[] = []\n  for (let i = 0; i < first.namedChildCount; i++) {\n    const item = first.namedChild(i)\n    if (!item) continue\n    const value = staticStringText(item)\n    if (value !== null) paths.push(value)\n  }\n  return paths\n}\n\nfunction nestJoinedPath(prefix: string, leaf: string): string {\n  const segments = [prefix, leaf]\n    .map((part) => part.replace(/^\\/+|\\/+$/g, ''))\n    .filter((part) => part.length > 0)\n  return canonicalizeTemplate(segments.join('/'))\n}\n\n// Nest composes class-level `@Controller()` metadata with method-level HTTP\n// decorators. The method decorator is the definition site, so its line is the\n// evidence line and matches where a maintainer edits the route.\nexport function nestjsRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  const tree = parseSource(parser, source)\n  const imports = nestDecoratorImports(tree.rootNode)\n  if (![...imports.values()].includes('Controller')) return []\n\n  const out: ExtractedRoute[] = []\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'class_declaration') return\n    const decoratorOwner = node.parent?.type === 'export_statement' ? node.parent : node\n    const classDecorators: Parser.SyntaxNode[] = []\n    for (let i = 0; i < decoratorOwner.namedChildCount; i++) {\n      const child = decoratorOwner.namedChild(i)\n      if (child?.type === 'decorator') classDecorators.push(child)\n    }\n    const controller = classDecorators.find(\n      (decorator) => decoratorCanonicalName(decorator, imports) === 'Controller',\n    )\n    const controllerCall = controller ? decoratorCall(controller) : null\n    if (!controllerCall) return\n    const prefixes = nestStaticPaths(controllerCall)\n    if (prefixes.length === 0) return\n\n    const body = node.childForFieldName('body')\n    if (!body) return\n    for (let i = 0; i < body.namedChildCount; i++) {\n      const methodNode = body.namedChild(i)\n      if (methodNode?.type !== 'method_definition') continue\n      for (let j = 0; j < methodNode.namedChildCount; j++) {\n        const decorator = methodNode.namedChild(j)\n        if (decorator?.type !== 'decorator') continue\n        const canonical = decoratorCanonicalName(decorator, imports)\n        const method = canonical ? NESTJS_METHODS.get(canonical) : undefined\n        const call = decoratorCall(decorator)\n        if (!method || !call) continue\n        const leaves = nestStaticPaths(call)\n        for (const prefix of prefixes) {\n          for (const leaf of leaves) {\n            out.push({\n              method,\n              pathTemplate: nestJoinedPath(prefix, leaf),\n              line: decorator.startPosition.row + 1,\n              framework: 'nestjs',\n            })\n          }\n        }\n      }\n    }\n  })\n  return out\n}\n\n// ── Express / Fastify / Hono call-expression routes ─────────────────────────\n\n// Recognise route registrations of the shape `<router>.<method>('/path', …)`\n// — Express, Fastify, and Hono (`hono.get('/path', handler)` etc.) all share\n// this exact call shape (ADR-133 §5: same registry pattern, Cloudflare\n// Worker's route-grain fast-follow) — and Fastify's own generic\n// `<fastify>.route({ method, url })` form. The guard that keeps this off\n// `db.get('key')` / `_.get(obj, path)` is a string first argument that starts\n// with '/', combined with the caller-side dep gate in addRoutes (only\n// services that depend on express / fastify / hono reach here). This per-file\n// scan captures the leaf path as declared; the Express mount prefix\n// (`app.use('/api', router)`) is composed onto it afterwards by\n// `expressMountPrefixes` (ADR-160), the whole-program pass that resolves the\n// mounted router across files. `.route().get()` chaining and Hono's own\n// `app.on([...methods], '/path', handler)` form remain out of scope for this\n// slice. Coverage grows one router at a time, same discipline as the registry.\nexport function serverRoutesFromSource(\n  source: string,\n  parser: Parser,\n  hasExpress: boolean,\n  hasFastify: boolean,\n  hasHono = false,\n): ExtractedRoute[] {\n  const tree = parseSource(parser, source)\n  const out: ExtractedRoute[] = []\n  const framework = hasExpress ? 'express' : hasFastify ? 'fastify' : hasHono ? 'hono' : 'unknown'\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'call_expression') return\n    const fn = node.childForFieldName('function')\n    if (!fn || fn.type !== 'member_expression') return\n    const prop = fn.childForFieldName('property')\n    if (!prop) return\n    const method = prop.text.toLowerCase()\n    const args = node.childForFieldName('arguments')\n    const first = args?.namedChild(0)\n    if (!first) return\n    const line = node.startPosition.row + 1\n\n    if (ROUTER_METHODS.has(method)) {\n      const p = staticStringText(first)\n      if (p && p.startsWith('/')) {\n        out.push({\n          method: method === 'all' ? 'ALL' : method.toUpperCase(),\n          pathTemplate: canonicalizeTemplate(p),\n          line,\n          framework,\n        })\n      }\n      return\n    }\n\n    // Fastify's generic form: fastify.route({ method, url }).\n    if (method === 'route' && hasFastify && first.type === 'object') {\n      const url = objectStringProp(first, 'url')\n      if (!url || !url.startsWith('/')) return\n      const methods = fastifyRouteMethods(first)\n      const list = methods.length > 0 ? methods : ['ALL']\n      for (const m of list) {\n        out.push({\n          method: m === 'ALL' ? 'ALL' : m.toUpperCase(),\n          pathTemplate: canonicalizeTemplate(url),\n          line,\n          framework: 'fastify',\n        })\n      }\n    }\n  })\n  return out\n}\n\n// ── Next.js file-convention routes ──────────────────────────────────────────\n\nfunction segmentsOf(relFile: string): string[] {\n  return toPosix(relFile).split('/').filter((s) => s.length > 0)\n}\n\n// An app-router route handler file: `<…>/app/**/route.{js,ts,jsx,tsx,…}` (also\n// `src/app`). Route handlers live only in a file literally named `route`.\nexport function isNextAppRouteFile(relFile: string): boolean {\n  const segs = segmentsOf(relFile)\n  if (!segs.includes('app')) return false\n  const base = segs[segs.length - 1] ?? ''\n  return /^route\\.(?:js|jsx|mjs|cjs|ts|tsx)$/.test(base)\n}\n\n// A pages-router API file: `<…>/pages/api/**/*.{js,ts,…}`. Skips Next's special\n// `_app` / `_document` / `_middleware` files, which aren't routes.\nexport function isNextPagesApiFile(relFile: string): boolean {\n  const segs = segmentsOf(relFile)\n  const pagesIdx = segs.indexOf('pages')\n  if (pagesIdx === -1 || segs[pagesIdx + 1] !== 'api') return false\n  const base = segs[segs.length - 1] ?? ''\n  if (/^_(app|document|middleware)\\./.test(base)) return false\n  return JS_ROUTE_EXTENSIONS.has(path.extname(base))\n}\n\n// Convert one Next path segment to its template form: route groups `(group)`\n// drop out, `[...slug]` / `[[...slug]]` catch-alls and `[id]` dynamics become\n// `:name`, everything else stays literal.\nfunction nextSegment(seg: string): string | null {\n  if (seg.startsWith('(') && seg.endsWith(')')) return null // route group — not in the URL\n  const catchAll = seg.match(/^\\[\\[?\\.\\.\\.(.+?)\\]?\\]$/)\n  if (catchAll) return ':' + catchAll[1]\n  const dynamic = seg.match(/^\\[(.+?)\\]$/)\n  if (dynamic) return ':' + dynamic[1]\n  return seg\n}\n\n// Derive the URL path-template from an app-router `route.*` file's directory:\n// `app/users/[id]/route.ts` → `/users/:id`.\nfunction nextAppPathTemplate(relFile: string): string {\n  const segs = segmentsOf(relFile)\n  const appIdx = segs.lastIndexOf('app')\n  const between = segs.slice(appIdx + 1, segs.length - 1) // dirs between app/ and route.*\n  const parts: string[] = []\n  for (const seg of between) {\n    const mapped = nextSegment(seg)\n    if (mapped !== null) parts.push(mapped)\n  }\n  return '/' + parts.join('/')\n}\n\n// Derive the URL path-template from a pages `api/` file:\n// `pages/api/users/[id].ts` → `/api/users/:id`, `pages/api/index.ts` → `/api`.\nfunction nextPagesApiPathTemplate(relFile: string): string {\n  const segs = segmentsOf(relFile)\n  const pagesIdx = segs.indexOf('pages')\n  const rest = segs.slice(pagesIdx + 1) // api/...\n  const parts: string[] = []\n  for (let i = 0; i < rest.length; i++) {\n    let seg = rest[i]!\n    if (i === rest.length - 1) {\n      seg = seg.replace(/\\.(?:js|jsx|mjs|cjs|ts|tsx)$/, '')\n      if (seg === 'index') continue\n    }\n    const mapped = nextSegment(seg)\n    if (mapped !== null) parts.push(mapped)\n  }\n  return '/' + parts.join('/')\n}\n\n// The exported HTTP-method handler names in an app-router `route.*` file:\n// `export async function GET() {}` / `export const POST = …`. Each is one route.\nfunction nextAppMethods(root: Parser.SyntaxNode): { method: string; line: number }[] {\n  const out: { method: string; line: number }[] = []\n  walk(root, (node) => {\n    if (node.type !== 'export_statement') return\n    const decl = node.childForFieldName('declaration')\n    if (!decl) return\n    const line = node.startPosition.row + 1\n    if (decl.type === 'function_declaration') {\n      const name = decl.childForFieldName('name')?.text\n      if (name && NEXT_APP_METHODS.has(name)) out.push({ method: name, line })\n      return\n    }\n    if (decl.type === 'lexical_declaration' || decl.type === 'variable_declaration') {\n      for (let i = 0; i < decl.namedChildCount; i++) {\n        const d = decl.namedChild(i)\n        if (d?.type !== 'variable_declarator') continue\n        const name = d.childForFieldName('name')?.text\n        if (name && NEXT_APP_METHODS.has(name)) out.push({ method: name, line })\n      }\n    }\n  })\n  return out\n}\n\nfunction nextRoutesFromFile(\n  source: string,\n  relFile: string,\n  parser: Parser,\n): ExtractedRoute[] {\n  if (isNextAppRouteFile(relFile)) {\n    const tree = parseSource(parser, source)\n    const template = nextAppPathTemplate(relFile)\n    return nextAppMethods(tree.rootNode).map(({ method, line }) => ({\n      method,\n      pathTemplate: canonicalizeTemplate(template),\n      line,\n      framework: 'next',\n    }))\n  }\n  if (isNextPagesApiFile(relFile)) {\n    // A pages API handler is the module's default export and serves every\n    // method — recorded as a single method-agnostic route.\n    return [\n      {\n        method: 'ALL',\n        pathTemplate: canonicalizeTemplate(nextPagesApiPathTemplate(relFile)),\n        line: 1,\n        framework: 'next',\n      },\n    ]\n  }\n  return []\n}\n\n// ── Python / FastAPI decorator routes ───────────────────────────────────────\n\n// The interior text of a Python string literal, stripped of quotes. Returns\n// null for an f-string carrying interpolation (a route path is a static\n// literal); returns '' for an empty string (no `string_content` child).\nfunction pyStaticStringText(node: Parser.SyntaxNode): string | null {\n  if (node.type !== 'string') return null\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (child?.type === 'interpolation') return null // f-string — not a static path\n    if (child?.type === 'string_content') return child.text\n  }\n  return ''\n}\n\n// Read a keyword argument whose value is a list of string literals:\n// `methods=['GET','POST']` → ['GET','POST']. Anything else → [].\nfunction keywordArrayStrings(argsNode: Parser.SyntaxNode, key: string): string[] {\n  for (let i = 0; i < argsNode.namedChildCount; i++) {\n    const arg = argsNode.namedChild(i)\n    if (arg?.type !== 'keyword_argument') continue\n    if (arg.childForFieldName('name')?.text !== key) continue\n    const val = arg.childForFieldName('value')\n    if (!val || val.type !== 'list') return []\n    const out: string[] = []\n    for (let j = 0; j < val.namedChildCount; j++) {\n      const el = val.namedChild(j)\n      if (el?.type === 'string') {\n        const s = pyStaticStringText(el)\n        if (s) out.push(s)\n      }\n    }\n    return out\n  }\n  return []\n}\n\n// Map an in-file router/blueprint variable to its declared literal prefix:\n// FastAPI `router = APIRouter(prefix='/items')` → { router: '/items' }, Flask\n// `bp = Blueprint('x', __name__, url_prefix='/api')` → { bp: '/api' }. Handles\n// bare and dotted constructors (`fastapi.APIRouter(...)`), the prefix kwarg in\n// any position. A prefix built from a config symbol or an f-string\n// (`prefix=settings.API_V1_STR`) stays unmapped — the router contributes no\n// prefix rather than a guessed one, and the leaf-relative path is kept honestly.\nfunction collectPythonRouterPrefixes(root: Parser.SyntaxNode): Map<string, string> {\n  const prefixes = new Map<string, string>()\n  walk(root, (node) => {\n    if (node.type !== 'assignment') return\n    const right = node.childForFieldName('right')\n    if (!right || right.type !== 'call') return\n    const fn = right.childForFieldName('function')\n    if (!fn) return\n    const ctor = fn.type === 'attribute' ? fn.childForFieldName('attribute')?.text : fn.text\n    // FastAPI's APIRouter names its mount `prefix`; Flask's Blueprint names it\n    // `url_prefix`. Any other constructor contributes no prefix.\n    const prefixKey = ctor === 'APIRouter' ? 'prefix' : ctor === 'Blueprint' ? 'url_prefix' : null\n    if (!prefixKey) return\n    const left = node.childForFieldName('left')\n    if (!left || left.type !== 'identifier') return\n    const args = right.childForFieldName('arguments')\n    if (!args) return\n    for (let i = 0; i < args.namedChildCount; i++) {\n      const arg = args.namedChild(i)\n      if (arg?.type !== 'keyword_argument') continue\n      if (arg.childForFieldName('name')?.text !== prefixKey) continue\n      const val = arg.childForFieldName('value')\n      const p = val ? pyStaticStringText(val) : null\n      if (p !== null) prefixes.set(left.text, p)\n    }\n  })\n  return prefixes\n}\n\n// Module-level string constants, for resolving a mount prefix given as a symbol\n// (`prefix=API_V1_STR` or `prefix=settings.API_V1_STR`) rather than a literal.\nfunction collectStringConstants(root: Parser.SyntaxNode): Map<string, string> {\n  const consts = new Map<string, string>()\n  walk(root, (node) => {\n    if (node.type !== 'assignment') return\n    const left = node.childForFieldName('left')\n    const right = node.childForFieldName('right')\n    if (left?.type !== 'identifier' || right?.type !== 'string') return\n    const v = pyStaticStringText(right)\n    if (v !== null) consts.set(left.text, v)\n  })\n  return consts\n}\n\n// Resolve a mount-prefix argument: a literal string, a bare constant\n// (`API_V1_STR`), or an attribute (`settings.API_V1_STR`) whose trailing name is\n// a known in-file constant. Anything else → null (unmapped, kept honest).\nfunction resolvePrefixArg(node: Parser.SyntaxNode | null, consts: Map<string, string>): string | null {\n  if (!node) return null\n  if (node.type === 'string') return pyStaticStringText(node)\n  if (node.type === 'identifier') return consts.get(node.text) ?? null\n  if (node.type === 'attribute') {\n    const attr = node.childForFieldName('attribute')?.text\n    return attr ? (consts.get(attr) ?? null) : null\n  }\n  return null\n}\n\n// In-file mounts — `app.include_router(<router>, prefix=<p>)` (FastAPI) and\n// `app.register_blueprint(<bp>, url_prefix=<p>)` (Flask). Maps the mounted\n// router/blueprint variable to its resolved mount prefix, so a route on that\n// router carries the mounted path. A cross-file mount (the router imported from\n// another module) and nested `include_router` chains are a follow-on — the\n// one-level prefix is composed, honestly.\nfunction collectMountPrefixes(\n  root: Parser.SyntaxNode,\n  consts: Map<string, string>,\n): Map<string, string> {\n  const mounts = new Map<string, string>()\n  walk(root, (node) => {\n    if (node.type !== 'call') return\n    const fn = node.childForFieldName('function')\n    if (fn?.type !== 'attribute') return\n    const method = fn.childForFieldName('attribute')?.text\n    const prefixKey =\n      method === 'include_router' ? 'prefix' : method === 'register_blueprint' ? 'url_prefix' : null\n    if (!prefixKey) return\n    const args = node.childForFieldName('arguments')\n    const first = args?.namedChild(0)\n    if (first?.type !== 'identifier') return // only a bare in-file router var\n    let prefix: string | null = null\n    for (let i = 0; i < (args?.namedChildCount ?? 0); i++) {\n      const a = args!.namedChild(i)\n      if (a?.type !== 'keyword_argument') continue\n      if (a.childForFieldName('name')?.text !== prefixKey) continue\n      prefix = resolvePrefixArg(a.childForFieldName('value'), consts)\n    }\n    if (prefix !== null && prefix.length > 0) mounts.set(first.text, prefix)\n  })\n  return mounts\n}\n\n// The decorator forms `<router>.<verb>('/path')` (FastAPI + Flask 2.0 shortcuts),\n// FastAPI's `<router>.api_route('/path', methods=[…])`, and Flask's\n// `<router>.route('/path', methods=[…])` (default GET). `<router>` is the app, an\n// APIRouter, or a Blueprint; the path is the first positional string, read off\n// the call's argument list (so a multi-line decorator still lands). A route's\n// full path composes the in-file mount prefix (`app.include_router(r,\n// prefix='/api/v1')`, resolving a config constant) + the router's own\n// `APIRouter(prefix='/x')` / `Blueprint(url_prefix='/x')` + the decorator path.\n// The declared template keeps its `{id}` params verbatim so an OBSERVED server\n// span's `http.route` lands on the same node.\n//\n// Out of scope, deferred like express `app.use('/api', router)`: cross-file /\n// nested mounting. The one-level, in-file prefix is composed as-is.\nexport function pythonRoutesFromSource(\n  source: string,\n  parser: Parser,\n  framework: string,\n): ExtractedRoute[] {\n  const tree = parseSource(parser, source)\n  const prefixes = collectPythonRouterPrefixes(tree.rootNode)\n  const consts = collectStringConstants(tree.rootNode)\n  const mounts = collectMountPrefixes(tree.rootNode, consts)\n  const out: ExtractedRoute[] = []\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'decorator') return\n    const call = node.namedChild(0)\n    if (!call || call.type !== 'call') return\n    const fn = call.childForFieldName('function')\n    if (!fn || fn.type !== 'attribute') return\n    const method = fn.childForFieldName('attribute')?.text?.toLowerCase()\n    if (!method) return\n    const isVerb = FASTAPI_METHODS.has(method)\n    const isFlaskRoute = method === 'route' // Flask `.route(...)`, defaults to GET\n    const isApiRoute = method === 'api_route' // FastAPI multi-method\n    if (!isVerb && !isFlaskRoute && !isApiRoute) return\n\n    const args = call.childForFieldName('arguments')\n    const first = args?.namedChild(0)\n    if (!first || first.type !== 'string') return\n    const rawPath = pyStaticStringText(first)\n    if (rawPath === null || !rawPath.startsWith('/')) return\n\n    const obj = fn.childForFieldName('object')?.text\n    const routerPrefix = obj ? (prefixes.get(obj) ?? '') : ''\n    const mountPrefix = obj ? (mounts.get(obj) ?? '') : ''\n    const pathTemplate = canonicalizeTemplate(mountPrefix + routerPrefix + rawPath)\n    const line = node.startPosition.row + 1\n\n    if (isVerb) {\n      out.push({ method: method.toUpperCase(), pathTemplate, line, framework })\n      return\n    }\n    // `.route` (Flask, default GET) / `.api_route` (FastAPI) — one route per method.\n    const methods = keywordArrayStrings(args!, 'methods')\n    const list = methods.length > 0 ? methods : isFlaskRoute ? ['GET'] : ['ALL']\n    for (const m of list) {\n      out.push({ method: m === 'ALL' ? 'ALL' : m.toUpperCase(), pathTemplate, line, framework })\n    }\n  })\n  return out\n}\n\n// Back-compat alias — FastAPI is the framework-labelled specialisation.\nexport function fastapiRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  return pythonRoutesFromSource(source, parser, 'fastapi')\n}\n\n// Django URLconf routes — `urlpatterns = [path('orders/<int:pk>/', view), …]`.\n// Django dispatches HTTP methods inside the view, not at the URLconf, so a route\n// is method-agnostic (`ALL`). Only the modern `path()` converter form is\n// recognised; an `include(...)` mount (cross-file, the Python analog of express\n// `app.use`) and legacy `re_path` regex patterns are a follow-on. The `<int:pk>`\n// converter param is kept verbatim and collapses to `:param` at match time.\nexport function djangoRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  const tree = parseSource(parser, source)\n  const out: ExtractedRoute[] = []\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'assignment') return\n    if (node.childForFieldName('left')?.text !== 'urlpatterns') return\n    const list = node.childForFieldName('right')\n    if (!list || list.type !== 'list') return\n    for (let i = 0; i < list.namedChildCount; i++) {\n      const el = list.namedChild(i)\n      if (el?.type !== 'call') continue\n      if (el.childForFieldName('function')?.text !== 'path') continue // path() only\n      const args = el.childForFieldName('arguments')\n      const first = args?.namedChild(0)\n      if (first?.type !== 'string') continue\n      const raw = pyStaticStringText(first)\n      if (raw === null) continue\n      // Skip an `include(...)` mount — cross-file, deferred.\n      const second = args?.namedChild(1)\n      if (second?.type === 'call' && second.childForFieldName('function')?.text === 'include') continue\n      out.push({\n        method: 'ALL',\n        pathTemplate: canonicalizeTemplate(raw),\n        line: el.startPosition.row + 1,\n        framework: 'django',\n      })\n    }\n  })\n  return out\n}\n\n// ── Rails config/routes.rb routes (ADR-173) ─────────────────────────────────\n//\n// Reads a Rails router table out of `config/routes.rb` and emits a RouteNode per\n// (HTTP method, path template). Explicit verb routes and `root` are read from\n// the source directly; `resources`/`resource` fan out through Rails' resourceful\n// expansion, `namespace`/`scope` contribute a path and/or a controller-module\n// prefix, `member`/`collection` add routes to the enclosing resource, and one\n// level of nesting stamps the parent's `:<singular>_id` param onto the child.\n//\n// The declared template keeps Rails' `:id` form verbatim: the action_pack OTel\n// instrumentation (Rails ≥ 7.1) sets `http.route` to exactly that string with\n// the trailing `(.:format)` stripped, and `normalizePathTemplate` already\n// collapses every `:word` segment to `:param`, so a route-grain server span\n// fuses onto this node with no normalisation. What can't be resolved statically\n// — routes.rb metaprogramming, `draw(:file)` split files, mounted engines,\n// `constraints`, nesting past one level — is left out rather than guessed; those\n// routes still appear at runtime, as an honest observed-but-not-declared\n// divergence rather than a wrong RouteNode.\n\nconst RAILS_VERBS = new Set(['get', 'post', 'put', 'patch', 'delete', 'options', 'head'])\n\n// The member routes a `resources` (plural) declaration fans out to. `update`\n// lands on both PATCH and PUT — Rails registers both and a runtime request can\n// carry either. `new`/`edit` are the form-rendering GETs.\ninterface ResourceRow {\n  action: string\n  methods: string[]\n  suffix: string\n}\nconst RAILS_PLURAL_ROWS: ResourceRow[] = [\n  { action: 'index', methods: ['GET'], suffix: '' },\n  { action: 'new', methods: ['GET'], suffix: '/new' },\n  { action: 'create', methods: ['POST'], suffix: '' },\n  { action: 'show', methods: ['GET'], suffix: '/:id' },\n  { action: 'edit', methods: ['GET'], suffix: '/:id/edit' },\n  { action: 'update', methods: ['PATCH', 'PUT'], suffix: '/:id' },\n  { action: 'destroy', methods: ['DELETE'], suffix: '/:id' },\n]\n// The singular `resource` set — no index and no `:id` segment (there is only ever\n// one), and the controller is pluralised (`resource :profile` → `profiles`).\nconst RAILS_SINGULAR_ROWS: ResourceRow[] = [\n  { action: 'new', methods: ['GET'], suffix: '/new' },\n  { action: 'create', methods: ['POST'], suffix: '' },\n  { action: 'show', methods: ['GET'], suffix: '' },\n  { action: 'edit', methods: ['GET'], suffix: '/edit' },\n  { action: 'update', methods: ['PATCH', 'PUT'], suffix: '' },\n  { action: 'destroy', methods: ['DELETE'], suffix: '' },\n]\n\n// Minimal English inflection — enough for the common resource names. Rails uses\n// ActiveSupport's fuller irregular table; a resource's own path segments are the\n// literal symbol it declares, so only the derived controller name and the nested\n// `:<singular>_id` param depend on this — and the param name never affects fusion\n// (`normalizePathTemplate` collapses any `:word` to `:param`). Irregular plurals\n// (person/people) are a later refinement, not a fusion risk.\nfunction railsPluralize(word: string): string {\n  if (/[^aeiou]y$/i.test(word)) return word.slice(0, -1) + 'ies'\n  if (/(s|x|z|ch|sh)$/i.test(word)) return word + 'es'\n  return word + 's'\n}\nfunction railsSingularize(word: string): string {\n  if (/ies$/i.test(word)) return word.slice(0, -3) + 'y'\n  if (/(x|z|ch|sh)es$/i.test(word)) return word.slice(0, -2)\n  if (/s$/i.test(word) && !/ss$/i.test(word)) return word.slice(0, -1)\n  return word\n}\n\n// The interior text of a Ruby string literal, or a symbol's name without its\n// leading colon (`:orders` → 'orders'). Returns null for an interpolated string\n// (it carries a child that isn't `string_content`) — a route path or handler is\n// a static literal.\nfunction rubyLiteral(node: Parser.SyntaxNode | null | undefined): string | null {\n  if (!node) return null\n  if (node.type === 'simple_symbol') return node.text.replace(/^:/, '')\n  if (node.type === 'string') {\n    let text = ''\n    let sawContent = false\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (!child) continue\n      if (child.type === 'string_content' || child.type === 'escape_sequence') {\n        text += child.text\n        sawContent = true\n      } else {\n        return null // interpolation or anything non-literal\n      }\n    }\n    return sawContent ? text : '' // an empty string literal has no content child\n  }\n  return null\n}\n\nfunction rubyArgs(call: Parser.SyntaxNode): Parser.SyntaxNode | null {\n  return call.childForFieldName('arguments')\n}\n\n// The positional (non-`pair`) arguments of a call, in order.\nfunction rubyPositional(args: Parser.SyntaxNode | null): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  if (!args) return out\n  for (let i = 0; i < args.namedChildCount; i++) {\n    const c = args.namedChild(i)\n    if (c && c.type !== 'pair') out.push(c)\n  }\n  return out\n}\n\n// The value node of a keyword argument `key: …` — a `pair` whose key is a\n// `hash_key_symbol` with the given name.\nfunction rubyKwarg(args: Parser.SyntaxNode | null, key: string): Parser.SyntaxNode | null {\n  if (!args) return null\n  for (let i = 0; i < args.namedChildCount; i++) {\n    const pair = args.namedChild(i)\n    if (!pair || pair.type !== 'pair') continue\n    const k = pair.childForFieldName('key')\n    if (k?.type === 'hash_key_symbol' && k.text === key) return pair.childForFieldName('value')\n  }\n  return null\n}\n\nfunction rubyKwargText(args: Parser.SyntaxNode | null, key: string): string | null {\n  return rubyLiteral(rubyKwarg(args, key))\n}\n\n// The hash-rocket verb shorthand `get 'path' => 'controller#action'` — a `pair`\n// whose key is a string literal. Returns the path and the handler target.\nfunction rubyRocketRoute(\n  args: Parser.SyntaxNode | null,\n): { path: string; target: string | null } | null {\n  if (!args) return null\n  for (let i = 0; i < args.namedChildCount; i++) {\n    const pair = args.namedChild(i)\n    if (!pair || pair.type !== 'pair') continue\n    const k = pair.childForFieldName('key')\n    if (k?.type !== 'string') continue\n    const path = rubyLiteral(k)\n    if (path === null) continue\n    return { path, target: rubyLiteral(pair.childForFieldName('value')) }\n  }\n  return null\n}\n\n// The statement `call` nodes directly inside a `do … end` block. tree-sitter-ruby\n// wraps multiple statements in a `body_statement`; fall back to the block's own\n// direct children for the single-statement shape.\nfunction rubyBlockCalls(block: Parser.SyntaxNode | null): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  if (!block) return out\n  const pushCalls = (n: Parser.SyntaxNode): void => {\n    for (let i = 0; i < n.namedChildCount; i++) {\n      const c = n.namedChild(i)\n      if (c?.type === 'call') out.push(c)\n    }\n  }\n  let sawBody = false\n  for (let i = 0; i < block.namedChildCount; i++) {\n    const c = block.namedChild(i)\n    if (c?.type === 'body_statement') {\n      pushCalls(c)\n      sawBody = true\n    }\n  }\n  if (!sawBody) pushCalls(block)\n  return out\n}\n\n// Join an accumulated prefix with a leaf path, tolerating a leading slash on the\n// leaf. `canonicalizeTemplate` finishes the job (leading slash, no trailing).\nfunction railsJoin(prefix: string, leaf: string): string {\n  return prefix + '/' + leaf.replace(/^\\/+/, '')\n}\n\nfunction railsEmit(\n  out: ExtractedRoute[],\n  method: string,\n  rawPath: string,\n  controller: string | null,\n  line: number,\n): void {\n  out.push({\n    method,\n    pathTemplate: canonicalizeTemplate(rawPath === '' ? '/' : rawPath),\n    line,\n    framework: 'rails',\n    ...(controller ? { controller } : {}),\n  })\n}\n\n// `only:` / `except:` restrict a resource's emitted action set. A value is a\n// single symbol (`except: :destroy`) or an array (`only: [:index, :show]`).\nfunction railsActionFilter(args: Parser.SyntaxNode | null): (action: string) => boolean {\n  const collect = (key: string): Set<string> | null => {\n    const val = rubyKwarg(args, key)\n    if (!val) return null\n    const set = new Set<string>()\n    if (val.type === 'array') {\n      for (let i = 0; i < val.namedChildCount; i++) {\n        const name = rubyLiteral(val.namedChild(i))\n        if (name) set.add(name)\n      }\n    } else {\n      const name = rubyLiteral(val)\n      if (name) set.add(name)\n    }\n    return set\n  }\n  const only = collect('only')\n  const except = collect('except')\n  return (action: string) =>\n    (only ? only.has(action) : true) && (except ? !except.has(action) : true)\n}\n\n// A bare `get :recent` verb inside a resource block — emits one route relative to\n// `pathBase` (a member path carries `:id`, a collection path does not).\nfunction railsSingleVerb(\n  verb: Parser.SyntaxNode,\n  pathBase: string,\n  controller: string,\n  out: ExtractedRoute[],\n): void {\n  const vm = verb.childForFieldName('method')?.text\n  if (!vm || !RAILS_VERBS.has(vm)) return\n  const action = rubyLiteral(rubyPositional(rubyArgs(verb))[0])\n  if (action === null) return\n  railsEmit(out, vm.toUpperCase(), railsJoin(pathBase, action), `${controller}#${action}`, verb.startPosition.row + 1)\n}\n\n// The `member do … end` / `collection do … end` verb lists inside a resource.\nfunction railsBlockVerbs(\n  call: Parser.SyntaxNode,\n  pathBase: string,\n  controller: string,\n  out: ExtractedRoute[],\n): void {\n  for (const verb of rubyBlockCalls(call.childForFieldName('block'))) {\n    railsSingleVerb(verb, pathBase, controller, out)\n  }\n}\n\ninterface RailsCtx {\n  path: string // accumulated path prefix, '' at the draw root, no trailing slash\n  module: string // accumulated controller-module prefix, '' or e.g. 'admin/'\n  depth: number // resource-nesting depth; 0 at the top level\n}\n\n// An explicit verb route: `get '/x', to: 'c#a'`, the hash-rocket `get 'x' => 'c#a'`,\n// or a bare `get 'about'` (handler inferred `about#index`-style).\nfunction railsVerbRoute(\n  call: Parser.SyntaxNode,\n  method: string,\n  ctx: RailsCtx,\n  out: ExtractedRoute[],\n  line: number,\n): void {\n  const args = rubyArgs(call)\n  let rawPath: string | null\n  let target: string | null\n  const rocket = rubyRocketRoute(args)\n  if (rocket) {\n    rawPath = rocket.path\n    target = rocket.target\n  } else {\n    rawPath = rubyLiteral(rubyPositional(args)[0])\n    target = rubyKwargText(args, 'to')\n  }\n  if (rawPath === null) return\n  if (target === null) target = railsInferHandler(rawPath)\n  railsEmit(out, method, railsJoin(ctx.path, rawPath), target ? ctx.module + target : null, line)\n}\n\n// Infer a `controller#action` for a bare verb route with no `to:`: a single\n// segment maps to `<segment>#index`, a multi-segment path splits the last off as\n// the action. Handler metadata only — the path template is what fuses.\nfunction railsInferHandler(rawPath: string): string {\n  const segs = rawPath\n    .replace(/^\\/+|\\/+$/g, '')\n    .split('/')\n    .filter((s) => s.length > 0 && !s.startsWith(':'))\n  if (segs.length === 0) return 'index'\n  if (segs.length === 1) return `${segs[0]}#index`\n  return `${segs.slice(0, -1).join('/')}#${segs[segs.length - 1]}`\n}\n\n// `resources :orders` (plural) / `resource :profile` (singular) — Rails'\n// resourceful expansion, plus the resource's own `member`/`collection`/nested\n// block. One level of nesting is composed; deeper nesting is deferred.\nfunction railsResource(\n  call: Parser.SyntaxNode,\n  ctx: RailsCtx,\n  out: ExtractedRoute[],\n  plural: boolean,\n): void {\n  if (ctx.depth >= 2) return // one level of nesting only (ADR-173)\n  const args = rubyArgs(call)\n  const name = rubyLiteral(rubyPositional(args)[0])\n  if (!name) return\n  const base = `${ctx.path}/${name}`\n  const controller = ctx.module + (plural ? name : railsPluralize(name))\n  const allow = railsActionFilter(args)\n  const line = call.startPosition.row + 1\n\n  for (const row of plural ? RAILS_PLURAL_ROWS : RAILS_SINGULAR_ROWS) {\n    if (!allow(row.action)) continue\n    for (const m of row.methods) railsEmit(out, m, base + row.suffix, `${controller}#${row.action}`, line)\n  }\n\n  const block = call.childForFieldName('block')\n  if (!block) return\n  const memberBase = plural ? `${base}/:id` : base // a singular member has no :id\n  const nestedPath = plural ? `${base}/:${railsSingularize(name)}_id` : base\n  for (const child of rubyBlockCalls(block)) {\n    const cm = child.childForFieldName('method')?.text\n    if (cm === 'member') railsBlockVerbs(child, memberBase, controller, out)\n    else if (cm === 'collection') railsBlockVerbs(child, base, controller, out)\n    else if (cm && RAILS_VERBS.has(cm)) railsSingleVerb(child, base, controller, out)\n    else if (cm === 'resources' || cm === 'resource' || cm === 'namespace' || cm === 'scope') {\n      railsProcess([child], { path: nestedPath, module: ctx.module, depth: ctx.depth + 1 }, out)\n    }\n    // concerns, member-less helpers, etc. — deferred\n  }\n}\n\n// Walk a list of routes.rb statements in a routing context, dispatching each\n// `call` on its method name.\nfunction railsProcess(statements: Parser.SyntaxNode[], ctx: RailsCtx, out: ExtractedRoute[]): void {\n  for (const call of statements) {\n    const method = call.childForFieldName('method')?.text\n    if (!method) continue\n    const args = rubyArgs(call)\n    const line = call.startPosition.row + 1\n\n    if (method === 'root') {\n      const target = rubyKwargText(args, 'to') ?? rubyLiteral(rubyPositional(args)[0])\n      railsEmit(out, 'GET', ctx.path || '/', target ? ctx.module + target : null, line)\n      continue\n    }\n    if (RAILS_VERBS.has(method)) {\n      railsVerbRoute(call, method.toUpperCase(), ctx, out, line)\n      continue\n    }\n    if (method === 'resources' || method === 'resource') {\n      railsResource(call, ctx, out, method === 'resources')\n      continue\n    }\n    if (method === 'namespace') {\n      const name = rubyLiteral(rubyPositional(args)[0])\n      if (!name) continue\n      railsProcess(rubyBlockCalls(call.childForFieldName('block')), {\n        path: `${ctx.path}/${name}`,\n        module: `${ctx.module}${name}/`,\n        depth: ctx.depth,\n      }, out)\n      continue\n    }\n    if (method === 'scope') {\n      // A positional string/symbol scopes the path; `path:`/`module:` scope each\n      // axis explicitly. A `scope module: 'admin'` shifts only the controller\n      // module, leaving the URL unchanged — the case only the handler shows.\n      const scopePath = rubyKwargText(args, 'path') ?? rubyLiteral(rubyPositional(args)[0])\n      const scopeModule = rubyKwargText(args, 'module')\n      railsProcess(rubyBlockCalls(call.childForFieldName('block')), {\n        path: scopePath ? railsJoin(ctx.path, scopePath) : ctx.path,\n        module: scopeModule ? `${ctx.module}${scopeModule}/` : ctx.module,\n        depth: ctx.depth,\n      }, out)\n      continue\n    }\n    // mount, constraints, `%i[…].each { resources … }`, concerns — deferred.\n  }\n}\n\n// Read `config/routes.rb`: find the `Rails.application.routes.draw do … end`\n// block and expand its body. `draw(:file)` split-route files carry no block and\n// are deferred.\nexport function railsRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  const tree = parseSource(parser, source)\n  const out: ExtractedRoute[] = []\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'call') return\n    if (node.childForFieldName('method')?.text !== 'draw') return\n    const block = node.childForFieldName('block')\n    if (!block) return\n    railsProcess(rubyBlockCalls(block), { path: '', module: '', depth: 0 }, out)\n  })\n  return out\n}\n\n// ── Ruby Sinatra routes (ADR-206) ───────────────────────────────────────────\n//\n// Sinatra declares a route with a bare verb DSL call carrying a string pattern\n// and a block — `post '/send_order_confirmation' do … end`, `get '/health' do …\n// end`. The call has no receiver (it sends to the app `self`), the verb is the\n// HTTP method, and the first argument is the path. Unlike Rails' single\n// conventional `config/routes.rb`, a Sinatra app declares routes throughout its\n// source, so this reads every `.rb` file and self-gates two ways: the file must\n// itself reference Sinatra (a `require 'sinatra'` or a `Sinatra::Base`\n// superclass), AND each call must be the receiver-less verb-with-string-path-and-\n// block shape. That is the precision that keeps a bare `get` / `post` method call\n// in unrelated Ruby (an HTTP client, a config setting) from minting a route.\n//\n// The declared template keeps Sinatra's `:id` param form verbatim: the Rack /\n// Sinatra OTel instrumentation sets `http.route` to the matched pattern, and\n// `normalizePathTemplate` collapses every `:word` segment to `:param`, so a\n// route-grain server span fuses onto this node with no ingest change. Gated per\n// service on the `sinatra` gem (extract/ruby.ts's Gemfile reader). Regex routes,\n// `Sinatra::Namespace` prefix composition, and routes in files that don't\n// themselves reference Sinatra are deferred — those surface as an honest\n// observed-but-not-declared divergence rather than a fabricated node.\n\nconst SINATRA_VERBS = new Set(['get', 'post', 'put', 'patch', 'delete', 'options', 'head'])\n\nexport function sinatraRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  const tree = parseSource(parser, source)\n  if (!fileReferencesSinatra(tree.rootNode)) return []\n  const out: ExtractedRoute[] = []\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'call') return\n    if (node.childForFieldName('receiver')) return // a receiver'd call is not the bare DSL\n    const method = node.childForFieldName('method')?.text\n    if (!method || !SINATRA_VERBS.has(method)) return\n    if (!node.childForFieldName('block')) return // a Sinatra route always takes a block\n    const first = node.childForFieldName('arguments')?.namedChild(0)\n    if (first?.type !== 'string') return // a regex / symbol pattern is not read\n    const p = rubyLiteral(first)\n    if (p === null || !p.startsWith('/')) return\n    out.push({\n      method: method.toUpperCase(),\n      pathTemplate: canonicalizeTemplate(p),\n      line: node.startPosition.row + 1,\n      framework: 'sinatra',\n    })\n  })\n  return out\n}\n\n// Whether the file references Sinatra — a `require` / `require_relative` of a\n// `sinatra…` path, or a `Sinatra`(`::Base`) constant (the modular-app\n// superclass). The file-level precision gate: a `.rb` file in a Sinatra service\n// that names no route surface (a model, an initializer) reads no routes.\nfunction fileReferencesSinatra(root: Parser.SyntaxNode): boolean {\n  let found = false\n  walk(root, (node) => {\n    if (found) return\n    if (node.type === 'call') {\n      const m = node.childForFieldName('method')?.text\n      if (m === 'require' || m === 'require_relative') {\n        const s = rubyLiteral(node.childForFieldName('arguments')?.namedChild(0))\n        if (s !== null && /^sinatra\\b/.test(s)) found = true\n      }\n      return\n    }\n    if (\n      (node.type === 'constant' && node.text === 'Sinatra') ||\n      (node.type === 'scope_resolution' && node.text.startsWith('Sinatra'))\n    ) {\n      found = true\n    }\n  })\n  return found\n}\n\n// ── Laravel routes/web.php + routes/api.php (ADR-177) ───────────────────────\n//\n// Reads a Laravel router table out of `routes/web.php` and `routes/api.php` and\n// emits a RouteNode per (HTTP method, path template). Explicit verb routes\n// (`Route::get('/orders/{id}', …)`) are read from the source directly;\n// `Route::resource`/`apiResource` fan out through Laravel's resourceful\n// convention; `Route::prefix('admin')->group(…)` (and the `middleware`,\n// `controller`, `name` group forms) compose a path prefix across nesting; and\n// every route in `routes/api.php` gets the automatic `/api` prefix the framework\n// adds (it isn't in the source), passed in as the base prefix.\n//\n// The declared template keeps Laravel's `{id}` form verbatim: Laravel's\n// OpenTelemetry auto-instrumentation sets `http.route` to exactly the templated\n// URI (`orders/{id}` for a request to `/orders/42`), and `normalizePathTemplate`\n// already drops the leading slash and collapses every `{…}` segment to `:param`,\n// so a route-grain server span fuses onto this node with no ingest change.\n//\n// Deferred (ADR-177): Symfony entirely — its OTel emits the route NAME, not the\n// path, so it needs a distinct extractor + ingest name-join; `config/routes.yaml`;\n// controller-array handler resolution beyond the template; `match`, `redirect`,\n// `view`, `fallback`, singleton and domain routing; and resource `->only`/`->except`\n// filtering. Those routes surface as observed-but-not-declared divergence rather\n// than a fabricated node.\n\nconst LARAVEL_VERBS = new Set(['get', 'post', 'put', 'patch', 'delete', 'options'])\n\n// The rows a `Route::resource` fans out to — Laravel's convention, reimplemented\n// (it isn't in the source text). `{param}` is the singularized resource name;\n// `update` lands on both PUT and PATCH, since Laravel registers both and a\n// runtime request can carry either. `apiResource` drops the two form-rendering\n// GETs (`create`, `edit`).\ninterface LaravelResourceRow {\n  action: string\n  methods: string[]\n  suffix: string\n}\nconst LARAVEL_RESOURCE_ROWS: LaravelResourceRow[] = [\n  { action: 'index', methods: ['GET'], suffix: '' },\n  { action: 'create', methods: ['GET'], suffix: '/create' },\n  { action: 'store', methods: ['POST'], suffix: '' },\n  { action: 'show', methods: ['GET'], suffix: '/{param}' },\n  { action: 'edit', methods: ['GET'], suffix: '/{param}/edit' },\n  { action: 'update', methods: ['PUT', 'PATCH'], suffix: '/{param}' },\n  { action: 'destroy', methods: ['DELETE'], suffix: '/{param}' },\n]\nconst LARAVEL_API_RESOURCE_SKIP = new Set(['create', 'edit'])\n\n// A deliberately simple singularizer — strip one trailing `s`. The resource param\n// is DISPLAY ONLY: `normalizePathTemplate` collapses every `{…}` segment to\n// `:param` before fusion, so `{photo}` vs `{photos}` never changes the matching\n// key (ADR-177). Reproducing Laravel's fuller inflection isn't a fusion\n// requirement, so the cheap rule stands.\nfunction laravelSingularize(word: string): string {\n  return word.endsWith('s') ? word.slice(0, -1) : word\n}\n\n// The interior text of a PHP single-quoted `string` or double-quoted\n// `encapsed_string`, or null when it carries interpolation (a route path is a\n// static literal). An empty literal returns ''.\nfunction phpStaticString(node: Parser.SyntaxNode | null | undefined): string | null {\n  if (!node) return null\n  if (node.type !== 'string' && node.type !== 'encapsed_string') return null\n  let text = ''\n  let sawContent = false\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (!child) continue\n    if (child.type === 'string_content') {\n      text += child.text\n      sawContent = true\n    } else {\n      return null // interpolation / escape / anything non-literal\n    }\n  }\n  return sawContent ? text : ''\n}\n\n// The value nodes of a call's positional arguments. tree-sitter-php wraps each in\n// an `argument`; the value is its last named child (a PHP-8 named argument\n// `name: value` carries a `name` field that precedes the value).\nfunction phpArgumentValues(argsNode: Parser.SyntaxNode | null | undefined): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  if (!argsNode) return out\n  for (let i = 0; i < argsNode.namedChildCount; i++) {\n    const arg = argsNode.namedChild(i)\n    if (!arg || arg.type !== 'argument') continue\n    const val = arg.namedChild(arg.namedChildCount - 1)\n    if (val) out.push(val)\n  }\n  return out\n}\n\n// The first positional argument as a static string (the route path / resource\n// name), or null.\nfunction phpFirstString(argsNode: Parser.SyntaxNode | null | undefined): string | null {\n  const vals = phpArgumentValues(argsNode)\n  return vals.length > 0 ? phpStaticString(vals[0]) : null\n}\n\n// Join path parts into a canonical `/`-leading, no-trailing-slash template,\n// trimming any embedded leading/trailing slashes on each part (Laravel's own\n// prefix-composition discipline). An empty set of parts is the root, `/`.\nfunction laravelJoinPath(...parts: string[]): string {\n  const segs: string[] = []\n  for (const part of parts) {\n    for (const s of part.split('/')) {\n      if (s.length > 0) segs.push(s)\n    }\n  }\n  return '/' + segs.join('/')\n}\n\ninterface LaravelSeg {\n  method: string\n  args: Parser.SyntaxNode | null\n  node: Parser.SyntaxNode\n}\n\n// Flatten a `Route::…->…->…` fluent chain into its ordered (method, args)\n// segments, innermost first. `Route::prefix('admin')->group(fn)` →\n// [prefix, group]; a bare `Route::get('/x')` → [get]. Returns null when the chain\n// doesn't root at the `Route` facade (bare, leading-backslash, or the\n// fully-qualified `Illuminate\\Support\\Facades\\Route`).\nfunction laravelUnrollChain(node: Parser.SyntaxNode): LaravelSeg[] | null {\n  const segs: LaravelSeg[] = []\n  let cur: Parser.SyntaxNode | null = node\n  while (cur && cur.type === 'member_call_expression') {\n    const name = cur.childForFieldName('name')?.text\n    if (!name) return null\n    segs.unshift({ method: name, args: cur.childForFieldName('arguments'), node: cur })\n    cur = cur.childForFieldName('object')\n  }\n  if (!cur || cur.type !== 'scoped_call_expression') return null\n  const method = cur.childForFieldName('name')?.text\n  if (!method) return null\n  segs.unshift({ method, args: cur.childForFieldName('arguments'), node: cur })\n  const scopeText = cur.childForFieldName('scope')?.text ?? ''\n  const rooted = scopeText === 'Route' || scopeText.endsWith('\\\\Route')\n  return rooted ? segs : null\n}\n\n// The closure a `->group(…)` call carries — a `function () { … }`\n// (`anonymous_function_creation_expression`) or a `fn () => …` (`arrow_function`).\nfunction laravelGroupClosure(argsNode: Parser.SyntaxNode | null): Parser.SyntaxNode | null {\n  for (const v of phpArgumentValues(argsNode)) {\n    if (v.type === 'anonymous_function_creation_expression' || v.type === 'arrow_function') return v\n  }\n  return null\n}\n\n// The route-call statements inside a group closure body — a `{ … }` block of\n// `expression_statement`s, or a single-expression arrow body.\nfunction laravelClosureCalls(closure: Parser.SyntaxNode): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  const push = (n: Parser.SyntaxNode | null): void => {\n    if (n && (n.type === 'member_call_expression' || n.type === 'scoped_call_expression')) out.push(n)\n  }\n  const body = closure.childForFieldName('body')\n  if (!body) return out\n  if (closure.type === 'arrow_function') {\n    push(body)\n    return out\n  }\n  for (let i = 0; i < body.namedChildCount; i++) {\n    const stmt = body.namedChild(i)\n    if (stmt?.type === 'expression_statement') push(stmt.namedChild(0))\n  }\n  return out\n}\n\nfunction laravelEmit(out: ExtractedRoute[], method: string, rawPath: string, line: number): void {\n  // An optional param `{id?}` drops its `?` so the stored template stays clean —\n  // `canonicalizeTemplate` reads a literal `?` as a query-string delimiter and\n  // would truncate `/users/{id?}` to `/users/{id`. Fusion is unaffected either\n  // way (`normalizePathTemplate` collapses every `{…}` segment to `:param`); this\n  // only keeps the declared template readable and honest.\n  const cleaned = rawPath.replace(/\\{([^}?]+)\\?\\}/g, '{$1}')\n  out.push({\n    method,\n    pathTemplate: canonicalizeTemplate(cleaned === '' ? '/' : cleaned),\n    line,\n    framework: 'laravel',\n  })\n}\n\n// `Route::resource('photos', …)` / `apiResource` — Laravel's resourceful\n// expansion. A dotted name (`photos.comments`) composes into a nested path with\n// the parent param stamped on (`/photos/{photo}/comments/{comment}`), best-effort.\nfunction laravelResource(\n  seg: LaravelSeg,\n  prefix: string,\n  out: ExtractedRoute[],\n  api: boolean,\n): void {\n  const name = phpFirstString(seg.args)\n  if (name === null || name.length === 0) return\n  const line = seg.node.startPosition.row + 1\n  const parts = name.split('.')\n  const leaf = parts[parts.length - 1]!\n  let base = prefix\n  for (let i = 0; i < parts.length - 1; i++) {\n    base = laravelJoinPath(base, parts[i]!, `{${laravelSingularize(parts[i]!)}}`)\n  }\n  base = laravelJoinPath(base, leaf)\n  const param = laravelSingularize(leaf)\n  for (const row of LARAVEL_RESOURCE_ROWS) {\n    if (api && LARAVEL_API_RESOURCE_SKIP.has(row.action)) continue\n    const suffix = row.suffix.replace('{param}', `{${param}}`)\n    const template = laravelJoinPath(base, suffix)\n    for (const m of row.methods) laravelEmit(out, m, template, line)\n  }\n}\n\n// Process one `Route::…` statement in a routing context (the accumulated path\n// prefix). A `->group(…)` composes its `prefix('x')` contributions onto the\n// prefix and recurses into the closure; a verb emits a route; `any` is a\n// method-agnostic `ALL`; `resource`/`apiResource` fan out. Per-route modifiers\n// chained after a verb (`->name(…)`, `->where(…)`, `->middleware(…)`) don't\n// change the template, so they fall out — the verb sits at the base of the chain.\nfunction laravelProcessCall(callNode: Parser.SyntaxNode, prefix: string, out: ExtractedRoute[]): void {\n  const segs = laravelUnrollChain(callNode)\n  if (!segs) return\n\n  const groupSeg = segs.find((s) => s.method === 'group')\n  if (groupSeg) {\n    let composed = prefix\n    for (const s of segs) {\n      if (s === groupSeg) break\n      if (s.method === 'prefix') {\n        const p = phpFirstString(s.args)\n        if (p !== null) composed = laravelJoinPath(composed, p)\n      }\n    }\n    const closure = laravelGroupClosure(groupSeg.args)\n    if (!closure) return\n    for (const child of laravelClosureCalls(closure)) {\n      laravelProcessCall(child, composed, out)\n    }\n    return\n  }\n\n  const base = segs[0]!\n  const line = base.node.startPosition.row + 1\n  if (LARAVEL_VERBS.has(base.method)) {\n    const p = phpFirstString(base.args)\n    if (p === null) return\n    laravelEmit(out, base.method.toUpperCase(), laravelJoinPath(prefix, p), line)\n    return\n  }\n  if (base.method === 'any') {\n    const p = phpFirstString(base.args)\n    if (p === null) return\n    laravelEmit(out, 'ALL', laravelJoinPath(prefix, p), line)\n    return\n  }\n  if (base.method === 'resource' || base.method === 'apiResource') {\n    laravelResource(base, prefix, out, base.method === 'apiResource')\n  }\n}\n\n// Read `routes/web.php` (no prefix) or `routes/api.php` (`basePrefix` = '/api',\n// the framework's automatic prefix, not in the source). Walk the top-level route\n// statements; groups nest and are recursed into explicitly.\nexport function laravelRoutesFromSource(\n  source: string,\n  parser: Parser,\n  basePrefix = '',\n): ExtractedRoute[] {\n  const tree = parseSource(parser, source)\n  const out: ExtractedRoute[] = []\n  const root = tree.rootNode\n  for (let i = 0; i < root.namedChildCount; i++) {\n    const stmt = root.namedChild(i)\n    if (stmt?.type !== 'expression_statement') continue\n    const call = stmt.namedChild(0)\n    if (call && (call.type === 'member_call_expression' || call.type === 'scoped_call_expression')) {\n      laravelProcessCall(call, basePrefix, out)\n    }\n  }\n  return out\n}\n\n// ── PHP Slim routes (ADR-206) ───────────────────────────────────────────────\n//\n// Slim declares routes on its `App` value — `$app->post('/getquote', …)`,\n// `$app->get(…)`, the multi-method `$app->map(['GET','POST'], '/x', …)`, the\n// method-agnostic `$app->any('/x', …)`, and route groups `$app->group('/prefix',\n// function ($group) { $group->get('/y', …) })` whose prefix composes across\n// nesting. Unlike Laravel's two conventional files, a Slim app has no fixed route\n// location, so this reads every `.php` file and self-gates on finding a Slim App\n// value in the file: a variable assigned from `AppFactory::create()` (Slim 4) or\n// `new …App` (Slim 3), OR a function/closure parameter typed `Slim\\App` — the Slim\n// skeleton (which the otel-demo `quote` service uses) builds the app in\n// `public/index.php` and registers its routes in a separate `app/routes.php` that\n// returns `function (App $app) { $app->post('/getquote', …) }`, so the route file\n// never constructs the app and the `App` type hint is the local gate. Either way a\n// `$x->get('key')` on some other, untyped object never mints a route. Inside a group\n// closure the proxy parameter (and `$this`, which Slim binds to the app in the\n// closure form) joins the app-var set for that scope only, so a nested\n// `$group->get(…)` composes the group prefix.\n//\n// The declared template keeps Slim's `{id}` param form verbatim: the Slim OTel\n// instrumentation sets `http.route` to the matched pattern (`/getquote`), and\n// `normalizePathTemplate` collapses every `{…}` segment to `:param`, so a\n// route-grain server span fuses onto this node with no ingest change. Gated per\n// service on the `slim/slim` dependency (extract/php.ts's composer.json reader).\n// Cross-file route registration where the route file gives no local Slim signal\n// (the app is neither constructed nor `App`-typed in it) and controller-array\n// handlers are deferred — those routes surface as an honest observed-but-not-declared\n// divergence rather than a fabricated node.\n\nconst SLIM_VERBS = new Set(['get', 'post', 'put', 'patch', 'delete', 'options', 'head'])\n\n// Whether a PHP expression constructs a Slim `App` — `AppFactory::create()` (the\n// Slim 4 idiom) or `new \\Slim\\App(...)` / `new App(...)` (Slim 3). Keys the app-var\n// set the route reader scopes to; gated on slim/slim already, so a bare `App` in a\n// Slim service is the framework app.\nfunction isSlimAppCtor(node: Parser.SyntaxNode | null | undefined): boolean {\n  if (!node) return false\n  if (node.type === 'scoped_call_expression') {\n    const scope = node.childForFieldName('scope')?.text ?? ''\n    const name = node.childForFieldName('name')?.text\n    return name === 'create' && (scope === 'AppFactory' || scope.endsWith('\\\\AppFactory'))\n  }\n  if (node.type === 'object_creation_expression') {\n    const cls = node.namedChild(0)?.text ?? ''\n    return cls === 'App' || cls.endsWith('\\\\App') || cls.includes('Slim')\n  }\n  return false\n}\n\n// Whether a parameter type hint names the Slim `App` — `App` (imported via `use\n// Slim\\App`), the qualified `Slim\\App`, or the fully-qualified `\\Slim\\App`. Same\n// precision bar as the object-creation branch of `isSlimAppCtor` (`=== 'App'` or a\n// trailing `\\App`): a bare `App` in a slim/slim-gated service is the framework app.\nfunction isSlimAppType(node: Parser.SyntaxNode | null | undefined): boolean {\n  if (!node || node.type !== 'named_type') return false\n  const text = node.text\n  return text === 'App' || text.endsWith('\\\\App')\n}\n\n// The Slim app variables a file declares — a `$app = AppFactory::create()` style\n// assignment, OR a function/closure parameter typed `Slim\\App`. The second form is\n// the Slim skeleton (the shape the otel-demo `quote` service uses): `public/index.php`\n// builds the app and `app/routes.php` returns `function (App $app) { $app->post(…) }`,\n// so the route file never constructs the app — the `App` type hint on the passed-in\n// `$app` is the only local Slim signal, and an authoritative one. The route reader\n// treats only these vars (plus a group closure's proxy param) as routers, which is\n// the file-level precision gate.\nfunction collectSlimAppVars(root: Parser.SyntaxNode): Set<string> {\n  const vars = new Set<string>()\n  walk(root, (node) => {\n    if (node.type === 'assignment_expression') {\n      const left = node.childForFieldName('left')\n      if (left?.type === 'variable_name' && isSlimAppCtor(node.childForFieldName('right'))) {\n        vars.add(left.text)\n      }\n      return\n    }\n    if (node.type === 'simple_parameter' && isSlimAppType(node.childForFieldName('type'))) {\n      const name = node.childForFieldName('name')\n      if (name?.type === 'variable_name') vars.add(name.text)\n    }\n  })\n  return vars\n}\n\n// The variable names a group closure binds as its router proxy — the closure's\n// formal parameters, plus `$this` (Slim binds the closure to the app). Scoped to\n// that closure only.\nfunction slimClosureParamVars(closure: Parser.SyntaxNode): string[] {\n  const out: string[] = ['$this']\n  for (let i = 0; i < closure.namedChildCount; i++) {\n    const params = closure.namedChild(i)\n    if (params?.type !== 'formal_parameters') continue\n    for (let j = 0; j < params.namedChildCount; j++) {\n      const param = params.namedChild(j)\n      if (param?.type !== 'simple_parameter') continue\n      for (let k = 0; k < param.namedChildCount; k++) {\n        const v = param.namedChild(k)\n        if (v?.type === 'variable_name') {\n          out.push(v.text)\n          break\n        }\n      }\n    }\n  }\n  return out\n}\n\n// The string literals in a PHP array literal `['GET','POST']` — the methods a\n// Slim `->map([...], …)` names. A non-string / interpolated element is skipped.\nfunction phpStringArray(node: Parser.SyntaxNode | null | undefined): string[] {\n  const out: string[] = []\n  if (node?.type !== 'array_creation_expression') return out\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const el = node.namedChild(i)\n    if (el?.type !== 'array_element_initializer') continue\n    const s = phpStaticString(el.namedChild(0))\n    if (s !== null) out.push(s)\n  }\n  return out\n}\n\nexport function slimRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  const tree = parseSource(parser, source)\n  const appVars = collectSlimAppVars(tree.rootNode)\n  if (appVars.size === 0) return [] // no Slim app in this file — nothing to read\n  const out: ExtractedRoute[] = []\n  slimWalk(tree.rootNode, '', appVars, out)\n  return out\n}\n\nfunction slimWalk(\n  node: Parser.SyntaxNode,\n  prefix: string,\n  appVars: Set<string>,\n  out: ExtractedRoute[],\n): void {\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (child) slimHandle(child, prefix, appVars, out)\n  }\n}\n\nfunction slimHandle(\n  node: Parser.SyntaxNode,\n  prefix: string,\n  appVars: Set<string>,\n  out: ExtractedRoute[],\n): void {\n  if (node.type === 'member_call_expression') {\n    const obj = node.childForFieldName('object')\n    const method = node.childForFieldName('name')?.text\n    const args = node.childForFieldName('arguments')\n    if (obj?.type === 'variable_name' && method && appVars.has(obj.text)) {\n      const line = node.startPosition.row + 1\n\n      if (method === 'group') {\n        const groupPrefix = phpFirstString(args)\n        const closure = laravelGroupClosure(args)\n        if (groupPrefix !== null && closure) {\n          const inner = new Set(appVars)\n          for (const v of slimClosureParamVars(closure)) inner.add(v)\n          const body = closure.childForFieldName('body')\n          if (body) slimWalk(body, laravelJoinPath(prefix, groupPrefix), inner, out)\n        }\n        return\n      }\n      if (SLIM_VERBS.has(method)) {\n        const p = phpFirstString(args)\n        if (p !== null) {\n          out.push({\n            method: method.toUpperCase(),\n            pathTemplate: laravelJoinPath(prefix, p),\n            line,\n            framework: 'slim',\n          })\n        }\n        return\n      }\n      if (method === 'any') {\n        const p = phpFirstString(args)\n        if (p !== null) {\n          out.push({ method: 'ALL', pathTemplate: laravelJoinPath(prefix, p), line, framework: 'slim' })\n        }\n        return\n      }\n      if (method === 'map') {\n        const vals = phpArgumentValues(args)\n        const methods = phpStringArray(vals[0])\n        const p = vals.length > 1 ? phpStaticString(vals[1]) : null\n        if (p !== null) {\n          for (const m of methods) {\n            out.push({\n              method: m.toUpperCase(),\n              pathTemplate: laravelJoinPath(prefix, p),\n              line,\n              framework: 'slim',\n            })\n          }\n        }\n        return\n      }\n      // Any other method on the app var (`->run()`, `->add()`,\n      // `->addErrorMiddleware()`) carries no route — fall through and descend, so a\n      // route call chained onto it (`$app->get(…)->setName(…)`) is still reached.\n    }\n  }\n  slimWalk(node, prefix, appVars, out)\n}\n\n// ── Rust Actix-Web routes (ADR-206) ─────────────────────────────────────────\n//\n// Actix-Web declares a route two ways, and this reads both. The idiomatic form is\n// an attribute macro on the handler fn — `#[post(\"/ship-order\")]`,\n// `#[get(\"/get-quote\")]`, or the multi-method `#[route(\"/x\", method = \"GET\",\n// method = \"POST\")]` — where the macro NAME is the HTTP method and its first\n// string literal is the path; the handler is then wired in with\n// `.service(handler)`, which carries no path of its own (the macro already did),\n// so `.service` needs no separate read. The second form is the builder\n// `App::new().route(\"/health\", web::get().to(handler))`, where the path is the\n// first argument and the method is the `web::<verb>()` in the second — a bare\n// `web::route()` (method-agnostic) or a `.route(...)` whose method doesn't resolve\n// to a known verb mints nothing, so a generic `.route` in unrelated code can't\n// manufacture a route.\n//\n// The declared template keeps Actix's `{id}` param form verbatim: the actix-web\n// OTel instrumentation sets `http.route` to the matched pattern, and\n// `normalizePathTemplate` collapses every `{…}` segment to `:param`, so a\n// route-grain server span fuses onto this node with no ingest change. Gated per\n// service on the `actix-web` dependency (extract/rust.ts's Cargo reader), the same\n// manifest gate Gin/Echo/Fiber use; an attribute / `.route` idiom in a non-Actix\n// Rust service never reaches here. Scope-, resource-, and `web::scope(\"/prefix\")`\n// prefix composition is deferred — those routes surface as an honest\n// observed-but-not-declared divergence rather than a fabricated node.\n\nconst ACTIX_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'])\n\n// The inner text of a Rust string literal (`\"…\"`), quotes stripped, via its\n// `string_content` child. An empty `\"\"` literal (no content child) returns '';\n// a non-string node returns null.\nfunction rustStringContent(node: Parser.SyntaxNode | null | undefined): string | null {\n  if (!node || node.type !== 'string_literal') return null\n  for (let i = 0; i < node.namedChildCount; i++) {\n    if (node.namedChild(i)?.type === 'string_content') return node.namedChild(i)!.text\n  }\n  return ''\n}\n\nexport function actixRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  const tree = parseSource(parser, source)\n  const out: ExtractedRoute[] = []\n  walk(tree.rootNode, (node) => {\n    if (node.type === 'attribute_item') {\n      actixAttributeRoute(node, out)\n      return\n    }\n    if (node.type === 'call_expression') {\n      actixBuilderRoute(node, out)\n    }\n  })\n  return out\n}\n\n// An attribute-macro route `#[post(\"/x\")]` / `#[route(\"/x\", method = \"GET\", …)]`.\n// The macro name is the HTTP method (a verb macro) or the multi-method `route`;\n// the first string literal in the macro's token tree is the path.\nfunction actixAttributeRoute(attrItem: Parser.SyntaxNode, out: ExtractedRoute[]): void {\n  const attr = attrItem.namedChild(0)\n  if (!attr || attr.type !== 'attribute') return\n  const nameNode = attr.namedChild(0)\n  if (!nameNode) return\n  // The macro name — `post` (a bare identifier) or `actix_web::post` (scoped, its\n  // trailing segment the verb).\n  const macro =\n    nameNode.type === 'identifier'\n      ? nameNode.text\n      : nameNode.type === 'scoped_identifier'\n        ? (nameNode.childForFieldName('name')?.text ?? null)\n        : null\n  if (!macro) return\n  const tokens = attr.childForFieldName('arguments')\n  if (!tokens || tokens.type !== 'token_tree') return\n\n  const strings: string[] = []\n  for (let i = 0; i < tokens.namedChildCount; i++) {\n    const s = rustStringContent(tokens.namedChild(i))\n    if (s !== null) strings.push(s)\n  }\n  const pathStr = strings[0]\n  if (pathStr === undefined || !pathStr.startsWith('/')) return\n  const line = attrItem.startPosition.row + 1\n  const template = canonicalizeTemplate(pathStr)\n\n  if (ACTIX_METHODS.has(macro)) {\n    out.push({ method: macro.toUpperCase(), pathTemplate: template, line, framework: 'actix-web' })\n    return\n  }\n  if (macro === 'route') {\n    // `#[route(\"/x\", method = \"GET\", method = \"POST\")]` — the method values are\n    // the `\"GET\"`/`\"POST\"` string literals after the path; a `guard = \"…\"` string\n    // that isn't a known verb is filtered out. No method resolved → method-agnostic.\n    const methods = strings.slice(1).filter((m) => ACTIX_METHODS.has(m.toLowerCase()))\n    const list = methods.length > 0 ? methods.map((m) => m.toUpperCase()) : ['ALL']\n    for (const m of list) {\n      out.push({ method: m, pathTemplate: template, line, framework: 'actix-web' })\n    }\n  }\n}\n\n// A builder route `<App>.route(\"/x\", web::get().to(h))`. The path is the first\n// argument; the method is the `web::<verb>()` named in the second. Mints only when\n// a known verb resolves, so a bare `web::route()` or a non-Actix `.route(...)` is\n// left alone.\nfunction actixBuilderRoute(call: Parser.SyntaxNode, out: ExtractedRoute[]): void {\n  const fn = call.childForFieldName('function')\n  if (fn?.type !== 'field_expression') return\n  if (fn.childForFieldName('field')?.text !== 'route') return\n  const args = call.childForFieldName('arguments')\n  const pathStr = rustStringContent(args?.namedChild(0))\n  if (pathStr === null || !pathStr.startsWith('/')) return\n  const second = args?.namedChild(1)\n  if (!second) return\n  const method = actixBuilderMethod(second)\n  if (!method) return\n  out.push({\n    method,\n    pathTemplate: canonicalizeTemplate(pathStr),\n    line: call.startPosition.row + 1,\n    framework: 'actix-web',\n  })\n}\n\n// Resolve the HTTP method a `.route(...)` second argument declares by finding the\n// `web::<verb>()` call in it (`web::post().to(h)` → POST). Returns null when no\n// known verb is named (a bare `web::route()` or a non-builder expression), so the\n// caller mints nothing rather than guessing.\nfunction actixBuilderMethod(node: Parser.SyntaxNode): string | null {\n  let method: string | null = null\n  walk(node, (n) => {\n    if (method || n.type !== 'scoped_identifier') return\n    const verb = n.childForFieldName('name')?.text\n    const scopeLeaf = n.childForFieldName('path')?.text?.split('::').pop()\n    if (scopeLeaf === 'web' && verb && ACTIX_METHODS.has(verb)) method = verb.toUpperCase()\n  })\n  return method\n}\n\n// ── Express cross-file mount-prefix composition (ADR-160) ───────────────────\n\n// Real Express apps mount a router under a prefix — `app.use('/api', router)` —\n// with the router and its routes defined in other files. The per-file scan above\n// captures each leaf path (`/tags`) without the prefix, so a production span for\n// `/api/tags` never fuses onto the static route. This whole-program pass composes\n// the prefix onto the routes it mounts, resolving the mounted router across files\n// through the same import graph `imports.ts` walks (the ADR-149 mechanism the\n// Mongoose cross-file pass established).\n//\n// The discipline is the ADR-149 discipline: a prefix that isn't a `/`-leading\n// string literal (a config symbol or computed expression), or a mounted router\n// that resolves to no file, leaves the leaf path un-prefixed rather than guessing.\n// A route at the wrong grain is an honest partial; a fabricated one is not.\n\n// One `<router>.use(<prefix>, <mounted>)` mount. `prefix` is '' when the router is\n// mounted at root (`app.use(router)`); `target` is the mounted binding's local\n// name, or null when the argument isn't a bare identifier (middleware, a computed\n// prefix followed by a router, a factory call — none of which we compose).\ninterface Mount {\n  prefix: string\n  target: string | null\n}\n\ninterface RouterVarInfo {\n  declares: boolean // has a direct `<var>.get('/…')` route call\n  mounts: Mount[] // the routers this var mounts, via `.use()`\n  aliasOf?: string // `const r2 = r1` — r2 is r1 under another name\n}\n\ninterface RawBinding {\n  local: string\n  specifier: string\n  sel: string // 'default' | 'namespace' | an export name\n}\n\ninterface FileRouterInfo {\n  dir: string // absolute directory of the file, for import resolution\n  routerVars: Map<string, RouterVarInfo>\n  appVars: Set<string> // vars bound to `express()` — the recursion roots\n  exportDefaultName: string | null // routerVars key the default export resolves to\n  exportNamed: Map<string, string> // export name → routerVars key\n  rawBindings: RawBinding[] // imports, before cross-file resolution\n  importedRouters: Map<string, { file: string; sel: string }> // local → target file + export\n}\n\n// The named arguments of a call, comments skipped.\nfunction namedArgs(argsNode: Parser.SyntaxNode | null | undefined): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  if (!argsNode) return out\n  for (let i = 0; i < argsNode.namedChildCount; i++) {\n    const c = argsNode.namedChild(i)\n    if (c && c.type !== 'comment') out.push(c)\n  }\n  return out\n}\n\n// Parse a `.use(...)` call into a Mount, or null when it mounts no resolvable\n// router. `.use('/api', router)` → prefix '/api'; `.use(router)` → prefix '';\n// `.use(cors())` / `.use(PREFIX, router)` / `.use(mw, router)` → null. A computed\n// (non-literal) prefix is deliberately dropped — we compose only a literal one.\nfunction parseUseMount(callNode: Parser.SyntaxNode): Mount | null {\n  const args = namedArgs(callNode.childForFieldName('arguments'))\n  if (args.length === 0) return null\n  const first = args[0]!\n  const firstStr =\n    first.type === 'string' || first.type === 'template_string' ? staticStringText(first) : null\n  if (firstStr !== null && firstStr.startsWith('/')) {\n    const prefix = canonicalizeTemplate(firstStr)\n    const second = args[1]\n    const target = second && second.type === 'identifier' ? second.text : null\n    return { prefix: prefix === '/' ? '' : prefix, target }\n  }\n  // A single bare identifier is a router mounted at root (`app.use(router)`).\n  // Two args led by an identifier is a computed prefix or a middleware — not\n  // something we can compose, so we leave it alone.\n  if (args.length === 1 && first.type === 'identifier') return { prefix: '', target: first.text }\n  return null\n}\n\n// Unwrap a router expression to its base and the `.use()` mounts chained onto it.\n// `Router().use(a).use('/x', b)` → base 'newRouter', mounts [a, /x→b]; `express()`\n// → base 'app'; a bare `router` identifier → base { alias: 'router' }. Returns\n// null when the expression isn't a router value.\nfunction unwrapRouterExpr(\n  node: Parser.SyntaxNode,\n  expressLocals: Set<string>,\n  routerCtors: Set<string>,\n): { base: 'app' | 'newRouter' | { alias: string }; mounts: Mount[] } | null {\n  if (node.type === 'identifier') return { base: { alias: node.text }, mounts: [] }\n  if (node.type !== 'call_expression') return null\n  const fn = node.childForFieldName('function')\n  if (!fn) return null\n\n  if (fn.type === 'member_expression') {\n    const prop = fn.childForFieldName('property')?.text\n    const obj = fn.childForFieldName('object')\n    if (!prop || !obj) return null\n    if (prop === 'use') {\n      const inner = unwrapRouterExpr(obj, expressLocals, routerCtors)\n      if (!inner) return null\n      const mount = parseUseMount(node)\n      return { base: inner.base, mounts: mount ? [...inner.mounts, mount] : inner.mounts }\n    }\n    // `express.Router()`\n    if (prop === 'Router' && obj.type === 'identifier' && expressLocals.has(obj.text)) {\n      return { base: 'newRouter', mounts: [] }\n    }\n    return null\n  }\n\n  if (fn.type === 'identifier') {\n    if (expressLocals.has(fn.text)) return { base: 'app', mounts: [] } // express()\n    if (routerCtors.has(fn.text)) return { base: 'newRouter', mounts: [] } // Router()\n  }\n  return null\n}\n\n// Import bindings + which locals name express() / the Router ctor. Both ESM\n// (`import express, { Router } from 'express'`) and CJS (`const { Router } =\n// require('express')`) forms.\nfunction collectExpressImports(root: Parser.SyntaxNode): {\n  expressLocals: Set<string>\n  routerCtors: Set<string>\n  bindings: RawBinding[]\n} {\n  const expressLocals = new Set<string>()\n  const routerCtors = new Set<string>()\n  const bindings: RawBinding[] = []\n\n  const addFromExpress = (local: string, sel: string, exported: string): void => {\n    if (sel === 'default' || sel === 'namespace') expressLocals.add(local)\n    else if (exported === 'Router') routerCtors.add(local)\n  }\n\n  walk(root, (node) => {\n    if (node.type === 'import_statement') {\n      const source = node.childForFieldName('source')\n      const spec = source ? staticStringText(source) : null\n      if (!spec) return\n      let clause: Parser.SyntaxNode | null = null\n      for (let i = 0; i < node.namedChildCount; i++) {\n        const c = node.namedChild(i)\n        if (c?.type === 'import_clause') clause = c\n      }\n      if (!clause) return\n      for (let i = 0; i < clause.namedChildCount; i++) {\n        const c = clause.namedChild(i)\n        if (!c) continue\n        if (c.type === 'identifier') {\n          if (spec === 'express') addFromExpress(c.text, 'default', 'default')\n          else bindings.push({ local: c.text, specifier: spec, sel: 'default' })\n        } else if (c.type === 'namespace_import') {\n          const id = c.namedChild(0)\n          if (id?.type === 'identifier') {\n            if (spec === 'express') addFromExpress(id.text, 'namespace', 'namespace')\n            else bindings.push({ local: id.text, specifier: spec, sel: 'namespace' })\n          }\n        } else if (c.type === 'named_imports') {\n          for (let j = 0; j < c.namedChildCount; j++) {\n            const s = c.namedChild(j)\n            if (s?.type !== 'import_specifier') continue\n            const name = s.childForFieldName('name')?.text\n            if (!name) continue\n            const local = s.childForFieldName('alias')?.text ?? name\n            if (spec === 'express') addFromExpress(local, name, name)\n            else bindings.push({ local, specifier: spec, sel: name })\n          }\n        }\n      }\n      return\n    }\n\n    if (node.type === 'variable_declarator') {\n      const value = node.childForFieldName('value')\n      if (value?.type !== 'call_expression') return\n      const fn = value.childForFieldName('function')\n      if (fn?.type !== 'identifier' || fn.text !== 'require') return\n      const arg = namedArgs(value.childForFieldName('arguments'))[0]\n      const spec = arg ? staticStringText(arg) : null\n      if (!spec) return\n      const name = node.childForFieldName('name')\n      if (name?.type === 'identifier') {\n        if (spec === 'express') expressLocals.add(name.text)\n        else bindings.push({ local: name.text, specifier: spec, sel: 'default' }) // require = module.exports\n      } else if (name?.type === 'object_pattern') {\n        for (let i = 0; i < name.namedChildCount; i++) {\n          const el = name.namedChild(i)\n          if (!el) continue\n          let local: string | undefined\n          let exported: string | undefined\n          if (el.type === 'shorthand_property_identifier_pattern') {\n            local = el.text\n            exported = el.text\n          } else if (el.type === 'pair_pattern') {\n            exported = el.childForFieldName('key')?.text\n            local = el.childForFieldName('value')?.text ?? exported\n          }\n          if (!local || !exported) continue\n          if (spec === 'express') addFromExpress(local, exported, exported)\n          else bindings.push({ local, specifier: spec, sel: exported })\n        }\n      }\n    }\n  })\n\n  return { expressLocals, routerCtors, bindings }\n}\n\n// Analyse one file's router topology: which vars are routers, what each mounts,\n// which declare routes, and what the file exports.\nfunction analyzeExpressFile(root: Parser.SyntaxNode, dir: string): FileRouterInfo {\n  const { expressLocals, routerCtors, bindings } = collectExpressImports(root)\n  const routerVars = new Map<string, RouterVarInfo>()\n  const appVars = new Set<string>()\n  const exportNamed = new Map<string, string>()\n  let exportDefaultName: string | null = null\n\n  const getVar = (name: string): RouterVarInfo => {\n    let rv = routerVars.get(name)\n    if (!rv) {\n      rv = { declares: false, mounts: [] }\n      routerVars.set(name, rv)\n    }\n    return rv\n  }\n\n  // Resolve an exported expression to a routerVars key. A bare identifier names\n  // a var directly; a `Router().use(...)` chain becomes a synthetic entry keyed\n  // `key`, so every export is expressible as a var reference.\n  const refFromExpr = (expr: Parser.SyntaxNode, key: string): string | null => {\n    if (expr.type === 'identifier') return expr.text\n    const u = unwrapRouterExpr(expr, expressLocals, routerCtors)\n    if (!u) return null\n    const rv = getVar(key)\n    for (const m of u.mounts) rv.mounts.push(m)\n    if (typeof u.base === 'object') rv.aliasOf = u.base.alias\n    return key\n  }\n\n  const isExported = (declarator: Parser.SyntaxNode): boolean => {\n    const decl = declarator.parent // lexical_declaration / variable_declaration\n    return decl?.parent?.type === 'export_statement'\n  }\n\n  walk(root, (node) => {\n    if (node.type === 'variable_declarator') {\n      const value = node.childForFieldName('value')\n      const name = node.childForFieldName('name')\n      if (name?.type !== 'identifier' || !value) return\n      if (value.type === 'call_expression') {\n        const fn = value.childForFieldName('function')\n        if (fn?.type === 'identifier' && fn.text === 'require') return // an import, handled above\n      }\n      const u = unwrapRouterExpr(value, expressLocals, routerCtors)\n      if (!u) return\n      const rv = getVar(name.text)\n      for (const m of u.mounts) rv.mounts.push(m)\n      if (u.base === 'app') appVars.add(name.text)\n      else if (typeof u.base === 'object') rv.aliasOf = u.base.alias\n      if (isExported(node)) exportNamed.set(name.text, name.text)\n      return\n    }\n\n    if (node.type === 'call_expression') {\n      const fn = node.childForFieldName('function')\n      if (fn?.type !== 'member_expression') return\n      const obj = fn.childForFieldName('object')\n      const prop = fn.childForFieldName('property')?.text\n      if (obj?.type !== 'identifier' || !prop) return\n      if (prop === 'use') {\n        const m = parseUseMount(node)\n        if (m) getVar(obj.text).mounts.push(m)\n      } else if (ROUTER_METHODS.has(prop.toLowerCase())) {\n        const first = namedArgs(node.childForFieldName('arguments'))[0]\n        const p = first ? staticStringText(first) : null\n        if (p !== null && p.startsWith('/')) getVar(obj.text).declares = true\n      }\n      return\n    }\n\n    if (node.type === 'export_statement') {\n      // Named clause: `export { router, r as default }`.\n      let clause: Parser.SyntaxNode | null = null\n      for (let i = 0; i < node.namedChildCount; i++) {\n        const c = node.namedChild(i)\n        if (c?.type === 'export_clause') clause = c\n      }\n      if (clause) {\n        for (let i = 0; i < clause.namedChildCount; i++) {\n          const spec = clause.namedChild(i)\n          if (spec?.type !== 'export_specifier') continue\n          const local = spec.childForFieldName('name')?.text\n          if (!local) continue\n          const exportedAs = spec.childForFieldName('alias')?.text ?? local\n          if (exportedAs === 'default') exportDefaultName = local\n          else exportNamed.set(exportedAs, local)\n        }\n        return\n      }\n      // `export const NAME = …` — the declarator handler registers it.\n      if (node.childForFieldName('declaration')) return\n      // `export default <expr>`.\n      for (let i = 0; i < node.namedChildCount; i++) {\n        const c = node.namedChild(i)\n        if (c && c.type !== 'export_clause') {\n          exportDefaultName = refFromExpr(c, '#default')\n          break\n        }\n      }\n      return\n    }\n\n    if (node.type === 'assignment_expression') {\n      const left = node.childForFieldName('left')\n      const right = node.childForFieldName('right')\n      if (left?.type !== 'member_expression' || !right) return\n      const lobj = left.childForFieldName('object')?.text\n      const lprop = left.childForFieldName('property')?.text\n      if (lobj === 'module' && lprop === 'exports') exportDefaultName = refFromExpr(right, '#default')\n      else if (lobj === 'exports' && lprop) {\n        const key = refFromExpr(right, `#exp:${lprop}`)\n        if (key) exportNamed.set(lprop, key)\n      }\n    }\n  })\n\n  return {\n    dir,\n    routerVars,\n    appVars,\n    exportDefaultName,\n    exportNamed,\n    rawBindings: bindings,\n    importedRouters: new Map(),\n  }\n}\n\n/**\n * Whole-program pass (ADR-160): compose Express cross-file mount prefixes onto\n * the routes they mount. Returns a map from a route-declaring file's\n * service-relative path to the prefix its routes serve under — e.g. a controller\n * mounted through `app.use(routes)` → `Router().use('/api', api)` → `.use(ctrl)`\n * lands `'/api'`. Files with no composed prefix are absent (their leaf paths\n * stand as declared). `files` should be the service's source files; only Express\n * `.js`/`.ts` files are analysed.\n */\nexport async function expressMountPrefixes(\n  files: SourceFile[],\n  serviceDir: string,\n  tsPaths: TsPathConfig | null,\n): Promise<Map<string, string>> {\n  const jsParser = makeJsParser()\n  const fileInfo = new Map<string, FileRouterInfo>()\n\n  for (const f of files) {\n    if (!JS_ROUTE_EXTENSIONS.has(path.extname(f.path))) continue\n    if (isTestPath(f.path)) continue\n    const rel = toPosix(path.relative(serviceDir, f.path))\n    try {\n      const tree = parseSource(jsParser, f.content)\n      fileInfo.set(rel, analyzeExpressFile(tree.rootNode, path.dirname(f.path)))\n    } catch {\n      // A file that won't parse contributes no mounts; leave its routes bare.\n    }\n  }\n  if (fileInfo.size === 0) return new Map()\n\n  // Resolve each import binding to its defining file through the import graph —\n  // the same specifier→file resolution imports.ts uses (ADR-149). A specifier\n  // that leaves the service (node_modules, a Node builtin) resolves to null and\n  // is dropped, so it can never carry a prefix.\n  for (const info of fileInfo.values()) {\n    for (const b of info.rawBindings) {\n      const resolved = await resolveJsImport(b.specifier, info.dir, serviceDir, tsPaths)\n      if (!resolved || !fileInfo.has(resolved)) continue\n      info.importedRouters.set(b.local, { file: resolved, sel: b.sel === 'namespace' ? 'default' : b.sel })\n    }\n  }\n\n  // Resolve a mounted identifier to (file, routerVars-key) — a local router var,\n  // or a cross-file import's selected export. null when it names no router we can\n  // reach, which leaves the leaf un-prefixed.\n  const resolveTarget = (name: string, file: string): { file: string; name: string } | null => {\n    const info = fileInfo.get(file)\n    if (!info) return null\n    if (info.routerVars.has(name)) return { file, name }\n    const imp = info.importedRouters.get(name)\n    if (!imp) return null\n    const target = fileInfo.get(imp.file)\n    if (!target) return null\n    const key = imp.sel === 'default' ? target.exportDefaultName : target.exportNamed.get(imp.sel)\n    if (!key) return null\n    return { file: imp.file, name: key }\n  }\n\n  const filePrefix = new Map<string, string>()\n  const conflicted = new Set<string>()\n  const apply = (file: string, prefix: string): void => {\n    if (conflicted.has(file)) return\n    const existing = filePrefix.get(file)\n    if (existing === undefined) filePrefix.set(file, prefix)\n    else if (existing !== prefix) {\n      // The same file reached at two different prefixes — genuinely ambiguous.\n      // Drop it rather than pick one (ADR-160 discipline).\n      filePrefix.delete(file)\n      conflicted.add(file)\n    }\n  }\n\n  const visited = new Set<string>()\n  const collect = (file: string, name: string, accPrefix: string): void => {\n    const key = `${file}|${name}|${accPrefix}`\n    if (visited.has(key)) return\n    visited.add(key)\n    const info = fileInfo.get(file)\n    const rv = info?.routerVars.get(name)\n    if (!info || !rv) return\n    // A file that also hosts an express() app serves its declared routes at the\n    // app root; don't push a mount prefix onto them.\n    if (rv.declares && info.appVars.size === 0) apply(file, accPrefix)\n    for (const m of rv.mounts) {\n      if (!m.target) continue\n      const t = resolveTarget(m.target, file)\n      if (t) collect(t.file, t.name, accPrefix + m.prefix)\n    }\n    if (rv.aliasOf) {\n      const t = resolveTarget(rv.aliasOf, file)\n      if (t) collect(t.file, t.name, accPrefix)\n    }\n  }\n\n  // Root the walk at each express() app. What the app mounts is what the server\n  // actually serves, so the prefix path from the app down is the real one.\n  for (const [rel, info] of fileInfo) {\n    for (const appVar of info.appVars) collect(rel, appVar, '')\n  }\n\n  const out = new Map<string, string>()\n  for (const [file, prefix] of filePrefix) if (prefix && prefix !== '/') out.set(file, prefix)\n  return out\n}\n\n// ── producer ────────────────────────────────────────────────────────────────\n\nexport async function addRoutes(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  const jsParser = makeJsParser()\n  const pyParser = makePyParser()\n  const goParser = makeGoParser()\n  const rubyParser = makeRubyParser()\n  const phpParser = makePhpParser()\n  const rustParser = makeRustParser()\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    const deps = {\n      ...(service.pkg.dependencies ?? {}),\n      ...(service.pkg.devDependencies ?? {}),\n    }\n    const hasExpress = deps['express'] !== undefined\n    const hasFastify = deps['fastify'] !== undefined\n    const hasHono = deps['hono'] !== undefined\n    const hasNext = deps['next'] !== undefined\n    const hasNestjs = deps['@nestjs/core'] !== undefined\n    // FastAPI / Flask are discovered on a Python service the same dependency-gated\n    // way: the manifest reader (extract/python.ts) strips the `fastapi[standard]`\n    // extra to the bare `fastapi` distribution name.\n    const hasFastapi = deps['fastapi'] !== undefined\n    const hasFlask = deps['flask'] !== undefined\n    const hasDjango = deps['django'] !== undefined\n    const hasGin = deps['github.com/gin-gonic/gin'] !== undefined\n    // Echo and Fiber join Go's route recognizers (ADR-181): the go.mod require\n    // path carries the major-version suffix, so gate on both the versioned module\n    // and the pre-modules path. Each declares routes the same shape Gin does.\n    const hasEcho =\n      deps['github.com/labstack/echo/v4'] !== undefined ||\n      deps['github.com/labstack/echo'] !== undefined\n    const hasFiber =\n      deps['github.com/gofiber/fiber/v2'] !== undefined ||\n      deps['github.com/gofiber/fiber/v3'] !== undefined\n    // Chi joins the Go recognizers (ADR-182); the go.mod require path carries the\n    // major-version suffix, so gate on both the versioned module and the\n    // pre-modules path. Its verbs read like Fiber's; its `Route` prefix\n    // composition is closure-scoped (a stack, not a var map).\n    const hasChi =\n      deps['github.com/go-chi/chi/v5'] !== undefined ||\n      deps['github.com/go-chi/chi'] !== undefined\n    // net/http is stdlib — there's no dependency to gate on, so a service can't be\n    // pre-selected for it the way a framework service is. Any Go service may carry\n    // ServeMux routes, so a Go service is admitted on its language alone and the\n    // net/http recognizer self-gates per file (import + method-pattern shape).\n    const isGoService = service.node.language === 'go'\n    // Rails is discovered from the Gemfile (extract/ruby.ts) the same\n    // dependency-gated way; its routes live in one conventional file (ADR-173).\n    const hasRails = deps['rails'] !== undefined\n    // Laravel is discovered from composer.json (extract/php.ts) the same\n    // dependency-gated way; its routes live in routes/web.php + api.php (ADR-177).\n    const hasLaravel = deps['laravel/framework'] !== undefined\n    // Slim is discovered from composer.json alongside Laravel; unlike Laravel it\n    // has no conventional route file, so its recognizer reads every .php file and\n    // self-gates on finding a Slim App value (ADR-206).\n    const hasSlim = deps['slim/slim'] !== undefined\n    // Sinatra is discovered from the Gemfile alongside Rails; like Slim it has no\n    // conventional route file, so its recognizer reads every .rb file and\n    // self-gates on the file referencing Sinatra (ADR-206).\n    const hasSinatra = deps['sinatra'] !== undefined\n    // Actix-Web is discovered from Cargo.toml (extract/rust.ts) the same\n    // dependency-gated way; its routes live in attribute macros / the App builder\n    // (ADR-206).\n    const hasActix = deps['actix-web'] !== undefined\n    if (\n      !hasExpress &&\n      !hasFastify &&\n      !hasHono &&\n      !hasNext &&\n      !hasNestjs &&\n      !hasFastapi &&\n      !hasFlask &&\n      !hasDjango &&\n      !hasGin &&\n      !hasEcho &&\n      !hasFiber &&\n      !hasChi &&\n      !isGoService &&\n      !hasRails &&\n      !hasLaravel &&\n      !hasSlim &&\n      !hasSinatra &&\n      !hasActix\n    )\n      continue\n\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n    // Cross-file Express mount-prefix composition (ADR-160). Resolved once per\n    // service after the file list is loaded; the per-file scan below prepends the\n    // composed prefix so a mounted controller's leaf path (`/tags`) becomes the\n    // full path a production span carries (`/api/tags`), and the two fuse.\n    const mountPrefixes = hasExpress\n      ? await expressMountPrefixes(files, service.dir, await loadTsPathConfig(service.dir))\n      : new Map<string, string>()\n\n    for (const file of files) {\n      // ADR-065 #1 — test-scope exclusion. A test that spins up a router isn't\n      // the service's declared route surface.\n      if (isTestPath(file.path)) continue\n      const ext = path.extname(file.path)\n      const isPy = ext === '.py'\n      const isGo = ext === '.go'\n      const isRb = ext === '.rb'\n      const isPhp = ext === '.php'\n      const isRs = ext === '.rs'\n      if (!JS_ROUTE_EXTENSIONS.has(ext) && !isPy && !isGo && !isRb && !isPhp && !isRs) continue\n      const relFile = toPosix(path.relative(service.dir, file.path))\n\n      let routes: ExtractedRoute[]\n      try {\n        if (isPhp) {\n          // Laravel declares its HTTP surface in two conventional files; every\n          // route in routes/api.php gets the framework's automatic `/api` prefix\n          // (not in the source), passed as the base prefix. Other `.php` files\n          // carry no Laravel routes (ADR-177).\n          routes =\n            hasLaravel && (relFile === 'routes/web.php' || relFile === 'routes/api.php')\n              ? laravelRoutesFromSource(\n                  file.content,\n                  phpParser,\n                  relFile === 'routes/api.php' ? '/api' : '',\n                )\n              : []\n          // Slim has no conventional route file, so it runs on every .php file and\n          // self-gates on finding a Slim App value in the file (ADR-206).\n          if (hasSlim) routes = routes.concat(slimRoutesFromSource(file.content, phpParser))\n        } else if (isRb) {\n          // Rails declares its whole route table in one conventional file; other\n          // `.rb` files carry no Rails routes (ADR-173).\n          routes =\n            hasRails && relFile === 'config/routes.rb'\n              ? railsRoutesFromSource(file.content, rubyParser)\n              : []\n          // Sinatra has no conventional route file, so it runs on every .rb file\n          // and self-gates on the file referencing Sinatra (ADR-206).\n          if (hasSinatra) routes = routes.concat(sinatraRoutesFromSource(file.content, rubyParser))\n        } else if (isRs) {\n          // Actix-Web routes live in attribute macros / the App builder, gated on\n          // the actix-web crate; a non-Actix Rust service reads no routes (ADR-206).\n          routes = hasActix ? actixRoutesFromSource(file.content, rustParser) : []\n        } else if (isGo) {\n          // One framework recognizer per service — Gin, Echo, Fiber, and Chi are\n          // dependency-gated, so a file is read by whichever the manifest names.\n          if (hasGin) routes = ginRoutesFromSource(file.content, goParser)\n          else if (hasEcho) routes = echoRoutesFromSource(file.content, goParser)\n          else if (hasFiber) routes = fiberRoutesFromSource(file.content, goParser)\n          else if (hasChi) routes = chiRoutesFromSource(file.content, goParser)\n          else routes = []\n          // net/http has no dependency to gate on, so it runs additively on every\n          // Go file and self-gates on the `net/http` import plus the\n          // method-prefixed ServeMux pattern shape (ADR-182). A framework file\n          // won't carry that shape, so there's no double count.\n          routes = routes.concat(netHttpRoutesFromSource(file.content, goParser))\n        } else if (isPy) {\n          routes =\n            hasFastapi || hasFlask\n              ? pythonRoutesFromSource(file.content, pyParser, hasFastapi ? 'fastapi' : 'flask')\n              : []\n          // Django's URLconf shape (a urlpatterns list) is independent of the\n          // decorator shape, so a Django service's routes come from here too.\n          if (hasDjango) routes = routes.concat(djangoRoutesFromSource(file.content, pyParser))\n        } else if (hasNext && (isNextAppRouteFile(relFile) || isNextPagesApiFile(relFile))) {\n          routes = nextRoutesFromFile(file.content, relFile, jsParser)\n        } else if (hasNestjs) {\n          routes = nestjsRoutesFromSource(file.content, jsParser)\n        } else if (hasExpress || hasFastify || hasHono) {\n          routes = serverRoutesFromSource(file.content, jsParser, hasExpress, hasFastify, hasHono)\n        } else {\n          routes = []\n        }\n      } catch (err) {\n        recordExtractionError('route extraction', file.path, err)\n        continue\n      }\n      if (routes.length === 0) continue\n\n      // A cross-file Express mount prefix for this file's routes, if one resolved.\n      const mountPrefix = mountPrefixes.get(relFile)\n\n      for (const route of routes) {\n        const pathTemplate = mountPrefix\n          ? canonicalizeTemplate(mountPrefix + route.pathTemplate)\n          : route.pathTemplate\n        const rid = routeId(service.pkg.name, route.method, pathTemplate)\n        if (!graph.hasNode(rid)) {\n          const node: RouteNode = {\n            id: rid,\n            type: NodeType.RouteNode,\n            name: `${route.method} ${pathTemplate}`,\n            service: service.pkg.name,\n            method: route.method,\n            pathTemplate,\n            path: relFile,\n            line: route.line,\n            framework: route.framework,\n            discoveredVia: 'static',\n          }\n          graph.addNode(rid, node)\n          nodesAdded++\n        }\n        // `service ──CONTAINS──▶ route` — the service owns its routes the same\n        // way it owns its files (file-awareness.md §2). Structural ownership,\n        // evidence pinned to the defining file:line.\n        const containsId = extractedEdgeId(service.node.id, rid, EdgeType.CONTAINS)\n        if (!graph.hasEdge(containsId)) {\n          const edge: GraphEdge = {\n            id: containsId,\n            source: service.node.id,\n            target: rid,\n            type: EdgeType.CONTAINS,\n            provenance: Provenance.EXTRACTED,\n            confidence: confidenceForExtracted('structural'),\n            evidence: {\n              file: relFile,\n              line: route.line,\n              snippet: snippet(file.content, route.line),\n            },\n          }\n          graph.addEdgeWithKey(containsId, service.node.id, rid, edge)\n          edgesAdded++\n        }\n      }\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import { readGoModule } from './go.js'\nimport path from 'node:path'\nimport { promises as fs } from 'node:fs'\nimport Parser from 'tree-sitter'\nimport JavaScript from 'tree-sitter-javascript'\nimport Python from 'tree-sitter-python'\nimport Go from 'tree-sitter-go'\nimport type { GraphEdge } from '@neat.is/types'\nimport {\n  EdgeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  fileId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport { isTestPath, type DiscoveredService } from './shared.js'\nimport { recordExtractionError } from './errors.js'\nimport { loadSourceFiles, toPosix } from './calls/shared.js'\n\n// Phase 2 — import graph extraction (ADR-092, file-awareness.md §10). Walks\n// every source file's AST for import / require statements and emits IMPORTS\n// edges between FileNodes within the same service. Cross-service and\n// unresolvable specifiers are silent skips — Phase 3's CALLS producers cover\n// the cross-service case where an external-call pattern matches.\n\n// Same chunked-parse approach as calls/shared.ts — tree-sitter's bare string\n// path throws \"Invalid argument\" once the source clears ~32K code units. The\n// callback form streams the source in bounded slices instead.\nconst PARSE_CHUNK = 16384\n\nexport function parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nexport function makeJsParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(JavaScript)\n  return p\n}\n\nexport function makePyParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Python)\n  return p\n}\n\nexport function makeGoParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Go)\n  return p\n}\n\n// ── string-literal text ────────────────────────────────────────────────────\n\n// The interior text of a string literal node, stripped of quote characters.\n// tree-sitter-javascript wraps the content in a `string_fragment` child;\n// fall back to slicing the raw text when that shape isn't present (e.g. an\n// empty string literal has no fragment child at all).\nfunction stringLiteralText(node: Parser.SyntaxNode): string | null {\n  for (let i = 0; i < node.childCount; i++) {\n    const child = node.child(i)\n    if (child?.type === 'string_fragment') return child.text\n  }\n  const raw = node.text\n  if (raw.length >= 2) return raw.slice(1, -1)\n  return raw.length === 0 ? null : ''\n}\n\nfunction clipSnippet(text: string): string {\n  const oneLine = text.split('\\n')[0] ?? text\n  return oneLine.length > 120 ? oneLine.slice(0, 120) : oneLine\n}\n\n// ── JS / TS import collection ──────────────────────────────────────────────\n\nexport interface RawImport {\n  specifier: string\n  line: number // 1-indexed\n  snippet: string\n  // Names the import binds locally: an ESM default, `* as ns` or named-import\n  // name (the alias when there is one), a `const x = require(...)` target, a Go\n  // package alias or its package name. Read by the dependency-import phase\n  // (dependency-inventory.md §4); first-party resolution ignores it.\n  bindings?: string[]\n}\n\n// The package name an unaliased Go import binds, when the path shows it: the last\n// segment, minus a `/vN` major-version suffix and a gopkg.in `.vN`\n// (`gopkg.in/yaml.v3` binds `yaml`). The real name is the package clause in the\n// imported source, and the path can't always tell it: `github.com/redis/go-redis/v9`\n// binds `redis`. A segment that isn't a Go identifier gives no binding rather\n// than a guessed one.\nfunction goPackageName(importPath: string): string | null {\n  const segs = importPath.split('/')\n  let last = segs.at(-1) ?? importPath\n  if (/^v\\d+$/.test(last) && segs.length > 1) last = segs.at(-2)!\n  last = last.replace(/\\.v\\d+$/, '')\n  return /^[A-Za-z_][A-Za-z0-9_]*$/.test(last) ? last : null\n}\n\nexport function collectGoImports(node: Parser.SyntaxNode, out: RawImport[]): void {\n  if (node.type === 'import_spec') {\n    const pathNode = node.childForFieldName('path')\n    if (pathNode) {\n      const specifier = pathNode.text.replace(/^`|`$/g, '').replace(/^\"|\"$/g, '')\n      // `_` binds nothing and `.` merges the package into file scope; neither is a name.\n      const alias = node.childForFieldName('name')?.text\n      const local = alias ?? goPackageName(specifier)\n      const bindings = local === null || alias === '_' || alias === '.' ? [] : [local]\n      if (specifier) out.push({ specifier, line: node.startPosition.row + 1, snippet: clipSnippet(node.text), bindings })\n    }\n    return\n  }\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (child) collectGoImports(child, out)\n  }\n}\n\n// Walks the AST for `import ... from 'spec'` / `import 'spec'` (ES modules)\n// and `require('spec')` (CommonJS). Doesn't recurse into import_statement —\n// its only string child is the source specifier, never a nested import.\n// The local names an ESM import clause binds: `x` in `import x`, `ns` in\n// `import * as ns`, and each named import's alias or name.\nfunction esmBindings(stmt: Parser.SyntaxNode): string[] {\n  const out: string[] = []\n  for (let i = 0; i < stmt.namedChildCount; i++) {\n    const clause = stmt.namedChild(i)\n    if (clause?.type !== 'import_clause') continue\n    for (let j = 0; j < clause.namedChildCount; j++) {\n      const part = clause.namedChild(j)\n      if (!part) continue\n      if (part.type === 'identifier') out.push(part.text)\n      else if (part.type === 'namespace_import') {\n        const id = part.namedChildren.find((c) => c.type === 'identifier')\n        if (id) out.push(id.text)\n      } else if (part.type === 'named_imports') {\n        for (const spec of part.namedChildren) {\n          if (spec.type !== 'import_specifier') continue\n          const local = spec.childForFieldName('alias') ?? spec.childForFieldName('name')\n          if (local) out.push(local.text)\n        }\n      }\n    }\n  }\n  return out\n}\n\n// What `require(...)` is assigned to: `const x = require(...)` binds `x`,\n// `const { a, b: c } = require(...)` binds `a` and `c`. Anything else binds nothing.\nfunction requireBindings(call: Parser.SyntaxNode): string[] {\n  const decl = call.parent\n  if (decl?.type !== 'variable_declarator' || decl.childForFieldName('value')?.id !== call.id) return []\n  const target = decl.childForFieldName('name')\n  if (!target) return []\n  if (target.type === 'identifier') return [target.text]\n  if (target.type !== 'object_pattern') return []\n  const out: string[] = []\n  for (const p of target.namedChildren) {\n    if (p.type === 'shorthand_property_identifier_pattern') out.push(p.text)\n    else if (p.type === 'pair_pattern') {\n      const v = p.childForFieldName('value')\n      if (v?.type === 'identifier') out.push(v.text)\n    }\n  }\n  return out\n}\n\nexport function collectJsImports(node: Parser.SyntaxNode, out: RawImport[]): void {\n  if (node.type === 'import_statement') {\n    const source = node.childForFieldName('source')\n    if (source) {\n      const specifier = stringLiteralText(source)\n      if (specifier) {\n        out.push({ specifier, line: node.startPosition.row + 1, snippet: clipSnippet(node.text), bindings: esmBindings(node) })\n      }\n    }\n    return\n  }\n\n  if (node.type === 'call_expression') {\n    const fn = node.childForFieldName('function')\n    if (fn?.type === 'identifier' && fn.text === 'require') {\n      const args = node.childForFieldName('arguments')\n      const firstArg = args?.namedChild(0)\n      if (firstArg?.type === 'string') {\n        const specifier = stringLiteralText(firstArg)\n        if (specifier) {\n          out.push({ specifier, line: node.startPosition.row + 1, snippet: clipSnippet(node.text), bindings: requireBindings(node) })\n        }\n      }\n    }\n  }\n\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (child) collectJsImports(child, out)\n  }\n}\n\n// ── Python import collection ───────────────────────────────────────────────\n\nexport interface RawPyImport {\n  modulePath: string // dotted path with the leading dots stripped, e.g. 'utils.auth'\n  level: number // count of leading dots; 0 = absolute import\n  names: string[] // the imported names after `import` — each may be a submodule\n  line: number\n  snippet: string\n  // The names bound locally (an `as` alias over the imported name). Read by the\n  // dependency-import phase; first-party resolution keys on `names`.\n  bindings?: string[]\n}\n\n// Local names a `from`-import binds: each name, or its `as` alias.\nfunction collectPyBindings(node: Parser.SyntaxNode, out: string[]): void {\n  if (node.type === 'aliased_import') {\n    const local = node.childForFieldName('alias') ?? node.childForFieldName('name')\n    if (local) out.push(local.text)\n    return\n  }\n  if (node.type === 'dotted_name') {\n    out.push(node.text)\n    return\n  }\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (child) collectPyBindings(child, out)\n  }\n}\n\n// Collects the imported names from the tail of a `from`-import — the part\n// after the `import` keyword. Pushes each `name` (and the original name of an\n// `as`-aliased import); descends into a parenthesised list so `from app import\n// (config, db)` reads the same as the unparenthesised form. A wildcard `*`\n// has no name and is left for the module-file fallback in resolution.\nfunction collectImportedNames(node: Parser.SyntaxNode, out: string[]): void {\n  if (node.type === 'aliased_import') {\n    const nameNode = node.childForFieldName('name')\n    if (nameNode) out.push(nameNode.text)\n    return\n  }\n  if (node.type === 'dotted_name') {\n    out.push(node.text)\n    return\n  }\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (child) collectImportedNames(child, out)\n  }\n}\n\n// Walks the AST for `from X import a, b` / `from .X import a`. Bare `import X`\n// statements name modules without resolving to a single file (`import os.path`\n// doesn't tell us which file in `os` got used), so Phase 2 limits itself to\n// the `from`-form per the resolution rules in the contract. The imported names\n// matter: `from app import config` names the `config` submodule, not a symbol\n// on `app/__init__.py`, so resolution keys on them (see resolvePyImport).\nexport function collectPyImports(node: Parser.SyntaxNode, out: RawPyImport[]): void {\n  if (node.type === 'import_from_statement') {\n    let level = 0\n    let modulePath = ''\n    const names: string[] = []\n    const bindings: string[] = []\n    let pastFrom = false\n    let pastImport = false\n\n    for (let i = 0; i < node.childCount; i++) {\n      const child = node.child(i)\n      if (!child) continue\n      if (!pastFrom) {\n        if (child.type === 'from') pastFrom = true\n        continue\n      }\n      if (!pastImport) {\n        if (child.type === 'import') {\n          pastImport = true\n          continue\n        }\n        // The `from`-module spec, before the `import` keyword.\n        if (child.type === 'relative_import') {\n          for (let j = 0; j < child.childCount; j++) {\n            const rc = child.child(j)\n            if (!rc) continue\n            // tree-sitter-python groups every leading dot into a single\n            // import_prefix node — `..` parses as one import_prefix with two\n            // `.` children, not two import_prefix nodes. Count the `.` tokens,\n            // not the prefix nodes, or multi-dot imports under-count `level`\n            // and resolve onto the wrong (sometimes self) target (#457).\n            if (rc.type === 'import_prefix') {\n              for (let k = 0; k < rc.childCount; k++) {\n                if (rc.child(k)?.type === '.') level++\n              }\n            } else if (rc.type === 'dotted_name') modulePath = rc.text\n          }\n        } else if (child.type === 'dotted_name') {\n          modulePath = child.text\n        }\n        continue\n      }\n      // Past the `import` keyword — the imported names.\n      collectImportedNames(child, names)\n      collectPyBindings(child, bindings)\n    }\n\n    if (level > 0 || modulePath) {\n      out.push({ modulePath, level, names, line: node.startPosition.row + 1, snippet: clipSnippet(node.text), bindings })\n    }\n  }\n\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (child) collectPyImports(child, out)\n  }\n}\n\n// Bare `import X` / `import X.Y as Z` statements, one entry per imported module.\n// First-party resolution doesn't read these (see collectPyImports); the\n// dependency-import phase does, since `import requests` is how most code pulls in\n// a package. `import a.b` binds `a`; `import a.b as z` binds `z`.\nexport function collectPyBareImports(node: Parser.SyntaxNode, out: RawPyImport[]): void {\n  if (node.type === 'import_statement') {\n    for (const child of node.namedChildren) {\n      let modulePath: string\n      let local: string\n      if (child.type === 'dotted_name') {\n        modulePath = child.text\n        local = modulePath.split('.')[0]!\n      } else if (child.type === 'aliased_import') {\n        const name = child.childForFieldName('name')\n        const alias = child.childForFieldName('alias')\n        if (!name) continue\n        modulePath = name.text\n        local = alias?.text ?? modulePath.split('.')[0]!\n      } else continue\n      out.push({ modulePath, level: 0, names: [], line: node.startPosition.row + 1, snippet: clipSnippet(node.text), bindings: [local] })\n    }\n    return\n  }\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (child) collectPyBareImports(child, out)\n  }\n}\n\n// ── filesystem resolution helpers ──────────────────────────────────────────\n\nasync function fileExists(p: string): Promise<boolean> {\n  try {\n    await fs.access(p)\n    return true\n  } catch {\n    return false\n  }\n}\n\n// An import that escapes the service directory (`../../other-service/x`)\n// isn't an intra-service edge — Phase 2 is scoped to within-service module\n// dependencies (file-awareness.md §10).\nfunction isWithinServiceDir(candidate: string, serviceDir: string): boolean {\n  const rel = path.relative(serviceDir, candidate)\n  return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)\n}\n\nconst JS_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']\nconst JS_INDEX_FILES = JS_EXTENSIONS.map((ext) => `index${ext}`)\n\n// Try `base`, `base.<ext>`, and `base/index.<ext>` in TypeScript-resolution\n// order. Returns the service-relative posix path of the first hit.\nasync function firstExistingCandidate(\n  base: string,\n  serviceDir: string,\n): Promise<string | null> {\n  for (const ext of JS_EXTENSIONS) {\n    const candidate = base + ext\n    if (isWithinServiceDir(candidate, serviceDir) && (await fileExists(candidate))) {\n      return toPosix(path.relative(serviceDir, candidate))\n    }\n  }\n  for (const indexFile of JS_INDEX_FILES) {\n    const candidate = path.join(base, indexFile)\n    if (isWithinServiceDir(candidate, serviceDir) && (await fileExists(candidate))) {\n      return toPosix(path.relative(serviceDir, candidate))\n    }\n  }\n  return null\n}\n\nexport interface TsPathConfig {\n  paths: Record<string, string[]>\n  baseDir: string // absolute directory compilerOptions.baseUrl resolves against\n}\n\n// `tsconfig.json` at the service root. The contract names scanPath as a\n// fallback location too, but every discovered service already carries its own\n// root — the scanPath fallback only matters for configs that live above the\n// service tree, which the resolver doesn't have a path back to from here.\nexport async function loadTsPathConfig(serviceDir: string): Promise<TsPathConfig | null> {\n  const tsconfigPath = path.join(serviceDir, 'tsconfig.json')\n  let raw: string\n  try {\n    raw = await fs.readFile(tsconfigPath, 'utf8')\n  } catch {\n    return null\n  }\n  try {\n    const parsed = JSON.parse(raw) as {\n      compilerOptions?: { paths?: Record<string, string[]>; baseUrl?: string }\n    }\n    const paths = parsed.compilerOptions?.paths\n    if (!paths || Object.keys(paths).length === 0) return null\n    const baseUrl = parsed.compilerOptions?.baseUrl\n    return { paths, baseDir: baseUrl ? path.resolve(serviceDir, baseUrl) : serviceDir }\n  } catch (err) {\n    recordExtractionError('import alias resolution', tsconfigPath, err)\n    return null\n  }\n}\n\n// Resolve a bare specifier against `compilerOptions.paths`. Matches the first\n// alias whose pattern fits — exact (`@db`) or wildcard (`@db/*`) — and tries\n// each mapped target in declaration order. No match anywhere → null, the\n// silent-skip the contract calls for.\nasync function resolveTsAlias(\n  specifier: string,\n  config: TsPathConfig,\n  serviceDir: string,\n): Promise<string | null> {\n  for (const [pattern, targets] of Object.entries(config.paths)) {\n    let suffix: string | null = null\n    if (pattern === specifier) {\n      suffix = ''\n    } else if (pattern.endsWith('/*')) {\n      const prefix = pattern.slice(0, -1) // keep the trailing '/'\n      if (specifier.startsWith(prefix)) suffix = specifier.slice(prefix.length)\n    }\n    if (suffix === null) continue\n\n    for (const target of targets) {\n      const targetBase = target.endsWith('/*') ? target.slice(0, -2) : target.replace(/\\*$/, '')\n      const resolvedBase = path.resolve(config.baseDir, targetBase, suffix)\n      const hit = await firstExistingCandidate(resolvedBase, serviceDir)\n      if (hit) return hit\n      // The candidate may already carry its own extension (`@db/mongo.ts`).\n      if (isWithinServiceDir(resolvedBase, serviceDir) && (await fileExists(resolvedBase))) {\n        return toPosix(path.relative(serviceDir, resolvedBase))\n      }\n    }\n  }\n  return null\n}\n\n// Resolves a JS/TS module specifier to a service-relative posix path, or\n// null when it names something outside the service (node_modules, Node\n// builtins, an alias with no tsconfig match, an escaping relative path).\n// Exported so the cross-file mongoose resolver (ADR-149) can reuse the same\n// specifier→FileNode resolution — extensions, index/barrel files, the .js→.ts\n// sibling convention — instead of re-implementing it. Relative specifiers\n// resolve without `tsPaths`; a bare specifier needs the alias table (pass null\n// to skip aliases).\nexport async function resolveJsImport(\n  specifier: string,\n  importerDir: string,\n  serviceDir: string,\n  tsPaths: TsPathConfig | null,\n): Promise<string | null> {\n  if (!specifier) return null\n\n  if (specifier.startsWith('./') || specifier.startsWith('../')) {\n    const base = path.resolve(importerDir, specifier)\n    const ext = path.extname(specifier)\n\n    if (ext) {\n      // `./foo.js` written against a `.ts` source — the TypeScript ESM\n      // convention of naming the post-build extension in source. Try the\n      // TS sibling before the literal path.\n      if (ext === '.js' || ext === '.jsx') {\n        const tsExt = ext === '.jsx' ? '.tsx' : '.ts'\n        const tsSibling = base.slice(0, -ext.length) + tsExt\n        if (isWithinServiceDir(tsSibling, serviceDir) && (await fileExists(tsSibling))) {\n          return toPosix(path.relative(serviceDir, tsSibling))\n        }\n      }\n      if (isWithinServiceDir(base, serviceDir) && (await fileExists(base))) {\n        return toPosix(path.relative(serviceDir, base))\n      }\n      // `path.extname` reads the tail of a dotted module name — `foo.controller`,\n      // `bar.model`, `x.service` (the NestJS / Angular / RealWorld convention) — as\n      // an extension, but the file on disk is `foo.controller.ts`. When the literal\n      // path doesn't exist and the \"extension\" isn't one we compile, the dot is part\n      // of the module name: resolve the whole specifier as extensionless.\n      if (!JS_EXTENSIONS.includes(ext)) {\n        return firstExistingCandidate(base, serviceDir)\n      }\n      return null\n    }\n\n    return firstExistingCandidate(base, serviceDir)\n  }\n\n  // Bare specifier — only a registered TS path alias can make this\n  // intra-service. Anything else is node_modules / a Node builtin.\n  if (tsPaths) return resolveTsAlias(specifier, tsPaths, serviceDir)\n  return null\n}\n\n// Resolves a Python `from`-import to the service-relative posix paths it\n// touches — one per imported module. Relative imports (level > 0) walk up from\n// the importing module's directory; absolute imports match against the service\n// source tree directly.\n//\n// `from app import config` names the `config` *submodule* (app/config.py), not\n// a symbol re-exported by app/__init__.py. Resolving the whole statement onto\n// the package's __init__.py was wrong: every intra-package import collapsed\n// onto one target and the per-(source,target) edge dedup then made the second\n// such dependency invisible. So we key on each imported name, resolving it to\n// its own module file, and fall back to the package/module file only for names\n// that aren't submodules (plain symbols, or a `*` wildcard).\nasync function resolvePyImport(\n  imp: RawPyImport,\n  importerPath: string,\n  serviceDir: string,\n): Promise<string[]> {\n  let baseDir: string\n  if (imp.level > 0) {\n    baseDir = path.dirname(importerPath)\n    for (let i = 1; i < imp.level; i++) baseDir = path.dirname(baseDir)\n  } else {\n    baseDir = serviceDir\n  }\n\n  // The on-disk base of the `from`-module. `from app import x` → app/ ;\n  // `from . import x` → the importer's own package directory (modulePath empty).\n  const moduleBase = imp.modulePath\n    ? path.join(baseDir, imp.modulePath.split('.').join('/'))\n    : baseDir\n\n  const resolved = new Set<string>()\n  let needModuleFile = imp.names.length === 0 // wildcard / unparsed → the module itself\n\n  for (const name of imp.names) {\n    const submoduleFile = path.join(moduleBase, `${name}.py`)\n    const subpackageInit = path.join(moduleBase, name, '__init__.py')\n    if (isWithinServiceDir(submoduleFile, serviceDir) && (await fileExists(submoduleFile))) {\n      resolved.add(toPosix(path.relative(serviceDir, submoduleFile)))\n    } else if (isWithinServiceDir(subpackageInit, serviceDir) && (await fileExists(subpackageInit))) {\n      resolved.add(toPosix(path.relative(serviceDir, subpackageInit)))\n    } else {\n      // Not a submodule — the name is a symbol defined in the module itself.\n      needModuleFile = true\n    }\n  }\n\n  if (needModuleFile) {\n    // An empty modulePath (`from . import x`) has no module file of its own —\n    // the package is the directory, so only its __init__.py applies.\n    const moduleFileCandidates = imp.modulePath\n      ? [`${moduleBase}.py`, path.join(moduleBase, '__init__.py')]\n      : [path.join(moduleBase, '__init__.py')]\n    for (const candidate of moduleFileCandidates) {\n      if (isWithinServiceDir(candidate, serviceDir) && (await fileExists(candidate))) {\n        resolved.add(toPosix(path.relative(serviceDir, candidate)))\n        break\n      }\n    }\n  }\n\n  return [...resolved]\n}\n\nasync function resolveGoImport(\n  specifier: string,\n  modulePath: string,\n  serviceDir: string,\n): Promise<string | null> {\n  if (specifier !== modulePath && !specifier.startsWith(`${modulePath}/`)) return null\n  const suffix = specifier === modulePath ? '' : specifier.slice(modulePath.length + 1)\n  const dir = path.join(serviceDir, suffix)\n  const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => [])\n  const candidates = entries\n    .filter((entry) => entry.isFile() && entry.name.endsWith('.go') && !entry.name.endsWith('_test.go'))\n    .map((entry) => path.join(dir, entry.name))\n  if (candidates.length !== 1) return null\n  return toPosix(path.relative(serviceDir, candidates[0]!))\n}\n\n// ── edge emission ──────────────────────────────────────────────────────────\n\nfunction emitImportEdge(\n  graph: NeatGraph,\n  serviceName: string,\n  importerFileId: string,\n  importerRelPath: string,\n  importeeRelPath: string,\n  line: number,\n  snippet: string,\n): number {\n  const importeeFileId = fileId(serviceName, importeeRelPath)\n  // Phase 1 enumerates every source file unconditionally; a resolved path\n  // that isn't a FileNode is outside SERVICE_FILE_EXTENSIONS or otherwise\n  // wasn't walked — not an intra-service module edge.\n  if (!graph.hasNode(importeeFileId)) return 0\n\n  // A file whose import resolves to itself (barrel re-export / path-alias cycle)\n  // is not a dependency edge, and a self-loop throws in graphology (allowSelfLoops\n  // is off) — which today kills the whole extraction. Skip it: a self-import is a\n  // non-edge, not a per-file failure worth logging. [surfaced extracting n8n]\n  if (importerFileId === importeeFileId) return 0\n\n  const edgeId = extractedEdgeId(importerFileId, importeeFileId, EdgeType.IMPORTS)\n  if (graph.hasEdge(edgeId)) return 0\n\n  const edge: GraphEdge = {\n    id: edgeId,\n    source: importerFileId,\n    target: importeeFileId,\n    type: EdgeType.IMPORTS,\n    provenance: Provenance.EXTRACTED,\n    confidence: confidenceForExtracted('structural'),\n    evidence: { file: importerRelPath, line, snippet },\n  }\n  graph.addEdgeWithKey(edgeId, importerFileId, importeeFileId, edge)\n  return 1\n}\n\n// ── producer ───────────────────────────────────────────────────────────────\n\nexport async function addImports(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  const jsParser = makeJsParser()\n  const pyParser = makePyParser()\n  const goParser = makeGoParser()\n  let edgesAdded = 0\n\n  const goModulePaths = new Map<string, string | null>()\n  for (const service of services) {\n    const tsPaths = await loadTsPathConfig(service.dir)\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n\n    for (const file of files) {\n      // ADR-065 §1 — test-scope exclusion. The file stays a FileNode (Phase 1);\n      // only its outbound module edges are filtered (file-awareness.md §10).\n      if (isTestPath(file.path)) continue\n\n      const relFile = toPosix(path.relative(service.dir, file.path))\n      const importerFileId = fileId(service.pkg.name, relFile)\n      const isPython = path.extname(file.path) === '.py'\n      const isGo = path.extname(file.path) === '.go'\n\n      // Ruby is a route-and-service-grain pilot (ADR-173): `.rb` files are\n      // FileNodes and their routes.rb is read, but Ruby's autoload-driven\n      // require graph isn't modelled yet — parsing it with the JS grammar would\n      // fabricate nothing useful, so skip. Ruby import resolution is a later rung.\n      if (path.extname(file.path) === '.rb') continue\n\n      // PHP is a route-and-service-grain pilot (ADR-177): `.php` files are\n      // FileNodes and Laravel's routes/*.php are read, but PHP's PSR-4 autoload\n      // require graph isn't modelled yet — parsing it with the JS grammar would\n      // fabricate nothing useful, so skip. PHP import resolution is a later rung.\n      if (path.extname(file.path) === '.php') continue\n\n      if (isGo) {\n        let goImports: RawImport[] = []\n        try {\n          const tree = parseSource(goParser, file.content)\n          collectGoImports(tree.rootNode, goImports)\n        } catch (err) {\n          recordExtractionError('import extraction', file.path, err)\n          continue\n        }\n        // go.mod's module line, or a dep-layout repo's inferred import path (ADR-256).\n        let modulePath = goModulePaths.get(service.dir)\n        if (modulePath === undefined) {\n          modulePath = (await readGoModule(service.dir))?.module ?? null\n          goModulePaths.set(service.dir, modulePath)\n        }\n        if (!modulePath) continue\n        for (const imp of goImports) {\n          const resolved = await resolveGoImport(imp.specifier, modulePath, service.dir)\n          if (!resolved) continue\n          edgesAdded += emitImportEdge(graph, service.pkg.name, importerFileId, relFile, resolved, imp.line, imp.snippet)\n        }\n        continue\n      }\n\n      if (isPython) {\n        let pyImports: RawPyImport[] = []\n        try {\n          const tree = parseSource(pyParser, file.content)\n          collectPyImports(tree.rootNode, pyImports)\n        } catch (err) {\n          recordExtractionError('import extraction', file.path, err)\n          continue\n        }\n        for (const imp of pyImports) {\n          const resolvedPaths = await resolvePyImport(imp, file.path, service.dir)\n          for (const resolved of resolvedPaths) {\n            edgesAdded += emitImportEdge(\n              graph,\n              service.pkg.name,\n              importerFileId,\n              relFile,\n              resolved,\n              imp.line,\n              imp.snippet,\n            )\n          }\n        }\n        continue\n      }\n\n      let jsImports: RawImport[] = []\n      try {\n        const tree = parseSource(jsParser, file.content)\n        collectJsImports(tree.rootNode, jsImports)\n      } catch (err) {\n        recordExtractionError('import extraction', file.path, err)\n        continue\n      }\n      for (const imp of jsImports) {\n        const resolved = await resolveJsImport(imp.specifier, path.dirname(file.path), service.dir, tsPaths)\n        if (!resolved) continue\n        edgesAdded += emitImportEdge(\n          graph,\n          service.pkg.name,\n          importerFileId,\n          relFile,\n          resolved,\n          imp.line,\n          imp.snippet,\n        )\n      }\n    }\n  }\n\n  return { nodesAdded: 0, edgesAdded }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { ServiceNode } from '@neat.is/types'\nimport { NodeType, serviceId } from '@neat.is/types'\nimport type { DiscoveredService, PackageJson } from './shared.js'\nimport { IGNORED_DIRS } from './shared.js'\n\nexport interface GoModule {\n  module: string\n  goVersion?: string\n  dependencies: Record<string, string>\n}\n\nexport function parseGoMod(source: string): GoModule | null {\n  const module = source.match(/^\\s*module\\s+(\\S+)\\s*$/m)?.[1]\n  if (!module) return null\n  const goVersion = source.match(/^\\s*go\\s+(\\S+)\\s*$/m)?.[1]\n  const dependencies: Record<string, string> = {}\n  const block = source.match(/^\\s*require\\s*\\(([^]*?)^\\s*\\)/m)?.[1] ?? ''\n  for (const line of block.split(/\\r?\\n/)) {\n    const m = line.replace(/\\/\\/.*$/, '').trim().match(/^(\\S+)\\s+(v\\S+)$/)\n    if (m) dependencies[m[1]!] = m[2]!\n  }\n  for (const m of source.matchAll(/^\\s*require\\s+(\\S+)\\s+(v\\S+)(?:\\s*\\/\\/.*)?$/gm)) {\n    dependencies[m[1]!] = m[2]!\n  }\n  return { module, ...(goVersion ? { goVersion } : {}), dependencies }\n}\n\n// The web framework a Go service declares, for the ServiceNode's `framework`\n// label — the same package-name → label discipline the JS/Python readers use.\n// The go.mod require path carries the major-version suffix (`.../echo/v4`), so\n// the versioned and pre-modules module paths both map to one label.\nfunction goFramework(deps: Record<string, string>): string | undefined {\n  if (deps['github.com/gin-gonic/gin']) return 'gin'\n  if (deps['github.com/labstack/echo/v4'] || deps['github.com/labstack/echo']) return 'echo'\n  if (deps['github.com/gofiber/fiber/v2'] || deps['github.com/gofiber/fiber/v3']) return 'fiber'\n  if (deps['github.com/go-chi/chi/v5'] || deps['github.com/go-chi/chi']) return 'chi'\n  return undefined\n}\n\nconst IMPORT_BLOCK = /^\\s*import\\s*\\(([^]*?)^\\s*\\)/gm\nconst IMPORT_SINGLE = /^\\s*import\\s+(?:[\\w.]+\\s+)?\"([^\"]+)\"/gm\nconst IMPORT_LINE = /^\\s*(?:[\\w.]+\\s+)?\"([^\"]+)\"/\n\n// The import paths a Go file names. Only the header matters, and the regexes stop\n// at the first match shape, so a string in a function body never reads as one.\nexport function goImports(source: string): string[] {\n  const out: string[] = []\n  for (const m of source.matchAll(IMPORT_BLOCK)) {\n    for (const line of m[1]!.split(/\\r?\\n/)) {\n      const im = IMPORT_LINE.exec(line.replace(/\\/\\/.*$/, ''))\n      if (im) out.push(im[1]!)\n    }\n  }\n  for (const m of source.matchAll(IMPORT_SINGLE)) out.push(m[1]!)\n  return out\n}\n\n// golang/dep's lock file: one `[[projects]]` table per dependency, carrying its\n// `name` and a `version` (else `branch`, else `revision`). Read for the same\n// dependency map a go.mod `require` block gives (ADR-256).\nexport function parseGopkgLock(source: string): Record<string, string> {\n  const deps: Record<string, string> = {}\n  for (const block of source.split(/^\\s*\\[\\[(?:projects|constraint)\\]\\]\\s*$/m).slice(1)) {\n    const field = (k: string): string | undefined => block.match(new RegExp(`^\\\\s*${k}\\\\s*=\\\\s*\"([^\"]+)\"`, 'm'))?.[1]\n    const name = field('name')\n    if (!name) continue\n    deps[name] = field('version') ?? field('branch') ?? field('revision') ?? '*'\n  }\n  return deps\n}\n\n// The directories under `root` that hold Go source of their own (a Go package is a\n// directory), relative and slash-separated. `vendor/`, nested modules and the\n// usual ignored directories are skipped.\nasync function goPackageDirs(root: string): Promise<string[]> {\n  const out = new Set<string>()\n  async function walk(current: string, isRoot: boolean): Promise<void> {\n    const entries = await fs.readdir(current, { withFileTypes: true }).catch(() => [])\n    if (!isRoot && entries.some((e) => e.isFile() && (e.name === 'go.mod' || e.name === 'Gopkg.toml'))) return\n    for (const e of entries) {\n      const full = path.join(current, e.name)\n      if (e.isDirectory()) {\n        if (IGNORED_DIRS.has(e.name) || e.name.startsWith('.')) continue\n        await walk(full, false)\n      } else if (e.isFile() && e.name.endsWith('.go')) {\n        out.add(path.relative(root, current).split(path.sep).join('/'))\n      }\n    }\n  }\n  await walk(root, true)\n  return [...out]\n}\n\n// A dep-layout repository names its own import path nowhere in a file. Recover it\n// from its own source: an import that ends in one of the repo's package\n// directories (`…/services/geo` while `services/geo/` exists) names the module as\n// everything before that directory. The prefix most imports agree on wins, which\n// keeps a stray coincidental match from deciding it.\nexport async function inferGoModulePath(root: string): Promise<string | null> {\n  const dirs = (await goPackageDirs(root)).filter((d) => d.length > 0)\n  if (dirs.length === 0) return null\n  const counts = new Map<string, number>()\n  for (const dir of dirs) {\n    const abs = path.join(root, ...dir.split('/'))\n    const entries = await fs.readdir(abs).catch(() => [] as string[])\n    for (const f of entries) {\n      if (!f.endsWith('.go')) continue\n      const src = await fs.readFile(path.join(abs, f), 'utf8').catch(() => '')\n      for (const imp of goImports(src)) {\n        for (const d of dirs) {\n          if (!imp.endsWith('/' + d)) continue\n          const prefix = imp.slice(0, imp.length - d.length - 1)\n          if (prefix.length > 0) counts.set(prefix, (counts.get(prefix) ?? 0) + 1)\n        }\n      }\n    }\n  }\n  let best: string | null = null\n  let bestCount = 0\n  for (const [prefix, n] of [...counts].sort(([a], [b]) => a.localeCompare(b))) {\n    if (n > bestCount) {\n      best = prefix\n      bestCount = n\n    }\n  }\n  return best\n}\n\n// The Go module rooted at `dir`: from go.mod, else from golang/dep's\n// `Gopkg.toml` / `Gopkg.lock` (ADR-256), whose import path is inferred from the\n// repo's own imports, falling back to the directory name.\nexport async function readGoModule(dir: string): Promise<GoModule | null> {\n  const goMod = await fs.readFile(path.join(dir, 'go.mod'), 'utf8').catch(() => null)\n  if (goMod !== null) return parseGoMod(goMod)\n  const lock = await fs.readFile(path.join(dir, 'Gopkg.lock'), 'utf8').catch(() => null)\n  const toml = await fs.readFile(path.join(dir, 'Gopkg.toml'), 'utf8').catch(() => null)\n  if (lock === null && toml === null) return null\n  const module = (await inferGoModulePath(dir)) ?? path.basename(path.resolve(dir))\n  return { module, dependencies: parseGopkgLock(lock ?? toml ?? '') }\n}\n\nexport async function discoverGoService(\n  scanPath: string,\n  dir: string,\n): Promise<DiscoveredService | null> {\n  const mod = await readGoModule(dir)\n  if (!mod) return null\n  const name = mod.module.split('/').filter(Boolean).pop() ?? mod.module\n  const pkg: PackageJson = { name, dependencies: mod.dependencies }\n  const framework = goFramework(mod.dependencies)\n  const node: ServiceNode = {\n    id: serviceId(name),\n    type: NodeType.ServiceNode,\n    name,\n    language: 'go',\n    dependencies: mod.dependencies,\n    repoPath: path.relative(scanPath, dir),\n    ...(framework ? { framework } : {}),\n  }\n  return { pkg, dir, node }\n}\n","import { NodeType } from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport type { SourceBaseline } from '@neat.is/types'\nexport type { SourceBaseline } from '@neat.is/types'\n\nexport interface SourceCommit {\n  repository: string\n  sha: string\n}\n\ninterface Entry {\n  baseline: SourceBaseline\n  // The pass that owns this entry's next verdict. A newer pass or an\n  // invalidation replaces it, so an older pass can never restore its claim.\n  generation: symbol\n  // Services this repo's files belonged to when its pass finished. Node ids are\n  // keyed by service, not repository, so two repos sharing a service name share\n  // nodes, and neither one's evidence describes them alone.\n  services: Set<string>\n}\n\ninterface State {\n  repos: Map<string, Entry>\n  active: Set<symbol>\n  conflicted: Set<symbol>\n}\n\n// Not graph attributes: evidence cannot survive a snapshot/load or be supplied\n// by an incoming snapshot. Weak keys also keep project removal independent.\nconst states = new WeakMap<NeatGraph, State>()\n\nconst REPOSITORY = /^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/\n\nfunction validCommit(commit: SourceCommit | undefined, repository: string): commit is SourceCommit {\n  return !!commit && commit.repository === repository && /^[0-9a-f]{40}$/.test(commit.sha)\n}\n\nfunction stateOf(graph: NeatGraph): State {\n  let state = states.get(graph)\n  if (!state) {\n    state = { repos: new Map(), active: new Set(), conflicted: new Set() }\n    states.set(graph, state)\n  }\n  return state\n}\n\nfunction setEntry(\n  state: State,\n  repository: string,\n  baseline: SourceBaseline,\n  generation: symbol = Symbol(),\n): void {\n  state.repos.set(repository, {\n    baseline,\n    generation,\n    services: state.repos.get(repository)?.services ?? new Set(),\n  })\n}\n\n/** One entry per repository with evidence, sorted by repository. Copies. */\nexport function readSourceBaselines(graph: NeatGraph): SourceBaseline[] {\n  const state = states.get(graph)\n  if (!state) return []\n  return [...state.repos.entries()]\n    .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n    .map(([, entry]) => ({ ...entry.baseline }))\n}\n\n/**\n * Drop evidence. With a repository, only that repo's entry, superseding any\n * pass of its own in flight. Without one, every entry, because the write that\n * called it may have touched any repo's nodes; a pass running at the time is\n * marked conflicted, so it cannot restore a claim over a graph that changed\n * underneath it.\n */\nexport function invalidateSourceBaseline(\n  graph: NeatGraph,\n  repository?: string,\n  status: 'unavailable' | 'syncing' = 'unavailable',\n): void {\n  if (repository !== undefined) {\n    if (REPOSITORY.test(repository)) setEntry(stateOf(graph), repository, { status, repository })\n    return\n  }\n  const state = states.get(graph)\n  if (!state) return\n  for (const generation of state.active) state.conflicted.add(generation)\n  for (const name of state.repos.keys()) {\n    setEntry(state, name, { status: 'unavailable', repository: name })\n  }\n}\n\n/** Keep entries only for the repositories still bound to this project. */\nexport function retainSourceBaselines(graph: NeatGraph, repositories: Iterable<string>): void {\n  const state = states.get(graph)\n  if (!state) return\n  const keep = new Set(repositories)\n  for (const name of [...state.repos.keys()]) if (!keep.has(name)) state.repos.delete(name)\n}\n\n/**\n * Called when a pass starts. `source` is the repo the pass is scoped to\n * (ADR-233). A pass scoped to no repo may rewrite any repo's nodes, so it\n * invalidates every entry.\n */\nexport function beginSourceExtraction(\n  graph: NeatGraph,\n  source: string | undefined,\n  commit?: SourceCommit,\n): symbol {\n  const generation = Symbol()\n  const state = stateOf(graph)\n  if (source === undefined) {\n    invalidateSourceBaseline(graph)\n    state.active.add(generation)\n    return generation\n  }\n  state.active.add(generation)\n  if (!REPOSITORY.test(source)) return generation\n  setEntry(\n    state,\n    source,\n    validCommit(commit, source)\n      ? { status: 'syncing', repository: source }\n      : { status: 'unavailable', repository: source },\n    generation,\n  )\n  return generation\n}\n\nfunction servicesOf(graph: NeatGraph, repository: string): Set<string> {\n  const services = new Set<string>()\n  graph.forEachNode((_id, attrs) => {\n    const node = attrs as { type?: string; source?: string; service?: string }\n    if (node.type === NodeType.FileNode && node.source === repository && node.service) {\n      services.add(node.service)\n    }\n  })\n  return services\n}\n\nexport function finishSourceExtraction(\n  graph: NeatGraph,\n  generation: symbol,\n  source: string | undefined,\n  commit: SourceCommit | undefined,\n  result: { extractionErrors: number; skippedFiles: number },\n): void {\n  const state = states.get(graph)\n  if (!state) return\n  state.active.delete(generation)\n  const conflicted = state.conflicted.delete(generation)\n  if (source === undefined || !REPOSITORY.test(source)) return\n  const entry = state.repos.get(source)\n  // Another pass or invalidation has superseded this one.\n  if (!entry || entry.generation !== generation) return\n  entry.services = servicesOf(graph, source)\n  let shared = false\n  for (const [name, other] of state.repos) {\n    if (name === source || ![...entry.services].some((s) => other.services.has(s))) continue\n    shared = true\n    setEntry(state, name, { status: 'unavailable', repository: name }, other.generation)\n  }\n  entry.baseline =\n    !conflicted &&\n    !shared &&\n    validCommit(commit, source) &&\n    result.extractionErrors === 0 &&\n    result.skippedFiles === 0\n      ? { status: 'ready', repository: source, sha: commit.sha }\n      : { status: 'unavailable', repository: source }\n}\n","import type { GraphEdge, InfraNode } from '@neat.is/types'\nimport { EdgeTypeValue, NodeType, Provenance, confidenceForExtracted, infraId } from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { makeEdgeId } from '../shared.js'\n\n// ADR-010 reserves the `infra:` prefix; the kind segment lets traversal and\n// MCP tools sub-type without inventing a new top-level NodeType per source.\nexport function makeInfraNode(\n  kind: string,\n  name: string,\n  provider = 'self',\n  extras?: { region?: string },\n): InfraNode {\n  return {\n    id: infraId(kind, name),\n    type: NodeType.InfraNode,\n    name,\n    provider,\n    kind,\n    ...(extras?.region ? { region: extras.region } : {}),\n  }\n}\n\n// Stable kind for an image string like \"postgres:15-alpine\" or \"mysql:8\".\n// The image name itself ends up in the InfraNode `name` field; this function\n// only classifies what the image *is*, so callers can group similar runtimes.\n// The datastore engine a bare name denotes, or undefined when it names no engine\n// NEAT recognizes. One list, one home: `classifyImage` (image strings) and the\n// opentracing datastore-client resolver (ingest, `peer.service`, #1415) both read it,\n// so the recognized-engine set is defined once here rather than duplicated. Message\n// brokers (kafka, rabbitmq) are deliberately out — they are not datastores.\nexport function knownDatastoreEngine(name: string | undefined): string | undefined {\n  if (!name) return undefined\n  const n = name.toLowerCase()\n  if (n.startsWith('postgres')) return 'postgres'\n  if (n.startsWith('mysql') || n.startsWith('mariadb')) return 'mysql'\n  if (n.startsWith('mongo')) return 'mongodb'\n  if (n.startsWith('redis')) return 'redis'\n  if (n.startsWith('memcached')) return 'memcached'\n  return undefined\n}\n\nexport function classifyImage(image: string): string {\n  const lower = image.toLowerCase()\n  const repo = lower.split(':')[0]!\n  const last = repo.split('/').pop() ?? repo\n  const engine = knownDatastoreEngine(last)\n  if (engine) return engine\n  if (last.startsWith('rabbitmq')) return 'rabbitmq'\n  if (last.startsWith('kafka') || last.includes('kafka')) return 'kafka'\n  return 'container'\n}\n\n// Best-effort 1-indexed line for a declared value in a config file's raw text —\n// the same \"read config as data\" text search cloudflare.ts and terraform.ts use\n// rather than a real AST.\nexport function lineContaining(raw: string, needle: string | undefined): number | undefined {\n  if (!needle) return undefined\n  const idx = raw.indexOf(needle)\n  if (idx === -1) return undefined\n  let line = 1\n  for (let i = 0; i < idx; i++) if (raw[i] === '\\n') line++\n  return line\n}\n\n// One declared-resource InfraNode + an edge from the anchor (a ServiceNode or an\n// entry FileNode). Idempotent; every edge carries evidence.file. Shared by the\n// platform extractors (vercel/railway/supabase); cloudflare.ts predates this and\n// keeps its own local copy. No self-loop when a resource id equals the anchor.\nexport function emitPlatformResourceEdge(\n  graph: NeatGraph,\n  anchorId: string,\n  edgeType: EdgeTypeValue,\n  kind: string,\n  name: string,\n  provider: string,\n  evidenceFile: string,\n  line?: number,\n): { nodesAdded: number; edgesAdded: number } {\n  let nodesAdded = 0\n  let edgesAdded = 0\n  const node = makeInfraNode(kind, name, provider)\n  if (!graph.hasNode(node.id)) {\n    graph.addNode(node.id, node)\n    nodesAdded++\n  }\n  if (node.id === anchorId) return { nodesAdded, edgesAdded }\n  const edgeId = makeEdgeId(anchorId, node.id, edgeType)\n  if (!graph.hasEdge(edgeId)) {\n    const edge: GraphEdge = {\n      id: edgeId,\n      source: anchorId,\n      target: node.id,\n      type: edgeType,\n      provenance: Provenance.EXTRACTED,\n      confidence: confidenceForExtracted('structural'),\n      evidence: { file: evidenceFile, ...(line !== undefined ? { line } : {}) },\n    }\n    graph.addEdgeWithKey(edgeId, edge.source, edge.target, edge)\n    edgesAdded++\n  }\n  return { nodesAdded, edgesAdded }\n}\n","// Column-grain provenance fold (ADR-157). Columns are a provenanced attribute\n// list on a `sql-table` InfraNode, never their own nodes. This module is the one\n// place that folds a column presence onto that list; the graph mutation itself\n// stays with the two lifecycle authorities that call it — `ingest.ts` for the\n// OBSERVED read off `db.statement`, and `extract/calls/*` for the EXTRACTED read\n// off a schema definition (lifecycle.md §3). The divergence detector\n// (divergences.ts) only reads the list. Keeping the fold pure here (no graph\n// handle) lets extract call in without importing ingest — ingest already imports\n// extract, so the reverse would be a cycle.\n//\n// A column records each provenance it has been seen with in a deduped\n// `provenances` set: a column that is both declared and observed carries\n// `[EXTRACTED, OBSERVED]`, and the column-drift query (ADR-157 §4) reads the\n// declared set and the observed set straight off that one entry. `confidence` is\n// the strongest evidence's grade (max) — a column seen on both sides is the most\n// certain, and a one-sided (drift) column's confidence is just that side's grade.\n\nimport { Provenance, type ColumnAttr, type ProvenanceValue } from '@neat.is/types'\n\n// OBSERVED columns are read verbatim from a parameterized `db.statement`: the\n// value is redacted but the column NAME is present in the text, so the read is\n// near-certain. Graded just below 1.0 to acknowledge the parser's conservative\n// reach (it degrades on JOIN / subquery / `SELECT *`) rather than claim total\n// coverage. EXTRACTED columns carry their producer's grade instead.\nexport const OBSERVED_COLUMN_CONFIDENCE = 0.9\n\n// Deterministic, deduped provenance order so a node's serialized shape is stable\n// regardless of the order extract / ingest passes ran in. Alphabetical happens to\n// read EXTRACTED, INFERRED, OBSERVED, STALE.\nfunction normalizeProvenances(provenances: ProvenanceValue[]): ProvenanceValue[] {\n  return [...new Set(provenances)].sort()\n}\n\n// Fold a set of column names onto a table node's `columns` list at one\n// provenance, returning a fresh array (pure — the caller writes it back). Column\n// names are lowercased so the declared read fuses with the observed read, which\n// already lowercases: an unquoted SQL identifier is case-folded by the database\n// anyway, so lowercasing both sides is the fusion-safe normalization and stops a\n// case difference from minting a phantom drift. An unseen column is added with the\n// one provenance; a column already present gains this provenance in its set\n// (deduped) and keeps the stronger confidence — never duplicated. Order-stable and\n// idempotent, so an OBSERVED fold and an EXTRACTED fold compose either way round.\nexport function foldColumns(\n  existing: readonly ColumnAttr[] | undefined,\n  names: readonly string[],\n  provenance: ProvenanceValue,\n  confidence: number,\n): ColumnAttr[] {\n  const out: ColumnAttr[] = (existing ?? []).map((c) => ({\n    ...c,\n    provenances: [...c.provenances],\n  }))\n  const byName = new Map(out.map((c) => [c.name, c]))\n  for (const raw of names) {\n    const name = raw.toLowerCase()\n    const prior = byName.get(name)\n    if (!prior) {\n      const col: ColumnAttr = { name, provenances: [provenance], confidence }\n      byName.set(name, col)\n      out.push(col)\n      continue\n    }\n    if (!prior.provenances.includes(provenance)) {\n      prior.provenances = normalizeProvenances([...prior.provenances, provenance])\n    }\n    if (confidence > prior.confidence) prior.confidence = confidence\n  }\n  return out\n}\n\n// Fold per-field write-SDK tags onto a table/collection node's `columns` list\n// (ADR-167), returning a fresh array — the parallel of `foldColumns`, kept\n// separate so `foldColumns` (shared by Drizzle / Prisma / SQLAlchemy / OBSERVED\n// ingest) stays byte-identical. `writes` maps a field name to the SDK(s) that\n// wrote it (`client` = firebase/firestore, `admin` = firebase-admin/firestore); it\n// merges into each column's `sdkWrites` set, deduped and order-stable the way\n// `provenances` is. Field names are lowercased to match `foldColumns` (which the\n// column entries went through first), so the tag lands on the right column. A\n// written field with no existing column entry is skipped — the columns fold runs\n// first with the same field set, so the entry is already present; this is the\n// defensive path. This is the declared interface ADR-169's field-guard policy\n// consumes (`col.sdkWrites ?? []`).\nexport function foldSdkWrites(\n  existing: readonly ColumnAttr[] | undefined,\n  writes: Readonly<Record<string, readonly ('client' | 'admin')[]>>,\n): ColumnAttr[] {\n  const out: ColumnAttr[] = (existing ?? []).map((c) => ({\n    ...c,\n    provenances: [...c.provenances],\n    ...(c.sdkWrites ? { sdkWrites: [...c.sdkWrites] } : {}),\n  }))\n  const byName = new Map(out.map((c) => [c.name, c]))\n  for (const [raw, sdks] of Object.entries(writes)) {\n    const col = byName.get(raw.toLowerCase())\n    if (!col) continue\n    const merged = new Set<'client' | 'admin'>([...(col.sdkWrites ?? []), ...sdks])\n    col.sdkWrites = [...merged].sort()\n  }\n  return out\n}\n\n// Read helpers the divergence detector uses so the \"is this column declared /\n// observed\" test lives with the model rather than being re-derived per caller.\nexport function columnIsDeclared(col: ColumnAttr): boolean {\n  return col.provenances.includes(Provenance.EXTRACTED)\n}\nexport function columnIsObserved(col: ColumnAttr): boolean {\n  return col.provenances.includes(Provenance.OBSERVED)\n}\n","// Flag grain (ADR-242). A feature-flag store is a dependency the services call,\n// like a database, and its flags are its grain the way columns are a table's\n// (ADR-157). The store is a `flag-store` InfraNode; each flag is a provenanced\n// entry in its `flags` list. This module is the one place that parses a flag\n// definition and folds one onto that list. The graph mutation stays with the\n// lifecycle authorities that call it: `extract/flags.ts` for the committed\n// definitions and the code that reads each key, `ingest.ts` for what the store is\n// serving and what an evaluation reported. The divergence detector only reads the\n// list. Pure, no graph handle, so extract and ingest can both call in.\n\nimport {\n  Provenance,\n  type FlagAttr,\n  type FlagDefinition,\n  type ProvenanceValue,\n} from '@neat.is/types'\n\nexport const FLAG_STORE_KIND = 'flag-store'\n\n// The four fields that decide what a flag evaluates to. Everything else a flag\n// carries (`description`, `metadata`, a provider's `source`/`selector`/\n// `flagSetId`) is bookkeeping and never part of the compare.\nconst DEFINITION_FIELDS = ['state', 'defaultVariant', 'variants', 'targeting'] as const\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n  return typeof v === 'object' && v !== null && !Array.isArray(v)\n}\n\n// Recursively key-sorted copy, so two definitions that differ only in key order\n// serialize the same.\nfunction sortKeys(v: unknown): unknown {\n  if (Array.isArray(v)) return v.map(sortKeys)\n  if (!isRecord(v)) return v\n  const out: Record<string, unknown> = {}\n  for (const k of Object.keys(v).sort()) out[k] = sortKeys(v[k])\n  return out\n}\n\n// One flag's raw definition → its canonical form, or null when it isn't a flag\n// definition at all (no `state`, or no `variants` object).\nexport function canonicalFlag(raw: unknown): FlagDefinition | null {\n  if (!isRecord(raw)) return null\n  if (typeof raw['state'] !== 'string' || !isRecord(raw['variants'])) return null\n  const dv = raw['defaultVariant']\n  const def: FlagDefinition = {\n    state: raw['state'],\n    defaultVariant: typeof dv === 'string' ? dv : null,\n    variants: sortKeys(raw['variants']) as Record<string, unknown>,\n  }\n  // An empty targeting object is the same as none.\n  const t = raw['targeting']\n  if (t !== undefined && t !== null && !(isRecord(t) && Object.keys(t).length === 0)) {\n    def.targeting = sortKeys(t)\n  }\n  return def\n}\n\n// The top-level definition fields that differ between two canonical forms, in a\n// fixed order. Empty means the two would evaluate the same.\nexport function flagFieldsChanged(a: FlagDefinition, b: FlagDefinition): string[] {\n  const out: string[] = []\n  for (const f of DEFINITION_FIELDS) {\n    if (JSON.stringify(a[f] ?? null) !== JSON.stringify(b[f] ?? null)) out.push(f)\n  }\n  return out\n}\n\n// A flag document's `flags` object → key → canonical definition. Recognition is\n// structural: the document has a top-level `flags` object and at least one entry\n// is a flag definition. Returns null for anything else, so an arbitrary JSON file\n// costs one parse and yields nothing. Only the `flags` object is read (ADR-242's\n// one fenced content read; ADR-016 keeps every other config file paths-only).\nexport function parseFlagDocument(doc: unknown): Map<string, FlagDefinition> | null {\n  if (!isRecord(doc) || !isRecord(doc['flags'])) return null\n  const out = new Map<string, FlagDefinition>()\n  for (const [key, raw] of Object.entries(doc['flags'])) {\n    const def = canonicalFlag(raw)\n    if (def) out.set(key, def)\n  }\n  return out.size > 0 ? out : null\n}\n\nfunction provenancesOf(f: FlagAttr): ProvenanceValue[] {\n  const out: ProvenanceValue[] = []\n  if (f.declared) out.push(Provenance.EXTRACTED)\n  if (f.observed || f.observedVariant !== undefined) out.push(Provenance.OBSERVED)\n  return out.sort()\n}\n\nfunction clone(existing: readonly FlagAttr[] | undefined): FlagAttr[] {\n  return (existing ?? []).map((f) => ({\n    ...f,\n    provenances: [...f.provenances],\n    ...(f.readers ? { readers: f.readers.map((r) => ({ ...r })) } : {}),\n  }))\n}\n\nfunction finish(flags: FlagAttr[]): FlagAttr[] {\n  return flags\n    .map((f) => ({ ...f, provenances: provenancesOf(f) }))\n    .filter((f) => f.provenances.length > 0)\n    .sort((a, b) => a.key.localeCompare(b.key))\n}\n\nexport interface DeclaredFlag {\n  key: string\n  definition: FlagDefinition\n  declaredIn: string\n  readers: { file: string; service: string; line?: number }[]\n}\n\n// The EXTRACTED side, replaced whole on every extraction pass: this pass's\n// declarations and readers are the truth, so a flag deleted from the file or a\n// reader deleted from the code drops out. The OBSERVED side of each flag is kept.\nexport function foldDeclaredFlags(\n  existing: readonly FlagAttr[] | undefined,\n  declared: readonly DeclaredFlag[],\n): FlagAttr[] {\n  const byKey = new Map<string, FlagAttr>()\n  for (const f of clone(existing)) {\n    const { declared: _d, declaredIn: _i, readers: _r, ...observedOnly } = f\n    byKey.set(f.key, observedOnly)\n  }\n  for (const d of declared) {\n    const cur = byKey.get(d.key) ?? { key: d.key, provenances: [] }\n    cur.declared = d.definition\n    cur.declaredIn = d.declaredIn\n    if (d.readers.length > 0) cur.readers = d.readers.map((r) => ({ ...r }))\n    byKey.set(d.key, cur)\n  }\n  return finish([...byKey.values()])\n}\n\n// The OBSERVED side from the store's own reader: what it is serving now. Folded\n// only onto flags the code base declares. A served flag with no committed\n// declaration mints nothing and comes back in `undeclared`, so the reader can\n// count it without the graph growing a flag nobody wrote down.\nexport function foldObservedFlags(\n  existing: readonly FlagAttr[] | undefined,\n  served: ReadonlyMap<string, FlagDefinition>,\n  at: string,\n): { flags: FlagAttr[]; undeclared: string[] } {\n  const flags = clone(existing)\n  const byKey = new Map(flags.map((f) => [f.key, f]))\n  const undeclared: string[] = []\n  for (const [key, def] of served) {\n    const cur = byKey.get(key)\n    if (!cur || !cur.declared) {\n      undeclared.push(key)\n      continue\n    }\n    cur.observed = def\n    cur.observedAt = at\n  }\n  // A declared flag the store no longer serves keeps no stale observed copy.\n  for (const f of flags) {\n    if (f.observed && !served.has(f.key)) {\n      delete f.observed\n      delete f.observedAt\n    }\n  }\n  return { flags: finish(flags), undeclared: undeclared.sort() }\n}\n\n// The OBSERVED side from a service's own evaluation (a `feature_flag.evaluation`\n// span event): the variant it got and why. Same rule as the reader: only a\n// declared flag takes it.\nexport function foldObservedVariant(\n  existing: readonly FlagAttr[] | undefined,\n  key: string,\n  variant: string,\n  reason: string | undefined,\n  at: string,\n): FlagAttr[] | null {\n  const flags = clone(existing)\n  const cur = flags.find((f) => f.key === key)\n  if (!cur || !cur.declared) return null\n  cur.observedVariant = variant\n  if (reason) cur.observedVariantReason = reason\n  else delete cur.observedVariantReason\n  cur.observedVariantAt = at\n  return finish(flags)\n}\n","// Bounded streaming latency-percentile estimator (ADR-190, otel-ingest.md\n// §Per-edge latency). `upsertObservedEdge` records each span's duration into a\n// per-edge histogram and re-derives `latencyMs: { p50, p95 }` from it. The\n// contract forbids retaining raw durations — the ingest path is non-blocking and\n// edge cardinality is unbounded — so this is a fixed-resolution log-linear\n// (HDR-style) histogram: one span updates it in O(1), and the bucket count is\n// bounded regardless of how many spans an edge accumulates.\n//\n// Storage is a sparse `Record<bucketIndex, count>` carried on the edge signal, so\n// a narrow latency distribution costs a handful of keys and the whole thing rides\n// the graph snapshot as additive schema growth. The estimator is deterministic:\n// the same span durations always yield the same buckets and the same percentiles.\n\nexport type LatencyHistogram = Record<string, number>\n\n// Log-linear bucketing. Each power-of-two octave is split into SUB linear\n// sub-buckets, giving ~1/SUB relative resolution (SUB=16 → ~6% bucket width,\n// tight enough to tell a saturated p95 from a healthy one). The covered range\n// runs from 2^MIN_EXP ms (~1µs) to 2^(MAX_EXP+1) ms (~70min); anything below\n// lands in the zero/underflow bucket, anything above in the overflow bucket.\nconst SUB = 16\nconst MIN_EXP = -10\nconst MAX_EXP = 22\n// Index 0 is the zero/underflow bucket; 1..(OCTAVES*SUB) are the log-linear\n// buckets; the last index is the overflow bucket.\nconst OCTAVES = MAX_EXP - MIN_EXP + 1\nconst OVERFLOW_INDEX = OCTAVES * SUB + 1\n\n// The bucket a duration (in ms) falls into. Non-finite, zero, and negative\n// durations land in the underflow bucket rather than throwing — a span with a\n// missing or degenerate duration records as ~0 latency, honestly.\nexport function latencyBucketIndex(ms: number): number {\n  if (!Number.isFinite(ms) || ms <= 0) return 0\n  const e = Math.floor(Math.log2(ms))\n  if (e < MIN_EXP) return 0\n  if (e > MAX_EXP) return OVERFLOW_INDEX\n  const base = 2 ** e\n  const raw = Math.floor((ms / base - 1) * SUB)\n  const s = raw < 0 ? 0 : raw >= SUB ? SUB - 1 : raw\n  return (e - MIN_EXP) * SUB + s + 1\n}\n\n// The representative latency (ms) a bucket stands for — the midpoint of its\n// value range — used when a percentile lands in that bucket.\nfunction bucketRepresentativeMs(index: number): number {\n  if (index <= 0) return 0\n  if (index >= OVERFLOW_INDEX) return 2 ** (MAX_EXP + 1)\n  const zeroBased = index - 1\n  const e = MIN_EXP + Math.floor(zeroBased / SUB)\n  const s = zeroBased % SUB\n  const base = 2 ** e\n  const lower = base * (1 + s / SUB)\n  const upper = base * (1 + (s + 1) / SUB)\n  return (lower + upper) / 2\n}\n\n// Record one duration into the histogram in place. Returns the same object for\n// convenience. Callers pass the edge signal's `latencyHist` (creating it on\n// first observation).\nexport function recordLatency(hist: LatencyHistogram, ms: number): LatencyHistogram {\n  const key = String(latencyBucketIndex(ms))\n  hist[key] = (hist[key] ?? 0) + 1\n  return hist\n}\n\nfunction quantile(hist: LatencyHistogram, q: number): number {\n  const entries = Object.entries(hist)\n    .map(([k, c]) => [Number(k), c] as const)\n    .filter(([idx, c]) => Number.isFinite(idx) && c > 0)\n    .sort((a, b) => a[0] - b[0])\n  let total = 0\n  for (const [, c] of entries) total += c\n  if (total === 0) return 0\n  // Nearest-rank: the smallest bucket whose cumulative count reaches ⌈q·total⌉.\n  const rank = Math.max(1, Math.ceil(q * total))\n  let cumulative = 0\n  for (const [idx, c] of entries) {\n    cumulative += c\n    if (cumulative >= rank) return bucketRepresentativeMs(idx)\n  }\n  return bucketRepresentativeMs(entries[entries.length - 1]![0])\n}\n\nfunction round(ms: number): number {\n  // Two significant-ish decimals — enough to read a p95 without pretending the\n  // bucketed estimate is exact.\n  return Math.round(ms * 100) / 100\n}\n\n// Derive { p50, p95 } from the histogram, or undefined when it holds no\n// observations — an edge with no recorded latency reads honestly absent, never a\n// fabricated zero (file-awareness.md §6).\nexport function latencyPercentiles(\n  hist: LatencyHistogram | undefined,\n): { p50: number; p95: number } | undefined {\n  if (!hist) return undefined\n  let total = 0\n  for (const c of Object.values(hist)) total += c\n  if (total === 0) return undefined\n  return { p50: round(quantile(hist, 0.5)), p95: round(quantile(hist, 0.95)) }\n}\n","// ──────────────────────────────────────────────────────────────────────────\n// Stacktrace code-locus recovery (ADR-216)\n//\n// An OBSERVED exception span often carries `exception.stacktrace` but no\n// `code.*` semconv attributes — Python auto-instrumentation records the\n// exception through `record_exception` without stamping a call site, and the\n// same is true of many runtimes' exception recording. The declaring file:line\n// is still named, plainly, inside the stacktrace text. This module recovers the\n// deepest APPLICATION frame from that text so incident localization can join it\n// to a FileNode / SymbolNode the graph already carries — turning a service-level\n// incident back into the code-grain locus the fusion query needs.\n//\n// It keys STRICTLY on generic frame syntax and generic vendor-prefix markers,\n// never on a language / framework / provider name (ADR-158 §6). A new frame\n// shape is a new row in FRAME_SHAPES; a new vendor marker a new row in\n// VENDOR_MARKERS. There is no per-language branch anywhere below.\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface StackFrame {\n  file: string\n  line: number\n  fn?: string\n}\n\n// One frame syntax. `deepest` records where the throw-site frame sits among the\n// matches of THIS shape — a property of the syntax, not of any language: the\n// `File \"…\", line N` shape lists most-recent last (the raising line is at the\n// bottom of the trace), the `at …` shapes list most-recent first (the throw\n// site is at the top). Keying an ordering convention on the frame syntax is\n// keying on syntax, which ADR-158 §6 permits; keying on the language that uses\n// the syntax is what it forbids.\ninterface FrameShape {\n  re: RegExp\n  file: number // capture-group index of the file path\n  line: number // capture-group index of the line number\n  fn?: number // capture-group index of the function name, when the shape carries one\n  deepest: 'first' | 'last'\n}\n\nconst FRAME_SHAPES: readonly FrameShape[] = [\n  // `File \"<path>\", line <N>, in <func>` — the \"most recent call last\" shape.\n  { re: /File \"([^\"]+)\", line (\\d+)(?:, in (\\S+))?/, file: 1, line: 2, fn: 3, deepest: 'last' },\n  // `at <func> (<path>:<line>:<col>)` — named call frame, most recent first.\n  { re: /\\bat\\s+(.+?)\\s+\\((.+?):(\\d+):\\d+\\)/, file: 2, line: 3, fn: 1, deepest: 'first' },\n  // `at <path>:<line>:<col>` — anonymous call frame, most recent first.\n  { re: /\\bat\\s+(.+?):(\\d+):\\d+/, file: 1, line: 2, deepest: 'first' },\n  // `at <qualified.method>(<File.ext>:<line>)` — JVM-style, most recent first.\n  { re: /\\bat\\s+(.+?)\\((\\S+\\.\\w+):(\\d+)\\)/, file: 2, line: 3, fn: 1, deepest: 'first' },\n]\n\n// Generic markers for a non-application (runtime / vendor / dependency) frame —\n// directory conventions and synthetic-frame forms, no language or provider name.\n// A frame whose file path contains any of these is dependency / runtime code,\n// not the application's own. The graph join stays the ultimate arbiter: even if\n// a frame slips through, incident localization attributes to a code node ONLY\n// when the frame resolves to a FileNode the graph carries — so this list picks\n// the right application frame, it does not gate honesty.\nconst VENDOR_MARKERS: readonly string[] = [\n  'node_modules', // dependency root\n  'site-packages', // installed-package root\n  'dist-packages', // distro-packaged root\n  'node:', // runtime-internal module scheme (a stdlib/runtime-root frame)\n]\n\ninterface OrientedFrame {\n  frame: StackFrame\n  deepest: 'first' | 'last'\n}\n\nfunction matchFrame(line: string): OrientedFrame | null {\n  for (const shape of FRAME_SHAPES) {\n    const m = shape.re.exec(line)\n    if (!m) continue\n    const file = m[shape.file]\n    const lineNo = Number(m[shape.line])\n    if (!file || !Number.isFinite(lineNo)) continue\n    const fn = shape.fn !== undefined ? m[shape.fn] : undefined\n    return { frame: { file, line: lineNo, ...(fn ? { fn } : {}) }, deepest: shape.deepest }\n  }\n  return null\n}\n\nfunction isApplicationFrame(file: string): boolean {\n  // Synthetic frames (`<frozen importlib._bootstrap>`, `<anonymous>`, `<string>`)\n  // name no real source file, so they are never application code.\n  if (file.startsWith('<')) return false\n  const norm = file.split('\\\\').join('/')\n  for (const marker of VENDOR_MARKERS) {\n    if (norm.includes(marker)) return false\n  }\n  return true\n}\n\n// Recover the deepest application frame — the frame nearest the throw site that\n// is not runtime / vendor code. Returns null when the stacktrace names no\n// application frame at all: an all-vendor trace recovers nothing, so the caller\n// keeps its honest service attribution and nothing is fabricated (ADR-158 §6).\nexport function deepestApplicationFrame(stacktrace: string | undefined): StackFrame | null {\n  if (!stacktrace) return null\n\n  const appFrames: OrientedFrame[] = []\n  for (const raw of stacktrace.split('\\n')) {\n    const matched = matchFrame(raw)\n    if (!matched) continue\n    if (!isApplicationFrame(matched.frame.file)) continue\n    appFrames.push(matched)\n  }\n  if (appFrames.length === 0) return null\n\n  // Orientation is a property of the frame syntax, and a real trace is written\n  // in one syntax: the `File \"…\"` shape puts the throw site last, the `at …`\n  // shapes put it first. Read the dominant orientation off the frames we matched\n  // and pick the throw-site-nearest application frame among that orientation.\n  const orientation: 'first' | 'last' = appFrames.some((f) => f.deepest === 'last')\n    ? 'last'\n    : 'first'\n  const oriented = appFrames.filter((f) => f.deepest === orientation)\n  const chosen = orientation === 'last' ? oriented[oriented.length - 1] : oriented[0]\n  return chosen ? chosen.frame : null\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport ignore, { type Ignore } from 'ignore'\nimport { minimatch } from 'minimatch'\nimport type { ServiceNode } from '@neat.is/types'\nimport { NodeType, serviceId } from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport {\n  IGNORED_DIRS,\n  exists,\n  isPythonVenvDir,\n  readJson,\n  type DiscoveredService,\n  type PackageJson,\n} from './shared.js'\nimport { discoverPythonService, pythonToPackage } from './python.js'\nimport { discoverGoService } from './go.js'\nimport { splitGoBinaries } from './go-binaries.js'\nimport { discoverRubyService } from './ruby.js'\nimport { discoverPhpService } from './php.js'\nimport { discoverCsharpService, hasCsharpProject } from './csharp.js'\nimport { discoverJavaService, hasJavaManifest } from './java.js'\nimport { discoverKotlinService } from './kotlin.js'\nimport { discoverRustService, hasRustManifest } from './rust.js'\nimport { discoverCppService, hasCppManifest } from './cpp.js'\nimport {\n  discoverDockerfileService,\n  hasDockerfileDeclaredService,\n} from './dockerfile-service.js'\nimport { computeServiceOwner, loadCodeowners } from './owners.js'\nimport { recordExtractionError } from './errors.js'\n\nconst DEFAULT_SCAN_DEPTH = 5\n\ninterface RootPackageJson extends PackageJson {\n  workspaces?: string[] | { packages?: string[] }\n  main?: unknown\n  module?: unknown\n  bin?: unknown\n  scripts?: Record<string, unknown>\n}\n\n// A workspaces root that is also an app (#1538): it declares an entry or a\n// `start` script, so it runs itself, the way an Expo / React Native client sits at\n// the repo root beside a `backend` workspace. A pure monorepo root (tooling\n// scripts, no entry) stays a container.\nfunction rootRunsItself(pkg: RootPackageJson): boolean {\n  if (!pkg.name) return false\n  if (typeof pkg.main === 'string' || typeof pkg.module === 'string' || pkg.bin !== undefined) return true\n  return typeof pkg.scripts?.['start'] === 'string'\n}\n\n// #1557: a package.json with no `name` is still a service when it is an app: it\n// declares an entry, a `start` or `dev` script, or a framework. Apps often leave the\n// name out (npm needs one only to publish), e.g. vercel/commerce. A bare\n// `{\"type\": \"module\"}` marker or a tooling-only root stays out.\nfunction unnamedPackageIsApp(pkg: RootPackageJson): boolean {\n  if (typeof pkg.main === 'string' || typeof pkg.module === 'string' || pkg.bin !== undefined) return true\n  if (typeof pkg.scripts?.['start'] === 'string' || typeof pkg.scripts?.['dev'] === 'string') return true\n  return detectJsFramework(pkg) !== undefined\n}\n\nfunction parseScanDepth(): number {\n  const raw = process.env.NEAT_SCAN_DEPTH\n  if (!raw) return DEFAULT_SCAN_DEPTH\n  const n = Number.parseInt(raw, 10)\n  return Number.isFinite(n) && n >= 0 ? n : DEFAULT_SCAN_DEPTH\n}\n\nfunction workspaceGlobs(pkg: RootPackageJson): string[] | null {\n  const ws = pkg.workspaces\n  if (!ws) return null\n  if (Array.isArray(ws)) return ws.length > 0 ? ws : null\n  if (Array.isArray(ws.packages)) return ws.packages.length > 0 ? ws.packages : null\n  return null\n}\n\nasync function hasPythonManifest(dir: string): Promise<boolean> {\n  return (\n    (await exists(path.join(dir, 'pyproject.toml'))) ||\n    (await exists(path.join(dir, 'requirements.txt'))) ||\n    (await exists(path.join(dir, 'setup.py')))\n  )\n}\n\n// go.mod, or golang/dep's Gopkg.toml / Gopkg.lock for a repository that predates\n// modules (ADR-256).\nasync function hasGoManifest(dir: string): Promise<boolean> {\n  return (\n    (await exists(path.join(dir, 'go.mod'))) ||\n    (await exists(path.join(dir, 'Gopkg.toml'))) ||\n    (await exists(path.join(dir, 'Gopkg.lock')))\n  )\n}\n\nasync function hasRubyManifest(dir: string): Promise<boolean> {\n  return exists(path.join(dir, 'Gemfile'))\n}\n\nasync function hasPhpManifest(dir: string): Promise<boolean> {\n  return exists(path.join(dir, 'composer.json'))\n}\n\n// C#'s marker is a glob (`*.csproj` / `*.sln`), not a fixed filename, so it can't\n// be a single `exists` check the way the others are — `hasCsharpProject` reads the\n// directory (extract/csharp.ts).\nasync function hasCsharpManifest(dir: string): Promise<boolean> {\n  return hasCsharpProject(dir)\n}\n\nasync function loadGitignore(scanPath: string): Promise<Ignore | null> {\n  const gitignorePath = path.join(scanPath, '.gitignore')\n  if (!(await exists(gitignorePath))) return null\n  const raw = await fs.readFile(gitignorePath, 'utf8')\n  return ignore().add(raw)\n}\n\ninterface WalkOptions {\n  maxDepth: number\n  ig: Ignore | null\n}\n\nasync function walkDirs(\n  start: string,\n  scanPath: string,\n  options: WalkOptions,\n  visit: (dir: string) => Promise<void> | void,\n): Promise<void> {\n  async function recurse(current: string, depth: number): Promise<void> {\n    if (depth > options.maxDepth) return\n    const entries = await fs.readdir(current, { withFileTypes: true }).catch(() => [])\n    for (const entry of entries) {\n      if (!entry.isDirectory()) continue\n      if (IGNORED_DIRS.has(entry.name)) continue\n      const child = path.join(current, entry.name)\n      if (options.ig) {\n        const rel = path.relative(scanPath, child).split(path.sep).join('/')\n        // Trailing slash so `ignore` evaluates the entry as a directory; without\n        // it, gitignore patterns like `dist/` won't match because the lib\n        // distinguishes file vs. directory tests.\n        if (rel && options.ig.ignores(rel + '/')) continue\n      }\n      // Issue #344 — `pyvenv.cfg` marks every directory that `python -m venv`\n      // or `virtualenv` creates, regardless of what the wrapper dir is called.\n      // The `IGNORED_DIRS` name list catches the common shapes (`.venv`,\n      // `venv`, `.tox`); this catches the long-tail ones (`env-3.11`,\n      // `.direnv`, ad-hoc names).\n      if (await isPythonVenvDir(child)) continue\n      await visit(child)\n      await recurse(child, depth + 1)\n    }\n  }\n  await recurse(start, 0)\n}\n\nasync function expandWorkspaceGlobs(\n  scanPath: string,\n  globs: string[],\n): Promise<string[]> {\n  const found = new Set<string>()\n  const scanDepth = parseScanDepth()\n\n  for (const raw of globs) {\n    const pattern = raw.replace(/^\\.\\//, '')\n\n    if (!pattern.includes('*')) {\n      const candidate = path.join(scanPath, pattern)\n      if (await exists(path.join(candidate, 'package.json'))) found.add(candidate)\n      continue\n    }\n\n    const segments = pattern.split('/')\n    const staticSegments: string[] = []\n    for (const seg of segments) {\n      if (seg.includes('*')) break\n      staticSegments.push(seg)\n    }\n    const start = path.join(scanPath, ...staticSegments)\n    if (!(await exists(start))) continue\n\n    const hasDoubleStar = pattern.includes('**')\n    const walkDepth = hasDoubleStar\n      ? scanDepth\n      : Math.max(0, segments.length - staticSegments.length - 1)\n\n    await walkDirs(start, scanPath, { maxDepth: walkDepth, ig: null }, async (dir) => {\n      const rel = path.relative(scanPath, dir).split(path.sep).join('/')\n      if (minimatch(rel, pattern) && (await exists(path.join(dir, 'package.json')))) {\n        found.add(dir)\n      }\n    })\n  }\n\n  return [...found]\n}\n\n// Framework detection from package.json deps (ADR-074 §3). Mirrors the\n// installer dispatch precedence so a project the installer recognises as\n// Remix records `framework: 'remix'` on its ServiceNode. The static\n// extractor sees only manifest data, so detection is dep-presence based —\n// it doesn't crack open config files. Detection precedence: Next → Remix\n// → SvelteKit → Nuxt → Astro → NestJS → vanilla Node.\nfunction detectJsFramework(pkg: PackageJson): string | undefined {\n  const deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) }\n  if (deps['next'] !== undefined) return 'next'\n  if (deps['remix'] !== undefined) return 'remix'\n  for (const k of Object.keys(deps)) {\n    if (k.startsWith('@remix-run/')) return 'remix'\n  }\n  if (deps['@sveltejs/kit'] !== undefined) return 'sveltekit'\n  if (deps['nuxt'] !== undefined) return 'nuxt'\n  if (deps['astro'] !== undefined) return 'astro'\n  if (deps['@nestjs/core'] !== undefined) return 'nestjs'\n  return undefined\n}\n\n// A JS-manifest service is TypeScript when its package depends on `typescript`\n// or carries a tsconfig — otherwise we default to javascript. The per-file\n// extractor already routes by extension (`languageForPath`); this only sets the\n// ServiceNode's own `language` field, which the static walker can't read off a\n// single file. One readdir, conservative on the javascript side.\nasync function detectJsServiceLanguage(\n  dir: string,\n  pkg: PackageJson,\n): Promise<'typescript' | 'javascript'> {\n  const deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) }\n  if (deps['typescript'] !== undefined) return 'typescript'\n  const entries = await fs.readdir(dir).catch(() => [] as string[])\n  if (entries.some((name) => /^tsconfig(\\..+)?\\.json$/.test(name))) return 'typescript'\n  return 'javascript'\n}\n\nasync function discoverNodeService(\n  scanPath: string,\n  dir: string,\n): Promise<DiscoveredService | null> {\n  const pkgPath = path.join(dir, 'package.json')\n  if (!(await exists(pkgPath))) return null\n  let pkg: PackageJson\n  try {\n    pkg = await readJson<PackageJson>(pkgPath)\n  } catch (err) {\n    recordExtractionError('services', path.relative(scanPath, pkgPath), err)\n    return null\n  }\n  // No declared name: the directory basename, the same default ADR-273 gives a\n  // project's display name and the Go/Ruby/Java/Rust readers give a nameless\n  // manifest. It depends only on where the service sits, so it is stable across\n  // passes, which the ServiceNode id needs.\n  const declared = typeof pkg.name === 'string' ? pkg.name.trim() : ''\n  if (!declared && !unnamedPackageIsApp(pkg as RootPackageJson)) return null\n  const name = declared || path.basename(path.resolve(dir))\n  const framework = detectJsFramework(pkg)\n  const language = await detectJsServiceLanguage(dir, pkg)\n  const node: ServiceNode = {\n    id: serviceId(name),\n    type: NodeType.ServiceNode,\n    name,\n    language,\n    version: pkg.version,\n    dependencies: pkg.dependencies ?? {},\n    repoPath: path.relative(scanPath, dir),\n    ...(pkg.engines?.node ? { nodeEngine: pkg.engines.node } : {}),\n    ...(framework ? { framework } : {}),\n  }\n  // Every later phase names the service by `pkg.name` (file, symbol and route ids\n  // all hang off it), so the fallback has to be written there too, not only on the node.\n  if (declared) return { pkg, dir, node }\n  return { pkg: { ...pkg, name }, dir, node, nameFromDir: true }\n}\n\nasync function discoverPyService(\n  scanPath: string,\n  dir: string,\n): Promise<DiscoveredService | null> {\n  const py = await discoverPythonService(dir)\n  if (!py) return null\n  const pkg = pythonToPackage(py)\n  const node: ServiceNode = {\n    id: serviceId(py.name),\n    type: NodeType.ServiceNode,\n    name: py.name,\n    language: 'python',\n    version: py.version,\n    dependencies: py.dependencies,\n    repoPath: path.relative(scanPath, dir),\n  }\n  return { pkg, dir, node }\n}\n\n// Phase 1 — discover service directories under scanPath. A service is any\n// directory containing a language manifest — a JS/TS `package.json`, a Python\n// `pyproject.toml` / `requirements.txt` / `setup.py`, a Go `go.mod`, a Ruby\n// `Gemfile`, a PHP `composer.json`, a C#/.NET `*.csproj` / `*.sln` (ADR-196), or a\n// Java or Kotlin `pom.xml` / `build.gradle` / `build.gradle.kts` (ADR-197, ADR-199 —\n// the JVM manifest is shared, so the `.kt`-vs-`.java` source decides which language),\n// or a Rust `Cargo.toml` (ADR-201), or a C++ `CMakeLists.txt` (ADR-202) — with the\n// manifest paths tried in that order so an earlier one wins on tie. A\n// manifest-less directory that a `Dockerfile` plus source declares is discovered last\n// (ADR-194), so a manifest always takes precedence and nothing double-mints.\n//\n// If the root `package.json` declares `workspaces`, those globs are\n// authoritative — we don't fall back to a free recursive walk. The root is a\n// service too when it runs itself (an entry or a `start` script, #1538). Otherwise we\n// walk recursively, depth-bounded by `NEAT_SCAN_DEPTH` (default 5), skipping\n// `IGNORED_DIRS` and anything matched by the root `.gitignore`.\n//\n// Two manifests sharing a `name` collapse to one node per ADR-010; the\n// duplicate logs a warning naming both paths.\nexport async function discoverServices(scanPath: string): Promise<DiscoveredService[]> {\n  const rootPkgPath = path.join(scanPath, 'package.json')\n  let rootPkg: RootPackageJson | null = null\n  if (await exists(rootPkgPath)) {\n    try {\n      rootPkg = await readJson<RootPackageJson>(rootPkgPath)\n    } catch (err) {\n      recordExtractionError(\n        'services workspaces',\n        path.relative(scanPath, rootPkgPath),\n        err,\n      )\n    }\n  }\n  const wsGlobs = rootPkg ? workspaceGlobs(rootPkg) : null\n\n  const candidateDirs: string[] = []\n  if (wsGlobs) {\n    // The root joins as a service only when it is itself an app; nearest-service\n    // ownership (ADR-200, below) keeps its file walk out of the members.\n    if (rootPkg && rootRunsItself(rootPkg)) candidateDirs.push(scanPath)\n    candidateDirs.push(...(await expandWorkspaceGlobs(scanPath, wsGlobs)))\n  } else {\n    if (rootPkg && (rootPkg.name || unnamedPackageIsApp(rootPkg))) {\n      candidateDirs.push(scanPath)\n    } else if (\n      (await hasPythonManifest(scanPath)) ||\n      (await hasGoManifest(scanPath)) ||\n      (await hasRubyManifest(scanPath)) ||\n      (await hasPhpManifest(scanPath)) ||\n      (await hasCsharpManifest(scanPath)) ||\n      (await hasJavaManifest(scanPath)) ||\n      (await hasRustManifest(scanPath)) ||\n      (await hasCppManifest(scanPath))\n    ) {\n      // A Python / Go / Rails / Laravel / .NET / Java / Rust / C++ project commonly keeps\n      // its manifest at the repo root with the code in a subpackage and no\n      // package.json anywhere. The walk only visits descendants, so without this\n      // the root manifest is never seen and the whole project discovers zero\n      // services.\n      candidateDirs.push(scanPath)\n    }\n    const ig = await loadGitignore(scanPath)\n    await walkDirs(\n      scanPath,\n      scanPath,\n      { maxDepth: parseScanDepth(), ig },\n      async (dir) => {\n        if (await exists(path.join(dir, 'package.json'))) {\n          candidateDirs.push(dir)\n        } else if (\n          (await hasPythonManifest(dir)) ||\n          (await hasGoManifest(dir)) ||\n          (await hasRubyManifest(dir)) ||\n          (await hasPhpManifest(dir)) ||\n          (await hasCsharpManifest(dir)) ||\n          (await hasJavaManifest(dir)) ||\n          (await hasRustManifest(dir)) ||\n          (await hasCppManifest(dir))\n        ) {\n          candidateDirs.push(dir)\n        } else if (await hasDockerfileDeclaredService(dir)) {\n          // A manifest-less dir that a Dockerfile plus source declares a service\n          // (ADR-194). Ordered last so any manifest wins; the walk has already\n          // skipped IGNORED_DIRS and .gitignore, so vendored dirs never land here.\n          candidateDirs.push(dir)\n        }\n      },\n    )\n  }\n\n  candidateDirs.sort()\n\n  const seen = new Map<string, string>()\n  const seenDirs = new Set<string>()\n  const out: DiscoveredService[] = []\n  // Services named after their directory are placed after every declared name is\n  // in, so a sibling that declares the same name keeps it (#1557).\n  const fromDir: DiscoveredService[] = []\n  for (const dir of candidateDirs) {\n    const service =\n      (await discoverNodeService(scanPath, dir)) ??\n      (await discoverPyService(scanPath, dir)) ??\n      (await discoverGoService(scanPath, dir)) ??\n      (await discoverRubyService(scanPath, dir)) ??\n      (await discoverPhpService(scanPath, dir)) ??\n      (await discoverCsharpService(scanPath, dir)) ??\n      // Kotlin runs ahead of Java: both mark a service with the same Maven/Gradle\n      // manifest, so Kotlin claims a JVM-manifest dir whose source is `.kt` (ADR-199)\n      // and a `.java`-dominant one falls through to the Java reader unchanged.\n      (await discoverKotlinService(scanPath, dir)) ??\n      (await discoverJavaService(scanPath, dir)) ??\n      // Rust keys on a `Cargo.toml`, a manifest no other language shares (ADR-201),\n      // so its order among the distinct-manifest discoverers doesn't matter.\n      (await discoverRustService(scanPath, dir)) ??\n      // C++ keys on a `CMakeLists.txt`, likewise a manifest no other language shares\n      // (ADR-202), so it too sits anywhere among the distinct-manifest discoverers.\n      (await discoverCppService(scanPath, dir)) ??\n      (await discoverDockerfileService(scanPath, dir))\n    if (!service) continue\n\n    // A C# service root and its nested `src/` project resolve to the same service\n    // directory (ADR-196), and the recursive walk surfaces both as candidates.\n    // Collapse them silently on that resolved directory — before the name check,\n    // so the nested layout never double-mints and never trips the duplicate-name\n    // warning. Every other discoverer anchors on the candidate dir itself, which\n    // is unique per candidate, so this only ever folds the C# root/src pair.\n    if (seenDirs.has(service.dir)) continue\n    seenDirs.add(service.dir)\n    if (service.nameFromDir) {\n      fromDir.push(service)\n      continue\n    }\n\n    const existingDir = seen.get(service.node.name)\n    if (existingDir !== undefined) {\n      const a = path.relative(scanPath, existingDir) || '.'\n      const b = path.relative(scanPath, dir) || '.'\n      console.warn(\n        `[neat] duplicate package name \"${service.node.name}\" — keeping ${a}, ignoring ${b}`,\n      )\n      continue\n    }\n    seen.set(service.node.name, dir)\n    out.push(service)\n\n    // ADR-255 — a Go module with two or more `cmd/<name>/main.go` is one service\n    // per binary, plus the module service for the code they share.\n    for (const bin of await splitGoBinaries(service)) {\n      const taken = seen.get(bin.node.name)\n      if (taken !== undefined) {\n        console.warn(\n          `[neat] duplicate package name \"${bin.node.name}\" — keeping ${path.relative(scanPath, taken) || '.'}, ignoring the Go binary cmd/${bin.node.name}`,\n        )\n        continue\n      }\n      seen.set(bin.node.name, dir)\n      out.push(bin)\n    }\n  }\n\n  // A directory-named service whose basename a declared service already holds takes\n  // its repo-relative path instead (`apps/web`), which is unique per directory and\n  // still a real name, not a made-up one. The root has no path to fall back on, so a\n  // clash there keeps the declared service and skips the root with the usual warning.\n  for (const service of fromDir) {\n    let name = service.node.name\n    if (seen.has(name)) {\n      const rel = service.node.repoPath.split(path.sep).join('/')\n      if (!rel || seen.has(rel)) {\n        console.warn(\n          `[neat] duplicate package name \"${name}\": keeping ${path.relative(scanPath, seen.get(name)!) || '.'}, ignoring ${rel || '.'} (no name in its package.json)`,\n        )\n        continue\n      }\n      name = rel\n      service.node = { ...service.node, id: serviceId(name), name }\n      service.pkg = { ...service.pkg, name }\n    }\n    seen.set(name, service.dir)\n    out.push(service)\n  }\n  // Keep discovery order by directory, as before. The sort is stable, so a Go\n  // module still precedes the binaries split from it.\n  if (fromDir.length) out.sort((a, b) => (a.dir < b.dir ? -1 : a.dir > b.dir ? 1 : 0))\n\n  // Owner extraction (ADR-054). CODEOWNERS first, package.json `author`\n  // fallback, undefined otherwise. Read once per discovery pass; the file\n  // is small and parsing it per-service would be wasteful.\n  const codeowners = await loadCodeowners(scanPath)\n  for (const service of out) {\n    const owner = await computeServiceOwner(codeowners, service.node.repoPath, service.dir)\n    if (owner !== undefined) service.node.owner = owner\n  }\n\n  // ADR-200 — nearest-service-wins file ownership. A source file belongs to the\n  // deepest discovered service that contains it. When the root manifest has a\n  // name but no `workspaces`, the root becomes a service at `scanPath` *and* the\n  // recursive walk discovers every nested service under it; without ownership the\n  // root's file walk re-visits each nested service's subtree and re-mints its\n  // symbols/routes/ORM nodes under the root — inert repo-relative phantoms that\n  // never fuse and double-count every nested service. So for each service, record\n  // the dirs of the other discovered services nested strictly under it; the shared\n  // file walk skips those subtrees. Applied uniformly to every service (root,\n  // no-workspace, and workspace member alike) — a workspace member that nests a\n  // discovered service excludes it the same way.\n  const resolvedDirs = out.map((s) => path.resolve(s.dir))\n  for (let i = 0; i < out.length; i++) {\n    const self = resolvedDirs[i]!\n    const nested: string[] = []\n    for (let j = 0; j < out.length; j++) {\n      if (i === j) continue\n      const other = resolvedDirs[j]!\n      if (other.startsWith(self + path.sep)) nested.push(other)\n    }\n    // Appended, not replaced: a Go binary split (ADR-255) has already excluded the\n    // files it doesn't own.\n    out[i]!.excludeDirs = [...(out[i]!.excludeDirs ?? []), ...nested]\n  }\n\n  return out\n}\n\nexport function addServiceNodes(graph: NeatGraph, services: DiscoveredService[]): number {\n  let nodesAdded = 0\n  for (const service of services) {\n    if (!graph.hasNode(service.node.id)) {\n      graph.addNode(service.node.id, { ...service.node, discoveredVia: 'static' })\n      nodesAdded++\n      continue\n    }\n    // OTel ingest may have auto-created a minimal node at this id. Merge per\n    // ADR-033 / identity contract: static fields override OTel-derived fields,\n    // and discoveredVia flips to 'merged' when both layers contributed.\n    const existing = graph.getNodeAttributes(service.node.id) as ServiceNode\n    const mergedDiscoveredVia: 'static' | 'otel' | 'merged' =\n      existing.discoveredVia === 'otel' ? 'merged' : 'static'\n    graph.replaceNodeAttributes(service.node.id, {\n      ...existing,\n      ...service.node,\n      discoveredVia: mergedDiscoveredVia,\n    })\n  }\n  return nodesAdded\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport { exists, type PackageJson } from './shared.js'\n\n// Lines like `psycopg2==2.7.0`, `psycopg2 == 2.7.0`, `psycopg2[extras]==2.7`,\n// or `psycopg2~=2.7,<3`. We capture the package name and the first version\n// that follows an `==` operator. Anything else (range, no pin, no version) is\n// recorded with an empty version — the compat matrix's semver coercer treats\n// those as \"can't reason\" and under-flags rather than over-flags.\nconst REQUIREMENT_LINE = /^\\s*([A-Za-z0-9_.-]+)(?:\\[[^\\]]*\\])?\\s*(?:(==)\\s*([A-Za-z0-9_.+-]+))?/\n\nfunction parseRequirementsTxt(content: string): Record<string, string> {\n  const out: Record<string, string> = {}\n  for (const rawLine of content.split('\\n')) {\n    const line = rawLine.split('#')[0]?.trim()\n    if (!line) continue\n    if (line.startsWith('-')) continue // -r requirements-dev.txt etc.\n    const match = REQUIREMENT_LINE.exec(line)\n    if (!match) continue\n    const name = match[1]!.toLowerCase()\n    const version = match[3] ?? ''\n    out[name] = version\n  }\n  return out\n}\n\ninterface PyProjectFile {\n  project?: {\n    name?: string\n    version?: string\n    dependencies?: string[]\n  }\n  tool?: {\n    poetry?: {\n      name?: string\n      version?: string\n      dependencies?: Record<string, string | { version?: string }>\n    }\n  }\n}\n\nfunction depsFromPyProject(pyproject: PyProjectFile): Record<string, string> {\n  const out: Record<string, string> = {}\n\n  // PEP 621 — [project] dependencies = [\"psycopg2==2.7.0\", \"requests\"]\n  for (const entry of pyproject.project?.dependencies ?? []) {\n    const match = REQUIREMENT_LINE.exec(entry)\n    if (!match) continue\n    out[match[1]!.toLowerCase()] = match[3] ?? ''\n  }\n\n  // Poetry — [tool.poetry.dependencies] psycopg2 = \"2.7.0\"\n  const poetryDeps = pyproject.tool?.poetry?.dependencies ?? {}\n  for (const [name, value] of Object.entries(poetryDeps)) {\n    if (name.toLowerCase() === 'python') continue\n    const raw = typeof value === 'string' ? value : (value?.version ?? '')\n    out[name.toLowerCase()] = raw.replace(/^[\\^~><=v\\s]+/, '')\n  }\n  return out\n}\n\nexport interface PythonService {\n  name: string\n  version?: string\n  dependencies: Record<string, string>\n}\n\n// Detect a Python service by the conventional manifest files. We try\n// pyproject.toml first because it can name the package; fallback to the\n// directory name when only requirements.txt or setup.py is present.\nexport async function discoverPythonService(serviceDir: string): Promise<PythonService | null> {\n  const pyprojectPath = path.join(serviceDir, 'pyproject.toml')\n  const requirementsPath = path.join(serviceDir, 'requirements.txt')\n  const setupPath = path.join(serviceDir, 'setup.py')\n\n  const hasPyproject = await exists(pyprojectPath)\n  const hasRequirements = await exists(requirementsPath)\n  const hasSetup = await exists(setupPath)\n  if (!hasPyproject && !hasRequirements && !hasSetup) return null\n\n  let name = path.basename(serviceDir)\n  let version: string | undefined\n  const dependencies: Record<string, string> = {}\n\n  if (hasPyproject) {\n    const raw = await fs.readFile(pyprojectPath, 'utf8')\n    const pyproject = parseToml(raw) as PyProjectFile\n    name = pyproject.project?.name ?? pyproject.tool?.poetry?.name ?? name\n    version = pyproject.project?.version ?? pyproject.tool?.poetry?.version ?? undefined\n    Object.assign(dependencies, depsFromPyProject(pyproject))\n  }\n\n  if (hasRequirements) {\n    const raw = await fs.readFile(requirementsPath, 'utf8')\n    Object.assign(dependencies, parseRequirementsTxt(raw))\n  }\n\n  return { name, version, dependencies }\n}\n\n// Build the same `pkg`-shaped shim the JS path uses so downstream phases\n// (databases, calls, etc.) can keep reading service.pkg.dependencies and\n// service.pkg.name without caring which language produced the service.\nexport function pythonToPackage(service: PythonService): PackageJson {\n  return {\n    name: service.name,\n    version: service.version,\n    dependencies: service.dependencies,\n  }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { ServiceNode } from '@neat.is/types'\nimport { serviceId } from '@neat.is/types'\nimport type { DiscoveredService } from './shared.js'\nimport { IGNORED_DIRS } from './shared.js'\nimport { goImports, readGoModule } from './go.js'\n\n// ADR-255 — one Go module, several binaries. A repository like DeathStarBench's\n// hotelReservation is a single go.mod with one `cmd/<name>/main.go` per deployed\n// service, and its packages under `services/<name>/`. Discovery keys a Go service\n// on go.mod, so the whole repository was one service named after the module,\n// while each binary reports its own `service.name` at runtime (`frontend`, `geo`).\n//\n// When a module has two or more `cmd/<name>/main.go`, each becomes a service named\n// `<name>`. A Go package is a directory, so ownership is per package directory:\n// - a package reachable from exactly one binary's import closure (imports inside\n//   this module only) belongs to that binary's service;\n// - a package reachable from several binaries, or from none, stays on the module\n//   service as shared code, never duplicated;\n// - a directory with no Go package of its own (static assets, a config dir)\n//   follows its nearest ancestor package directory, else the module.\n// Every binary service and the module service keep the module root as `dir`, so\n// file ids stay module-relative; each one excludes the files it doesn't own.\n// A module with one main (or none) is returned unchanged, so existing repos don't\n// move.\n\ninterface GoFile {\n  abs: string\n  dir: string\n}\n\nasync function listModuleFiles(moduleDir: string): Promise<string[]> {\n  const out: string[] = []\n  async function walk(current: string, isRoot: boolean): Promise<void> {\n    const entries = await fs.readdir(current, { withFileTypes: true }).catch(() => [])\n    // A nested go.mod or Gopkg.toml is another module; its files are not this module's.\n    if (!isRoot && entries.some((e) => e.isFile() && (e.name === 'go.mod' || e.name === 'Gopkg.toml'))) return\n    for (const entry of entries) {\n      const full = path.join(current, entry.name)\n      if (entry.isDirectory()) {\n        if (IGNORED_DIRS.has(entry.name) || entry.name.startsWith('.')) continue\n        await walk(full, false)\n      } else if (entry.isFile()) {\n        out.push(full)\n      }\n    }\n  }\n  await walk(moduleDir, true)\n  return out\n}\n\nexport async function splitGoBinaries(module: DiscoveredService): Promise<DiscoveredService[]> {\n  if (module.node.language !== 'go') return []\n  const root = path.resolve(module.dir)\n  const mod = await readGoModule(root)\n  if (!mod) return []\n  const modulePath = mod.module\n  const cmdDir = path.join(root, 'cmd')\n  const cmdEntries = await fs.readdir(cmdDir, { withFileTypes: true }).catch(() => [])\n  const binaries: string[] = []\n  for (const e of cmdEntries) {\n    if (!e.isDirectory()) continue\n    const main = path.join(cmdDir, e.name, 'main.go')\n    if (await fs.stat(main).then((s) => s.isFile()).catch(() => false)) binaries.push(e.name)\n  }\n  if (binaries.length < 2) return []\n  binaries.sort()\n\n  const files = await listModuleFiles(root)\n  const goFiles: GoFile[] = files\n    .filter((f) => f.endsWith('.go') && !f.endsWith('_test.go'))\n    .map((abs) => ({ abs, dir: path.dirname(abs) }))\n  const packageDirs = new Set(goFiles.map((f) => f.dir))\n\n  // package dir → the in-module package dirs it imports.\n  const importsOf = new Map<string, Set<string>>()\n  const prefix = modulePath + '/'\n  for (const f of goFiles) {\n    const src = await fs.readFile(f.abs, 'utf8').catch(() => '')\n    const set = importsOf.get(f.dir) ?? new Set<string>()\n    for (const imp of goImports(src)) {\n      if (!imp.startsWith(prefix)) continue\n      const dir = path.join(root, ...imp.slice(prefix.length).split('/'))\n      if (packageDirs.has(dir)) set.add(dir)\n    }\n    importsOf.set(f.dir, set)\n  }\n\n  // Which binaries reach each package.\n  const reachedBy = new Map<string, Set<string>>()\n  for (const bin of binaries) {\n    const start = path.join(cmdDir, bin)\n    const seen = new Set<string>([start])\n    const queue = [start]\n    while (queue.length > 0) {\n      const dir = queue.shift()!\n      for (const next of importsOf.get(dir) ?? []) {\n        if (!seen.has(next)) {\n          seen.add(next)\n          queue.push(next)\n        }\n      }\n    }\n    for (const dir of seen) {\n      const set = reachedBy.get(dir) ?? new Set<string>()\n      set.add(bin)\n      reachedBy.set(dir, set)\n    }\n  }\n\n  // The owning binary of a directory, or null for the module (shared).\n  const ownerCache = new Map<string, string | null>()\n  function ownerOf(dir: string): string | null {\n    const cached = ownerCache.get(dir)\n    if (cached !== undefined) return cached\n    let owner: string | null\n    if (packageDirs.has(dir)) {\n      const bins = reachedBy.get(dir)\n      owner = bins && bins.size === 1 ? [...bins][0]! : null\n    } else if (dir === root || !dir.startsWith(root + path.sep)) {\n      owner = null\n    } else {\n      owner = ownerOf(path.dirname(dir))\n    }\n    ownerCache.set(dir, owner)\n    return owner\n  }\n\n  const ownedBy = new Map<string | null, string[]>()\n  for (const f of files) {\n    const owner = ownerOf(path.dirname(f))\n    const list = ownedBy.get(owner) ?? []\n    list.push(f)\n    ownedBy.set(owner, list)\n  }\n  const notOwnedBy = (owner: string | null): string[] =>\n    [...ownedBy.entries()].filter(([o]) => o !== owner).flatMap(([, fs]) => fs)\n\n  // The module service keeps the shared code; it excludes what a binary owns.\n  module.excludeDirs = [...(module.excludeDirs ?? []), ...notOwnedBy(null)]\n\n  return binaries.map((bin) => {\n    const node: ServiceNode = { ...module.node, id: serviceId(bin), name: bin }\n    return {\n      pkg: { ...module.pkg, name: bin },\n      dir: module.dir,\n      node,\n      excludeDirs: notOwnedBy(bin),\n    }\n  })\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { ServiceNode } from '@neat.is/types'\nimport { NodeType, serviceId } from '@neat.is/types'\nimport type { DiscoveredService, PackageJson } from './shared.js'\n\n// Ruby service discovery (ADR-173), the Gemfile analog of extract/go.ts's\n// `go.mod` reader. A Gemfile names no project, so the service takes its\n// directory's basename; the `gem` lines become dependency gates the way a\n// `go.mod` `require` block does, so the route producer can gate on `rails`.\n\nexport interface Gemfile {\n  dependencies: Record<string, string>\n}\n\n// Read the gems a Gemfile declares. `gem 'rails', '~> 7.1'` → { rails: '~> 7.1' }.\n// A version is optional (`gem 'puma'` → ''); a gem with only non-version options\n// (`gem 'pg', require: false`) still registers, at ''. Commented lines are\n// skipped. This is a line scan, not a Ruby parse — the same discipline go.ts's\n// `go.mod` reader and proto.ts's `.proto` scan use for polyglot manifest data.\nexport function parseGemfile(source: string): Gemfile {\n  const dependencies: Record<string, string> = {}\n  for (const raw of source.split(/\\r?\\n/)) {\n    const line = raw.replace(/#.*$/, '').trim()\n    const m = line.match(/^gem\\s+(['\"])([^'\"]+)\\1\\s*(?:,\\s*(['\"])([^'\"]+)\\3)?/)\n    if (!m) continue\n    const name = m[2]!\n    const version = m[4] && /\\d/.test(m[4]) ? m[4] : ''\n    dependencies[name] = version\n  }\n  return { dependencies }\n}\n\nexport async function discoverRubyService(\n  scanPath: string,\n  dir: string,\n): Promise<DiscoveredService | null> {\n  let raw: string\n  try {\n    raw = await fs.readFile(path.join(dir, 'Gemfile'), 'utf8')\n  } catch {\n    return null\n  }\n  const gemfile = parseGemfile(raw)\n  const name = path.basename(dir)\n  const pkg: PackageJson = { name, dependencies: gemfile.dependencies }\n  const node: ServiceNode = {\n    id: serviceId(name),\n    type: NodeType.ServiceNode,\n    name,\n    language: 'ruby',\n    dependencies: gemfile.dependencies,\n    repoPath: path.relative(scanPath, dir),\n    ...(gemfile.dependencies['rails'] !== undefined ? { framework: 'rails' } : {}),\n  }\n  return { pkg, dir, node }\n}\n","import path from 'node:path'\nimport type { ServiceNode } from '@neat.is/types'\nimport { NodeType, serviceId } from '@neat.is/types'\nimport { readJson, type DiscoveredService, type PackageJson } from './shared.js'\n\n// PHP service discovery (ADR-177), the `composer.json` analog of extract/ruby.ts's\n// Gemfile reader and extract/go.ts's `go.mod` reader. A composer.json does name a\n// project (`vendor/package`), but we keep the basename-as-service-name convention\n// the Gemfile/go.mod readers use so a PHP service sits next to the others without\n// a vendor slash in its id; the `require` block becomes the dependency gates the\n// route producer reads, so it can gate on `laravel/framework`.\n\ninterface ComposerJson {\n  name?: string\n  require?: Record<string, string>\n  'require-dev'?: Record<string, string>\n}\n\nexport interface Composer {\n  dependencies: Record<string, string>\n}\n\n// Read the packages a composer.json declares, merging `require` and\n// `require-dev` the way the JS reader merges dependencies and devDependencies.\n// `laravel/framework` in `require` is the gate the Laravel route recognizer uses.\nexport function parseComposerJson(composer: ComposerJson): Composer {\n  return {\n    dependencies: {\n      ...(composer.require ?? {}),\n      ...(composer['require-dev'] ?? {}),\n    },\n  }\n}\n\nexport async function discoverPhpService(\n  scanPath: string,\n  dir: string,\n): Promise<DiscoveredService | null> {\n  let composer: ComposerJson\n  try {\n    composer = await readJson<ComposerJson>(path.join(dir, 'composer.json'))\n  } catch {\n    return null\n  }\n  const { dependencies } = parseComposerJson(composer)\n  const name = path.basename(dir)\n  const pkg: PackageJson = { name, dependencies }\n  const node: ServiceNode = {\n    id: serviceId(name),\n    type: NodeType.ServiceNode,\n    name,\n    language: 'php',\n    dependencies,\n    repoPath: path.relative(scanPath, dir),\n    ...(dependencies['laravel/framework'] !== undefined ? { framework: 'laravel' } : {}),\n  }\n  return { pkg, dir, node }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { ServiceNode } from '@neat.is/types'\nimport { NodeType, serviceId } from '@neat.is/types'\nimport type { DiscoveredService, PackageJson } from './shared.js'\n\n// C#/.NET service discovery (ADR-196), the MSBuild-project analog of\n// extract/ruby.ts's Gemfile reader, extract/php.ts's composer.json reader, and\n// extract/go.ts's go.mod reader. A .NET service is a directory that ships an\n// MSBuild project — a `*.csproj` — or a solution — a `*.sln`. Unlike the other\n// language manifests, the marker is a glob, not a fixed filename: the file is\n// named after the assembly (`Cart.csproj`, `Accounting.csproj`), so a directory\n// is a service when it holds *any* `.csproj` / `.sln`. The `.csproj` names the\n// service (its basename, the assembly name convention); a `.sln`-only directory\n// falls back to the directory basename. `PackageReference` items become the\n// dependency gates a later route / EF Core recognizer keys on, the way a go.mod\n// `require` block or a composer.json `require` does.\n//\n// The project can sit at the service-root directory (`accounting/Accounting.csproj`,\n// the flat layout, `.cs` beside it) or one level down in the conventional `src/`\n// subdirectory (`cart/src/cart.csproj`, the nested layout the otel-demo `cart`\n// service uses). Both are real .NET service shapes, so the lookup checks the\n// directory itself first, then its `src/` child. The top level wins on a tie, and\n// the nested case anchors on the `src/` directory that actually holds the project —\n// the same directory the recursive discovery walk reaches on its own, so a\n// whole-repo scan and a scan pointed straight at the service root land the same\n// node (the discovery loop collapses the two candidates on that shared directory).\n\nexport interface Csproj {\n  dependencies: Record<string, string>\n}\n\n// The MSBuild project extensions that mark a .NET service directory. A `.csproj`\n// is a single project; a `.sln` aggregates projects. Either is an explicit\n// \"this is a .NET service\" marker.\nconst CSHARP_PROJECT_EXTS = new Set(['.csproj', '.sln'])\n\n// List the .NET project markers at the top level of `dir`, sorted so discovery\n// picks the same one on every pass (idempotency). One readdir; the glob shape\n// (any `*.csproj` / `*.sln`) is why C# can't ride the fixed-filename `exists`\n// checks the other manifests use.\nasync function projectFiles(dir: string): Promise<string[]> {\n  const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => [])\n  const out: string[] = []\n  for (const entry of entries) {\n    if (!entry.isFile()) continue\n    if (CSHARP_PROJECT_EXTS.has(path.extname(entry.name).toLowerCase())) out.push(entry.name)\n  }\n  return out.sort()\n}\n\n// The conventional subdirectory a .NET service keeps its project in when it isn't\n// flat at the root. Kept to the single `src/` convention — not an open recursive\n// hunt — so discovery stays precise: a directory becomes a service only on an\n// actual `.csproj` / `.sln`, at the root or exactly one `src/` level down.\nconst NESTED_PROJECT_DIR = 'src'\n\n// Conventional subdirectories whose own basename is not a service name — a nested\n// project's `src/`, a test project's `tests/` / `test/`. When a candidate dir IS one\n// of these, the service is named from its parent, so the root/subdir candidates fold\n// onto one service via the duplicate-name dedup rather than minting a bogus `src` /\n// `tests` service (ADR-252).\nconst NAMING_SUBDIRS = new Set([NESTED_PROJECT_DIR, 'tests', 'test'])\n\n// Resolve the directory that actually holds `dir`'s MSBuild project: `dir` itself\n// when it carries a top-level `.csproj` / `.sln` (the flat layout, top level wins),\n// else its `src/` child when that carries one (the nested layout), else null when\n// neither does. This is the one place the flat-vs-nested choice is made; every\n// other function reads through it.\nasync function resolveProjectDir(dir: string): Promise<string | null> {\n  if ((await projectFiles(dir)).length > 0) return dir\n  const nested = path.join(dir, NESTED_PROJECT_DIR)\n  if ((await projectFiles(nested)).length > 0) return nested\n  return null\n}\n\n// Cheap predicate the discovery walk and the Dockerfile fallback share: does this\n// directory carry a `.csproj` or `.sln` — at its root or one `src/` level down?\n// Keyed on the glob, so it can't be an `exists(path.join(dir, 'X'))` the way\n// `hasGoManifest` is.\nexport async function hasCsharpProject(dir: string): Promise<boolean> {\n  return (await resolveProjectDir(dir)) !== null\n}\n\n// Read the `PackageReference` items a `.csproj` declares. A line/regex scan, the\n// same discipline go.ts's go.mod reader and ruby.ts's Gemfile reader use for\n// polyglot manifest data — not a full MSBuild parse. The version is optional\n// (Central Package Management moves it to `Directory.Packages.props`), so a\n// reference with only an `Include` registers at ''. `Microsoft.AspNetCore.*` in\n// the set is the gate a later ASP.NET route recognizer reads.\nexport function parseCsproj(source: string): Csproj {\n  const dependencies: Record<string, string> = {}\n  const re = /<PackageReference\\b([^>]*?)\\/?>/g\n  let m: RegExpExecArray | null\n  while ((m = re.exec(source)) !== null) {\n    const attrs = m[1] ?? ''\n    const include = attrs.match(/\\bInclude\\s*=\\s*\"([^\"]+)\"/)?.[1]\n    if (!include) continue\n    const version = attrs.match(/\\bVersion\\s*=\\s*\"([^\"]+)\"/)?.[1]\n    dependencies[include] = version ?? ''\n  }\n  return { dependencies }\n}\n\nexport async function discoverCsharpService(\n  scanPath: string,\n  dir: string,\n): Promise<DiscoveredService | null> {\n  // Flat (`dir/X.csproj`) or nested (`dir/src/X.csproj`) — `projectDir` is\n  // whichever actually holds the project; null when neither does.\n  const projectDir = await resolveProjectDir(dir)\n  if (projectDir === null) return null\n  const projects = await projectFiles(projectDir)\n\n  // The service is named from its directory, matching every other manifest reader\n  // (Go module basename, Ruby / PHP / Rust / C++ / Gradle-Java dir basename) and the\n  // deployed OTEL_SERVICE_NAME / k8s convention. A `.csproj` basename is the PascalCase\n  // assembly name (`Accounting.csproj`), which doesn't fuse with the lowercase runtime\n  // `service.name` (`accounting`) — the directory is the stable, deploy-matching\n  // identity (ADR-252). A candidate that IS a nested `src/` / `tests/` subdir takes its\n  // parent's name, so the root/subdir pair folds onto one service. The `.csproj` is\n  // still read below for its PackageReference dependencies.\n  const csproj = projects.find((p) => p.toLowerCase().endsWith('.csproj'))\n  const base = path.basename(dir)\n  const name = NAMING_SUBDIRS.has(base) ? path.basename(path.dirname(dir)) : base\n\n  let dependencies: Record<string, string> = {}\n  if (csproj) {\n    const raw = await fs.readFile(path.join(projectDir, csproj), 'utf8').catch(() => '')\n    dependencies = parseCsproj(raw).dependencies\n  }\n\n  const pkg: PackageJson = { name, dependencies }\n  const node: ServiceNode = {\n    id: serviceId(name),\n    type: NodeType.ServiceNode,\n    name,\n    language: 'csharp',\n    dependencies,\n    // Anchor on the directory that holds the project and its `.cs` files, so file\n    // attribution reaches the source whether it sits at the root or under `src/`.\n    repoPath: path.relative(scanPath, projectDir),\n  }\n  return { pkg, dir: projectDir, node }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { ServiceNode } from '@neat.is/types'\nimport { NodeType, serviceId } from '@neat.is/types'\nimport { exists, type DiscoveredService, type PackageJson } from './shared.js'\n\n// Java service discovery (ADR-197), the build-manifest analog of extract/ruby.ts's\n// Gemfile reader, extract/php.ts's composer.json reader, and extract/go.ts's go.mod\n// reader. A Java service is a directory that ships a build manifest — a Maven\n// `pom.xml` or a Gradle `build.gradle` / `build.gradle.kts`. Unlike C# (ADR-196),\n// the marker is a fixed filename, so it rides the same `exists` predicate the\n// Ruby/PHP/Go readers use rather than a directory glob. Maven's `pom.xml` names the\n// project (its `<artifactId>`); a Gradle build has no name in `build.gradle` (the\n// canonical `rootProject.name` lives in `settings.gradle`), so it falls back to the\n// directory basename — the same basename-as-service-name convention the Gemfile and\n// go.mod readers use. Declared dependencies (`groupId:artifactId`) become the gates\n// a later Spring / JPA recognizer keys on, the way a go.mod `require` block does.\n\n// The build manifests that mark a Java service directory. Maven keys on `pom.xml`;\n// Gradle on `build.gradle` (Groovy DSL) or `build.gradle.kts` (Kotlin DSL). Any one\n// is an explicit \"this is a Java service\" marker, a fixed filename, not a glob.\nexport const JAVA_MANIFESTS = ['pom.xml', 'build.gradle', 'build.gradle.kts'] as const\n\nexport interface JavaManifest {\n  // The project name a Maven `pom.xml` declares (`<artifactId>`), if any. Gradle\n  // builds carry no name here, so this is undefined and discovery uses the dir.\n  name?: string\n  dependencies: Record<string, string>\n}\n\n// Cheap predicate the discovery walk and the Dockerfile fallback share: does this\n// directory carry a Maven or Gradle build manifest? A fixed-filename `exists`\n// check, the same shape `hasGoManifest` uses (extract/services.ts) — the Java\n// marker is a filename, not the directory glob C# needs (ADR-196).\nexport async function hasJavaManifest(dir: string): Promise<boolean> {\n  for (const manifest of JAVA_MANIFESTS) {\n    if (await exists(path.join(dir, manifest))) return true\n  }\n  return false\n}\n\n// Read a Maven `pom.xml`. A line/regex scan for the project `<artifactId>` and the\n// `<dependency>` coordinates, the same discipline go.ts's go.mod reader and ruby.ts's\n// Gemfile reader use for polyglot manifest data — not a full POM model with property\n// or parent-inheritance resolution. The project name is the first `<artifactId>`\n// once `<parent>` / `<dependencyManagement>` / `<dependencies>` / `<build>` blocks\n// are stripped, so the parent's or a dependency's artifactId can't be mistaken for\n// it. Each `<dependency>` registers as `groupId:artifactId` → version (version is\n// optional under a managed BOM, so it falls back to ''); `org.springframework.boot:*`\n// in the map is the gate a later Spring route recognizer reads.\nexport function parsePomXml(source: string): JavaManifest {\n  const dependencies: Record<string, string> = {}\n  const depBlock = /<dependency\\b[^>]*>([\\s\\S]*?)<\\/dependency>/g\n  let d: RegExpExecArray | null\n  while ((d = depBlock.exec(source)) !== null) {\n    const body = d[1] ?? ''\n    const groupId = body.match(/<groupId>\\s*([^<]+?)\\s*<\\/groupId>/)?.[1]\n    const artifactId = body.match(/<artifactId>\\s*([^<]+?)\\s*<\\/artifactId>/)?.[1]\n    if (!groupId || !artifactId) continue\n    const version = body.match(/<version>\\s*([^<]+?)\\s*<\\/version>/)?.[1]\n    dependencies[`${groupId}:${artifactId}`] = version ?? ''\n  }\n\n  const withoutBlocks = source\n    .replace(/<parent\\b[^>]*>[\\s\\S]*?<\\/parent>/g, '')\n    .replace(/<dependencyManagement\\b[^>]*>[\\s\\S]*?<\\/dependencyManagement>/g, '')\n    .replace(/<dependencies\\b[^>]*>[\\s\\S]*?<\\/dependencies>/g, '')\n    .replace(/<build\\b[^>]*>[\\s\\S]*?<\\/build>/g, '')\n  const name = withoutBlocks.match(/<artifactId>\\s*([^<]+?)\\s*<\\/artifactId>/)?.[1]\n  return { name, dependencies }\n}\n\n// The Gradle configurations that declare a runtime/compile dependency. A `gem`-line\n// equivalent for `build.gradle` — the string-notation coordinate is what a later\n// recognizer gates on, so the map form (`group:`, `name:`, `version:`) is out of\n// scope for a v1 line scan, the same way ruby.ts skips option-only `gem` forms.\nconst GRADLE_CONFIGS =\n  'implementation|api|compileOnly|runtimeOnly|compileOnlyApi|testImplementation|testRuntimeOnly|testCompileOnly|annotationProcessor|developmentOnly|runtimeClasspath'\n\n// Read a Gradle `build.gradle` / `build.gradle.kts`. A line scan for\n// `implementation 'group:artifact:version'` (and the Kotlin-DSL `implementation(\"…\")`\n// form) — the same discipline the Gemfile reader uses. The coordinate's first two\n// `:`-separated segments are the `groupId:artifactId` key; the remainder (version,\n// or version+classifier) is the value, '' when the coordinate names no version.\nexport function parseGradle(source: string): JavaManifest {\n  const dependencies: Record<string, string> = {}\n  const re = new RegExp(`\\\\b(?:${GRADLE_CONFIGS})\\\\s*\\\\(?\\\\s*(['\"])([^'\"]+)\\\\1`, 'g')\n  let m: RegExpExecArray | null\n  while ((m = re.exec(source)) !== null) {\n    const coord = m[2] ?? ''\n    const parts = coord.split(':')\n    if (parts.length < 2 || !parts[0] || !parts[1]) continue\n    const key = `${parts[0]}:${parts[1]}`\n    dependencies[key] = parts.slice(2).join(':')\n  }\n  return { dependencies }\n}\n\nexport async function discoverJavaService(\n  scanPath: string,\n  dir: string,\n): Promise<DiscoveredService | null> {\n  // Maven wins on a mixed dir (a `pom.xml` next to a `build.gradle` is a Maven\n  // project with a Gradle wrapper checked in), then Gradle Groovy, then Kotlin DSL.\n  const pomPath = path.join(dir, 'pom.xml')\n  const gradlePath = path.join(dir, 'build.gradle')\n  const gradleKtsPath = path.join(dir, 'build.gradle.kts')\n\n  let manifest: JavaManifest | null = null\n  if (await exists(pomPath)) {\n    manifest = parsePomXml(await fs.readFile(pomPath, 'utf8').catch(() => ''))\n  } else if (await exists(gradlePath)) {\n    manifest = parseGradle(await fs.readFile(gradlePath, 'utf8').catch(() => ''))\n  } else if (await exists(gradleKtsPath)) {\n    manifest = parseGradle(await fs.readFile(gradleKtsPath, 'utf8').catch(() => ''))\n  }\n  if (!manifest) return null\n\n  // The Maven `<artifactId>` names the service; a Gradle build has no name here, so\n  // it takes the directory basename the Go/Ruby/PHP readers use for name-less\n  // manifests.\n  const name = manifest.name?.trim() || path.basename(dir)\n  const dependencies = manifest.dependencies\n\n  const pkg: PackageJson = { name, dependencies }\n  const node: ServiceNode = {\n    id: serviceId(name),\n    type: NodeType.ServiceNode,\n    name,\n    language: 'java',\n    dependencies,\n    repoPath: path.relative(scanPath, dir),\n  }\n  return { pkg, dir, node }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { ServiceNode } from '@neat.is/types'\nimport { NodeType, serviceId } from '@neat.is/types'\nimport { exists, IGNORED_DIRS, type DiscoveredService, type PackageJson } from './shared.js'\nimport {\n  JAVA_MANIFESTS,\n  parseGradle,\n  parsePomXml,\n  hasJavaManifest,\n  type JavaManifest,\n} from './java.js'\n\n// Kotlin service discovery (ADR-199). Kotlin is the JVM sibling of Java (ADR-197)\n// and shares its entire build toolchain: a Kotlin service is a directory with the\n// *same* Maven `pom.xml` or Gradle `build.gradle` / `build.gradle.kts` a Java\n// service carries — the manifest alone can't tell the two apart. So the marker is\n// the source, not the manifest: a JVM manifest directory whose source is `.kt` is\n// Kotlin, one whose source is `.java` is Java. This reader keys on that\n// discriminator, running ahead of `discoverJavaService` in the chain so a\n// `.kt`-dominant Gradle directory (the otel-demo `fraud-detection` shape —\n// `build.gradle.kts` plus `src/main/kotlin/frauddetection/*.kt`) mints a **kotlin**\n// ServiceNode, while a `.java`-dominant one falls through untouched and Java claims\n// it exactly as before. The manifest parsing (POM `<artifactId>` naming, Gradle\n// basename fallback, `groupId:artifactId` dependency gates) is reused verbatim from\n// `extract/java.ts` — only the language label and the source-based discriminator\n// differ.\n\n// Kotlin source files. A `.kt` under the service tree is what tells a JVM-manifest\n// directory apart from a Java one; the Gradle Kotlin-DSL build script is `.kts`\n// (a manifest, not service source), so it never counts here.\nexport const KOTLIN_SOURCE_EXT = '.kt'\nconst JAVA_SOURCE_EXT = '.java'\n\n// How deep to look for source under a service directory when deciding Kotlin vs\n// Java. Kotlin conventionally lives at `src/main/kotlin/<pkg>/…`, several levels\n// below the manifest, so a top-level-only look (the Dockerfile fallback's precision\n// knob) would miss it — the discriminator has to descend, but bounded so a large\n// tree doesn't turn discovery into a full walk.\nconst SOURCE_PROBE_MAX_DEPTH = 8\n\n// The JVM source language a manifest directory actually holds. A bounded recursive\n// count of `.kt` vs `.java` files under the directory (`IGNORED_DIRS` skipped, so\n// `build/` output and vendored trees don't sway it): Kotlin wins when it is present\n// and at least ties Java, so a pure-Kotlin service resolves to `kotlin`, a pure-Java\n// one to `java`, and a mixed tree to whichever source dominates (ties to Kotlin,\n// the more specific case). `undefined` when the directory carries neither, which\n// leaves the JVM readers to fall through on a manifest with no JVM source yet.\nexport async function dominantJvmSourceLanguage(\n  dir: string,\n): Promise<'kotlin' | 'java' | undefined> {\n  let kt = 0\n  let java = 0\n\n  async function recurse(current: string, depth: number): Promise<void> {\n    if (depth > SOURCE_PROBE_MAX_DEPTH) return\n    const entries = await fs.readdir(current, { withFileTypes: true }).catch(() => [])\n    for (const entry of entries) {\n      if (entry.isDirectory()) {\n        if (IGNORED_DIRS.has(entry.name)) continue\n        await recurse(path.join(current, entry.name), depth + 1)\n        continue\n      }\n      if (!entry.isFile()) continue\n      const ext = path.extname(entry.name).toLowerCase()\n      if (ext === KOTLIN_SOURCE_EXT) kt++\n      else if (ext === JAVA_SOURCE_EXT) java++\n    }\n  }\n  await recurse(dir, 0)\n\n  if (kt > 0 && kt >= java) return 'kotlin'\n  if (java > 0) return 'java'\n  return undefined\n}\n\n// Read the JVM build manifest a directory ships, with the same precedence\n// `discoverJavaService` uses (a `pom.xml` next to a `build.gradle` is a Maven\n// project with a Gradle wrapper checked in, so Maven wins; then Gradle Groovy, then\n// the Kotlin DSL). Reused so a Kotlin service is named and gated the same way its\n// Java sibling is.\nasync function readJvmManifest(dir: string): Promise<JavaManifest | null> {\n  const pomPath = path.join(dir, JAVA_MANIFESTS[0])\n  const gradlePath = path.join(dir, JAVA_MANIFESTS[1])\n  const gradleKtsPath = path.join(dir, JAVA_MANIFESTS[2])\n  if (await exists(pomPath)) {\n    return parsePomXml(await fs.readFile(pomPath, 'utf8').catch(() => ''))\n  }\n  if (await exists(gradlePath)) {\n    return parseGradle(await fs.readFile(gradlePath, 'utf8').catch(() => ''))\n  }\n  if (await exists(gradleKtsPath)) {\n    return parseGradle(await fs.readFile(gradleKtsPath, 'utf8').catch(() => ''))\n  }\n  return null\n}\n\nexport async function discoverKotlinService(\n  scanPath: string,\n  dir: string,\n): Promise<DiscoveredService | null> {\n  // Kotlin and Java both mark a service with a Maven/Gradle manifest — the source\n  // decides which. Only claim the directory when a JVM manifest is present *and*\n  // Kotlin is the dominant source; otherwise fall through so `discoverJavaService`\n  // handles a Java (or source-less) manifest directory exactly as it did before.\n  if (!(await hasJavaManifest(dir))) return null\n  if ((await dominantJvmSourceLanguage(dir)) !== 'kotlin') return null\n\n  const manifest = await readJvmManifest(dir)\n  if (!manifest) return null\n\n  // A Maven `<artifactId>` names the service; a Gradle build carries no name here,\n  // so it takes the directory basename the Go/Ruby/PHP readers use.\n  const name = manifest.name?.trim() || path.basename(dir)\n  const dependencies = manifest.dependencies\n\n  const pkg: PackageJson = { name, dependencies }\n  const node: ServiceNode = {\n    id: serviceId(name),\n    type: NodeType.ServiceNode,\n    name,\n    language: 'kotlin',\n    dependencies,\n    repoPath: path.relative(scanPath, dir),\n  }\n  return { pkg, dir, node }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport type { ServiceNode } from '@neat.is/types'\nimport { NodeType, serviceId } from '@neat.is/types'\nimport { exists, type DiscoveredService, type PackageJson } from './shared.js'\n\n// Rust service discovery (ADR-201), the Cargo analog of extract/go.ts's go.mod\n// reader and extract/java.ts's Maven/Gradle reader. A Rust service is a directory\n// that ships a `Cargo.toml` — a fixed filename, so it rides the same `exists`\n// predicate the Go/Ruby/PHP/Java readers use rather than a directory glob. Cargo's\n// `[package] name` names the service; a virtual-workspace manifest (a `[workspace]`\n// with no `[package]`) carries no name here, so it falls back to the directory\n// basename — the same basename-as-service-name convention the Gemfile and go.mod\n// readers use. Declared `[dependencies]` (crate → version) become the gates a later\n// Axum / Actix / SQLx recognizer would key on, the way a go.mod `require` block does.\n//\n// TOML is parsed with `smol-toml`, the same parser extract/python.ts reads\n// `pyproject.toml` with and the infra readers read `wrangler.toml` / `railway.toml`\n// with — the established manifest-parser for this repo, already a dependency, so no\n// hand-rolled scan and no new package (unlike java.ts, which regex-scans XML/Gradle\n// because no lightweight parser for those was on hand).\n\n// The build manifest that marks a Rust service directory. Cargo keys on a fixed\n// `Cargo.toml`, an explicit \"this is a Rust crate\" marker — a filename, not a glob.\nexport const CARGO_MANIFEST = 'Cargo.toml'\n\nexport interface CargoManifest {\n  // The crate name a `[package] name` declares, if any. A virtual-workspace\n  // manifest carries no `[package]`, so this is undefined and discovery uses the dir.\n  name?: string\n  dependencies: Record<string, string>\n}\n\n// The `Cargo.toml` shape this reader looks at — `[package] name` and the flat\n// `[dependencies]` table. A dependency's value is either a bare version string\n// (`serde = \"1.0\"`) or an inline table (`tokio = { version = \"1\", … }`); anything\n// else is a path / git source with no version.\ninterface CargoToml {\n  package?: { name?: unknown }\n  dependencies?: Record<string, unknown>\n}\n\n// Cheap predicate the discovery walk and the Dockerfile fallback share: does this\n// directory carry a `Cargo.toml`? A fixed-filename `exists` check, the same shape\n// `hasGoManifest` uses (extract/services.ts) — the Rust marker is a filename, not\n// the directory glob C# needs (ADR-196).\nexport async function hasRustManifest(dir: string): Promise<boolean> {\n  return exists(path.join(dir, CARGO_MANIFEST))\n}\n\n// Read a `Cargo.toml` into the crate name and its declared dependency gates. Each\n// `[dependencies]` entry registers as `crate` → version, whether it takes the string\n// form or the inline-table form (version '' when the table names a path / git source\n// with no version) — the same \"which packages does this service pull in\" gate a\n// go.mod `require` or a composer.json `require` provides. A malformed manifest is\n// swallowed to an empty result rather than thrown, so one bad `Cargo.toml` can't\n// abort a whole-repo discovery walk (java.ts's `.catch(() => '')` read discipline).\nexport function parseCargoToml(source: string): CargoManifest {\n  const dependencies: Record<string, string> = {}\n  let name: string | undefined\n\n  let parsed: CargoToml\n  try {\n    parsed = parseToml(source) as CargoToml\n  } catch {\n    return { dependencies }\n  }\n\n  if (typeof parsed.package?.name === 'string') name = parsed.package.name\n\n  for (const [crate, spec] of Object.entries(parsed.dependencies ?? {})) {\n    if (typeof spec === 'string') {\n      dependencies[crate] = spec\n    } else if (spec && typeof spec === 'object') {\n      const version = (spec as { version?: unknown }).version\n      dependencies[crate] = typeof version === 'string' ? version : ''\n    } else {\n      dependencies[crate] = ''\n    }\n  }\n\n  return { name, dependencies }\n}\n\nexport async function discoverRustService(\n  scanPath: string,\n  dir: string,\n): Promise<DiscoveredService | null> {\n  const cargoPath = path.join(dir, CARGO_MANIFEST)\n  if (!(await exists(cargoPath))) return null\n\n  const manifest = parseCargoToml(await fs.readFile(cargoPath, 'utf8').catch(() => ''))\n\n  // The `[package] name` names the service; a virtual-workspace manifest carries no\n  // name here, so it takes the directory basename the Go/Ruby/Java readers use for\n  // name-less manifests.\n  const name = manifest.name?.trim() || path.basename(dir)\n  const dependencies = manifest.dependencies\n\n  const pkg: PackageJson = { name, dependencies }\n  const node: ServiceNode = {\n    id: serviceId(name),\n    type: NodeType.ServiceNode,\n    name,\n    language: 'rust',\n    dependencies,\n    repoPath: path.relative(scanPath, dir),\n  }\n  return { pkg, dir, node }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { ServiceNode } from '@neat.is/types'\nimport { NodeType, serviceId } from '@neat.is/types'\nimport { exists, type DiscoveredService, type PackageJson } from './shared.js'\n\n// C++ service discovery (ADR-202), the last of the OpenTelemetry Demo languages.\n// Unlike Go/Ruby/Java/Rust, C++ has no single clean dependency manifest that also\n// names the service — a directory can build with plain `g++`, a Makefile, Bazel,\n// or CMake, and only some of those carry a service name at all. The primary marker\n// this reader keys on is CMake's `CMakeLists.txt`: a fixed filename, so it rides the\n// same `exists` predicate the Go/Ruby/Java/Rust readers use (not the directory glob\n// C# needs, ADR-196), and its `project(<name> …)` directive names the service. The\n// otel-demo `currency` service is exactly this shape — a `CMakeLists.txt` with\n// `project(currency)` plus `src/server.cpp`.\n//\n// There is no crate/gem/composer dependency table to lift into the ServiceNode's\n// `dependencies` gates — CMake's `find_package` / `target_link_libraries` are the\n// nearest analog, but they name build targets, not the versioned packages a route /\n// data recognizer would gate on — so `dependencies` is left empty here, the way the\n// Dockerfile-declared reader (ADR-194) leaves it empty. A `currency` discovered\n// instead via that Dockerfile path still reaches symbol grain: the symbol grain keys\n// off the file extension (`.cpp`), not the discovery route.\n\n// The build manifest that marks a C++ service directory. CMake keys on a fixed\n// `CMakeLists.txt`, an explicit \"this is a buildable project\" marker — a filename,\n// not a glob.\nexport const CMAKE_MANIFEST = 'CMakeLists.txt'\n\n// Cheap predicate the discovery walk and the Dockerfile fallback share: does this\n// directory carry a `CMakeLists.txt`? A fixed-filename `exists` check, the same\n// shape `hasRustManifest` / `hasJavaManifest` use — the C++ marker is a filename,\n// not the directory glob C# needs (ADR-196).\nexport async function hasCppManifest(dir: string): Promise<boolean> {\n  return exists(path.join(dir, CMAKE_MANIFEST))\n}\n\n// Read the service name out of a `CMakeLists.txt`'s `project(<name> …)` directive.\n// CMake's `project()` command always takes the project name as its first argument;\n// every optional keyword (`VERSION`, `DESCRIPTION`, `LANGUAGES`, `HOMEPAGE_URL`)\n// follows it, so the first token after `project(` is always the name. `#`-to-end-of-\n// line comments are stripped first so a commented-out `project()` can't win, and the\n// name is matched against a plain identifier character class — a computed name like\n// `project(${APP_NAME})` matches nothing and the caller falls back to the directory\n// basename. A targeted regex read, not a CMake parser: there is no TOML/JSON to lift,\n// and the name is the only field this reader needs.\nexport function parseCMakeProjectName(source: string): string | undefined {\n  const withoutComments = source.replace(/#.*$/gm, '')\n  // `project` `(` then optional whitespace/newlines, an optional quote, then the\n  // name token. `\\s` spans newlines, so a multi-line `project(\\n  currency\\n …)`\n  // still resolves. The character class is CMake's identifier shape plus the `.`/`+`\n  // /`-` that appear in real project names; `$`/`{` are excluded so a variable\n  // reference fails to match rather than capturing a bogus name.\n  const m = withoutComments.match(/\\bproject\\s*\\(\\s*\"?([A-Za-z0-9_.+-]+)\"?/i)\n  return m?.[1]\n}\n\nexport async function discoverCppService(\n  scanPath: string,\n  dir: string,\n): Promise<DiscoveredService | null> {\n  const cmakePath = path.join(dir, CMAKE_MANIFEST)\n  if (!(await exists(cmakePath))) return null\n\n  const source = await fs.readFile(cmakePath, 'utf8').catch(() => '')\n  // The `project()` name names the service; a manifest with no usable `project()`\n  // name takes the directory basename the Go/Ruby/Java/Rust readers use for\n  // name-less manifests.\n  const name = parseCMakeProjectName(source)?.trim() || path.basename(dir)\n\n  // No dependency-manifest analog to parse — CMake names build targets, not the\n  // versioned packages a later route / data recognizer would gate on.\n  const dependencies: Record<string, string> = {}\n\n  const pkg: PackageJson = { name, dependencies }\n  const node: ServiceNode = {\n    id: serviceId(name),\n    type: NodeType.ServiceNode,\n    name,\n    language: 'cpp',\n    dependencies,\n    repoPath: path.relative(scanPath, dir),\n  }\n  return { pkg, dir, node }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { ServiceNode } from '@neat.is/types'\nimport { NodeType, serviceId } from '@neat.is/types'\nimport {\n  SERVICE_FILE_EXTENSIONS,\n  exists,\n  isNeatAuthoredSourceFile,\n  type DiscoveredService,\n  type PackageJson,\n} from './shared.js'\nimport { hasCsharpProject } from './csharp.js'\nimport { hasJavaManifest } from './java.js'\nimport { hasRustManifest } from './rust.js'\nimport { hasCppManifest } from './cpp.js'\n\n// Dockerfile-declared service discovery (ADR-194). Every other `discoverXService`\n// keys on a language manifest — package.json, pyproject.toml/requirements.txt,\n// go.mod, Gemfile, composer.json. A containerized service that ships none of them\n// (a k6 load generator is `Dockerfile` + `script.js` and nothing else) is\n// invisible to all of them, so it never becomes a ServiceNode and never reaches\n// symbol grain. The Dockerfile is the missing signal: it's an explicit \"this\n// directory is a deployable service\" marker, which is exactly what lets us mint\n// here without over-minting on any stray script.\n//\n// The precision boundary is three ANDs — a Dockerfile, AND top-level source, AND\n// no language manifest:\n//   - Dockerfile alone (no source)      → not a service. The Dockerfile could be\n//                                          a base image or a tooling container.\n//   - source alone (no Dockerfile)      → not a service. A loose script isn't a\n//                                          deployable unit; the manifest paths\n//                                          already cover real projects.\n//   - a manifest is present             → the manifest path owns the dir. This\n//                                          fallback bails so nothing double-mints.\n// Directories the walk already skips (`IGNORED_DIRS`, `.gitignore`) never reach\n// this function, so vendored / build-output dirs can't mint either.\n\n// Extension → language tag for a manifest-less service's `language` field. Only\n// the extensions the source walker actually reads (`SERVICE_FILE_EXTENSIONS`) map\n// to a language; anything else returns null so a `.sh` entrypoint or a `.json`\n// data file never counts as source.\nfunction languageForSourceExt(ext: string): string | null {\n  switch (ext) {\n    case '.py':\n      return 'python'\n    case '.go':\n      return 'go'\n    case '.rb':\n      return 'ruby'\n    case '.php':\n      return 'php'\n    case '.cs':\n      return 'csharp'\n    case '.java':\n      return 'java'\n    case '.kt':\n      return 'kotlin'\n    case '.rs':\n      return 'rust'\n    case '.cpp':\n    case '.cc':\n    case '.cxx':\n    case '.c++':\n    case '.hpp':\n    case '.hh':\n    case '.hxx':\n    case '.h++':\n      return 'cpp'\n    case '.ts':\n    case '.tsx':\n      return 'typescript'\n    case '.js':\n    case '.mjs':\n    case '.cjs':\n      return 'javascript'\n    default:\n      return null\n  }\n}\n\n// Detection precedence when a dir mixes languages at the top level — the winner\n// is the language with the most top-level source files, ties broken by this fixed\n// order so a mixed dir resolves to the same language on every pass (idempotency).\nconst LANGUAGE_PRECEDENCE = ['typescript', 'javascript', 'python', 'go', 'ruby', 'php', 'csharp', 'java', 'kotlin', 'rust', 'cpp']\n\n// Infer the service's language from the primary source at the *top level* of the\n// dir — not recursively. Top-level-only is the precision knob: it pins discovery\n// to a leaf service directory whose own files are the source (the load-generator\n// shape), so a repo root that merely has a Dockerfile and subdir services doesn't\n// mint a phantom root service off code that belongs to something else. Returns\n// null when the dir carries no recognized source, which is the \"Dockerfile alone\"\n// guardrail.\nasync function inferServiceLanguage(dir: string): Promise<string | null> {\n  const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => [])\n  const counts = new Map<string, number>()\n  for (const entry of entries) {\n    if (!entry.isFile()) continue\n    // NEAT's own generated bootstrap isn't the user's source.\n    if (isNeatAuthoredSourceFile(entry.name)) continue\n    const ext = path.extname(entry.name).toLowerCase()\n    if (!SERVICE_FILE_EXTENSIONS.has(ext)) continue\n    const lang = languageForSourceExt(ext)\n    if (!lang) continue\n    counts.set(lang, (counts.get(lang) ?? 0) + 1)\n  }\n  if (counts.size === 0) return null\n  let best: string | null = null\n  let bestCount = -1\n  for (const lang of LANGUAGE_PRECEDENCE) {\n    const c = counts.get(lang) ?? 0\n    if (c > bestCount) {\n      best = lang\n      bestCount = c\n    }\n  }\n  return best\n}\n\n// The language manifests every other discovery path keys on. A dir carrying any\n// of them is owned by that path, so the Dockerfile fallback stands down — even a\n// nameless package.json counts, so \"no language manifest\" is read strictly.\nasync function hasLanguageManifest(dir: string): Promise<boolean> {\n  return (\n    (await exists(path.join(dir, 'package.json'))) ||\n    (await exists(path.join(dir, 'pyproject.toml'))) ||\n    (await exists(path.join(dir, 'requirements.txt'))) ||\n    (await exists(path.join(dir, 'setup.py'))) ||\n    (await exists(path.join(dir, 'go.mod'))) ||\n    (await exists(path.join(dir, 'Gemfile'))) ||\n    (await exists(path.join(dir, 'composer.json'))) ||\n    // C#'s marker is a glob (`*.csproj` / `*.sln`), so it reads the directory\n    // rather than probing a fixed filename (ADR-196).\n    (await hasCsharpProject(dir)) ||\n    // Java (and its JVM sibling Kotlin, ADR-199) key on the same Maven / Gradle\n    // build manifest (ADR-197), so this one check stands the Dockerfile fallback\n    // down for both.\n    (await hasJavaManifest(dir)) ||\n    // Rust's marker is a fixed `Cargo.toml` (ADR-201).\n    (await hasRustManifest(dir)) ||\n    // C++'s marker is a fixed `CMakeLists.txt` (ADR-202).\n    (await hasCppManifest(dir))\n  )\n}\n\n// An nginx / OpenResty front end ships no source at all — a Dockerfile on an nginx\n// or OpenResty base image, its config, and static files — so the source-language\n// test above can't see it. It's still a deployable service: the Dockerfile's final\n// `FROM` (the runtime stage) names an nginx or OpenResty image AND the directory\n// carries an nginx config (`nginx.conf`, `conf/nginx.conf`, `conf.d/*.conf`). Both\n// are required, so a Dockerfile that merely mentions nginx, or a stray nginx.conf,\n// mints nothing. Its proxy_pass routes are read by infra/nginx.ts.\nconst NGINX_IMAGE = /^(?:[\\w.-]+\\/)*(?:nginx|openresty)(?:-[\\w.-]+)?(?::[\\w.-]+)?(?:@\\S+)?$/i\n\nasync function isNginxFrontend(dir: string): Promise<boolean> {\n  const dockerfile = await fs.readFile(path.join(dir, 'Dockerfile'), 'utf8').catch(() => '')\n  const froms = [...dockerfile.matchAll(/^\\s*FROM\\s+(?:--\\S+\\s+)*(\\S+)/gim)].map((m) => m[1]!)\n  const image = froms[froms.length - 1]\n  if (!image || !NGINX_IMAGE.test(image)) return false\n  if (await exists(path.join(dir, 'nginx.conf'))) return true\n  if (await exists(path.join(dir, 'conf', 'nginx.conf'))) return true\n  const confd = await fs.readdir(path.join(dir, 'conf.d')).catch(() => [] as string[])\n  return confd.some((n) => n.endsWith('.conf'))\n}\n\n// Cheap predicate the discovery walk uses to decide whether a manifest-less dir\n// is a candidate at all. The `Dockerfile` `exists` check gates the readdir, so a\n// dir without one pays a single `fs.access` and stops.\nexport async function hasDockerfileDeclaredService(dir: string): Promise<boolean> {\n  if (!(await exists(path.join(dir, 'Dockerfile')))) return false\n  return (await inferServiceLanguage(dir)) !== null || (await isNginxFrontend(dir))\n}\n\nexport async function discoverDockerfileService(\n  scanPath: string,\n  dir: string,\n): Promise<DiscoveredService | null> {\n  if (!(await exists(path.join(dir, 'Dockerfile')))) return null\n  // Manifest wins — the manifest-based paths run before this one in the discovery\n  // chain, but bail here too so the rule holds no matter the call order.\n  if (await hasLanguageManifest(dir)) return null\n  const language = (await inferServiceLanguage(dir)) ?? ((await isNginxFrontend(dir)) ? 'nginx' : null)\n  if (!language) return null\n  const name = path.basename(dir)\n  const pkg: PackageJson = { name, dependencies: {} }\n  const node: ServiceNode = {\n    id: serviceId(name),\n    type: NodeType.ServiceNode,\n    name,\n    language,\n    dependencies: {},\n    repoPath: path.relative(scanPath, dir),\n  }\n  return { pkg, dir, node }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { minimatch } from 'minimatch'\nimport { exists, readJson } from './shared.js'\n\nexport interface CodeownersRule {\n  pattern: string\n  owners: string\n}\n\nexport interface CodeownersFile {\n  rules: CodeownersRule[]\n}\n\ninterface PackageJsonAuthor {\n  author?: string | { name?: string }\n}\n\n// Read CODEOWNERS at <scanPath>/CODEOWNERS first, then <scanPath>/.github/CODEOWNERS.\n// Returns null when neither exists. ADR-054 #2.1.\nexport async function loadCodeowners(scanPath: string): Promise<CodeownersFile | null> {\n  const candidates = [\n    path.join(scanPath, 'CODEOWNERS'),\n    path.join(scanPath, '.github', 'CODEOWNERS'),\n  ]\n  for (const file of candidates) {\n    if (await exists(file)) {\n      const raw = await fs.readFile(file, 'utf8')\n      return parseCodeowners(raw)\n    }\n  }\n  return null\n}\n\nfunction parseCodeowners(raw: string): CodeownersFile {\n  const rules: CodeownersRule[] = []\n  for (const line of raw.split('\\n')) {\n    const trimmed = line.trim()\n    if (!trimmed || trimmed.startsWith('#')) continue\n    const match = /^(\\S+)\\s+(.+)$/.exec(trimmed)\n    if (!match) continue\n    rules.push({ pattern: match[1]!, owners: match[2]!.trim() })\n  }\n  return { rules }\n}\n\n// First matching pattern wins; returns the literal RHS or null. ADR-054 #2.1.\n// Pattern matcher is minimal per ADR-054 #6 — handles `*`, `**`, and exact\n// paths; not a full gitignore-style parser.\nexport function matchOwner(file: CodeownersFile, repoPath: string): string | null {\n  const normalized = repoPath.split(path.sep).join('/')\n  for (const rule of file.rules) {\n    if (matchesPattern(rule.pattern, normalized)) return rule.owners\n  }\n  return null\n}\n\nfunction matchesPattern(rawPattern: string, repoPath: string): boolean {\n  let pattern = rawPattern.startsWith('/') ? rawPattern.slice(1) : rawPattern\n  if (pattern === '*') return !repoPath.includes('/')\n  if (pattern === '**' || pattern === '') return true\n  // Trailing slash means \"everything in this directory\".\n  if (pattern.endsWith('/')) pattern = pattern + '**'\n  if (minimatch(repoPath, pattern, { dot: true })) return true\n  // A pattern that names a directory should match files beneath it too.\n  if (!pattern.includes('*') && minimatch(repoPath, pattern + '/**', { dot: true })) return true\n  return false\n}\n\n// Read <serviceDir>/package.json and return the `author` field as a literal\n// string. Accepts either string form (\"Cem D <cem@example.com>\") or object\n// form ({ name: 'Cem D' }). Returns null when missing or unparseable.\n// ADR-054 #2.2.\nexport async function readPackageJsonAuthor(serviceDir: string): Promise<string | null> {\n  const pkgPath = path.join(serviceDir, 'package.json')\n  if (!(await exists(pkgPath))) return null\n  try {\n    const pkg = await readJson<PackageJsonAuthor>(pkgPath)\n    if (!pkg.author) return null\n    if (typeof pkg.author === 'string') return pkg.author\n    if (typeof pkg.author === 'object' && typeof pkg.author.name === 'string') return pkg.author.name\n    return null\n  } catch {\n    return null\n  }\n}\n\n// Compute owner per ADR-054 priority: CODEOWNERS first, package.json `author`\n// fallback, undefined otherwise. Literal source value, no normalization (#3).\nexport async function computeServiceOwner(\n  codeowners: CodeownersFile | null,\n  repoPath: string | undefined,\n  serviceDir: string,\n): Promise<string | undefined> {\n  if (codeowners && repoPath !== undefined) {\n    const owner = matchOwner(codeowners, repoPath)\n    if (owner) return owner\n  }\n  const author = await readPackageJsonAuthor(serviceDir)\n  return author ?? undefined\n}\n","import path from 'node:path'\nimport { promises as fs } from 'node:fs'\nimport { parseAllDocuments } from 'yaml'\nimport type { ServiceNode } from '@neat.is/types'\nimport { NodeType } from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport { recordExtractionError } from './errors.js'\nimport {\n  CONFIG_FILE_EXTENSIONS,\n  IGNORED_DIRS,\n  exists,\n  isPythonVenvDir,\n  readYaml,\n  type DiscoveredService,\n} from './shared.js'\n\n// Populate ServiceNode.aliases from sources that the OTel layer is likely to\n// see in span attributes:\n//\n//   - docker-compose service names (compose-DNS).\n//   - Dockerfile LABEL values that name the service.\n//   - k8s metadata.name (and the cluster-DNS variants) for Service /\n//     Deployment / StatefulSet whose name matches a known service.\n//\n// resolveServiceId in ingest.ts checks aliases before falling back to a\n// FRONTIER placeholder; promoteFrontierNodes uses them to retire stale\n// placeholders once they map to a real service.\n\ninterface ComposeService {\n  container_name?: string\n  hostname?: string\n  networks?: string[] | Record<string, unknown>\n}\n\ninterface ComposeFile {\n  services?: Record<string, ComposeService>\n}\n\ninterface K8sDoc {\n  kind?: string\n  metadata?: {\n    name?: string\n    namespace?: string\n    labels?: Record<string, string>\n  }\n  spec?: {\n    selector?: {\n      app?: string\n      matchLabels?: Record<string, string>\n    }\n  }\n}\n\nconst K8S_KINDS_WITH_HOSTNAMES = new Set([\n  'Service',\n  'Deployment',\n  'StatefulSet',\n  'DaemonSet',\n])\n\nfunction addAliases(graph: NeatGraph, serviceId: string, candidates: Iterable<string>): void {\n  if (!graph.hasNode(serviceId)) return\n  const node = graph.getNodeAttributes(serviceId) as ServiceNode & { type?: string }\n  if (node.type !== NodeType.ServiceNode) return\n  const set = new Set(node.aliases ?? [])\n  for (const c of candidates) {\n    if (!c) continue\n    if (c === node.name) continue\n    set.add(c)\n  }\n  if (set.size === 0) return\n  const updated: ServiceNode = { ...node, aliases: [...set].sort() }\n  graph.replaceNodeAttributes(serviceId, updated)\n}\n\nfunction indexServicesByName(services: DiscoveredService[]): Map<string, string> {\n  const map = new Map<string, string>()\n  for (const s of services) {\n    map.set(s.node.name, s.node.id)\n    map.set(path.basename(s.dir), s.node.id)\n  }\n  return map\n}\n\nasync function collectComposeAliases(\n  graph: NeatGraph,\n  scanPath: string,\n  serviceIndex: Map<string, string>,\n): Promise<void> {\n  let composePath: string | null = null\n  for (const name of ['docker-compose.yml', 'docker-compose.yaml']) {\n    const abs = path.join(scanPath, name)\n    if (await exists(abs)) {\n      composePath = abs\n      break\n    }\n  }\n  if (!composePath) return\n\n  let compose: ComposeFile\n  try {\n    compose = await readYaml<ComposeFile>(composePath)\n  } catch (err) {\n    recordExtractionError(\n      'aliases compose',\n      path.relative(scanPath, composePath),\n      err,\n    )\n    return\n  }\n  if (!compose?.services) return\n\n  for (const [composeName, svc] of Object.entries(compose.services)) {\n    const serviceId = serviceIndex.get(composeName)\n    if (!serviceId) continue\n    const aliases = new Set<string>([composeName])\n    if (svc.container_name) aliases.add(svc.container_name)\n    if (svc.hostname) aliases.add(svc.hostname)\n    addAliases(graph, serviceId, aliases)\n  }\n}\n\nconst LABEL_KEYS = new Set([\n  'service',\n  'service.name',\n  'app',\n  'app.name',\n  'com.docker.compose.service',\n  'org.opencontainers.image.title',\n])\n\nfunction parseDockerfileLabels(content: string): string[] {\n  const out: string[] = []\n  // Support `LABEL key=value`, `LABEL key=\"value with spaces\"`, and the\n  // multi-pair form `LABEL k1=v1 k2=v2`. We don't try to honour line\n  // continuations — the common single-line form is enough.\n  const lineRegex = /^\\s*label\\s+(.+)$/i\n  for (const raw of content.split('\\n')) {\n    const m = lineRegex.exec(raw)\n    if (!m) continue\n    const rest = m[1]!\n    const pairRegex = /([\\w.-]+)\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s]+))/g\n    let pair: RegExpExecArray | null\n    while ((pair = pairRegex.exec(rest)) !== null) {\n      const key = pair[1]!.toLowerCase()\n      if (!LABEL_KEYS.has(key)) continue\n      const value = pair[3] ?? pair[4] ?? pair[5] ?? ''\n      if (value) out.push(value)\n    }\n  }\n  return out\n}\n\nasync function collectDockerfileAliases(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<void> {\n  for (const service of services) {\n    const dockerfilePath = path.join(service.dir, 'Dockerfile')\n    if (!(await exists(dockerfilePath))) continue\n    let content: string\n    try {\n      content = await fs.readFile(dockerfilePath, 'utf8')\n    } catch (err) {\n      recordExtractionError('aliases dockerfile', dockerfilePath, err)\n      continue\n    }\n    const aliases = parseDockerfileLabels(content)\n    if (aliases.length > 0) addAliases(graph, service.node.id, aliases)\n  }\n}\n\nasync function walkYamlFiles(start: string, depth = 0, max = 5): Promise<string[]> {\n  if (depth > max) return []\n  const out: string[] = []\n  const entries = await fs.readdir(start, { withFileTypes: true }).catch(() => [])\n  for (const entry of entries) {\n    if (entry.isDirectory()) {\n      if (IGNORED_DIRS.has(entry.name)) continue\n      const child = path.join(start, entry.name)\n      if (await isPythonVenvDir(child)) continue\n      out.push(...(await walkYamlFiles(child, depth + 1, max)))\n    } else if (entry.isFile() && CONFIG_FILE_EXTENSIONS.has(path.extname(entry.name))) {\n      out.push(path.join(start, entry.name))\n    }\n  }\n  return out\n}\n\nfunction k8sHostnames(name: string, namespace: string | undefined): string[] {\n  const ns = namespace ?? 'default'\n  return [\n    name,\n    `${name}.${ns}`,\n    `${name}.${ns}.svc`,\n    `${name}.${ns}.svc.cluster.local`,\n  ]\n}\n\nfunction k8sServiceTarget(\n  doc: K8sDoc,\n  byName: Map<string, string>,\n): string | null {\n  // For `Service` resources, the target is whatever app the spec selects, not\n  // necessarily the Service's own metadata.name. We prefer that mapping; if no\n  // selector, fall back to the metadata.name match.\n  const selector = doc.spec?.selector\n  const selectorApp = selector?.app ?? selector?.matchLabels?.app\n  if (selectorApp && byName.has(selectorApp)) return byName.get(selectorApp)!\n\n  const labelApp = doc.metadata?.labels?.app\n  if (labelApp && byName.has(labelApp)) return byName.get(labelApp)!\n\n  const metaName = doc.metadata?.name\n  if (metaName && byName.has(metaName)) return byName.get(metaName)!\n\n  return null\n}\n\nasync function collectK8sAliases(\n  graph: NeatGraph,\n  scanPath: string,\n  serviceIndex: Map<string, string>,\n): Promise<void> {\n  const files = await walkYamlFiles(scanPath)\n  for (const file of files) {\n    const content = await fs.readFile(file, 'utf8')\n    let docs: K8sDoc[]\n    try {\n      docs = parseAllDocuments(content).map((d) => d.toJSON() as K8sDoc)\n    } catch {\n      continue\n    }\n    for (const doc of docs) {\n      if (!doc?.kind || !doc.metadata?.name) continue\n      if (!K8S_KINDS_WITH_HOSTNAMES.has(doc.kind)) continue\n      const target = k8sServiceTarget(doc, serviceIndex)\n      if (!target) continue\n      addAliases(graph, target, k8sHostnames(doc.metadata.name, doc.metadata.namespace))\n    }\n  }\n}\n\nexport async function addServiceAliases(\n  graph: NeatGraph,\n  scanPath: string,\n  services: DiscoveredService[],\n): Promise<void> {\n  const byName = indexServicesByName(services)\n  await collectComposeAliases(graph, scanPath, byName)\n  await collectDockerfileAliases(graph, services)\n  await collectK8sAliases(graph, scanPath, byName)\n}\n","import type { NeatGraph } from '../graph.js'\nimport type { DiscoveredService } from './shared.js'\nimport { ensureFileNode, walkSourceFiles, toPosix } from './calls/shared.js'\nimport path from 'node:path'\n\n// Phase 1 — unconditional file enumeration (ADR-092, file-awareness.md §1).\n// Walks every source file matching SERVICE_FILE_EXTENSIONS within each service\n// and emits a FileNode + service ──CONTAINS──▶ file edge, regardless of whether\n// any call pattern fires from the file later.\nexport async function addFiles(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    const filePaths = await walkSourceFiles(service.dir, service.excludeDirs)\n    for (const filePath of filePaths) {\n      const relPath = toPosix(path.relative(service.dir, filePath))\n      const { nodesAdded: n, edgesAdded: e } = ensureFileNode(\n        graph,\n        service.pkg.name,\n        service.node.id,\n        relPath,\n      )\n      nodesAdded += n\n      edgesAdded += e\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport type { GraphEdge, SymbolKind, SymbolNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  symbolId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport type { DiscoveredService } from './shared.js'\nimport { recordExtractionError } from './errors.js'\nimport { loadSourceFiles, snippet, toPosix } from './calls/shared.js'\nimport {\n  GRAMMAR_BY_EXT,\n  collectSymbolDefs,\n  disambiguate,\n  parseSource,\n} from './symbols.js'\nimport { loadTsPathConfig, resolveJsImport, type TsPathConfig } from './imports.js'\n\n// Static symbol *edges* (ADR-158 §3, Phase 2). Builds on the Phase-1 SymbolNode\n// inventory: for every class it mints `INHERITS` / `IMPLEMENTS` from the parsed\n// heritage clause, and for every call expression a symbol→symbol `CALLS` from the\n// enclosing caller symbol to the callee — but only the confident ones. The\n// load-bearing discipline (ADR-158 §3, file-awareness.md §6): an edge is emitted\n// only when its target resolves to exactly one known SymbolNode without guessing —\n// a same-file definition, or an imported binding resolved through the import graph\n// to the exact exported symbol. A callee that needs a type or a runtime value to\n// resolve (method dispatch on a receiver, a dynamic/computed call, an unresolvable\n// or re-exported import, a default/namespace import) is left unclaimed rather than\n// fuzzy-matched. A guessed symbol edge poisons the determinism the graph sells.\n//\n// Runs after `addSymbols` (the inventory it resolves against) and `addImports`\n// (so the import graph is in place), reusing the same tree-sitter grammars and\n// the `resolveJsImport` specifier→file resolver rather than reimplementing them.\n// JS/TS only, matching Phase-1 node grain; Python/Go heritage and calls are a\n// follow-on rung. Every edge grades EXTRACTED with `evidence.file`/`line` pinned\n// to the real heritage clause / call site (never fabricated, §6).\n\n// A Phase-1 symbol as this producer needs it: the id plus the definition span it\n// was minted with, so a call line can be attributed to its enclosing symbol.\ninterface LocalSymbol {\n  sid: string\n  qualname: string\n  kind: SymbolKind\n  startLine: number\n  endLine: number\n}\n\n// A named import binding resolved to the intra-service file that defines it and\n// the exported name to match there. `import { Base } from './base'` →\n// `Base → { targetRelPath: 'base.ts', importedName: 'Base' }`; an alias keeps the\n// source-declared export name (`import { Shape as S }` → `S → …importedName:'Shape'`).\ninterface ResolvedImport {\n  targetRelPath: string\n  importedName: string\n}\n\n// The bare superclass name of a class's heritage, when it is a plain identifier\n// this producer can resolve — handling both grammar shapes: the TS grammar wraps\n// the superclass in an `extends_clause` (its `value` field), the JS grammar puts\n// the identifier directly under `class_heritage`. A qualified superclass\n// (`mod.Base`, a mixin call `mixin(Base)`) is not a bare identifier, so it returns\n// null and no INHERITS edge is guessed.\nfunction extendsInfo(\n  classHeritage: Parser.SyntaxNode,\n): { name: string; line: number } | null {\n  for (let i = 0; i < classHeritage.namedChildCount; i++) {\n    const child = classHeritage.namedChild(i)\n    if (!child) continue\n    if (child.type === 'extends_clause') {\n      const value = child.childForFieldName('value')\n      if (value && value.type === 'identifier') {\n        return { name: value.text, line: value.startPosition.row + 1 }\n      }\n      return null\n    }\n    // JS grammar: the superclass identifier hangs directly off class_heritage.\n    if (child.type === 'identifier') {\n      return { name: child.text, line: child.startPosition.row + 1 }\n    }\n  }\n  return null\n}\n\n// The bare implemented-type names of a class's `implements` clause (TS only).\n// Each entry is a `type_identifier` (`implements Shape`) or a `generic_type`\n// (`implements Comparable<number>`); a qualified `nested_type_identifier`\n// (`ns.Shape`) is skipped rather than guessed. Note: an interface is not a\n// SymbolNode (ADR-158 §2 fixes the kind set to function/method/constructor/class),\n// so an IMPLEMENTS edge lands only when the implemented name resolves to a known\n// *class* symbol (TS permits `implements <class>`); an `implements <interface>`\n// resolves to nothing and emits no edge, honestly, until interface symbols exist.\nfunction implementsInfo(\n  classHeritage: Parser.SyntaxNode,\n): { name: string; line: number }[] {\n  const out: { name: string; line: number }[] = []\n  for (let i = 0; i < classHeritage.namedChildCount; i++) {\n    const clause = classHeritage.namedChild(i)\n    if (!clause || clause.type !== 'implements_clause') continue\n    for (let j = 0; j < clause.namedChildCount; j++) {\n      const t = clause.namedChild(j)\n      if (!t) continue\n      if (t.type === 'type_identifier') {\n        out.push({ name: t.text, line: t.startPosition.row + 1 })\n      } else if (t.type === 'generic_type') {\n        const nameNode = t.childForFieldName('name')\n        if (nameNode && nameNode.type === 'type_identifier') {\n          out.push({ name: nameNode.text, line: nameNode.startPosition.row + 1 })\n        }\n      }\n    }\n  }\n  return out\n}\n\n// Collect the ES-import bindings of a file: local name → { specifier, importedName }.\n// Only named imports (including `as`-aliased) are collected — the binding names the\n// exported symbol exactly. Default imports (`import X from`) and namespace imports\n// (`import * as ns`) are skipped: resolving the former needs the target's\n// export-default declaration and the latter is member access, both deferred rather\n// than guessed. CommonJS `require` destructuring is likewise out of this slice.\nfunction collectImportBindings(\n  root: Parser.SyntaxNode,\n): Map<string, { specifier: string; importedName: string }> {\n  const out = new Map<string, { specifier: string; importedName: string }>()\n  const visit = (node: Parser.SyntaxNode): void => {\n    if (node.type === 'import_statement') {\n      const source = node.childForFieldName('source')\n      const specifier = source ? stringInner(source) : null\n      if (specifier) {\n        for (let i = 0; i < node.namedChildCount; i++) {\n          const clause = node.namedChild(i)\n          if (clause?.type === 'import_clause') collectClause(clause, specifier, out)\n        }\n      }\n      return\n    }\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (child) visit(child)\n    }\n  }\n  visit(root)\n  return out\n}\n\nfunction collectClause(\n  clause: Parser.SyntaxNode,\n  specifier: string,\n  out: Map<string, { specifier: string; importedName: string }>,\n): void {\n  for (let i = 0; i < clause.namedChildCount; i++) {\n    const child = clause.namedChild(i)\n    if (!child) continue\n    if (child.type === 'named_imports') {\n      for (let j = 0; j < child.namedChildCount; j++) {\n        const spec = child.namedChild(j)\n        if (spec?.type !== 'import_specifier') continue\n        const nameNode = spec.childForFieldName('name')\n        const aliasNode = spec.childForFieldName('alias')\n        if (!nameNode) continue\n        const importedName = nameNode.text\n        const localName = aliasNode ? aliasNode.text : importedName\n        out.set(localName, { specifier, importedName })\n      }\n    }\n    // `identifier` (default import) and `namespace_import` are intentionally\n    // skipped — see collectImportBindings.\n  }\n}\n\n// The interior text of a string literal node (its `string_fragment` child), or a\n// quote-stripped fallback. Mirrors imports.ts's `stringLiteralText`.\nfunction stringInner(node: Parser.SyntaxNode): string | null {\n  for (let i = 0; i < node.childCount; i++) {\n    const child = node.child(i)\n    if (child?.type === 'string_fragment') return child.text\n  }\n  const raw = node.text\n  return raw.length >= 2 ? raw.slice(1, -1) : null\n}\n\n// A heritage or call edge to emit once its target resolves.\ninterface EdgeRequest {\n  sourceSid: string\n  targetName: string\n  wantKind: SymbolKind\n  edgeType: typeof EdgeType.INHERITS | typeof EdgeType.IMPLEMENTS | typeof EdgeType.CALLS\n  line: number\n}\n\n// How one file's edges are named and resolved. The per-file core below is pure\n// over these, so the same resolution runs on first-party code (service-scoped\n// ids, the filesystem import resolver, the graph's symbols) and on dependency\n// code (dependency symbol ids, an in-memory resolver over the package's files).\nexport interface SymbolEdgeContext {\n  // The SymbolNode id for a definition in a file of this scope.\n  idFor: (relPath: string, qualname: string, disambiguator?: number) => string\n  // The scope-relative file an import specifier written in `fromRelPath` resolves\n  // to, or null when it leaves the scope or doesn't resolve.\n  resolveImport: (specifier: string, fromRelPath: string) => Promise<string | null> | string | null\n  // The kind of an existing SymbolNode, or null when there is no such symbol.\n  kindOf: (sid: string) => SymbolKind | null\n}\n\n/**\n * The confident INHERITS / IMPLEMENTS / CALLS edges of one JS/TS file: a target\n * is a same-file definition or a named import resolved to the exact exported\n * symbol, never a guess (ADR-158 §3). Pure over `ctx`: nothing is read or\n * written here. Edges come in walk order, deduplicated by id.\n */\nexport async function symbolEdgesOfFile(\n  root: Parser.SyntaxNode,\n  relPath: string,\n  content: string,\n  ctx: SymbolEdgeContext,\n): Promise<GraphEdge[]> {\n  // Rebuild this file's symbol table (spans + ids) from the same collector\n  // the node producer used, so ids and spans line up exactly.\n  const disambiguated = disambiguate(collectSymbolDefs(root))\n  const locals: LocalSymbol[] = disambiguated.map(({ def, disambiguator }) => ({\n    sid: ctx.idFor(relPath, def.qualname, disambiguator),\n    qualname: def.qualname,\n    kind: def.kind,\n    startLine: def.startLine,\n    endLine: def.endLine,\n  }))\n  if (locals.length === 0) return []\n\n  // A bare (dot-free) qualname that appears exactly once in the file — the\n  // clean, disambiguator-free id. Same-name siblings (overloads, a module and\n  // a nested definition sharing a name) are all disambiguated, so none lands\n  // here: existence in this map *is* the \"resolves to exactly one\" test.\n  const uniqueByBareName = new Map<string, LocalSymbol>()\n  for (const { def, disambiguator } of disambiguated) {\n    if (disambiguator !== undefined) continue\n    if (def.qualname.includes('.')) continue // a method, not a callable bare name\n    const local = locals.find((l) => l.qualname === def.qualname && l.startLine === def.startLine)\n    if (local) uniqueByBareName.set(def.qualname, local)\n  }\n\n  // The symbol a definition span identifies exactly (used to find a class's own\n  // node from its class_declaration span).\n  const localBySpan = new Map<string, LocalSymbol>()\n  for (const l of locals) localBySpan.set(`${l.startLine}:${l.endLine}`, l)\n\n  // Resolve every named-import binding's specifier to its in-scope file once, so\n  // target resolution during the walk stays a pure map lookup.\n  const bindings = collectImportBindings(root)\n  const resolvedImports = new Map<string, ResolvedImport>()\n  for (const [localName, binding] of bindings) {\n    const targetRelPath = await ctx.resolveImport(binding.specifier, relPath)\n    if (targetRelPath) {\n      resolvedImports.set(localName, { targetRelPath, importedName: binding.importedName })\n    }\n  }\n\n  // Resolve a used name to exactly one SymbolNode of the wanted kind, or null.\n  // Same-file first (a unique bare definition), then a resolved named import\n  // whose exported symbol exists in the target file at the wanted kind.\n  const resolveTarget = (name: string, wantKind: SymbolKind): string | null => {\n    const local = uniqueByBareName.get(name)\n    if (local) return local.kind === wantKind ? local.sid : null\n\n    const imp = resolvedImports.get(name)\n    if (imp) {\n      const candidate = ctx.idFor(imp.targetRelPath, imp.importedName)\n      if (ctx.kindOf(candidate) === wantKind) return candidate\n    }\n    return null\n  }\n\n  // Innermost symbol whose span contains `line` — the enclosing caller of a\n  // call site. Smallest containing span wins (a call inside a method belongs to\n  // the method, not the class), matching ingest's observed-landing choice.\n  const enclosingSymbol = (line: number): LocalSymbol | null => {\n    let best: LocalSymbol | null = null\n    for (const l of locals) {\n      if (line < l.startLine || line > l.endLine) continue\n      if (!best || l.endLine - l.startLine < best.endLine - best.startLine) best = l\n    }\n    return best\n  }\n\n  // Walk once, collecting the confident edge requests.\n  const requests: EdgeRequest[] = []\n  const walk = (node: Parser.SyntaxNode): void => {\n    if (\n      node.type === 'class_declaration' ||\n      node.type === 'abstract_class_declaration' ||\n      node.type === 'class'\n    ) {\n      const self = localBySpan.get(`${node.startPosition.row + 1}:${node.endPosition.row + 1}`)\n      if (self && self.kind === 'class') {\n        for (let i = 0; i < node.namedChildCount; i++) {\n          const child = node.namedChild(i)\n          if (!child || child.type !== 'class_heritage') continue\n          const ext = extendsInfo(child)\n          if (ext) {\n            requests.push({\n              sourceSid: self.sid,\n              targetName: ext.name,\n              wantKind: 'class',\n              edgeType: EdgeType.INHERITS,\n              line: ext.line,\n            })\n          }\n          for (const impl of implementsInfo(child)) {\n            requests.push({\n              sourceSid: self.sid,\n              targetName: impl.name,\n              wantKind: 'class',\n              edgeType: EdgeType.IMPLEMENTS,\n              line: impl.line,\n            })\n          }\n        }\n      }\n    } else if (node.type === 'call_expression') {\n      const fn = node.childForFieldName('function')\n      // Only a bare identifier callee is resolvable without a receiver type —\n      // `obj.foo()` (member_expression), `arr[k]()` (subscript), and dynamic\n      // callees are left to observed / SCIP (ADR-158 §3).\n      if (fn && fn.type === 'identifier') {\n        const line = node.startPosition.row + 1\n        const caller = enclosingSymbol(line)\n        if (caller) {\n          requests.push({\n            sourceSid: caller.sid,\n            targetName: fn.text,\n            wantKind: 'function',\n            edgeType: EdgeType.CALLS,\n            line,\n          })\n        }\n      }\n    }\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (child) walk(child)\n    }\n  }\n  walk(root)\n\n  const edges: GraphEdge[] = []\n  const seen = new Set<string>()\n  for (const req of requests) {\n    const targetSid = resolveTarget(req.targetName, req.wantKind)\n    if (!targetSid) continue\n    if (targetSid === req.sourceSid) continue // no self-loop (recursion / self-reference)\n\n    const edgeId = extractedEdgeId(req.sourceSid, targetSid, req.edgeType)\n    if (seen.has(edgeId)) continue\n    seen.add(edgeId)\n    edges.push({\n      id: edgeId,\n      source: req.sourceSid,\n      target: targetSid,\n      type: req.edgeType,\n      provenance: Provenance.EXTRACTED,\n      confidence: confidenceForExtracted('structural'),\n      evidence: {\n        file: relPath,\n        line: req.line,\n        snippet: snippet(content, req.line),\n      },\n    })\n  }\n  return edges\n}\n\nconst parsers = new Map<string, Parser>()\nexport function symbolEdgeParserFor(ext: string): Parser | null {\n  const grammar = GRAMMAR_BY_EXT[ext]\n  if (!grammar) return null\n  let parser = parsers.get(ext)\n  if (!parser) {\n    parser = new Parser()\n    parser.setLanguage(grammar)\n    parsers.set(ext, parser)\n  }\n  return parser\n}\n\nexport async function addSymbolEdges(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let edgesAdded = 0\n\n  for (const service of services) {\n    const serviceName = service.pkg.name\n    const tsPaths: TsPathConfig | null = await loadTsPathConfig(service.dir)\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n    const ctx: SymbolEdgeContext = {\n      idFor: (relPath, qualname, disambiguator) => symbolId(serviceName, relPath, qualname, disambiguator),\n      resolveImport: (specifier, fromRelPath) =>\n        resolveJsImport(specifier, path.dirname(path.join(service.dir, fromRelPath)), service.dir, tsPaths),\n      kindOf: (sid) => {\n        if (!graph.hasNode(sid)) return null\n        const node = graph.getNodeAttributes(sid) as SymbolNode\n        return node.type === NodeType.SymbolNode ? node.kind : null\n      },\n    }\n\n    for (const file of files) {\n      const parser = symbolEdgeParserFor(path.extname(file.path))\n      if (!parser) continue\n      const relPath = toPosix(path.relative(service.dir, file.path))\n\n      let root: Parser.SyntaxNode\n      try {\n        root = parseSource(parser, file.content).rootNode\n      } catch (err) {\n        recordExtractionError('symbol edge extraction', file.path, err)\n        continue\n      }\n\n      for (const edge of await symbolEdgesOfFile(root, relPath, file.content, ctx)) {\n        if (graph.hasEdge(edge.id)) continue\n        graph.addEdgeWithKey(edge.id, edge.source, edge.target, edge)\n        edgesAdded++\n      }\n    }\n  }\n\n  return { nodesAdded: 0, edgesAdded }\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport type { GraphEdge, SymbolKind } from '@neat.is/types'\nimport {\n  EdgeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  symbolId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport type { DiscoveredService } from './shared.js'\nimport { recordExtractionError } from './errors.js'\nimport { loadSourceFiles, snippet, toPosix } from './calls/shared.js'\nimport { SYMBOL_GRAMMAR_BY_EXT, collectGoSymbolDefs, disambiguate, parseSource } from './symbols.js'\n\n// Static Go symbol *edges* — the \"Python/Go calls\" follow-on rung `symbol-edges.ts`\n// names (ADR-158 §3). symbol-edges.ts mints JS/TS symbol→symbol CALLS; Go can't ride\n// it (its AST node types differ and it has no ES-import resolver), so Go gets its own\n// producer here holding the SAME precision discipline: a CALLS edge is emitted only\n// when the callee is a bare identifier resolving to exactly one known same-file\n// top-level function SymbolNode. A method/selector call (`s.Render()`, `fmt.Println()`),\n// a builtin (`len`, `make` — an identifier resolving to no in-file symbol), a\n// package-qualified call, and a same-package call to a function defined in another\n// file are all left unclaimed rather than guessed — a guessed symbol edge poisons the\n// determinism the graph sells (file-awareness.md §6).\n//\n// Deferred to later rungs, deliberately: same-package cross-file resolution (Go has no\n// per-file import map naming the exact callee the way `resolveJsImport` does, so it\n// needs a package symbol index), cross-package resolution, and method-dispatch edges\n// (which need receiver typing). Runs after `addSymbols`, reusing `collectGoSymbolDefs`\n// so ids and spans line up exactly with the SymbolNodes that producer minted. Every\n// edge grades EXTRACTED with evidence.file/line pinned to the real call site.\n\n// A Phase-1 Go symbol as this producer needs it: the id plus the definition span it\n// was minted with, so a call line can be attributed to its enclosing symbol.\ninterface LocalSymbol {\n  sid: string\n  qualname: string\n  kind: SymbolKind\n  startLine: number\n  endLine: number\n}\n\nexport async function addGoSymbolEdges(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  const grammar = SYMBOL_GRAMMAR_BY_EXT['.go']\n  if (!grammar) return { nodesAdded: 0, edgesAdded: 0 }\n  const parser = new Parser()\n  parser.setLanguage(grammar)\n\n  let edgesAdded = 0\n\n  for (const service of services) {\n    const serviceName = service.pkg.name\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n\n    for (const file of files) {\n      if (path.extname(file.path) !== '.go') continue\n      const relPath = toPosix(path.relative(service.dir, file.path))\n\n      let root: Parser.SyntaxNode\n      try {\n        root = parseSource(parser, file.content).rootNode\n      } catch (err) {\n        recordExtractionError('go symbol edge extraction', file.path, err)\n        continue\n      }\n\n      // Rebuild this file's symbol inventory from the same collector the node\n      // producer used, so ids and spans match the minted SymbolNodes exactly.\n      const disambiguated = disambiguate(collectGoSymbolDefs(root))\n      const locals: LocalSymbol[] = disambiguated.map(({ def, disambiguator }) => ({\n        sid: symbolId(serviceName, relPath, def.qualname, disambiguator),\n        qualname: def.qualname,\n        kind: def.kind,\n        startLine: def.startLine,\n        endLine: def.endLine,\n      }))\n      if (locals.length === 0) continue\n\n      // A bare (dot-free) function name that appears exactly once in the file — the\n      // clean, disambiguator-free id. A method qualname (`Receiver.method`) carries a\n      // dot and is excluded: a Go method is only ever reached through a selector\n      // (`s.Render()`), never a bare-identifier callee. Existence in this map IS the\n      // \"resolves to exactly one same-file function\" test (Go forbids two top-level\n      // funcs sharing a name, so a bare function name is unique by the language rule).\n      const uniqueFnByName = new Map<string, LocalSymbol>()\n      for (const { def, disambiguator } of disambiguated) {\n        if (disambiguator !== undefined) continue\n        if (def.kind !== 'function') continue\n        if (def.qualname.includes('.')) continue\n        const local = locals.find(\n          (l) => l.qualname === def.qualname && l.startLine === def.startLine,\n        )\n        if (local) uniqueFnByName.set(def.qualname, local)\n      }\n\n      // Innermost symbol whose span contains `line` — the enclosing caller of a call\n      // site; smallest containing span wins (a call inside a method belongs to the\n      // method), matching ingest's observed-landing choice.\n      const enclosingSymbol = (line: number): LocalSymbol | null => {\n        let best: LocalSymbol | null = null\n        for (const l of locals) {\n          if (line < l.startLine || line > l.endLine) continue\n          if (!best || l.endLine - l.startLine < best.endLine - best.startLine) best = l\n        }\n        return best\n      }\n\n      // Walk once, minting a CALLS for each confident bare-function call site.\n      const walk = (node: Parser.SyntaxNode): void => {\n        if (node.type === 'call_expression') {\n          const fn = node.childForFieldName('function')\n          // Only a bare identifier callee is a same-file free-function call. A\n          // `selector_expression` callee (`s.Render()`, `fmt.Println()`) needs a\n          // receiver type or a package to resolve and is left to observed / a later rung.\n          if (fn && fn.type === 'identifier') {\n            const line = node.startPosition.row + 1\n            const caller = enclosingSymbol(line)\n            const target = uniqueFnByName.get(fn.text)\n            if (caller && target && caller.sid !== target.sid) {\n              const edgeId = extractedEdgeId(caller.sid, target.sid, EdgeType.CALLS)\n              if (!graph.hasEdge(edgeId)) {\n                const edge: GraphEdge = {\n                  id: edgeId,\n                  source: caller.sid,\n                  target: target.sid,\n                  type: EdgeType.CALLS,\n                  provenance: Provenance.EXTRACTED,\n                  confidence: confidenceForExtracted('structural'),\n                  evidence: {\n                    file: relPath,\n                    line,\n                    snippet: snippet(file.content, line),\n                  },\n                }\n                graph.addEdgeWithKey(edgeId, caller.sid, target.sid, edge)\n                edgesAdded++\n              }\n            }\n          }\n        }\n        for (let i = 0; i < node.namedChildCount; i++) {\n          const child = node.namedChild(i)\n          if (child) walk(child)\n        }\n      }\n      walk(root)\n    }\n  }\n\n  return { nodesAdded: 0, edgesAdded }\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport type { ExtractedConfidenceKind, GraphEdge } from '@neat.is/types'\nimport { EdgeType, Provenance, confidenceForExtracted, extractedEdgeId, symbolId } from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport type { DiscoveredService } from './shared.js'\nimport { recordExtractionError } from './errors.js'\nimport { loadSourceFiles, snippet, toPosix, type SourceFile } from './calls/shared.js'\nimport { SYMBOL_GRAMMAR_BY_EXT, collectJavaSymbolDefs, disambiguate, parseSource } from './symbols.js'\n\n// Static Java symbol edges — the Java rung of ADR-158 §3, beside go-symbol-edges.ts\n// and holding its precision rule: a CALLS edge only where the callee resolves to\n// exactly one method SymbolNode, never a guess. Three tiers, all inside one\n// service directory, never across services:\n//\n//   1. Same file (#1442). An unqualified call or `this.m(…)` resolves to the one\n//      method the innermost named class declares under that name; `Type.m(…)` to\n//      the one such method of a same-file class.\n//   2. Typed receiver (ADR-257). `x.m(…)` / `this.x.m(…)` where `x` is a local, a\n//      parameter or a field (innermost scope first) resolves through `x`'s\n//      declared type: the type name goes through the file's single-type imports,\n//      then its own package, then its wildcard imports, to a class in the same\n//      service, and the callee is the one method that class declares by that name.\n//   3. Interface → implementation (ADR-257). When that declared type is an\n//      interface, the call lands on the implementing class's method, but only when\n//      the service's own source has exactly one class implementing it — the single\n//      candidate that lets Spring wire the bean without a @Qualifier.\n//\n// Left unclaimed: an overloaded name (the argument types would have to pick), an\n// inherited or outer-class method, a call inside an anonymous or local class\n// (its own methods would shadow), a receiver typed `var`, generic-only or by a\n// type outside the service, an interface with zero or several implementors in the\n// service, and any receiver that isn't a plain name (`a.b().m()`). One case the\n// rules can't see: a superclass declaring an overload of the same name, which a\n// call could bind to instead; the class hierarchy isn't read beyond `implements`.\n// Runs after `addSymbols`, reusing its collector so ids and spans match the minted\n// SymbolNodes exactly.\n\ninterface Def {\n  sid: string\n  qualname: string\n  kind: string\n  startIndex: number\n  ambiguous: boolean\n}\n\ninterface FileInfo {\n  file: SourceFile\n  relPath: string\n  root: Parser.SyntaxNode\n  pkg: string | undefined\n  singleImports: Map<string, string> // simple name → qualified\n  wildcardImports: string[] // package prefixes\n  defs: Def[]\n  byStart: Map<number, Def>\n}\n\ninterface TypeInfo {\n  qualname: string\n  isInterface: boolean\n  implementsNames: string[] // as written, resolved against `file`\n  file: FileInfo\n}\n\nconst TYPE_DECLS = new Set(['class_declaration', 'interface_declaration', 'enum_declaration', 'record_declaration'])\n\nfunction readImports(root: Parser.SyntaxNode): { single: Map<string, string>; wildcard: string[] } {\n  const single = new Map<string, string>()\n  const wildcard: string[] = []\n  for (const c of root.namedChildren) {\n    if (c.type !== 'import_declaration') continue\n    const m = /^import\\s+(static\\s+)?([\\w.]+?)(\\.\\*)?\\s*;/.exec(c.text)\n    if (!m || m[1]) continue\n    if (m[3]) wildcard.push(m[2]!)\n    else single.set(m[2]!.slice(m[2]!.lastIndexOf('.') + 1), m[2]!)\n  }\n  return { single, wildcard }\n}\n\n// A declared type as a name to resolve; generics, arrays and `var` → null.\nfunction declaredTypeName(typeNode: Parser.SyntaxNode | null): string | null {\n  if (!typeNode) return null\n  if (typeNode.type === 'type_identifier') return typeNode.text === 'var' ? null : typeNode.text\n  if (typeNode.type === 'scoped_type_identifier') return typeNode.text\n  return null\n}\n\n// A field's declared type in a class body; undefined when the class has no such field.\nfunction fieldType(name: string, classNode: Parser.SyntaxNode): string | null | undefined {\n  for (const f of classNode.childForFieldName('body')?.namedChildren ?? []) {\n    if (f.type !== 'field_declaration') continue\n    for (const d of f.namedChildren) {\n      if (d.type === 'variable_declarator' && d.childForFieldName('name')?.text === name) {\n        return declaredTypeName(f.childForFieldName('type'))\n      }\n    }\n  }\n  return undefined\n}\n\n// The declared type of `name` at `call`: a local or parameter of an enclosing\n// scope (innermost first), else a field of the innermost class. null when it's\n// declared but untyped for our purposes (var, generic); undefined when not found.\nfunction declaredType(name: string, call: Parser.SyntaxNode, classNode: Parser.SyntaxNode): string | null | undefined {\n  for (let n: Parser.SyntaxNode | null = call.parent; n && n !== classNode; n = n.parent) {\n    let found: string | null | undefined\n    for (const c of n.namedChildren) {\n      if (c.startIndex >= call.startIndex) break\n      if (c.type !== 'local_variable_declaration') continue\n      for (const d of c.namedChildren) {\n        if (d.type === 'variable_declarator' && d.childForFieldName('name')?.text === name) {\n          found = declaredTypeName(c.childForFieldName('type'))\n        }\n      }\n    }\n    if (found !== undefined) return found\n    if (n.type === 'enhanced_for_statement' && n.childForFieldName('name')?.text === name) {\n      return declaredTypeName(n.childForFieldName('type'))\n    }\n    if (n.type === 'method_declaration' || n.type === 'constructor_declaration' || n.type === 'lambda_expression') {\n      const params = n.childForFieldName('parameters')\n      if (params?.type === 'identifier' && params.text === name) return null // `x -> …`\n      for (const p of params?.namedChildren ?? []) {\n        if (p.type === 'formal_parameter' && p.childForFieldName('name')?.text === name) {\n          return declaredTypeName(p.childForFieldName('type'))\n        }\n        if ((p.type === 'identifier' || p.type === 'spread_parameter') && p.text.endsWith(name)) return null\n      }\n    }\n  }\n  return fieldType(name, classNode)\n}\n\nexport async function addJavaSymbolEdges(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  const grammar = SYMBOL_GRAMMAR_BY_EXT['.java']\n  if (!grammar) return { nodesAdded: 0, edgesAdded: 0 }\n  const parser = new Parser()\n  parser.setLanguage(grammar)\n  let edgesAdded = 0\n\n  for (const service of services) {\n    if (service.node.language !== 'java') continue\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n\n    // Pass 1: every file's symbols, package, imports and declared types.\n    const infos: FileInfo[] = []\n    const types = new Map<string, TypeInfo | null>() // null: qualname declared twice\n    for (const file of files) {\n      if (path.extname(file.path) !== '.java') continue\n      let root: Parser.SyntaxNode\n      try {\n        root = parseSource(parser, file.content).rootNode\n      } catch (err) {\n        recordExtractionError('java symbol edge extraction', file.path, err)\n        continue\n      }\n      const relPath = toPosix(path.relative(service.dir, file.path))\n      const defs: Def[] = disambiguate(collectJavaSymbolDefs(root)).map(({ def, disambiguator }) => ({\n        sid: symbolId(service.pkg.name, relPath, def.qualname, disambiguator),\n        qualname: def.qualname,\n        kind: def.kind,\n        startIndex: def.startIndex,\n        ambiguous: disambiguator !== undefined,\n      }))\n      const byStart = new Map<number, Def>()\n      for (const d of defs) byStart.set(d.startIndex, d)\n      const { single, wildcard } = readImports(root)\n      const info: FileInfo = {\n        file,\n        relPath,\n        root,\n        pkg: root.namedChildren.find((c) => c.type === 'package_declaration')?.namedChildren[0]?.text,\n        singleImports: single,\n        wildcardImports: wildcard,\n        defs,\n        byStart,\n      }\n      infos.push(info)\n      const visitTypes = (n: Parser.SyntaxNode): void => {\n        if (TYPE_DECLS.has(n.type)) {\n          const def = byStart.get(n.startIndex)\n          if (def) {\n            const names: string[] = []\n            const ifaces = n.type === 'class_declaration' ? n.childForFieldName('interfaces') : null\n            for (const t of ifaces?.descendantsOfType(['type_identifier', 'scoped_type_identifier']) ?? []) {\n              if (t.parent?.type === 'type_list') names.push(t.text)\n            }\n            types.set(\n              def.qualname,\n              types.has(def.qualname)\n                ? null\n                : { qualname: def.qualname, isInterface: n.type === 'interface_declaration', implementsNames: names, file: info },\n            )\n          }\n        }\n        for (const c of n.namedChildren) visitTypes(c)\n      }\n      visitTypes(root)\n    }\n    if (infos.length === 0) continue\n\n    // A type name as written in `info` → a type declared in this service.\n    const resolveType = (name: string, info: FileInfo): TypeInfo | null => {\n      if (name.includes('.')) return types.get(name) ?? null\n      const imported = info.singleImports.get(name)\n      if (imported) return types.get(imported) ?? null\n      const local = types.get(info.pkg ? `${info.pkg}.${name}` : name)\n      if (local) return local\n      const viaWildcard = info.wildcardImports\n        .map((p) => types.get(`${p}.${name}`))\n        .filter((t): t is TypeInfo => !!t)\n      return viaWildcard.length === 1 ? viaWildcard[0]! : null\n    }\n\n    // Methods by owner + name across the service; more than one means overloads.\n    const methods = new Map<string, Def[]>()\n    for (const info of infos) {\n      for (const d of info.defs) {\n        if (d.kind === 'method') methods.set(d.qualname, [...(methods.get(d.qualname) ?? []), d])\n      }\n    }\n    const uniqueMethod = (owner: string, name: string): Def | null => {\n      const found = methods.get(`${owner}.${name}`)\n      return found && found.length === 1 && !found[0]!.ambiguous ? found[0]! : null\n    }\n\n    // Interface → the classes in this service that implement it directly.\n    const implementors = new Map<string, string[]>()\n    for (const t of types.values()) {\n      if (!t || t.isInterface) continue\n      for (const n of t.implementsNames) {\n        const iface = resolveType(n, t.file)\n        if (iface?.isInterface) implementors.set(iface.qualname, [...(implementors.get(iface.qualname) ?? []), t.qualname])\n      }\n    }\n\n    const addEdge = (caller: Def, target: Def, kind: ExtractedConfidenceKind, info: FileInfo, line: number): void => {\n      if (caller.sid === target.sid) return\n      const edgeId = extractedEdgeId(caller.sid, target.sid, EdgeType.CALLS)\n      if (graph.hasEdge(edgeId) || !graph.hasNode(caller.sid) || !graph.hasNode(target.sid)) return\n      const edge: GraphEdge = {\n        id: edgeId,\n        source: caller.sid,\n        target: target.sid,\n        type: EdgeType.CALLS,\n        provenance: Provenance.EXTRACTED,\n        confidence: confidenceForExtracted(kind),\n        evidence: { file: info.relPath, line, snippet: snippet(info.file.content, line) },\n      }\n      graph.addEdgeWithKey(edgeId, caller.sid, target.sid, edge)\n      edgesAdded++\n    }\n\n    // A typed receiver's call: tier 2 on a class, tier 3 through an interface.\n    const viaType = (typeName: string, name: string, info: FileInfo): { target: Def; kind: ExtractedConfidenceKind } | null => {\n      const type = resolveType(typeName, info)\n      if (!type) return null\n      if (!type.isInterface) {\n        const t = uniqueMethod(type.qualname, name)\n        return t ? { target: t, kind: 'structural' } : null\n      }\n      const impls = implementors.get(type.qualname) ?? []\n      if (impls.length !== 1) return null\n      const t = uniqueMethod(impls[0]!, name)\n      return t ? { target: t, kind: 'verified-call-site' } : null\n    }\n\n    // Pass 2: resolve each call site.\n    for (const info of infos) {\n      const classBySimple = new Map<string, string | null>()\n      for (const d of info.defs) {\n        if (d.kind !== 'class') continue\n        const simple = d.qualname.slice(d.qualname.lastIndexOf('.') + 1)\n        classBySimple.set(simple, classBySimple.has(simple) ? null : d.qualname)\n      }\n\n      // The caller and the innermost named class, or null when an anonymous or\n      // local class sits in between.\n      const context = (call: Parser.SyntaxNode): { caller: Def; classNode: Parser.SyntaxNode; classQual: string } | null => {\n        let caller: Def | null = null\n        for (let n = call.parent; n; n = n.parent) {\n          if (n.type === 'class_body' && n.parent?.type === 'object_creation_expression') return null\n          if (!caller && (n.type === 'method_declaration' || n.type === 'constructor_declaration')) {\n            caller = info.byStart.get(n.startIndex) ?? null\n            if (!caller) return null\n          }\n          if (TYPE_DECLS.has(n.type)) {\n            const cls = info.byStart.get(n.startIndex)\n            if (!caller || !cls || cls.kind !== 'class') return null\n            return { caller, classNode: n, classQual: cls.qualname }\n          }\n        }\n        return null\n      }\n\n      const visit = (node: Parser.SyntaxNode): void => {\n        if (node.type === 'method_invocation') {\n          const name = node.childForFieldName('name')?.text\n          const obj = node.childForFieldName('object')\n          const ctx = name ? context(node) : null\n          if (ctx && name) {\n            const line = node.startPosition.row + 1\n            let hit: { target: Def; kind: ExtractedConfidenceKind } | null = null\n            if (!obj || obj.type === 'this') {\n              // Tier 1: the enclosing class's own method.\n              const t = uniqueMethod(ctx.classQual, name)\n              if (t && info.defs.includes(t)) hit = { target: t, kind: 'structural' }\n            } else if (obj.type === 'identifier') {\n              const typeName = declaredType(obj.text, node, ctx.classNode)\n              if (typeName) hit = viaType(typeName, name, info)\n              else if (typeName === undefined) {\n                // Tier 1: `Type.m()` on a same-file class.\n                const cls = classBySimple.get(obj.text)\n                const t = cls ? uniqueMethod(cls, name) : null\n                if (t) hit = { target: t, kind: 'structural' }\n              }\n            } else if (obj.type === 'field_access' && obj.childForFieldName('object')?.type === 'this') {\n              const field = obj.childForFieldName('field')?.text\n              const typeName = field ? fieldType(field, ctx.classNode) : null\n              if (typeName) hit = viaType(typeName, name, info)\n            }\n            if (hit) addEdge(ctx.caller, hit.target, hit.kind, info, line)\n          }\n        }\n        for (const c of node.namedChildren) visit(c)\n      }\n      visit(info.root)\n    }\n  }\n  return { nodesAdded: 0, edgesAdded }\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport type { GraphEdge, ServerActionNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  serverActionId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport { isTestPath, type DiscoveredService } from './shared.js'\nimport { recordExtractionError } from './errors.js'\nimport { ensureFileNode, loadSourceFiles, snippet, toPosix } from './calls/shared.js'\nimport { GRAMMAR_BY_EXT, parseSource } from './symbols.js'\nimport { loadTsPathConfig, resolveJsImport, type TsPathConfig } from './imports.js'\n\n// Next.js Server Action extraction (ADR-168). A Server Action is the mutation\n// boundary of a modern App Router app: an exported async function marked\n// `\"use server\"`, either by a module-level directive (every exported async\n// function in the file is an action) or an in-body directive (that one\n// function). The client references the imported action binding — a call, an\n// `action={fn}` JSX attribute, a `useActionState(fn)` / `fn.bind(...)` argument —\n// and Next posts to it, serialising the call to an opaque `Next-Action` hash. At\n// HTTP grain the whole surface collapses onto one POST edge, so this producer\n// mints a ServerActionNode per exported action to recover the per-action\n// topology, owned by its file through `file ──CONTAINS──▶ action`, and stitches\n// `file ──CALLS──▶ action` on any client reference resolved through the import\n// graph.\n//\n// EXTRACTED-first: OBSERVED fusion is deferred (the `Next-Action` hash carries no\n// action name), the same posture GraphQLOperationNode took before its static\n// extractor. Scope is gated by the `next` manifest dependency, JS/TS only,\n// matching the SymbolNode grain the client-stitch resolves against. The\n// load-bearing discipline (file-awareness.md §6): the client-stitch fires only\n// when the imported binding resolves through `resolveJsImport` to exactly one\n// known ServerActionNode — never fuzzy-matched — so the edge is deterministic.\n\n// The interior text of a JS/TS string literal node (its `string_fragment`\n// child), quote-stripped. Mirrors imports.ts's `stringLiteralText`.\nfunction stringLiteralText(node: Parser.SyntaxNode): string | null {\n  for (let i = 0; i < node.childCount; i++) {\n    const child = node.child(i)\n    if (child?.type === 'string_fragment') return child.text\n  }\n  const raw = node.text\n  return raw.length >= 2 ? raw.slice(1, -1) : null\n}\n\n// A `\"use server\"` directive is a leading string-literal expression statement in\n// a module body or a function's statement block. Scan only the leading run of\n// string-literal statements (the directive prologue): a `\"use strict\"` /\n// `\"use client\"` before it is skipped, and the first non-directive statement ends\n// the prologue. Returns true when one of the leading directives is `use server`.\nfunction hasUseServerDirective(container: Parser.SyntaxNode): boolean {\n  for (let i = 0; i < container.namedChildCount; i++) {\n    const stmt = container.namedChild(i)\n    if (!stmt || stmt.type !== 'expression_statement') break\n    const expr = stmt.namedChild(0)\n    if (!expr || expr.type !== 'string') break\n    if (stringLiteralText(expr) === 'use server') return true\n    // Another leading directive (`use strict` / `use client`) — keep scanning.\n  }\n  return false\n}\n\n// A function node is async when it carries the `async` keyword token. tree-sitter\n// exposes it as an anonymous child of the function / arrow node.\nfunction isAsyncFunction(node: Parser.SyntaxNode): boolean {\n  for (let i = 0; i < node.childCount; i++) {\n    if (node.child(i)?.type === 'async') return true\n  }\n  return false\n}\n\n// One exported async function the file declares — the unit a `\"use server\"`\n// directive promotes to an action. `bodyNode` is the function's statement block\n// (for the in-body directive test) or null for a concise-body arrow.\ninterface ExportedAsyncFn {\n  exportName: string\n  fnNode: Parser.SyntaxNode\n  bodyNode: Parser.SyntaxNode | null\n  line: number\n}\n\n// Collect the file's directly-exported async functions: `export async function\n// f(){}` and `export const f = async () => {}` / `= async function(){}`. A\n// destructuring export, a re-export clause (`export { f }`), and a default export\n// are out of this slice — the direct-declaration forms are the idiomatic action\n// shape. Sync exports are skipped (a Server Action must be async).\nfunction collectExportedAsyncFns(root: Parser.SyntaxNode): ExportedAsyncFn[] {\n  const out: ExportedAsyncFn[] = []\n  const visit = (node: Parser.SyntaxNode): void => {\n    if (node.type === 'export_statement') {\n      const decl = node.childForFieldName('declaration')\n      const line = node.startPosition.row + 1\n      if (decl?.type === 'function_declaration') {\n        const name = decl.childForFieldName('name')?.text\n        if (name && isAsyncFunction(decl)) {\n          out.push({ exportName: name, fnNode: decl, bodyNode: decl.childForFieldName('body'), line })\n        }\n      } else if (decl?.type === 'lexical_declaration' || decl?.type === 'variable_declaration') {\n        for (let i = 0; i < decl.namedChildCount; i++) {\n          const d = decl.namedChild(i)\n          if (d?.type !== 'variable_declarator') continue\n          const nameNode = d.childForFieldName('name')\n          const value = d.childForFieldName('value')\n          if (nameNode?.type !== 'identifier' || !value) continue\n          if (\n            (value.type === 'arrow_function' ||\n              value.type === 'function' ||\n              value.type === 'function_expression' ||\n              value.type === 'generator_function') &&\n            isAsyncFunction(value)\n          ) {\n            out.push({\n              exportName: nameNode.text,\n              fnNode: value,\n              bodyNode: value.childForFieldName('body'),\n              line,\n            })\n          }\n        }\n      }\n    }\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (child) visit(child)\n    }\n  }\n  visit(root)\n  return out\n}\n\n// The named-import bindings of a file: local name → the exported name it names in\n// its source module. Only named imports (including `as`-aliased) are collected —\n// a Server Action is a named export, so a default / namespace import can't name\n// one. `import type` is skipped (a type reference is not a value call path).\nfunction collectNamedImports(\n  root: Parser.SyntaxNode,\n): Map<string, { specifier: string; importedName: string }> {\n  const out = new Map<string, { specifier: string; importedName: string }>()\n  const visit = (node: Parser.SyntaxNode): void => {\n    if (node.type === 'import_statement') {\n      // `import type { … }` — skip the whole statement.\n      for (let i = 0; i < node.childCount; i++) {\n        if (node.child(i)?.type === 'type') return\n      }\n      const source = node.childForFieldName('source')\n      const specifier = source ? stringLiteralText(source) : null\n      if (specifier) {\n        for (let i = 0; i < node.namedChildCount; i++) {\n          const clause = node.namedChild(i)\n          if (clause?.type !== 'import_clause') continue\n          for (let j = 0; j < clause.namedChildCount; j++) {\n            const named = clause.namedChild(j)\n            if (named?.type !== 'named_imports') continue\n            for (let k = 0; k < named.namedChildCount; k++) {\n              const spec = named.namedChild(k)\n              if (spec?.type !== 'import_specifier') continue\n              // A per-specifier `import { type Foo }` marks a type-only binding.\n              let isType = false\n              for (let t = 0; t < spec.childCount; t++) {\n                if (spec.child(t)?.type === 'type') isType = true\n              }\n              if (isType) continue\n              const nameNode = spec.childForFieldName('name')\n              if (!nameNode) continue\n              const importedName = nameNode.text\n              const localName = spec.childForFieldName('alias')?.text ?? importedName\n              out.set(localName, { specifier, importedName })\n            }\n          }\n        }\n      }\n      return\n    }\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (child) visit(child)\n    }\n  }\n  visit(root)\n  return out\n}\n\n// First reference line for each name in `wanted`, walking value-position\n// `identifier` uses and skipping the import declarations themselves. A call\n// (`fn()`), a JSX attribute (`action={fn}`), a `useActionState(fn)` argument, and\n// a `fn.bind(...)` receiver are all plain `identifier` nodes — property keys and\n// shorthand are their own node types, so they never match — which is what closes\n// the form-action gap: referenced, not only called.\nfunction firstReferenceLines(\n  root: Parser.SyntaxNode,\n  wanted: Set<string>,\n): Map<string, number> {\n  const lines = new Map<string, number>()\n  const visit = (node: Parser.SyntaxNode): void => {\n    // Don't descend into the import that declares the binding — the import\n    // specifier is not a usage reference.\n    if (node.type === 'import_statement') return\n    if (node.type === 'identifier' && wanted.has(node.text) && !lines.has(node.text)) {\n      lines.set(node.text, node.startPosition.row + 1)\n    }\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (child) visit(child)\n    }\n  }\n  visit(root)\n  return lines\n}\n\nexport async function addServerActions(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  const parsers = new Map<string, Parser>()\n  const parserForExt = (ext: string): Parser | null => {\n    const grammar = GRAMMAR_BY_EXT[ext]\n    if (!grammar) return null\n    let parser = parsers.get(ext)\n    if (!parser) {\n      parser = new Parser()\n      parser.setLanguage(grammar)\n      parsers.set(ext, parser)\n    }\n    return parser\n  }\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    const deps = {\n      ...(service.pkg.dependencies ?? {}),\n      ...(service.pkg.devDependencies ?? {}),\n    }\n    // Gated on the `next` dependency, the same registry discipline addRoutes\n    // uses — a service that isn't a Next.js app declares no Server Actions.\n    if (deps['next'] === undefined) continue\n\n    const tsPaths: TsPathConfig | null = await loadTsPathConfig(service.dir)\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n\n    // ── Pass 1: mint an action node per exported `\"use server\"` function. ──\n    for (const file of files) {\n      if (isTestPath(file.path)) continue\n      const parser = parserForExt(path.extname(file.path))\n      if (!parser) continue\n      const relPath = toPosix(path.relative(service.dir, file.path))\n\n      let root: Parser.SyntaxNode\n      try {\n        root = parseSource(parser, file.content).rootNode\n      } catch (err) {\n        recordExtractionError('server action extraction', file.path, err)\n        continue\n      }\n\n      const moduleDirective = hasUseServerDirective(root)\n      const exported = collectExportedAsyncFns(root)\n      const actions = exported.filter(\n        (fn) => moduleDirective || (fn.bodyNode ? hasUseServerDirective(fn.bodyNode) : false),\n      )\n      if (actions.length === 0) continue\n\n      // The file owns its actions; ensure its FileNode (and the owning\n      // `service ──CONTAINS──▶ file` edge) exists before an action hangs off it.\n      const { fileNodeId, nodesAdded: fn, edgesAdded: fe } = ensureFileNode(\n        graph,\n        service.pkg.name,\n        service.node.id,\n        relPath,\n      )\n      nodesAdded += fn\n      edgesAdded += fe\n\n      for (const action of actions) {\n        const aid = serverActionId(service.pkg.name, relPath, action.exportName)\n        if (!graph.hasNode(aid)) {\n          const node: ServerActionNode = {\n            id: aid,\n            type: NodeType.ServerActionNode,\n            name: action.exportName,\n            service: service.pkg.name,\n            module: relPath,\n            exportName: action.exportName,\n            path: relPath,\n            line: action.line,\n            discoveredVia: 'static',\n          }\n          graph.addNode(aid, node)\n          nodesAdded++\n        }\n        // `file ──CONTAINS──▶ action` — structural ownership, the same tier and\n        // shape as `file ──CONTAINS──▶ symbol` (file-awareness.md §2), evidence\n        // pinned to the action's declaration file:line.\n        const containsId = extractedEdgeId(fileNodeId, aid, EdgeType.CONTAINS)\n        if (!graph.hasEdge(containsId)) {\n          const edge: GraphEdge = {\n            id: containsId,\n            source: fileNodeId,\n            target: aid,\n            type: EdgeType.CONTAINS,\n            provenance: Provenance.EXTRACTED,\n            confidence: confidenceForExtracted('structural'),\n            evidence: {\n              file: relPath,\n              line: action.line,\n              snippet: snippet(file.content, action.line),\n            },\n          }\n          graph.addEdgeWithKey(containsId, fileNodeId, aid, edge)\n          edgesAdded++\n        }\n      }\n    }\n\n    // ── Pass 2: client-stitch `file ──CALLS──▶ action` on any reference to an ──\n    //    imported action binding, resolved through the import graph.\n    for (const file of files) {\n      if (isTestPath(file.path)) continue\n      const parser = parserForExt(path.extname(file.path))\n      if (!parser) continue\n      const relPath = toPosix(path.relative(service.dir, file.path))\n      const fileDir = path.dirname(file.path)\n\n      let root: Parser.SyntaxNode\n      try {\n        root = parseSource(parser, file.content).rootNode\n      } catch (err) {\n        recordExtractionError('server action stitch', file.path, err)\n        continue\n      }\n\n      // Resolve each named import to a known ServerActionNode; a local binding\n      // that resolves to one is an action reference in this file.\n      const bindings = collectNamedImports(root)\n      const actionBindings = new Map<string, string>() // local name → action id\n      for (const [local, binding] of bindings) {\n        const target = await resolveJsImport(binding.specifier, fileDir, service.dir, tsPaths)\n        if (!target) continue\n        const aid = serverActionId(service.pkg.name, target, binding.importedName)\n        if (graph.hasNode(aid)) actionBindings.set(local, aid)\n      }\n      if (actionBindings.size === 0) continue\n\n      const refLines = firstReferenceLines(root, new Set(actionBindings.keys()))\n\n      let clientFileId: string | null = null\n      for (const [local, aid] of actionBindings) {\n        const line = refLines.get(local)\n        if (line === undefined) continue // imported but never referenced — no edge, honestly.\n        if (clientFileId === null) {\n          const ensured = ensureFileNode(graph, service.pkg.name, service.node.id, relPath)\n          clientFileId = ensured.fileNodeId\n          nodesAdded += ensured.nodesAdded\n          edgesAdded += ensured.edgesAdded\n        }\n        // `file ──CALLS──▶ action` — a client reference to the action, resolved\n        // through the import graph to exactly one known node. Reuses CALLS; no new\n        // edge type (ADR-168). Deduped by the deterministic edge id, so multiple\n        // references (a call and a JSX `action={fn}`) land one edge.\n        const callsId = extractedEdgeId(clientFileId, aid, EdgeType.CALLS)\n        if (graph.hasEdge(callsId)) continue\n        const edge: GraphEdge = {\n          id: callsId,\n          source: clientFileId,\n          target: aid,\n          type: EdgeType.CALLS,\n          provenance: Provenance.EXTRACTED,\n          confidence: confidenceForExtracted('structural'),\n          evidence: {\n            file: relPath,\n            line,\n            snippet: snippet(file.content, line),\n          },\n        }\n        graph.addEdgeWithKey(callsId, clientFileId, aid, edge)\n        edgesAdded++\n      }\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import path from 'node:path'\nimport type {\n  CompatibleDriver,\n  ConfigNode,\n  DatabaseNode,\n  GraphEdge,\n  GraphNode,\n  ServiceNode,\n} from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  configId,\n  databaseId,\n  confidenceForExtracted,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport {\n  checkCompatibility,\n  checkDeprecatedApi,\n  checkNodeEngineConstraint,\n  checkPackageConflict,\n  compatPairs,\n  deprecatedApis,\n  nodeEngineConstraints,\n  packageConflicts,\n} from '../../compat.js'\nimport {\n  cleanVersion,\n  isConfigFile,\n  makeEdgeId,\n  type DiscoveredService,\n} from '../shared.js'\nimport { ensureFileNode, toPosix } from '../calls/shared.js'\nimport { dbConfigYamlParser } from './db-config-yaml.js'\nimport { dotenvParser } from './dotenv.js'\nimport { prismaParser } from './prisma.js'\nimport { drizzleParser } from './drizzle.js'\nimport { knexParser } from './knex.js'\nimport { ormconfigParser } from './ormconfig.js'\nimport { typeormParser } from './typeorm.js'\nimport { sequelizeParser } from './sequelize.js'\nimport { csharpParser } from './csharp.js'\nimport { springDatasourceParser } from './spring.js'\nimport { dockerComposeParser } from './docker-compose.js'\nimport type { DbConfig } from './shared.js'\n\nexport type { DbConfig } from './shared.js'\n\nexport interface DbParser {\n  name: string\n  parse(serviceDir: string): Promise<DbConfig[]>\n}\n\n// Registry — order is for tie-breaking only (first wins on identical host).\n// db-config.yaml stays first so the canonical demo behaviour matches today's\n// extraction byte-for-byte.\nexport const DB_PARSERS: DbParser[] = [\n  dbConfigYamlParser,\n  dotenvParser,\n  prismaParser,\n  drizzleParser,\n  knexParser,\n  ormconfigParser,\n  typeormParser,\n  sequelizeParser,\n  csharpParser,\n  springDatasourceParser,\n  dockerComposeParser,\n]\n\nfunction compatibleDriversFor(engine: string): CompatibleDriver[] {\n  return compatPairs()\n    .filter((p) => p.engine === engine)\n    .map((p) => ({ name: p.driver, minVersion: p.minDriverVersion }))\n}\n\nfunction toDatabaseNode(config: DbConfig): DatabaseNode {\n  return {\n    id: databaseId(config.host),\n    type: NodeType.DatabaseNode,\n    name: config.database || config.host,\n    engine: config.engine,\n    engineVersion: config.engineVersion,\n    compatibleDrivers: compatibleDriversFor(config.engine),\n    host: config.host,\n    port: config.port,\n  }\n}\n\nexport function attachIncompatibilities(\n  service: DiscoveredService,\n  configs: DbConfig[],\n): void {\n  const deps = { ...(service.pkg.dependencies ?? {}), ...(service.pkg.devDependencies ?? {}) }\n  const incompatibilities: NonNullable<ServiceNode['incompatibilities']> = []\n  const seen = new Set<string>()\n\n  // 1. driver-engine — original behaviour. Per (db config, configured driver\n  // pair) check that the declared driver version meets the engine threshold.\n  for (const config of configs) {\n    for (const pair of compatPairs()) {\n      if (pair.engine !== config.engine) continue\n      const declaredVersion = cleanVersion(deps[pair.driver])\n      if (!declaredVersion) continue\n      const result = checkCompatibility(\n        pair.driver,\n        declaredVersion,\n        config.engine,\n        config.engineVersion,\n      )\n      if (!result.compatible && result.reason) {\n        const key = `driver-engine|${pair.driver}@${declaredVersion}|${config.engine}@${config.engineVersion}`\n        if (seen.has(key)) continue\n        seen.add(key)\n        incompatibilities.push({\n          kind: 'driver-engine',\n          driver: pair.driver,\n          driverVersion: declaredVersion,\n          engine: config.engine,\n          engineVersion: config.engineVersion,\n          reason: result.reason,\n        })\n      }\n    }\n  }\n\n  // 2. node-engine — service's `engines.node` vs each declared dep that has a\n  // matrix-recorded minimum.\n  const serviceNodeEngine = service.node.nodeEngine ?? service.pkg.engines?.node\n  for (const constraint of nodeEngineConstraints()) {\n    const declared = cleanVersion(deps[constraint.package])\n    if (!declared) continue\n    const result = checkNodeEngineConstraint(constraint, declared, serviceNodeEngine)\n    if (!result.compatible && result.reason) {\n      const key = `node-engine|${constraint.package}@${declared}|${serviceNodeEngine ?? ''}`\n      if (seen.has(key)) continue\n      seen.add(key)\n      incompatibilities.push({\n        kind: 'node-engine',\n        package: constraint.package,\n        packageVersion: declared,\n        requiredNodeVersion: result.requiredNodeVersion ?? constraint.minNodeVersion,\n        ...(serviceNodeEngine ? { declaredNodeEngine: serviceNodeEngine } : {}),\n        reason: result.reason,\n      })\n    }\n  }\n\n  // 3. package-conflict — pair like react-query 5+ requiring react 18+.\n  for (const conflict of packageConflicts()) {\n    const declared = cleanVersion(deps[conflict.package])\n    if (!declared) continue\n    const requiredVersion = cleanVersion(deps[conflict.requires.name])\n    const result = checkPackageConflict(conflict, declared, requiredVersion)\n    if (!result.compatible && result.reason) {\n      const key = `package-conflict|${conflict.package}@${declared}|${conflict.requires.name}@${requiredVersion ?? 'missing'}`\n      if (seen.has(key)) continue\n      seen.add(key)\n      incompatibilities.push({\n        kind: 'package-conflict',\n        package: conflict.package,\n        packageVersion: declared,\n        requires: conflict.requires,\n        ...(requiredVersion ? { foundVersion: requiredVersion } : {}),\n        reason: result.reason,\n      })\n    }\n  }\n\n  // 4. deprecated-api — flag presence of a known-deprecated package.\n  for (const rule of deprecatedApis()) {\n    const declared = cleanVersion(deps[rule.package])\n    if (declared === undefined) continue\n    const result = checkDeprecatedApi(rule, declared)\n    if (!result.compatible && result.reason) {\n      const key = `deprecated-api|${rule.package}@${declared}`\n      if (seen.has(key)) continue\n      seen.add(key)\n      incompatibilities.push({\n        kind: 'deprecated-api',\n        package: rule.package,\n        packageVersion: declared,\n        reason: result.reason,\n      })\n    }\n  }\n\n  if (incompatibilities.length > 0) service.node.incompatibilities = incompatibilities\n}\n\n// Phase 2 — for each service, run every parser and merge their DbConfigs by\n// host. Each unique host produces one DatabaseNode + CONNECTS_TO edge from the\n// service. The parser registry decides priority on tie; the demo's\n// db-config.yaml stays first so its `engineVersion: 15` continues to win.\nexport async function addDatabasesAndCompat(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n  scanPath: string,\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    const merged = new Map<string, DbConfig>()\n    for (const parser of DB_PARSERS) {\n      let configs: DbConfig[]\n      try {\n        configs = await parser.parse(service.dir)\n      } catch (err) {\n        console.warn(\n          `[neat] ${parser.name} parser failed on ${service.node.name}: ${(err as Error).message}`,\n        )\n        continue\n      }\n      for (const config of configs) {\n        if (!config.host) continue\n        if (!merged.has(config.host)) merged.set(config.host, config)\n      }\n    }\n\n    const allConfigs = [...merged.values()]\n    for (const config of allConfigs) {\n      const dbNode = toDatabaseNode(config)\n      if (!graph.hasNode(dbNode.id)) {\n        graph.addNode(dbNode.id, { ...dbNode, discoveredVia: 'static' })\n        nodesAdded++\n      } else {\n        // OTel ingest may have auto-created a minimal node at this id. Merge\n        // per ADR-033: static fields override OTel-derived fields, discoveredVia\n        // flips to 'merged' when both layers contributed.\n        const existing = graph.getNodeAttributes(dbNode.id) as DatabaseNode\n        const mergedDiscoveredVia: 'static' | 'otel' | 'merged' =\n          existing.discoveredVia === 'otel' ? 'merged' : 'static'\n        graph.replaceNodeAttributes(dbNode.id, {\n          ...existing,\n          ...dbNode,\n          discoveredVia: mergedDiscoveredVia,\n        })\n      }\n      // file-awareness §1 — the connection is declared in a config file; that\n      // file is the relationship origin. ensureFileNode creates the FileNode +\n      // CONTAINS edge so the CONNECTS_TO lands file-grained, not service-level.\n      const relConfigFile = toPosix(path.relative(service.dir, config.sourceFile))\n      const { fileNodeId, nodesAdded: fn, edgesAdded: fe } = ensureFileNode(\n        graph,\n        service.pkg.name,\n        service.node.id,\n        relConfigFile,\n      )\n      nodesAdded += fn\n      edgesAdded += fe\n      const evidenceFile = toPosix(path.relative(scanPath, config.sourceFile))\n      const edge: GraphEdge = {\n        id: makeEdgeId(fileNodeId, dbNode.id, EdgeType.CONNECTS_TO),\n        source: fileNodeId,\n        target: dbNode.id,\n        type: EdgeType.CONNECTS_TO,\n        provenance: Provenance.EXTRACTED,\n        confidence: confidenceForExtracted('structural'),\n        // Carry how the host was recovered (ADR-213) so the divergence ranker\n        // can tell a real declared store from a hardcoded fault-injection /\n        // flag-gated probe. Only set when the parser distinguished the two.\n        evidence: config.hostSource\n          ? { file: evidenceFile, hostSource: config.hostSource }\n          : { file: evidenceFile },\n      }\n      if (!graph.hasEdge(edge.id)) {\n        graph.addEdgeWithKey(edge.id, edge.source, edge.target, edge)\n        edgesAdded++\n      }\n    }\n\n    // Service-level declared DB target. When a service declares exactly one DB\n    // connection in config — a `postgres://…` string in .env, a db-config.yaml,\n    // a prisma/drizzle/knex datasource — record where it's pointed on the\n    // ServiceNode as `dbConnectionTarget` (host[:port]) and link the service to\n    // the config that declared it with an EXTRACTED CONFIGURED_BY edge. This is\n    // the service-grained declared intent the host-mismatch divergence compares\n    // against the service-grained OBSERVED CONNECTS_TO (file-awareness §7 —\n    // compare at the shared grain; a DB OTel span carries no call site, so the\n    // comparison is service-level). Without this, `declaredHostFor` reads an\n    // unpopulated field and host-mismatch never fires.\n    //\n    // We hold to a *single* declared target: with two or more distinct hosts\n    // the single-target model is ambiguous and would flag every observed host\n    // but one as a false mismatch, so we decline rather than guess.\n    if (allConfigs.length === 1) {\n      const primary = allConfigs[0]!\n      service.node.dbConnectionTarget = primary.port\n        ? `${primary.host}:${primary.port}`\n        : primary.host\n\n      // Link to the config file that declared the connection. Mirror configs.ts's\n      // ConfigNode id (Phase 3 runs after this and is idempotent on the node);\n      // the CONFIGURED_BY edge is service-grained here, matching the grain of\n      // the declared target it backs.\n      const relPath = path.relative(scanPath, primary.sourceFile)\n      const cfgId = configId(relPath)\n      if (!graph.hasNode(cfgId)) {\n        const cfgNode: ConfigNode = {\n          id: cfgId,\n          type: NodeType.ConfigNode,\n          name: path.basename(primary.sourceFile),\n          path: relPath,\n          fileType: isConfigFile(path.basename(primary.sourceFile)).fileType || 'config',\n        }\n        graph.addNode(cfgId, cfgNode)\n        nodesAdded++\n      }\n      const cfgEdge: GraphEdge = {\n        id: makeEdgeId(service.node.id, cfgId, EdgeType.CONFIGURED_BY),\n        source: service.node.id,\n        target: cfgId,\n        type: EdgeType.CONFIGURED_BY,\n        provenance: Provenance.EXTRACTED,\n        confidence: confidenceForExtracted('structural'),\n        evidence: { file: toPosix(relPath) },\n      }\n      if (!graph.hasEdge(cfgEdge.id)) {\n        graph.addEdgeWithKey(cfgEdge.id, cfgEdge.source, cfgEdge.target, cfgEdge)\n        edgesAdded++\n      }\n    }\n\n    // Run all kinds of incompat checks even for services with no db connection\n    // — node-engine / package-conflict / deprecated-api don't depend on db.\n    attachIncompatibilities(service, allConfigs)\n    if (graph.hasNode(service.node.id)) {\n      // Merge with whatever's on the node already (aliases from γ #75 land\n      // before this phase), so the writeback doesn't drop fields populated by\n      // earlier passes.\n      const current = graph.getNodeAttributes(service.node.id) as ServiceNode\n      const updated: ServiceNode = {\n        ...current,\n        ...(service.node as ServiceNode),\n        ...(current.aliases ? { aliases: current.aliases } : {}),\n      }\n      // attachIncompatibilities only sets the field when there's something to\n      // flag. On a re-extract (`neat watch`, `POST /graph/scan`), a stale\n      // entry on `current` would otherwise survive the spread and leave the\n      // graph reporting a problem the new manifest no longer has.\n      if (!service.node.incompatibilities || service.node.incompatibilities.length === 0) {\n        delete (updated as { incompatibilities?: unknown }).incompatibilities\n      }\n      // Same stale-survivor guard for the declared DB target: if this pass found\n      // no single declared connection, a value left on `current` from a prior\n      // extract would otherwise survive the spread.\n      if (!service.node.dbConnectionTarget) {\n        delete (updated as { dbConnectionTarget?: unknown }).dbConnectionTarget\n      }\n      graph.replaceNodeAttributes(service.node.id, updated as unknown as GraphNode)\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import path from 'node:path'\nimport { exists, readYaml } from '../shared.js'\nimport type { DbConfig } from './shared.js'\n\ninterface DbConfigYaml {\n  host: string\n  port?: number\n  database: string\n  engine: string\n  engineVersion?: string | number\n}\n\n// The original db-config.yaml format, kept as a parser so the demo continues\n// to work. Engine + version are explicit here, so this is the one source that\n// can produce a real engineVersion without inference.\nexport async function parse(serviceDir: string): Promise<DbConfig[]> {\n  const yamlPath = path.join(serviceDir, 'db-config.yaml')\n  if (!(await exists(yamlPath))) return []\n  const raw = await readYaml<DbConfigYaml>(yamlPath)\n  return [\n    {\n      host: raw.host,\n      port: raw.port,\n      database: raw.database,\n      engine: raw.engine,\n      engineVersion: raw.engineVersion !== undefined ? String(raw.engineVersion) : 'unknown',\n      sourceFile: yamlPath,\n    },\n  ]\n}\n\nexport const dbConfigYamlParser = { name: 'db-config.yaml', parse }\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { isConfigFile } from '../shared.js'\nimport { parseConnectionString, type DbConfig } from './shared.js'\n\n// Both the `_URL` and `_URI` spellings for every engine — apps split roughly\n// evenly between them and the two are interchangeable. `MONGODB_URL` in\n// particular is the single most common Mongo env-var name (the Mongoose docs\n// and most boilerplates use it), and its earlier absence meant an app's own\n// database connection went unextracted, so the runtime span had nothing to fuse\n// onto and minted a standalone `database:<host>` node instead (#832).\nconst CONNECTION_KEYS = new Set([\n  'DATABASE_URL',\n  'DATABASE_URI',\n  'DB_URL',\n  'DB_URI',\n  'POSTGRES_URL',\n  'POSTGRES_URI',\n  'POSTGRESQL_URL',\n  'POSTGRESQL_URI',\n  'MYSQL_URL',\n  'MYSQL_URI',\n  'MONGODB_URL',\n  'MONGODB_URI',\n  'MONGO_URL',\n  'MONGO_URI',\n  'REDIS_URL',\n  'REDIS_URI',\n])\n\n// Per ADR-016, .env contents do not land in any snapshot. We read them here\n// only to derive a transient DbConfig — the value never reaches a ConfigNode.\nfunction parseDotenvLine(line: string): { key: string; value: string } | null {\n  const trimmed = line.trim()\n  if (!trimmed || trimmed.startsWith('#')) return null\n  const eq = trimmed.indexOf('=')\n  if (eq < 0) return null\n  const key = trimmed.slice(0, eq).trim()\n  let value = trimmed.slice(eq + 1).trim()\n  if (\n    (value.startsWith('\"') && value.endsWith('\"')) ||\n    (value.startsWith(\"'\") && value.endsWith(\"'\"))\n  ) {\n    value = value.slice(1, -1)\n  }\n  return { key, value }\n}\n\nexport async function parse(serviceDir: string): Promise<DbConfig[]> {\n  const entries = await fs.readdir(serviceDir, { withFileTypes: true }).catch(() => [])\n  const configs: DbConfig[] = []\n  const seen = new Set<string>()\n\n  for (const entry of entries) {\n    if (!entry.isFile()) continue\n    const match = isConfigFile(entry.name)\n    if (!match.match || match.fileType !== 'env') continue\n\n    const filePath = path.join(serviceDir, entry.name)\n    const content = await fs.readFile(filePath, 'utf8')\n    for (const line of content.split('\\n')) {\n      const parsed = parseDotenvLine(line)\n      if (!parsed) continue\n      if (!CONNECTION_KEYS.has(parsed.key.toUpperCase())) continue\n      const config = parseConnectionString(parsed.value)\n      if (!config) continue\n      const key = `${config.engine}://${config.host}:${config.port ?? ''}/${config.database}`\n      if (seen.has(key)) continue\n      seen.add(key)\n      configs.push({ ...config, sourceFile: filePath })\n    }\n  }\n  return configs\n}\n\nexport const dotenvParser = { name: '.env', parse }\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\n\nexport interface DbConfig {\n  host: string\n  port?: number\n  database: string\n  engine: string\n  engineVersion: string // \"unknown\" when not statically determinable\n  // Absolute path to the file the parser read this config from. Required —\n  // ghost-edge cleanup keys CONNECTS_TO retirement on `evidence.file` per\n  // ADR-032 / #140. Parsers that synthesize a DbConfig from a partial\n  // source still set this to the file the partial came from.\n  sourceFile: string\n  // How the host was recovered (ADR-213): `config` when resolved from an env\n  // var / IConfiguration key / config file — the deployment's real target —\n  // and `literal` when read from a hardcoded string literal in source. Threaded\n  // onto the CONNECTS_TO edge's evidence so the divergence ranker can tell a\n  // real declared store from a hardcoded fault-injection / flag-gated probe.\n  // Optional — a parser that doesn't distinguish the two leaves it unset, and\n  // the ranker then treats the host as a normal declaration.\n  hostSource?: 'literal' | 'config'\n}\n\n// Map a connection-string scheme to the engine name our compat matrix uses.\n// Schemes like \"postgres+asyncpg\" are normalised by stripping the dialect\n// suffix; anything we don't recognise returns null so the parser can decline.\nexport function schemeToEngine(scheme: string): string | null {\n  const s = scheme.toLowerCase().split('+')[0]\n  switch (s) {\n    case 'postgres':\n    case 'postgresql':\n      return 'postgresql'\n    case 'mysql':\n    case 'mariadb':\n      return 'mysql'\n    case 'mongodb':\n    case 'mongodb+srv':\n      return 'mongodb'\n    case 'redis':\n    case 'rediss':\n      return 'redis'\n    case 'sqlite':\n      return 'sqlite'\n    default:\n      return null\n  }\n}\n\n// Returns the inner DbConfig fields without sourceFile — every caller spreads\n// the parser's own file path on top. Type makes that contract explicit.\nexport type ParsedConnectionConfig = Omit<DbConfig, 'sourceFile'>\n\nexport function parseConnectionString(url: string): ParsedConnectionConfig | null {\n  const m = url.match(\n    /^(?<scheme>[a-z][a-z+]*):\\/\\/(?:[^@/]+(?::[^@]*)?@)?(?<host>[^:/?]+)(?::(?<port>\\d+))?(?:\\/(?<db>[^?#]*))?/i,\n  )\n  if (!m || !m.groups) return null\n  const engine = schemeToEngine(m.groups.scheme!)\n  if (!engine) return null\n  return {\n    host: m.groups.host!,\n    port: m.groups.port ? Number(m.groups.port) : undefined,\n    database: m.groups.db ?? '',\n    engine,\n    engineVersion: 'unknown',\n  }\n}\n\nexport async function readIfExists(filePath: string): Promise<string | null> {\n  try {\n    return await fs.readFile(filePath, 'utf8')\n  } catch {\n    return null\n  }\n}\n\n// Resolve an env variable an ORM datasource references indirectly — Prisma's\n// `url = env(\"DATABASE_URL\")`, Drizzle/Knex reading `process.env.DATABASE_URL`\n// — from the service's `.env` files, so the parser can recover the real host\n// instead of falling back to a placeholder (ADR-141). Precedence follows the\n// dotenv convention: `.env.local` overrides `.env`, then any other `.env.*`.\n// Per ADR-016 the value is transient — it only derives the DatabaseNode host and\n// never lands in a ConfigNode or the snapshot.\nexport async function resolveEnvVar(serviceDir: string, name: string): Promise<string | null> {\n  const entries = await fs.readdir(serviceDir, { withFileTypes: true }).catch(() => [])\n  const envNames = entries\n    .filter((e) => e.isFile() && (e.name === '.env' || e.name.startsWith('.env.')))\n    .map((e) => e.name)\n  const rank = (n: string): number => (n === '.env.local' ? 0 : n === '.env' ? 1 : 2)\n  envNames.sort((a, b) => rank(a) - rank(b) || a.localeCompare(b))\n  for (const fileName of envNames) {\n    const content = await readIfExists(path.join(serviceDir, fileName))\n    if (!content) continue\n    for (const line of content.split('\\n')) {\n      const trimmed = line.trim()\n      if (!trimmed || trimmed.startsWith('#')) continue\n      const eq = trimmed.indexOf('=')\n      if (eq < 0) continue\n      if (trimmed.slice(0, eq).trim() !== name) continue\n      let value = trimmed.slice(eq + 1).trim()\n      if (\n        (value.startsWith('\"') && value.endsWith('\"')) ||\n        (value.startsWith(\"'\") && value.endsWith(\"'\"))\n      ) {\n        value = value.slice(1, -1)\n      }\n      return value || null\n    }\n  }\n  return null\n}\n\nexport async function findFirst(\n  serviceDir: string,\n  candidates: string[],\n): Promise<string | null> {\n  for (const rel of candidates) {\n    const abs = path.join(serviceDir, rel)\n    const content = await readIfExists(abs)\n    if (content !== null) return abs\n  }\n  return null\n}\n\n// Engine name from a docker-compose `image:` value like \"postgres:15-alpine\"\n// or \"mysql/mysql-server:8.0\". Returns the engine + version when both are\n// resolvable, or null if the image isn't one we recognise.\nexport function engineFromImage(\n  image: string,\n): { engine: string; engineVersion: string } | null {\n  const lower = image.toLowerCase()\n  const colon = lower.lastIndexOf(':')\n  const repo = colon >= 0 ? lower.slice(0, colon) : lower\n  const tag = colon >= 0 ? lower.slice(colon + 1) : 'latest'\n  const last = repo.split('/').pop() ?? repo\n  let engine: string | null = null\n  if (last.startsWith('postgres')) engine = 'postgresql'\n  else if (last.startsWith('mysql') || last.startsWith('mariadb')) engine = 'mysql'\n  else if (last.startsWith('mongo')) engine = 'mongodb'\n  else if (last.startsWith('redis')) engine = 'redis'\n  else if (last.startsWith('sqlite')) engine = 'sqlite'\n  if (!engine) return null\n  // Strip everything after the major version digit run; \"15-alpine\" -> \"15\".\n  const versionMatch = tag.match(/^(\\d+(?:\\.\\d+){0,2})/)\n  return {\n    engine,\n    engineVersion: versionMatch ? versionMatch[1]! : 'unknown',\n  }\n}\n","import path from 'node:path'\nimport {\n  readIfExists,\n  parseConnectionString,\n  resolveEnvVar,\n  schemeToEngine,\n  type DbConfig,\n} from './shared.js'\n\n// Prisma's schema file declares datasources of the form:\n//\n//   datasource db {\n//     provider = \"postgresql\"\n//     url      = env(\"DATABASE_URL\")\n//   }\n//\n// We match the provider directly. The url is almost always an env() indirection,\n// so we resolve the referenced variable from the service's .env to recover the\n// real host — that keys the DatabaseNode on the same host the dotenv parser\n// mints, so the two fuse to one declared node instead of a placeholder twin\n// (ADR-141). Only when the url is a literal, or the env var is absent, do we\n// fall back (literal parse, then a deterministic per-service placeholder).\nexport async function parse(serviceDir: string): Promise<DbConfig[]> {\n  const schemaPath = path.join(serviceDir, 'prisma', 'schema.prisma')\n  const content = await readIfExists(schemaPath)\n  if (!content) return []\n\n  const block = content.match(/datasource\\s+\\w+\\s*\\{([^}]*)\\}/s)\n  if (!block) return []\n  const body = block[1] ?? ''\n\n  const providerMatch = body.match(/provider\\s*=\\s*\"([^\"]+)\"/)\n  if (!providerMatch) return []\n  const engine = schemeToEngine(providerMatch[1]!)\n  if (!engine) return []\n\n  const urlMatch = body.match(/url\\s*=\\s*\"([^\"]+)\"/)\n  if (urlMatch) {\n    const config = parseConnectionString(urlMatch[1]!)\n    if (config) return [{ ...config, sourceFile: schemaPath }]\n  }\n\n  const envMatch = body.match(/url\\s*=\\s*env\\(\\s*\"([^\"]+)\"\\s*\\)/)\n  if (envMatch) {\n    const resolved = await resolveEnvVar(serviceDir, envMatch[1]!)\n    if (resolved) {\n      const config = parseConnectionString(resolved)\n      if (config) return [{ ...config, sourceFile: schemaPath }]\n    }\n  }\n\n  return [\n    {\n      host: `${engine}-prisma`,\n      database: '',\n      engine,\n      engineVersion: 'unknown',\n      sourceFile: schemaPath,\n    },\n  ]\n}\n\nexport const prismaParser = { name: 'prisma', parse }\n","import {\n  findFirst,\n  readIfExists,\n  parseConnectionString,\n  resolveEnvVar,\n  schemeToEngine,\n  type DbConfig,\n} from './shared.js'\n\nconst DIALECT_TO_ENGINE: Record<string, string> = {\n  postgresql: 'postgresql',\n  postgres: 'postgresql',\n  pg: 'postgresql',\n  mysql: 'mysql',\n  mysql2: 'mysql',\n  sqlite: 'sqlite',\n  'better-sqlite': 'sqlite',\n}\n\n// Drizzle's drizzle.config.{ts,js,mjs} declares a `dialect` plus credentials.\n// We can't safely eval the file, but the relevant bits are simple key/value\n// expressions — regex-extracted to stay sandbox-clean and dep-free.\nexport async function parse(serviceDir: string): Promise<DbConfig[]> {\n  const filePath = await findFirst(serviceDir, [\n    'drizzle.config.ts',\n    'drizzle.config.js',\n    'drizzle.config.mjs',\n  ])\n  if (!filePath) return []\n  const content = await readIfExists(filePath)\n  if (!content) return []\n\n  const dialectMatch = content.match(/dialect\\s*:\\s*['\"`]([^'\"`]+)['\"`]/)\n  if (!dialectMatch) return []\n  const engine =\n    DIALECT_TO_ENGINE[dialectMatch[1]!.toLowerCase()] ?? schemeToEngine(dialectMatch[1]!)\n  if (!engine) return []\n\n  const urlMatch = content.match(\n    /(?:url|connectionString)\\s*:\\s*['\"`]([a-z][a-z+]*:\\/\\/[^'\"`]+)['\"`]/i,\n  )\n  if (urlMatch) {\n    const config = parseConnectionString(urlMatch[1]!)\n    if (config) return [{ ...config, sourceFile: filePath }]\n  }\n  // `url: process.env.DATABASE_URL` (or `connectionString:`, bracket form) — the\n  // common env-driven shape. Resolve it from the service's .env so the node keys\n  // on the real host and dedups with the dotenv parser instead of a placeholder\n  // (ADR-141, #807).\n  const urlEnvMatch = content.match(\n    /(?:url|connectionString)\\s*:\\s*process\\.env(?:\\.([A-Za-z_$][\\w$]*)|\\[\\s*['\"]([^'\"]+)['\"]\\s*\\])/,\n  )\n  if (urlEnvMatch) {\n    const varName = urlEnvMatch[1] ?? urlEnvMatch[2]\n    const resolved = varName ? await resolveEnvVar(serviceDir, varName) : null\n    const config = resolved ? parseConnectionString(resolved) : null\n    if (config) return [{ ...config, sourceFile: filePath }]\n  }\n  const hostMatch = content.match(/host\\s*:\\s*['\"`]([^'\"`]+)['\"`]/)\n  if (hostMatch) {\n    const portMatch = content.match(/port\\s*:\\s*(\\d+)/)\n    const dbMatch = content.match(/database\\s*:\\s*['\"`]([^'\"`]+)['\"`]/)\n    return [\n      {\n        host: hostMatch[1]!,\n        port: portMatch ? Number(portMatch[1]) : undefined,\n        database: dbMatch?.[1] ?? '',\n        engine,\n        engineVersion: 'unknown',\n        sourceFile: filePath,\n      },\n    ]\n  }\n  return [\n    { host: `${engine}-drizzle`, database: '', engine, engineVersion: 'unknown', sourceFile: filePath },\n  ]\n}\n\nexport const drizzleParser = { name: 'drizzle', parse }\n","import {\n  findFirst,\n  readIfExists,\n  parseConnectionString,\n  resolveEnvVar,\n  type DbConfig,\n} from './shared.js'\n\nconst CLIENT_TO_ENGINE: Record<string, string> = {\n  pg: 'postgresql',\n  postgres: 'postgresql',\n  postgresql: 'postgresql',\n  mysql: 'mysql',\n  mysql2: 'mysql',\n  sqlite3: 'sqlite',\n  'better-sqlite3': 'sqlite',\n}\n\n// knexfile.{js,ts} declares a client (one of pg/mysql/sqlite/...) plus a\n// connection string or host/port object. We pick whichever shape is in the\n// file and ignore environment-driven values we can't resolve statically.\nexport async function parse(serviceDir: string): Promise<DbConfig[]> {\n  const filePath = await findFirst(serviceDir, [\n    'knexfile.js',\n    'knexfile.ts',\n    'knexfile.cjs',\n    'knexfile.mjs',\n  ])\n  if (!filePath) return []\n  const content = await readIfExists(filePath)\n  if (!content) return []\n\n  const clientMatch = content.match(/client\\s*:\\s*['\"`]([^'\"`]+)['\"`]/)\n  if (!clientMatch) return []\n  const engine = CLIENT_TO_ENGINE[clientMatch[1]!.toLowerCase()]\n  if (!engine) return []\n\n  const urlMatch = content.match(\n    /connection\\s*:\\s*['\"`]([a-z][a-z+]*:\\/\\/[^'\"`]+)['\"`]/i,\n  )\n  if (urlMatch) {\n    const config = parseConnectionString(urlMatch[1]!)\n    if (config) return [{ ...config, sourceFile: filePath }]\n  }\n\n  // `connection: process.env.DATABASE_URL` (bracket form too) — the whole\n  // connection is a URL from env. Resolve it from the service's .env so the node\n  // keys on the real host and dedups instead of a placeholder (ADR-141, #807).\n  // `connection: { host: process.env.DB_HOST }` deliberately does not match — an\n  // object of env fields keeps the placeholder rather than a fabricated URL.\n  const urlEnvMatch = content.match(\n    /connection\\s*:\\s*process\\.env(?:\\.([A-Za-z_$][\\w$]*)|\\[\\s*['\"]([^'\"]+)['\"]\\s*\\])/,\n  )\n  if (urlEnvMatch) {\n    const varName = urlEnvMatch[1] ?? urlEnvMatch[2]\n    const resolved = varName ? await resolveEnvVar(serviceDir, varName) : null\n    const config = resolved ? parseConnectionString(resolved) : null\n    if (config) return [{ ...config, sourceFile: filePath }]\n  }\n\n  const host = content.match(/host\\s*:\\s*['\"`]([^'\"`]+)['\"`]/)?.[1]\n  if (host) {\n    const port = content.match(/port\\s*:\\s*(\\d+)/)?.[1]\n    const database = content.match(/database\\s*:\\s*['\"`]([^'\"`]+)['\"`]/)?.[1] ?? ''\n    return [\n      {\n        host,\n        port: port ? Number(port) : undefined,\n        database,\n        engine,\n        engineVersion: 'unknown',\n        sourceFile: filePath,\n      },\n    ]\n  }\n\n  return [{ host: `${engine}-knex`, database: '', engine, engineVersion: 'unknown', sourceFile: filePath }]\n}\n\nexport const knexParser = { name: 'knex', parse }\n","import path from 'node:path'\nimport { exists, readJson, readYaml } from '../shared.js'\nimport { schemeToEngine, type DbConfig } from './shared.js'\n\ninterface OrmConfigEntry {\n  type?: string\n  host?: string\n  port?: number\n  database?: string\n}\n\n// ormconfig.{json,yaml,yml} — TypeORM's legacy config file. Single object or\n// an array of named connections; we walk both.\nexport async function parse(serviceDir: string): Promise<DbConfig[]> {\n  for (const candidate of ['ormconfig.json', 'ormconfig.yaml', 'ormconfig.yml']) {\n    const abs = path.join(serviceDir, candidate)\n    if (!(await exists(abs))) continue\n    const raw = candidate.endsWith('.json')\n      ? await readJson<OrmConfigEntry | OrmConfigEntry[]>(abs)\n      : await readYaml<OrmConfigEntry | OrmConfigEntry[]>(abs)\n    const entries = Array.isArray(raw) ? raw : [raw]\n\n    const out: DbConfig[] = []\n    for (const entry of entries) {\n      if (!entry?.type || !entry.host) continue\n      const engine = schemeToEngine(entry.type)\n      if (!engine) continue\n      out.push({\n        host: entry.host,\n        port: entry.port,\n        database: entry.database ?? '',\n        engine,\n        engineVersion: 'unknown',\n        sourceFile: abs,\n      })\n    }\n    if (out.length > 0) return out\n  }\n  return []\n}\n\nexport const ormconfigParser = { name: 'ormconfig', parse }\n","import { findFirst, readIfExists, schemeToEngine, type DbConfig } from './shared.js'\n\n// TypeORM's modern shape: `new DataSource({ type: 'postgres', host, port, ... })`\n// in a data-source.ts (or .js). We regex for the type/host/port/database keys\n// in the first DataSource literal we find.\nexport async function parse(serviceDir: string): Promise<DbConfig[]> {\n  const filePath = await findFirst(serviceDir, [\n    'data-source.ts',\n    'data-source.js',\n    'src/data-source.ts',\n    'src/data-source.js',\n  ])\n  if (!filePath) return []\n  const content = await readIfExists(filePath)\n  if (!content) return []\n\n  const block = content.match(/new\\s+DataSource\\s*\\(\\s*\\{([\\s\\S]*?)\\}\\s*\\)/)\n  const body = block ? block[1]! : content\n\n  const typeMatch = body.match(/type\\s*:\\s*['\"`]([^'\"`]+)['\"`]/)\n  const host = body.match(/host\\s*:\\s*['\"`]([^'\"`]+)['\"`]/)?.[1]\n  if (!typeMatch || !host) return []\n\n  const engine = schemeToEngine(typeMatch[1]!)\n  if (!engine) return []\n\n  const port = body.match(/port\\s*:\\s*(\\d+)/)?.[1]\n  const database = body.match(/database\\s*:\\s*['\"`]([^'\"`]+)['\"`]/)?.[1] ?? ''\n\n  return [\n    {\n      host,\n      port: port ? Number(port) : undefined,\n      database,\n      engine,\n      engineVersion: 'unknown',\n      sourceFile: filePath,\n    },\n  ]\n}\n\nexport const typeormParser = { name: 'typeorm', parse }\n","import path from 'node:path'\nimport { exists, readJson } from '../shared.js'\nimport { schemeToEngine, type DbConfig } from './shared.js'\n\ninterface SequelizeConfigEntry {\n  dialect?: string\n  host?: string\n  port?: number\n  database?: string\n}\n\ntype SequelizeConfig = Record<string, SequelizeConfigEntry>\n\n// Sequelize stores per-environment configs under config/config.json. We read\n// every named environment so a service that declares production + staging\n// surfaces both DB targets.\nexport async function parse(serviceDir: string): Promise<DbConfig[]> {\n  const configPath = path.join(serviceDir, 'config', 'config.json')\n  if (!(await exists(configPath))) return []\n  const raw = await readJson<SequelizeConfig>(configPath)\n\n  const out: DbConfig[] = []\n  const seen = new Set<string>()\n  for (const entry of Object.values(raw)) {\n    if (!entry?.dialect || !entry.host) continue\n    const engine = schemeToEngine(entry.dialect)\n    if (!engine) continue\n    const key = `${engine}://${entry.host}:${entry.port ?? ''}/${entry.database ?? ''}`\n    if (seen.has(key)) continue\n    seen.add(key)\n    out.push({\n      host: entry.host,\n      port: entry.port,\n      database: entry.database ?? '',\n      engine,\n      engineVersion: 'unknown',\n      sourceFile: configPath,\n    })\n  }\n  return out\n}\n\nexport const sequelizeParser = { name: 'sequelize', parse }\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { maskCommentsInSource } from '../shared.js'\nimport { walkSourceFiles } from '../calls/shared.js'\nimport {\n  parseConnectionString,\n  resolveEnvVar,\n  type DbConfig,\n  type ParsedConnectionConfig,\n} from './shared.js'\n\n// C# datastore clients (ADR-205; id scheme refined by ADR-207) — the connection axis of C#/.NET, the sibling\n// of prisma.ts / drizzle.ts here and of calls/efcore.ts (the table axis). Two\n// client shapes, both producing a `DatabaseNode` keyed on the resolved peer host\n// so the EXTRACTED twin lands on the same `database:<host>` id an OBSERVED\n// CONNECTS_TO span already minted (ingest keys a db span on server.address /\n// net.peer.name via `databaseId`, ingest.ts) — the whole point being that the\n// two layers fuse instead of twinning:\n//\n//   1. EF Core / Npgsql -> Postgres. A `DbContext.OnConfiguring` (or a DI\n//      `AddDbContext`/`AddNpgsql*`) calls `UseNpgsql(<conn>)`. The connection is\n//      an ADO.NET keyword string — `Host=postgresql;Username=...;Database=otel`\n//      — either a literal or read from an env var / `IConfiguration` key, so the\n//      host is recovered by parsing the `Host=` keyword (resolving the env var\n//      from the service's `.env`, walking up to the repo root, when it's\n//      indirected — the otel-demo puts `DB_CONNECTION_STRING` and `VALKEY_ADDR`\n//      in a root `.env`/compose, above each service dir).\n//\n//   2. StackExchange.Redis -> Redis/Valkey. `ConnectionMultiplexer.Connect(...)`\n//      / `ConfigurationOptions.Parse(\"host:port,opts\")` names the endpoint; the\n//      host is the token before the first `:` / `,`. Valkey is Redis-wire\n//      compatible, so `db.system` is `redis` and the store keys on its own host\n//      (`valkey-cart`) exactly like any Redis peer — engine `redis`.\n//\n// Precision & identity (ADR-207): a config is emitted only when a real client\n// call is present AND a host resolves to a plain string (no unresolved `${VAR}`\n// left in it). The `DatabaseNode` is keyed on that resolved host ALONE — the\n// engine (`postgres`/`redis`) is a node ATTRIBUTE, never part of the id — so the\n// id equals the `database:<host>` an OBSERVED span already minted from\n// `server.address` (no `-npgsql`/`-stackexchange` driver suffix, which would key\n// the twin off the observed peer and never fuse). Every genuinely declared host\n// is extracted, config-driven addresses first: the otel-demo cart declares both\n// the `VALKEY_ADDR` peer (`valkey-cart`, which fuses) AND a hardcoded\n// `\"badhost:1234\"` fault-probe store, so both mint — `badhost` is a real declared\n// connection that simply has no OBSERVED twin (an honest divergence), not a\n// phantom to drop. What is NEVER minted is a fabricated placeholder host for a\n// client whose connection can't be resolved at all: a made-up host looks fusable\n// but isn't, so an unresolvable connection is left as an honest gap. Comment\n// bodies are masked before scanning so a connection string inside a `//` / `/* */`\n// comment never mints a node (the ADR-065 #2 discipline the regex extractors\n// share).\n\nconst CS_EXT = '.cs'\n\n// Cheap per-file gates — skip a `.cs` file that names neither client before the\n// heavier scan runs, the import-gate discipline the data-axis readers follow.\nconst NPGSQL_GATE = /\\bUseNpgsql\\b|\\bNpgsql\\b/\nconst REDIS_GATE = /\\bConnectionMultiplexer\\b|\\bStackExchange\\.Redis\\b|\\bConfigurationOptions\\.Parse\\b|\\bAddStackExchangeRedisCache\\b/\n\n// An `IConfiguration` / environment read that yields a connection string:\n//   Environment.GetEnvironmentVariable(\"NAME\")\n//   Configuration[\"NAME\"] / builder.Configuration[\"NAME\"]\n//   Configuration.GetConnectionString(\"NAME\")\nconst ENV_READ_RE =\n  /(?:GetEnvironmentVariable|GetConnectionString)\\(\\s*\"([^\"]+)\"\\s*\\)|Configuration\\s*\\[\\s*\"([^\"]+)\"\\s*\\]/g\n\n// A double-quoted string literal (C# `\"...\"` or verbatim `@\"...\"`; interpolated\n// `$\"...\"` is skipped by the caller since its host is a runtime value).\nconst STRING_LITERAL_RE = /@?\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"/g\n\n// A host token still carrying an interpolation hole (`${VAR}`, `$(cmd)`, a C#\n// `{expr}`, or a bare `$`) never resolved to a real peer — reject it so a\n// runtime-computed host falls through to the placeholder instead of minting a\n// node id with braces in it.\nfunction hostIsUnresolved(host: string): boolean {\n  return host === '' || /[${}]/.test(host)\n}\n\n// Does a string look like a Postgres keyword / URL connection string?\nfunction looksLikePostgres(s: string): boolean {\n  return /(?:^|;)\\s*(?:host|server|data\\s*source)\\s*=/i.test(s) || /^postgres(?:ql)?:\\/\\//i.test(s)\n}\n\n// Does a string look like a StackExchange.Redis endpoint? A bare word is too\n// ambiguous (any string literal in the file would match) — require a `host:port`\n// pair, a redis option token (`,ssl=`, `,abortConnect=`, …), or a `redis://` URL,\n// so a log message or a schema name is never mistaken for a Redis host.\nfunction looksLikeRedis(s: string): boolean {\n  return (\n    /^rediss?:\\/\\//i.test(s) ||\n    /^[A-Za-z0-9_.-]+:\\d+(?:$|,)/.test(s) ||\n    /,\\s*(?:ssl|abortconnect|allowadmin|connecttimeout|password|user)\\s*=/i.test(s)\n  )\n}\n\n// Host / port / database out of an ADO.NET keyword connection string\n// (`Host=postgresql;Port=5432;Database=otel;Username=...`) or a `postgres://` URL.\n// Case-insensitive keys, first host of a comma-separated multi-host list, null\n// when no host key is present or the host is still an unresolved `${VAR}`.\nfunction parsePostgresConnection(raw: string): ParsedConnectionConfig | null {\n  const s = raw.trim()\n  if (/^postgres(?:ql)?:\\/\\//i.test(s)) return parseConnectionString(s)\n\n  const fields = new Map<string, string>()\n  for (const part of s.split(';')) {\n    const eq = part.indexOf('=')\n    if (eq < 0) continue\n    const key = part.slice(0, eq).trim().toLowerCase().replace(/\\s+/g, ' ')\n    const value = part.slice(eq + 1).trim()\n    if (value && !fields.has(key)) fields.set(key, value)\n  }\n  const hostRaw = fields.get('host') ?? fields.get('server') ?? fields.get('data source')\n  if (!hostRaw) return null\n  const host = hostRaw.split(',')[0]!.trim()\n  if (hostIsUnresolved(host)) return null\n  const portRaw = fields.get('port')\n  const port = portRaw && /^\\d+$/.test(portRaw) ? Number(portRaw) : undefined\n  const database = fields.get('database') ?? fields.get('db') ?? ''\n  return { host, port, database, engine: 'postgresql', engineVersion: 'unknown' }\n}\n\n// Host / port out of a StackExchange.Redis endpoint string\n// (`valkey-cart:6379,ssl=false,abortConnect=false`) or a `redis://` URL. The\n// endpoint is the first comma-separated token; the host is the part before the\n// last `:` (an option token like `ssl=false` has no bare host shape and is\n// rejected). Null when the leading token is not a host[:port].\nfunction parseRedisEndpoint(raw: string): ParsedConnectionConfig | null {\n  const s = raw.trim()\n  if (/^rediss?:\\/\\//i.test(s)) return parseConnectionString(s)\n\n  const first = s.split(',')[0]!.trim()\n  const m = first.match(/^([A-Za-z0-9_.-]+)(?::(\\d+))?$/)\n  if (!m) return null\n  const host = m[1]!\n  if (hostIsUnresolved(host) || host.includes('=')) return null\n  const port = m[2] ? Number(m[2]) : undefined\n  return { host, port, database: '', engine: 'redis', engineVersion: 'unknown' }\n}\n\n// Resolve an env var / IConfiguration key the way .NET layers configuration:\n// the value most often lives in a `.env` at the repo root, ABOVE the service\n// dir (the otel-demo keeps `DB_CONNECTION_STRING` / `VALKEY_ADDR` there), so this\n// walks up from the service dir checking each level's `.env*` (via the shared\n// dotenv reader) and stops at the repo root — a directory holding `.git`. Bounded\n// so a detached service dir can't walk the whole filesystem.\nasync function resolveEnvUpTree(startDir: string, name: string): Promise<string | null> {\n  let dir = path.resolve(startDir)\n  for (let depth = 0; depth < 12; depth++) {\n    const value = await resolveEnvVar(dir, name)\n    if (value !== null) return value\n    const atRepoRoot = await fs\n      .access(path.join(dir, '.git'))\n      .then(() => true)\n      .catch(() => false)\n    const parent = path.dirname(dir)\n    if (atRepoRoot || parent === dir) break\n    dir = parent\n  }\n  return null\n}\n\n// Replace `${VAR}` / `$VAR` references in an env value with their own resolved\n// values (one pass), so `Host=${POSTGRES_HOST}` recovers the real host when the\n// referenced var is declared in a reachable `.env`. An unresolved reference is\n// left verbatim; a host that still carries `${` is treated as unresolved by the\n// parsers above and falls back to the placeholder.\nasync function interpolateEnvRefs(value: string, dir: string): Promise<string> {\n  const refs = new Set<string>()\n  for (const m of value.matchAll(/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}|\\$([A-Za-z_][A-Za-z0-9_]*)/g)) {\n    refs.add(m[1] ?? m[2]!)\n  }\n  let out = value\n  for (const name of refs) {\n    const resolved = await resolveEnvUpTree(dir, name)\n    if (resolved === null) continue\n    out = out\n      .split(`\\${${name}}`)\n      .join(resolved)\n      .replace(new RegExp(`\\\\$${name}\\\\b`, 'g'), resolved)\n  }\n  return out\n}\n\n// Every double-quoted string literal in the (comment-masked) source.\nfunction stringLiterals(masked: string): string[] {\n  const out: string[] = []\n  STRING_LITERAL_RE.lastIndex = 0\n  let m: RegExpExecArray | null\n  while ((m = STRING_LITERAL_RE.exec(masked)) !== null) out.push(m[1]!)\n  return out\n}\n\n// Every env-var / config key referenced in the (comment-masked) source.\nfunction envKeys(masked: string): string[] {\n  const out: string[] = []\n  ENV_READ_RE.lastIndex = 0\n  let m: RegExpExecArray | null\n  while ((m = ENV_READ_RE.exec(masked)) !== null) {\n    const key = m[1] ?? m[2]\n    if (key) out.push(key)\n  }\n  return out\n}\n\n// Resolve EVERY host a client declares in the service — a service can genuinely\n// name more than one peer of an engine, and each real declaration is extracted\n// rather than one silently winning. The otel-demo cart is the shape: it connects\n// to the config-driven `VALKEY_ADDR` (`valkey-cart`) AND constructs a second store\n// against a hardcoded `\"badhost:1234\"` fault-probe, so both are declared and both\n// mint — `valkey-cart` fuses with the OBSERVED peer, `badhost` stands as a\n// declared-but-unobserved connection (the honest divergence, not a node to drop).\n// Config/env-referenced hosts are listed first (the deployment's real target),\n// then matching literals. A host is only skipped when it doesn't parse to a plain\n// string; a caller that gets an empty array mints no node (no fabricated\n// placeholder). De-dup by `engine:host` is the caller's job (`push`).\nasync function resolveConfigs(\n  literals: string[],\n  keys: string[],\n  serviceDir: string,\n  looksLike: (s: string) => boolean,\n  parse: (s: string) => ParsedConnectionConfig | null,\n): Promise<ParsedConnectionConfig[]> {\n  const out: ParsedConnectionConfig[] = []\n  for (const key of keys) {\n    const raw = await resolveEnvUpTree(serviceDir, key)\n    if (raw === null) continue\n    const value = await interpolateEnvRefs(raw, serviceDir)\n    if (!looksLike(value)) continue\n    const parsed = parse(value)\n    // An env var / IConfiguration key is the deployment's real target — mark it\n    // `config` so the divergence ranker never mistakes it for a dead-code probe\n    // (ADR-213).\n    if (parsed) out.push({ ...parsed, hostSource: 'config' })\n  }\n  for (const lit of literals) {\n    if (!looksLike(lit)) continue\n    const parsed = parse(lit)\n    // A hardcoded string literal — mark it `literal`. The cart's `\"badhost:1234\"`\n    // fault-probe lands here; the ranker dampens its missing-observed when it has\n    // never been observed and a config-driven store of the same engine has\n    // (ADR-213).\n    if (parsed) out.push({ ...parsed, hostSource: 'literal' })\n  }\n  return out\n}\n\n// The connection string and the client call can live in different files — cart\n// reads `VALKEY_ADDR` in Program.cs but calls `ConnectionMultiplexer.Connect` in\n// cartstore/ValkeyCartStore.cs — so scanning is service-wide: literals and config\n// keys are pooled across every `.cs` file, and the file holding the client call is\n// remembered as the connection's origin (the CONNECTS_TO source, ADR-205). The\n// shape gates (`looksLikePostgres` / `looksLikeRedis`) keep the two engines'\n// pools disjoint even though they share one literal/key pool.\nexport async function parse(serviceDir: string): Promise<DbConfig[]> {\n  const files = (await walkSourceFiles(serviceDir).catch(() => [])).filter(\n    (f) => path.extname(f) === CS_EXT,\n  )\n  if (files.length === 0) return []\n\n  const sources: Array<{ file: string; content: string }> = []\n  for (const file of files) {\n    const content = await fs.readFile(file, 'utf8').catch(() => null)\n    if (content !== null) sources.push({ file, content })\n  }\n\n  // First locate the client calls; the file holding one is the connection origin.\n  let pgGateFile: string | null = null\n  let redisGateFile: string | null = null\n  for (const { file, content } of sources) {\n    if (pgGateFile === null && NPGSQL_GATE.test(content)) pgGateFile = file\n    if (redisGateFile === null && REDIS_GATE.test(content)) redisGateFile = file\n  }\n  if (!pgGateFile && !redisGateFile) return []\n\n  // Pool literals and config keys from EVERY `.cs` file, not only the ones holding\n  // the client call — the connection string / address is often read in a different\n  // file (cart reads `VALKEY_ADDR` in Program.cs, connects in the store). The shape\n  // gates keep the two engines' pools disjoint despite the shared pool.\n  const literals: string[] = []\n  const keys: string[] = []\n  for (const { content } of sources) {\n    const masked = maskCommentsInSource(content)\n    literals.push(...stringLiterals(masked))\n    keys.push(...envKeys(masked))\n  }\n\n  const out: DbConfig[] = []\n  const seenHosts = new Set<string>()\n  const push = (config: ParsedConnectionConfig, sourceFile: string): void => {\n    const dedupe = `${config.engine}:${config.host}`\n    if (seenHosts.has(dedupe)) return\n    seenHosts.add(dedupe)\n    out.push({ ...config, sourceFile })\n  }\n\n  // Every genuinely declared host mints a node; a host that can't be resolved to a\n  // real peer mints nothing. The key discipline (ADR-207): never fabricate a\n  // placeholder host — a made-up `database:<host>` shares the shape an OBSERVED span\n  // carries but never fuses, so an unresolvable connection is an honest gap, not a\n  // twin. A host that IS declared but simply doesn't fuse is still real and is kept\n  // (the cart's `badhost:1234` fault-probe stands as a declared-but-unobserved edge).\n  if (pgGateFile) {\n    for (const pg of await resolveConfigs(literals, keys, serviceDir, looksLikePostgres, parsePostgresConnection)) {\n      push(pg, pgGateFile)\n    }\n  }\n\n  if (redisGateFile) {\n    for (const redis of await resolveConfigs(literals, keys, serviceDir, looksLikeRedis, parseRedisEndpoint)) {\n      push(redis, redisGateFile)\n    }\n  }\n\n  return out\n}\n\nexport const csharpParser = { name: 'csharp', parse }\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { parseAllDocuments } from 'yaml'\nimport { parseConnectionString, resolveEnvVar, type DbConfig } from './shared.js'\n\n// Spring Boot datasources — the connection axis of Java, the sibling of\n// csharp.ts here and of calls/jpa.ts (the table axis). A Spring service names\n// its store in `application.yml` / `application.properties`:\n//\n//   spring:\n//     datasource:\n//       url: jdbc:mysql://${ORDER_MYSQL_HOST:ts-order-mysql}:${ORDER_MYSQL_PORT:3306}/ts\n//\n// The keys read are `spring.datasource.url` and `spring.r2dbc.url` (a JDBC /\n// R2DBC URL, whose `jdbc:` / `r2dbc:` prefix is dropped before the usual\n// connection-string parse) and `spring.data.mongodb.uri`. A `${NAME:default}`\n// placeholder resolves from the service's `.env` when it sets NAME, else to its\n// default — the value the app runs with when the deployment sets nothing. A\n// placeholder with neither leaves the URL unresolved, and nothing is minted.\n//\n// Only the default profile is read: a document activated by a profile\n// (`spring.config.activate.on-profile`, or the older `spring.profiles`) says\n// where the app points under that profile, not by default.\n\nconst CONFIG_FILES = ['application.yml', 'application.yaml', 'application.properties']\nconst URL_KEYS = ['spring.datasource.url', 'spring.r2dbc.url', 'spring.data.mongodb.uri']\n\n// A key from a YAML document, nested (`spring: datasource: url:`) or written\n// flat (`spring.datasource.url:`), or any mix of the two.\nfunction yamlValue(doc: unknown, key: string): unknown {\n  if (!doc || typeof doc !== 'object') return undefined\n  const obj = doc as Record<string, unknown>\n  if (key in obj) return obj[key]\n  const parts = key.split('.')\n  for (let i = 1; i < parts.length; i++) {\n    const head = parts.slice(0, i).join('.')\n    if (head in obj) {\n      const v = yamlValue(obj[head], parts.slice(i).join('.'))\n      if (v !== undefined) return v\n    }\n  }\n  return undefined\n}\n\nfunction isProfileDocument(doc: unknown): boolean {\n  return (\n    yamlValue(doc, 'spring.config.activate.on-profile') !== undefined ||\n    yamlValue(doc, 'spring.profiles') !== undefined\n  )\n}\n\nfunction urlsFromYaml(text: string): string[] {\n  const out: string[] = []\n  for (const d of parseAllDocuments(text)) {\n    if (d.errors.length > 0) continue\n    const doc = d.toJS() as unknown\n    if (isProfileDocument(doc)) continue\n    for (const key of URL_KEYS) {\n      const v = yamlValue(doc, key)\n      if (typeof v === 'string' && v.trim()) out.push(v.trim())\n    }\n  }\n  return out\n}\n\nfunction urlsFromProperties(text: string): string[] {\n  const out: string[] = []\n  for (const raw of text.split('\\n')) {\n    const line = raw.trim()\n    if (!line || line.startsWith('#') || line.startsWith('!')) continue\n    const m = /^([^=:\\s]+)\\s*[=:]\\s*(.*)$/.exec(line)\n    if (m && URL_KEYS.includes(m[1]!) && m[2]!.trim()) out.push(m[2]!.trim())\n  }\n  return out\n}\n\n// `${NAME:default}` / `${NAME}` → the .env value, else the default; null when a\n// placeholder has neither.\nasync function resolvePlaceholders(serviceDir: string, value: string): Promise<string | null> {\n  let out = ''\n  let last = 0\n  const re = /\\$\\{([^}:]+)(?::([^}]*))?\\}/g\n  let m: RegExpExecArray | null\n  while ((m = re.exec(value)) !== null) {\n    out += value.slice(last, m.index)\n    const fromEnv = await resolveEnvVar(serviceDir, m[1]!)\n    const resolved = fromEnv ?? m[2]\n    if (resolved === undefined) return null\n    out += resolved\n    last = m.index + m[0].length\n  }\n  return out + value.slice(last)\n}\n\nexport async function parse(serviceDir: string): Promise<DbConfig[]> {\n  const out: DbConfig[] = []\n  for (const dir of [path.join(serviceDir, 'src', 'main', 'resources'), serviceDir]) {\n    for (const name of CONFIG_FILES) {\n      const file = path.join(dir, name)\n      const text = await fs.readFile(file, 'utf8').catch(() => null)\n      if (text === null) continue\n      // A malformed config file yields nothing rather than failing the pass (ADR-055).\n      try {\n        const urls = name.endsWith('.properties') ? urlsFromProperties(text) : urlsFromYaml(text)\n        for (const raw of urls) {\n          const resolved = await resolvePlaceholders(serviceDir, raw)\n          if (!resolved) continue\n          const parsed = parseConnectionString(resolved.replace(/^(?:jdbc|r2dbc):/i, ''))\n          if (!parsed || !parsed.host) continue\n          out.push({ ...parsed, sourceFile: file, hostSource: 'config' })\n        }\n      } catch {\n        continue\n      }\n    }\n  }\n  return out\n}\n\nexport const springDatasourceParser = { name: 'spring-datasource', parse }\n","import path from 'node:path'\nimport { exists, readYaml } from '../shared.js'\nimport { engineFromImage, type DbConfig } from './shared.js'\n\ninterface ComposeService {\n  image?: string\n  ports?: (string | number)[]\n  environment?: Record<string, string> | string[]\n}\n\ninterface ComposeFile {\n  services?: Record<string, ComposeService>\n}\n\nfunction portFromService(svc: ComposeService): number | undefined {\n  for (const raw of svc.ports ?? []) {\n    const str = String(raw)\n    // \"5432:5432\", \"5432\", or \"host:5432\" → take the trailing port.\n    const last = str.split(':').pop()\n    const n = Number(last)\n    if (Number.isFinite(n) && n > 0) return n\n  }\n  return undefined\n}\n\nfunction databaseFromEnv(svc: ComposeService): string {\n  const env = svc.environment\n  const get = (key: string): string | undefined => {\n    if (!env) return undefined\n    if (Array.isArray(env)) {\n      for (const line of env) {\n        const [k, v] = line.split('=')\n        if (k === key) return v\n      }\n      return undefined\n    }\n    return env[key]\n  }\n  return get('POSTGRES_DB') ?? get('MYSQL_DATABASE') ?? get('MONGO_INITDB_DATABASE') ?? ''\n}\n\n// Service-local docker-compose.yml — every service whose image we recognise\n// becomes a candidate DB. The compose service name doubles as the host since\n// that's how peer services on the same compose network reach it.\nexport async function parse(serviceDir: string): Promise<DbConfig[]> {\n  for (const name of ['docker-compose.yml', 'docker-compose.yaml']) {\n    const abs = path.join(serviceDir, name)\n    if (!(await exists(abs))) continue\n    const raw = await readYaml<ComposeFile>(abs)\n    if (!raw?.services) return []\n\n    const out: DbConfig[] = []\n    for (const [serviceName, svc] of Object.entries(raw.services)) {\n      if (!svc.image) continue\n      const meta = engineFromImage(svc.image)\n      if (!meta) continue\n      out.push({\n        host: serviceName,\n        port: portFromService(svc),\n        database: databaseFromEnv(svc),\n        engine: meta.engine,\n        engineVersion: meta.engineVersion,\n        sourceFile: abs,\n      })\n    }\n    return out\n  }\n  return []\n}\n\nexport const dockerComposeParser = { name: 'docker-compose', parse }\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { ConfigNode, GraphEdge } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  configId,\n  confidenceForExtracted,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport {\n  IGNORED_DIRS,\n  isConfigFile,\n  isPythonVenvDir,\n  makeEdgeId,\n  type DiscoveredService,\n} from './shared.js'\nimport { ensureFileNode, toPosix } from './calls/shared.js'\n\n// Walk a service directory and collect every config file path\n// (yaml/yml + .env-shaped). We deliberately stop at file paths here so nothing\n// in this module reads file contents — .env files routinely carry secrets\n// (ADR-016).\nexport async function walkConfigFiles(dir: string, excludeDirs: string[] = []): Promise<string[]> {\n  // ADR-200 — skip nested discovered services' subtrees so an ancestor doesn't\n  // re-mint their ConfigNodes under itself.\n  const excluded = new Set(excludeDirs.map((d) => path.resolve(d)))\n  const out: string[] = []\n  async function walk(current: string): Promise<void> {\n    const entries = await fs.readdir(current, { withFileTypes: true })\n    for (const entry of entries) {\n      const full = path.join(current, entry.name)\n      if (entry.isDirectory()) {\n        if (IGNORED_DIRS.has(entry.name)) continue\n        if (excluded.has(path.resolve(full))) continue\n        if (await isPythonVenvDir(full)) continue\n        await walk(full)\n      } else if (entry.isFile() && isConfigFile(entry.name).match && !excluded.has(path.resolve(full))) {\n        out.push(full)\n      }\n    }\n  }\n  await walk(dir)\n  return out\n}\n\n// Phase 3 — turn each config file into a ConfigNode with a CONFIGURED_BY edge\n// from its owning service.\nexport async function addConfigNodes(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n  scanPath: string,\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n  for (const service of services) {\n    const configFiles = await walkConfigFiles(service.dir, service.excludeDirs)\n    for (const file of configFiles) {\n      const relPath = path.relative(scanPath, file)\n      const node: ConfigNode = {\n        id: configId(relPath),\n        type: NodeType.ConfigNode,\n        name: path.basename(file),\n        path: relPath,\n        fileType: isConfigFile(path.basename(file)).fileType,\n      }\n      if (!graph.hasNode(node.id)) {\n        graph.addNode(node.id, node)\n        nodesAdded++\n      }\n      // file-awareness §1 — the config file IS the relationship origin.\n      // ensureFileNode creates the FileNode + CONTAINS edge so CONFIGURED_BY\n      // lands file-grained rather than service-level.\n      const relToService = toPosix(path.relative(service.dir, file))\n      const { fileNodeId, nodesAdded: fn, edgesAdded: fe } = ensureFileNode(\n        graph,\n        service.pkg.name,\n        service.node.id,\n        relToService,\n      )\n      nodesAdded += fn\n      edgesAdded += fe\n      const edge: GraphEdge = {\n        id: makeEdgeId(fileNodeId, node.id, EdgeType.CONFIGURED_BY),\n        source: fileNodeId,\n        target: node.id,\n        type: EdgeType.CONFIGURED_BY,\n        provenance: Provenance.EXTRACTED,\n        confidence: confidenceForExtracted('structural'),\n        evidence: { file: relPath.split(path.sep).join('/') },\n      }\n      if (!graph.hasEdge(edge.id)) {\n        graph.addEdgeWithKey(edge.id, edge.source, edge.target, edge)\n        edgesAdded++\n      }\n    }\n  }\n  return { nodesAdded, edgesAdded }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { GraphEdge, InfraNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  infraId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport { flagStoreProviders } from '../compat.js'\nimport { FLAG_STORE_KIND, foldDeclaredFlags, parseFlagDocument, type DeclaredFlag } from '../flags.js'\nimport type { FlagDefinition } from '@neat.is/types'\nimport { isTestPath, makeEdgeId, maskCommentsInSource, type DiscoveredService } from './shared.js'\nimport { ensureFileNode, isMinifiedSource, toPosix, walkSourceFiles } from './calls/shared.js'\nimport { configMapFlagsFromYaml } from './flags-configmap.js'\n\n// Flag grain, EXTRACTED side (ADR-242). Two reads:\n//\n// 1. The committed definitions. A flag file is any `.json` under the scan root\n//    whose top level holds a `flags` object of flag definitions and whose\n//    `$schema` names a flag-store provider listed in compat.json. Each provider\n//    becomes one `flag-store` InfraNode; each flag a grain entry on it carrying\n//    its canonical definition. Only the `flags` object is read.\n// 2. The code that reads each key. A source file holding a string literal exactly\n//    equal to a declared key reads that flag. The match is on the literal, not on\n//    any SDK call shape, so it holds in every language the walk covers and through\n//    a wrapper or a constant: the literal is still in the service's own tree. The\n//    file gets an EXTRACTED CONNECTS_TO to the store (the dependency, evidence at\n//    the literal's line), and the flag records the file as a reader.\n//\n// A key built at runtime holds no literal and gets no reader: nothing is guessed.\n//\n// The committed definitions have a second source (#1454): a Kubernetes ConfigMap\n// manifest, plain or Helm template, whose data holds a flag document. See\n// flags-configmap.ts.\n\nconst JSON_EXTENSIONS: ReadonlySet<string> = new Set(['.json'])\nconst YAML_EXTENSIONS: ReadonlySet<string> = new Set(['.yaml', '.yml'])\n// A flag file is small. Anything past this is data, not a flag file.\nconst MAX_FLAG_FILE_BYTES = 1_000_000\n// One string literal on one line, in any of the three quote styles the walked\n// languages use. Comments are masked first, so a key named in a comment is not a\n// reader.\nconst STRING_LITERAL_RE = /([\"'`])((?:\\\\.|(?!\\1)[^\\\\\\n])*)\\1/g\n\nfunction providerFor(doc: unknown): string | null {\n  if (typeof doc !== 'object' || doc === null) return null\n  const schema = (doc as Record<string, unknown>)['$schema']\n  if (typeof schema !== 'string') return null\n  for (const p of flagStoreProviders()) {\n    if (schema.includes(p.schemaPattern)) return p.provider\n  }\n  return null\n}\n\ninterface FlagFile {\n  provider: string\n  relPath: string\n  flags: Map<string, FlagDefinition>\n}\n\nasync function findFlagFiles(scanPath: string): Promise<FlagFile[]> {\n  const out: FlagFile[] = []\n  const files = (await walkSourceFiles(scanPath, [], JSON_EXTENSIONS)).sort()\n  for (const file of files) {\n    const relPath = toPosix(path.relative(scanPath, file))\n    if (isTestPath(relPath)) continue\n    let text: string\n    try {\n      const stat = await fs.stat(file)\n      if (stat.size > MAX_FLAG_FILE_BYTES) continue\n      text = await fs.readFile(file, 'utf8')\n    } catch {\n      continue\n    }\n    // Cheap gate before a parse: every flag file names both words.\n    if (!text.includes('\"flags\"') || !text.includes('\"variants\"')) continue\n    let doc: unknown\n    try {\n      doc = JSON.parse(text)\n    } catch {\n      continue\n    }\n    const provider = providerFor(doc)\n    if (!provider) continue\n    const flags = parseFlagDocument(doc)\n    if (flags) out.push({ provider, relPath, flags })\n  }\n  return out.concat(await findConfigMapFlagFiles(scanPath))\n}\n\n// Flag documents embedded in ConfigMap manifests (#1454).\nasync function findConfigMapFlagFiles(scanPath: string): Promise<FlagFile[]> {\n  const out: FlagFile[] = []\n  const providers = flagStoreProviders().map((p) => p.provider)\n  const files = (await walkSourceFiles(scanPath, [], YAML_EXTENSIONS)).sort()\n  for (const file of files) {\n    const relPath = toPosix(path.relative(scanPath, file))\n    if (isTestPath(relPath)) continue\n    let text: string\n    try {\n      const stat = await fs.stat(file)\n      if (stat.size > MAX_FLAG_FILE_BYTES) continue\n      text = await fs.readFile(file, 'utf8')\n    } catch {\n      continue\n    }\n    // Cheap gate before a parse: a ConfigMap holding flag definitions.\n    if (!text.includes('ConfigMap') || !text.includes('flags') || !text.includes('variants')) continue\n    for (const found of configMapFlagsFromYaml(text, providers)) {\n      out.push({ provider: found.provider, relPath, flags: found.flags })\n    }\n  }\n  return out\n}\n\ninterface Reader {\n  file: string\n  service: string\n  line: number\n}\n\n// Every (key → first literal line) in one source file, for the keys asked about.\nfunction literalKeyLines(src: string, keys: ReadonlySet<string>): Map<string, number> {\n  const masked = maskCommentsInSource(src)\n  const out = new Map<string, number>()\n  STRING_LITERAL_RE.lastIndex = 0\n  let m: RegExpExecArray | null\n  while ((m = STRING_LITERAL_RE.exec(masked)) !== null) {\n    const value = m[2]!\n    if (!keys.has(value) || out.has(value)) continue\n    let line = 1\n    for (let i = 0; i < m.index; i++) if (masked.charCodeAt(i) === 10) line++\n    out.set(value, line)\n  }\n  return out\n}\n\nexport async function addFlagStores(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n  scanPath: string,\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n  const flagFiles = await findFlagFiles(scanPath)\n  if (flagFiles.length === 0) return { nodesAdded, edgesAdded }\n\n  // provider → key → declaration. The first file (sorted path) to declare a key\n  // for a provider wins, so the result is stable across runs.\n  const byProvider = new Map<string, Map<string, { definition: FlagDefinition; declaredIn: string }>>()\n  for (const ff of flagFiles) {\n    const keys = byProvider.get(ff.provider) ?? new Map()\n    for (const [key, definition] of ff.flags) {\n      if (!keys.has(key)) keys.set(key, { definition, declaredIn: ff.relPath })\n    }\n    byProvider.set(ff.provider, keys)\n  }\n\n  for (const [provider, declarations] of byProvider) {\n    const storeId = infraId(FLAG_STORE_KIND, provider)\n    if (!graph.hasNode(storeId)) {\n      const node: InfraNode = {\n        id: storeId,\n        type: NodeType.InfraNode,\n        name: provider,\n        provider,\n        kind: FLAG_STORE_KIND,\n      }\n      graph.addNode(storeId, node)\n      nodesAdded++\n    }\n\n    const keys = new Set(declarations.keys())\n    const readers = new Map<string, Reader[]>()\n    for (const service of services) {\n      const files = await walkSourceFiles(service.dir, service.excludeDirs)\n      for (const file of files) {\n        const relToService = toPosix(path.relative(service.dir, file))\n        if (isTestPath(relToService)) continue\n        let src: string\n        try {\n          src = await fs.readFile(file, 'utf8')\n        } catch {\n          continue\n        }\n        if (isMinifiedSource(file, src).minified) continue\n        const hits = literalKeyLines(src, keys)\n        if (hits.size === 0) continue\n        const { fileNodeId, nodesAdded: fn, edgesAdded: fe } = ensureFileNode(\n          graph,\n          service.pkg.name,\n          service.node.id,\n          relToService,\n        )\n        nodesAdded += fn\n        edgesAdded += fe\n        let firstLine = Number.POSITIVE_INFINITY\n        for (const [key, line] of hits) {\n          const list = readers.get(key) ?? []\n          list.push({ file: fileNodeId, service: service.node.id, line })\n          readers.set(key, list)\n          firstLine = Math.min(firstLine, line)\n        }\n        const edge: GraphEdge = {\n          id: makeEdgeId(fileNodeId, storeId, EdgeType.CONNECTS_TO),\n          source: fileNodeId,\n          target: storeId,\n          type: EdgeType.CONNECTS_TO,\n          provenance: Provenance.EXTRACTED,\n          confidence: confidenceForExtracted('structural'),\n          evidence: { file: toPosix(path.relative(scanPath, file)), line: firstLine },\n        }\n        if (!graph.hasEdge(edge.id)) {\n          graph.addEdgeWithKey(edge.id, edge.source, edge.target, edge)\n          edgesAdded++\n        }\n      }\n    }\n\n    const declared: DeclaredFlag[] = [...declarations].map(([key, d]) => ({\n      key,\n      definition: d.definition,\n      declaredIn: d.declaredIn,\n      readers: readers.get(key) ?? [],\n    }))\n    const node = graph.getNodeAttributes(storeId) as InfraNode\n    graph.mergeNodeAttributes(storeId, { flags: foldDeclaredFlags(node.flags, declared) })\n  }\n  return { nodesAdded, edgesAdded }\n}\n","import { parseAllDocuments, parse as parseYaml } from 'yaml'\nimport type { FlagDefinition } from '@neat.is/types'\nimport { parseFlagDocument } from '../flags.js'\n\n// Flag grain, EXTRACTED side, second source (ADR-242 amendment, #1454): flag\n// definitions embedded in a Kubernetes ConfigMap.\n//\n//   kind: ConfigMap\n//   metadata:\n//     name: flagd-config\n//   data:\n//     flags.yaml: |\n//       flags:\n//         tt-feat-01:\n//           state: ENABLED\n//           variants: { \"on\": true, \"off\": false }\n//           defaultVariant: \"off\"\n//\n// A data value is read as YAML (which also reads JSON) and is a flag document\n// when it holds a `flags` map of definitions, the same shape a flag file holds.\n// A ConfigMap carries no `$schema`, so the provider is the one whose name (from\n// compat.json's flag-store list) appears in the ConfigMap's name or the data key.\n//\n// Helm templates are read as text and never rendered. A `{{ … }}` expression is\n// swapped for a marker before the parse, and a line holding only a template\n// action (`{{- if … }}`) is dropped. A flag whose definition still holds the\n// marker came from a template value and stays unclaimed; the rest of the file\n// is read. A file that won't parse yields nothing.\n\nconst MARKER = '__neat_helm_expr__'\n\nexport interface ConfigMapFlags {\n  provider: string\n  flags: Map<string, FlagDefinition>\n}\n\nfunction untemplate(text: string): string {\n  return text\n    .split('\\n')\n    .filter((line) => !/^\\s*\\{\\{-?[^}]*-?\\}\\}\\s*$/.test(line))\n    .join('\\n')\n    .replace(/\\{\\{-?[^}]*?-?\\}\\}/g, MARKER)\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n  return typeof v === 'object' && v !== null && !Array.isArray(v)\n}\n\n/** Flag documents in one YAML manifest's ConfigMaps, by provider. */\nexport function configMapFlagsFromYaml(text: string, providers: readonly string[]): ConfigMapFlags[] {\n  const out: ConfigMapFlags[] = []\n  let docs\n  try {\n    docs = parseAllDocuments(untemplate(text))\n  } catch {\n    return out\n  }\n  for (const d of docs) {\n    if (d.errors.length > 0) continue\n    const doc = d.toJS() as unknown\n    if (!isRecord(doc) || doc['kind'] !== 'ConfigMap' || !isRecord(doc['data'])) continue\n    const name = isRecord(doc['metadata']) && typeof doc['metadata']['name'] === 'string' ? doc['metadata']['name'] : ''\n    for (const [key, value] of Object.entries(doc['data'])) {\n      if (typeof value !== 'string' || !value.includes('flags')) continue\n      const provider = providers.find((p) => name.includes(p) || key.includes(p))\n      if (!provider) continue\n      let inner: unknown\n      try {\n        inner = parseYaml(value)\n      } catch {\n        continue\n      }\n      // A flag whose raw definition came from a template value is left out.\n      if (isRecord(inner) && isRecord(inner['flags'])) {\n        const flagsObj = inner['flags']\n        for (const k of Object.keys(flagsObj)) {\n          if (k.includes(MARKER) || JSON.stringify(flagsObj[k]).includes(MARKER)) delete flagsObj[k]\n        }\n      }\n      const flags = parseFlagDocument(inner)\n      if (flags) out.push({ provider, flags })\n    }\n  }\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport Java from 'tree-sitter-java'\nimport type { GraphEdge, RouteNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  routeId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport { isTestPath, type DiscoveredService } from './shared.js'\nimport { recordExtractionError } from './errors.js'\nimport { loadSourceFiles, snippet, toPosix } from './calls/shared.js'\nimport { canonicalizeTemplate, type ExtractedRoute } from './routes.js'\n\n// Spring MVC route extraction. A Java service's HTTP surface is declared in\n// annotations: a controller class may carry a `@RequestMapping(\"/prefix\")`, and\n// each handler method a `@GetMapping` / `@PostMapping` / `@PutMapping` /\n// `@DeleteMapping` / `@PatchMapping`, or a `@RequestMapping(method = …)`. Each\n// (method, path) pair becomes a RouteNode owned by its service through\n// `service ──CONTAINS──▶ route`, the same shape addRoutes mints for every other\n// router (ADR-119), so a Spring server span's `http.route` fuses onto it.\n//\n// The gate is the source, not the manifest. A Spring service usually inherits\n// `spring-boot-starter-web` from a parent POM (train-ticket's 41 services all\n// do), and java.ts reads each module's own POM, so the dependency isn't there to\n// gate on. A file is read when it imports `org.springframework.web.bind.annotation`\n// (or names an annotation fully qualified), the per-file self-gate Sinatra and\n// Slim use (ADR-206).\n//\n// Only classes Spring treats as handlers are read: a `@RestController` /\n// `@Controller`, or a class carrying `@RequestMapping` itself. A `@FeignClient`\n// interface declares the same annotations for the *client* side and is never a\n// route. A path that isn't a literal, or a concatenation of literals and same-file\n// `static final String` constants, stays unclaimed rather than guessed.\n\nconst PARSE_CHUNK = 16384\nconst SPRING_WEB = 'org.springframework.web.bind.annotation'\n\nconst VERB_ANNOTATIONS: Record<string, string> = {\n  GetMapping: 'GET',\n  PostMapping: 'POST',\n  PutMapping: 'PUT',\n  DeleteMapping: 'DELETE',\n  PatchMapping: 'PATCH',\n}\nconst HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'TRACE'])\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nexport function makeJavaParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Java)\n  return p\n}\n\n// The annotation's simple name and whether it was written fully qualified under\n// Spring's web package.\nfunction annotationName(node: Parser.SyntaxNode): { name: string; qualified: boolean } | null {\n  const n = node.childForFieldName('name')\n  if (!n) return null\n  const text = n.text\n  const dot = text.lastIndexOf('.')\n  return dot === -1\n    ? { name: text, qualified: false }\n    : { name: text.slice(dot + 1), qualified: text.slice(0, dot) === SPRING_WEB }\n}\n\nfunction annotationsOf(decl: Parser.SyntaxNode): Parser.SyntaxNode[] {\n  const mods = decl.namedChildren.find((c) => c.type === 'modifiers')\n  if (!mods) return []\n  return mods.namedChildren.filter((c) => c.type === 'annotation' || c.type === 'marker_annotation')\n}\n\nfunction javaStringLiteral(node: Parser.SyntaxNode): string | null {\n  if (node.type !== 'string_literal') return null\n  // A plain literal's fragments; an escape sequence makes it not worth guessing.\n  let out = ''\n  for (const c of node.namedChildren) {\n    if (c.type === 'string_fragment') out += c.text\n    else return null\n  }\n  return out\n}\n\n// `static final String NAME = \"literal\"` fields anywhere in the file.\nfunction stringConstants(root: Parser.SyntaxNode): Map<string, string> {\n  const out = new Map<string, string>()\n  const visit = (n: Parser.SyntaxNode): void => {\n    if (n.type === 'field_declaration') {\n      const mods = n.namedChildren.find((c) => c.type === 'modifiers')?.text ?? ''\n      if (/\\bstatic\\b/.test(mods) && /\\bfinal\\b/.test(mods)) {\n        for (const d of n.namedChildren) {\n          if (d.type !== 'variable_declarator') continue\n          const name = d.childForFieldName('name')?.text\n          const value = d.childForFieldName('value')\n          const lit = value ? constantString(value, out) : null\n          if (name && lit !== null) out.set(name, lit)\n        }\n      }\n    }\n    for (const c of n.namedChildren) visit(c)\n  }\n  visit(root)\n  return out\n}\n\n// A string built only from literals and known constants; null otherwise.\nfunction constantString(node: Parser.SyntaxNode, consts: Map<string, string>): string | null {\n  if (node.type === 'string_literal') return javaStringLiteral(node)\n  if (node.type === 'identifier') return consts.get(node.text) ?? null\n  if (node.type === 'parenthesized_expression' && node.namedChildren[0]) {\n    return constantString(node.namedChildren[0], consts)\n  }\n  if (node.type === 'binary_expression' && node.childForFieldName('operator')?.text === '+') {\n    const l = node.childForFieldName('left')\n    const r = node.childForFieldName('right')\n    const ls = l ? constantString(l, consts) : null\n    const rs = r ? constantString(r, consts) : null\n    return ls !== null && rs !== null ? ls + rs : null\n  }\n  return null\n}\n\n// The value nodes for `key` (or the lone positional value, which Spring binds to\n// `value`), unwrapping an `{a, b}` array.\nfunction annotationValues(ann: Parser.SyntaxNode, keys: string[]): Parser.SyntaxNode[] | null {\n  const args = ann.childForFieldName('arguments')\n  if (!args) return null\n  let value: Parser.SyntaxNode | null = null\n  for (const c of args.namedChildren) {\n    if (c.type === 'element_value_pair') {\n      if (keys.includes(c.childForFieldName('key')?.text ?? '')) value = c.childForFieldName('value')\n    } else if (keys.includes('value')) {\n      value = c\n    }\n  }\n  if (!value) return null\n  return value.type === 'element_value_array_initializer' ? value.namedChildren : [value]\n}\n\n// The paths an annotation declares: [''] when it names none (the handler sits at\n// the prefix), null when one isn't a resolvable constant (skip, don't guess).\nfunction annotationPaths(ann: Parser.SyntaxNode, consts: Map<string, string>): string[] | null {\n  const values = annotationValues(ann, ['value', 'path'])\n  if (!values || values.length === 0) return ['']\n  const out: string[] = []\n  for (const v of values) {\n    const s = constantString(v, consts)\n    if (s === null) return null\n    out.push(s)\n  }\n  return out\n}\n\n// `method = RequestMethod.GET` / `{GET, POST}`; ['ALL'] when none is named.\nfunction requestMappingMethods(ann: Parser.SyntaxNode): string[] | null {\n  const values = annotationValues(ann, ['method'])\n  if (!values || values.length === 0) return ['ALL']\n  const out: string[] = []\n  for (const v of values) {\n    const name = (v.type === 'field_access' ? v.childForFieldName('field')?.text : v.text) ?? ''\n    if (!HTTP_METHODS.has(name)) return null\n    out.push(name)\n  }\n  return out\n}\n\nfunction joinPath(prefix: string, leaf: string): string {\n  if (!prefix) return canonicalizeTemplate(leaf || '/')\n  if (!leaf) return canonicalizeTemplate(prefix)\n  return canonicalizeTemplate(prefix.replace(/\\/+$/, '') + '/' + leaf.replace(/^\\/+/, ''))\n}\n\nfunction importsSpringWeb(root: Parser.SyntaxNode): boolean {\n  return root.namedChildren.some(\n    (c) => c.type === 'import_declaration' && c.text.includes(SPRING_WEB),\n  )\n}\n\n/** Spring MVC routes declared in one Java source file. */\nexport function springRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  const root = parseSource(parser, source).rootNode\n  const imported = importsSpringWeb(root)\n  const consts = stringConstants(root)\n  const out: ExtractedRoute[] = []\n  const isSpring = (a: { qualified: boolean }): boolean => imported || a.qualified\n\n  const visitClass = (cls: Parser.SyntaxNode): void => {\n    const anns = annotationsOf(cls)\n    let isHandler = false\n    let prefixes: string[] | null = ['']\n    for (const a of anns) {\n      const n = annotationName(a)\n      if (!n) continue\n      if (n.name === 'RestController' || n.name === 'Controller') isHandler = true\n      if (n.name === 'RequestMapping' && isSpring(n)) {\n        isHandler = true\n        prefixes = annotationPaths(a, consts)\n      }\n    }\n    const body = cls.childForFieldName('body')\n    if (isHandler && prefixes && body) {\n      for (const m of body.namedChildren) {\n        if (m.type !== 'method_declaration') continue\n        for (const a of annotationsOf(m)) {\n          const n = annotationName(a)\n          if (!n || !isSpring(n)) continue\n          const verb = VERB_ANNOTATIONS[n.name]\n          const methods = verb ? [verb] : n.name === 'RequestMapping' ? requestMappingMethods(a) : null\n          if (!methods) continue\n          const leaves = annotationPaths(a, consts)\n          if (!leaves) continue\n          for (const prefix of prefixes) {\n            for (const leaf of leaves) {\n              for (const method of methods) {\n                out.push({\n                  method,\n                  pathTemplate: joinPath(prefix, leaf),\n                  line: a.startPosition.row + 1,\n                  framework: 'spring',\n                })\n              }\n            }\n          }\n        }\n      }\n    }\n    // Nested classes declare their own mappings, with their own prefix.\n    if (body) for (const c of body.namedChildren) if (c.type === 'class_declaration') visitClass(c)\n  }\n\n  for (const c of root.namedChildren) if (c.type === 'class_declaration') visitClass(c)\n  return out\n}\n\n/** Mint Spring MVC RouteNodes for every Java service. */\nexport async function addJavaRoutes(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  const parser = makeJavaParser()\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    if (service.node.language !== 'java') continue\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n    for (const file of files) {\n      if (path.extname(file.path) !== '.java' || isTestPath(file.path)) continue\n      // Cheap pre-check before parsing: a file with no Spring web reference\n      // can't declare a route.\n      if (!file.content.includes(SPRING_WEB)) continue\n      let routes: ExtractedRoute[]\n      try {\n        routes = springRoutesFromSource(file.content, parser)\n      } catch (err) {\n        recordExtractionError('route extraction', file.path, err)\n        continue\n      }\n      const relFile = toPosix(path.relative(service.dir, file.path))\n      for (const route of routes) {\n        const rid = routeId(service.pkg.name, route.method, route.pathTemplate)\n        if (!graph.hasNode(rid)) {\n          const node: RouteNode = {\n            id: rid,\n            type: NodeType.RouteNode,\n            name: `${route.method} ${route.pathTemplate}`,\n            service: service.pkg.name,\n            method: route.method,\n            pathTemplate: route.pathTemplate,\n            path: relFile,\n            line: route.line,\n            framework: route.framework,\n            discoveredVia: 'static',\n          }\n          graph.addNode(rid, node)\n          nodesAdded++\n        }\n        const containsId = extractedEdgeId(service.node.id, rid, EdgeType.CONTAINS)\n        if (!graph.hasEdge(containsId)) {\n          const edge: GraphEdge = {\n            id: containsId,\n            source: service.node.id,\n            target: rid,\n            type: EdgeType.CONTAINS,\n            provenance: Provenance.EXTRACTED,\n            confidence: confidenceForExtracted('structural'),\n            evidence: { file: relFile, line: route.line, snippet: snippet(file.content, route.line) },\n          }\n          graph.addEdgeWithKey(containsId, service.node.id, rid, edge)\n          edgesAdded++\n        }\n      }\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport Python from 'tree-sitter-python'\nimport type { GraphEdge, RouteNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  routeId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport { isTestPath, type DiscoveredService } from './shared.js'\nimport { recordExtractionError } from './errors.js'\nimport { loadSourceFiles, snippet, toPosix } from './calls/shared.js'\nimport { canonicalizeTemplate, type ExtractedRoute } from './routes.js'\n\n// Tornado route extraction. A Tornado app declares its routes as a literal\n// handler table passed to `Application`:\n//\n//   tornado.web.Application([\n//       (r\"/getVoucher\", GetVoucherHandler),\n//       url(r\"/orders/(?P<id>[0-9]+)\", OrderHandler, name=\"order\"),\n//   ])\n//\n// Each entry's path pattern becomes a RouteNode, with one route per HTTP verb\n// method (`get`, `post`, …) the handler class defines in the same file; a\n// handler defined elsewhere gives one `ALL` route. The table may be inline,\n// passed as `handlers=[…]`, or a same-file list variable.\n//\n// A pattern is a regex. Each capture group becomes a param segment (`:id` for a\n// named group, `:param` otherwise), a leading `^` and trailing `$` or `/?` are\n// dropped, and a pattern that still carries regex syntax after that is left\n// unclaimed rather than guessed. Gated on the service's `tornado` dependency.\n\nconst PARSE_CHUNK = 16384\nconst VERBS = ['get', 'post', 'put', 'delete', 'patch', 'head', 'options']\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nfunction walk(node: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (const c of node.namedChildren) walk(c, visit)\n}\n\n// A plain (raw or not) string literal's text; null for an f-string or a\n// concatenation.\nfunction pyString(node: Parser.SyntaxNode | undefined): string | null {\n  if (!node || node.type !== 'string') return null\n  let out = ''\n  for (const c of node.namedChildren) {\n    if (c.type === 'string_content') out += c.text\n    else if (c.type === 'interpolation') return null\n  }\n  return out\n}\n\n/** A Tornado URL regex as a path template; null when it isn't one. */\nexport function tornadoPathTemplate(pattern: string): string | null {\n  let p = pattern.replace(/^\\^/, '').replace(/\\$$/, '').replace(/\\/\\?$/, '')\n  p = p.replace(/\\(\\?P<([A-Za-z_][A-Za-z0-9_]*)>[^()]*\\)/g, ':$1')\n  p = p.replace(/\\((?!\\?)[^()]*\\)/g, ':param')\n  if (/[\\\\()[\\]{}*+?|^$]/.test(p)) return null\n  return canonicalizeTemplate(p || '/')\n}\n\n// The verb methods each same-file class defines.\nfunction handlerVerbs(root: Parser.SyntaxNode): Map<string, string[]> {\n  const out = new Map<string, string[]>()\n  for (const c of root.namedChildren) {\n    const cls = c.type === 'decorated_definition' ? c.childForFieldName('definition') : c\n    if (cls?.type !== 'class_definition') continue\n    const name = cls.childForFieldName('name')?.text\n    const body = cls.childForFieldName('body')\n    if (!name || !body) continue\n    const verbs: string[] = []\n    for (const m of body.namedChildren) {\n      const fn = m.type === 'decorated_definition' ? m.childForFieldName('definition') : m\n      const fname = fn?.type === 'function_definition' ? fn.childForFieldName('name')?.text : undefined\n      if (fname && VERBS.includes(fname)) verbs.push(fname.toUpperCase())\n    }\n    out.set(name, verbs)\n  }\n  return out\n}\n\n// Same-file `name = [...]` list assignments, for a handler table passed by name.\nfunction listVariables(root: Parser.SyntaxNode): Map<string, Parser.SyntaxNode | null> {\n  const out = new Map<string, Parser.SyntaxNode | null>()\n  walk(root, (n) => {\n    if (n.type !== 'assignment') return\n    const left = n.childForFieldName('left')\n    const right = n.childForFieldName('right')\n    if (left?.type !== 'identifier') return\n    out.set(left.text, out.has(left.text) ? null : right?.type === 'list' ? right : null)\n  })\n  return out\n}\n\nfunction isApplicationCall(call: Parser.SyntaxNode): boolean {\n  const fn = call.childForFieldName('function')\n  const name = fn?.type === 'attribute' ? fn.childForFieldName('attribute')?.text : fn?.text\n  return name === 'Application'\n}\n\n/** Tornado routes declared in one Python source file. */\nexport function tornadoRoutesFromSource(source: string, parser: Parser): ExtractedRoute[] {\n  const root = parseSource(parser, source).rootNode\n  const verbs = handlerVerbs(root)\n  const lists = listVariables(root)\n  const out: ExtractedRoute[] = []\n\n  walk(root, (call) => {\n    if (call.type !== 'call' || !isApplicationCall(call)) return\n    const args = call.childForFieldName('arguments')?.namedChildren ?? []\n    let table: Parser.SyntaxNode | null | undefined = args.find((a) => a.type !== 'keyword_argument')\n    for (const a of args) {\n      if (a.type === 'keyword_argument' && a.childForFieldName('name')?.text === 'handlers') {\n        table = a.childForFieldName('value')\n      }\n    }\n    if (table?.type === 'identifier') table = lists.get(table.text) ?? null\n    if (!table || table.type !== 'list') return\n\n    for (const entry of table.namedChildren) {\n      // `(pattern, Handler, …)` or `url(pattern, Handler, …)` / `URLSpec(…)`.\n      let parts: Parser.SyntaxNode[] = []\n      if (entry.type === 'tuple') parts = entry.namedChildren\n      else if (entry.type === 'call') {\n        const fn = entry.childForFieldName('function')\n        const fname = fn?.type === 'attribute' ? fn.childForFieldName('attribute')?.text : fn?.text\n        if (fname !== 'url' && fname !== 'URLSpec') continue\n        parts = (entry.childForFieldName('arguments')?.namedChildren ?? []).filter((a) => a.type !== 'keyword_argument')\n      } else continue\n      const pattern = pyString(parts[0])\n      const handler = parts[1]\n      if (pattern === null || !handler) continue\n      const pathTemplate = tornadoPathTemplate(pattern)\n      if (!pathTemplate) continue\n      const handlerName = handler.type === 'attribute' ? handler.childForFieldName('attribute')?.text : handler.text\n      const methods = (handlerName && verbs.get(handlerName)?.length ? verbs.get(handlerName)! : ['ALL'])\n      for (const method of methods) {\n        out.push({ method, pathTemplate, line: entry.startPosition.row + 1, framework: 'tornado' })\n      }\n    }\n  })\n  return out\n}\n\n/** Mint Tornado RouteNodes for every service that depends on tornado. */\nexport async function addTornadoRoutes(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let parser: Parser | null = null\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    const deps = { ...(service.pkg.dependencies ?? {}), ...(service.pkg.devDependencies ?? {}) }\n    if (deps['tornado'] === undefined) continue\n    parser ??= (() => {\n      const p = new Parser()\n      p.setLanguage(Python)\n      return p\n    })()\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n    for (const file of files) {\n      if (path.extname(file.path) !== '.py' || isTestPath(file.path)) continue\n      if (!file.content.includes('Application')) continue\n      let routes: ExtractedRoute[]\n      try {\n        routes = tornadoRoutesFromSource(file.content, parser)\n      } catch (err) {\n        recordExtractionError('route extraction', file.path, err)\n        continue\n      }\n      const relFile = toPosix(path.relative(service.dir, file.path))\n      for (const route of routes) {\n        const rid = routeId(service.pkg.name, route.method, route.pathTemplate)\n        if (!graph.hasNode(rid)) {\n          const node: RouteNode = {\n            id: rid,\n            type: NodeType.RouteNode,\n            name: `${route.method} ${route.pathTemplate}`,\n            service: service.pkg.name,\n            method: route.method,\n            pathTemplate: route.pathTemplate,\n            path: relFile,\n            line: route.line,\n            framework: route.framework,\n            discoveredVia: 'static',\n          }\n          graph.addNode(rid, node)\n          nodesAdded++\n        }\n        const containsId = extractedEdgeId(service.node.id, rid, EdgeType.CONTAINS)\n        if (!graph.hasEdge(containsId)) {\n          const edge: GraphEdge = {\n            id: containsId,\n            source: service.node.id,\n            target: rid,\n            type: EdgeType.CONTAINS,\n            provenance: Provenance.EXTRACTED,\n            confidence: confidenceForExtracted('structural'),\n            evidence: { file: relFile, line: route.line, snippet: snippet(file.content, route.line) },\n          }\n          graph.addEdgeWithKey(containsId, service.node.id, rid, edge)\n          edgesAdded++\n        }\n      }\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { parseAllDocuments, isMap, isSeq, isScalar, type Node as YamlNode } from 'yaml'\nimport type { GraphEdge, RouteNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  routeId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport { makeEdgeId, type DiscoveredService } from './shared.js'\nimport { recordExtractionError, noteExtractedDropped } from './errors.js'\nimport { resolveEnvVar } from './databases/shared.js'\nimport { buildServiceHostIndex, ensureFileNode, snippet, toPosix } from './calls/shared.js'\n\n// Spring Cloud Gateway routes — config as a source. A gateway service declares\n// its whole routing table in application.yml:\n//\n//   spring:\n//     cloud:\n//       gateway:\n//         routes:\n//           - id: order\n//             uri: lb://${ORDER_SERVICE_HOST:ts-order-service}\n//             predicates:\n//               - Path=/api/v1/orderservice/**\n//\n// Each route's Path patterns become RouteNodes on the gateway (method from a\n// `Method=` predicate, else ALL), owned through `service ──CONTAINS──▶ route`\n// like any other route, and the config file gets `file ──CALLS──▶ service` to\n// the service the `uri` names. That is the hop every request takes from the\n// front door, declared in config rather than code.\n//\n// Read from `spring.cloud.gateway.routes` and the newer\n// `spring.cloud.gateway.server.webflux.routes`, default profile only, in either\n// predicate form: the shortcut string (`Path=/a/**,/b/**`) or the expanded map\n// (`name: Path`, `args: { patterns: … }`). A `${NAME:default}` in the uri\n// resolves from the service's `.env`, else to its default. A uri with no\n// resolvable host, or whose host names no service in the graph, gets no CALLS\n// edge; an unresolved one is recorded as a drop with its reason.\n\nconst CONFIG_FILES = ['application.yml', 'application.yaml']\nconst ROUTE_KEYS = ['spring.cloud.gateway.routes', 'spring.cloud.gateway.server.webflux.routes']\nconst HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'])\n\nexport interface GatewayRoute {\n  id?: string\n  // The uri as written, and its host once placeholders resolve (null when they\n  // can't be).\n  uri: string\n  host: string | null\n  paths: string[]\n  methods: string[]\n  line: number\n}\n\n// A key from a YAML map node, nested or written flat (`spring.cloud.gateway:`).\nfunction mapGet(node: unknown, key: string): unknown {\n  if (!isMap(node)) return undefined\n  for (const pair of node.items) {\n    const k = isScalar(pair.key) ? String(pair.key.value) : undefined\n    if (k === undefined) continue\n    if (k === key) return pair.value\n    if (key.startsWith(k + '.')) {\n      const v = mapGet(pair.value, key.slice(k.length + 1))\n      if (v !== undefined) return v\n    }\n  }\n  return undefined\n}\n\nfunction scalarString(node: unknown): string | undefined {\n  return isScalar(node) && node.value !== null && node.value !== undefined ? String(node.value) : undefined\n}\n\nfunction lineAt(text: string, offset: number): number {\n  return text.slice(0, offset).split('\\n').length\n}\n\n// A predicate as (name, values): `Path=/a/**,/b/**` or the expanded map form.\nfunction predicate(node: unknown): { name: string; values: string[]; offset: number } | null {\n  const offset = (node as YamlNode | undefined)?.range?.[0] ?? 0\n  const s = scalarString(node)\n  if (s !== undefined) {\n    const eq = s.indexOf('=')\n    if (eq <= 0) return null\n    return { name: s.slice(0, eq).trim(), values: s.slice(eq + 1).split(',').map((v) => v.trim()).filter(Boolean), offset }\n  }\n  if (!isMap(node)) return null\n  const name = scalarString(mapGet(node, 'name'))\n  if (!name) return null\n  const args = mapGet(node, 'args')\n  const values: string[] = []\n  if (isMap(args)) {\n    for (const pair of args.items) {\n      const v = pair.value\n      if (isSeq(v)) for (const item of v.items) {\n        const t = scalarString(item)\n        if (t) values.push(...t.split(',').map((x) => x.trim()).filter(Boolean))\n      }\n      else {\n        const t = scalarString(v)\n        if (t) values.push(...t.split(',').map((x) => x.trim()).filter(Boolean))\n      }\n    }\n  }\n  return { name, values, offset }\n}\n\nasync function resolvePlaceholders(serviceDir: string, value: string): Promise<string | null> {\n  let out = ''\n  let last = 0\n  const re = /\\$\\{([^}:]+)(?::([^}]*))?\\}/g\n  let m: RegExpExecArray | null\n  while ((m = re.exec(value)) !== null) {\n    out += value.slice(last, m.index)\n    const resolved = (await resolveEnvVar(serviceDir, m[1]!)) ?? m[2]\n    if (resolved === undefined) return null\n    out += resolved\n    last = m.index + m[0].length\n  }\n  return out + value.slice(last)\n}\n\n// `lb://name`, `http://host:port/x`, `ws://…` → host; null otherwise.\nfunction hostOf(uri: string): string | null {\n  const m = /^[a-z][a-z0-9+.-]*:\\/\\/([^/:?#]+)/i.exec(uri)\n  return m ? m[1]! : null\n}\n\n/** The Spring Cloud Gateway routes one application.yml declares (default profile). */\nexport async function gatewayRoutesFromYaml(text: string, serviceDir: string): Promise<GatewayRoute[]> {\n  const out: GatewayRoute[] = []\n  for (const doc of parseAllDocuments(text)) {\n    if (doc.errors.length > 0) continue\n    const root = doc.contents\n    if (mapGet(root, 'spring.config.activate.on-profile') !== undefined || mapGet(root, 'spring.profiles') !== undefined) {\n      continue\n    }\n    for (const key of ROUTE_KEYS) {\n      const routes = mapGet(root, key)\n      if (!isSeq(routes)) continue\n      for (const r of routes.items) {\n        const uri = scalarString(mapGet(r, 'uri'))\n        const preds = mapGet(r, 'predicates')\n        if (!uri || !isSeq(preds)) continue\n        const paths: string[] = []\n        let methods: string[] = ['ALL']\n        let line = lineAt(text, (r as YamlNode).range?.[0] ?? 0)\n        for (const p of preds.items) {\n          const pred = predicate(p)\n          if (!pred) continue\n          if (pred.name === 'Path') {\n            paths.push(...pred.values)\n            line = lineAt(text, pred.offset)\n          } else if (pred.name === 'Method') {\n            const ms = pred.values.map((v) => v.toUpperCase()).filter((v) => HTTP_METHODS.has(v))\n            if (ms.length > 0) methods = ms\n          }\n        }\n        if (paths.length === 0) continue\n        const resolved = await resolvePlaceholders(serviceDir, uri)\n        out.push({\n          id: scalarString(mapGet(r, 'id')),\n          uri,\n          host: resolved ? hostOf(resolved) : null,\n          paths,\n          methods,\n          line,\n        })\n      }\n    }\n  }\n  return out\n}\n\n/** Gateway RouteNodes and the config file's CALLS to each routed service. */\nexport async function addGatewayRoutes(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  const { hostToNodeId } = buildServiceHostIndex(services)\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    if (service.node.language !== 'java') continue\n    for (const dir of [path.join(service.dir, 'src', 'main', 'resources'), service.dir]) {\n      for (const name of CONFIG_FILES) {\n        const abs = path.join(dir, name)\n        const text = await fs.readFile(abs, 'utf8').catch(() => null)\n        if (text === null || !text.includes('gateway')) continue\n        let routes: GatewayRoute[]\n        try {\n          routes = await gatewayRoutesFromYaml(text, service.dir)\n        } catch (err) {\n          recordExtractionError('gateway route extraction', abs, err)\n          continue\n        }\n        if (routes.length === 0) continue\n        const relFile = toPosix(path.relative(service.dir, abs))\n        const { fileNodeId, nodesAdded: n, edgesAdded: e } = ensureFileNode(\n          graph,\n          service.pkg.name,\n          service.node.id,\n          relFile,\n        )\n        nodesAdded += n\n        edgesAdded += e\n\n        for (const r of routes) {\n          const ev = { file: relFile, line: r.line, snippet: snippet(text, r.line) }\n          for (const p of r.paths) {\n            const pathTemplate = p.startsWith('/') ? p : '/' + p\n            for (const method of r.methods) {\n              const rid = routeId(service.pkg.name, method, pathTemplate)\n              if (!graph.hasNode(rid)) {\n                const node: RouteNode = {\n                  id: rid,\n                  type: NodeType.RouteNode,\n                  name: `${method} ${pathTemplate}`,\n                  service: service.pkg.name,\n                  method,\n                  pathTemplate,\n                  path: relFile,\n                  line: r.line,\n                  framework: 'spring-cloud-gateway',\n                  discoveredVia: 'static',\n                }\n                graph.addNode(rid, node)\n                nodesAdded++\n              }\n              const containsId = extractedEdgeId(service.node.id, rid, EdgeType.CONTAINS)\n              if (!graph.hasEdge(containsId)) {\n                const edge: GraphEdge = {\n                  id: containsId,\n                  source: service.node.id,\n                  target: rid,\n                  type: EdgeType.CONTAINS,\n                  provenance: Provenance.EXTRACTED,\n                  confidence: confidenceForExtracted('structural'),\n                  evidence: ev,\n                }\n                graph.addEdgeWithKey(containsId, service.node.id, rid, edge)\n                edgesAdded++\n              }\n            }\n          }\n\n          if (r.host === null) {\n            noteExtractedDropped({\n              source: fileNodeId,\n              target: 'service:unresolved',\n              type: EdgeType.CALLS,\n              confidence: confidenceForExtracted('reconstructed-approximate'),\n              confidenceKind: 'reconstructed-approximate',\n              evidence: { ...ev, approximate: true, reason: `the route's uri host doesn't resolve: ${r.uri}` },\n            })\n            continue\n          }\n          const target = hostToNodeId.get(r.host)\n          if (!target || target === service.node.id) continue\n          const edgeId = makeEdgeId(fileNodeId, target, EdgeType.CALLS)\n          if (graph.hasEdge(edgeId)) continue\n          const edge: GraphEdge = {\n            id: edgeId,\n            source: fileNodeId,\n            target,\n            type: EdgeType.CALLS,\n            provenance: Provenance.EXTRACTED,\n            // A declared routing table: the gateway forwards these paths to this\n            // service by configuration, not by a guessed URL.\n            confidence: confidenceForExtracted('structural'),\n            evidence: { ...ev, pathTemplate: r.paths[0] },\n          }\n          graph.addEdgeWithKey(edgeId, fileNodeId, target, edge)\n          edgesAdded++\n        }\n      }\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { GraphEdge, GrpcMethodNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  grpcMethodId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport { IGNORED_DIRS, isPythonVenvDir, isTestPath, type DiscoveredService } from './shared.js'\nimport { recordExtractionError } from './errors.js'\nimport { snippet, toPosix } from './calls/shared.js'\n\n// gRPC `.proto` service/method extraction (ADR-123). gRPC used to engage only at\n// service grain — the client-stub detector in calls/grpc.ts maps a\n// `new OrderServiceClient()` to one `infra:grpc-service:*` node, and nothing read\n// the method surface at all. This producer reads the `.proto` service contract\n// as DATA (a bounded line-scan, no tree-sitter grammar — polyglot files are read\n// as data, CLAUDE.md) and materialises each `rpc` as a `GrpcMethodNode`. A proto\n// under a service's dir is owned through a `service ──CONTAINS──▶ method` edge; a\n// centralized proto that sits outside every service dir (otel-demo's `pb/demo.proto`,\n// a sibling of `src/`) mints the node alone, the OBSERVED span supplying the\n// service link (ADR-123 scan scope, #1459).\n//\n// This is the static half of two-sided gRPC observation: the node is keyed on the\n// fully-qualified `<package>.<Service>` name — the exact `rpc.service` an OBSERVED\n// execution span carries — so a declared method and its observed counterpart fuse\n// onto one node into a method-grain divergence (docs/contracts/otel-ingest.md\n// §gRPC methods). Scope is the service/method definitions only; message/field\n// grain, `import` resolution across proto files, and error-detail enrichment are\n// out of scope for this slice.\n\nconst PROTO_EXTENSION = '.proto'\n\n// A `.proto` service/method definition parsed out of one file.\nexport interface ExtractedGrpcMethod {\n  rpcService: string // fully-qualified `<package>.<Service>` (or bare `<Service>` when the file declares no package)\n  rpcMethod: string // bare method name, e.g. `GetOrder`\n  line: number // 1-indexed line the `rpc` is declared on\n  streaming?: true // `stream` on the request or the response (ADR-272)\n}\n\n// ── `.proto` parsing (data, not a grammar) ──────────────────────────────────\n\n// The file-level `package foo.bar;` declaration, if present. gRPC fully-qualifies\n// `rpc.service` as `<package>.<Service>`, so the package prefixes every service\n// name in the file. proto2/proto3 both use this single-line form.\nfunction packageOf(content: string): string | null {\n  const m = content.match(/^\\s*package\\s+([A-Za-z_][A-Za-z0-9_.]*)\\s*;/m)\n  return m ? m[1]! : null\n}\n\n// The 1-indexed line an absolute character offset falls on.\nfunction lineAt(content: string, offset: number): number {\n  return content.slice(0, offset).split('\\n').length\n}\n\n// Scan a `.proto` file's `service X { rpc M(Req) returns (Res); }` blocks and\n// emit one method per `rpc`. Brace-balanced so a service body is read to its\n// close; the `rpc` scan is confined to that body. Streaming qualifiers\n// (`rpc M(stream Req) returns (stream Res)`) don't change the method identity;\n// they mark the method `streaming` (ADR-272). Comment-only or option lines that merely mention\n// `rpc`/`service` don't match — both anchors require the keyword followed by an\n// identifier and the structural token (`{` for a service, `(` for an rpc).\nexport function grpcMethodsFromProto(content: string, fqPackage: string | null): ExtractedGrpcMethod[] {\n  const out: ExtractedGrpcMethod[] = []\n  const serviceRe = /\\bservice\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*\\{/g\n  let sm: RegExpExecArray | null\n  while ((sm = serviceRe.exec(content)) !== null) {\n    const serviceName = sm[1]!\n    const rpcService = fqPackage ? `${fqPackage}.${serviceName}` : serviceName\n    // Walk from the opening brace to its matching close, tracking depth so a\n    // nested block (an inline `option`/message) doesn't end the service early.\n    const bodyStart = serviceRe.lastIndex // index just past the `{`\n    let depth = 1\n    let i = bodyStart\n    for (; i < content.length && depth > 0; i++) {\n      const ch = content[i]\n      if (ch === '{') depth++\n      else if (ch === '}') depth--\n    }\n    const body = content.slice(bodyStart, i - 1)\n    const rpcRe = /\\brpc\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*\\(/g\n    let rm: RegExpExecArray | null\n    while ((rm = rpcRe.exec(body)) !== null) {\n      const rpcMethod = rm[1]!\n      const line = lineAt(content, bodyStart + rm.index)\n      // The signature runs to the `;` or `{` that ends the rpc; a `stream`\n      // qualifier on either side makes it a streaming method (ADR-272).\n      const rest = body.slice(rm.index)\n      const end = rest.search(/[;{]/)\n      const streaming = /\\bstream\\b/.test(end === -1 ? rest : rest.slice(0, end))\n      out.push({ rpcService, rpcMethod, line, ...(streaming ? { streaming: true } : {}) })\n    }\n    // Continue the outer scan past this service body.\n    serviceRe.lastIndex = i\n  }\n  return out\n}\n\n// ── file discovery ──────────────────────────────────────────────────────────\n\n// Walk a service directory for `.proto` files, honouring the shared ignore set\n// (node_modules, .git, …) and Python venvs the same way walkSourceFiles does.\n// `.proto` isn't a SERVICE_FILE_EXTENSION, so the source-file walker skips it —\n// this is a dedicated pass over the proto contract surface.\nasync function walkProtoFiles(dir: string, excludeDirs: string[] = []): Promise<string[]> {\n  // ADR-200 — skip nested discovered services' subtrees so an ancestor doesn't\n  // re-mint their `.proto` methods under itself.\n  const excluded = new Set(excludeDirs.map((d) => path.resolve(d)))\n  const out: string[] = []\n  async function walk(current: string): Promise<void> {\n    const entries = await fs.readdir(current, { withFileTypes: true }).catch(() => [])\n    for (const entry of entries) {\n      const full = path.join(current, entry.name)\n      if (entry.isDirectory()) {\n        if (IGNORED_DIRS.has(entry.name)) continue\n        if (excluded.has(path.resolve(full))) continue\n        if (await isPythonVenvDir(full)) continue\n        await walk(full)\n      } else if (entry.isFile() && path.extname(entry.name) === PROTO_EXTENSION && !excluded.has(path.resolve(full))) {\n        out.push(full)\n      }\n    }\n  }\n  await walk(dir)\n  return out\n}\n\n// ── producer ─────────────────────────────────────────────────────────────────\n\n// Read one `.proto`, parse its services/methods, and mint a `GrpcMethodNode` per\n// `rpc` (idempotent on the wire-canonical id). When `owner` is set — the proto sits\n// inside a discovered service's dir — also mint the static\n// `service ──CONTAINS──▶ method` edge. A centralized proto that no service owns\n// mints the node alone.\nasync function mintMethodsFromProto(\n  graph: NeatGraph,\n  protoPath: string,\n  relFile: string,\n  owner: DiscoveredService | null,\n  counters: { nodesAdded: number; edgesAdded: number },\n): Promise<void> {\n  let content: string\n  try {\n    content = await fs.readFile(protoPath, 'utf8')\n  } catch (err) {\n    recordExtractionError('proto extraction', protoPath, err)\n    return\n  }\n\n  let methods: ExtractedGrpcMethod[]\n  try {\n    methods = grpcMethodsFromProto(content, packageOf(content))\n  } catch (err) {\n    recordExtractionError('proto extraction', protoPath, err)\n    return\n  }\n  if (methods.length === 0) return\n\n  for (const method of methods) {\n    const mid = grpcMethodId(method.rpcService, method.rpcMethod)\n    if (!graph.hasNode(mid)) {\n      const node: GrpcMethodNode = {\n        id: mid,\n        type: NodeType.GrpcMethodNode,\n        name: `${method.rpcService}/${method.rpcMethod}`,\n        rpcService: method.rpcService,\n        rpcMethod: method.rpcMethod,\n        path: relFile,\n        line: method.line,\n        discoveredVia: 'static',\n        ...(method.streaming ? { streaming: true } : {}),\n      }\n      graph.addNode(mid, node)\n      counters.nodesAdded++\n    } else if (method.streaming) {\n      // An observed span may have minted the node first; the declaration still holds.\n      graph.mergeNodeAttributes(mid, { streaming: true })\n    }\n    if (!owner) continue\n    // `service ──CONTAINS──▶ method` — the service owns the methods its `.proto`\n    // declares, the same structural verb it has over its routes (ADR-119) and\n    // files (file-awareness.md §2). Evidence pinned to the `rpc` line. The node id\n    // is the wire-canonical FQN, so an OBSERVED execution span lands on this same\n    // node — declared and observed fuse.\n    const containsId = extractedEdgeId(owner.node.id, mid, EdgeType.CONTAINS)\n    if (!graph.hasEdge(containsId)) {\n      const edge: GraphEdge = {\n        id: containsId,\n        source: owner.node.id,\n        target: mid,\n        type: EdgeType.CONTAINS,\n        provenance: Provenance.EXTRACTED,\n        confidence: confidenceForExtracted('structural'),\n        evidence: {\n          file: relFile,\n          line: method.line,\n          snippet: snippet(content, method.line),\n        },\n      }\n      graph.addEdgeWithKey(containsId, owner.node.id, mid, edge)\n      counters.edgesAdded++\n    }\n  }\n}\n\nexport async function addGrpcMethods(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n  scanPath: string,\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  const counters = { nodesAdded: 0, edgesAdded: 0 }\n  // Resolved paths of every `.proto` a per-service walk has already claimed, so the\n  // project-root pass doesn't re-read one or shadow its `CONTAINS`.\n  const claimed = new Set<string>()\n\n  // Pass 1 — per service. A `.proto` under a service's own dir is that service's\n  // declared contract: mint the methods and the `service ──CONTAINS──▶ method`\n  // edge. ADR-255 narrows a shared-module binary to its own files through\n  // `excludeDirs`, so each binary claims only the protos it owns.\n  for (const service of services) {\n    const protoPaths = await walkProtoFiles(service.dir, service.excludeDirs)\n    for (const protoPath of protoPaths) {\n      // ADR-065 #1 — test-scope exclusion. A `.proto` under a test tree isn't the\n      // service's declared contract surface.\n      if (isTestPath(protoPath)) continue\n      claimed.add(path.resolve(protoPath))\n      await mintMethodsFromProto(\n        graph,\n        protoPath,\n        toPosix(path.relative(service.dir, protoPath)),\n        service,\n        counters,\n      )\n    }\n  }\n\n  // Pass 2 — project root (ADR-123 scan scope, #1459). A centralized contract that\n  // sits outside every service dir never reaches a per-service walk: otel-demo keeps\n  // its whole gRPC surface in `pb/demo.proto`, a sibling of `src/`, so none of the\n  // `src/<service>` dirs contain it and the `oteldemo.*` methods had no static twin\n  // at all. Scan the whole project root and mint the method node for any `.proto` no\n  // service claimed. Node only — there is no owning service dir to attribute a static\n  // `CONTAINS` to, and the OBSERVED SERVER span already carries the emitting service,\n  // so the node alone makes the observed methods two-sided (declared + observed on\n  // one id).\n  const rootProtos = await walkProtoFiles(scanPath)\n  for (const protoPath of rootProtos) {\n    if (isTestPath(protoPath)) continue\n    if (claimed.has(path.resolve(protoPath))) continue\n    await mintMethodsFromProto(\n      graph,\n      protoPath,\n      toPosix(path.relative(scanPath, protoPath)),\n      null,\n      counters,\n    )\n  }\n\n  return counters\n}\n","import type { GraphEdge, InfraNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  passesExtractedFloor,\n} from '@neat.is/types'\nimport { noteExtractedDropped, recordExtractionError } from '../errors.js'\nimport type { NeatGraph } from '../../graph.js'\nimport {\n  isTestPath,\n  makeEdgeId,\n  maskCommentsInSource,\n  type DiscoveredService,\n} from '../shared.js'\nimport { addHttpCallEdges } from './http.js'\nimport { addRouteCallEdges } from './route-match.js'\nimport { ensureFileNode, loadSourceFiles, toPosix, type ExternalEndpoint, type SourceFile } from './shared.js'\nimport { kafkaEndpointsFromFile } from './kafka.js'\nimport { redisEndpointsFromFile } from './redis.js'\nimport { awsEndpointsFromFile } from './aws.js'\nimport { grpcEndpointsFromFile } from './grpc.js'\nimport { supabaseEndpointsFromFile } from './supabase.js'\nimport { firestoreEndpointsFromFile, firestoreCrossFileEndpoints } from './firestore.js'\nimport { mongooseEndpointsFromFile, mongooseCrossFileEndpoints } from './mongoose.js'\nimport { sqlalchemyEndpointsFromFile, pythonOrmCrossFileEndpoints } from './sqlalchemy.js'\nimport { socketEndpointsFromFile } from './socket.js'\nimport { djangoOrmEndpointsFromFile } from './django-orm.js'\nimport { drizzleEndpointsFromFile } from './drizzle.js'\nimport { prismaColumnEndpoints } from './prisma.js'\nimport { railsSchemaEndpointsFromFile, railsModelEndpointsFromFile } from './activerecord.js'\nimport { laravelMigrationEndpointsFromFile, laravelModelEndpointsFromFile } from './eloquent.js'\nimport { foldColumns, foldSdkWrites } from '../../columns.js'\nimport { goSqlEndpointsFromFile } from './go.js'\nimport { gormEndpointsFromFile } from './gorm.js'\nimport { efcoreEndpointsFromFile } from './efcore.js'\nimport { mysqlJsEndpointsFromFile } from './mysql-js.js'\nimport { pythonDbapiEndpointsFromFile } from './dbapi-python.js'\nimport { jpaEndpoints } from './jpa.js'\n\nexport interface CallExtractResult {\n  nodesAdded: number\n  edgesAdded: number\n}\n\nfunction edgeTypeFromEndpoint(ep: ExternalEndpoint): (typeof EdgeType)[keyof typeof EdgeType] {\n  switch (ep.edgeType) {\n    case 'PUBLISHES_TO':\n      return EdgeType.PUBLISHES_TO\n    case 'CONSUMES_FROM':\n      return EdgeType.CONSUMES_FROM\n    default:\n      return EdgeType.CALLS\n  }\n}\n\nfunction isAwsKind(kind: string): boolean {\n  return (\n    kind.startsWith('aws-') ||\n    kind.startsWith('s3') ||\n    kind.startsWith('dynamodb')\n  )\n}\n\nasync function addExternalEndpointEdges(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<CallExtractResult> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n    const endpoints: ExternalEndpoint[] = []\n    const maskedFiles: SourceFile[] = []\n    for (const file of files) {\n      // ADR-065 #1 — test-scope exclusion. Tests stay registered as\n      // service-internal (via the file walk earlier); only outbound\n      // endpoint inference from them is filtered.\n      if (isTestPath(file.path)) continue\n      // ADR-065 #2 — comment-body exclusion. The regex-based extractors\n      // (redis / kafka / aws / grpc) scan raw file.content; URLs inside\n      // JSDoc / line / block comments leaked through to the graph in the\n      // v0.3.0 medusa run. Mask comments while preserving line/column for\n      // evidence line-mapping.\n      const masked = maskCommentsInSource(file.content)\n      const maskedFile = { path: file.path, content: masked }\n      maskedFiles.push(maskedFile)\n      endpoints.push(...kafkaEndpointsFromFile(maskedFile, service.dir))\n      endpoints.push(...redisEndpointsFromFile(maskedFile, service.dir))\n      endpoints.push(...awsEndpointsFromFile(maskedFile, service.dir))\n      endpoints.push(...grpcEndpointsFromFile(maskedFile, service.dir))\n      endpoints.push(...supabaseEndpointsFromFile(maskedFile, service.dir))\n      endpoints.push(...firestoreEndpointsFromFile(maskedFile, service.dir))\n      endpoints.push(...mongooseEndpointsFromFile(maskedFile, service.dir))\n      endpoints.push(...sqlalchemyEndpointsFromFile(maskedFile, service.dir))\n      endpoints.push(...djangoOrmEndpointsFromFile(maskedFile, service.dir))\n      endpoints.push(...drizzleEndpointsFromFile(maskedFile, service.dir))\n      try {\n        endpoints.push(...goSqlEndpointsFromFile(maskedFile, service.dir))\n      } catch (err) {\n        recordExtractionError('go SQL call extraction', file.path, err)\n      }\n      // JS/TS raw-SQL data axis (#1432). `mysql`/`mysql2` `.query`/`.execute` with a\n      // literal (or literal-headed, variable-resolved) statement → `sql-table` nodes +\n      // touched columns, the JS sibling of the Go database/sql reader above. Runs on\n      // the comment-masked copy like the other JS recognizers; wrapped because\n      // tree-sitter is a native module — a per-file failure must not abort the phase.\n      try {\n        endpoints.push(...mysqlJsEndpointsFromFile(maskedFile, service.dir))\n      } catch (err) {\n        recordExtractionError('mysql/mysql2 SQL call extraction', file.path, err)\n      }\n      // Go/GORM data axis (ADR-180). Model structs → `sql-table` nodes + literal\n      // columns. Parsed via tree-sitter-go from the raw file (not the JS-comment-\n      // masked copy), so Go `//` comments are excluded structurally as `comment`\n      // nodes. Wrapped because tree-sitter-go is a native module — a per-file\n      // failure must not abort the phase (ADR-055).\n      try {\n        endpoints.push(...gormEndpointsFromFile(file, service.dir))\n      } catch (err) {\n        recordExtractionError('gorm data-axis extraction', file.path, err)\n      }\n      // Rails ActiveRecord data axis (ADR-174). `db/schema.rb` tables + columns\n      // and the model→table link. Parsed via tree-sitter-ruby from the raw file\n      // (not the JS-comment-masked copy), so Ruby `#` comments are excluded\n      // structurally as `comment` nodes. Wrapped because tree-sitter-ruby is a\n      // native module — a per-file failure must not abort the phase (ADR-055).\n      try {\n        endpoints.push(...railsSchemaEndpointsFromFile(file, service.dir))\n        endpoints.push(...railsModelEndpointsFromFile(file, service.dir))\n      } catch (err) {\n        recordExtractionError('rails activerecord extraction', file.path, err)\n      }\n      // Laravel data axis (ADR-178). `database/migrations/*.php` Schema::create\n      // blueprints (tables + literal columns) and the `app/Models/*.php`\n      // Eloquent class→table link. Parsed via tree-sitter-php (`php_only`) from\n      // the raw file — PHP `//` / `#` comments are excluded structurally as\n      // `comment` nodes. Wrapped because tree-sitter-php is a native module — a\n      // per-file failure must not abort the phase (ADR-055).\n      try {\n        endpoints.push(...laravelMigrationEndpointsFromFile(file, service.dir))\n        endpoints.push(...laravelModelEndpointsFromFile(file, service.dir))\n      } catch (err) {\n        recordExtractionError('laravel eloquent extraction', file.path, err)\n      }\n      // C#/.NET EF Core data axis (ADR-203). `[Table(\"...\")]` annotations and\n      // `.ToTable(\"...\")` fluent calls → `sql-table` nodes. Parsed via\n      // tree-sitter-c-sharp from the raw file (not the JS-comment-masked copy), so\n      // C# `//` / `/* */` comments are excluded structurally as `comment` nodes.\n      // Wrapped because tree-sitter-c-sharp is a native module — a per-file failure\n      // must not abort the phase (ADR-055).\n      try {\n        endpoints.push(...efcoreEndpointsFromFile(file, service.dir))\n      } catch (err) {\n        recordExtractionError('efcore data-axis extraction', file.path, err)\n      }\n      // Python raw-socket dependencies. `socket.socket(...)` + `.connect((host, port))`\n      // → a `socket` endpoint — the bare-socket dependency the frameworked recognizers\n      // (grpc / redis / sqlalchemy) miss, so a custom line-protocol datastore call has a\n      // static twin its OBSERVED connection-refused can fuse onto. Parsed via\n      // tree-sitter-python from the raw file, so Python `#` comments are excluded\n      // structurally as `comment` nodes. Wrapped because tree-sitter-python is a native\n      // module — a per-file failure must not abort the phase (ADR-055).\n      try {\n        endpoints.push(...socketEndpointsFromFile(file, service.dir))\n      } catch (err) {\n        recordExtractionError('python socket call extraction', file.path, err)\n      }\n      // Python raw-SQL data axis (#1432). DB-API `cursor.execute`/`.executemany` with a\n      // literal (or literal-headed, variable-resolved) statement → `sql-table` nodes +\n      // touched columns, the Python sibling of the Go/JS raw-SQL readers. Parsed via\n      // tree-sitter-python from the raw file like the socket recognizer above (the\n      // JS-comment masker would corrupt Python `//` floor-division); wrapped because\n      // tree-sitter is a native module — a per-file failure must not abort the phase.\n      try {\n        endpoints.push(...pythonDbapiEndpointsFromFile(file, service.dir))\n      } catch (err) {\n        recordExtractionError('python dbapi SQL call extraction', file.path, err)\n      }\n    }\n    // Cross-file mongoose resolution (ADR-149) — a whole-program pass over the\n    // service's files, attributing a query in one file to a model defined in\n    // another via the import graph.\n    // Cross-file Firestore client resolution (#1223) — the near-universal Firebase\n    // layout exports one client (`export const db = getFirestore(app)`) and imports it\n    // everywhere else, so the per-file pass above claims none of those calls. Same\n    // whole-program shape as the mongoose pass below, applied to the client.\n    endpoints.push(...(await firestoreCrossFileEndpoints(maskedFiles, service.dir)))\n    endpoints.push(...(await mongooseCrossFileEndpoints(maskedFiles, service.dir)))\n    // Cross-file SQLAlchemy model→table query attribution (ADR-149 analog): a\n    // query file gets the table edge for a model imported from another file.\n    endpoints.push(...pythonOrmCrossFileEndpoints(maskedFiles, service.dir))\n    // JPA / Spring Data (Java): an entity's literal @Table name, attributed to the\n    // entity file and to each repository over it, across the service's files.\n    try {\n      endpoints.push(...jpaEndpoints(maskedFiles, service.dir))\n    } catch (err) {\n      recordExtractionError('jpa data-axis extraction', service.dir, err)\n    }\n    // Prisma declared columns (ADR-157 §3): `schema.prisma` is read as text —\n    // it isn't a source file the walker loads — so this runs once per service,\n    // reading each model's scalar fields as EXTRACTED columns at DB-name fidelity.\n    endpoints.push(...(await prismaColumnEndpoints(service.dir)))\n    if (endpoints.length === 0) continue\n\n    const seenEdges = new Set<string>()\n    for (const ep of endpoints) {\n      if (!graph.hasNode(ep.infraId)) {\n        const node: InfraNode = {\n          id: ep.infraId,\n          type: NodeType.InfraNode,\n          name: ep.name,\n          // #238 — `aws-*` covers AWS-SDK client kinds (aws-s3, aws-dynamodb,\n          // aws-cognito-identity-provider, …); `s3-` / `dynamodb-` cover the\n          // bucket / table kinds from aws.ts.\n          provider: isAwsKind(ep.kind) ? 'aws' : 'self',\n          kind: ep.kind,\n        }\n        graph.addNode(node.id, node)\n        nodesAdded++\n      }\n\n      // Column grain (ADR-157 §3): a schema-column producer (Drizzle) carries the\n      // declared columns at database-name fidelity. Fold them onto the table node\n      // with EXTRACTED provenance — whether the node was just minted here or\n      // already exists from an OBSERVED span, so the declared and observed columns\n      // fuse on one node and column-drift (§4) can read both sides. The\n      // definition's file:line rides the EXTRACTED edge minted below. Mutation is\n      // allowed here — extract/* is a lifecycle authority (lifecycle.md §3).\n      if (ep.columns && ep.columns.length > 0) {\n        const node = graph.getNodeAttributes(ep.infraId) as InfraNode\n        if (node.type === NodeType.InfraNode) {\n          graph.replaceNodeAttributes(ep.infraId, {\n            ...node,\n            columns: foldColumns(\n              node.columns,\n              ep.columns,\n              Provenance.EXTRACTED,\n              confidenceForExtracted(ep.confidenceKind),\n            ),\n          })\n        }\n      }\n\n      // Firestore write-SDK tags (ADR-167). A `firestore-collection` endpoint\n      // carries, per written field, which SDK wrote it (client vs admin) — the\n      // seam the field-guard policy (ADR-169) joins on. Fold it onto the columns\n      // the block above just landed, via the parallel `foldSdkWrites` — a separate\n      // firestore-gated pass so `foldColumns` and its fold block stay untouched.\n      // Gated on `ep.sdkWrites`, which only calls/firestore.ts populates.\n      if (ep.sdkWrites && Object.keys(ep.sdkWrites).length > 0) {\n        const node = graph.getNodeAttributes(ep.infraId) as InfraNode\n        if (node.type === NodeType.InfraNode) {\n          graph.replaceNodeAttributes(ep.infraId, {\n            ...node,\n            columns: foldSdkWrites(node.columns, ep.sdkWrites),\n          })\n        }\n      }\n\n      const edgeType = edgeTypeFromEndpoint(ep)\n      const confidence = confidenceForExtracted(ep.confidenceKind)\n      // File-first (file-awareness.md §1): the endpoint relationship originates\n      // from the file the call site lives in, with the owning service\n      // ──CONTAINS──▶ file edge alongside it (§2). File-node existence is\n      // independent of edge-target precision (ADR-089 amendment) — a matched\n      // call site is a parsed fact, so the FileNode + CONTAINS materialize\n      // regardless of how confident we are about the resolved target.\n      const relFile = toPosix(ep.evidence.file)\n      const { fileNodeId, nodesAdded: n, edgesAdded: e } = ensureFileNode(\n        graph,\n        service.pkg.name,\n        service.node.id,\n        relFile,\n      )\n      nodesAdded += n\n      edgesAdded += e\n      // Precision floor (ADR-066 §3). Only the file→target edge is gated:\n      // sub-threshold candidates are recorded as drops (banner accounting) and\n      // never added to the graph; the file and its call site still surface.\n      if (!passesExtractedFloor(confidence)) {\n        noteExtractedDropped({\n          source: fileNodeId,\n          target: ep.infraId,\n          type: edgeType,\n          confidence,\n          confidenceKind: ep.confidenceKind,\n          evidence: ep.evidence,\n        })\n        continue\n      }\n      const edgeId = makeEdgeId(fileNodeId, ep.infraId, edgeType)\n      if (seenEdges.has(edgeId)) continue\n      seenEdges.add(edgeId)\n      if (!graph.hasEdge(edgeId)) {\n        const edge: GraphEdge = {\n          id: edgeId,\n          source: fileNodeId,\n          target: ep.infraId,\n          type: edgeType,\n          provenance: Provenance.EXTRACTED,\n          confidence,\n          evidence: ep.evidence,\n        }\n        graph.addEdgeWithKey(edgeId, edge.source, edge.target, edge)\n        edgesAdded++\n      }\n    }\n  }\n  return { nodesAdded, edgesAdded }\n}\n\nexport async function addCallEdges(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<CallExtractResult> {\n  const http = await addHttpCallEdges(graph, services)\n  const ext = await addExternalEndpointEdges(graph, services)\n  // Cross-service contract matching (ADR-119). Runs after the RouteNodes are in\n  // the graph (addRoutes, a prior phase) so client call sites can be matched\n  // against the full route table, minting route-grained CALLS edges.\n  const routes = await addRouteCallEdges(graph, services)\n  return {\n    nodesAdded: http.nodesAdded + ext.nodesAdded + routes.nodesAdded,\n    edgesAdded: http.edgesAdded + ext.edgesAdded + routes.edgesAdded,\n  }\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport JavaScript from 'tree-sitter-javascript'\nimport TypeScript from 'tree-sitter-typescript'\nimport Python from 'tree-sitter-python'\nimport type { GraphEdge } from '@neat.is/types'\nimport {\n  EdgeType,\n  Provenance,\n  confidenceForExtracted,\n  passesExtractedFloor,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport {\n  isTestPath,\n  makeEdgeId,\n  urlMatchesHost,\n  type DiscoveredService,\n} from '../shared.js'\nimport { recordExtractionError, noteExtractedDropped } from '../errors.js'\nimport {\n  buildServiceHostIndex,\n  ensureFileNode,\n  loadSourceFiles,\n  snippet,\n  toPosix,\n} from './shared.js'\n\n// JS uses `string_fragment` for the textual interior of a template/string;\n// Python uses `string_content` inside a `string` node. Either way we want the\n// raw textual content (no quotes), so we accept both.\nconst STRING_LITERAL_NODE_TYPES = new Set(['string_fragment', 'string_content'])\n\n// ADR-065 #3 — JSX external-link exclusion. Tags whose URL-attr strings are\n// user-clickable hyperlinks, not service-to-service calls.\nconst JSX_EXTERNAL_LINK_TAGS = new Set(['a', 'Link', 'NavLink', 'ExternalLink', 'Anchor'])\n\n// Walk upward from a string-literal node to detect whether it sits inside a\n// JSX attribute on an external-link element. Returns true if the literal\n// should be filtered.\nfunction isInsideJsxExternalLink(node: Parser.SyntaxNode): boolean {\n  let cursor: Parser.SyntaxNode | null = node.parent\n  // Step out of the string wrapper if needed (parent is `string` /\n  // `template_string`).\n  while (cursor) {\n    if (cursor.type === 'jsx_attribute') {\n      // The element that owns this attribute. jsx_attribute lives inside\n      // jsx_opening_element / jsx_self_closing_element.\n      let owner: Parser.SyntaxNode | null = cursor.parent\n      while (owner && owner.type !== 'jsx_opening_element' && owner.type !== 'jsx_self_closing_element') {\n        owner = owner.parent\n      }\n      if (!owner) return false\n      // First named child of an opening/self-closing element is the tag name\n      // (`identifier` or `member_expression`).\n      const tagNode = owner.namedChild(0)\n      const tagName = tagNode?.text ?? ''\n      // For `<Foo.Bar>` we just want the rightmost ident; pick after the\n      // last dot.\n      const right = tagName.includes('.') ? tagName.split('.').pop()! : tagName\n      return JSX_EXTERNAL_LINK_TAGS.has(right)\n    }\n    cursor = cursor.parent\n  }\n  return false\n}\n\n// Collect (literal text, ast-node) pairs so the JSX-context check has the\n// node available. Comment tokens have no string_fragment / string_content\n// children in tree-sitter — JSDoc text lives inside `comment` nodes — so\n// comment-body exclusion comes for free with this AST walk (ADR-065 #2).\nfunction collectStringLiterals(\n  node: Parser.SyntaxNode,\n  out: { text: string; node: Parser.SyntaxNode }[],\n): void {\n  if (STRING_LITERAL_NODE_TYPES.has(node.type)) out.push({ text: node.text, node })\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (child) collectStringLiterals(child, out)\n  }\n}\n\n// A matched outbound call: the host the URL literal names and the 1-indexed\n// line it sits on. File-first extraction (file-awareness.md §1) originates a\n// CALLS edge from the file the call site lives in, so the position travels with\n// the host rather than being recovered after the fact.\nexport interface HttpCallSite {\n  host: string\n  line: number\n}\n\n// tree-sitter's node binding copies a string handed to `parser.parse` into a\n// fixed scratch buffer of ~32K code units and throws a bare \"Invalid argument\"\n// once the source is larger — it never names the size as the cause. NEAT's own\n// `cli.ts`, `ingest.ts`, and `installers/javascript.ts` all clear 40K, so the\n// http-call extractor was quietly skipping the three most interesting files in\n// the repo while dogfooding NEAT-on-NEAT. The callback form sidesteps the\n// buffer entirely: tree-sitter pulls the text in chunks we keep well under the\n// limit, so a file of any length parses. Chunking is by `.length` (UTF-16 code\n// units), which is exactly what the buffer counts.\nconst PARSE_CHUNK = 16384\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nexport function callsFromSource(\n  source: string,\n  parser: Parser,\n  knownHosts: Set<string>,\n): HttpCallSite[] {\n  const tree = parseSource(parser, source)\n  const literals: { text: string; node: Parser.SyntaxNode }[] = []\n  collectStringLiterals(tree.rootNode, literals)\n  const out: HttpCallSite[] = []\n  for (const lit of literals) {\n    // ADR-065 #3 — JSX external-link exclusion. URL strings on <a>, <Link>,\n    // <NavLink>, <ExternalLink>, <Anchor> are user-clickable hyperlinks, not\n    // service calls.\n    if (isInsideJsxExternalLink(lit.node)) continue\n    for (const host of knownHosts) {\n      // ADR-065 #5 — exact hostname match (not substring containment).\n      // `medusa.cloud` no longer matches `@medusajs/medusa`.\n      if (urlMatchesHost(lit.text, host)) {\n        out.push({ host, line: lit.node.startPosition.row + 1 })\n      }\n    }\n  }\n  return out\n}\n\n// Grammar per source extension. `.ts` / `.tsx` parse through\n// tree-sitter-typescript so TypeScript-only syntax — a `<T>expr` type\n// assertion, a `const` type parameter — parses cleanly instead of collapsing\n// into an ERROR node that can swallow a nearby URL literal and undercount CALLS\n// (issue #883). The JS grammar survives *most* TypeScript files but not all;\n// symbols.ts (ADR-158), drizzle.ts, zod-shapes.ts, and actions.ts already pick\n// their grammar by extension for the same reason. `.py` stays on\n// tree-sitter-python; anything else falls back to JavaScript, matching the\n// prior behaviour for non-mapped extensions.\nconst GRAMMAR_BY_EXT: Record<string, typeof JavaScript> = {\n  '.ts': TypeScript.typescript,\n  '.tsx': TypeScript.tsx,\n  '.js': JavaScript,\n  '.jsx': JavaScript,\n  '.mjs': JavaScript,\n  '.cjs': JavaScript,\n  '.py': Python,\n}\n\n// One Parser per grammar, created on first use and reused across files — a\n// Parser is reusable once its language is set, so the cache keys on the grammar\n// object rather than re-instantiating per file.\nfunction parserForExt(ext: string, cache: Map<unknown, Parser>): Parser {\n  const grammar = GRAMMAR_BY_EXT[ext] ?? JavaScript\n  let parser = cache.get(grammar)\n  if (!parser) {\n    parser = new Parser()\n    parser.setLanguage(grammar)\n    cache.set(grammar, parser)\n  }\n  return parser\n}\n\n// HTTP CALLS via URL hostname match. Parser is picked per file extension:\n// .py uses tree-sitter-python; everything else uses tree-sitter-javascript.\n//\n// File-first (file-awareness.md §1): each matched call site originates a\n// `file:<svc>:<relPath> ──CALLS──▶ target` edge plus the owning service's\n// CONTAINS edge, rather than collapsing every call in a service to one\n// service-level edge.\n//\n// File-node existence is independent of edge-target precision (file-awareness.md\n// §1, ADR-089 amendment). A matched call site is a parsed fact — the file and\n// its `service ──CONTAINS──▶ file` edge are certain regardless of how confident\n// we are about *what* it calls. So the FileNode + CONTAINS materialize for every\n// matched site; only the file→target CALLS edge is subject to the precision\n// floor. A scheme-qualified URL literal to a registered service grades at the\n// floor (url-literal-service-target, 0.7) so the declared HTTP dependency enters\n// the graph; if the floor is raised past it for diagnostics the file and its\n// call site still surface, without claiming the resolved target.\nexport async function addHttpCallEdges(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  // One reusable parser per grammar, picked by file extension (see\n  // GRAMMAR_BY_EXT). `.ts` / `.tsx` ride tree-sitter-typescript so TypeScript\n  // syntax doesn't drop URL literals (#883).\n  const parserCache = new Map<unknown, Parser>()\n\n  // Host → owning ServiceNode id (ADR-065 #5), shared with the route-matching\n  // producer so both resolve a URL's host to a service the same way.\n  const { knownHosts, hostToNodeId } = buildServiceHostIndex(services)\n\n  let nodesAdded = 0\n  let edgesAdded = 0\n  for (const service of services) {\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n    // File grain: one file→target CALLS per (file, target) pair, even when a\n    // file names the same host on several lines (function-level is deferred).\n    const seen = new Set<string>()\n    for (const file of files) {\n      // ADR-065 #1 — test-scope exclusion.\n      if (isTestPath(file.path)) continue\n      const parser = parserForExt(path.extname(file.path), parserCache)\n      let sites: HttpCallSite[]\n      try {\n        sites = callsFromSource(file.content, parser, knownHosts)\n      } catch (err) {\n        recordExtractionError('http call extraction', file.path, err)\n        continue\n      }\n      if (sites.length === 0) continue\n      const relFile = toPosix(path.relative(service.dir, file.path))\n      for (const site of sites) {\n        const targetId = hostToNodeId.get(site.host)\n        if (!targetId || targetId === service.node.id) continue\n        const dedupKey = `${relFile}|${targetId}`\n        if (seen.has(dedupKey)) continue\n        seen.add(dedupKey)\n        // A scheme-qualified URL literal that resolves to a registered service\n        // is a declared HTTP dependency (static-extraction contract §5). It\n        // grades at the precision floor rather than below it, so the EXTRACTED\n        // CALLS edge enters the graph and missing-observed can flag a declared-\n        // but-never-driven upstream (issue #592). Still below structural /\n        // verified-call-site: no call expression wraps the literal.\n        const confidence = confidenceForExtracted('url-literal-service-target')\n        const ev = {\n          file: relFile,\n          line: site.line,\n          snippet: snippet(file.content, site.line),\n        }\n        // The matched call site is a parsed fact: materialize the FileNode and\n        // its `service ──CONTAINS──▶ file` edge regardless of target precision\n        // (file-awareness.md §1, ADR-089 amendment). The file surfaces even\n        // when the resolved target sits below the floor.\n        const { fileNodeId, nodesAdded: n, edgesAdded: e } = ensureFileNode(\n          graph,\n          service.pkg.name,\n          service.node.id,\n          relFile,\n        )\n        nodesAdded += n\n        edgesAdded += e\n        // The file→target CALLS edge alone is subject to the precision floor.\n        // A sub-floor target is recorded as a drop (banner accounting) and not\n        // claimed as a resolved edge — the file and its call site still stand.\n        if (!passesExtractedFloor(confidence)) {\n          noteExtractedDropped({\n            source: fileNodeId,\n            target: targetId,\n            type: EdgeType.CALLS,\n            confidence,\n            confidenceKind: 'url-literal-service-target',\n            evidence: ev,\n          })\n          continue\n        }\n        const edgeId = makeEdgeId(fileNodeId, targetId, EdgeType.CALLS)\n        if (!graph.hasEdge(edgeId)) {\n          const edge: GraphEdge = {\n            id: edgeId,\n            source: fileNodeId,\n            target: targetId,\n            type: EdgeType.CALLS,\n            provenance: Provenance.EXTRACTED,\n            confidence,\n            evidence: ev,\n          }\n          graph.addEdgeWithKey(edgeId, fileNodeId, targetId, edge)\n          edgesAdded++\n        }\n      }\n    }\n  }\n  return { nodesAdded, edgesAdded }\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport JavaScript from 'tree-sitter-javascript'\nimport type { ExtractedConfidenceKind, GraphEdge, RouteNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  passesExtractedFloor,\n  serviceId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { isTestPath, makeEdgeId, urlMatchesHost, type DiscoveredService } from '../shared.js'\nimport { recordExtractionError, noteExtractedDropped } from '../errors.js'\nimport { normalizePathTemplate } from '../routes.js'\nimport {\n  buildServiceHostIndex,\n  ensureFileNode,\n  loadSourceFiles,\n  snippet,\n  toPosix,\n} from './shared.js'\n\n// Cross-service contract matching (ADR-119). This is the bridge between the two\n// static islands: a client call site names a URL (host + method + path); a\n// server RouteNode (extracted by routes.ts) declares (method, path-template).\n// When a client call's (host→service, method, normalised path) resolves to a\n// server route, this producer mints a route-grained EXTRACTED CALLS edge from\n// the client's FileNode to the server's RouteNode. It reuses the host→service\n// resolution the HTTP producers share (buildServiceHostIndex / urlMatchesHost),\n// adding path-template matching for the route half.\n//\n// The edge pairs with the OBSERVED server-span edge landing on the same\n// RouteNode (#576), giving get_divergences a file-precise, two-sided comparison\n// at route grain instead of only at service grain.\n//\n// Mainstream clients only: `fetch`, `axios` (default instance + method calls),\n// and node `http`/`https` `.request`/`.get`. The host and path must sit in the\n// same URL literal (or template literal) for a match — split base-URL + path\n// across variables is out of scope for this slice.\n\nconst PARSE_CHUNK = 16384\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nfunction makeJsParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(JavaScript)\n  return p\n}\n\nconst JS_CLIENT_EXTENSIONS = new Set(['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx'])\nconst AXIOS_METHODS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'request'])\n\nexport interface ClientCallSite {\n  // The known host the URL named (basename or pkg name), or null when the base\n  // URL was an interpolation we couldn't resolve — an approximate call site with\n  // no resolvable target (ADR-219).\n  host: string | null\n  method?: string // upper-cased; undefined when not statically determinable\n  pathTemplate: string // the URL path, with `:param` for unresolved interpolations; '' when the host is unresolved\n  line: number\n  snippet: string\n  // Reconstruction fidelity (ADR-219). True when a load-bearing interpolation in\n  // the URL couldn't be resolved statically, so any match rests on shape rather\n  // than literal evidence.\n  approximate: boolean\n  reason?: string // why the reconstruction was approximated (diagnostic)\n}\n\n// ── AST helpers ─────────────────────────────────────────────────────────────\n\nfunction walk(node: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (child) walk(child, visit)\n  }\n}\n\n// Resolve an expression node to a static string when the file alone determines\n// it: a string / no-substitution template literal, an identifier bound to one\n// earlier in the file, or the literal side of a `||` / `??` default (the\n// `process.env.X || 'http://localhost'` shape). Returns null for anything\n// computed at runtime. This is what turns an interpolated base URL held in a\n// `const` back into a real host instead of a `:param` (ADR-219).\nfunction resolveStaticString(\n  node: Parser.SyntaxNode | null,\n  constMap: Map<string, string>,\n  depth = 0,\n): string | null {\n  if (!node || depth > 4) return null\n  if (node.type === 'string') return stringText(node)\n  if (node.type === 'template_string') {\n    let out = ''\n    let sawSub = false\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (!child) continue\n      if (child.type === 'string_fragment') out += child.text\n      else if (child.type === 'template_substitution') sawSub = true\n    }\n    return sawSub ? null : out\n  }\n  if (node.type === 'identifier') return constMap.get(node.text) ?? null\n  if (node.type === 'binary_expression') {\n    // `a || b` / `a ?? b` — take whichever side resolves. Covers an env read\n    // with a literal dev default, where the literal is the statically-known value.\n    const left = resolveStaticString(node.childForFieldName('left'), constMap, depth + 1)\n    if (left !== null) return left\n    return resolveStaticString(node.childForFieldName('right'), constMap, depth + 1)\n  }\n  if (node.type === 'parenthesized_expression') {\n    return resolveStaticString(node.namedChild(0), constMap, depth + 1)\n  }\n  return null\n}\n\n// Build identifier → static-string bindings from the file's declarations, so an\n// interpolated base URL held in a variable (`const API_BASE = 'http://api'`) can\n// be substituted back into the URL. Document-order pass; later writes win. This\n// deliberately doesn't model block scope or reassignment — the target is the\n// common module-level base-URL const, not a general dataflow.\nfunction collectStaticStringBindings(root: Parser.SyntaxNode): Map<string, string> {\n  const map = new Map<string, string>()\n  walk(root, (node) => {\n    if (node.type !== 'variable_declarator') return\n    const name = node.childForFieldName('name')\n    if (!name || name.type !== 'identifier') return\n    const resolved = resolveStaticString(node.childForFieldName('value'), map)\n    if (resolved !== null) map.set(name.text, resolved)\n  })\n  return map\n}\n\n// Reconstruct the URL text a string / template-string argument names, resolving\n// interpolations back to their static values where the file determines them (a\n// base URL held in a const, ADR-219). A substitution that stays unresolvable\n// becomes `:param` and marks the result approximate: `/users/${id}` →\n// `/users/:param` (approximate), `${API_BASE}/x` with `API_BASE` a const → the\n// real base + `/x` (exact). Returns null for anything that isn't a string-ish\n// literal.\nfunction reconstructUrl(\n  node: Parser.SyntaxNode,\n  constMap: Map<string, string>,\n): { url: string; approximate: boolean } | null {\n  if (node.type === 'string') {\n    const s = stringText(node)\n    return s === null ? null : { url: s, approximate: false }\n  }\n  if (node.type === 'template_string') {\n    let out = ''\n    let approximate = false\n    let sawPart = false\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (!child) continue\n      if (child.type === 'string_fragment') {\n        out += child.text\n        sawPart = true\n      } else if (child.type === 'template_substitution') {\n        sawPart = true\n        const resolved = resolveStaticString(child.namedChild(0), constMap)\n        if (resolved !== null) out += resolved\n        else {\n          out += ':param'\n          approximate = true\n        }\n      }\n    }\n    // A template with no fragments/subs (empty) — fall back to stripped text.\n    if (!sawPart) {\n      const raw = node.text\n      return { url: raw.length >= 2 ? raw.slice(1, -1) : '', approximate: false }\n    }\n    return { url: out, approximate }\n  }\n  return null\n}\n\n// Read the `method` string off an options / config object (`{ method: 'POST' }`).\nfunction methodFromOptions(objNode: Parser.SyntaxNode): string | undefined {\n  for (let i = 0; i < objNode.namedChildCount; i++) {\n    const pair = objNode.namedChild(i)\n    if (!pair || pair.type !== 'pair') continue\n    const k = pair.childForFieldName('key')\n    const kText = k ? (k.type === 'string' ? stringText(k) : k.text) : null\n    if (kText !== 'method') continue\n    const v = pair.childForFieldName('value')\n    if (v && (v.type === 'string' || v.type === 'template_string')) {\n      const s = stringText(v)\n      return s ? s.toUpperCase() : undefined\n    }\n  }\n  return undefined\n}\n\nfunction stringText(node: Parser.SyntaxNode): string | null {\n  if (node.type === 'string') {\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (child?.type === 'string_fragment') return child.text\n    }\n    return ''\n  }\n  return null\n}\n\n// The URL string a config object names (`axios({ url: '…', method })`).\nfunction urlNodeFromConfig(objNode: Parser.SyntaxNode): Parser.SyntaxNode | null {\n  for (let i = 0; i < objNode.namedChildCount; i++) {\n    const pair = objNode.namedChild(i)\n    if (!pair || pair.type !== 'pair') continue\n    const k = pair.childForFieldName('key')\n    const kText = k ? (k.type === 'string' ? stringText(k) : k.text) : null\n    if (kText === 'url') return pair.childForFieldName('value')\n  }\n  return null\n}\n\n// Parse the path out of a reconstructed URL string. Returns null when the string\n// isn't URL-shaped (no scheme + host). `:param` in the path survives parsing.\nfunction pathOf(urlStr: string): string | null {\n  try {\n    const candidate = urlStr.startsWith('//') ? `http:${urlStr}` : urlStr\n    const parsed = new URL(candidate)\n    return parsed.pathname || '/'\n  } catch {\n    return null\n  }\n}\n\n// Resolve which known host a reconstructed URL names (ADR-065 #5 — scheme +\n// exact hostname). Returns the host token or null.\nfunction matchHost(urlStr: string, knownHosts: Set<string>): string | null {\n  for (const host of knownHosts) {\n    if (urlMatchesHost(urlStr, host)) return host\n  }\n  return null\n}\n\n// Whether the authority (host[:port]) slot of a reconstructed URL is an\n// unresolved interpolation rather than a literal host. Distinguishes a base URL\n// that couldn't be resolved (`:param/charges`, `${base}` unresolved) — which we\n// surface as an approximate diagnostic — from a literal external host that\n// simply isn't one of our services (`https://stripe.com/${id}`), which stays a\n// silent skip (ADR-219).\nfunction hostSlotUnresolved(url: string): boolean {\n  const schemeRel = url.indexOf('//')\n  let authority: string\n  if (schemeRel >= 0) {\n    const rest = url.slice(schemeRel + 2)\n    const slash = rest.indexOf('/')\n    authority = slash >= 0 ? rest.slice(0, slash) : rest\n  } else {\n    const slash = url.indexOf('/')\n    authority = slash >= 0 ? url.slice(0, slash) : url\n  }\n  return authority.length === 0 || authority.includes(':param')\n}\n\n// Whether a reconstructed path carries at least one literal segment to anchor\n// which route it names. A path that is entirely dynamic once normalised — a lone\n// `/:param` from a computed first segment — matches any same-arity `/:id` route\n// with no literal evidence, so it must not mint a confident edge (ADR-219). A\n// literal segment (`/charges/:param`) pins the match to a specific route family.\nfunction pathHasLiteralAnchor(pathTemplate: string): boolean {\n  const segs = normalizePathTemplate(pathTemplate)\n    .split('/')\n    .filter((s) => s.length > 0)\n  if (segs.length === 0) return false\n  return segs.some((s) => s !== ':param')\n}\n\n// ── client call-site recognition ────────────────────────────────────────────\n\n// Extract every recognised HTTP client call site whose URL literal names a\n// known host. Each site carries the method (when statically determinable) and\n// the path-template, ready to be matched against the server route table.\nexport function clientCallSitesFromSource(\n  source: string,\n  parser: Parser,\n  knownHosts: Set<string>,\n): ClientCallSite[] {\n  const tree = parseSource(parser, source)\n  const out: ClientCallSite[] = []\n  // File-level static bindings, so an interpolated base URL held in a const\n  // resolves back to its real host instead of collapsing to `:param` (ADR-219).\n  const constMap = collectStaticStringBindings(tree.rootNode)\n\n  const push = (\n    urlNode: Parser.SyntaxNode,\n    method: string | undefined,\n    callNode: Parser.SyntaxNode,\n  ): void => {\n    const rec = reconstructUrl(urlNode, constMap)\n    if (!rec) return\n    const line = callNode.startPosition.row + 1\n    const host = matchHost(rec.url, knownHosts)\n    if (host === null) {\n      // No known host resolved. When the authority itself was an unresolved\n      // interpolation, surface it as an approximate call site — never a silent\n      // drop (ADR-219). A literal external host that just isn't one of our\n      // services stays a silent skip.\n      if (rec.approximate && hostSlotUnresolved(rec.url)) {\n        out.push({\n          host: null,\n          method,\n          pathTemplate: '',\n          line,\n          snippet: snippet(source, line),\n          approximate: true,\n          reason: 'base URL interpolation could not be resolved statically',\n        })\n      }\n      return\n    }\n    const p = pathOf(rec.url)\n    if (p === null) return\n    out.push({\n      host,\n      method,\n      pathTemplate: p,\n      line,\n      snippet: snippet(source, line),\n      approximate: rec.approximate,\n      reason: rec.approximate\n        ? 'path segment interpolation could not be resolved statically'\n        : undefined,\n    })\n  }\n\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'call_expression') return\n    const fn = node.childForFieldName('function')\n    if (!fn) return\n    const args = node.childForFieldName('arguments')\n    const first = args?.namedChild(0)\n    if (!first) return\n\n    // fetch(url, opts?) — global or member (globalThis.fetch).\n    const fnName =\n      fn.type === 'identifier'\n        ? fn.text\n        : fn.type === 'member_expression'\n          ? (fn.childForFieldName('property')?.text ?? '')\n          : ''\n\n    if (fn.type === 'identifier' && fnName === 'fetch') {\n      const opts = args?.namedChild(1)\n      const method = opts && opts.type === 'object' ? (methodFromOptions(opts) ?? 'GET') : 'GET'\n      push(first, method, node)\n      return\n    }\n\n    // axios(url | config) — default instance called directly.\n    if (fn.type === 'identifier' && fnName === 'axios') {\n      if (first.type === 'object') {\n        const urlNode = urlNodeFromConfig(first)\n        if (urlNode) push(urlNode, methodFromOptions(first) ?? 'GET', node)\n      } else {\n        const opts = args?.namedChild(1)\n        const method = opts && opts.type === 'object' ? (methodFromOptions(opts) ?? 'GET') : 'GET'\n        push(first, method, node)\n      }\n      return\n    }\n\n    if (fn.type === 'member_expression') {\n      const obj = fn.childForFieldName('object')\n      const objName = obj?.text ?? ''\n\n      // axios.get('/x') / axios.post('/x', body) / axios.request({ url, method }).\n      if (objName === 'axios' && AXIOS_METHODS.has(fnName)) {\n        if (fnName === 'request' && first.type === 'object') {\n          const urlNode = urlNodeFromConfig(first)\n          if (urlNode) push(urlNode, methodFromOptions(first) ?? 'GET', node)\n        } else {\n          push(first, fnName.toUpperCase(), node)\n        }\n        return\n      }\n\n      // node http/https .request(url, …) / .get(url, …).\n      if ((objName === 'http' || objName === 'https') && (fnName === 'request' || fnName === 'get')) {\n        const opts = args?.namedChild(1)\n        const method =\n          opts && opts.type === 'object'\n            ? (methodFromOptions(opts) ?? (fnName === 'get' ? 'GET' : 'GET'))\n            : 'GET'\n        push(first, method, node)\n        return\n      }\n    }\n  })\n\n  return out\n}\n\n// ── route index + matching ──────────────────────────────────────────────────\n\ninterface RouteEntry {\n  method: string // upper, or 'ALL'\n  normalizedPath: string\n  routeNodeId: string\n}\n\n// Group every RouteNode in the graph by its owning ServiceNode id, keyed for\n// (method, normalised-path) lookup. Built once per pass so client matching is a\n// map read, not a graph scan per call site.\nfunction buildRouteIndex(graph: NeatGraph): Map<string, RouteEntry[]> {\n  const index = new Map<string, RouteEntry[]>()\n  graph.forEachNode((_id, attrs) => {\n    const node = attrs as unknown as { type?: string }\n    if (node.type !== NodeType.RouteNode) return\n    const route = attrs as unknown as RouteNode\n    const owner = serviceId(route.service)\n    const entry: RouteEntry = {\n      method: route.method.toUpperCase(),\n      normalizedPath: normalizePathTemplate(route.pathTemplate),\n      routeNodeId: route.id,\n    }\n    const list = index.get(owner)\n    if (list) list.push(entry)\n    else index.set(owner, [entry])\n  })\n  return index\n}\n\n// A client call matches a route when the normalised paths agree and the methods\n// are compatible: exact, or the route is method-agnostic (`ALL`), or the client\n// method couldn't be read statically.\nfunction findRoute(\n  entries: RouteEntry[],\n  method: string | undefined,\n  normalizedPath: string,\n): RouteEntry | undefined {\n  return entries.find(\n    (e) =>\n      e.normalizedPath === normalizedPath &&\n      (e.method === 'ALL' || method === undefined || e.method === method),\n  )\n}\n\nexport async function addRouteCallEdges(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  const jsParser = makeJsParser()\n  const { knownHosts, hostToNodeId } = buildServiceHostIndex(services)\n  const routeIndex = buildRouteIndex(graph)\n  if (routeIndex.size === 0) return { nodesAdded: 0, edgesAdded: 0 }\n\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n    // One edge per (client file, route) pair even if a file calls the route on\n    // several lines (function grain is deferred, matching http.ts).\n    const seen = new Set<string>()\n    for (const file of files) {\n      // ADR-065 #1 — test-scope exclusion.\n      if (isTestPath(file.path)) continue\n      if (!JS_CLIENT_EXTENSIONS.has(path.extname(file.path))) continue\n\n      let sites: ClientCallSite[]\n      try {\n        sites = clientCallSitesFromSource(file.content, jsParser, knownHosts)\n      } catch (err) {\n        recordExtractionError('route-match call extraction', file.path, err)\n        continue\n      }\n      if (sites.length === 0) continue\n\n      const relFile = toPosix(path.relative(service.dir, file.path))\n      for (const site of sites) {\n        // An unresolved base URL has no host to attribute the call to. It is\n        // still a recognised call site (file-awareness §1), so materialise the\n        // file and record an approximate drop — visible under the rejected log /\n        // diagnostic floor, never a silent miss (ADR-219).\n        if (site.host === null) {\n          const dedupKey = `${relFile}|unresolved-host`\n          if (seen.has(dedupKey)) continue\n          seen.add(dedupKey)\n          const { fileNodeId, nodesAdded: n, edgesAdded: e } = ensureFileNode(\n            graph,\n            service.pkg.name,\n            service.node.id,\n            relFile,\n          )\n          nodesAdded += n\n          edgesAdded += e\n          noteExtractedDropped({\n            source: fileNodeId,\n            target: 'route:unresolved',\n            type: EdgeType.CALLS,\n            confidence: confidenceForExtracted('reconstructed-approximate'),\n            confidenceKind: 'reconstructed-approximate',\n            evidence: {\n              file: relFile,\n              line: site.line,\n              snippet: site.snippet,\n              method: site.method,\n              approximate: true,\n              reason: site.reason,\n            },\n          })\n          continue\n        }\n\n        const serverServiceId = hostToNodeId.get(site.host)\n        // Skip a self-call (intra-service — no cross-service contract to match,\n        // mirroring http.ts).\n        if (!serverServiceId || serverServiceId === service.node.id) continue\n        const entries = routeIndex.get(serverServiceId)\n        if (!entries) continue\n        const normalizedPath = normalizePathTemplate(site.pathTemplate)\n        const match = findRoute(entries, site.method, normalizedPath)\n        if (!match) continue\n\n        const dedupKey = `${relFile}|${match.routeNodeId}`\n        if (seen.has(dedupKey)) continue\n        seen.add(dedupKey)\n\n        // The matched call site is a parsed fact — the client FileNode and its\n        // service ──CONTAINS──▶ file edge materialise regardless (file-awareness\n        // §1). Only the file→route edge is gated by the precision floor.\n        const { fileNodeId, nodesAdded: n, edgesAdded: e } = ensureFileNode(\n          graph,\n          service.pkg.name,\n          service.node.id,\n          relFile,\n        )\n        nodesAdded += n\n        edgesAdded += e\n\n        // Reconstruction-fidelity grade (ADR-219). A fully-resolved URL — literal,\n        // or with every interpolation resolved from scope — grades\n        // verified-call-site (0.85): both endpoints are recognised and the client\n        // URL is faithful. A URL that stayed approximate keeps that grade only\n        // when a literal path segment anchors which route it names\n        // (`/charges/:param`); an all-dynamic path (`/:param` from a computed\n        // segment) has no literal evidence of the target and grades\n        // reconstructed-approximate, below the precision floor — refused under the\n        // default floor, visible with its reason when the floor is lowered.\n        const anchored = pathHasLiteralAnchor(site.pathTemplate)\n        const confidenceKind: ExtractedConfidenceKind =\n          site.approximate && !anchored ? 'reconstructed-approximate' : 'verified-call-site'\n        const confidence = confidenceForExtracted(confidenceKind)\n        const ev = {\n          file: relFile,\n          line: site.line,\n          snippet: site.snippet,\n          method: site.method ?? match.method,\n          pathTemplate: site.pathTemplate,\n          ...(confidenceKind === 'reconstructed-approximate'\n            ? { approximate: true, reason: site.reason }\n            : {}),\n        }\n        if (!passesExtractedFloor(confidence)) {\n          noteExtractedDropped({\n            source: fileNodeId,\n            target: match.routeNodeId,\n            type: EdgeType.CALLS,\n            confidence,\n            confidenceKind,\n            evidence: ev,\n          })\n          continue\n        }\n        const edgeId = makeEdgeId(fileNodeId, match.routeNodeId, EdgeType.CALLS)\n        if (!graph.hasEdge(edgeId)) {\n          const edge: GraphEdge = {\n            id: edgeId,\n            source: fileNodeId,\n            target: match.routeNodeId,\n            type: EdgeType.CALLS,\n            provenance: Provenance.EXTRACTED,\n            confidence,\n            evidence: ev,\n          }\n          graph.addEdgeWithKey(edgeId, fileNodeId, match.routeNodeId, edge)\n          edgesAdded++\n        }\n      }\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import path from 'node:path'\nimport { infraId } from '@neat.is/types'\nimport { lineOf, snippet, type ExternalEndpoint, type SourceFile } from './shared.js'\n\n// Match `producer.send({ topic: \"orders\" ... })` and `producer.send({\n// topic: 'orders' })` plus the two-arg form `producer.send(\"orders\", ...)`.\n// Kafka client libraries vary; these two forms cover kafkajs + node-rdkafka\n// well enough for static extraction. Same shape covers consumer.subscribe.\nconst PRODUCER_TOPIC_RE =\n  /(?:producer|kafkaProducer)[\\s\\S]{0,40}?\\.send\\s*\\(\\s*\\{[\\s\\S]{0,200}?topic\\s*:\\s*['\"`]([^'\"`]+)['\"`]/g\nconst CONSUMER_TOPIC_RE =\n  /(?:consumer|kafkaConsumer)[\\s\\S]{0,40}?\\.(?:subscribe|run)\\s*\\(\\s*\\{[\\s\\S]{0,200}?topic[s]?\\s*:\\s*(?:\\[\\s*)?['\"`]([^'\"`]+)['\"`]/g\n\n// --- Go (Sarama) ---\n//\n// The otel-demo `checkout` service is Go using IBM/Shopify Sarama; the JS regexes\n// above never match its `sarama.ProducerMessage{Topic: \"orders\"}` shape, so the\n// observed `PUBLISHES_TO infra:kafka-topic:orders` edge orphaned with no static\n// twin. These read the Go call sites as data — the same \"polyglot files are read,\n// the extractor stays TypeScript\" approach proto.ts uses — and mint the SAME\n// `infra:kafka-topic:<topic>` node the JS path and the OBSERVED span land on, so\n// declared and observed queue topology fuse on one node.\n//\n// Everything below is gated on a real Sarama import: without it an arbitrary Go\n// struct named `ProducerMessage` or any `.Consume(...)` method would mint a\n// phantom topic. This mirrors the import gate calls/go.ts and routes.ts use.\nconst SARAMA_IMPORT_RE = /\"[^\"]*\\/sarama\"/\n\n// Producer: `sarama.ProducerMessage{Topic: \"orders\"}` (sync SendMessage) and\n// `producer.Input() <- &sarama.ProducerMessage{Topic: topicVar}` (async). The\n// `Topic` field can sit anywhere in the struct literal, so scan a bounded window\n// for it and capture either a string literal (interpreted `\"x\"` or raw `` `x` ``)\n// or a bare identifier we resolve to an in-file literal below.\nconst GO_PRODUCER_RE =\n  /ProducerMessage\\s*\\{[\\s\\S]{0,300}?\\bTopic\\s*:\\s*(?:\"([^\"]+)\"|`([^`]+)`|([A-Za-z_]\\w*))/g\n\n// Consumer group: `consumerGroup.Consume(ctx, []string{\"orders\"}, handler)`. The\n// topic list is the `[]string{...}` argument; it may hold literals or identifiers.\nconst GO_CONSUMER_RE = /\\.Consume\\s*\\([\\s\\S]{0,120}?\\[\\]string\\s*\\{([^}]*)\\}/g\n\n// Every string literal (interpreted or raw) inside a captured `[]string{...}` body.\nconst GO_STRING_LITERAL_RE = /\"([^\"]+)\"|`([^`]+)`/g\n\n// A bare identifier — the fallback when the topic is a const/var rather than a\n// literal at the call site.\nconst GO_IDENT_RE = /[A-Za-z_]\\w*/g\n\nfunction findAll(re: RegExp, text: string): { topic: string; index: number }[] {\n  re.lastIndex = 0\n  const out: { topic: string; index: number }[] = []\n  let m: RegExpExecArray | null\n  while ((m = re.exec(text)) !== null) {\n    out.push({ topic: m[1]!, index: m.index })\n  }\n  return out\n}\n\n// Resolve a Go identifier to an in-file string literal — `topic := \"orders\"`,\n// `topic = \"orders\"`, `const KafkaTopic = \"orders\"` (const-block members read as\n// `KafkaTopic = \"orders\"`), and typed `var topic string = \"orders\"`. A value that\n// isn't an in-file literal — `topic := os.Getenv(\"KAFKA_TOPIC\")`, a computed\n// string — has no literal RHS and stays unresolved rather than guessed: NEAT would\n// be inventing a topic name it cannot see.\nfunction resolveGoLiteral(ident: string, text: string): string | undefined {\n  const esc = ident.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n  const re = new RegExp(\n    `\\\\b${esc}(?:\\\\s+\\\\w[\\\\w.\\\\[\\\\]*]*)?\\\\s*(?::=|=)\\\\s*(?:\"([^\"]+)\"|\\`([^\\`]+)\\`)`,\n  )\n  const m = re.exec(text)\n  if (!m) return undefined\n  return m[1] ?? m[2]\n}\n\n// Character offset of the topic token at the tail of a producer match, so evidence\n// points at the `Topic: \"orders\"` line rather than the head of the struct literal.\nfunction producerTopicAnchor(match: RegExpExecArray): number {\n  const [full] = match\n  const tokenLen = match[1]\n    ? match[1].length + 2 // \"x\"\n    : match[2]\n      ? match[2].length + 2 // `x`\n      : (match[3]?.length ?? 0) // ident\n  return match.index + full.length - tokenLen\n}\n\ntype Emit = (\n  topic: string,\n  edgeType: 'PUBLISHES_TO' | 'CONSUMES_FROM',\n  anchor: number,\n) => void\n\n// Walk a Go file's Sarama producer / consumer-group call sites, emitting a topic\n// per resolved site. No-op unless the file imports Sarama.\nfunction goSaramaEndpoints(text: string, emit: Emit): void {\n  if (!SARAMA_IMPORT_RE.test(text)) return\n\n  GO_PRODUCER_RE.lastIndex = 0\n  let m: RegExpExecArray | null\n  while ((m = GO_PRODUCER_RE.exec(text)) !== null) {\n    const literal = m[1] ?? m[2]\n    const anchor = producerTopicAnchor(m)\n    if (literal) {\n      emit(literal, 'PUBLISHES_TO', anchor)\n    } else if (m[3]) {\n      const resolved = resolveGoLiteral(m[3], text)\n      if (resolved) emit(resolved, 'PUBLISHES_TO', anchor)\n    }\n  }\n\n  GO_CONSUMER_RE.lastIndex = 0\n  while ((m = GO_CONSUMER_RE.exec(text)) !== null) {\n    const inside = m[1] ?? ''\n    const anchor = m.index + Math.max(0, m[0].indexOf('[]string'))\n    let sawLiteral = false\n    GO_STRING_LITERAL_RE.lastIndex = 0\n    let s: RegExpExecArray | null\n    while ((s = GO_STRING_LITERAL_RE.exec(inside)) !== null) {\n      const topic = s[1] ?? s[2]\n      if (topic) {\n        emit(topic, 'CONSUMES_FROM', anchor)\n        sawLiteral = true\n      }\n    }\n    if (sawLiteral) continue\n    // `[]string{topicVar}` — resolve each identifier to an in-file literal.\n    GO_IDENT_RE.lastIndex = 0\n    let id: RegExpExecArray | null\n    while ((id = GO_IDENT_RE.exec(inside)) !== null) {\n      const resolved = resolveGoLiteral(id[0], text)\n      if (resolved) emit(resolved, 'CONSUMES_FROM', anchor)\n    }\n  }\n}\n\nexport function kafkaEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n  const make = (\n    topic: string,\n    edgeType: 'PUBLISHES_TO' | 'CONSUMES_FROM',\n    anchor?: number,\n  ): void => {\n    const key = `${edgeType}|${topic}`\n    if (seen.has(key)) return\n    seen.add(key)\n    // JS callers pass no anchor and fall back to finding the topic string. The Go\n    // path already knows the exact call-site offset (the topic may be a const, so\n    // its literal lives elsewhere in the file), so count newlines up to it.\n    const line =\n      anchor !== undefined\n        ? file.content.slice(0, anchor).split('\\n').length\n        : lineOf(file.content, topic)\n    out.push({\n      infraId: infraId('kafka-topic', topic),\n      name: topic,\n      kind: 'kafka-topic',\n      edgeType,\n      // JS: `producer.send({topic: 'x'})` / `consumer.subscribe({topic: 'x'})`\n      // (kafkajs / node-rdkafka). Go: `sarama.ProducerMessage{Topic: 'x'}` /\n      // `consumerGroup.Consume(ctx, []string{'x'}, …)`. Both are framework-aware\n      // call sites — verified-call-site tier (ADR-066).\n      confidenceKind: 'verified-call-site',\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  }\n\n  if (path.extname(file.path) === '.go') {\n    goSaramaEndpoints(file.content, make)\n  } else {\n    for (const { topic } of findAll(PRODUCER_TOPIC_RE, file.content)) make(topic, 'PUBLISHES_TO')\n    for (const { topic } of findAll(CONSUMER_TOPIC_RE, file.content)) make(topic, 'CONSUMES_FROM')\n  }\n  return out\n}\n","import path from 'node:path'\nimport { infraId } from '@neat.is/types'\nimport { lineOf, snippet, type ExternalEndpoint, type SourceFile } from './shared.js'\n\n// Redis URLs in source — `redis://host[:port]` or `rediss://...`. We only\n// catch literal strings; env-driven URLs go through the database parsers\n// (.env, ormconfig, etc.) and don't need a CALLS edge.\nconst REDIS_URL_RE = /redis(?:s)?:\\/\\/(?:[^@'\"`\\s]+@)?([^:/'\"`\\s]+)(?::(\\d+))?/g\n\nexport function redisEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n  REDIS_URL_RE.lastIndex = 0\n  let m: RegExpExecArray | null\n  while ((m = REDIS_URL_RE.exec(file.content)) !== null) {\n    const host = m[1]!\n    if (seen.has(host)) continue\n    seen.add(host)\n    const line = lineOf(file.content, host)\n    out.push({\n      infraId: infraId('redis', host),\n      name: host,\n      kind: 'redis',\n      edgeType: 'CALLS',\n      // `redis://host` URL literal — the scheme is structural support, but no\n      // call expression is verified to wire it through. URL-with-structural-\n      // support tier (ADR-066).\n      confidenceKind: 'url-with-structural-support',\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  }\n  return out\n}\n","import path from 'node:path'\nimport { infraId } from '@neat.is/types'\nimport { lineOf, snippet, type ExternalEndpoint, type SourceFile } from './shared.js'\n\n// AWS SDK v3 calls. We catch S3 (`Bucket: \"x\"` near a `S3Client`-using\n// PutObjectCommand / GetObjectCommand / DeleteObjectCommand) and DynamoDB\n// (`TableName: \"x\"` near GetCommand / PutCommand / DynamoDBClient). The\n// pattern is intentionally permissive: a literal Bucket/TableName near an\n// SDK constant is good enough evidence; misses are fine because non-static\n// resources can't be catalogued anyway.\nconst S3_BUCKET_RE = /Bucket\\s*:\\s*['\"`]([^'\"`]+)['\"`]/g\nconst DYNAMO_TABLE_RE = /TableName\\s*:\\s*['\"`]([^'\"`]+)['\"`]/g\n\nfunction hasMarker(text: string, markers: string[]): boolean {\n  return markers.some((m) => text.includes(m))\n}\n\nfunction findAll(re: RegExp, text: string): { name: string; index: number }[] {\n  re.lastIndex = 0\n  const out: { name: string; index: number }[] = []\n  let m: RegExpExecArray | null\n  while ((m = re.exec(text)) !== null) {\n    out.push({ name: m[1]!, index: m.index })\n  }\n  return out\n}\n\nexport function awsEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n  const make = (kind: string, name: string): void => {\n    const key = `${kind}|${name}`\n    if (seen.has(key)) return\n    seen.add(key)\n    const line = lineOf(file.content, name)\n    out.push({\n      infraId: infraId(kind, name),\n      name,\n      kind,\n      edgeType: 'CALLS',\n      // SDK marker (S3Client, GetCommand, etc.) plus a Bucket/TableName\n      // literal — framework-aware recognizer, verified-call-site tier\n      // (ADR-066).\n      confidenceKind: 'verified-call-site',\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  }\n\n  if (hasMarker(file.content, ['S3Client', 'PutObjectCommand', 'GetObjectCommand', 'DeleteObjectCommand'])) {\n    for (const { name } of findAll(S3_BUCKET_RE, file.content)) make('s3-bucket', name)\n  }\n  if (\n    hasMarker(file.content, [\n      'DynamoDBClient',\n      'DynamoDBDocumentClient',\n      'GetCommand',\n      'PutCommand',\n      'QueryCommand',\n      'UpdateCommand',\n      'DeleteCommand',\n    ])\n  ) {\n    for (const { name } of findAll(DYNAMO_TABLE_RE, file.content)) make('dynamodb-table', name)\n  }\n  return out\n}\n","import path from 'node:path'\nimport { infraId } from '@neat.is/types'\nimport { lineOf, snippet, type ExternalEndpoint, type SourceFile } from './shared.js'\n\n// Client-construction in JS/TS:\n//\n//   const client = new orders_proto.OrderService(...)\n//   const client = new OrdersClient('orders.internal:50051', ...)\n//   const client = new S3Client({ region: 'us-east-1' })\n//\n// The same `new <Name>Client(...)` shape is used by gRPC client stubs, AWS\n// SDK v3 service clients, and a long tail of other SDKs. v0.3.0 mapped every\n// `*Client(...)` to `infra:grpc-service:*`, which was true for the demo and\n// false for every AWS service medusa imported.\n//\n// Per ADR-065 / #238, classification is import-aware:\n//   1. file imports `@aws-sdk/client-<suffix>` and `<Name>` lowercases to the\n//      same alphanumeric tail (`S3Client` ↔ `client-s3`,\n//      `CognitoIdentityProviderClient` ↔ `client-cognito-identity-provider`)\n//      → kind `aws-<suffix>` (e.g. `infra:aws-s3:S3`).\n//   2. file imports `@grpc/grpc-js` or any `*_grpc_pb` generated stub\n//      → kind `grpc-service` (the legitimate gRPC path; demo unchanged).\n//   3. otherwise → kind `service` (the safe default — accurate but\n//      uninformative, the v0.3.0 grpc lie is removed).\nconst GRPC_CLIENT_RE = /new\\s+([A-Z][A-Za-z0-9_]*)Client\\s*\\(\\s*['\"`]?([^,'\"`)]+)?/g\nconst AWS_SDK_IMPORT_RE =\n  /(?:from\\s+['\"`]|require\\(\\s*['\"`])@aws-sdk\\/client-([a-z0-9-]+)['\"`]/g\nconst GRPC_IMPORT_RE =\n  /(?:from\\s+['\"`]|require\\(\\s*['\"`])@grpc\\/grpc-js['\"`]|_grpc_pb['\"`]/\n\nfunction isLikelyAddress(value: string | undefined): boolean {\n  if (!value) return false\n  // Reject code expressions: object literals, anything with whitespace.\n  // process.env.X contains dots and would otherwise pass the dot check.\n  if (/\\s/.test(value) || value.startsWith('{')) return false\n  return /:\\d{2,5}$/.test(value) || value.includes('.')\n}\n\nfunction normaliseForMatch(s: string): string {\n  return s.toLowerCase().replace(/[^a-z0-9]/g, '')\n}\n\ninterface ImportContext {\n  awsSdkSuffixes: Map<string, string>  // normalised → raw suffix (e.g. 's3' → 's3')\n  hasGrpcImport: boolean\n}\n\nfunction readImports(content: string): ImportContext {\n  const awsSdkSuffixes = new Map<string, string>()\n  AWS_SDK_IMPORT_RE.lastIndex = 0\n  let m: RegExpExecArray | null\n  while ((m = AWS_SDK_IMPORT_RE.exec(content)) !== null) {\n    const raw = m[1]!\n    awsSdkSuffixes.set(normaliseForMatch(raw), raw)\n  }\n  return {\n    awsSdkSuffixes,\n    hasGrpcImport: GRPC_IMPORT_RE.test(content),\n  }\n}\n\nfunction classifyClient(\n  symbol: string,\n  ctx: ImportContext,\n): { kind: string } | null {\n  const key = normaliseForMatch(symbol)\n  const awsRaw = ctx.awsSdkSuffixes.get(key)\n  if (awsRaw) return { kind: `aws-${awsRaw}` }\n  if (ctx.hasGrpcImport) return { kind: 'grpc-service' }\n  // ADR-065 #5-adjacent — a bare `new <Name>Client()` with no AWS or gRPC\n  // import context is ambiguous; could be an in-process client object\n  // (`new QueryClient()` from @tanstack/react-query, `new PrismaClient()`,\n  // a domain Client class, etc.). Refuse to emit an edge rather than guess\n  // a `service` kind that produces false positives. v0.3.3 medusa run had\n  // a QueryClient false positive before this guard.\n  return null\n}\n\nexport function grpcEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n  const ctx = readImports(file.content)\n  GRPC_CLIENT_RE.lastIndex = 0\n  let m: RegExpExecArray | null\n  while ((m = GRPC_CLIENT_RE.exec(file.content)) !== null) {\n    const symbol = m[1]!\n    const addr = m[2]?.trim()\n    const name = isLikelyAddress(addr) ? addr! : symbol\n    if (seen.has(name)) continue\n    const classified = classifyClient(symbol, ctx)\n    if (!classified) continue\n    seen.add(name)\n    const { kind } = classified\n    const line = lineOf(file.content, m[0])\n    out.push({\n      infraId: infraId(kind, name),\n      name,\n      kind,\n      edgeType: 'CALLS',\n      // `new <Name>Client(...)` with @aws-sdk/* or @grpc/grpc-js import\n      // context — import-aware classification per #238. Verified-call-site\n      // tier (ADR-066).\n      confidenceKind: 'verified-call-site',\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  }\n  return out\n}\n","import path from 'node:path'\nimport { infraId } from '@neat.is/types'\nimport { lineOf, snippet, type ExternalEndpoint, type SourceFile } from './shared.js'\n\n// Supabase clients in JS/TS:\n//\n//   import { createClient } from '@supabase/supabase-js'\n//   const supabase = createClient(process.env.SUPABASE_URL, key)\n//   const db = createClient('https://abc.supabase.co', key)\n//   supabase.from('orders').select()\n//   db.auth.getUser()\n//\n//   import { createServerClient } from '@supabase/ssr'\n//   const supabase = createServerClient(url, key, { cookies })\n//\n// Supabase apps talk to *.supabase.co exclusively through these client\n// constructors. The HTTP-call extractor never sees the host: it lives behind\n// `createClient`, and in the common case the URL is `process.env.SUPABASE_URL`\n// (or `EXPO_PUBLIC_SUPABASE_URL`), not a literal. So a production-observed\n// `service → *.supabase.co` CALLS edge arrives with no declared twin and shows\n// up as a false `missing-extracted` divergence. This extractor closes that gap.\n//\n// Classification is import-aware, the same discipline grpc.ts / aws.ts use\n// (#238): a bare `createClient(...)` is too common a name to claim without the\n// `@supabase/*` import in scope. The constructor names map to the package that\n// owns them:\n//   - `createClient`                       ← @supabase/supabase-js\n//   - `createServerClient` / `createBrowserClient` ← @supabase/ssr\nconst SUPABASE_JS_IMPORT_RE =\n  /(?:from\\s+['\"`]|require\\(\\s*['\"`])@supabase\\/supabase-js['\"`]/\nconst SUPABASE_SSR_IMPORT_RE =\n  /(?:from\\s+['\"`]|require\\(\\s*['\"`])@supabase\\/ssr['\"`]/\n\n// First argument of a Supabase client constructor. Group 1 is the constructor\n// name, group 2 (when present) is a string-literal URL. A non-literal first arg\n// (`process.env.SUPABASE_URL`, a config getter) leaves group 2 undefined — we\n// still match the construction, we just can't resolve the literal host.\nconst SUPABASE_CLIENT_RE =\n  /\\b(createClient|createServerClient|createBrowserClient)\\s*\\(\\s*(?:['\"`]([^'\"`]*)['\"`])?/g\n\n// A *.supabase.co host pulled out of a literal URL argument. We only treat the\n// constructor's URL as a resolvable host when the literal actually names a\n// supabase.co domain — anything else (a self-hosted Supabase behind a custom\n// domain, a placeholder) stays the unresolved env target rather than a guessed\n// host. Reading the literal is the only honest host source (file-awareness §6).\nfunction hostFromLiteral(literal: string | undefined): string | null {\n  if (!literal) return null\n  const m = /^https?:\\/\\/([^/:'\"`\\s]+)/.exec(literal.trim())\n  if (!m) return null\n  const host = m[1]!\n  if (!/\\.supabase\\.(co|in)$/i.test(host)) return null\n  return host\n}\n\ninterface ImportContext {\n  hasSupabaseJs: boolean\n  hasSupabaseSsr: boolean\n}\n\nfunction readImports(content: string): ImportContext {\n  return {\n    hasSupabaseJs: SUPABASE_JS_IMPORT_RE.test(content),\n    hasSupabaseSsr: SUPABASE_SSR_IMPORT_RE.test(content),\n  }\n}\n\n// A constructor name is only a Supabase client when the package that owns it is\n// imported in the same file. `createClient` needs @supabase/supabase-js;\n// `createServerClient` / `createBrowserClient` need @supabase/ssr. Without the\n// import in scope we refuse to emit — a bare `createClient` could be anything.\nfunction constructorMatchesImport(name: string, ctx: ImportContext): boolean {\n  if (name === 'createClient') return ctx.hasSupabaseJs\n  return ctx.hasSupabaseSsr\n}\n\n// Variables assigned from a Supabase client constructor in this file, e.g.\n// `const supabase = createClient(...)`. We scope `.from()` / `.rpc()` matching to\n// these so `supabase.from('orders')` (a table query) is recognized while\n// `Array.from(...)` or an unrelated `.from` never mints a phantom table node.\nconst SUPABASE_CLIENT_ASSIGN_RE =\n  /(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:await\\s+)?(createClient|createServerClient|createBrowserClient)\\s*\\(/g\n\nfunction supabaseClientVars(content: string, ctx: ImportContext): Set<string> {\n  const vars = new Set<string>()\n  SUPABASE_CLIENT_ASSIGN_RE.lastIndex = 0\n  let m: RegExpExecArray | null\n  while ((m = SUPABASE_CLIENT_ASSIGN_RE.exec(content)) !== null) {\n    if (constructorMatchesImport(m[2]!, ctx)) vars.add(m[1]!)\n  }\n  return vars\n}\n\nexport function supabaseEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  const ctx = readImports(file.content)\n  if (!ctx.hasSupabaseJs && !ctx.hasSupabaseSsr) return []\n\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n  SUPABASE_CLIENT_RE.lastIndex = 0\n  let m: RegExpExecArray | null\n  while ((m = SUPABASE_CLIENT_RE.exec(file.content)) !== null) {\n    const ctor = m[1]!\n    if (!constructorMatchesImport(ctor, ctx)) continue\n\n    // When the first argument is a literal *.supabase.co URL we resolve the\n    // real host. Otherwise the URL is env-driven (`process.env.SUPABASE_URL`,\n    // a config getter) and unknowable statically — the edge still has to land,\n    // so it resolves to a stable `supabase:env` target. That target is honest:\n    // we read the @supabase import and the `createClient` call, but not a host,\n    // so we don't fabricate one (file-awareness §6).\n    const host = hostFromLiteral(m[2])\n    const name = host ?? 'env'\n    if (seen.has(name)) continue\n    seen.add(name)\n\n    const line = lineOf(file.content, m[0])\n    out.push({\n      infraId: infraId('supabase', name),\n      name,\n      kind: 'supabase',\n      edgeType: 'CALLS',\n      // `createClient(...)` from @supabase/supabase-js (or createServerClient /\n      // createBrowserClient from @supabase/ssr) with the import in scope — a\n      // framework-aware recognizer matched the SDK shape. Verified-call-site\n      // tier (ADR-066), the same grade aws.ts / grpc.ts emit at.\n      confidenceKind: 'verified-call-site',\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  }\n\n  // `<client>.from('<table>')` / `<client>.rpc('<fn>')` — table/RPC-grained call\n  // sites (#803). These give a production-observed supabase-table access a\n  // file-grained static twin to fuse onto (the Supabase connector otherwise\n  // observes the table but not the calling file). Scoped to the client vars found\n  // above so `Array.from` and unrelated `.from` never mint a phantom table.\n  const clientVars = supabaseClientVars(file.content, ctx)\n  for (const clientVar of clientVars) {\n    const accessRe = new RegExp(\n      `\\\\b${clientVar}\\\\s*\\\\.\\\\s*(from|rpc)\\\\s*\\\\(\\\\s*['\"\\`]([\\\\w.-]+)['\"\\`]`,\n      'g',\n    )\n    let am: RegExpExecArray | null\n    while ((am = accessRe.exec(file.content)) !== null) {\n      const kind = am[1] === 'rpc' ? 'supabase-rpc' : 'supabase-table'\n      const resource = am[2]!\n      const key = `${kind}/${resource}`\n      if (seen.has(key)) continue\n      seen.add(key)\n      const line = lineOf(file.content, am[0])\n      out.push({\n        infraId: infraId(kind, resource),\n        name: resource,\n        kind,\n        edgeType: 'CALLS',\n        confidenceKind: 'verified-call-site',\n        evidence: {\n          file: path.relative(serviceDir, file.path),\n          line,\n          snippet: snippet(file.content, line),\n        },\n      })\n    }\n  }\n\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport JavaScript from 'tree-sitter-javascript'\nimport { infraId } from '@neat.is/types'\nimport { GRAMMAR_BY_EXT, parseSource } from '../symbols.js'\nimport { resolveJsImport } from '../imports.js'\nimport { snippet, toPosix, type ExternalEndpoint, type SourceFile } from './shared.js'\n\n// Firestore call sites (ADR-167). The collection-grained analog of\n// calls/supabase.ts (`.from('table')`) and calls/mongoose.ts (`.collection(...)`):\n// it names the collection a file reads or writes so a Firebase/Next.js app's\n// datastore surface — collections, and the fields the code writes — becomes\n// first-class in the graph at the same grain as `sql-table` + `ColumnAttr`.\n//\n//   // modular (firebase/firestore)\n//   import { getFirestore, collection, doc, addDoc, setDoc, query, where } from 'firebase/firestore'\n//   const db = getFirestore(app)\n//   collection(db, 'orders')                        // → collection 'orders'\n//   doc(db, 'orders', id)                            // → collection 'orders'\n//   collection(doc(db, 'users', id), 'posts')        // → 'users/{}/posts'\n//   addDoc(collection(db, 'orders'), { total, status })   // → written fields\n//   query(collection(db, 'orders'), where('status', '==', s))  // → read field\n//\n//   // namespaced / admin (firebase-admin/firestore)\n//   import admin from 'firebase-admin'\n//   const db = admin.firestore()\n//   db.collection('orders').doc(id).set({ total })   // → collection + written field\n//   db.collection('orders').where('status', '==', s) // → read field\n//\n// Firestore has no least-privilege telemetry path (ADR-128 makes its runtime an\n// explicit connector non-goal), so its value is EXTRACTED-only. The load-bearing\n// distinction for the field-guard policy (ADR-169) is whether a write comes from\n// the client SDK (`firebase/firestore`, governed by security rules) or the admin\n// SDK (`firebase-admin/firestore`, which bypasses rules entirely) — recorded per\n// written field as `sdkWrites`.\n//\n// Classification is import-aware, the same discipline calls/supabase.ts uses: the\n// producer is gated on a firebase import, and `collection(` / `.collection(` are\n// only claimed when scoped to a recognized Firestore client var (or an inline\n// client factory) — a bare `collection(...)` could be Mongoose's native driver.\n// A computed or interpolated path segment is left unclaimed rather than guessed.\n\nconst FIRESTORE_CLIENT_IMPORT_RE =\n  /(?:from\\s+['\"`]|require\\(\\s*['\"`])firebase\\/firestore['\"`]/\nconst FIRESTORE_ADMIN_IMPORT_RE =\n  /(?:from\\s+['\"`]|require\\(\\s*['\"`])firebase-admin(?:\\/firestore)?['\"`]/\n\ntype SdkWrite = 'client' | 'admin'\n\nfunction parserForExt(ext: string): Parser {\n  const p = new Parser()\n  p.setLanguage(GRAMMAR_BY_EXT[ext] ?? JavaScript)\n  return p\n}\n\nfunction namedChildren(node: Parser.SyntaxNode): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const c = node.namedChild(i)\n    if (c) out.push(c)\n  }\n  return out\n}\n\n// The literal text inside a `string` node (quotes stripped). Null for a template /\n// interpolated string — never guessed at (identical to drizzle.ts).\nfunction stringLiteralText(node: Parser.SyntaxNode | null): string | null {\n  if (!node || node.type !== 'string') return null\n  for (const child of namedChildren(node)) {\n    if (child.type === 'string_fragment') return child.text\n  }\n  return '' // an empty '' literal has no string_fragment child\n}\n\nfunction callArgs(call: Parser.SyntaxNode): Parser.SyntaxNode[] {\n  const args = call.childForFieldName('arguments')\n  return args ? namedChildren(args) : []\n}\n\n// A `getFirestore(...)` / `initializeFirestore(...)` call, or an `X.firestore()`\n// namespaced/admin client — the factory shapes a Firestore client comes from.\nfunction isFirestoreClientFactory(node: Parser.SyntaxNode | null): boolean {\n  if (node?.type !== 'call_expression') return false\n  const fn = node.childForFieldName('function')\n  if (fn?.type === 'identifier') return fn.text === 'getFirestore' || fn.text === 'initializeFirestore'\n  if (fn?.type === 'member_expression') return fn.childForFieldName('property')?.text === 'firestore'\n  return false\n}\n\n// Variables assigned from a Firestore client factory in this file, e.g.\n// `const db = getFirestore(app)` / `const db = admin.firestore()`. We scope the\n// `collection(db, …)` and `db.collection(…)` matching to these so an unrelated\n// `.collection` (Mongoose's native driver, an array helper) never mints a phantom\n// collection — the same scoping calls/supabase.ts applies to `.from()`.\nfunction firestoreClientVars(root: Parser.SyntaxNode): Set<string> {\n  const vars = new Set<string>()\n  const walk = (node: Parser.SyntaxNode): void => {\n    if (node.type === 'variable_declarator') {\n      const name = node.childForFieldName('name')\n      let value = node.childForFieldName('value')\n      if (value?.type === 'await_expression') value = namedChildren(value)[0] ?? null\n      if (name?.type === 'identifier' && isFirestoreClientFactory(value)) {\n        vars.add(name.text)\n      }\n    }\n    for (const c of namedChildren(node)) walk(c)\n  }\n  walk(root)\n  return vars\n}\n\nfunction isClientExpr(node: Parser.SyntaxNode | null, clientVars: Set<string>): boolean {\n  if (!node) return false\n  if (node.type === 'identifier') return clientVars.has(node.text)\n  return isFirestoreClientFactory(node)\n}\n\n// Resolve a modular `collection(...)` / `doc(...)` call to its ordered Firestore\n// path segments, where a collection name is its literal string and a document id\n// collapses to '{}' (the path-template placeholder — the collection template is\n// the same whatever the doc id). Returns null when the base is not a recognized\n// client or any collection-position segment is computed/interpolated: left\n// unclaimed, never guessed. Segments alternate collection(0)/doc(1)/collection(2)…\nfunction resolveModular(node: Parser.SyntaxNode, clientVars: Set<string>): string[] | null {\n  const fn = node.childForFieldName('function')\n  if (fn?.type !== 'identifier' || (fn.text !== 'collection' && fn.text !== 'doc')) return null\n  const args = callArgs(node)\n  const first = args[0]\n  if (!first) return null\n\n  let segs: string[]\n  if (first.type === 'call_expression') {\n    const base = resolveModular(first, clientVars)\n    if (base === null) return null\n    segs = [...base]\n  } else if (isClientExpr(first, clientVars)) {\n    segs = []\n  } else {\n    return null // first arg is not a firestore client — not our call\n  }\n\n  for (let i = 1; i < args.length; i++) {\n    const isCollectionPos = segs.length % 2 === 0\n    if (isCollectionPos) {\n      const lit = stringLiteralText(args[i]!)\n      if (lit === null) return null // computed collection name → unclaimed\n      segs.push(lit)\n    } else {\n      segs.push('{}') // a document id — literal or computed alike → placeholder\n    }\n  }\n  return segs\n}\n\n// Resolve a namespaced `<client>.collection('x')` / `.doc(id)` chain to its\n// ordered path segments, the same segment model as the modular resolver.\nfunction resolveNamespaced(node: Parser.SyntaxNode, clientVars: Set<string>): string[] | null {\n  if (node.type !== 'call_expression') return null\n  const fn = node.childForFieldName('function')\n  if (fn?.type !== 'member_expression') return null\n  const prop = fn.childForFieldName('property')?.text\n  if (prop !== 'collection' && prop !== 'doc') return null\n  const obj = fn.childForFieldName('object')\n\n  let base: string[]\n  if (obj?.type === 'call_expression') {\n    const inner = resolveNamespaced(obj, clientVars)\n    if (inner === null) return null\n    base = inner\n  } else if (isClientExpr(obj, clientVars)) {\n    base = []\n  } else {\n    return null\n  }\n\n  if (prop === 'doc') return [...base, '{}']\n  const lit = stringLiteralText(callArgs(node)[0] ?? null)\n  if (lit === null) return null // computed collection name → unclaimed\n  return [...base, lit]\n}\n\n// The collection path a resolved segment list names: a `collection(...)` call\n// ends on a collection (odd length), a `doc(...)` call ends on a document — drop\n// its trailing id to get the collection it belongs to. Joined with '/'.\nfunction collectionPathOf(node: Parser.SyntaxNode, segs: string[] | null): string | null {\n  if (segs === null || segs.length === 0) return null\n  const fn = node.childForFieldName('function')\n  const prop =\n    fn?.type === 'identifier'\n      ? fn.text\n      : fn?.type === 'member_expression'\n        ? fn.childForFieldName('property')?.text\n        : null\n  const collSegs = prop === 'doc' ? segs.slice(0, -1) : segs\n  if (collSegs.length === 0) return null\n  return collSegs.join('/')\n}\n\n// The collection path any collection/doc reference (modular or namespaced) names.\nfunction collectionPathFromCall(node: Parser.SyntaxNode, clientVars: Set<string>): string | null {\n  const modular = resolveModular(node, clientVars)\n  if (modular !== null) return collectionPathOf(node, modular)\n  const namespaced = resolveNamespaced(node, clientVars)\n  if (namespaced !== null) return collectionPathOf(node, namespaced)\n  return null\n}\n\n// Descend a namespaced query/write receiver chain (`.where().orderBy()`, or a\n// bare collection/doc ref) to the collection it targets.\nfunction receiverColl(node: Parser.SyntaxNode | null, clientVars: Set<string>): string | null {\n  let cur: Parser.SyntaxNode | null = node\n  while (cur?.type === 'call_expression') {\n    const fn = cur.childForFieldName('function')\n    if (fn?.type !== 'member_expression') return null\n    const prop = fn.childForFieldName('property')?.text\n    if (prop === 'collection' || prop === 'doc') return collectionPathFromCall(cur, clientVars)\n    cur = fn.childForFieldName('object') // skip query methods (where/orderBy/limit/…)\n  }\n  return null\n}\n\n// The collection a modular `query(collRef, …)` reads — arg0 is the collection ref\n// or a nested `query(...)`.\nfunction modularQueryColl(node: Parser.SyntaxNode, clientVars: Set<string>): string | null {\n  const fn = node.childForFieldName('function')\n  if (fn?.type !== 'identifier') return null\n  if (fn.text === 'query') {\n    const arg0 = callArgs(node)[0]\n    return arg0?.type === 'call_expression' ? modularQueryColl(arg0, clientVars) : null\n  }\n  if (fn.text === 'collection' || fn.text === 'doc') return collectionPathFromCall(node, clientVars)\n  return null\n}\n\n// A property name, the way drizzle.ts reads it: a bare `status:` or quoted\n// `'status':` key, or a `{ status }` shorthand. A computed / spread key is skipped\n// (returns null / not a pair) rather than guessed at.\nfunction keyName(key: Parser.SyntaxNode | null): string | null {\n  if (!key) return null\n  if (key.type === 'property_identifier') return key.text\n  if (key.type === 'string') return stringLiteralText(key)\n  return null\n}\n\nfunction objectKeys(obj: Parser.SyntaxNode | undefined): string[] {\n  if (obj?.type !== 'object') return []\n  const out: string[] = []\n  for (const child of namedChildren(obj)) {\n    if (child.type === 'pair') {\n      const k = keyName(child.childForFieldName('key'))\n      if (k) out.push(k)\n    } else if (child.type === 'shorthand_property_identifier') {\n      out.push(child.text)\n    }\n    // spread_element / computed key → left unclaimed\n  }\n  return out\n}\n\nconst MODULAR_WRITES = new Set(['addDoc', 'setDoc', 'updateDoc'])\nconst NAMESPACED_WRITES = new Set(['add', 'set', 'update'])\nconst READ_CLAUSES = new Set(['where', 'orderBy'])\n\n/** A Firestore client this file imported from another module, resolved by the cross-file\n *  pass (#1223). `sdk` is the *exporting* file's SDK, since the importing file may name no\n *  Firestore package itself. */\nexport interface ImportedFirestoreClients {\n  names: Set<string>\n  sdk: SdkWrite | null\n}\n\nexport function firestoreEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n  imported?: ImportedFirestoreClients,\n): ExternalEndpoint[] {\n  const hasClient = FIRESTORE_CLIENT_IMPORT_RE.test(file.content)\n  const hasAdmin = FIRESTORE_ADMIN_IMPORT_RE.test(file.content)\n  // A file that imports its client from elsewhere may name no Firestore package at all —\n  // `import { db } from './firebase'` then `db.collection('orders')` under the admin SDK.\n  // The resolved import is the evidence there, so the package gate only decides when\n  // there are no imported clients to go on.\n  const importedNames = imported?.names ?? new Set<string>()\n  if (!hasClient && !hasAdmin && importedNames.size === 0) return []\n\n  // The writing SDK is the file's imported Firestore SDK: a file uses one SDK\n  // (`getFirestore` resolves to client under firebase/firestore, admin under\n  // firebase-admin/firestore; `admin.firestore()` is admin). When a file imports\n  // both — rare — the per-write SDK is genuinely ambiguous, so we leave the tag\n  // off (the field still lands as a column); ADR-169 reads `sdkWrites ?? []`, so\n  // an untagged write degrades to silence, never a false positive.\n  // A file with no SDK import of its own inherits the exporting file's SDK, which is\n  // where its client was actually constructed.\n  const ownSdk: SdkWrite | null =\n    hasClient && !hasAdmin ? 'client' : hasAdmin && !hasClient ? 'admin' : null\n  const fileSdk: SdkWrite | null = !hasClient && !hasAdmin ? (imported?.sdk ?? null) : ownSdk\n\n  const tree = parseSource(parserForExt(path.extname(file.path)), file.content)\n  const clientVars = firestoreClientVars(tree.rootNode)\n  for (const n of importedNames) clientVars.add(n)\n\n  const collLine = new Map<string, number>() // path → first evidence line\n  const writes = new Map<string, Map<string, Set<SdkWrite>>>() // path → field → sdks\n  const reads = new Map<string, Set<string>>() // path → read field names\n\n  const noteColl = (p: string, line: number): void => {\n    if (!collLine.has(p)) collLine.set(p, line)\n  }\n  const noteWrite = (p: string, fields: string[], line: number): void => {\n    if (fields.length === 0) return\n    noteColl(p, line)\n    let byField = writes.get(p)\n    if (!byField) {\n      byField = new Map()\n      writes.set(p, byField)\n    }\n    for (const f of fields) {\n      let sdks = byField.get(f)\n      if (!sdks) {\n        sdks = new Set()\n        byField.set(f, sdks)\n      }\n      if (fileSdk) sdks.add(fileSdk)\n    }\n  }\n  const noteRead = (p: string, field: string, line: number): void => {\n    noteColl(p, line)\n    let s = reads.get(p)\n    if (!s) {\n      s = new Set()\n      reads.set(p, s)\n    }\n    s.add(field)\n  }\n\n  const walk = (node: Parser.SyntaxNode): void => {\n    if (node.type === 'call_expression') {\n      const fn = node.childForFieldName('function')\n      const line = node.startPosition.row + 1\n\n      // A collection / doc reference — the collection node itself.\n      const collPath = collectionPathFromCall(node, clientVars)\n      if (collPath) noteColl(collPath, line)\n\n      if (fn?.type === 'identifier') {\n        // Modular write: setDoc(ref, {…}) / updateDoc(ref, {…}) / addDoc(ref, {…}).\n        if (MODULAR_WRITES.has(fn.text)) {\n          const args = callArgs(node)\n          const ref = args[0]\n          const p = ref?.type === 'call_expression' ? collectionPathFromCall(ref, clientVars) : null\n          if (p) noteWrite(p, objectKeys(args[1]), line)\n        }\n        // Modular read: query(collRef, where('field', …), orderBy('field')).\n        if (fn.text === 'query') {\n          const p = modularQueryColl(node, clientVars)\n          if (p) {\n            for (const arg of callArgs(node)) {\n              if (arg.type !== 'call_expression') continue\n              const cfn = arg.childForFieldName('function')\n              if (cfn?.type === 'identifier' && READ_CLAUSES.has(cfn.text)) {\n                const field = stringLiteralText(callArgs(arg)[0] ?? null)\n                if (field) noteRead(p, field, arg.startPosition.row + 1)\n              }\n            }\n          }\n        }\n      } else if (fn?.type === 'member_expression') {\n        const prop = fn.childForFieldName('property')?.text\n        const receiver = fn.childForFieldName('object')\n        // Namespaced write: <ref>.set({…}) / .update({…}) / .add({…}).\n        if (prop && NAMESPACED_WRITES.has(prop)) {\n          const p = receiverColl(receiver, clientVars)\n          if (p) noteWrite(p, objectKeys(callArgs(node)[0]), line)\n        }\n        // Namespaced read: <ref>.where('field', …) / .orderBy('field').\n        if (prop && READ_CLAUSES.has(prop)) {\n          const p = receiverColl(receiver, clientVars)\n          const field = stringLiteralText(callArgs(node)[0] ?? null)\n          if (p && field) noteRead(p, field, line)\n        }\n      }\n    }\n    for (const c of namedChildren(node)) walk(c)\n  }\n  walk(tree.rootNode)\n\n  const out: ExternalEndpoint[] = []\n  for (const [collPath, line] of collLine) {\n    const byField = writes.get(collPath)\n    const readFields = reads.get(collPath)\n    // Union of written + read field names → columns (the existing columns fold in\n    // calls/index.ts lands these with EXTRACTED provenance).\n    const columnSet = new Set<string>()\n    if (byField) for (const f of byField.keys()) columnSet.add(f)\n    if (readFields) for (const f of readFields) columnSet.add(f)\n\n    // Per-written-field SDK tags → the seam ADR-169 joins on. Only fields with a\n    // known writing SDK carry a tag; an ambiguous (both-imports) write is a column\n    // with no tag.\n    let sdkWrites: Record<string, SdkWrite[]> | undefined\n    if (byField) {\n      for (const [field, sdks] of byField) {\n        if (sdks.size === 0) continue\n        if (!sdkWrites) sdkWrites = {}\n        sdkWrites[field] = [...sdks].sort()\n      }\n    }\n\n    out.push({\n      infraId: infraId('firestore-collection', collPath),\n      name: collPath,\n      kind: 'firestore-collection',\n      edgeType: 'CALLS',\n      // A firebase import is in scope and the call is scoped to a recognized\n      // Firestore client — a framework-aware recognizer matched the SDK shape.\n      // Verified-call-site tier (ADR-066), the grade calls/supabase.ts emits at.\n      confidenceKind: 'verified-call-site',\n      ...(columnSet.size > 0 ? { columns: [...columnSet] } : {}),\n      ...(sdkWrites ? { sdkWrites } : {}),\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  }\n  return out\n}\n\n// ── Cross-file client resolution (#1223) ──────────────────────────────────────────────\n//\n// The per-file pass only claims a call whose client variable was declared in the same\n// file, which misses the layout nearly every Firebase app uses: one module constructs the\n// client and exports it, every querying module imports it. That left a Firestore-heavy\n// codebase looking like one with no Firestore at all.\n//\n// This is the whole-program pass mongoose already has (ADR-149, `mongooseCrossFileEndpoints`)\n// applied to the client rather than the model: build a registry of which module exports a\n// Firestore client under which name, then re-run the per-file recognizer on each importer\n// with those local bindings treated as clients.\n\n/** Client vars a file EXPORTS — `export const db = getFirestore(app)`. */\nfunction exportedFirestoreClients(root: Parser.SyntaxNode): Set<string> {\n  const out = new Set<string>()\n  const collect = (node: Parser.SyntaxNode): void => {\n    if (node.type === 'variable_declarator') {\n      const name = node.childForFieldName('name')\n      let value = node.childForFieldName('value')\n      if (value?.type === 'await_expression') value = namedChildren(value)[0] ?? null\n      if (name?.type === 'identifier' && isFirestoreClientFactory(value)) out.add(name.text)\n    }\n    for (const c of namedChildren(node)) collect(c)\n  }\n  const walk = (node: Parser.SyntaxNode): void => {\n    if (node.type === 'export_statement') collect(node)\n    else for (const c of namedChildren(node)) walk(c)\n  }\n  walk(root)\n  return out\n}\n\ninterface NamedBinding {\n  local: string\n  imported: string\n  specifier: string\n}\n\n/** Named import bindings only. A Firestore client is a named export, so a default or\n *  namespace import can't name one — the same reasoning the Server Action stitch uses. */\nfunction namedImportBindings(root: Parser.SyntaxNode): NamedBinding[] {\n  const out: NamedBinding[] = []\n  const walk = (node: Parser.SyntaxNode): void => {\n    if (node.type === 'import_statement') {\n      const src = node.childForFieldName('source')\n      const specifier = src ? src.text.slice(1, -1) : ''\n      if (specifier.length > 0) {\n        const stack: Parser.SyntaxNode[] = [node]\n        while (stack.length > 0) {\n          const n = stack.pop()!\n          if (n.type === 'import_specifier') {\n            const nameNode = n.childForFieldName('name')\n            const aliasNode = n.childForFieldName('alias')\n            const importedName = nameNode?.text\n            if (importedName) {\n              out.push({ local: aliasNode?.text ?? importedName, imported: importedName, specifier })\n            }\n            continue\n          }\n          for (const c of namedChildren(n)) stack.push(c)\n        }\n      }\n    }\n    for (const c of namedChildren(node)) walk(c)\n  }\n  walk(root)\n  return out\n}\n\nfunction sdkOf(content: string): SdkWrite | null {\n  const hasClient = FIRESTORE_CLIENT_IMPORT_RE.test(content)\n  const hasAdmin = FIRESTORE_ADMIN_IMPORT_RE.test(content)\n  return hasClient && !hasAdmin ? 'client' : hasAdmin && !hasClient ? 'admin' : null\n}\n\nfunction parseOrNull(file: SourceFile): Parser.SyntaxNode | null {\n  const ext = path.extname(file.path)\n  if (!(ext in GRAMMAR_BY_EXT)) return null\n  try {\n    return parseSource(parserForExt(ext), file.content).rootNode\n  } catch {\n    return null\n  }\n}\n\n/**\n * Attribute a Firestore call to a client imported from another module in the same service.\n * Returns endpoints only for files the per-file pass could not already claim on its own, so\n * a file holding both its own client and an imported one isn't walked twice.\n */\nexport async function firestoreCrossFileEndpoints(\n  files: SourceFile[],\n  serviceDir: string,\n): Promise<ExternalEndpoint[]> {\n  // Registry: service-relative posix path → the client names that module exports.\n  const registry = new Map<string, { names: Set<string>; sdk: SdkWrite | null }>()\n  for (const f of files) {\n    if (sdkOf(f.content) === null && !FIRESTORE_CLIENT_IMPORT_RE.test(f.content)) continue\n    const root = parseOrNull(f)\n    if (!root) continue\n    const names = exportedFirestoreClients(root)\n    if (names.size === 0) continue\n    registry.set(toPosix(path.relative(serviceDir, f.path)), { names, sdk: sdkOf(f.content) })\n  }\n  if (registry.size === 0) return []\n\n  const out: ExternalEndpoint[] = []\n  for (const f of files) {\n    const root = parseOrNull(f)\n    if (!root) continue\n    // Files that construct their own client are already fully covered per-file.\n    if (firestoreClientVars(root).size > 0) continue\n    const bindings = namedImportBindings(root)\n    if (bindings.length === 0) continue\n\n    const names = new Set<string>()\n    let sdk: SdkWrite | null = null\n    for (const b of bindings) {\n      const rel = await resolveJsImport(b.specifier, path.dirname(f.path), serviceDir, null)\n      if (!rel) continue\n      const entry = registry.get(rel)\n      if (!entry || !entry.names.has(b.imported)) continue\n      names.add(b.local)\n      sdk ??= entry.sdk\n    }\n    if (names.size === 0) continue\n    out.push(...firestoreEndpointsFromFile(f, serviceDir, { names, sdk }))\n  }\n  return out\n}\n","import path from 'node:path'\nimport { infraId } from '@neat.is/types'\nimport { resolveJsImport } from '../imports.js'\nimport { lineOf, snippet, toPosix, type ExternalEndpoint, type SourceFile } from './shared.js'\n\n// MongoDB collection call sites (ADR-147 in-file, ADR-149 cross-file). The\n// collection-grained analog of calls/supabase.ts: it names the collection a file\n// reads or writes so a production-observed mongodb operation (ADR-148 mints the\n// OBSERVED side from the driver's OTel spans) has a file-grained static twin to\n// fuse onto.\n//\n//   import mongoose from 'mongoose'\n//   const Order = mongoose.model('Order', orderSchema)   // → collection 'orders'\n//   const Log   = mongoose.model('Log', s, 'audit_logs') // → collection 'audit_logs'\n//\n//   import { MongoClient } from 'mongodb'\n//   db.collection('orders').insertOne(doc)               // → collection 'orders'\n//\n// A Mongoose query names a *model* (`Order`), not a collection; the collection\n// is derived. The derivation reuses Mongoose's own pluralizer VERBATIM (below)\n// because the real collection is named by it — `Goose` → `gooses`, not `geese`\n// — so our string matches the one the OBSERVED span carries. Fidelity is the\n// fusion key, not a nicety (ADR-147). The native-driver path is exact: the\n// collection is the string literal.\n//\n// The model is usually registered in `models/Order.js` and queried across\n// `routes/`, `services/` — so `mongooseCrossFileEndpoints` (ADR-149) resolves a\n// query binding to its defining file through the import graph imports.ts already\n// resolves, and names the collection at the *query* site too.\n\nconst MONGOOSE_IMPORT_RE = /(?:from\\s+['\"`]|require\\(\\s*['\"`])mongoose['\"`]/\nconst MONGODB_IMPORT_RE = /(?:from\\s+['\"`]|require\\(\\s*['\"`])mongodb['\"`]/\n\n// `mongoose.pluralize(null)` / `pluralize(false)` disables pluralization\n// globally — `toCollectionName` then returns the model name unchanged (case\n// preserved).\nconst PLURALIZE_DISABLED_RE = /\\bpluralize\\s*\\(\\s*(?:null|false)\\s*\\)/\n\nconst UNCOUNTABLES = new Set([\n  'advice', 'energy', 'excretion', 'digestion', 'cooperation', 'health', 'justice', 'labour',\n  'machinery', 'equipment', 'information', 'pollution', 'sewage', 'paper', 'money', 'species',\n  'series', 'rain', 'rice', 'fish', 'sheep', 'moose', 'deer', 'news', 'expertise', 'status', 'media',\n])\n\n// Ported verbatim from mongoose-legacy-pluralize@2.0.0 (byte-identical to\n// mongoose 9.x lib/helpers/pluralize.js). Ordered; the first matching rule wins.\n// Do not \"correct\" the quirks — an English-accurate pluralizer would produce\n// names Mongoose never generates and fuse onto nothing.\nconst PLURALIZE_RULES: ReadonlyArray<readonly [RegExp, string]> = [\n  [/human$/gi, 'humans'],\n  [/(m)an$/gi, '$1en'],\n  [/(pe)rson$/gi, '$1ople'],\n  [/(child)$/gi, '$1ren'],\n  [/^(ox)$/gi, '$1en'],\n  [/(ax|test)is$/gi, '$1es'],\n  [/(octop|vir)us$/gi, '$1i'],\n  [/(alias|status)$/gi, '$1es'],\n  [/(bu)s$/gi, '$1ses'],\n  [/(buffal|tomat|potat)o$/gi, '$1oes'],\n  [/([ti])um$/gi, '$1a'],\n  [/sis$/gi, 'ses'],\n  [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'],\n  [/(hive)$/gi, '$1s'],\n  [/([^aeiouy]|qu)y$/gi, '$1ies'],\n  [/(x|ch|ss|sh)$/gi, '$1es'],\n  [/(matr|vert|ind)ix|ex$/gi, '$1ices'],\n  [/([m|l])ouse$/gi, '$1ice'],\n  [/(kn|w|l)ife$/gi, '$1ives'],\n  [/(quiz)$/gi, '$1zes'],\n  [/s$/gi, 's'],\n  [/([^a-z])$/, '$1'],\n  [/$/gi, 's'],\n]\n\nexport function pluralizeCollection(name: string): string {\n  const str = name.toLowerCase()\n  if (UNCOUNTABLES.has(str)) return str\n  for (const [re, repl] of PLURALIZE_RULES) {\n    if (str.match(re)) return str.replace(re, repl)\n  }\n  return str\n}\n\n// The Mongoose Model query/write methods (statics + instance) plus the pre-v7\n// names still common in older code. A `<binding>.<one-of-these>(` call is a\n// collection access. Used cross-file to attribute a query to its collection.\nconst MODEL_METHODS = [\n  'find', 'findOne', 'findById', 'findByIdAndUpdate', 'findByIdAndDelete', 'findOneAndUpdate',\n  'findOneAndDelete', 'findOneAndReplace', 'countDocuments', 'estimatedDocumentCount', 'distinct',\n  'aggregate', 'exists', 'where', 'populate', 'watch', 'hydrate', 'create', 'insertMany', 'insertOne',\n  'updateOne', 'updateMany', 'replaceOne', 'deleteOne', 'deleteMany', 'bulkWrite', 'bulkSave', 'save',\n  // pre-v7, removed in current mongoose but present in older codebases:\n  'count', 'update', 'remove', 'findOneAndRemove', 'findByIdAndRemove',\n]\nconst MODEL_METHODS_ALT = MODEL_METHODS.join('|')\n\nfunction schemaCollectionVars(content: string): Map<string, string> {\n  const out = new Map<string, string>()\n  const re = /(?:const|let|var)\\s+(\\w+)\\s*=\\s*new\\s+(?:mongoose\\s*\\.\\s*)?Schema\\s*\\(/g\n  let m: RegExpExecArray | null\n  while ((m = re.exec(content)) !== null) {\n    const windowText = content.slice(m.index, m.index + 2000)\n    const opt = /\\bcollection\\s*:\\s*['\"`]([\\w.-]+)['\"`]/.exec(windowText)\n    if (opt) out.set(m[1]!, opt[1]!)\n  }\n  return out\n}\n\ninterface Resolved {\n  name: string\n  kind: 'mongodb-collection' | 'mongodb-model'\n}\n\nfunction resolveModel(\n  modelName: string,\n  rest: string,\n  schemaColl: Map<string, string>,\n  pluralizeOn: boolean,\n): Resolved {\n  const trimmed = rest.trim()\n  const literalThird = /,\\s*['\"`]([\\w.-]+)['\"`]\\s*$/.exec(trimmed)\n  if (literalThird) return { name: literalThird[1]!, kind: 'mongodb-collection' }\n\n  const firstIdent = /^([A-Za-z_$][\\w$]*)/.exec(trimmed)?.[1]\n  if (firstIdent && schemaColl.has(firstIdent)) {\n    return { name: schemaColl.get(firstIdent)!, kind: 'mongodb-collection' }\n  }\n  if (/,\\s*[A-Za-z_$][\\w$]*\\s*$/.test(trimmed)) {\n    return { name: modelName, kind: 'mongodb-model' }\n  }\n  return { name: pluralizeOn ? pluralizeCollection(modelName) : modelName, kind: 'mongodb-collection' }\n}\n\ninterface ModelDef {\n  modelName: string\n  varName: string | null // the `const X =` the registration was assigned to, if any\n  resolved: Resolved\n  matchText: string\n}\n\n// Every `[const X = ][obj.]model('Name'[, schema[, 'coll']])` registration in a\n// file, with its resolved collection. Shared by the in-file emitter and the\n// cross-file registry.\nfunction collectModelDefs(content: string, pluralizeOn: boolean): ModelDef[] {\n  const schemaColl = schemaCollectionVars(content)\n  const out: ModelDef[] = []\n  const re =\n    /(?:(?:const|let|var)\\s+(\\w+)\\s*=\\s*)?(?:await\\s+)?(?:\\b\\w+\\s*\\.\\s*)?\\bmodel\\s*\\(\\s*['\"`]([\\w$]+)['\"`]\\s*(?:,\\s*([\\s\\S]{0,300}?))?\\)/g\n  let m: RegExpExecArray | null\n  while ((m = re.exec(content)) !== null) {\n    out.push({\n      modelName: m[2]!,\n      varName: m[1] ?? null,\n      resolved: resolveModel(m[2]!, m[3] ?? '', schemaColl, pluralizeOn),\n      matchText: m[0],\n    })\n  }\n  return out\n}\n\nfunction endpoint(\n  r: Resolved,\n  file: SourceFile,\n  serviceDir: string,\n  matchText: string,\n): ExternalEndpoint {\n  const line = lineOf(file.content, matchText)\n  return {\n    infraId: infraId(r.kind, r.name),\n    name: r.name,\n    kind: r.kind,\n    edgeType: 'CALLS',\n    confidenceKind: 'verified-call-site',\n    evidence: { file: path.relative(serviceDir, file.path), line, snippet: snippet(file.content, line) },\n  }\n}\n\n// ── in-file (ADR-147) ──────────────────────────────────────────────────────\n\nexport function mongooseEndpointsFromFile(file: SourceFile, serviceDir: string): ExternalEndpoint[] {\n  const hasMongoose = MONGOOSE_IMPORT_RE.test(file.content)\n  const hasMongodb = MONGODB_IMPORT_RE.test(file.content)\n  if (!hasMongoose && !hasMongodb) return []\n\n  const content = file.content\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n  const push = (r: Resolved, matchText: string): void => {\n    const key = `${r.kind}/${r.name}`\n    if (seen.has(key)) return\n    seen.add(key)\n    out.push(endpoint(r, file, serviceDir, matchText))\n  }\n\n  if (hasMongoose) {\n    const pluralizeOn = !PLURALIZE_DISABLED_RE.test(content)\n    for (const def of collectModelDefs(content, pluralizeOn)) push(def.resolved, def.matchText)\n  }\n\n  // Native driver — `<db>.collection('orders')`. The literal is the collection.\n  const collRe = /\\.\\s*collection\\s*\\(\\s*['\"`]([\\w.$-]+)['\"`]\\s*\\)/g\n  let c: RegExpExecArray | null\n  while ((c = collRe.exec(content)) !== null) {\n    push({ name: c[1]!, kind: 'mongodb-collection' }, c[0])\n  }\n\n  return out\n}\n\n// ── cross-file (ADR-149) ───────────────────────────────────────────────────\n\n// A file's model exports: the collection reachable via each named export, and\n// via the default / whole-module export (`module.exports = Order`).\ninterface FileExports {\n  byName: Map<string, string>\n  default?: string\n}\n\n// A binding imported into a query file. `named` maps a local name to a specific\n// export; `default`/`whole`/`namespace` bind the module object itself.\ninterface ImportBinding {\n  local: string\n  kind: 'named' | 'default' | 'namespace' | 'whole'\n  exportName?: string\n  specifier: string\n}\n\nfunction parseDestructure(inner: string, specifier: string, out: ImportBinding[]): void {\n  for (const raw of inner.split(',')) {\n    const part = raw.trim()\n    if (!part) continue\n    const asM = /^(\\w+)\\s+as\\s+(\\w+)$/.exec(part) // ESM: A as C\n    const colonM = /^(\\w+)\\s*:\\s*(\\w+)$/.exec(part) // CJS: A: C\n    if (asM) out.push({ local: asM[2]!, kind: 'named', exportName: asM[1]!, specifier })\n    else if (colonM) out.push({ local: colonM[2]!, kind: 'named', exportName: colonM[1]!, specifier })\n    else {\n      const id = /^(\\w+)$/.exec(part)\n      if (id) out.push({ local: id[1]!, kind: 'named', exportName: id[1]!, specifier })\n    }\n  }\n}\n\nfunction parseImportBindings(content: string): ImportBinding[] {\n  const out: ImportBinding[] = []\n\n  const esm = /import\\s+([^;'\"`\\n]+?)\\s+from\\s*['\"`]([^'\"`]+)['\"`]/g\n  let m: RegExpExecArray | null\n  while ((m = esm.exec(content)) !== null) {\n    const clause = m[1]!.trim()\n    const spec = m[2]!\n    const ns = /^\\*\\s+as\\s+(\\w+)$/.exec(clause)\n    if (ns) {\n      out.push({ local: ns[1]!, kind: 'namespace', specifier: spec })\n      continue\n    }\n    const named = /\\{([^}]*)\\}/.exec(clause)\n    if (named) parseDestructure(named[1]!, spec, out)\n    const def = /^(\\w+)\\s*(?:,|$)/.exec(clause) // leading default binding, before any `{`\n    if (def && !clause.startsWith('{')) out.push({ local: def[1]!, kind: 'default', specifier: spec })\n  }\n\n  const cjs = /(?:const|let|var)\\s+(\\{[^}]*\\}|\\w+)\\s*=\\s*require\\(\\s*['\"`]([^'\"`]+)['\"`]\\s*\\)/g\n  while ((m = cjs.exec(content)) !== null) {\n    const lhs = m[1]!\n    const spec = m[2]!\n    if (lhs.startsWith('{')) parseDestructure(lhs.slice(1, -1), spec, out)\n    else out.push({ local: lhs, kind: 'whole', specifier: spec }) // require() default IS module.exports\n  }\n\n  return out\n}\n\n// A defining file's exports, keyed for both named and default/whole-module\n// import. `byName` treats every model var as a possible named export — valid\n// source can only import a name it actually exported, so a non-exported var is\n// never asked for. The default is the single-model file's model, or the one\n// named in `module.exports = X` / `export default X`.\nfunction fileExportsOf(content: string, pluralizeOn: boolean): FileExports | null {\n  const defs = collectModelDefs(content, pluralizeOn).filter((d) => d.resolved.kind === 'mongodb-collection')\n  if (defs.length === 0) return null\n\n  const byVar = new Map<string, string>()\n  for (const d of defs) if (d.varName) byVar.set(d.varName, d.resolved.name)\n\n  const byName = new Map(byVar)\n  let def: string | undefined\n\n  const named = /(?:module\\.exports|export\\s+default)\\s*=\\s*(\\w+)\\b/.exec(content)\n  if (named && byVar.has(named[1]!)) def = byVar.get(named[1]!)\n  if (!def) {\n    const inline =\n      /(?:module\\.exports|export\\s+default)\\s*=\\s*(?:await\\s+)?(?:\\w+\\s*\\.\\s*)?model\\s*\\(\\s*['\"`]([\\w$]+)['\"`]/.exec(content)\n    if (inline) def = pluralizeOn ? pluralizeCollection(inline[1]!) : inline[1]!\n  }\n  // Single-model file: a default/whole-module import binds to its one model.\n  if (!def && byVar.size === 1) def = [...byVar.values()][0]!\n\n  return { byName, ...(def ? { default: def } : {}) }\n}\n\n/**\n * Cross-file model→collection resolution (ADR-149). Names the collection at the\n * *query* site — `routes/orders.js` calling `Order.find()` on a model defined in\n * `models/Order.js` — by resolving the imported binding to its defining file\n * through the same import resolution `imports.ts` uses, then attributing the\n * query methods on that binding. Emits onto the same `mongodb-collection` node\n * the in-file and observed paths use, so all three fuse.\n *\n * `files` should be the same masked (comment-stripped) SourceFiles the per-file\n * pass sees. Returns endpoints whose evidence points at the query site.\n */\nexport async function mongooseCrossFileEndpoints(\n  files: SourceFile[],\n  serviceDir: string,\n): Promise<ExternalEndpoint[]> {\n  const mongooseFiles = files.filter((f) => MONGOOSE_IMPORT_RE.test(f.content))\n  if (mongooseFiles.length === 0) return []\n\n  // A single `pluralize(null)` anywhere flips derivation for the whole service.\n  const pluralizeOn = !files.some((f) => PLURALIZE_DISABLED_RE.test(f.content))\n\n  // Registry: service-relative posix path → its model exports.\n  const registry = new Map<string, FileExports>()\n  for (const f of mongooseFiles) {\n    const fx = fileExportsOf(f.content, pluralizeOn)\n    if (fx) registry.set(toPosix(path.relative(serviceDir, f.path)), fx)\n  }\n  if (registry.size === 0) return []\n\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n\n  for (const f of files) {\n    const bindings = parseImportBindings(f.content)\n    if (bindings.length === 0) continue\n\n    // Bindings that ARE a model (named/default import) → `local.method()`.\n    const directColl = new Map<string, string>()\n    // Whole-module / namespace bindings → `local.Export.method()`.\n    const nsExports = new Map<string, FileExports>()\n\n    for (const b of bindings) {\n      const resolvedRel = await resolveJsImport(b.specifier, path.dirname(f.path), serviceDir, null)\n      if (!resolvedRel) continue\n      const fx = registry.get(resolvedRel)\n      if (!fx) continue\n      if (b.kind === 'named' && b.exportName) {\n        const coll = fx.byName.get(b.exportName)\n        if (coll) directColl.set(b.local, coll)\n      } else if (b.kind === 'default') {\n        if (fx.default) directColl.set(b.local, fx.default)\n      } else {\n        // whole (require) or namespace — could be the model itself or the module object.\n        if (fx.default) directColl.set(b.local, fx.default)\n        nsExports.set(b.local, fx)\n      }\n    }\n    if (directColl.size === 0 && nsExports.size === 0) continue\n\n    // A binding defined *in this file* is the in-file pass's job — don't double-count.\n    const localDefs = new Set(\n      collectModelDefs(f.content, pluralizeOn)\n        .map((d) => d.varName)\n        .filter((v): v is string => v !== null),\n    )\n\n    const emit = (collection: string, matchText: string): void => {\n      const key = `${f.path}::${collection}`\n      if (seen.has(key)) return\n      seen.add(key)\n      out.push(endpoint({ name: collection, kind: 'mongodb-collection' }, f, serviceDir, matchText))\n    }\n\n    for (const [local, collection] of directColl) {\n      if (localDefs.has(local)) continue\n      const qre = new RegExp(`\\\\b${local}\\\\s*\\\\.\\\\s*(?:${MODEL_METHODS_ALT})\\\\s*\\\\(`, 'g')\n      let qm: RegExpExecArray | null\n      while ((qm = qre.exec(f.content)) !== null) emit(collection, qm[0])\n    }\n    for (const [local, fx] of nsExports) {\n      const qre = new RegExp(`\\\\b${local}\\\\s*\\\\.\\\\s*(\\\\w+)\\\\s*\\\\.\\\\s*(?:${MODEL_METHODS_ALT})\\\\s*\\\\(`, 'g')\n      let qm: RegExpExecArray | null\n      while ((qm = qre.exec(f.content)) !== null) {\n        const coll = fx.byName.get(qm[1]!)\n        if (coll) emit(coll, qm[0])\n      }\n    }\n  }\n\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport Python from 'tree-sitter-python'\nimport { infraId } from '@neat.is/types'\nimport { snippet, type ExternalEndpoint, type SourceFile, type TableReference } from './shared.js'\n\n// SQLAlchemy / Flask-SQLAlchemy table call sites (ADR-151, ADR-152). The SQL\n// analog of calls/mongoose.ts: it names the table a model maps to, so a\n// production SQLAlchemy query — whose OBSERVED table NEAT recovers by parsing the\n// `db.statement` SQL (the instrumentation emits no table attribute, ADR-152) —\n// has a file-grained static twin to fuse onto at `infra:sql-table:<name>`.\n//\n// The table name is the fusion key, derived VERBATIM the way the ORM derives it\n// so the static string matches the table the running query hits:\n//   - plain SQLAlchemy declarative:  __tablename__ = 'orders'   (explicit, required)\n//   - Flask-SQLAlchemy (no __tablename__):  camel_to_snake_case(ClassName)\n//       class UserProfile(db.Model): ...   → 'user_profile'\n//   - native Core:  Table('orders', metadata, ...)   → the string literal\n\nconst SQLALCHEMY_IMPORT_RE = /(?:from|import)\\s+(?:flask_sqlalchemy|sqlalchemy)\\b/\n\nconst PARSE_CHUNK = 16384\n\nfunction makePyParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Python)\n  return p\n}\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\n// Verbatim port of flask_sqlalchemy's `camel_to_snake_case` (model.py, v3.x):\n//   re.sub(r\"((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))\", r\"_\\1\", name).lower().lstrip(\"_\")\n// Reproduced byte-for-byte so a derived table matches the one Flask-SQLAlchemy\n// actually creates — `UserProfile` → `user_profile`, `HTTPRequest` →\n// `http_request`, `OAuth2Token` → `o_auth2_token`. Do not \"improve\" it: an\n// English-nicer version would name a table the ORM never created and fuse onto\n// nothing (the same fidelity rule the Mongoose pluralizer follows).\nexport function flaskSqlalchemyTableName(className: string): string {\n  return className\n    .replace(/((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))/g, '_$1')\n    .toLowerCase()\n    .replace(/^_+/, '')\n}\n\nfunction namedChildren(node: Parser.SyntaxNode): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const c = node.namedChild(i)\n    if (c) out.push(c)\n  }\n  return out\n}\n\nfunction pyStaticStringText(node: Parser.SyntaxNode): string | null {\n  if (node.type !== 'string') return null\n  for (const child of namedChildren(node)) {\n    if (child.type === 'interpolation') return null // f-string — not a static literal\n    if (child.type === 'string_content') return child.text\n  }\n  return ''\n}\n\n// The explicit `__tablename__ = 'x'` in a class body: its literal name, `'computed'`\n// when it's assigned a non-literal (never guessed), or null when absent.\nfunction explicitTablename(body: Parser.SyntaxNode): { name: string } | 'computed' | null {\n  for (const stmt of namedChildren(body)) {\n    if (stmt.type !== 'expression_statement') continue\n    const assign = stmt.namedChild(0)\n    if (assign?.type !== 'assignment') continue\n    if (assign.childForFieldName('left')?.text !== '__tablename__') continue\n    const right = assign.childForFieldName('right')\n    if (right?.type === 'string') {\n      const s = pyStaticStringText(right)\n      return s ? { name: s } : 'computed'\n    }\n    return 'computed'\n  }\n  return null\n}\n\n// A Flask-SQLAlchemy model derives its table from the class name when it has no\n// `__tablename__` — recognised by a `db.Model` / `Model` base class.\nfunction extendsFlaskModel(cls: Parser.SyntaxNode): boolean {\n  const supers = cls.childForFieldName('superclasses')\n  if (!supers) return false\n  for (const a of namedChildren(supers)) {\n    const t = a.text\n    if (t === 'db.Model' || t === 'Model' || t.endsWith('.Model')) return true\n  }\n  return false\n}\n\nfunction walk(node: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (const c of namedChildren(node)) walk(c, visit)\n}\n\n// ── declared columns off a SQLAlchemy model body (ADR-157 §3) ────────────────\n\n// The bare builder name a `Column(...)` / `mapped_column(...)` call resolves to,\n// tolerating a `db.` / `sa.` / `orm.` qualifier. Anything else (a `relationship`,\n// a plain value) is not a column.\nconst COLUMN_BUILDERS = new Set(['Column', 'mapped_column'])\nfunction isColumnBuilder(call: Parser.SyntaxNode): boolean {\n  const fn = call.childForFieldName('function')\n  const t = fn?.text\n  if (!t) return false\n  const base = t.includes('.') ? t.slice(t.lastIndexOf('.') + 1) : t\n  return COLUMN_BUILDERS.has(base)\n}\n\n// The first positional argument of a call as a static string, or null when the\n// first positional argument is not a plain string literal (a type like `Integer`)\n// — so the caller falls back to the attribute name.\nfunction firstPositionalString(call: Parser.SyntaxNode): string | null {\n  const args = call.childForFieldName('arguments')\n  if (!args) return null\n  for (const arg of namedChildren(args)) {\n    if (arg.type === 'keyword_argument') continue\n    return arg.type === 'string' ? pyStaticStringText(arg) : null\n  }\n  return null\n}\n\n// The DB columns a declarative model body declares. For each `x = Column(...)` /\n// `x: Mapped[..] = mapped_column(...)` assignment, the column name is the explicit\n// first-string argument where given (`Column('total_amount', Integer)` →\n// `total_amount`), else the attribute name itself — SQLAlchemy's own rule, where\n// the attribute name IS the column name (ADR-157 §3). Non-Column assignments\n// (`__tablename__`, `relationship(...)`) are skipped, and a computed / non-string\n// explicit name is left unclaimed rather than guessed.\nfunction columnsFromClassBody(body: Parser.SyntaxNode): string[] {\n  const out: string[] = []\n  const seen = new Set<string>()\n  for (const stmt of namedChildren(body)) {\n    if (stmt.type !== 'expression_statement') continue\n    const assign = stmt.namedChild(0)\n    if (assign?.type !== 'assignment') continue\n    const left = assign.childForFieldName('left')\n    if (left?.type !== 'identifier') continue\n    const right = assign.childForFieldName('right')\n    if (right?.type !== 'call' || !isColumnBuilder(right)) continue\n    const name = firstPositionalString(right) ?? left.text\n    if (name && !seen.has(name)) {\n      seen.add(name)\n      out.push(name)\n    }\n  }\n  return out\n}\n\n// ── foreign-key table→table references (ADR-161) ─────────────────────────────\n//\n// SQLAlchemy names a FK by the DATABASE table directly: `ForeignKey('users.id')`\n// — the string is `<table>.<column>` (or `<schema>.<table>.<column>`), so the\n// parent table is the segment before the last dot, already at DB-name fidelity\n// (no code-model translation needed, unlike Drizzle/Prisma). The child is the\n// enclosing model's `__tablename__` / Flask-derived table, the same table the\n// column read (ADR-157 §3) lands on. A non-string `ForeignKey(User.id)` (a mapped\n// attribute) is left unclaimed — resolving the class→table there is a follow-on.\n\n// The parent DB table a `ForeignKey('users.id')` names, tolerating a `db.` / `sa.`\n// / `sqlalchemy.` qualifier on the call. Null for a non-string / bare argument.\nfunction foreignKeyParentTable(call: Parser.SyntaxNode): string | null {\n  const fn = call.childForFieldName('function')\n  const t = fn?.text\n  if (!t) return null\n  const base = t.includes('.') ? t.slice(t.lastIndexOf('.') + 1) : t\n  if (base !== 'ForeignKey') return null\n  const target = firstPositionalString(call)\n  if (!target) return null\n  const parts = target.split('.')\n  if (parts.length < 2) return null // needs at least `<table>.<column>`\n  return parts[parts.length - 2]! // `users.id` → users; `public.users.id` → users\n}\n\nexport function sqlalchemyForeignKeys(\n  file: SourceFile,\n  serviceDir: string,\n): TableReference[] {\n  if (!SQLALCHEMY_IMPORT_RE.test(file.content)) return []\n  const tree = parseSource(makePyParser(), file.content)\n  const out: TableReference[] = []\n  const seen = new Set<string>()\n\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'class_definition') return\n    const body = node.childForFieldName('body')\n    const nameNode = node.childForFieldName('name')\n    if (!body || !nameNode) return\n    const explicit = explicitTablename(body)\n    if (explicit === 'computed') return // named but not a literal — never guess\n    let childTable: string | null = null\n    if (explicit) childTable = explicit.name\n    else if (extendsFlaskModel(node)) childTable = flaskSqlalchemyTableName(nameNode.text)\n    if (!childTable) return\n\n    walk(body, (n) => {\n      if (n.type !== 'call') return\n      const parentTable = foreignKeyParentTable(n)\n      if (!parentTable) return\n      const key = `${childTable}->${parentTable}`\n      if (seen.has(key)) return\n      seen.add(key)\n      const line = n.startPosition.row + 1\n      out.push({\n        childTable: childTable!,\n        parentTable,\n        evidence: {\n          file: path.relative(serviceDir, file.path),\n          line,\n          snippet: snippet(file.content, line),\n        },\n      })\n    })\n  })\n\n  return out\n}\n\nexport function sqlalchemyEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  if (!SQLALCHEMY_IMPORT_RE.test(file.content)) return []\n  const tree = parseSource(makePyParser(), file.content)\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n  const push = (name: string, line: number, columns?: string[]): void => {\n    if (seen.has(name)) return\n    seen.add(name)\n    out.push({\n      infraId: infraId('sql-table', name),\n      name,\n      kind: 'sql-table',\n      edgeType: 'CALLS',\n      confidenceKind: 'verified-call-site',\n      ...(columns && columns.length > 0 ? { columns } : {}),\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  }\n\n  walk(tree.rootNode, (node) => {\n    if (node.type === 'class_definition') {\n      const body = node.childForFieldName('body')\n      const nameNode = node.childForFieldName('name')\n      if (!body || !nameNode) return\n      const line = node.startPosition.row + 1\n      const explicit = explicitTablename(body)\n      if (explicit === 'computed') return // named but not a literal — never guess\n      // Declared columns off the model body — the DB name at attribute grain.\n      const columns = columnsFromClassBody(body)\n      if (explicit) {\n        push(explicit.name, line, columns)\n        return\n      }\n      // No __tablename__: Flask-SQLAlchemy derives the table from the class name.\n      if (extendsFlaskModel(node)) push(flaskSqlalchemyTableName(nameNode.text), line, columns)\n      return\n    }\n    // Native Core: `Table('orders', metadata, ...)` — the first positional string.\n    if (node.type === 'call') {\n      const fn = node.childForFieldName('function')\n      const fnText = fn?.text\n      if (fnText !== 'Table' && fnText !== 'sa.Table' && fnText !== 'sqlalchemy.Table') return\n      const first = node.childForFieldName('arguments')?.namedChild(0)\n      if (first?.type === 'string') {\n        const s = pyStaticStringText(first)\n        if (s) push(s, node.startPosition.row + 1)\n      }\n    }\n  })\n\n  return out\n}\n\n// ── cross-file model→table query attribution (ADR-149 analog) ────────────────\n\n// A model class name → its table, service-wide (SQLAlchemy + Flask-SQLAlchemy). A\n// name defined in two files with different tables is dropped — ambiguous, never\n// guessed (the ADR-147 discipline).\nfunction buildSqlalchemyModelRegistry(files: SourceFile[]): Map<string, string> {\n  const table = new Map<string, string>()\n  const ambiguous = new Set<string>()\n  const parser = makePyParser()\n  for (const file of files) {\n    if (!SQLALCHEMY_IMPORT_RE.test(file.content)) continue\n    const tree = parseSource(parser, file.content)\n    walk(tree.rootNode, (node) => {\n      if (node.type !== 'class_definition') return\n      const nameNode = node.childForFieldName('name')\n      const body = node.childForFieldName('body')\n      if (!nameNode || !body) return\n      const explicit = explicitTablename(body)\n      if (explicit === 'computed') return\n      let t: string | null = null\n      if (explicit) t = explicit.name\n      else if (extendsFlaskModel(node)) t = flaskSqlalchemyTableName(nameNode.text)\n      if (!t) return\n      const cls = nameNode.text\n      if (table.has(cls) && table.get(cls) !== t) ambiguous.add(cls)\n      else table.set(cls, t)\n    })\n  }\n  for (const a of ambiguous) table.delete(a)\n  return table\n}\n\n// The model class names a file queries: `session.query(X)` / `db.session.query(X)`\n// / `select(X)` / `session.get(X, …)` (the first argument), and `X.query`\n// (Flask-SQLAlchemy, the object). A non-model receiver (`session.query`) is\n// filtered downstream by the registry.\nfunction queryClassSites(root: Parser.SyntaxNode): { cls: string; line: number }[] {\n  const out: { cls: string; line: number }[] = []\n  walk(root, (node) => {\n    if (node.type === 'call') {\n      const fn = node.childForFieldName('function')\n      const isQueryCall =\n        (fn?.type === 'attribute' &&\n          (fn.childForFieldName('attribute')?.text === 'query' ||\n            fn.childForFieldName('attribute')?.text === 'get')) ||\n        (fn?.type === 'identifier' && fn.text === 'select')\n      if (isQueryCall) {\n        const arg = node.childForFieldName('arguments')?.namedChild(0)\n        if (arg?.type === 'identifier') out.push({ cls: arg.text, line: node.startPosition.row + 1 })\n      }\n    }\n    if (node.type === 'attribute') {\n      const obj = node.childForFieldName('object')\n      if (node.childForFieldName('attribute')?.text === 'query' && obj?.type === 'identifier') {\n        out.push({ cls: obj.text, line: node.startPosition.row + 1 })\n      }\n    }\n  })\n  return out\n}\n\n// Does a file import this name — so a query on it references a model defined\n// elsewhere? Bounds the attribution to a real cross-file reference (the in-file\n// case is already the definition-site edge).\nfunction importsModelName(content: string, name: string): boolean {\n  return new RegExp(`\\\\bimport\\\\b[^\\\\n]*\\\\b${name}\\\\b`).test(content)\n}\n\n// Attribute a cross-file query to its table at the *query* site: a file that runs\n// `session.query(Order)` on an `Order` model defined and imported from another\n// file gets the `file → sql-table:<name>` edge, so the code that actually reads\n// the table is named — not only the model-definition file. A computed model, or\n// a query on a locally-defined model (already the definition-site edge), is not\n// re-emitted here.\nexport function pythonOrmCrossFileEndpoints(\n  files: SourceFile[],\n  serviceDir: string,\n): ExternalEndpoint[] {\n  const registry = buildSqlalchemyModelRegistry(files)\n  if (registry.size === 0) return []\n  const parser = makePyParser()\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n  for (const file of files) {\n    if (!SQLALCHEMY_IMPORT_RE.test(file.content)) continue\n    const tree = parseSource(parser, file.content)\n    for (const { cls, line } of queryClassSites(tree.rootNode)) {\n      const t = registry.get(cls)\n      if (!t) continue\n      if (!importsModelName(file.content, cls)) continue // cross-file (imported) only\n      const key = `${file.path}::${t}`\n      if (seen.has(key)) continue\n      seen.add(key)\n      out.push({\n        infraId: infraId('sql-table', t),\n        name: t,\n        kind: 'sql-table',\n        edgeType: 'CALLS',\n        confidenceKind: 'verified-call-site',\n        evidence: {\n          file: path.relative(serviceDir, file.path),\n          line,\n          snippet: snippet(file.content, line),\n        },\n      })\n    }\n  }\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport Python from 'tree-sitter-python'\nimport { infraId } from '@neat.is/types'\nimport { snippet, type ExternalEndpoint, type SourceFile } from './shared.js'\n\n// Raw TCP socket dependencies in Python: `socket.socket(...)` paired with a\n// `<sock>.connect((host, port))`. Frameworked clients have their own recognizers\n// (gRPC stubs, `redis://` URLs, SQLAlchemy models, ...); this catches the bare-socket\n// dependency those miss — a service that speaks a custom line protocol to a datastore\n// over `socket.connect((host, port))`, which otherwise leaves NO EXTRACTED edge at all,\n// so a runtime connection-refused on that hop has no static twin to fuse onto and the\n// dependency is invisible past the last instrumented call.\n//\n// Precision — gated on both `import socket` AND a `socket.socket(...)` constructor in\n// the file, then only a `.connect(...)` whose single positional argument is a 2-element\n// address TUPLE. That tuple is socket.connect's distinctive signature: a DB driver or\n// ORM `.connect()` takes a URL or keyword arguments, never a bare `(host, port)` pair,\n// so the tuple shape is what separates a real socket connect from an unrelated\n// `.connect()` method call.\n//\n// Target naming honors \"evidence is never fabricated\": a string-literal host resolves\n// to a named `infra:socket:<host>[:<port>]` endpoint; a non-literal host — a variable or\n// env-driven address, e.g. `s.connect((host, port))` where `host` came from\n// `os.environ` — is not guessed, it lands on a stable `infra:socket:env` sentinel, the\n// same honest-sentinel discipline calls/supabase.ts uses for `process.env`-driven URLs.\n// Resolving an env-var name or its .env value to the concrete host is a follow-on.\n\nconst SOCKET_IMPORT_RE = /(?:^|\\n)\\s*(?:import\\s+socket\\b|from\\s+socket\\s+import\\b)/\n\nconst PARSE_CHUNK = 16384\n\nfunction makePyParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Python)\n  return p\n}\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nfunction namedChildren(node: Parser.SyntaxNode): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const c = node.namedChild(i)\n    if (c) out.push(c)\n  }\n  return out\n}\n\nfunction walk(node: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (const c of namedChildren(node)) walk(c, visit)\n}\n\nfunction pyStaticStringText(node: Parser.SyntaxNode): string | null {\n  if (node.type !== 'string') return null\n  for (const child of namedChildren(node)) {\n    if (child.type === 'interpolation') return null // f-string — not a static literal\n    if (child.type === 'string_content') return child.text\n  }\n  return ''\n}\n\n// The file constructs a raw socket: `socket.socket(...)`, or a `from socket import\n// socket` then a bare `socket(...)`. This gate keeps a `.connect(tuple)` on some other\n// object from ever being read as a socket connect.\nfunction hasSocketConstructor(root: Parser.SyntaxNode): boolean {\n  let found = false\n  walk(root, (n) => {\n    if (found || n.type !== 'call') return\n    const t = n.childForFieldName('function')?.text\n    if (t === 'socket.socket' || t === 'socket') found = true\n  })\n  return found\n}\n\nexport function socketEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  if (!SOCKET_IMPORT_RE.test(file.content)) return []\n  const tree = parseSource(makePyParser(), file.content)\n  if (!hasSocketConstructor(tree.rootNode)) return []\n\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'call') return\n    const fn = node.childForFieldName('function')\n    if (fn?.type !== 'attribute' || fn.childForFieldName('attribute')?.text !== 'connect') return\n    const args = node.childForFieldName('arguments')\n    const first = args ? namedChildren(args).find((a) => a.type !== 'keyword_argument') : undefined\n    // socket.connect's one positional argument is the address TUPLE `(host, port)` —\n    // the discriminator that separates it from an unrelated `.connect()`.\n    if (!first || first.type !== 'tuple') return\n    const elems = namedChildren(first)\n    if (elems.length < 2) return\n\n    const hostNode = elems[0]!\n    const host = hostNode.type === 'string' ? pyStaticStringText(hostNode) : null\n    const portNode = elems[1]!\n    const port = portNode.type === 'integer' ? portNode.text : null\n    // Literal host → named endpoint; non-literal (variable / env-driven) → honest\n    // sentinel, never a guessed host.\n    const name = host ? (port ? `${host}:${port}` : host) : 'env'\n    if (seen.has(name)) return\n    seen.add(name)\n\n    const line = node.startPosition.row + 1\n    out.push({\n      infraId: infraId('socket', name),\n      name,\n      kind: 'socket',\n      edgeType: 'CALLS',\n      // A verified `socket.socket(...)` + `.connect((host, port))` call site.\n      confidenceKind: 'verified-call-site',\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  })\n\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport Python from 'tree-sitter-python'\nimport { infraId } from '@neat.is/types'\nimport { snippet, type ExternalEndpoint, type SourceFile } from './shared.js'\n\n// Django ORM table call sites (ADR-151). A Django model maps to a table named\n// `<app_label>_<lowercased-model>` unless `Meta.db_table` overrides it; the\n// app_label defaults to the model file's app package (its parent directory),\n// overridable by `Meta.app_label`. This is Django's naming reproduced verbatim —\n// the fusion key, the same discipline the Mongoose pluralizer follows.\n//\n// It emits the same `infra:sql-table:<name>` node the SQLAlchemy extractor and\n// the OBSERVED `db.statement` parse (ADR-152) use, so a declared Django model and\n// the runtime query that hits its table fuse onto one node.\n\nconst DJANGO_IMPORT_RE = /(?:from|import)\\s+django\\b/\nconst PARSE_CHUNK = 16384\n\nfunction makePyParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Python)\n  return p\n}\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nfunction namedChildren(node: Parser.SyntaxNode): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const c = node.namedChild(i)\n    if (c) out.push(c)\n  }\n  return out\n}\n\nfunction pyStaticStringText(node: Parser.SyntaxNode): string | null {\n  if (node.type !== 'string') return null\n  for (const c of namedChildren(node)) {\n    if (c.type === 'interpolation') return null\n    if (c.type === 'string_content') return c.text\n  }\n  return ''\n}\n\nfunction walk(node: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (const c of namedChildren(node)) walk(c, visit)\n}\n\nfunction extendsDjangoModel(cls: Parser.SyntaxNode): boolean {\n  const supers = cls.childForFieldName('superclasses')\n  if (!supers) return false\n  for (const a of namedChildren(supers)) {\n    const t = a.text\n    if (t === 'models.Model' || t === 'Model' || t.endsWith('.Model')) return true\n  }\n  return false\n}\n\n// Read `Meta.db_table` / `Meta.app_label` off a model class body (both literal).\nfunction readMeta(body: Parser.SyntaxNode): { dbTable?: string; appLabel?: string } {\n  const out: { dbTable?: string; appLabel?: string } = {}\n  for (const stmt of namedChildren(body)) {\n    if (stmt.type !== 'class_definition') continue\n    if (stmt.childForFieldName('name')?.text !== 'Meta') continue\n    const metaBody = stmt.childForFieldName('body')\n    if (!metaBody) continue\n    for (const ms of namedChildren(metaBody)) {\n      if (ms.type !== 'expression_statement') continue\n      const a = ms.namedChild(0)\n      if (a?.type !== 'assignment') continue\n      const l = a.childForFieldName('left')?.text\n      const r = a.childForFieldName('right')\n      if (r?.type !== 'string') continue\n      if (l === 'db_table') out.dbTable = pyStaticStringText(r) ?? undefined\n      if (l === 'app_label') out.appLabel = pyStaticStringText(r) ?? undefined\n    }\n  }\n  return out\n}\n\nexport function djangoOrmEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  if (!DJANGO_IMPORT_RE.test(file.content)) return []\n  const tree = parseSource(makePyParser(), file.content)\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n  // The app_label defaults to the model file's app package — its parent directory.\n  const defaultAppLabel = path.basename(path.dirname(file.path))\n\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'class_definition') return\n    if (!extendsDjangoModel(node)) return\n    const nameNode = node.childForFieldName('name')\n    const body = node.childForFieldName('body')\n    if (!nameNode || !body) return\n    const meta = readMeta(body)\n    const table = meta.dbTable ?? `${meta.appLabel ?? defaultAppLabel}_${nameNode.text.toLowerCase()}`\n    if (seen.has(table)) return\n    seen.add(table)\n    const line = node.startPosition.row + 1\n    out.push({\n      infraId: infraId('sql-table', table),\n      name: table,\n      kind: 'sql-table',\n      edgeType: 'CALLS',\n      confidenceKind: 'verified-call-site',\n      evidence: { file: path.relative(serviceDir, file.path), line, snippet: snippet(file.content, line) },\n    })\n  })\n\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport JavaScript from 'tree-sitter-javascript'\nimport { infraId } from '@neat.is/types'\nimport { GRAMMAR_BY_EXT, parseSource } from '../symbols.js'\nimport { snippet, type ExternalEndpoint, type SourceFile, type TableReference } from './shared.js'\n\n// Drizzle schema table + column recognizer (ADR-152 table, ADR-157 §3 columns).\n// The declared side of column grain: it names the table a `pgTable('orders',\n// { … })` (mysqlTable / sqliteTable) declares AND the columns inside it, so a\n// production query — whose OBSERVED table + columns NEAT recovers by parsing\n// `db.statement` (ADR-152 / ADR-157 §2) — has a static twin to fuse onto at\n// `infra:sql-table:<name>`.\n//\n//   import { pgTable, integer, text } from 'drizzle-orm/pg-core'\n//   export const orders = pgTable('orders', {\n//     id: serial('id').primaryKey(),\n//     userId: integer('user_id'),\n//     total: integer(),\n//     status: text('status'),\n//   })\n//\n// The table name is the first string literal. Each COLUMN name is derived the way\n// Drizzle names the DB column, because that string — not the JS field name — is\n// the fusion key the running query carries (ADR-157 §3, the load-bearing rule):\n//   - the explicit column-builder name wins:  integer('user_id')  → user_id\n//   - the object key is Drizzle's own fallback when the builder is given no\n//     name:                                    total: integer()   → total\n// Reading the key alone would name `userId` where production writes `user_id` and\n// fuse onto nothing — the same fidelity rule the Mongoose pluralizer (ADR-147) and\n// the Flask table-name port (ADR-152) follow. A computed / interpolated name is\n// left unclaimed rather than guessed.\n\nconst DRIZZLE_IMPORT_RE = /drizzle-orm/\nconst TABLE_BUILDERS = new Set(['pgTable', 'mysqlTable', 'sqliteTable'])\n\nfunction parserForExt(ext: string): Parser {\n  const p = new Parser()\n  p.setLanguage(GRAMMAR_BY_EXT[ext] ?? JavaScript)\n  return p\n}\n\nfunction namedChildren(node: Parser.SyntaxNode): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const c = node.namedChild(i)\n    if (c) out.push(c)\n  }\n  return out\n}\n\n// The literal text inside a `string` node (quotes stripped). Null for a template\n// / interpolated string — never guessed at.\nfunction stringLiteralText(node: Parser.SyntaxNode | null): string | null {\n  if (!node || node.type !== 'string') return null\n  for (const child of namedChildren(node)) {\n    if (child.type === 'string_fragment') return child.text\n  }\n  return '' // an empty '' literal has no string_fragment child\n}\n\n// The first positional string argument of a call, or null when the first\n// argument is not a plain string literal (so the caller falls back to the key).\nfunction firstStringArg(call: Parser.SyntaxNode): string | null {\n  const args = call.childForFieldName('arguments')\n  if (!args) return null\n  for (const arg of namedChildren(args)) {\n    if (arg.type === 'string') return stringLiteralText(arg)\n    // Stop at the first positional arg — a non-string first arg means no name.\n    return null\n  }\n  return null\n}\n\n// The DB column name a Drizzle column value declares. Walks to the head builder\n// call at the base of a `.primaryKey().notNull()` chain and reads its first\n// string argument (the explicit column name). Null when the builder is given no\n// name, so the caller falls back to the object key — exactly as Drizzle does.\nfunction builderColumnName(value: Parser.SyntaxNode): string | null {\n  let node: Parser.SyntaxNode | null = value\n  while (node) {\n    if (node.type === 'call_expression') {\n      const fn = node.childForFieldName('function')\n      if (fn?.type === 'identifier') return firstStringArg(node)\n      if (fn?.type === 'member_expression') {\n        node = fn.childForFieldName('object')\n        continue\n      }\n      return null\n    }\n    if (node.type === 'member_expression') {\n      node = node.childForFieldName('object')\n      continue\n    }\n    return null\n  }\n  return null\n}\n\n// A pair key → its column-name string (a bare `total:` or a quoted `'total':`).\nfunction keyName(key: Parser.SyntaxNode | null): string | null {\n  if (!key) return null\n  if (key.type === 'property_identifier') return key.text\n  if (key.type === 'string') return stringLiteralText(key)\n  return null\n}\n\n// The columns declared in a pgTable's second-argument object. Reads each `pair`,\n// preferring the builder's explicit name over the object key, and skips spreads /\n// computed keys rather than guessing.\nfunction columnsFromObject(obj: Parser.SyntaxNode): string[] {\n  const out: string[] = []\n  const seen = new Set<string>()\n  for (const child of namedChildren(obj)) {\n    if (child.type !== 'pair') continue\n    const value = child.childForFieldName('value')\n    const key = keyName(child.childForFieldName('key'))\n    const name = (value ? builderColumnName(value) : null) ?? key\n    if (name && !seen.has(name)) {\n      seen.add(name)\n      out.push(name)\n    }\n  }\n  return out\n}\n\nexport function drizzleEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  if (!DRIZZLE_IMPORT_RE.test(file.content)) return []\n  const tree = parseSource(parserForExt(path.extname(file.path)), file.content)\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n\n  const walk = (node: Parser.SyntaxNode): void => {\n    if (node.type === 'call_expression') {\n      const fn = node.childForFieldName('function')\n      if (fn?.type === 'identifier' && TABLE_BUILDERS.has(fn.text)) {\n        const args = node.childForFieldName('arguments')\n        const argNodes = args ? namedChildren(args) : []\n        const tableName = stringLiteralText(argNodes[0] ?? null)\n        const obj = argNodes[1]\n        if (tableName && obj?.type === 'object' && !seen.has(tableName)) {\n          seen.add(tableName)\n          const columns = columnsFromObject(obj)\n          const line = node.startPosition.row + 1\n          out.push({\n            infraId: infraId('sql-table', tableName),\n            name: tableName,\n            kind: 'sql-table',\n            edgeType: 'CALLS',\n            confidenceKind: 'structural',\n            columns,\n            evidence: {\n              file: path.relative(serviceDir, file.path),\n              line,\n              snippet: snippet(file.content, line),\n            },\n          })\n        }\n      }\n    }\n    for (const c of namedChildren(node)) walk(c)\n  }\n\n  walk(tree.rootNode)\n  return out\n}\n\n// ── foreign-key table→table references (ADR-161) ─────────────────────────────\n//\n// Drizzle declares a FK inline on the column: `.references(() => users.id)`. The\n// referenced `users` is the schema *variable*, so the DB parent-table name is the\n// variable's own `pgTable('...')` first-string argument, NOT the variable name —\n// `export const appUsers = pgTable('app_users', …)` referenced as\n// `.references(() => appUsers.id)` is a FK onto `app_users`. Resolving through the\n// in-file variable→table map keeps the parent at DB-name fidelity, the same\n// fusion key the column/table read (ADR-157 §3) and OTLP already land on. A\n// reference to a table not declared in this file (imported from another schema\n// module) resolves to nothing and is left unclaimed — cross-file FK resolution is\n// a follow-on, not a guess.\n\ninterface DrizzleTable {\n  tableName: string\n  object: Parser.SyntaxNode | null\n}\n\n// Climb from a table-builder call to the `const <var> = …` it is bound to, so the\n// variable a `.references()` names can be resolved back to the DB table. Returns\n// the variable name, or null when the call is not a simple named binding.\nfunction enclosingVarName(call: Parser.SyntaxNode): string | null {\n  let node: Parser.SyntaxNode | null = call\n  while (node?.parent) {\n    const parent = node.parent\n    if (parent.type === 'variable_declarator') {\n      const name = parent.childForFieldName('name')\n      return name?.type === 'identifier' ? name.text : null\n    }\n    // Climb through a wrapping call/member (`pgTable(...).$type<X>()`).\n    if (parent.type === 'call_expression' || parent.type === 'member_expression') {\n      node = parent\n      continue\n    }\n    return null\n  }\n  return null\n}\n\n// Every table-builder declaration in the file: the DB table name (first string\n// argument) and its column object, plus a variable→table map for FK resolution.\nfunction collectDrizzleTables(root: Parser.SyntaxNode): {\n  tables: DrizzleTable[]\n  varToTable: Map<string, string>\n} {\n  const tables: DrizzleTable[] = []\n  const varToTable = new Map<string, string>()\n  const walk = (node: Parser.SyntaxNode): void => {\n    if (node.type === 'call_expression') {\n      const fn = node.childForFieldName('function')\n      if (fn?.type === 'identifier' && TABLE_BUILDERS.has(fn.text)) {\n        const args = node.childForFieldName('arguments')\n        const argNodes = args ? namedChildren(args) : []\n        const tableName = stringLiteralText(argNodes[0] ?? null)\n        const obj = argNodes[1]?.type === 'object' ? argNodes[1] : null\n        if (tableName) {\n          tables.push({ tableName, object: obj })\n          const varName = enclosingVarName(node)\n          if (varName) varToTable.set(varName, tableName)\n        }\n      }\n    }\n    for (const c of namedChildren(node)) walk(c)\n  }\n  walk(root)\n  return { tables, varToTable }\n}\n\n// The referenced table *variable* of a `.references(() => X.col)` call, or null\n// when the target is not a plain `X.col` member on a variable — a computed or\n// dynamic reference (`.references(() => makeRef().id)`) is left unclaimed.\nfunction referencesTargetVar(call: Parser.SyntaxNode): string | null {\n  const fn = call.childForFieldName('function')\n  if (fn?.type !== 'member_expression') return null\n  if (fn.childForFieldName('property')?.text !== 'references') return null\n  const args = call.childForFieldName('arguments')\n  const first = args ? (namedChildren(args)[0] ?? null) : null\n  if (first?.type !== 'arrow_function') return null\n  const body = first.childForFieldName('body')\n  if (body?.type !== 'member_expression') return null\n  const obj = body.childForFieldName('object')\n  return obj?.type === 'identifier' ? obj.text : null\n}\n\nexport function drizzleForeignKeys(file: SourceFile, serviceDir: string): TableReference[] {\n  if (!DRIZZLE_IMPORT_RE.test(file.content)) return []\n  const tree = parseSource(parserForExt(path.extname(file.path)), file.content)\n  const { tables, varToTable } = collectDrizzleTables(tree.rootNode)\n  const out: TableReference[] = []\n  const seen = new Set<string>()\n\n  for (const table of tables) {\n    if (!table.object) continue\n    const walk = (node: Parser.SyntaxNode): void => {\n      if (node.type === 'call_expression') {\n        const targetVar = referencesTargetVar(node)\n        const parentTable = targetVar ? varToTable.get(targetVar) : undefined\n        if (parentTable) {\n          const key = `${table.tableName}->${parentTable}`\n          if (!seen.has(key)) {\n            seen.add(key)\n            const line = node.startPosition.row + 1\n            out.push({\n              childTable: table.tableName,\n              parentTable,\n              evidence: {\n                file: path.relative(serviceDir, file.path),\n                line,\n                snippet: snippet(file.content, line),\n              },\n            })\n          }\n        }\n      }\n      for (const c of namedChildren(node)) walk(c)\n    }\n    walk(table.object)\n  }\n\n  return out\n}\n","import path from 'node:path'\nimport { infraId } from '@neat.is/types'\nimport { findFirst, readIfExists } from '../databases/shared.js'\nimport { snippet, type ExternalEndpoint, type SourceFile, type TableReference } from './shared.js'\n\n// Prisma schema table + column recognizer (ADR-157 §3 columns, the named\n// follow-on the ADR reserves after Drizzle). The declared side of column grain\n// for Prisma: it reads each `model` block in `schema.prisma` and emits the table\n// that model maps to AND the scalar columns it declares, so a production query —\n// whose OBSERVED table + columns NEAT recovers by parsing `db.statement`\n// (ADR-152 / ADR-157 §2) — has a static twin to fuse onto at\n// `infra:sql-table:<name>`.\n//\n//   model Article {\n//     id          Int       @id @default(autoincrement())\n//     title       String\n//     body        String    @map(\"article_body\")\n//     authorId    Int\n//     author      User      @relation(fields: [authorId], references: [id])\n//     comments    Comment[]\n//     @@map(\"articles\")\n//   }\n//\n// The fidelity rules are the load-bearing part (ADR-157 §3 — the fusion key the\n// running query carries is the DATABASE name, not the code name):\n//   - TABLE name  = the model name verbatim (Prisma's default is PascalCase, NOT\n//     snake-cased), or the `@@map(\"name\")` value when the model declares one.\n//   - COLUMN name = the field name verbatim, or the `@map(\"db_col\")` value when\n//     the field declares one. Prisma does NOT snake_case by default, so `authorId`\n//     is the column, not `author_id`.\n// A scalar field (`Int String Boolean DateTime Float Decimal BigInt Bytes Json`,\n// or an enum-typed field) is a column — foreign-key scalars like `authorId Int`\n// included. A relation field is NOT a column and is skipped: a field whose base\n// type is another declared model (`author User`, `comments Comment[]`) or that\n// carries `@relation(...)`. `schema.prisma` is not JS, so it is read as text with\n// a small block scanner (the same read-polyglot-as-data discipline `proto.ts`\n// follows). A field whose type is neither a scalar, a declared enum, nor a\n// declared model is left unclaimed rather than guessed.\n\nconst SCALAR_TYPES = new Set([\n  'Int',\n  'String',\n  'Boolean',\n  'DateTime',\n  'Float',\n  'Decimal',\n  'BigInt',\n  'Bytes',\n  'Json',\n])\n\n// Drop a trailing `//` line comment, respecting `\"...\"` strings so a `//` inside\n// a URL default (`@default(\"https://…\")`) is not mistaken for a comment.\nfunction stripLineComment(line: string): string {\n  let inStr = false\n  for (let i = 0; i < line.length; i++) {\n    const ch = line[i]\n    if (ch === '\"' && line[i - 1] !== '\\\\') inStr = !inStr\n    else if (!inStr && ch === '/' && line[i + 1] === '/') return line.slice(0, i)\n  }\n  return line\n}\n\n// Net `{` minus `}` on a line, ignoring comments and string contents so a brace\n// inside a default value can't unbalance the block scan. Prisma blocks don't\n// nest, but counting keeps the scan robust to odd formatting.\nfunction netBraces(line: string): number {\n  const s = stripLineComment(line).replace(/\"(\\\\.|[^\"\\\\])*\"/g, '')\n  let n = 0\n  for (const ch of s) {\n    if (ch === '{') n++\n    else if (ch === '}') n--\n  }\n  return n\n}\n\ninterface ModelBlock {\n  kind: string\n  tableName: string\n  startLine: number\n  columns: string[]\n  seenCol: Set<string>\n}\n\n// Parse a `schema.prisma`'s model blocks into `sql-table` endpoints carrying the\n// declared columns at database-name fidelity. Pure over the file content so a\n// test can drive it without touching the filesystem, mirroring\n// `drizzleEndpointsFromFile`.\nexport function prismaColumnsFromSchema(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  const content = file.content\n  if (!/\\bmodel\\s+[A-Za-z_]\\w*\\s*\\{/.test(content)) return []\n\n  const lines = content.split('\\n')\n\n  // First pass: the declared model + enum names. A field whose base type is a\n  // model name is a relation (skipped); an enum-typed field is a column. Names\n  // are collected up front so a relation to a model declared later in the file\n  // still resolves.\n  const modelNames = new Set<string>()\n  const enumNames = new Set<string>()\n  for (const line of lines) {\n    const m = line.match(/^\\s*model\\s+([A-Za-z_]\\w*)\\s*\\{/)\n    if (m) modelNames.add(m[1]!)\n    const e = line.match(/^\\s*enum\\s+([A-Za-z_]\\w*)\\s*\\{/)\n    if (e) enumNames.add(e[1]!)\n  }\n\n  const out: ExternalEndpoint[] = []\n  const seenTable = new Set<string>()\n\n  const finalize = (b: ModelBlock): void => {\n    if (seenTable.has(b.tableName)) return\n    seenTable.add(b.tableName)\n    out.push({\n      infraId: infraId('sql-table', b.tableName),\n      name: b.tableName,\n      kind: 'sql-table',\n      edgeType: 'CALLS',\n      confidenceKind: 'structural',\n      columns: b.columns,\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line: b.startLine,\n        snippet: snippet(content, b.startLine),\n      },\n    })\n  }\n\n  // Second pass: a line-based block scan. Only `model` blocks contribute\n  // columns; `datasource` / `generator` / `enum` / `type` blocks are consumed so\n  // their closing brace doesn't leak, but produce nothing here.\n  let current: ModelBlock | null = null\n  let depth = 0\n\n  for (let i = 0; i < lines.length; i++) {\n    const raw = lines[i]!\n    const lineNo = i + 1\n\n    if (current === null) {\n      const header = raw.match(/^\\s*(model|enum|datasource|generator|type)\\s+([A-Za-z_]\\w*)\\b/)\n      if (header && raw.includes('{')) {\n        current = {\n          kind: header[1]!,\n          tableName: header[2]!,\n          startLine: lineNo,\n          columns: [],\n          seenCol: new Set(),\n        }\n        depth = netBraces(raw)\n        if (depth <= 0) {\n          if (current.kind === 'model') finalize(current)\n          current = null\n        }\n      }\n      continue\n    }\n\n    depth += netBraces(raw)\n    if (depth <= 0) {\n      if (current.kind === 'model') finalize(current)\n      current = null\n      continue\n    }\n    if (current.kind !== 'model') continue\n\n    const trimmed = stripLineComment(raw).trim()\n    if (!trimmed) continue\n    if (trimmed.startsWith('@@')) {\n      const map = trimmed.match(/@@map\\(\\s*\"([^\"]+)\"\\s*\\)/)\n      if (map) current.tableName = map[1]!\n      continue\n    }\n\n    // `fieldName BaseType[...] attributes…` — the base type is the second token,\n    // with a trailing `[]` array marker stripped by the alternation.\n    const fm = trimmed.match(/^([A-Za-z_]\\w*)\\s+([A-Za-z_]\\w*)/)\n    if (!fm) continue\n    const fieldName = fm[1]!\n    const baseType = fm[2]!\n\n    // Relation fields are not columns: an `@relation(...)` field, or a field whose\n    // base type is another declared model (covers `author User`, `Tag[]`, `Comment[]`).\n    if (/@relation\\b/.test(trimmed) || modelNames.has(baseType)) continue\n    // A column is a scalar-typed or enum-typed field. Anything else (a composite\n    // type, `Unsupported(...)`, a cross-file model) is left unclaimed.\n    if (!enumNames.has(baseType) && !SCALAR_TYPES.has(baseType)) continue\n\n    const mapM = trimmed.match(/(?<!@)@map\\(\\s*\"([^\"]+)\"\\s*\\)/)\n    const columnName = mapM ? mapM[1]! : fieldName\n    if (!current.seenCol.has(columnName)) {\n      current.seenCol.add(columnName)\n      current.columns.push(columnName)\n    }\n  }\n\n  // An unterminated final model (no trailing `}` at EOF) is still emitted.\n  if (current && current.kind === 'model') finalize(current)\n\n  return out\n}\n\n// Per-service pass: locate the service's `schema.prisma` and read its declared\n// columns. `schema.prisma` is not a source file the walker loads (its extension\n// is not in SERVICE_FILE_EXTENSIONS), so — unlike the JS producers that scan an\n// already-loaded file — this reads the schema directly, the same standard\n// location `databases/prisma.ts` reads for the datasource.\nexport async function prismaColumnEndpoints(serviceDir: string): Promise<ExternalEndpoint[]> {\n  const schemaPath = await findFirst(serviceDir, [\n    path.join('prisma', 'schema.prisma'),\n    'schema.prisma',\n  ])\n  if (!schemaPath) return []\n  const content = await readIfExists(schemaPath)\n  if (!content) return []\n  return prismaColumnsFromSchema({ path: schemaPath, content }, serviceDir)\n}\n\n// ── foreign-key table→table references (ADR-161) ─────────────────────────────\n//\n// Prisma declares a FK on the relation field that carries the scalar columns:\n//   model Post {\n//     authorId Int\n//     author   User @relation(fields: [authorId], references: [id])\n//   }\n// The `fields:` side is the child (it holds the FK column); the field's base type\n// is the parent model. The FK edge is `child-table ──REFERENCES──▶ parent-table`,\n// both at DB-name fidelity — the model's `@@map` name where given, the model name\n// verbatim otherwise (ADR-157 §3). The back-relation side (`posts Post[]`, no\n// `fields:`) declares no FK and mints nothing, so the edge is minted once, in the\n// correct direction. A relation whose base type is not a declared model, or a\n// relation without `fields:`, resolves to no parent and is left unclaimed.\n\n// Model name → the DB table it maps to (the `@@map` value, else the model name\n// verbatim). Built up front so a relation to a model declared later still resolves.\nfunction buildModelTableMap(lines: string[]): Map<string, string> {\n  const map = new Map<string, string>()\n  let current: { model: string; table: string } | null = null\n  let depth = 0\n  for (const raw of lines) {\n    if (current === null) {\n      const header = raw.match(/^\\s*model\\s+([A-Za-z_]\\w*)\\b/)\n      if (header && raw.includes('{')) {\n        current = { model: header[1]!, table: header[1]! }\n        depth = netBraces(raw)\n        if (depth <= 0) {\n          map.set(current.model, current.table)\n          current = null\n        }\n      }\n      continue\n    }\n    depth += netBraces(raw)\n    const trimmed = stripLineComment(raw).trim()\n    if (trimmed.startsWith('@@')) {\n      const m = trimmed.match(/@@map\\(\\s*\"([^\"]+)\"\\s*\\)/)\n      if (m) current.table = m[1]!\n    }\n    if (depth <= 0) {\n      map.set(current.model, current.table)\n      current = null\n    }\n  }\n  if (current) map.set(current.model, current.table)\n  return map\n}\n\nexport function prismaForeignKeysFromSchema(\n  file: SourceFile,\n  serviceDir: string,\n): TableReference[] {\n  const content = file.content\n  if (!/\\bmodel\\s+[A-Za-z_]\\w*\\s*\\{/.test(content)) return []\n  const lines = content.split('\\n')\n  const modelToTable = buildModelTableMap(lines)\n\n  const out: TableReference[] = []\n  const seen = new Set<string>()\n  let current: { table: string } | null = null\n  let depth = 0\n\n  for (let i = 0; i < lines.length; i++) {\n    const raw = lines[i]!\n    const lineNo = i + 1\n\n    if (current === null) {\n      const header = raw.match(/^\\s*model\\s+([A-Za-z_]\\w*)\\b/)\n      if (header && raw.includes('{')) {\n        current = { table: modelToTable.get(header[1]!) ?? header[1]! }\n        depth = netBraces(raw)\n        if (depth <= 0) current = null\n      }\n      continue\n    }\n\n    depth += netBraces(raw)\n    const closing = depth <= 0\n    const trimmed = stripLineComment(raw).trim()\n\n    // A relation field holding the FK: `author User @relation(fields: [authorId],\n    // references: [id])`. Only the `fields:` side mints an edge — the back-relation\n    // (`posts Post[]`, no `fields:`) is skipped, so the direction is unambiguous.\n    if (trimmed && !trimmed.startsWith('@@') && !trimmed.startsWith('}')) {\n      const fm = trimmed.match(/^([A-Za-z_]\\w*)\\s+([A-Za-z_]\\w*)/)\n      if (fm && /@relation\\b[^)]*\\bfields\\s*:/.test(trimmed)) {\n        const parentTable = modelToTable.get(fm[2]!)\n        if (parentTable) {\n          const key = `${current.table}->${parentTable}`\n          if (!seen.has(key)) {\n            seen.add(key)\n            out.push({\n              childTable: current.table,\n              parentTable,\n              evidence: {\n                file: path.relative(serviceDir, file.path),\n                line: lineNo,\n                snippet: snippet(content, lineNo),\n              },\n            })\n          }\n        }\n      }\n    }\n\n    if (closing) current = null\n  }\n\n  return out\n}\n\n// Per-service pass: locate `schema.prisma` and read its declared foreign keys.\n// Mirrors `prismaColumnEndpoints` — the schema is not a walked source file, so it\n// is read directly from the standard location.\nexport async function prismaForeignKeys(serviceDir: string): Promise<TableReference[]> {\n  const schemaPath = await findFirst(serviceDir, [\n    path.join('prisma', 'schema.prisma'),\n    'schema.prisma',\n  ])\n  if (!schemaPath) return []\n  const content = await readIfExists(schemaPath)\n  if (!content) return []\n  return prismaForeignKeysFromSchema({ path: schemaPath, content }, serviceDir)\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport Ruby from 'tree-sitter-ruby'\nimport { infraId } from '@neat.is/types'\nimport { snippet, type ExternalEndpoint, type SourceFile, type TableReference } from './shared.js'\n\n// Ruby/Rails ActiveRecord data-axis recognizer (ADR-174), the second rung of the\n// Ruby pilot after ADR-173's routes. Rails declares its schema twice — literally\n// in `db/schema.rb` and behaviourally in the ActiveRecord models — and both feed\n// the SAME `sql-table` nodes, `ColumnAttr` columns (ADR-157), and `REFERENCES`\n// edges (ADR-161) Prisma and Drizzle already produce, so the reasoning core learns\n// nothing Rails-specific (calls/prisma.ts is the closest analog).\n//\n//   ActiveRecord::Schema[7.1].define do\n//     create_table \"orders\", force: :cascade do |t|\n//       t.string   \"name\"\n//       t.integer  \"qty\"\n//       t.references :user, foreign_key: true      # -> user_id column + FK to users\n//       t.timestamps                               # -> created_at, updated_at\n//     end\n//     add_foreign_key \"line_items\", \"orders\"       # -> line_items REFERENCES orders\n//   end\n//\n// The fidelity rule (ADR-157 §3): the table/column/FK names in schema.rb are\n// LITERAL — the exact strings the database uses and a query's `db.statement`\n// carries at runtime — so schema.rb is the anchor and needs no pluralization. The\n// models add what the schema can't name on its own: the class↔table link and the\n// association graph. There the ActiveSupport pluralizer is a fallback only, since\n// a wrong guess there is a missed edge, never a wrong table node.\n\nconst AR_SCHEMA_RE = /ActiveRecord::Schema/\n\nconst PARSE_CHUNK = 16384\n\nfunction makeRubyParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Ruby)\n  return p\n}\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nfunction walk(node: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const c = node.namedChild(i)\n    if (c) walk(c, visit)\n  }\n}\n\n// The interior text of a Ruby string literal, or a symbol's name without its\n// leading colon (`:orders` → 'orders'). Null for an interpolated string — a\n// schema name is always a static literal. Mirrors routes.ts's `rubyLiteral`.\nfunction rubyLiteral(node: Parser.SyntaxNode | null | undefined): string | null {\n  if (!node) return null\n  if (node.type === 'simple_symbol') return node.text.replace(/^:/, '')\n  if (node.type === 'string') {\n    let text = ''\n    let sawContent = false\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const child = node.namedChild(i)\n      if (!child) continue\n      if (child.type === 'string_content' || child.type === 'escape_sequence') {\n        text += child.text\n        sawContent = true\n      } else {\n        return null // interpolation or anything non-literal\n      }\n    }\n    return sawContent ? text : '' // an empty string literal has no content child\n  }\n  return null\n}\n\nfunction rubyArgs(call: Parser.SyntaxNode): Parser.SyntaxNode | null {\n  return call.childForFieldName('arguments')\n}\n\n// The positional (non-`pair`) arguments of a call, in order.\nfunction rubyPositional(args: Parser.SyntaxNode | null): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  if (!args) return out\n  for (let i = 0; i < args.namedChildCount; i++) {\n    const c = args.namedChild(i)\n    if (c && c.type !== 'pair') out.push(c)\n  }\n  return out\n}\n\n// The value node of a keyword argument `key: …` — a `pair` whose key is a\n// `hash_key_symbol` with the given name. Handles both an inline argument-list\n// pair (`create_table \"x\", id: false`) and a `hash` literal's own pairs\n// (`foreign_key: { to_table: :y }`).\nfunction rubyKwarg(container: Parser.SyntaxNode | null, key: string): Parser.SyntaxNode | null {\n  if (!container) return null\n  for (let i = 0; i < container.namedChildCount; i++) {\n    const pair = container.namedChild(i)\n    if (!pair || pair.type !== 'pair') continue\n    const k = pair.childForFieldName('key')\n    if (k?.type === 'hash_key_symbol' && k.text === key) return pair.childForFieldName('value')\n  }\n  return null\n}\n\n// The `call` statements at the top level of a `do … end` block or a class\n// `body_statement`. tree-sitter-ruby wraps multiple statements in a\n// `body_statement`; fall back to the container's own direct children for the\n// single-statement shape. Mirrors routes.ts's `rubyBlockCalls`.\nfunction rubyBodyCalls(container: Parser.SyntaxNode | null): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  if (!container) return out\n  const pushCalls = (n: Parser.SyntaxNode): void => {\n    for (let i = 0; i < n.namedChildCount; i++) {\n      const c = n.namedChild(i)\n      if (c?.type === 'call') out.push(c)\n    }\n  }\n  let sawBody = false\n  for (let i = 0; i < container.namedChildCount; i++) {\n    const c = container.namedChild(i)\n    if (c?.type === 'body_statement') {\n      pushCalls(c)\n      sawBody = true\n    }\n  }\n  if (!sawBody) pushCalls(container)\n  return out\n}\n\n// ── inflection (model / association fallback only) ───────────────────────────\n//\n// schema.rb names are literal and never routed through here. These reproduce the\n// common-case ActiveSupport rules for the model→table fallback and the singular\n// association→table derivation. Irregulars (person/people, child/children) and a\n// project's custom inflections are a documented refinement (ADR-174) — since the\n// schema.rb literal is the anchor, a wrong guess here is a missed corroborating\n// edge, not a wrong node.\n\n// `Admin::User` → `User`.\nfunction demodulize(name: string): string {\n  const i = name.lastIndexOf('::')\n  return i >= 0 ? name.slice(i + 2) : name\n}\n\n// ActiveSupport underscore: CamelCase → snake_case, keeping acronym runs together\n// (`APIKey` → `api_key`, `LineItem` → `line_item`).\nfunction underscore(name: string): string {\n  return name\n    .replace(/([A-Z\\d]+)([A-Z][a-z])/g, '$1_$2')\n    .replace(/([a-z\\d])([A-Z])/g, '$1_$2')\n    .replace(/-/g, '_')\n    .toLowerCase()\n}\n\n// Common-case English pluralizer — the rules ActiveSupport's default inflections\n// ship for the frequent endings.\nfunction pluralize(word: string): string {\n  if (/[^aeiou]y$/i.test(word)) return word.replace(/y$/i, 'ies')\n  if (/(s|x|z|ch|sh)$/i.test(word)) return word + 'es'\n  return word + 's'\n}\n\n// class name → table name (ActiveSupport `tableize`, default `table_name`):\n// pluralize(underscore(demodulize(name))). `Order` → orders, `LineItem` →\n// line_items, `Admin::User` → users.\nfunction tableize(className: string): string {\n  return pluralize(underscore(demodulize(className)))\n}\n\n// ── db/schema.rb: create_table → sql-table + columns ─────────────────────────\n\n// The ActiveRecord migration column-type methods that declare a column named by\n// their first string/symbol argument. `t.column \"name\", \"type\"` (the generic\n// form) is here too — its first positional is still the name. Non-column table\n// methods (`t.index`, `t.check_constraint`, `t.foreign_key`) are absent, so they\n// contribute nothing — the bounded-set discipline Drizzle's TABLE_BUILDERS and\n// SQLAlchemy's COLUMN_BUILDERS follow. `references`/`belongs_to`/`timestamps` are\n// handled specially below (they expand to `<name>_id` / created_at+updated_at).\nconst AR_COLUMN_TYPES = new Set([\n  'string', 'text', 'integer', 'bigint', 'float', 'decimal', 'numeric',\n  'datetime', 'timestamp', 'timestamptz', 'time', 'date', 'binary', 'boolean',\n  'json', 'jsonb', 'uuid', 'hstore', 'citext', 'inet', 'cidr', 'macaddr',\n  'money', 'xml', 'tsvector', 'ltree', 'interval', 'oid', 'bit', 'blob',\n  'int4range', 'int8range', 'numrange', 'tsrange', 'tstzrange', 'daterange',\n  'point', 'line', 'lseg', 'box', 'path', 'polygon', 'circle', 'enum',\n  'primary_key', 'virtual', 'column',\n])\n\nconst AR_REFERENCE_METHODS = new Set(['references', 'belongs_to'])\n\n// The receiver-and-method of a `t.<method> …` block call. Returns the method name\n// (`string`, `references`, `timestamps`, …) regardless of the block variable name.\nfunction blockCallMethod(call: Parser.SyntaxNode): string | null {\n  return call.childForFieldName('method')?.text ?? null\n}\n\ninterface SchemaTable {\n  name: string\n  line: number\n  columns: string[]\n}\n\n// Read a single `create_table \"orders\", … do |t| … end` call into its table name,\n// the implicit primary key, and the columns its block declares.\nfunction readCreateTable(call: Parser.SyntaxNode): SchemaTable | null {\n  const args = rubyArgs(call)\n  const name = rubyLiteral(rubyPositional(args)[0])\n  if (!name) return null // computed / interpolated table name — never guessed\n  const line = call.startPosition.row + 1\n\n  const columns: string[] = []\n  const seen = new Set<string>()\n  const add = (col: string | null): void => {\n    if (col && !seen.has(col)) {\n      seen.add(col)\n      columns.push(col)\n    }\n  }\n\n  // Implicit primary key, unless `id: false`. A `primary_key: \"uuid\"` renames it.\n  const idOpt = rubyKwarg(args, 'id')\n  if (!idOpt || idOpt.type !== 'false') {\n    add(rubyLiteral(rubyKwarg(args, 'primary_key')) ?? 'id')\n  }\n\n  for (const bc of rubyBodyCalls(call.childForFieldName('block'))) {\n    const method = blockCallMethod(bc)\n    if (!method) continue\n    const bArgs = rubyArgs(bc)\n    if (method === 'timestamps') {\n      add('created_at')\n      add('updated_at')\n    } else if (AR_REFERENCE_METHODS.has(method)) {\n      const refName = rubyLiteral(rubyPositional(bArgs)[0])\n      if (!refName) continue\n      add(`${refName}_id`)\n      // A polymorphic reference also declares a `<name>_type` discriminator.\n      const poly = rubyKwarg(bArgs, 'polymorphic')\n      if (poly && poly.type === 'true') add(`${refName}_type`)\n    } else if (AR_COLUMN_TYPES.has(method)) {\n      add(rubyLiteral(rubyPositional(bArgs)[0]))\n    }\n    // Anything else (index, check_constraint, …) declares no column.\n  }\n\n  return { name, line, columns }\n}\n\n// db/schema.rb tables + columns. Gated on the `ActiveRecord::Schema` marker so it\n// is inert on every other `.rb` file (the import-gate discipline Drizzle and\n// SQLAlchemy follow). Emits one `sql-table` endpoint per `create_table`, carrying\n// the literal column names — the orchestrator (calls/index.ts) mints the node and\n// folds the columns onto it as EXTRACTED `ColumnAttr`s (ADR-157 §3).\nexport function railsSchemaEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  if (!AR_SCHEMA_RE.test(file.content)) return []\n  const tree = parseSource(makeRubyParser(), file.content)\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'call') return\n    if (blockCallMethod(node) !== 'create_table') return\n    const table = readCreateTable(node)\n    if (!table || seen.has(table.name)) return\n    seen.add(table.name)\n    out.push({\n      infraId: infraId('sql-table', table.name),\n      name: table.name,\n      kind: 'sql-table',\n      edgeType: 'CALLS',\n      confidenceKind: 'structural',\n      ...(table.columns.length > 0 ? { columns: table.columns } : {}),\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line: table.line,\n        snippet: snippet(file.content, table.line),\n      },\n    })\n  })\n\n  return out\n}\n\n// db/schema.rb foreign keys → REFERENCES table→table edges. Two literal sources,\n// both preferred over any model inference: an inline `t.references :user,\n// foreign_key: true` inside a create_table (parent pluralized, or `to_table:`\n// verbatim when given) and a top-level `add_foreign_key \"orders\", \"users\"` (both\n// names literal). A polymorphic reference names no single parent and is left\n// unclaimed. `column:` / `primary_key:` on `add_foreign_key` don't change the\n// table-grain edge and are ignored.\nexport function railsSchemaForeignKeys(\n  file: SourceFile,\n  serviceDir: string,\n): TableReference[] {\n  if (!AR_SCHEMA_RE.test(file.content)) return []\n  const tree = parseSource(makeRubyParser(), file.content)\n  const out: TableReference[] = []\n  const seen = new Set<string>()\n\n  const emit = (childTable: string, parentTable: string, line: number): void => {\n    if (childTable === parentTable) return // self-loop, dropped by the graph anyway\n    const key = `${childTable}->${parentTable}`\n    if (seen.has(key)) return\n    seen.add(key)\n    out.push({\n      childTable,\n      parentTable,\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  }\n\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'call') return\n    const method = blockCallMethod(node)\n\n    // Top-level `add_foreign_key \"child\", \"parent\", …` — both names literal.\n    if (method === 'add_foreign_key') {\n      const args = rubyArgs(node)\n      const pos = rubyPositional(args)\n      const child = rubyLiteral(pos[0])\n      const parent = rubyLiteral(pos[1])\n      if (child && parent) emit(child, parent, node.startPosition.row + 1)\n      return\n    }\n\n    // Inline `t.references :user, foreign_key: true` inside a create_table.\n    if (method !== 'create_table') return\n    const table = readCreateTable(node)\n    if (!table) return\n    for (const bc of rubyBodyCalls(node.childForFieldName('block'))) {\n      if (!AR_REFERENCE_METHODS.has(blockCallMethod(bc) ?? '')) continue\n      const bArgs = rubyArgs(bc)\n      const refName = rubyLiteral(rubyPositional(bArgs)[0])\n      if (!refName) continue\n      const poly = rubyKwarg(bArgs, 'polymorphic')\n      if (poly && poly.type === 'true') continue // no single parent to reference\n      const fk = rubyKwarg(bArgs, 'foreign_key')\n      if (!fk || fk.type === 'false') continue // no `foreign_key: true` → no DB FK\n      // `foreign_key: { to_table: :accounts }` overrides the pluralized default.\n      const toTable = fk.type === 'hash' ? rubyLiteral(rubyKwarg(fk, 'to_table')) : null\n      const parent = toTable ?? pluralize(refName)\n      emit(table.name, parent, bc.startPosition.row + 1)\n    }\n  })\n\n  return out\n}\n\n// ── app/models/*.rb: class↔table link + associations ─────────────────────────\n\n// The superclass constant of a `class X < Y` — `Y`'s text, or null when the class\n// has no superclass. Reads the `superclass` node's constant / scope_resolution.\nfunction superclassName(cls: Parser.SyntaxNode): string | null {\n  const sup = cls.childForFieldName('superclass')\n  if (!sup) return null\n  for (let i = 0; i < sup.namedChildCount; i++) {\n    const c = sup.namedChild(i)\n    if (c && (c.type === 'constant' || c.type === 'scope_resolution')) return c.text\n  }\n  return null\n}\n\n// Is this class an ActiveRecord model? `< ApplicationRecord` (the Rails ≥ 5 base)\n// or `< ActiveRecord::Base` (legacy), including a namespaced `Foo::ApplicationRecord`.\nfunction isActiveRecordModel(cls: Parser.SyntaxNode): boolean {\n  const sup = superclassName(cls)\n  if (!sup) return false\n  return sup === 'ApplicationRecord' || sup.endsWith('::ApplicationRecord') || sup === 'ActiveRecord::Base'\n}\n\n// The table a model class maps to: an explicit `self.table_name = \"x\"` when set,\n// else the ActiveSupport pluralisation of the underscored class name (`Order` →\n// orders). schema.rb literals are the anchor; this only names the link.\nfunction modelTable(cls: Parser.SyntaxNode): string | null {\n  const nameNode = cls.childForFieldName('name')\n  if (!nameNode) return null\n  const body = cls.childForFieldName('body')\n  if (body) {\n    for (let i = 0; i < body.namedChildCount; i++) {\n      const stmt = body.namedChild(i)\n      if (stmt?.type !== 'assignment') continue\n      const left = stmt.childForFieldName('left')\n      if (left?.text !== 'self.table_name') continue\n      const explicit = rubyLiteral(stmt.childForFieldName('right'))\n      if (explicit) return explicit\n    }\n  }\n  return tableize(nameNode.text)\n}\n\n// app/models/*.rb: the model→table link. Emits a `sql-table` endpoint so the\n// model file gets a `file ──CALLS──▶ sql-table` edge (the SQLAlchemy model-file\n// pattern) — no columns, since ActiveRecord reads those from the DB, and schema.rb\n// is the column authority.\nexport function railsModelEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  const tree = parseSource(makeRubyParser(), file.content)\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'class' || !isActiveRecordModel(node)) return\n    const table = modelTable(node)\n    if (!table || seen.has(table)) return\n    seen.add(table)\n    const line = node.startPosition.row + 1\n    out.push({\n      infraId: infraId('sql-table', table),\n      name: table,\n      kind: 'sql-table',\n      edgeType: 'CALLS',\n      confidenceKind: 'verified-call-site',\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  })\n\n  return out\n}\n\nconst AR_ASSOCIATIONS = new Set(['belongs_to', 'has_many', 'has_one'])\n\n// app/models/*.rb associations → REFERENCES edges, deduped against the schema.rb\n// FKs at the graph level (table-edges.ts guards every write with `hasEdge`, and\n// the schema.rb refs are added first). The FK lives on the table that holds the\n// `<name>_id` column, so direction depends on the macro:\n//   belongs_to :user     -> this table REFERENCES the association's table (users)\n//   has_many :line_items -> line_items REFERENCES this table (FK on the other side)\n//   has_one :profile     -> profiles REFERENCES this table\n// `class_name:` retargets the association's class (hence table); `through:` (a\n// join through a third model) and `has_and_belongs_to_many` are deferred.\nexport function railsModelForeignKeys(\n  file: SourceFile,\n  serviceDir: string,\n): TableReference[] {\n  const tree = parseSource(makeRubyParser(), file.content)\n  const out: TableReference[] = []\n  const seen = new Set<string>()\n\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'class' || !isActiveRecordModel(node)) return\n    const thisTable = modelTable(node)\n    if (!thisTable) return\n\n    for (const call of rubyBodyCalls(node.childForFieldName('body'))) {\n      const macro = blockCallMethod(call)\n      if (!macro || !AR_ASSOCIATIONS.has(macro)) continue\n      const args = rubyArgs(call)\n      const assoc = rubyLiteral(rubyPositional(args)[0])\n      if (!assoc) continue\n      if (rubyKwarg(args, 'through')) continue // has_many/has_one :through — deferred\n\n      // The association's own table: `class_name:` when given, else the\n      // conventional derivation. A has_many name is already the plural table\n      // name; belongs_to / has_one names are singular and pluralize.\n      const className = rubyLiteral(rubyKwarg(args, 'class_name'))\n      const assocTable = className\n        ? tableize(className)\n        : macro === 'has_many'\n          ? assoc\n          : pluralize(assoc)\n\n      const childTable = macro === 'belongs_to' ? thisTable : assocTable\n      const parentTable = macro === 'belongs_to' ? assocTable : thisTable\n      if (childTable === parentTable) continue\n      const key = `${childTable}->${parentTable}`\n      if (seen.has(key)) continue\n      seen.add(key)\n      const line = call.startPosition.row + 1\n      out.push({\n        childTable,\n        parentTable,\n        evidence: {\n          file: path.relative(serviceDir, file.path),\n          line,\n          snippet: snippet(file.content, line),\n        },\n      })\n    }\n  })\n\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport Php from 'tree-sitter-php'\nimport { infraId } from '@neat.is/types'\nimport { snippet, type ExternalEndpoint, type SourceFile, type TableReference } from './shared.js'\n\n// PHP/Laravel data-axis recognizer (ADR-178), the second rung of the PHP pilot\n// after ADR-177's routes. Laravel declares its schema in two places — literally\n// in `database/migrations/*.php` and behaviourally in the Eloquent models — and\n// both feed the SAME `sql-table` nodes, `ColumnAttr` columns (ADR-157), and\n// `REFERENCES` edges (ADR-161) Prisma, Drizzle, and Rails' schema.rb already\n// produce, so the reasoning core learns nothing Laravel-specific\n// (calls/activerecord.ts is the closest analog — a migration is Rails' schema.rb,\n// an Eloquent model is an ActiveRecord model).\n//\n//   Schema::create('orders', function (Blueprint $table) {\n//     $table->id();                              // -> id\n//     $table->string('code');                    // -> code\n//     $table->foreignId('user_id')->constrained();  // -> user_id column + FK to users\n//     $table->timestamps();                      // -> created_at, updated_at\n//   });\n//\n//   class Order extends Model {                  // -> maps to the orders table\n//     public function user() { return $this->belongsTo(User::class); }  // orders -> users\n//   }\n//\n// The fidelity rule (ADR-157 §3): the table/column names inside `Schema::create`\n// are LITERAL — the exact strings the database uses and a query's `db.statement`\n// carries at runtime — so the migration is the anchor and needs no pluralization.\n// The models add what the migration can't name on its own: the class↔table link\n// and the relation graph. There the snake_case pluralizer is a fallback only,\n// since a wrong guess there is a missed corroborating edge, never a wrong table\n// node (the migration literal anchors the node either way).\n\n// Cheap per-file gate — inert on every `.php` file that declares no schema, the\n// import-gate discipline the other data-axis readers follow. A migration always\n// names `Schema::create` / `Schema::table` (or the `createIfNotExists` variant),\n// including the fully-qualified `\\Illuminate\\Support\\Facades\\Schema::create`.\nconst LARAVEL_SCHEMA_RE = /\\bSchema::(create|createIfNotExists|table)\\b/\n\nconst PARSE_CHUNK = 16384\n\nfunction makePhpParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Php.php_only)\n  return p\n}\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nfunction walk(node: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const c = node.namedChild(i)\n    if (c) walk(c, visit)\n  }\n}\n\n// ── PHP literal / argument helpers (mirrors routes.ts) ───────────────────────\n\n// The interior text of a PHP single-quoted `string` or double-quoted\n// `encapsed_string`, or null when it carries interpolation (a schema name is a\n// static literal). An empty literal returns ''.\nfunction phpStaticString(node: Parser.SyntaxNode | null | undefined): string | null {\n  if (!node) return null\n  if (node.type !== 'string' && node.type !== 'encapsed_string') return null\n  let text = ''\n  let sawContent = false\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (!child) continue\n    if (child.type === 'string_content') {\n      text += child.text\n      sawContent = true\n    } else {\n      return null // interpolation / escape / anything non-literal\n    }\n  }\n  return sawContent ? text : ''\n}\n\n// The value nodes of a call's positional arguments. tree-sitter-php wraps each in\n// an `argument`; the value is its last named child (a PHP-8 named argument\n// `name: value` carries a `name` field that precedes the value).\nfunction phpArgumentValues(argsNode: Parser.SyntaxNode | null | undefined): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  if (!argsNode) return out\n  for (let i = 0; i < argsNode.namedChildCount; i++) {\n    const arg = argsNode.namedChild(i)\n    if (!arg || arg.type !== 'argument') continue\n    const val = arg.namedChild(arg.namedChildCount - 1)\n    if (val) out.push(val)\n  }\n  return out\n}\n\n// The first positional argument as a static string, or null.\nfunction phpFirstString(argsNode: Parser.SyntaxNode | null | undefined): string | null {\n  const vals = phpArgumentValues(argsNode)\n  return vals.length > 0 ? phpStaticString(vals[0]) : null\n}\n\n// The basename of a class reference — `User::class` (`class_constant_access_expression`),\n// a namespaced `\\App\\Models\\User::class`, or a `'App\\Models\\User'` string literal —\n// stripped of its namespace: `User`. Null for anything else.\nfunction classRefBasename(node: Parser.SyntaxNode | null | undefined): string | null {\n  if (!node) return null\n  let raw: string | null = null\n  if (node.type === 'class_constant_access_expression') {\n    // First named child is the class name (`name` or `qualified_name`); the\n    // second is the `class` keyword.\n    raw = node.namedChild(0)?.text ?? null\n  } else if (node.type === 'string' || node.type === 'encapsed_string') {\n    // A `'App\\Models\\User'` string carries the namespace as literal backslashes\n    // (an escape_sequence child), so read the raw interior rather than the\n    // string_content pieces and split on the backslash separator below.\n    const t = node.text\n    raw = t.length >= 2 ? t.slice(1, -1) : null\n  }\n  if (raw === null) return null\n  const seg = raw.replace(/^\\\\+/, '').split(/\\\\+/)\n  return seg[seg.length - 1] || null\n}\n\n// ── inflection (convention / model fallback only) ────────────────────────────\n//\n// Migration `Schema::create` names are literal and never routed through here.\n// These reproduce the common-case Laravel rules for the model→table fallback, the\n// `foreignId('user_id')->constrained()` column→table convention, and the\n// `foreignIdFor(Model::class)` model→table derivation. Irregulars (person/people)\n// are a documented refinement (ADR-178) — since the migration literal is the\n// anchor, a wrong guess here is a missed corroborating edge, not a wrong node.\n\n// StudlyCase → snake_case: `LineItem` → line_item, `APIToken` → api_token.\nfunction snakeCase(name: string): string {\n  return name\n    .replace(/([A-Z\\d]+)([A-Z][a-z])/g, '$1_$2')\n    .replace(/([a-z\\d])([A-Z])/g, '$1_$2')\n    .replace(/-/g, '_')\n    .toLowerCase()\n}\n\n// Common-case English pluralizer — the frequent endings Laravel's Str::plural\n// covers. Irregulars are the documented refinement.\nfunction pluralize(word: string): string {\n  if (/[^aeiou]y$/i.test(word)) return word.replace(/y$/i, 'ies')\n  if (/(s|x|z|ch|sh)$/i.test(word)) return word + 'es'\n  return word + 's'\n}\n\n// class name → table name (Laravel's default `getTable()`): the snake_case plural\n// of the class basename. `Order` → orders, `LineItem` → line_items.\nfunction tableize(className: string): string {\n  return pluralize(snakeCase(className))\n}\n\n// `foreignId('user_id')->constrained()` infers its parent table from the column\n// name the way Laravel does: strip a trailing `_id`, then pluralize the singular.\n// `user_id` → users, `author_id` → authors, `category_id` → categories.\nfunction tableFromForeignKeyColumn(column: string): string | null {\n  const singular = column.replace(/_id$/, '')\n  if (singular.length === 0 || singular === column) return null\n  return pluralize(singular)\n}\n\n// ── member-call chain flattening ─────────────────────────────────────────────\n\ninterface PhpSeg {\n  method: string\n  args: Parser.SyntaxNode | null\n  node: Parser.SyntaxNode\n}\n\n// Flatten a `$table->foreignId('x')->constrained()` fluent chain into its ordered\n// (method, args) segments, innermost first, plus the base receiver. A bare\n// `$table->id()` → { base: $table, segs: [id] }; `$table->foreign('x')->on('y')` →\n// [foreign, on]. Returns null when the chain doesn't root at a `variable_name`.\nfunction unrollMemberChain(\n  node: Parser.SyntaxNode,\n): { base: Parser.SyntaxNode; segs: PhpSeg[] } | null {\n  const segs: PhpSeg[] = []\n  let cur: Parser.SyntaxNode | null = node\n  while (cur && cur.type === 'member_call_expression') {\n    const name = cur.childForFieldName('name')?.text\n    if (!name) return null\n    segs.unshift({ method: name, args: cur.childForFieldName('arguments'), node: cur })\n    cur = cur.childForFieldName('object')\n  }\n  if (!cur || cur.type !== 'variable_name') return null\n  return { base: cur, segs }\n}\n\n// The name of a `variable_name` (`$table` → 'table'), or null.\nfunction variableName(node: Parser.SyntaxNode | null | undefined): string | null {\n  if (!node || node.type !== 'variable_name') return null\n  return node.namedChild(0)?.text ?? null\n}\n\n// ── Schema::create / Schema::table discovery ─────────────────────────────────\n\ninterface Blueprint {\n  table: string\n  line: number\n  blueprintVar: string | null // the closure's Blueprint parameter name (`table`)\n  closureBody: Parser.SyntaxNode | null // compound_statement or an arrow body\n}\n\n// The closure a `Schema::create('x', …)` carries — an anonymous `function () {}`\n// (`anonymous_function_creation_expression`) or a `fn () => …` (`arrow_function`).\nfunction schemaClosure(argsNode: Parser.SyntaxNode | null): Parser.SyntaxNode | null {\n  for (const v of phpArgumentValues(argsNode)) {\n    if (v.type === 'anonymous_function_creation_expression' || v.type === 'arrow_function') return v\n  }\n  return null\n}\n\n// The Blueprint parameter name of a schema closure (`function (Blueprint $table)`\n// → 'table'), so column calls can be matched to that receiver and unrelated\n// `$other->foo()` statements in the body are ignored.\nfunction blueprintParamName(closure: Parser.SyntaxNode): string | null {\n  const params = closure.childForFieldName('parameters')\n  if (!params) return null\n  for (let i = 0; i < params.namedChildCount; i++) {\n    const p = params.namedChild(i)\n    if (p?.type === 'simple_parameter') return variableName(p.childForFieldName('name'))\n  }\n  return null\n}\n\n// The `$table->…()` statement chains inside a schema closure — the outer\n// `member_call_expression` of each, whether in a `{ … }` block or a single-\n// expression arrow body.\nfunction closureCalls(closure: Parser.SyntaxNode): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  const body = closure.childForFieldName('body')\n  if (!body) return out\n  if (closure.type === 'arrow_function') {\n    if (body.type === 'member_call_expression') out.push(body)\n    return out\n  }\n  for (let i = 0; i < body.namedChildCount; i++) {\n    const stmt = body.namedChild(i)\n    if (stmt?.type !== 'expression_statement') continue\n    const call = stmt.namedChild(0)\n    if (call?.type === 'member_call_expression') out.push(call)\n  }\n  return out\n}\n\n// Is this scoped call a `Schema::create` / `Schema::table` (or the FQ facade)?\nfunction isSchemaCall(node: Parser.SyntaxNode): boolean {\n  if (node.type !== 'scoped_call_expression') return false\n  const scope = node.childForFieldName('scope')?.text ?? ''\n  const rooted = scope === 'Schema' || scope.endsWith('\\\\Schema')\n  if (!rooted) return false\n  const method = node.childForFieldName('name')?.text ?? ''\n  return method === 'create' || method === 'createIfNotExists' || method === 'table'\n}\n\n// Read a `Schema::create('orders', function (Blueprint $table) { … })` into its\n// literal table name and the closure to scan for columns / FKs. A computed table\n// name (interpolated, a constant) is left unclaimed — never guessed.\nfunction readBlueprint(node: Parser.SyntaxNode): Blueprint | null {\n  const args = node.childForFieldName('arguments')\n  const table = phpFirstString(args)\n  if (table === null || table.length === 0) return null\n  const closure = schemaClosure(args)\n  return {\n    table,\n    line: node.startPosition.row + 1,\n    blueprintVar: closure ? blueprintParamName(closure) : null,\n    closureBody: closure,\n  }\n}\n\n// ── columns ──────────────────────────────────────────────────────────────────\n\n// The Blueprint methods whose FIRST string argument is the column name — the\n// bounded set the fidelity discipline keeps (the analog of ActiveRecord's\n// AR_COLUMN_TYPES and Drizzle's TABLE_BUILDERS). Non-column methods (index,\n// unique, primary, dropColumn, foreign) are absent, so they contribute nothing.\n// `id` / `timestamps` / `softDeletes` / `rememberToken` / `foreignId` /\n// `foreignIdFor` expand specially below.\nconst NAMED_COLUMN_METHODS = new Set([\n  'bigIncrements', 'bigInteger', 'binary', 'boolean', 'char', 'dateTime', 'dateTimeTz',\n  'date', 'decimal', 'double', 'enum', 'float', 'foreignUlid', 'foreignUuid', 'fullText',\n  'geography', 'geometry', 'increments', 'integer', 'ipAddress', 'json', 'jsonb', 'lineString',\n  'longText', 'macAddress', 'mediumIncrements', 'mediumInteger', 'mediumText', 'multiLineString',\n  'multiPoint', 'multiPolygon', 'point', 'polygon', 'set', 'smallIncrements', 'smallInteger',\n  'string', 'text', 'time', 'timeTz', 'timestamp', 'timestampTz', 'tinyIncrements',\n  'tinyInteger', 'tinyText', 'ulid', 'unsignedBigInteger', 'unsignedDecimal', 'unsignedInteger',\n  'unsignedMediumInteger', 'unsignedSmallInteger', 'unsignedTinyInteger', 'uuid', 'year',\n])\n\n// The column(s) a single `$table->…()` statement declares, or [] for a\n// non-column statement (an index, a bare `foreign()` constraint, a deferred\n// `morphs()`). The base segment is the column-defining method; chained modifiers\n// (`->nullable()`, `->constrained()`, …) don't rename the column.\nfunction columnsFromCall(chain: Parser.SyntaxNode, blueprintVar: string | null): string[] {\n  const un = unrollMemberChain(chain)\n  if (!un) return []\n  // Only columns on the Blueprint receiver, when the param name is known.\n  if (blueprintVar !== null && variableName(un.base) !== blueprintVar) return []\n  const base = un.segs[0]\n  if (!base) return []\n  const m = base.method\n  const first = phpFirstString(base.args)\n\n  if (m === 'id') return [first ?? 'id']\n  if (m === 'timestamps' || m === 'timestampsTz' || m === 'nullableTimestamps') {\n    return ['created_at', 'updated_at']\n  }\n  if (m === 'softDeletes' || m === 'softDeletesTz') return [first ?? 'deleted_at']\n  if (m === 'rememberToken') return ['remember_token']\n  if (m === 'foreignId') return first ? [first] : []\n  if (m === 'foreignIdFor') {\n    // The column Laravel derives from the model: snake_case(basename) + '_id'.\n    const cls = classRefBasename(phpArgumentValues(base.args)[0])\n    return cls ? [`${snakeCase(cls)}_id`] : []\n  }\n  if (NAMED_COLUMN_METHODS.has(m)) return first ? [first] : []\n  // Everything else (index, unique, primary, foreign, morphs, dropColumn, …)\n  // declares no column here.\n  return []\n}\n\n// database/migrations/*.php tables + columns. Gated on the `Schema::` marker so it\n// is inert on every other `.php` file. Emits one `sql-table` endpoint per\n// `Schema::create` / `Schema::table`, carrying the literal column names — the\n// orchestrator (calls/index.ts) mints the node and folds the columns onto it as\n// EXTRACTED `ColumnAttr`s (ADR-157 §3). `Schema::table` (an alter) folds its added\n// columns onto the same node the create minted.\nexport function laravelMigrationEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  if (!LARAVEL_SCHEMA_RE.test(file.content)) return []\n  const tree = parseSource(makePhpParser(), file.content)\n  const out: ExternalEndpoint[] = []\n\n  walk(tree.rootNode, (node) => {\n    if (!isSchemaCall(node)) return\n    const bp = readBlueprint(node)\n    if (!bp) return\n\n    const columns: string[] = []\n    const seen = new Set<string>()\n    if (bp.closureBody) {\n      for (const call of closureCalls(bp.closureBody)) {\n        for (const col of columnsFromCall(call, bp.blueprintVar)) {\n          if (!seen.has(col)) {\n            seen.add(col)\n            columns.push(col)\n          }\n        }\n      }\n    }\n\n    out.push({\n      infraId: infraId('sql-table', bp.table),\n      name: bp.table,\n      kind: 'sql-table',\n      edgeType: 'CALLS',\n      confidenceKind: 'structural',\n      ...(columns.length > 0 ? { columns } : {}),\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line: bp.line,\n        snippet: snippet(file.content, bp.line),\n      },\n    })\n  })\n\n  return out\n}\n\n// ── migration foreign keys ───────────────────────────────────────────────────\n\n// database/migrations/*.php foreign keys → REFERENCES table→table edges (ADR-161),\n// from the three literal migration sources:\n//   $table->foreignId('user_id')->constrained()          -> orders REFERENCES users\n//   $table->foreignId('acct_id')->constrained('accounts') -> orders REFERENCES accounts\n//   $table->foreignIdFor(User::class)                    -> orders REFERENCES users\n//   $table->foreign('buyer_id')->references('id')->on('buyers') -> orders REFERENCES buyers\n// A bare `foreignId('user_id')` with no `->constrained()` is a column only (no DB\n// FK), so it mints no edge. A computed / unresolvable target is left unclaimed.\nexport function laravelMigrationForeignKeys(\n  file: SourceFile,\n  serviceDir: string,\n): TableReference[] {\n  if (!LARAVEL_SCHEMA_RE.test(file.content)) return []\n  const tree = parseSource(makePhpParser(), file.content)\n  const out: TableReference[] = []\n  const seen = new Set<string>()\n\n  const emit = (childTable: string, parentTable: string, line: number): void => {\n    if (!parentTable || childTable === parentTable) return\n    const key = `${childTable}->${parentTable}`\n    if (seen.has(key)) return\n    seen.add(key)\n    out.push({\n      childTable,\n      parentTable,\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  }\n\n  walk(tree.rootNode, (node) => {\n    if (!isSchemaCall(node)) return\n    const bp = readBlueprint(node)\n    if (!bp || !bp.closureBody) return\n\n    for (const chain of closureCalls(bp.closureBody)) {\n      const un = unrollMemberChain(chain)\n      if (!un) continue\n      if (bp.blueprintVar !== null && variableName(un.base) !== bp.blueprintVar) continue\n      const base = un.segs[0]\n      if (!base) continue\n      const line = chain.startPosition.row + 1\n\n      // `foreignId('user_id')->constrained(['accounts'])` — FK only when a\n      // `constrained` segment is present; the parent is its explicit table\n      // argument, else the column-name convention.\n      if (base.method === 'foreignId' || base.method === 'foreignUuid') {\n        const constrained = un.segs.find((s) => s.method === 'constrained')\n        if (!constrained) continue\n        const column = phpFirstString(base.args)\n        if (!column) continue\n        const explicit = phpFirstString(constrained.args)\n        const parent = explicit ?? tableFromForeignKeyColumn(column)\n        if (parent) emit(bp.table, parent, line)\n        continue\n      }\n\n      // `foreignIdFor(User::class)` — the model names its table directly.\n      if (base.method === 'foreignIdFor') {\n        const cls = classRefBasename(phpArgumentValues(base.args)[0])\n        if (cls) emit(bp.table, tableize(cls), line)\n        continue\n      }\n\n      // `foreign('buyer_id')->references('id')->on('buyers')` — the parent table\n      // is the `on(...)` argument; `references(...)` is the parent column, ignored\n      // at table grain.\n      if (base.method === 'foreign') {\n        const on = un.segs.find((s) => s.method === 'on')\n        const parent = on ? phpFirstString(on.args) : null\n        if (parent) emit(bp.table, parent, line)\n        continue\n      }\n    }\n  })\n\n  return out\n}\n\n// ── app/Models/*.php: class↔table link + relations ───────────────────────────\n\n// The base-class basename of a `class X extends Y` — `Y`'s trailing name, or null.\nfunction baseClassName(cls: Parser.SyntaxNode): string | null {\n  for (let i = 0; i < cls.namedChildCount; i++) {\n    const c = cls.namedChild(i)\n    if (c?.type !== 'base_clause') continue\n    const ref = c.namedChild(0)\n    if (!ref) return null\n    const seg = ref.text.replace(/^\\\\+/, '').split('\\\\')\n    return seg[seg.length - 1] || null\n  }\n  return null\n}\n\n// Is this class an Eloquent model? `extends Model` (the Eloquent base) or\n// `extends Authenticatable` (the base Laravel's own `User` model uses), including\n// a fully-qualified `\\Illuminate\\Database\\Eloquent\\Model`.\nfunction isEloquentModel(cls: Parser.SyntaxNode): boolean {\n  const base = baseClassName(cls)\n  return base === 'Model' || base === 'Authenticatable'\n}\n\n// The `declaration_list` body of a class.\nfunction classBody(cls: Parser.SyntaxNode): Parser.SyntaxNode | null {\n  for (let i = 0; i < cls.namedChildCount; i++) {\n    const c = cls.namedChild(i)\n    if (c?.type === 'declaration_list') return c\n  }\n  return null\n}\n\n// The explicit `protected $table = 'x'` override on a model, or null.\nfunction modelTableOverride(cls: Parser.SyntaxNode): string | null {\n  const body = classBody(cls)\n  if (!body) return null\n  for (let i = 0; i < body.namedChildCount; i++) {\n    const decl = body.namedChild(i)\n    if (decl?.type !== 'property_declaration') continue\n    for (let j = 0; j < decl.namedChildCount; j++) {\n      const el = decl.namedChild(j)\n      if (el?.type !== 'property_element') continue\n      // property_element's first named child is the `variable_name`; a\n      // `property_initializer` (when the property has a default) wraps its value.\n      if (variableName(el.namedChild(0)) !== 'table') continue\n      for (let k = 0; k < el.namedChildCount; k++) {\n        const child = el.namedChild(k)\n        if (child?.type !== 'property_initializer') continue\n        const str = phpStaticString(child.namedChild(child.namedChildCount - 1))\n        if (str) return str\n      }\n    }\n  }\n  return null\n}\n\n// The table a model maps to: `protected $table` when set, else the snake_case\n// plural of the class name. The migration literal is the anchor; this only names\n// the link.\nfunction modelTable(cls: Parser.SyntaxNode): string | null {\n  const nameNode = cls.childForFieldName('name')\n  if (!nameNode) return null\n  return modelTableOverride(cls) ?? tableize(nameNode.text)\n}\n\n// Walk a class subtree WITHOUT crossing into a nested class / anonymous class, so\n// `$this->belongsTo(...)` calls inside the model's relation methods are found but\n// a nested declaration's calls are not attributed here.\nfunction walkWithinClass(cls: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  const body = classBody(cls)\n  if (!body) return\n  const recur = (n: Parser.SyntaxNode): void => {\n    visit(n)\n    for (let i = 0; i < n.namedChildCount; i++) {\n      const c = n.namedChild(i)\n      if (!c) continue\n      if (c.type === 'class_declaration' || c.type === 'object_creation_expression') continue\n      recur(c)\n    }\n  }\n  recur(body)\n}\n\n// app/Models/*.php: the model→table link. Emits a `sql-table` endpoint so the\n// model file gets a `file ──CALLS──▶ sql-table` edge (the ActiveRecord/SQLAlchemy\n// model-file pattern) — no columns, since Eloquent reads those from the DB and the\n// migration is the column authority.\nexport function laravelModelEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  const tree = parseSource(makePhpParser(), file.content)\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'class_declaration' || !isEloquentModel(node)) return\n    const table = modelTable(node)\n    if (!table || seen.has(table)) return\n    seen.add(table)\n    const line = node.startPosition.row + 1\n    out.push({\n      infraId: infraId('sql-table', table),\n      name: table,\n      kind: 'sql-table',\n      edgeType: 'CALLS',\n      confidenceKind: 'verified-call-site',\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  })\n\n  return out\n}\n\nconst ELOQUENT_RELATIONS = new Set(['belongsTo', 'hasMany', 'hasOne'])\n\n// app/Models/*.php relations → REFERENCES edges, deduped against the migration FKs\n// at the graph level (table-edges.ts guards every write with `hasEdge`, and the\n// migration refs are added first). The FK lives on the table that holds the\n// `<name>_id` column, so direction depends on the relation macro:\n//   belongsTo(User::class)     -> this table REFERENCES the relation's table (users)\n//   hasMany(LineItem::class)   -> line_items REFERENCES this table (FK on the other side)\n//   hasOne(Profile::class)     -> profiles REFERENCES this table\n// The first argument is the related model class; `belongsToMany` (pivot) and\n// `hasManyThrough` are deferred.\nexport function laravelModelForeignKeys(\n  file: SourceFile,\n  serviceDir: string,\n): TableReference[] {\n  const tree = parseSource(makePhpParser(), file.content)\n  const out: TableReference[] = []\n  const seen = new Set<string>()\n\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'class_declaration' || !isEloquentModel(node)) return\n    const thisTable = modelTable(node)\n    if (!thisTable) return\n\n    walkWithinClass(node, (call) => {\n      if (call.type !== 'member_call_expression') return\n      if (variableName(call.childForFieldName('object')) !== 'this') return\n      const macro = call.childForFieldName('name')?.text\n      if (!macro || !ELOQUENT_RELATIONS.has(macro)) return\n      const related = classRefBasename(phpArgumentValues(call.childForFieldName('arguments'))[0])\n      if (!related) return\n      const relatedTable = tableize(related)\n\n      const childTable = macro === 'belongsTo' ? thisTable : relatedTable\n      const parentTable = macro === 'belongsTo' ? relatedTable : thisTable\n      if (childTable === parentTable) return\n      const key = `${childTable}->${parentTable}`\n      if (seen.has(key)) return\n      seen.add(key)\n      const line = call.startPosition.row + 1\n      out.push({\n        childTable,\n        parentTable,\n        evidence: {\n          file: path.relative(serviceDir, file.path),\n          line,\n          snippet: snippet(file.content, line),\n        },\n      })\n    })\n  })\n\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport Go from 'tree-sitter-go'\nimport { infraId } from '@neat.is/types'\nimport { tableFromSqlStatement, columnsFromSqlStatement } from '../../otel.js'\nimport type { ExternalEndpoint, SourceFile } from './shared.js'\nimport { snippet, toPosix } from './shared.js'\n\n// Go raw-SQL data-axis recognizer. ADR-154 seeded this with the six `database/sql`\n// query/exec methods and the table alone; ADR-184 rounds it out into a real data\n// reader — the sqlx surface, the touched columns, and a structural import gate.\n//\n//   db.Query(\"SELECT id, email FROM users WHERE id = $1\")\n//   db.ExecContext(ctx, \"INSERT INTO orders (total) VALUES ($1)\")\n//   db.Get(&u, `SELECT id, email FROM accounts WHERE id = $1`)   // sqlx\n//\n// GORM (ADR-180) covers the ORM case; plenty of Go services skip the ORM and hand\n// `database/sql` or `github.com/jmoiron/sqlx` a literal SQL string, and those table\n// reads/writes land on the SAME `infra:sql-table:<name>` nodes every ORM reader\n// produces.\n//\n// THE POINT is fusion, not a static table list (that's what every other tool already\n// does). The OBSERVED ingest recovers the table by running `tableFromSqlStatement` on\n// the span's `db.statement` / `db.query.text` — there is no dedicated table attribute\n// (ADR-152) — so this recognizer runs the EXACT SAME helper on the SAME SQL text. The\n// extracted table name is therefore byte-identical to the observed one and the two\n// fuse on `infraId('sql-table', <name>)` rather than twinning. `columnsFromSqlStatement`\n// does the same for the touched columns, folded as `ColumnAttr` (ADR-157 §3). Don't\n// write a second SQL parser here — divergence from the ingest parse is the one way\n// this breaks.\n//\n// Import gate (mirrors net/http's structural gate in routes.ts): recognize only in a\n// file that imports `database/sql` and/or `github.com/jmoiron/sqlx`. Without it an\n// arbitrary `.Query(...)` / `.Exec(...)` on any object — an HTTP client, a template\n// engine — mints a phantom table from any string that happens to parse as SQL. The\n// sqlx-only methods (`Get`, `Select`, …) are common names, so they are recognized\n// only when sqlx is actually imported.\n\nconst PARSE_CHUNK = 16384\n\n// `database/sql`'s statement-taking methods. A `*sqlx.DB` embeds `*sql.DB`, so these\n// are recognized whenever EITHER import is present.\nconst DATABASE_SQL_METHODS = new Set([\n  'Query',\n  'QueryContext',\n  'QueryRow',\n  'QueryRowContext',\n  'Exec',\n  'ExecContext',\n  'Prepare',\n  'PrepareContext',\n])\n\n// sqlx's own statement-taking surface — recognized only when `sqlx` is imported.\n// `Get`/`Select`/`GetContext`/`SelectContext` take a destination pointer first, so\n// the SQL isn't argument 0; the \"first string-literal argument\" scan below handles\n// that the same way it skips a leading `ctx`.\nconst SQLX_METHODS = new Set([\n  'Get',\n  'Select',\n  'Queryx',\n  'QueryRowx',\n  'NamedExec',\n  'NamedQuery',\n  'MustExec',\n  'Preparex',\n  'GetContext',\n  'SelectContext',\n])\n\nconst DATABASE_SQL_IMPORT = 'database/sql'\nconst SQLX_IMPORT = 'github.com/jmoiron/sqlx'\n\nfunction makeGoParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Go)\n  return p\n}\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nfunction walk(node: Parser.SyntaxNode, visit: (node: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const child = node.namedChild(i)\n    if (child) walk(child, visit)\n  }\n}\n\n// The literal value of an interpreted (`\"...\"`) or raw/backtick (`` `...` ``) Go\n// string literal, delimiters stripped; null for anything else. Multi-line backtick\n// SQL is idiomatic in Go, so both node types are read verbatim — the backtick body\n// needs no unescaping.\nfunction goStringLiteralValue(node: Parser.SyntaxNode | null | undefined): string | null {\n  if (!node) return null\n  if (node.type === 'interpreted_string_literal' || node.type === 'raw_string_literal') {\n    const t = node.text\n    return t.length >= 2 ? t.slice(1, -1) : ''\n  }\n  return null\n}\n\n// Whether the file imports any of `names` — the structural half of the gate, read off\n// both the grouped `import ( … )` and the single `import \"database/sql\"` forms (each\n// yields an `import_spec` whose path is a string literal). Mirrors `goImportsNetHttp`\n// in routes.ts.\nfunction goImportsAny(root: Parser.SyntaxNode, names: Set<string>): boolean {\n  let found = false\n  walk(root, (node) => {\n    if (found || node.type !== 'import_spec') return\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const value = goStringLiteralValue(node.namedChild(i))\n      if (value !== null && names.has(value)) found = true\n    }\n  })\n  return found\n}\n\n// The first DIRECT argument that is itself a string literal — the SQL statement.\n// Scanning direct args (not recursing) both skips a leading `ctx` / destination\n// pointer and refuses a computed statement: a `fmt.Sprintf(...)` or `base + \" ...\"`\n// argument is a call/binary expression, not a string literal, so nothing matches and\n// the call site is left unclaimed rather than guessed.\nfunction firstStringLiteralArg(argsNode: Parser.SyntaxNode | null): string | null {\n  if (!argsNode) return null\n  for (let i = 0; i < argsNode.namedChildCount; i++) {\n    const value = goStringLiteralValue(argsNode.namedChild(i))\n    if (value !== null) return value\n  }\n  return null\n}\n\n// Raw-SQL call sites → `infra:sql-table:<name>` endpoints carrying the touched\n// columns (ADR-157 §3). Gated on the `database/sql` / `sqlx` import. One endpoint per\n// call site (not per table) so a SELECT and an INSERT to the same table each\n// contribute their columns — the orchestrator (calls/index.ts) dedupes the CALLS edge\n// and folds the union of columns onto the one node.\nexport function goSqlEndpointsFromFile(file: SourceFile, serviceDir: string): ExternalEndpoint[] {\n  if (path.extname(file.path) !== '.go') return []\n  // Cheap textual pre-check before parsing — inert on the vast majority of `.go`\n  // files that touch no SQL driver at all.\n  if (!file.content.includes(DATABASE_SQL_IMPORT) && !file.content.includes(SQLX_IMPORT)) return []\n\n  const tree = parseSource(makeGoParser(), file.content)\n  const importsDatabaseSql = goImportsAny(tree.rootNode, new Set([DATABASE_SQL_IMPORT]))\n  const importsSqlx = goImportsAny(tree.rootNode, new Set([SQLX_IMPORT]))\n  if (!importsDatabaseSql && !importsSqlx) return []\n\n  const out: ExternalEndpoint[] = []\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'call_expression') return\n    const fn = node.childForFieldName('function')\n    if (fn?.type !== 'selector_expression') return\n    const method = fn.childForFieldName('field')?.text\n    if (!method) return\n    const recognized = DATABASE_SQL_METHODS.has(method) || (importsSqlx && SQLX_METHODS.has(method))\n    if (!recognized) return\n\n    const sql = firstStringLiteralArg(node.childForFieldName('arguments'))\n    if (sql === null) return\n    const table = tableFromSqlStatement(sql)\n    if (!table) return\n    const columns = columnsFromSqlStatement(sql)\n    const line = node.startPosition.row + 1\n\n    out.push({\n      infraId: infraId('sql-table', table),\n      name: table,\n      kind: 'sql-table',\n      edgeType: 'CALLS',\n      confidenceKind: 'verified-call-site',\n      ...(columns.length > 0 ? { columns } : {}),\n      evidence: {\n        file: toPosix(path.relative(serviceDir, file.path)),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  })\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport Go from 'tree-sitter-go'\nimport { infraId } from '@neat.is/types'\nimport { snippet, toPosix, type ExternalEndpoint, type SourceFile, type TableReference } from './shared.js'\n\n// Go/GORM data-axis recognizer (ADR-180), the data rung for Go after ADR-154's\n// route + `database/sql` call sites. GORM model structs feed the SAME `sql-table`\n// nodes, `ColumnAttr` columns (ADR-157), and `REFERENCES` edges (ADR-161) Prisma,\n// Drizzle, Rails, and Laravel already produce, so the reasoning core learns nothing\n// GORM-specific (calls/activerecord.ts and calls/eloquent.ts are the closest\n// analogs — a Rails model or an Eloquent model is a GORM struct).\n//\n//   type User struct {\n//     gorm.Model                  // -> id, created_at, updated_at, deleted_at\n//     Name      string            // -> name\n//     CompanyID uint              // -> company_id (the belongs-to FK column)\n//     Company   Company           // belongs-to: users -> companies\n//     Orders    []Order           // has-many:   orders -> users\n//   }\n//   db.AutoMigrate(&User{}, &Company{}, &Order{})\n//\n// THE LOAD-BEARING DIFFERENCE from Rails/Laravel: GORM has no literal schema file.\n// Rails' `db/schema.rb` and Laravel's migrations spell the table/column names out\n// as the exact database strings; GORM DERIVES the table name from the struct name\n// by `inflection.Plural(toDBName(StructName))` (schema.NamingStrategy.TableName,\n// https://gorm.io/docs/conventions.html). So the pluralizer must reproduce GORM's\n// own — an initialism-aware snake_case plus a jinzhu/inflection-style pluralizer\n// with irregulars — because a wrong derivation mints a table node the runtime\n// never creates (a FALSE node), not merely a missed edge. The OBSERVED table is\n// the ground truth: the GORM OTel plugin reports `tx.Statement.Table` as\n// `db.collection.name`, which ADR-179 taught ingest to read into the table key, so\n// the extracted node fuses onto `infra:sql-table:<name>` by table NAME — the\n// derivation is aimed at exactly that string. Where the derivation is wrong, the\n// OBSERVED side is the anchor and the divergence surfaces the miss.\n\n// Cheap per-file gate — inert on every `.go` file that isn't a GORM model file,\n// the import-gate discipline the other data-axis readers follow.\nconst GORM_IMPORT_RE = /gorm\\.io\\/gorm/\n\nconst PARSE_CHUNK = 16384\n\nfunction makeGoParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Go)\n  return p\n}\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nfunction walk(node: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const c = node.namedChild(i)\n    if (c) walk(c, visit)\n  }\n}\n\n// ── inflection (GORM's schema.NamingStrategy, reproduced) ────────────────────\n//\n// Unlike the Rails/Laravel readers, where the schema literal is the anchor and the\n// pluralizer is a fallback, here the derived name IS the table name for every\n// struct without a `TableName()` override — so it must match GORM byte-for-byte or\n// the node fuses onto nothing.\n\n// The golint common-initialism list GORM's naming strategy links to. GORM replaces\n// each with its Title-case form BEFORE snake-casing, so a run like `API` collapses\n// to one word (`api`) instead of `a_p_i`. The exact set is GORM-version-sensitive\n// (GORM trims a few from golint's list across releases); this is the documented\n// best-effort surface where the OBSERVED table (ADR-179) is the ground-truth\n// anchor. Sorted longest-first so `HTTPS` wins over its `HTTP` prefix, matching\n// Go's `strings.Replacer` trie (longest match).\nconst COMMON_INITIALISMS = [\n  'ASCII', 'HTTPS', 'UTF8', 'XSRF', 'HTML', 'HTTP', 'JSON', 'UUID', 'XMPP',\n  'ACL', 'API', 'CPU', 'CSS', 'DNS', 'EOF', 'GUID', 'LHS', 'QPS', 'RAM', 'RHS',\n  'RPC', 'SLA', 'SQL', 'SSH', 'TCP', 'TLS', 'TTL', 'UDP', 'UID', 'URI', 'URL',\n  'UID', 'XSS', 'ID', 'IP', 'UI', 'VM', 'XML',\n].sort((a, b) => b.length - a.length)\n\nfunction titleCase(word: string): string {\n  return word.charAt(0) + word.slice(1).toLowerCase()\n}\n\n// Reproduce GORM's `commonInitialismsReplacer` — replace each initialism with its\n// Title-case form, scanning left-to-right, longest match first (Go's Replacer).\nfunction replaceInitialisms(name: string): string {\n  let out = ''\n  let i = 0\n  while (i < name.length) {\n    let matched = false\n    for (const init of COMMON_INITIALISMS) {\n      if (name.startsWith(init, i)) {\n        out += titleCase(init)\n        i += init.length\n        matched = true\n        break\n      }\n    }\n    if (!matched) {\n      out += name[i]\n      i++\n    }\n  }\n  return out\n}\n\nconst isUpper = (c: string): boolean => c >= 'A' && c <= 'Z'\nconst isDigit = (c: string): boolean => c >= '0' && c <= '9'\n\n// A faithful port of GORM's `NamingStrategy.toDBName` (schema/naming.go): run the\n// initialism replacer, then a CamelCase→snake pass that keeps capital runs\n// together (`APIKey` → `api_key`, `LineItem` → `line_item`, `GormUserName` →\n// `gorm_user_name`). Ported char-by-char since Go identifiers are ASCII.\nfunction toDBName(name: string): string {\n  if (name === '') return ''\n  const value = replaceInitialisms(name)\n  if (value.length === 1) return value.toLowerCase()\n\n  let buf = ''\n  let lastCase = false\n  let curCase = isUpper(value[0]!)\n  for (let i = 0; i < value.length - 1; i++) {\n    const v = value[i]!\n    const nextCase = isUpper(value[i + 1]!)\n    const nextNumber = isDigit(value[i + 1]!)\n    if (curCase) {\n      if (lastCase && (nextCase || nextNumber)) {\n        buf += v.toLowerCase()\n      } else {\n        if (i > 0 && value[i - 1] !== '_' && lastCase !== curCase) buf += '_'\n        buf += v.toLowerCase()\n      }\n    } else {\n      buf += v\n    }\n    lastCase = curCase\n    curCase = nextCase\n  }\n  const last = value[value.length - 1]!\n  if (curCase) {\n    if (!lastCase && value.length > 1) buf += '_'\n    buf += last.toLowerCase()\n  } else {\n    buf += last\n  }\n  return buf\n}\n\n// github.com/jinzhu/inflection (a Rails-ActiveSupport port) is what GORM pluralizes\n// with. Uncountables pass through, irregulars map directly, then the ordered rules\n// fire first-match-wins (specific before the generic `+s`). The irregular set is\n// finite/best-effort — documented in ADR-180, with the OBSERVED table as the\n// anchor where a rule is wrong. Operates on the snake_cased struct name, so the\n// rules anchor on the trailing word of a multi-word name (`line_item` → `line_items`).\nconst UNCOUNTABLE = new Set([\n  'equipment', 'information', 'rice', 'money', 'species', 'series', 'fish',\n  'sheep', 'jeans', 'police',\n])\n\nconst IRREGULAR: Array<[string, string]> = [\n  ['person', 'people'],\n  ['man', 'men'],\n  ['child', 'children'],\n  ['sex', 'sexes'],\n  ['move', 'moves'],\n]\n\nconst PLURAL_RULES: Array<[RegExp, string]> = [\n  [/(quiz)$/i, '$1zes'],\n  [/^(ox)$/i, '$1en'],\n  [/([ml])ouse$/i, '$1ice'],\n  [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'],\n  [/(x|ch|ss|sh)$/i, '$1es'],\n  [/([^aeiouy]|qu)y$/i, '$1ies'],\n  [/(hive)$/i, '$1s'],\n  [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'],\n  [/sis$/i, 'ses'],\n  [/([ti])um$/i, '$1a'],\n  [/([ti])a$/i, '$1a'],\n  [/(buffal|tomat)o$/i, '$1oes'],\n  [/(bu)s$/i, '$1ses'],\n  [/(alias|status)$/i, '$1es'],\n  [/(octop|vir)i$/i, '$1i'],\n  [/(octop|vir)us$/i, '$1i'],\n  [/(ax|test)is$/i, '$1es'],\n  [/s$/i, 's'],\n]\n\nfunction pluralize(word: string): string {\n  if (word === '') return word\n  const lower = word.toLowerCase()\n  for (const u of UNCOUNTABLE) {\n    if (lower === u || lower.endsWith('_' + u)) return word\n  }\n  for (const [sing, plur] of IRREGULAR) {\n    const re = new RegExp(sing + '$', 'i')\n    if (re.test(word)) return word.replace(re, plur)\n  }\n  for (const [re, rep] of PLURAL_RULES) {\n    if (re.test(word)) return word.replace(re, rep)\n  }\n  return word + 's'\n}\n\n// struct name → GORM's default table name: `inflection.Plural(toDBName(name))`.\n// `User` → users, `LineItem` → line_items, `APIKey` → api_keys, `Person` → people.\nfunction deriveTableName(structName: string): string {\n  return pluralize(toDBName(structName))\n}\n\n// ── struct / field model ─────────────────────────────────────────────────────\n\ninterface GormTag {\n  column?: string\n  skip?: boolean // gorm:\"-\"\n  primaryKey?: boolean\n  foreignKey?: string\n  many2many?: string\n  embedded?: boolean\n  embeddedPrefix?: string\n}\n\ninterface GoField {\n  names: string[] // empty for an embedded (anonymous) field\n  typeName: string | null // base type name, slice/pointer/array unwrapped\n  qualifier: string | null // package part of a qualified type (`gorm` in gorm.Model)\n  isSlice: boolean\n  isPointer: boolean\n  isQualified: boolean\n  tag: GormTag\n  line: number\n}\n\ninterface StructInfo {\n  name: string\n  fields: GoField[]\n  line: number\n}\n\nfunction stringLiteralValue(node: Parser.SyntaxNode | null | undefined): string | null {\n  if (!node) return null\n  if (node.type === 'interpreted_string_literal' || node.type === 'raw_string_literal') {\n    const t = node.text\n    return t.length >= 2 ? t.slice(1, -1) : ''\n  }\n  return null\n}\n\n// Parse a struct field's `gorm:\"...\"` tag. The tag node text carries its delimiters\n// (backticks for a raw string, quotes for an interpreted one); an interpreted tag\n// escapes its inner quotes, so unescape first.\nfunction parseGormTag(tagNode: Parser.SyntaxNode | null | undefined): GormTag {\n  const tag: GormTag = {}\n  if (!tagNode) return tag\n  let inner = tagNode.text\n  if (inner.length >= 2) inner = inner.slice(1, -1)\n  if (tagNode.type === 'interpreted_string_literal') inner = inner.replace(/\\\\\"/g, '\"')\n  const m = inner.match(/gorm:\"([^\"]*)\"/)\n  if (!m) return tag\n  for (const part of m[1]!.split(';')) {\n    if (part === '') continue\n    const idx = part.indexOf(':')\n    const key = (idx >= 0 ? part.slice(0, idx) : part).trim().toLowerCase()\n    const value = idx >= 0 ? part.slice(idx + 1).trim() : ''\n    if (key === '-') tag.skip = true\n    else if (key === 'column') tag.column = value\n    else if (key === 'primarykey' || key === 'primary_key') tag.primaryKey = true\n    else if (key === 'foreignkey') tag.foreignKey = value\n    else if (key === 'many2many') tag.many2many = value\n    else if (key === 'embedded') tag.embedded = true\n    else if (key === 'embeddedprefix') tag.embeddedPrefix = value\n  }\n  return tag\n}\n\n// Unwrap a field's type through any slice / array / pointer layers to the base\n// named type. `[]Order` → { name: 'Order', isSlice }, `*Company` → { name:\n// 'Company', isPointer }, `time.Time` → { name: 'Time', qualifier: 'time' }.\nfunction unwrapType(typeNode: Parser.SyntaxNode | null): {\n  name: string | null\n  qualifier: string | null\n  isSlice: boolean\n  isPointer: boolean\n  isQualified: boolean\n} {\n  let isSlice = false\n  let isPointer = false\n  let n: Parser.SyntaxNode | null = typeNode\n  while (n && (n.type === 'slice_type' || n.type === 'array_type' || n.type === 'pointer_type')) {\n    if (n.type === 'slice_type' || n.type === 'array_type') isSlice = true\n    if (n.type === 'pointer_type') isPointer = true\n    n = n.childForFieldName('element') ?? n.namedChild(n.namedChildCount - 1)\n  }\n  if (!n) return { name: null, qualifier: null, isSlice, isPointer, isQualified: false }\n  if (n.type === 'type_identifier') {\n    return { name: n.text, qualifier: null, isSlice, isPointer, isQualified: false }\n  }\n  if (n.type === 'qualified_type') {\n    const pkg = n.childForFieldName('package')?.text ?? n.namedChild(0)?.text ?? null\n    const nm = n.childForFieldName('name')?.text ?? n.namedChild(1)?.text ?? null\n    return { name: nm, qualifier: pkg, isSlice, isPointer, isQualified: true }\n  }\n  // map / func / interface / channel types are never a column or a relation.\n  return { name: null, qualifier: null, isSlice, isPointer, isQualified: false }\n}\n\nfunction readField(fieldDecl: Parser.SyntaxNode): GoField {\n  const names: string[] = []\n  let tagNode: Parser.SyntaxNode | null = null\n  for (let i = 0; i < fieldDecl.namedChildCount; i++) {\n    const c = fieldDecl.namedChild(i)\n    if (!c) continue\n    if (c.type === 'field_identifier') names.push(c.text)\n    else if (c.type === 'raw_string_literal' || c.type === 'interpreted_string_literal') tagNode = c\n  }\n  const typeNode = fieldDecl.childForFieldName('type')\n  const t = unwrapType(typeNode)\n  return {\n    names,\n    typeName: t.name,\n    qualifier: t.qualifier,\n    isSlice: t.isSlice,\n    isPointer: t.isPointer,\n    isQualified: t.isQualified,\n    tag: parseGormTag(tagNode),\n    line: fieldDecl.startPosition.row + 1,\n  }\n}\n\n// Every `type X struct { … }` in the file, keyed by name.\nfunction collectStructs(tree: Parser.Tree): Map<string, StructInfo> {\n  const structs = new Map<string, StructInfo>()\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'type_spec') return\n    const nameNode = node.childForFieldName('name')\n    const typeNode = node.childForFieldName('type')\n    if (!nameNode || typeNode?.type !== 'struct_type') return\n    const list = typeNode.childForFieldName('body') ?? typeNode.namedChild(0)\n    const fields: GoField[] = []\n    if (list && list.type === 'field_declaration_list') {\n      for (let i = 0; i < list.namedChildCount; i++) {\n        const fd = list.namedChild(i)\n        if (fd?.type === 'field_declaration') fields.push(readField(fd))\n      }\n    }\n    structs.set(nameNode.text, {\n      name: nameNode.text,\n      fields,\n      line: node.startPosition.row + 1,\n    })\n  })\n  return structs\n}\n\n// GORM entry points that take a model pointer/value and so name a model struct.\n// `AutoMigrate(&A{}, &B{})` is the richest — it enumerates the whole model set in\n// one call.\nconst GORM_MODEL_METHODS = new Set([\n  'AutoMigrate', 'Model', 'Create', 'Find', 'First', 'Take', 'Last', 'Save',\n  'Delete', 'Where', 'FirstOrCreate', 'FirstOrInit',\n])\n\n// The struct name a `&X{}` / `X{}` argument composite-literal names, or null.\nfunction compositeStructName(arg: Parser.SyntaxNode): string | null {\n  let n: Parser.SyntaxNode | null = arg\n  if (n.type === 'unary_expression') n = n.childForFieldName('operand') ?? n.namedChild(0)\n  if (!n || n.type !== 'composite_literal') return null\n  const typeNode = n.childForFieldName('type')\n  if (!typeNode) return null\n  if (typeNode.type === 'type_identifier') return typeNode.text\n  if (typeNode.type === 'qualified_type') {\n    return typeNode.childForFieldName('name')?.text ?? typeNode.namedChild(1)?.text ?? null\n  }\n  return null\n}\n\n// Model structs referenced through a GORM db-method call anywhere in the file.\nfunction collectCallModels(tree: Parser.Tree): Set<string> {\n  const models = new Set<string>()\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'call_expression') return\n    const fn = node.childForFieldName('function')\n    if (fn?.type !== 'selector_expression') return\n    const method = fn.childForFieldName('field')?.text\n    if (!method || !GORM_MODEL_METHODS.has(method)) return\n    const args = node.childForFieldName('arguments')\n    if (!args) return\n    for (let i = 0; i < args.namedChildCount; i++) {\n      const arg = args.namedChild(i)\n      if (!arg) continue\n      const name = compositeStructName(arg)\n      if (name) models.add(name)\n    }\n  })\n  return models\n}\n\n// A `func (X) TableName() string { return \"literal\" }` override map. A computed\n// return (a variable, a concatenation) yields no entry — the struct falls back to\n// the derived name — but still counts as a model signal.\nfunction collectTableNameOverrides(\n  tree: Parser.Tree,\n): { overrides: Map<string, string>; declarers: Set<string> } {\n  const overrides = new Map<string, string>()\n  const declarers = new Set<string>()\n  walk(tree.rootNode, (node) => {\n    if (node.type !== 'method_declaration') return\n    if (node.childForFieldName('name')?.text !== 'TableName') return\n    const receiver = node.childForFieldName('receiver')\n    if (!receiver) return\n    let recvType: string | null = null\n    for (let i = 0; i < receiver.namedChildCount; i++) {\n      const pd = receiver.namedChild(i)\n      if (pd?.type !== 'parameter_declaration') continue\n      const t = unwrapType(pd.childForFieldName('type'))\n      recvType = t.name\n    }\n    if (!recvType) return\n    declarers.add(recvType)\n    const body = node.childForFieldName('body')\n    if (!body) return\n    let literal: string | null = null\n    walk(body, (n) => {\n      if (literal !== null) return\n      if (n.type !== 'return_statement') return\n      const exprList = n.namedChild(0)\n      const first = exprList?.namedChild(0) ?? exprList\n      const v = stringLiteralValue(first)\n      if (v) literal = v\n    })\n    if (literal !== null) overrides.set(recvType, literal)\n  })\n  return { overrides, declarers }\n}\n\n// A field is a RELATION (association), not a column, when its base type — slice or\n// pointer unwrapped — is another struct declared in this file, and it is not a\n// qualified type (`time.Time`, `sql.NullString`) or the embedded `gorm.Model`.\nfunction isRelationField(field: GoField, structs: Map<string, StructInfo>): boolean {\n  if (field.names.length === 0) return false // embedded, handled separately\n  if (field.isQualified) return false\n  if (!field.typeName) return false\n  return structs.has(field.typeName)\n}\n\n// Is `gorm.Model`?\nfunction isGormModelEmbed(field: GoField): boolean {\n  return field.names.length === 0 && field.qualifier === 'gorm' && field.typeName === 'Model'\n}\n\n// ── analysis (shared by the endpoint and FK readers) ─────────────────────────\n\ninterface Analysis {\n  structs: Map<string, StructInfo>\n  models: Set<string>\n  tableFor: (structName: string) => string\n}\n\nfunction analyze(tree: Parser.Tree): Analysis {\n  const structs = collectStructs(tree)\n  const { overrides, declarers } = collectTableNameOverrides(tree)\n  const callModels = collectCallModels(tree)\n\n  // Seed the model set from the three direct signals: a gorm.Model embed, a GORM\n  // db-method call arg, or a TableName() declaration.\n  const models = new Set<string>()\n  for (const [name, info] of structs) {\n    if (info.fields.some(isGormModelEmbed)) models.add(name)\n  }\n  for (const name of callModels) if (structs.has(name)) models.add(name)\n  for (const name of declarers) if (structs.has(name)) models.add(name)\n\n  // Expand: a struct referenced as a relation field by a model is itself a model\n  // (GORM requires the related type to be a registered model). Fixpoint over the\n  // relation graph so a related model's own relations pull their targets in too.\n  let grew = true\n  while (grew) {\n    grew = false\n    for (const name of Array.from(models)) {\n      const info = structs.get(name)\n      if (!info) continue\n      for (const field of info.fields) {\n        if (!isRelationField(field, structs)) continue\n        const target = field.typeName!\n        if (!models.has(target) && structs.has(target)) {\n          models.add(target)\n          grew = true\n        }\n      }\n    }\n  }\n\n  const tableFor = (structName: string): string =>\n    overrides.get(structName) ?? deriveTableName(structName)\n\n  return { structs, models, tableFor }\n}\n\n// Expand a model struct's fields into its database column names. Anonymous\n// embedded fields inline: `gorm.Model` → the four audit columns, and an embedded\n// LOCAL struct (`type Base struct{…}; type User struct{ Base; … }`) inlines its own\n// columns (one level, cycle-guarded). A named field with `gorm:\"embedded\"` inlines\n// with an optional prefix. `gorm:\"-\"` skips; a relation field is not a column.\nfunction collectColumns(\n  struct: StructInfo,\n  structs: Map<string, StructInfo>,\n  seen: Set<string>,\n  prefix: string,\n  out: string[],\n  emitted: Set<string>,\n): void {\n  if (seen.has(struct.name)) return\n  seen.add(struct.name)\n\n  const add = (col: string): void => {\n    const full = prefix + col\n    if (!emitted.has(full)) {\n      emitted.add(full)\n      out.push(full)\n    }\n  }\n\n  for (const field of struct.fields) {\n    if (field.tag.skip) continue\n\n    // Anonymous embedded field.\n    if (field.names.length === 0) {\n      if (isGormModelEmbed(field)) {\n        add('id')\n        add('created_at')\n        add('updated_at')\n        add('deleted_at')\n      } else if (!field.isQualified && field.typeName && structs.has(field.typeName)) {\n        collectColumns(structs.get(field.typeName)!, structs, seen, prefix, out, emitted)\n      }\n      // An unresolved external embed (some other package's base) can't be inlined.\n      continue\n    }\n\n    // A named field tagged embedded inlines the target struct's columns.\n    if (field.tag.embedded && !field.isQualified && field.typeName && structs.has(field.typeName)) {\n      collectColumns(\n        structs.get(field.typeName)!,\n        structs,\n        seen,\n        prefix + (field.tag.embeddedPrefix ?? ''),\n        out,\n        emitted,\n      )\n      continue\n    }\n\n    // A relation to another model is not a column (its FK companion scalar is).\n    if (isRelationField(field, structs)) continue\n\n    // A scalar / time.Time / sql.Null* / []byte / named-scalar field is a column.\n    // The `gorm:\"column:x\"` override wins (verbatim); otherwise snake_case each\n    // name. The override only makes sense for a single-name declaration.\n    if (field.names.length === 1 && field.tag.column) {\n      add(field.tag.column)\n    } else {\n      for (const n of field.names) add(toDBName(n))\n    }\n  }\n\n  seen.delete(struct.name)\n}\n\n// GORM model structs → `infra:sql-table:<name>` endpoints carrying EXTRACTED\n// columns (ADR-157 §3). Gated on the `gorm.io/gorm` import. One endpoint per\n// distinct table; the orchestrator (calls/index.ts) mints the node, folds the\n// columns, and originates the `file ──CALLS──▶ sql-table` edge.\nexport function gormEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  if (path.extname(file.path) !== '.go') return []\n  if (!GORM_IMPORT_RE.test(file.content)) return []\n  const tree = parseSource(makeGoParser(), file.content)\n  const { structs, models, tableFor } = analyze(tree)\n\n  const out: ExternalEndpoint[] = []\n  const seenTables = new Set<string>()\n  for (const name of models) {\n    const struct = structs.get(name)\n    if (!struct) continue\n    const table = tableFor(name)\n    if (seenTables.has(table)) continue\n    seenTables.add(table)\n\n    const columns: string[] = []\n    collectColumns(struct, structs, new Set(), '', columns, new Set())\n\n    out.push({\n      infraId: infraId('sql-table', table),\n      name: table,\n      kind: 'sql-table',\n      edgeType: 'CALLS',\n      confidenceKind: 'structural',\n      ...(columns.length > 0 ? { columns } : {}),\n      evidence: {\n        file: toPosix(path.relative(serviceDir, file.path)),\n        line: struct.line,\n        snippet: snippet(file.content, struct.line),\n      },\n    })\n  }\n  return out\n}\n\n// GORM associations → `REFERENCES` table→table edges (ADR-161). The FK lives on the\n// table holding the `<Field>ID` column, so direction depends on the association:\n//   belongs to (User has CompanyID + Company Company) -> users REFERENCES companies\n//   has one    (User has CreditCard CreditCard)       -> credit_cards REFERENCES users\n//   has many   (User has Orders []Order)              -> orders REFERENCES users\n//   many2many  (User has Languages []Language `many2many:user_languages`)\n//                                    -> user_languages REFERENCES users + languages\n// A singular struct field is belongs-to when THIS struct also holds the\n// conventional `<Field>ID` (or `foreignKey:`-named) scalar; otherwise has-one.\n// `table-edges.ts` dedupes at the graph level and drops self-loops.\nexport function gormForeignKeys(file: SourceFile, serviceDir: string): TableReference[] {\n  if (path.extname(file.path) !== '.go') return []\n  if (!GORM_IMPORT_RE.test(file.content)) return []\n  const tree = parseSource(makeGoParser(), file.content)\n  const { structs, models, tableFor } = analyze(tree)\n\n  const out: TableReference[] = []\n  const seen = new Set<string>()\n  const emit = (childTable: string, parentTable: string, line: number): void => {\n    if (!childTable || !parentTable || childTable === parentTable) return\n    const key = `${childTable}->${parentTable}`\n    if (seen.has(key)) return\n    seen.add(key)\n    out.push({\n      childTable,\n      parentTable,\n      evidence: {\n        file: toPosix(path.relative(serviceDir, file.path)),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  }\n\n  for (const name of models) {\n    const struct = structs.get(name)\n    if (!struct) continue\n    const thisTable = tableFor(name)\n    const scalarNames = new Set(\n      struct.fields\n        .filter((f) => f.names.length > 0 && !isRelationField(f, structs))\n        .flatMap((f) => f.names),\n    )\n\n    for (const field of struct.fields) {\n      if (field.tag.skip) continue\n      if (!isRelationField(field, structs)) continue\n      const relTable = tableFor(field.typeName!)\n\n      // many2many: synthesize the join table and reference both sides.\n      if (field.tag.many2many) {\n        emit(field.tag.many2many, thisTable, field.line)\n        emit(field.tag.many2many, relTable, field.line)\n        continue\n      }\n\n      if (field.isSlice) {\n        // has many — FK on the other table.\n        emit(relTable, thisTable, field.line)\n        continue\n      }\n\n      // Singular struct field: belongs-to when this struct carries the FK column.\n      const convFk = field.names[0]! + 'ID'\n      const belongsTo =\n        scalarNames.has(convFk) ||\n        (field.tag.foreignKey ? scalarNames.has(field.tag.foreignKey) : false)\n      if (belongsTo) emit(thisTable, relTable, field.line)\n      else emit(relTable, thisTable, field.line)\n    }\n  }\n\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport CSharp from 'tree-sitter-c-sharp'\nimport { infraId } from '@neat.is/types'\nimport { snippet, toPosix, type ExternalEndpoint, type SourceFile } from './shared.js'\n\n// EF Core / .NET data-axis recognizer (ADR-203) — the C# rung of the same\n// `infra:sql-table:<name>` grain the SQLAlchemy, GORM, ActiveRecord, and Eloquent\n// readers already produce. The SQL analog of calls/gorm.ts, but with the opposite\n// fidelity problem solved for free: where GORM *derives* the table name from the\n// struct (so the pluralizer has to match byte-for-byte), EF Core's fusion-anchored\n// shape is an EXPLICIT table name, so the recognizer reads a literal and never\n// guesses:\n//\n//   [Table(\"orderitem\", Schema = \"accounting\")]          // data annotation\n//   public class OrderItemEntity { ... }\n//\n//   modelBuilder.Entity<OrderEntity>().ToTable(\"order\"); // fluent API\n//\n// Both name the database table VERBATIM — the same string the running query hits,\n// which is the string an OBSERVED db span reports (recovered from `db.statement`\n// the way ADR-152 recovers SQLAlchemy's), so the extracted node fuses onto\n// `infra:sql-table:<name>` by table name. The otel-demo `accounting` service names\n// `orderitem` / `order` / `shipping` this way, so its OBSERVED `CALLS\n// infra:sql-table:orderitem` edge gets a static twin instead of orphaning.\n//\n// Table grain only. EF Core's COLUMN names are convention-transformed\n// (`UseSnakeCaseNamingConvention()` and friends, configured in a different file\n// than the entity), so reproducing them faithfully is not a per-file fact the way\n// GORM's tags are — and a PARTIAL column set would manufacture false column-drift.\n// The OBSERVED side anchors columns regardless, so column grain is left as a named\n// follow-on rather than guessed at.\n\n// Cheap per-file gate — inert on any `.cs` file that isn't an EF Core entity /\n// model-configuration file, the import-gate discipline the data-axis readers share.\n// The `[Table]` / `[Column]` annotations live in\n// `System.ComponentModel.DataAnnotations.Schema`; `DbContext` / `DbSet<>` and the\n// fluent API live in `Microsoft.EntityFrameworkCore`.\nconst EFCORE_GATE =\n  /Microsoft\\.EntityFrameworkCore|DataAnnotations\\.Schema|\\bDbContext\\b|\\bDbSet\\s*</\n\nconst PARSE_CHUNK = 16384\n\nfunction makeCsParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(CSharp)\n  return p\n}\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nfunction walk(node: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const c = node.namedChild(i)\n    if (c) walk(c, visit)\n  }\n}\n\nfunction firstChildOfType(node: Parser.SyntaxNode, type: string): Parser.SyntaxNode | null {\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const c = node.namedChild(i)\n    if (c?.type === type) return c\n  }\n  return null\n}\n\n// A C# string literal node's value, or null when it is not a plain string (an\n// interpolated `$\"...\"` carries a runtime hole — never a static table name).\n// A regular `\"orders\"` exposes its text through a `string_literal_content` child;\n// a verbatim `@\"orders\"` is a leaf whose `@\"` / `\"` delimiters (and doubled `\"\"`\n// escapes) are stripped here.\nfunction csStringLiteral(node: Parser.SyntaxNode): string | null {\n  if (node.type === 'string_literal') {\n    let out = ''\n    for (let i = 0; i < node.namedChildCount; i++) {\n      const c = node.namedChild(i)\n      if (c?.type === 'string_literal_content') out += c.text\n    }\n    return out\n  }\n  if (node.type === 'verbatim_string_literal') {\n    const t = node.text\n    return t.length >= 3 ? t.slice(2, -1).replace(/\"\"/g, '\"') : ''\n  }\n  return null\n}\n\n// The trailing identifier of an attribute name (`Table`, or the last segment of a\n// qualified `…Schema.Table`), so `[Table(...)]` and a fully-qualified spelling\n// both resolve to `Table`. Tolerates the `Attribute` suffix C# allows to be\n// dropped (`[TableAttribute(...)]`).\nfunction attributeName(attr: Parser.SyntaxNode): string | null {\n  const nameNode = attr.childForFieldName('name') ?? attr.namedChild(0)\n  if (!nameNode) return null\n  const text = nameNode.text\n  const base = text.includes('.') ? text.slice(text.lastIndexOf('.') + 1) : text\n  return base.endsWith('Attribute') ? base.slice(0, -'Attribute'.length) : base\n}\n\n// The literal table name a `[Table(\"orders\", …)]` attribute declares: the value of\n// its first POSITIONAL string argument. A `[Table(nameof(X))]` or a keyword-only\n// form (`[Table(Schema = \"s\")]`) yields no positional string and is left unclaimed\n// rather than guessed.\nfunction tableFromAttribute(attr: Parser.SyntaxNode): string | null {\n  if (attributeName(attr) !== 'Table') return null\n  const args = attr.childForFieldName('arguments') ?? firstChildOfType(attr, 'attribute_argument_list')\n  if (!args) return null\n  for (let i = 0; i < args.namedChildCount; i++) {\n    const arg = args.namedChild(i)\n    if (arg?.type !== 'attribute_argument') continue\n    // A named argument (`Schema = \"accounting\"`) is an assignment_expression — not\n    // the positional table name. The positional table name is a bare string child.\n    const first = arg.namedChild(0)\n    if (!first) continue\n    const value = csStringLiteral(first)\n    if (value !== null) return value\n    return null // first positional arg is not a plain string — don't guess\n  }\n  return null\n}\n\n// The literal table name a `.ToTable(\"orders\")` fluent call declares: the value of\n// its first string argument. `.ToTable(t => …)` (a table-builder overload) and any\n// non-string first argument yield nothing.\nfunction tableFromToTable(call: Parser.SyntaxNode): string | null {\n  const fn = call.childForFieldName('function')\n  if (fn?.type !== 'member_access_expression') return null\n  const method = fn.childForFieldName('name') ?? fn.namedChild(fn.namedChildCount - 1)\n  if (method?.text !== 'ToTable') return null\n  const args = call.childForFieldName('arguments')\n  const firstArg = args?.namedChild(0)\n  if (firstArg?.type !== 'argument') return null\n  const value = firstArg.namedChild(0)\n  return value ? csStringLiteral(value) : null\n}\n\n// EF Core entity / model-configuration files → `infra:sql-table:<name>` endpoints\n// (ADR-203). Gated on an EF Core signal; parsed with tree-sitter-c-sharp from the\n// RAW file (comments are structural `comment` nodes, so a `[Table(\"x\")]` in a `//`\n// or `/* */` comment never mints a node). One endpoint per distinct table name;\n// the orchestrator (calls/index.ts) mints the node and the `file ──CALLS──▶\n// sql-table` edge. Table grain — no columns (see the file header).\nexport function efcoreEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  if (path.extname(file.path) !== '.cs') return []\n  if (!EFCORE_GATE.test(file.content)) return []\n  const tree = parseSource(makeCsParser(), file.content)\n\n  const out: ExternalEndpoint[] = []\n  const seen = new Set<string>()\n  const push = (name: string, line: number): void => {\n    if (!name || seen.has(name)) return\n    seen.add(name)\n    out.push({\n      infraId: infraId('sql-table', name),\n      name,\n      kind: 'sql-table',\n      edgeType: 'CALLS',\n      confidenceKind: 'structural',\n      evidence: {\n        file: toPosix(path.relative(serviceDir, file.path)),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  }\n\n  walk(tree.rootNode, (node) => {\n    if (node.type === 'attribute') {\n      const table = tableFromAttribute(node)\n      if (table) push(table, node.startPosition.row + 1)\n      return\n    }\n    if (node.type === 'invocation_expression') {\n      const table = tableFromToTable(node)\n      if (table) push(table, node.startPosition.row + 1)\n    }\n  })\n\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport JavaScript from 'tree-sitter-javascript'\nimport { infraId } from '@neat.is/types'\nimport { tableFromSqlStatement, columnsFromSqlStatement } from '../../otel.js'\nimport { GRAMMAR_BY_EXT, parseSource } from '../symbols.js'\nimport { snippet, toPosix, type ExternalEndpoint, type SourceFile } from './shared.js'\n\n// JS/TS raw-SQL data-axis recognizer for the `mysql` / `mysql2` drivers (#1432) —\n// the JavaScript sibling of the Go `database/sql` reader (calls/go.ts, ADR-184).\n// A service that talks to MySQL through a plain driver with SQL in strings gets no\n// table grain today: the JS ORM readers cover knex / sequelize / prisma / drizzle /\n// typeorm, but a bare `mysql`/`mysql2` connection handed a literal statement lands\n// nothing. This reads the table (and the touched columns) off that statement and\n// mints the same `infra:sql-table:<name>` node every ORM reader and the OBSERVED\n// ingest produce.\n//\n//   const mysql = require('mysql')\n//   conn.query(\"SELECT * FROM office\", cb)                         // inline literal\n//   const sql = \"SELECT * FROM office \" + where_sql; conn.query(sql, cb)   // var + head\n//   conn.execute(\"INSERT INTO office (name) VALUES (?)\", [n])      // mysql2\n//\n// THE POINT is fusion, not a static table list. The OBSERVED ingest recovers the\n// table by running `tableFromSqlStatement` on a span's `db.statement` (there is no\n// dedicated table attribute — ADR-152), so this recognizer runs the EXACT SAME\n// shared helper on the SAME SQL text and the extracted table is byte-identical to\n// the observed one — the two fuse on `infraId('sql-table', <name>)` rather than\n// twinning. `columnsFromSqlStatement` does the same for the touched columns (ADR-157\n// §3). Both live in otel.ts, their one home — never a second SQL parser here, since\n// divergence from the ingest parse is the one way this breaks.\n//\n// Statement shape (#1432 ruling a): a statement whose literal HEAD parses to\n// `SELECT … FROM <t>` / `INSERT INTO <t>` / `UPDATE <t>` / `DELETE FROM <t>` is\n// claimed with the table from the head; a runtime tail (`\"… FROM office \" + where`)\n// does not block it. A `CREATE TABLE` has no FROM/INTO/UPDATE keyword, so\n// `tableFromSqlStatement` returns null and it is left unclaimed — the honest,\n// conservative default, never guessed.\n//\n// Variable resolution (#1432): the statement is usually built into a local variable\n// first (`const sql = …; conn.query(sql, cb)`), so a `.query`/`.execute` whose first\n// argument is an identifier is resolved to its SAME-FILE, ENCLOSING-FUNCTION,\n// NEAREST-PRECEDING assignment, and only when that value is a string literal or a\n// literal-headed concatenation. An identifier reassigned in between (the nearest\n// assignment is then the non-literal one), a function parameter, or an argument with\n// no literal head stays unclaimed. This is the same literal inlining the URL-helper\n// recognizer (#1426) does for one-return helpers — precedent, not a new shape.\n//\n// Import gate (mirrors calls/go.ts' driver gate): recognized only in a file that\n// imports `mysql` or `mysql2` (incl. `mysql2/promise`). Without it a `.query(...)` /\n// `.execute(...)` on any object — an HTTP client, an ORM — could mint a phantom\n// table from any string that happens to parse as SQL. The SQL-parse gate\n// (`tableFromSqlStatement` returning a table) is the second filter, so a non-SQL\n// `.execute(\"...\")` in a mysql-importing file still claims nothing.\n\n// `require('mysql')` / `require('mysql2')` / `require('mysql2/promise')` and the\n// `import … from 'mysql2/promise'` forms.\nconst MYSQL_IMPORT_RE = /(?:from\\s+['\"`]|require\\(\\s*['\"`])mysql2?(?:\\/promise)?['\"`]/\n\n// Statement-taking methods on a `mysql`/`mysql2` connection, pool, or promise\n// wrapper. `query` is `mysql` + `mysql2`; `execute` is `mysql2`'s prepared path.\nconst SQL_METHODS = new Set(['query', 'execute'])\n\nconst JS_EXTS = new Set(['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx'])\n\n// Nodes that open a new function scope — the boundary variable resolution does not\n// cross (a `.query(sql)` resolves `sql` only within its own enclosing function).\nconst FUNCTION_NODE_TYPES = new Set([\n  'function_declaration',\n  'function_expression',\n  'arrow_function',\n  'method_definition',\n  'generator_function',\n  'generator_function_declaration',\n])\n\nfunction parserForExt(ext: string): Parser {\n  const p = new Parser()\n  p.setLanguage(GRAMMAR_BY_EXT[ext] ?? JavaScript)\n  return p\n}\n\nfunction namedChildren(node: Parser.SyntaxNode): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const c = node.namedChild(i)\n    if (c) out.push(c)\n  }\n  return out\n}\n\n// The full literal value of a plain `string` node (quotes stripped); null for a\n// template / any non-string node. An empty `''` has no `string_fragment` child.\nfunction stringLiteralValue(node: Parser.SyntaxNode | null): string | null {\n  if (!node || node.type !== 'string') return null\n  for (const c of namedChildren(node)) {\n    if (c.type === 'string_fragment') return c.text\n  }\n  return ''\n}\n\n// The value of an expression that is ENTIRELY string-literal — a `string`, a\n// template with no `${}`, or a `+` concatenation of such — else null.\nfunction pureLiteral(node: Parser.SyntaxNode | null): string | null {\n  if (!node) return null\n  if (node.type === 'string') return stringLiteralValue(node)\n  if (node.type === 'template_string') {\n    let v = ''\n    for (const c of namedChildren(node)) {\n      if (c.type === 'template_substitution') return null\n      if (c.type === 'string_fragment') v += c.text\n      else if (c.type === 'escape_sequence') return null\n    }\n    return v\n  }\n  if (node.type === 'binary_expression' && node.childForFieldName('operator')?.text === '+') {\n    const l = pureLiteral(node.childForFieldName('left'))\n    const r = pureLiteral(node.childForFieldName('right'))\n    return l !== null && r !== null ? l + r : null\n  }\n  return null\n}\n\n// The leading literal portion of an expression (#1432 ruling a): the statement head\n// even when a runtime tail follows. null when there is no literal head.\nfunction literalHead(node: Parser.SyntaxNode | null): string | null {\n  if (!node) return null\n  const whole = pureLiteral(node)\n  if (whole !== null) return whole\n  if (node.type === 'template_string') {\n    let head = ''\n    let saw = false\n    for (const c of namedChildren(node)) {\n      if (c.type === 'template_substitution') break\n      if (c.type === 'string_fragment') {\n        head += c.text\n        saw = true\n      } else if (c.type === 'escape_sequence') break\n    }\n    return saw ? head : null\n  }\n  if (node.type === 'binary_expression' && node.childForFieldName('operator')?.text === '+') {\n    const left = node.childForFieldName('left')\n    const leftFull = pureLiteral(left)\n    if (leftFull !== null) {\n      const rightHead = literalHead(node.childForFieldName('right'))\n      return rightHead !== null ? leftFull + rightHead : leftFull\n    }\n    return literalHead(left)\n  }\n  return null\n}\n\nfunction enclosingFunction(node: Parser.SyntaxNode): Parser.SyntaxNode | null {\n  let cur = node.parent\n  while (cur) {\n    if (FUNCTION_NODE_TYPES.has(cur.type)) return cur\n    cur = cur.parent\n  }\n  return null\n}\n\n// The value node of the nearest preceding assignment to `name` within `scope`, not\n// descending into nested function scopes. Handles both `var/let/const name = …`\n// (`variable_declarator`) and `name = …` (`assignment_expression`).\nfunction nearestAssignmentValue(\n  scope: Parser.SyntaxNode,\n  name: string,\n  beforeIndex: number,\n): Parser.SyntaxNode | null {\n  let best: { pos: number; value: Parser.SyntaxNode } | null = null\n  const visit = (node: Parser.SyntaxNode): void => {\n    for (const c of namedChildren(node)) {\n      if (c.type === 'variable_declarator') {\n        const nm = c.childForFieldName('name')\n        const val = c.childForFieldName('value')\n        if (nm?.type === 'identifier' && nm.text === name && val && c.startIndex < beforeIndex) {\n          if (!best || c.startIndex > best.pos) best = { pos: c.startIndex, value: val }\n        }\n      } else if (c.type === 'assignment_expression') {\n        const lhs = c.childForFieldName('left')\n        const val = c.childForFieldName('right')\n        if (lhs?.type === 'identifier' && lhs.text === name && val && c.startIndex < beforeIndex) {\n          if (!best || c.startIndex > best.pos) best = { pos: c.startIndex, value: val }\n        }\n      }\n      if (!FUNCTION_NODE_TYPES.has(c.type)) visit(c)\n    }\n  }\n  visit(scope)\n  return best ? best.value : null\n}\n\nexport function mysqlJsEndpointsFromFile(file: SourceFile, serviceDir: string): ExternalEndpoint[] {\n  const ext = path.extname(file.path)\n  if (!JS_EXTS.has(ext)) return []\n  // Cheap textual pre-check before parsing — inert on files that import no driver.\n  if (!MYSQL_IMPORT_RE.test(file.content)) return []\n\n  const tree = parseSource(parserForExt(ext), file.content)\n  const root = tree.rootNode\n  const out: ExternalEndpoint[] = []\n\n  const walk = (node: Parser.SyntaxNode): void => {\n    if (node.type === 'call_expression') {\n      const fn = node.childForFieldName('function')\n      if (fn?.type === 'member_expression') {\n        const method = fn.childForFieldName('property')?.text\n        if (method && SQL_METHODS.has(method)) {\n          const argsNode = node.childForFieldName('arguments')\n          const first = argsNode ? namedChildren(argsNode)[0] : undefined\n          if (first) {\n            let head = literalHead(first)\n            if (head === null && first.type === 'identifier') {\n              const scope = enclosingFunction(node) ?? root\n              const val = nearestAssignmentValue(scope, first.text, node.startIndex)\n              if (val) head = literalHead(val)\n            }\n            if (head !== null) {\n              const table = tableFromSqlStatement(head)\n              if (table) {\n                const columns = columnsFromSqlStatement(head)\n                const line = node.startPosition.row + 1\n                out.push({\n                  infraId: infraId('sql-table', table),\n                  name: table,\n                  kind: 'sql-table',\n                  edgeType: 'CALLS',\n                  confidenceKind: 'verified-call-site',\n                  ...(columns.length > 0 ? { columns } : {}),\n                  evidence: {\n                    file: toPosix(path.relative(serviceDir, file.path)),\n                    line,\n                    snippet: snippet(file.content, line),\n                  },\n                })\n              }\n            }\n          }\n        }\n      }\n    }\n    for (const c of namedChildren(node)) walk(c)\n  }\n  walk(root)\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport Python from 'tree-sitter-python'\nimport { infraId } from '@neat.is/types'\nimport { tableFromSqlStatement, columnsFromSqlStatement } from '../../otel.js'\nimport { snippet, toPosix, type ExternalEndpoint, type SourceFile } from './shared.js'\n\n// Python raw-SQL data-axis recognizer for the DB-API drivers (#1432) — the Python\n// sibling of the Go `database/sql` reader (calls/go.ts, ADR-184) and the JS\n// `mysql`/`mysql2` reader (calls/mysql-js.ts). A service that talks to its database\n// through a plain DB-API cursor with SQL in strings gets no table grain today: the\n// Python ORM readers cover SQLAlchemy and the Django ORM, but a bare\n// `cursor.execute(sql, params)` lands nothing. This reads the table (and the touched\n// columns) off that statement and mints the same `infra:sql-table:<name>` node every\n// ORM reader and the OBSERVED ingest produce.\n//\n//   import pymysql\n//   cur.execute(\"SELECT * FROM voucher where order_id = %s\", (oid,))   // inline\n//   sql = 'INSERT INTO voucher (order_id) VALUES (%s)'; cur.execute(sql, (oid,))  // var\n//\n// THE POINT is fusion, not a static table list. The OBSERVED dbapi instrumentation\n// emits no dedicated table attribute (ADR-152), so the table is recovered from a\n// span's `db.statement` by `tableFromSqlStatement`; this recognizer runs the EXACT\n// SAME shared helper on the SAME SQL text, so the extracted table is byte-identical\n// to the observed one and the two fuse on `infraId('sql-table', <name>)` rather than\n// twinning. `columnsFromSqlStatement` does the same for the touched columns (ADR-157\n// §3). Both live in otel.ts, their one home — never a second SQL parser here.\n//\n// Statement shape (#1432 ruling a): a statement whose literal HEAD parses to\n// `SELECT … FROM <t>` / `INSERT INTO <t>` / `UPDATE <t>` / `DELETE FROM <t>` is\n// claimed with the table from the head; a runtime tail does not block it. A\n// `CREATE TABLE` has no FROM/INTO/UPDATE keyword, so `tableFromSqlStatement` returns\n// null and it is left unclaimed — never guessed.\n//\n// Variable resolution (#1432): the statement is usually built into a local variable\n// first (`sql = …; cur.execute(sql, params)`), so a `.execute`/`.executemany` whose\n// first positional argument is an identifier is resolved to its SAME-FILE,\n// ENCLOSING-FUNCTION, NEAREST-PRECEDING assignment, and only when that value is a\n// string literal or a literal-headed concatenation. An identifier reassigned in\n// between, a function parameter, or an argument with no literal head stays unclaimed.\n// Same literal inlining the URL-helper recognizer (#1426) does — precedent, not a new\n// shape.\n//\n// Import gate (mirrors calls/socket.ts' import gate): recognized only in a file that\n// imports a DB-API driver — `pymysql`, `MySQLdb`, `psycopg2`, `psycopg`, or\n// `sqlite3`. Without it a `.execute(...)` on any object could mint a phantom table\n// from any string that happens to parse as SQL. The SQL-parse gate\n// (`tableFromSqlStatement` returning a table) is the second filter.\n\n// `import pymysql` / `from pymysql import …` for the common DB-API drivers. `psycopg`\n// is psycopg3; `psycopg2` its predecessor; `MySQLdb` is mysqlclient; `sqlite3` is the\n// stdlib driver.\nconst DBAPI_IMPORT_RE =\n  /(?:^|\\n)\\s*(?:import|from)\\s+(?:pymysql|MySQLdb|psycopg2|psycopg|sqlite3)\\b/\n\n// DB-API cursor statement methods. `executescript` (sqlite-only, multi-statement) is\n// intentionally excluded — it is not a single-statement, single-table shape.\nconst EXEC_METHODS = new Set(['execute', 'executemany'])\n\nconst PARSE_CHUNK = 16384\n\nfunction makePyParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Python)\n  return p\n}\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nfunction namedChildren(node: Parser.SyntaxNode): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const c = node.namedChild(i)\n    if (c) out.push(c)\n  }\n  return out\n}\n\nfunction walk(node: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (const c of namedChildren(node)) walk(c, visit)\n}\n\n// The full literal value of a `string` node (`string_content` + any escapes), or\n// null if it carries an `interpolation` (an f-string — not a pure literal).\nfunction pyStringFull(node: Parser.SyntaxNode): string | null {\n  let v = ''\n  for (const c of namedChildren(node)) {\n    if (c.type === 'interpolation') return null\n    if (c.type === 'string_content' || c.type === 'escape_sequence') v += c.text\n  }\n  return v\n}\n\n// The leading literal text of a `string` node, up to the first `interpolation` —\n// the head of an f-string. null if it opens with an interpolation.\nfunction pyStringHead(node: Parser.SyntaxNode): string | null {\n  let head = ''\n  let saw = false\n  for (const c of namedChildren(node)) {\n    if (c.type === 'interpolation') break\n    if (c.type === 'string_content' || c.type === 'escape_sequence') {\n      head += c.text\n      saw = true\n    }\n  }\n  return saw ? head : null\n}\n\n// The value of an expression that is ENTIRELY string-literal — a `string`, an\n// adjacency `concatenated_string`, or a `+` `binary_operator` of such — else null.\nfunction pyPureLiteral(node: Parser.SyntaxNode | null): string | null {\n  if (!node) return null\n  if (node.type === 'string') return pyStringFull(node)\n  if (node.type === 'concatenated_string') {\n    let v = ''\n    for (const c of namedChildren(node)) {\n      const s = pyPureLiteral(c)\n      if (s === null) return null\n      v += s\n    }\n    return v\n  }\n  if (node.type === 'binary_operator' && node.childForFieldName('operator')?.text === '+') {\n    const l = pyPureLiteral(node.childForFieldName('left'))\n    const r = pyPureLiteral(node.childForFieldName('right'))\n    return l !== null && r !== null ? l + r : null\n  }\n  return null\n}\n\n// The leading literal portion of an expression (#1432 ruling a): the statement head\n// even when a runtime tail follows. null when there is no literal head.\nfunction pyLiteralHead(node: Parser.SyntaxNode | null): string | null {\n  if (!node) return null\n  const whole = pyPureLiteral(node)\n  if (whole !== null) return whole\n  if (node.type === 'string') return pyStringHead(node)\n  if (node.type === 'concatenated_string') {\n    let v = ''\n    let saw = false\n    for (const c of namedChildren(node)) {\n      const pure = pyPureLiteral(c)\n      if (pure !== null) {\n        v += pure\n        saw = true\n        continue\n      }\n      const h = pyLiteralHead(c)\n      if (h !== null) {\n        v += h\n        saw = true\n      }\n      break\n    }\n    return saw ? v : null\n  }\n  if (node.type === 'binary_operator' && node.childForFieldName('operator')?.text === '+') {\n    const left = node.childForFieldName('left')\n    const leftFull = pyPureLiteral(left)\n    if (leftFull !== null) {\n      const rightHead = pyLiteralHead(node.childForFieldName('right'))\n      return rightHead !== null ? leftFull + rightHead : leftFull\n    }\n    return pyLiteralHead(left)\n  }\n  return null\n}\n\nfunction enclosingFunction(node: Parser.SyntaxNode): Parser.SyntaxNode | null {\n  let cur = node.parent\n  while (cur) {\n    if (cur.type === 'function_definition') return cur\n    cur = cur.parent\n  }\n  return null\n}\n\n// The value node of the nearest preceding `name = …` assignment within `scope`, not\n// descending into nested function scopes.\nfunction nearestAssignmentValue(\n  scope: Parser.SyntaxNode,\n  name: string,\n  beforeIndex: number,\n): Parser.SyntaxNode | null {\n  let best: { pos: number; value: Parser.SyntaxNode } | null = null\n  const visit = (node: Parser.SyntaxNode): void => {\n    for (const c of namedChildren(node)) {\n      if (c.type === 'assignment') {\n        const lhs = c.childForFieldName('left')\n        const val = c.childForFieldName('right')\n        if (lhs?.type === 'identifier' && lhs.text === name && val && c.startIndex < beforeIndex) {\n          if (!best || c.startIndex > best.pos) best = { pos: c.startIndex, value: val }\n        }\n      }\n      if (c.type !== 'function_definition' && c.type !== 'lambda') visit(c)\n    }\n  }\n  visit(scope)\n  return best ? best.value : null\n}\n\nexport function pythonDbapiEndpointsFromFile(\n  file: SourceFile,\n  serviceDir: string,\n): ExternalEndpoint[] {\n  if (path.extname(file.path) !== '.py') return []\n  if (!DBAPI_IMPORT_RE.test(file.content)) return []\n\n  const tree = parseSource(makePyParser(), file.content)\n  const root = tree.rootNode\n  const out: ExternalEndpoint[] = []\n\n  walk(root, (node) => {\n    if (node.type !== 'call') return\n    const fn = node.childForFieldName('function')\n    if (fn?.type !== 'attribute') return\n    const method = fn.childForFieldName('attribute')?.text\n    if (!method || !EXEC_METHODS.has(method)) return\n\n    const argsNode = node.childForFieldName('arguments')\n    const first = argsNode\n      ? namedChildren(argsNode).find((a) => a.type !== 'keyword_argument')\n      : undefined\n    if (!first) return\n\n    let head = pyLiteralHead(first)\n    if (head === null && first.type === 'identifier') {\n      const scope = enclosingFunction(node) ?? root\n      const val = nearestAssignmentValue(scope, first.text, node.startIndex)\n      if (val) head = pyLiteralHead(val)\n    }\n    if (head === null) return\n\n    const table = tableFromSqlStatement(head)\n    if (!table) return\n    const columns = columnsFromSqlStatement(head)\n    const line = node.startPosition.row + 1\n    out.push({\n      infraId: infraId('sql-table', table),\n      name: table,\n      kind: 'sql-table',\n      edgeType: 'CALLS',\n      confidenceKind: 'verified-call-site',\n      ...(columns.length > 0 ? { columns } : {}),\n      evidence: {\n        file: toPosix(path.relative(serviceDir, file.path)),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  })\n\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport Java from 'tree-sitter-java'\nimport { infraId } from '@neat.is/types'\nimport { snippet, toPosix, type ExternalEndpoint, type SourceFile } from './shared.js'\n\n// JPA / Spring Data data axis — the Java rung of the `infra:sql-table:<name>` grain\n// the EF Core, GORM, SQLAlchemy, ActiveRecord and Eloquent readers produce.\n//\n//   @Entity\n//   @Table(name = \"orders\")                  // the table, verbatim\n//   public class Order { ... }\n//\n//   public interface OrderRepository extends CrudRepository<Order, String> { }\n//\n// The entity's `@Table(name = \"…\")` names the database table verbatim — the\n// string an OBSERVED db span reports — so the node fuses by name. The entity\n// file gets `file ──CALLS──▶ sql-table`, and so does every Spring Data\n// repository over that entity (`CrudRepository<Order, …>`, `JpaRepository`,\n// `PagingAndSortingRepository`, the `List*` variants), resolved across the\n// service's files by the entity's simple class name. That is the file the\n// queries actually run from.\n//\n// An entity with no `@Table(name)` is left unclaimed. Its table name then comes\n// from the configured physical naming strategy, which lives outside the entity,\n// so reading the class name would be a guess. A name that isn't a plain literal,\n// an entity class name declared twice in one service, and a repository over an\n// unclaimed entity are all left unclaimed the same way.\n//\n// Table grain only: column names go through the same naming strategy.\n\nconst PARSE_CHUNK = 16384\nconst JPA_GATE = /\\b(?:javax|jakarta)\\.persistence\\b|@Entity\\b|Repository\\s*</\nconst REPOSITORY_BASES = new Set([\n  'CrudRepository',\n  'ListCrudRepository',\n  'JpaRepository',\n  'PagingAndSortingRepository',\n  'ListPagingAndSortingRepository',\n  'Repository',\n])\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nfunction walk(node: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (const c of node.namedChildren) walk(c, visit)\n}\n\nfunction annotations(decl: Parser.SyntaxNode): Parser.SyntaxNode[] {\n  const mods = decl.namedChildren.find((c) => c.type === 'modifiers')\n  return mods ? mods.namedChildren.filter((c) => c.type === 'annotation' || c.type === 'marker_annotation') : []\n}\n\nfunction simpleName(annotation: Parser.SyntaxNode): string {\n  const text = annotation.childForFieldName('name')?.text ?? ''\n  return text.slice(text.lastIndexOf('.') + 1)\n}\n\nfunction stringLiteral(node: Parser.SyntaxNode | null | undefined): string | null {\n  if (!node || node.type !== 'string_literal') return null\n  let out = ''\n  for (const c of node.namedChildren) {\n    if (c.type === 'string_fragment') out += c.text\n    else return null\n  }\n  return out\n}\n\n// `@Table(name = \"orders\")` → orders. A `@Table` without a literal `name` (only\n// `schema`, or a constant) → null.\nfunction tableName(annotation: Parser.SyntaxNode): string | null {\n  const args = annotation.childForFieldName('arguments')\n  if (!args) return null\n  for (const c of args.namedChildren) {\n    if (c.type === 'element_value_pair' && c.childForFieldName('key')?.text === 'name') {\n      return stringLiteral(c.childForFieldName('value'))\n    }\n  }\n  return null\n}\n\ninterface Entity {\n  table: string | null\n  file: SourceFile\n  line: number\n}\n\n// The entity type a Spring Data repository interface manages: the first type\n// argument of a known repository base in its `extends` list.\nfunction repositoryEntity(iface: Parser.SyntaxNode): string | null {\n  const ext = iface.namedChildren.find((c) => c.type === 'extends_interfaces')\n  if (!ext) return null\n  let found: string | null = null\n  walk(ext, (n) => {\n    if (found || n.type !== 'generic_type') return\n    const base = n.namedChildren.find((c) => c.type === 'type_identifier' || c.type === 'scoped_type_identifier')\n    const baseName = base?.text.slice(base.text.lastIndexOf('.') + 1) ?? ''\n    if (!REPOSITORY_BASES.has(baseName)) return\n    const first = n.namedChildren.find((c) => c.type === 'type_arguments')?.namedChildren[0]\n    if (first && (first.type === 'type_identifier' || first.type === 'scoped_type_identifier')) {\n      found = first.text.slice(first.text.lastIndexOf('.') + 1)\n    }\n  })\n  return found\n}\n\nfunction endpoint(table: string, file: SourceFile, serviceDir: string, line: number): ExternalEndpoint {\n  return {\n    infraId: infraId('sql-table', table),\n    name: table,\n    kind: 'sql-table',\n    edgeType: 'CALLS',\n    confidenceKind: 'structural',\n    evidence: {\n      file: toPosix(path.relative(serviceDir, file.path)),\n      line,\n      snippet: snippet(file.content, line),\n    },\n  }\n}\n\n/** JPA entities and Spring Data repositories across one service's files. */\nexport function jpaEndpoints(files: SourceFile[], serviceDir: string): ExternalEndpoint[] {\n  const javaFiles = files.filter((f) => path.extname(f.path) === '.java' && JPA_GATE.test(f.content))\n  if (javaFiles.length === 0) return []\n  const parser = new Parser()\n  parser.setLanguage(Java)\n\n  const entities = new Map<string, Entity | null>() // null: declared twice\n  const repositories: { entity: string; file: SourceFile; line: number }[] = []\n\n  for (const file of javaFiles) {\n    const root = parseSource(parser, file.content).rootNode\n    walk(root, (n) => {\n      if (n.type === 'class_declaration') {\n        const anns = annotations(n)\n        if (!anns.some((a) => simpleName(a) === 'Entity')) return\n        const name = n.childForFieldName('name')?.text\n        if (!name) return\n        const tableAnn = anns.find((a) => simpleName(a) === 'Table')\n        const entity: Entity = {\n          table: tableAnn ? tableName(tableAnn) : null,\n          file,\n          line: (tableAnn ?? n).startPosition.row + 1,\n        }\n        entities.set(name, entities.has(name) ? null : entity)\n      } else if (n.type === 'interface_declaration') {\n        const entity = repositoryEntity(n)\n        if (entity) repositories.push({ entity, file, line: n.startPosition.row + 1 })\n      }\n    })\n  }\n\n  const out: ExternalEndpoint[] = []\n  for (const entity of entities.values()) {\n    if (entity?.table) out.push(endpoint(entity.table, entity.file, serviceDir, entity.line))\n  }\n  for (const repo of repositories) {\n    const table = entities.get(repo.entity)?.table\n    if (table) out.push(endpoint(table, repo.file, serviceDir, repo.line))\n  }\n  return out\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport Java from 'tree-sitter-java'\nimport type { ExtractedConfidenceKind, GraphEdge, RouteNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  passesExtractedFloor,\n  serviceId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport { isTestPath, makeEdgeId, type DiscoveredService } from './shared.js'\nimport { recordExtractionError, noteExtractedDropped } from './errors.js'\nimport { buildServiceHostIndex, ensureFileNode, loadSourceFiles, snippet, toPosix } from './calls/shared.js'\nimport { normalizePathTemplate } from './routes.js'\n\n// Outbound HTTP from Java services: Spring's RestTemplate and WebClient.\n//\n// A call's URL is rarely one literal. train-ticket, for one, writes\n//   String url = getServiceUrl(\"ts-basic-service\");     // returns \"http://\" + name\n//   restTemplate.exchange(url + \"/api/v1/basicservice/basic/travel\", HttpMethod.POST, …)\n// so the URL is resolved by evaluating the argument as a string expression:\n// literals, `+`, same-file `static final String` constants, the enclosing\n// method's local variables, and calls to a same-file helper whose body is a\n// single `return` of the same kinds of pieces (inlined with its literal\n// arguments). Any other piece — a runtime value, a getter, an injected `@Value`\n// — becomes a `:param` path segment, or, in the host, leaves the host unknown.\n//\n// What it emits, the same shapes the JS/TS producers do:\n//   - file ──CALLS──▶ service, when the host names a service in the graph\n//     (http.ts's shape, graded verified-call-site: a client call wraps the URL);\n//   - file ──CALLS──▶ route, when the path also matches one of that service's\n//     RouteNodes (route-match.ts's shape and grading, ADR-119 / ADR-219).\n// A call whose host can't be resolved stays unclaimed: the file still surfaces,\n// and the call is recorded as a drop with its reason, never guessed.\n\nconst PARSE_CHUNK = 16384\n// Stands for a piece of the URL that isn't known statically.\nconst HOLE = '\\u0000'\n\nconst REST_TEMPLATE_METHODS: Record<string, string | null> = {\n  getForObject: 'GET',\n  getForEntity: 'GET',\n  postForObject: 'POST',\n  postForEntity: 'POST',\n  postForLocation: 'POST',\n  put: 'PUT',\n  delete: 'DELETE',\n  patchForObject: 'PATCH',\n  // The HTTP method is the second argument.\n  exchange: null,\n  execute: null,\n}\nconst HTTP_METHODS = new Set(['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'])\nconst WEBCLIENT_VERBS: Record<string, string> = {\n  get: 'GET',\n  post: 'POST',\n  put: 'PUT',\n  delete: 'DELETE',\n  patch: 'PATCH',\n  head: 'HEAD',\n  options: 'OPTIONS',\n}\n\nexport interface JavaCallSite {\n  method?: string\n  // The resolved host, or null when it couldn't be read statically.\n  host: string | null\n  // The path with `:param` for each unknown piece; '/' when the URL has none.\n  pathTemplate: string\n  approximate: boolean\n  line: number\n  reason?: string\n}\n\nfunction parseSource(parser: Parser, source: string): Parser.Tree {\n  return parser.parse((index: number) =>\n    index >= source.length ? '' : source.slice(index, index + PARSE_CHUNK),\n  )\n}\n\nfunction makeJavaParser(): Parser {\n  const p = new Parser()\n  p.setLanguage(Java)\n  return p\n}\n\nfunction walk(node: Parser.SyntaxNode, visit: (n: Parser.SyntaxNode) => void): void {\n  visit(node)\n  for (const c of node.namedChildren) walk(c, visit)\n}\n\nfunction stringLiteral(node: Parser.SyntaxNode): string | null {\n  let out = ''\n  for (const c of node.namedChildren) {\n    if (c.type === 'string_fragment') out += c.text\n    else return null\n  }\n  return out\n}\n\ninterface Helper {\n  params: string[]\n  body: Parser.SyntaxNode\n}\n\ninterface FileScope {\n  constants: Map<string, Parser.SyntaxNode>\n  helpers: Map<string, Helper>\n}\n\n// Same-file `static final` fields and single-return helper methods.\nfunction fileScope(root: Parser.SyntaxNode): FileScope {\n  const constants = new Map<string, Parser.SyntaxNode>()\n  const helpers = new Map<string, Helper>()\n  const dupHelpers = new Set<string>()\n  walk(root, (n) => {\n    if (n.type === 'field_declaration') {\n      const mods = n.namedChildren.find((c) => c.type === 'modifiers')?.text ?? ''\n      if (!/\\bstatic\\b/.test(mods) || !/\\bfinal\\b/.test(mods)) return\n      for (const d of n.namedChildren) {\n        if (d.type !== 'variable_declarator') continue\n        const name = d.childForFieldName('name')?.text\n        const value = d.childForFieldName('value')\n        if (name && value) constants.set(name, value)\n      }\n    } else if (n.type === 'method_declaration') {\n      const name = n.childForFieldName('name')?.text\n      const body = n.childForFieldName('body')\n      const params = n.childForFieldName('parameters')\n      if (!name || !body || !params) return\n      const stmts = body.namedChildren.filter((c) => c.type !== 'line_comment' && c.type !== 'block_comment')\n      const ret = stmts.length === 1 && stmts[0]!.type === 'return_statement' ? stmts[0]!.namedChildren[0] : undefined\n      if (!ret) return\n      if (helpers.has(name)) dupHelpers.add(name) // overloads: ambiguous\n      helpers.set(name, {\n        params: params.namedChildren\n          .filter((p) => p.type === 'formal_parameter')\n          .map((p) => p.childForFieldName('name')?.text ?? ''),\n        body: ret,\n      })\n    }\n  })\n  for (const name of dupHelpers) helpers.delete(name)\n  return { constants, helpers }\n}\n\n// The enclosing method's locals: name → initializer, or null when assigned more\n// than once (which value reaches the call isn't known statically).\nfunction methodLocals(call: Parser.SyntaxNode): Map<string, Parser.SyntaxNode | null> {\n  const out = new Map<string, Parser.SyntaxNode | null>()\n  let m: Parser.SyntaxNode | null = call.parent\n  while (m && m.type !== 'method_declaration' && m.type !== 'constructor_declaration' && m.type !== 'lambda_expression') {\n    m = m.parent\n  }\n  const body = m?.childForFieldName('body')\n  if (!body) return out\n  walk(body, (n) => {\n    if (n.type === 'local_variable_declaration') {\n      for (const d of n.namedChildren) {\n        if (d.type !== 'variable_declarator') continue\n        const name = d.childForFieldName('name')?.text\n        if (!name) continue\n        out.set(name, out.has(name) ? null : d.childForFieldName('value'))\n      }\n    } else if (n.type === 'assignment_expression') {\n      const left = n.childForFieldName('left')\n      if (left?.type === 'identifier') out.set(left.text, null)\n    }\n  })\n  return out\n}\n\ninterface EvalCtx {\n  scope: FileScope\n  locals: Map<string, Parser.SyntaxNode | null>\n  // Bound helper parameters while inlining.\n  bound: Map<string, string>\n  depth: number\n}\n\n// A string expression as text, with HOLE for each piece that isn't static.\nfunction evalString(node: Parser.SyntaxNode, ctx: EvalCtx): string {\n  if (ctx.depth > 8) return HOLE\n  const next = (n: Parser.SyntaxNode, extra?: Partial<EvalCtx>): string =>\n    evalString(n, { ...ctx, ...extra, depth: ctx.depth + 1 })\n  switch (node.type) {\n    case 'string_literal':\n      return stringLiteral(node) ?? HOLE\n    case 'parenthesized_expression':\n      return node.namedChildren[0] ? next(node.namedChildren[0]) : HOLE\n    case 'binary_expression': {\n      if (node.childForFieldName('operator')?.text !== '+') return HOLE\n      const l = node.childForFieldName('left')\n      const r = node.childForFieldName('right')\n      return (l ? next(l) : HOLE) + (r ? next(r) : HOLE)\n    }\n    case 'identifier': {\n      const name = node.text\n      if (ctx.bound.has(name)) return ctx.bound.get(name)!\n      if (ctx.locals.has(name)) {\n        const init = ctx.locals.get(name)\n        return init ? next(init) : HOLE\n      }\n      const c = ctx.scope.constants.get(name)\n      return c ? next(c, { locals: new Map(), bound: new Map() }) : HOLE\n    }\n    case 'method_invocation': {\n      const obj = node.childForFieldName('object')\n      if (obj && obj.type !== 'this') return HOLE\n      const helper = ctx.scope.helpers.get(node.childForFieldName('name')?.text ?? '')\n      const args = node.childForFieldName('arguments')?.namedChildren ?? []\n      if (!helper || helper.params.length !== args.length) return HOLE\n      const bound = new Map<string, string>()\n      helper.params.forEach((p, i) => bound.set(p, next(args[i]!)))\n      return next(helper.body, { locals: new Map(), bound })\n    }\n    default:\n      return HOLE\n  }\n}\n\n// Split an evaluated URL into host and path. A host is only taken from an\n// `http(s)://` URL whose host part is fully static.\nfunction splitUrl(url: string): { host: string | null; pathTemplate: string; approximate: boolean; reason?: string } {\n  const approximate = url.includes(HOLE)\n  const m = /^https?:\\/\\/([^/]*)(.*)$/.exec(url)\n  if (!m) {\n    return { host: null, pathTemplate: '/', approximate: true, reason: 'the URL has no static scheme and host' }\n  }\n  const hostPort = m[1]!\n  if (!hostPort || hostPort.includes(HOLE)) {\n    return { host: null, pathTemplate: '/', approximate: true, reason: 'the host is not static' }\n  }\n  const host = hostPort.replace(/:\\d+$/, '')\n  let p = (m[2] ?? '').split('?')[0]!.split('#')[0]!\n  // A hole mid-segment (`/order/` + id) or as a whole segment is one param.\n  p = p\n    .split('/')\n    .map((seg) => (seg.includes(HOLE) ? ':param' : seg))\n    .join('/')\n  if (!p.startsWith('/')) p = '/' + p\n  return { host, pathTemplate: p, approximate }\n}\n\nfunction httpMethodArg(node: Parser.SyntaxNode | undefined): string | undefined {\n  if (!node) return undefined\n  const name = node.type === 'field_access' ? node.childForFieldName('field')?.text : node.text\n  return name && HTTP_METHODS.has(name) ? name : undefined\n}\n\n// For `….get().uri(x)` / `….method(HttpMethod.X).uri(x)`: the verb in the chain.\nfunction webClientMethod(uriCall: Parser.SyntaxNode): string | null {\n  let cur: Parser.SyntaxNode | null = uriCall.childForFieldName('object')\n  while (cur && cur.type === 'method_invocation') {\n    const name = cur.childForFieldName('name')?.text ?? ''\n    const args = cur.childForFieldName('arguments')?.namedChildren ?? []\n    if (WEBCLIENT_VERBS[name] && args.length === 0) return WEBCLIENT_VERBS[name]!\n    if (name === 'method') return httpMethodArg(args[0]) ?? null\n    cur = cur.childForFieldName('object')\n  }\n  return null\n}\n\n// Names declared with type RestTemplate (fields, locals, parameters), so a\n// `put` / `delete` on a map or a repository is never read as an HTTP call.\nfunction restTemplateNames(root: Parser.SyntaxNode): Set<string> {\n  const out = new Set<string>()\n  walk(root, (n) => {\n    if (n.type !== 'field_declaration' && n.type !== 'local_variable_declaration' && n.type !== 'formal_parameter') return\n    const type = n.childForFieldName('type')?.text ?? ''\n    if (!/(^|\\.)RestTemplate$/.test(type)) return\n    if (n.type === 'formal_parameter') {\n      const name = n.childForFieldName('name')?.text\n      if (name) out.add(name)\n      return\n    }\n    for (const d of n.namedChildren) {\n      if (d.type === 'variable_declarator') {\n        const name = d.childForFieldName('name')?.text\n        if (name) out.add(name)\n      }\n    }\n  })\n  return out\n}\n\nfunction isRestTemplateReceiver(obj: Parser.SyntaxNode | null, names: Set<string>): boolean {\n  if (!obj) return false\n  if (obj.type === 'identifier') return names.has(obj.text)\n  if (obj.type === 'field_access' && obj.childForFieldName('object')?.type === 'this') {\n    return names.has(obj.childForFieldName('field')?.text ?? '')\n  }\n  return false\n}\n\n/** RestTemplate / WebClient call sites in one Java source file. */\nexport function javaCallSitesFromSource(source: string, parser: Parser): JavaCallSite[] {\n  const usesRestTemplate = source.includes('RestTemplate')\n  const usesWebClient = source.includes('WebClient')\n  if (!usesRestTemplate && !usesWebClient) return []\n  const root = parseSource(parser, source).rootNode\n  const scope = fileScope(root)\n  const templates = usesRestTemplate ? restTemplateNames(root) : new Set<string>()\n  const out: JavaCallSite[] = []\n\n  walk(root, (n) => {\n    if (n.type !== 'method_invocation') return\n    const name = n.childForFieldName('name')?.text ?? ''\n    const args = n.childForFieldName('arguments')?.namedChildren ?? []\n    let method: string | undefined\n    if (name in REST_TEMPLATE_METHODS && isRestTemplateReceiver(n.childForFieldName('object'), templates)) {\n      method = REST_TEMPLATE_METHODS[name] ?? httpMethodArg(args[1])\n      if (!method) return\n    } else if (usesWebClient && name === 'uri') {\n      const verb = webClientMethod(n)\n      if (!verb) return\n      method = verb\n    } else {\n      return\n    }\n    const urlNode = args[0]\n    if (!urlNode) return\n    const url = evalString(urlNode, { scope, locals: methodLocals(n), bound: new Map(), depth: 0 })\n    out.push({ method, ...splitUrl(url), line: n.startPosition.row + 1 })\n  })\n  return out\n}\n\ninterface RouteEntry {\n  method: string\n  normalizedPath: string\n  routeNodeId: string\n}\n\nfunction buildRouteIndex(graph: NeatGraph): Map<string, RouteEntry[]> {\n  const index = new Map<string, RouteEntry[]>()\n  graph.forEachNode((_id, attrs) => {\n    if ((attrs as { type?: string }).type !== NodeType.RouteNode) return\n    const route = attrs as unknown as RouteNode\n    const owner = serviceId(route.service)\n    const list = index.get(owner) ?? []\n    list.push({\n      method: route.method.toUpperCase(),\n      normalizedPath: normalizePathTemplate(route.pathTemplate),\n      routeNodeId: route.id,\n    })\n    index.set(owner, list)\n  })\n  return index\n}\n\n// A path with at least one literal segment says which route it names.\nfunction hasLiteralAnchor(pathTemplate: string): boolean {\n  return pathTemplate.split('/').some((s) => s.length > 0 && s !== ':param')\n}\n\n/** File → service (and file → route) CALLS for Java RestTemplate / WebClient calls. */\nexport async function addJavaCallEdges(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  const javaServices = services.filter((s) => s.node.language === 'java')\n  if (javaServices.length === 0) return { nodesAdded: 0, edgesAdded: 0 }\n  const parser = makeJavaParser()\n  const { hostToNodeId } = buildServiceHostIndex(services)\n  const routeIndex = buildRouteIndex(graph)\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  const addEdge = (source: string, target: string, kind: ExtractedConfidenceKind, ev: GraphEdge['evidence']): void => {\n    const confidence = confidenceForExtracted(kind)\n    if (!passesExtractedFloor(confidence)) {\n      noteExtractedDropped({ source, target, type: EdgeType.CALLS, confidence, confidenceKind: kind, evidence: ev! })\n      return\n    }\n    const id = makeEdgeId(source, target, EdgeType.CALLS)\n    if (graph.hasEdge(id)) return\n    const edge: GraphEdge = {\n      id,\n      source,\n      target,\n      type: EdgeType.CALLS,\n      provenance: Provenance.EXTRACTED,\n      confidence,\n      evidence: ev,\n    }\n    graph.addEdgeWithKey(id, source, target, edge)\n    edgesAdded++\n  }\n\n  for (const service of javaServices) {\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n    const seen = new Set<string>()\n    for (const file of files) {\n      if (path.extname(file.path) !== '.java' || isTestPath(file.path)) continue\n      let sites: JavaCallSite[]\n      try {\n        sites = javaCallSitesFromSource(file.content, parser)\n      } catch (err) {\n        recordExtractionError('java http call extraction', file.path, err)\n        continue\n      }\n      if (sites.length === 0) continue\n      const relFile = toPosix(path.relative(service.dir, file.path))\n\n      for (const site of sites) {\n        const targetService = site.host === null ? undefined : hostToNodeId.get(site.host)\n        // A literal host outside the graph (a third party, or a service not in\n        // this scan) is skipped, as http.ts skips it.\n        if (site.host !== null && !targetService) continue\n        if (targetService === service.node.id) continue\n\n        const { fileNodeId, nodesAdded: n, edgesAdded: e } = ensureFileNode(\n          graph,\n          service.pkg.name,\n          service.node.id,\n          relFile,\n        )\n        nodesAdded += n\n        edgesAdded += e\n        const ev = {\n          file: relFile,\n          line: site.line,\n          snippet: snippet(file.content, site.line),\n          method: site.method,\n          pathTemplate: site.pathTemplate,\n        }\n\n        if (!targetService) {\n          const key = `${relFile}|unresolved|${site.line}`\n          if (seen.has(key)) continue\n          seen.add(key)\n          noteExtractedDropped({\n            source: fileNodeId,\n            target: 'route:unresolved',\n            type: EdgeType.CALLS,\n            confidence: confidenceForExtracted('reconstructed-approximate'),\n            confidenceKind: 'reconstructed-approximate',\n            evidence: { ...ev, approximate: true, reason: site.reason },\n          })\n          continue\n        }\n\n        if (!seen.has(`${relFile}|${targetService}`)) {\n          seen.add(`${relFile}|${targetService}`)\n          addEdge(fileNodeId, targetService, 'verified-call-site', ev)\n        }\n\n        const route = routeIndex\n          .get(targetService)\n          ?.find(\n            (r) =>\n              r.normalizedPath === normalizePathTemplate(site.pathTemplate) &&\n              (r.method === 'ALL' || site.method === undefined || r.method === site.method),\n          )\n        if (!route || seen.has(`${relFile}|${route.routeNodeId}`)) continue\n        seen.add(`${relFile}|${route.routeNodeId}`)\n        const anchored = hasLiteralAnchor(site.pathTemplate)\n        addEdge(\n          fileNodeId,\n          route.routeNodeId,\n          site.approximate && !anchored ? 'reconstructed-approximate' : 'verified-call-site',\n          site.approximate && !anchored ? { ...ev, approximate: true, reason: 'no literal path segment' } : ev,\n        )\n      }\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import type { GraphEdge, InfraNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  infraId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport type { DiscoveredService } from './shared.js'\nimport { recordExtractionError } from './errors.js'\nimport { loadSourceFiles, type TableReference } from './calls/shared.js'\nimport { drizzleForeignKeys } from './calls/drizzle.js'\nimport { prismaForeignKeys } from './calls/prisma.js'\nimport { sqlalchemyForeignKeys } from './calls/sqlalchemy.js'\nimport { railsSchemaForeignKeys, railsModelForeignKeys } from './calls/activerecord.js'\nimport { laravelMigrationForeignKeys, laravelModelForeignKeys } from './calls/eloquent.js'\nimport { gormForeignKeys } from './calls/gorm.js'\n\n// Foreign-key table→table edges (ADR-161). The data-axis sibling of the symbol\n// heritage producer (`symbol-edges.ts`, ADR-158 §3): column grain (ADR-157) gave\n// a `infra:sql-table:<name>` node its columns but no edges *between* tables, so\n// blast-radius / dependencies / root-cause could not walk the data axis. This\n// mints one `infra:sql-table:<child> ──REFERENCES──▶ infra:sql-table:<parent>`\n// EXTRACTED edge per resolved foreign key.\n//\n// The per-ORM readers live beside the columns each already parses — Drizzle's\n// `.references(() => users.id)`, Prisma's `@relation(fields:[…], references:[…])`,\n// SQLAlchemy's `ForeignKey('users.id')`. Each resolves the parent to the DATABASE\n// table name (`infraId('sql-table', name)` — the same node the column/table\n// extractors and OTLP already target), reproduced verbatim the ORM's way, so the\n// FK lands on the fused table node rather than a code-model twin. A computed or\n// cross-file-unresolvable reference is left unclaimed by the reader (it returns\n// nothing) — never guessed, the never-fabricate discipline of file-awareness.md\n// §6. Every edge grades `structural` EXTRACTED with `evidence.file`/`line` pinned\n// to the FK declaration site, so ghost-edge cleanup (`retire.ts`) keys off it like\n// any other EXTRACTED edge, and every write is `hasNode` / `hasEdge`-guarded.\n//\n// Runs after `addCallEdges`, whose column/table read has already minted both\n// endpoints' InfraNodes; `ensureTableNode` is a self-contained safety net that\n// mints a bare table node (same id, no twin) when a referenced table was named in\n// a FK but not otherwise picked up. The reasoning core stays agnostic: REFERENCES\n// is a plain edge type the generic graph walk admits with no traversal change\n// (ADR-158 §6).\n\nexport async function addTableEdges(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n    const refs: TableReference[] = []\n    // Rails model associations (ADR-174) and Laravel Eloquent relations\n    // (ADR-178) corroborate the schema literals — a relationship is often\n    // declared on both sides. They are collected here and appended AFTER the\n    // schema/ORM literals, so when the same child→parent pair appears twice the\n    // literal (schema.rb / migration) evidence wins the graph-level dedup.\n    const modelRefs: TableReference[] = []\n\n    for (const file of files) {\n      try {\n        refs.push(...drizzleForeignKeys(file, service.dir))\n        refs.push(...sqlalchemyForeignKeys(file, service.dir))\n        refs.push(...railsSchemaForeignKeys(file, service.dir))\n        refs.push(...laravelMigrationForeignKeys(file, service.dir))\n        refs.push(...gormForeignKeys(file, service.dir))\n        modelRefs.push(...railsModelForeignKeys(file, service.dir))\n        modelRefs.push(...laravelModelForeignKeys(file, service.dir))\n      } catch (err) {\n        recordExtractionError('foreign-key extraction', file.path, err)\n      }\n    }\n    // Prisma's `schema.prisma` is not a walked source file — read once per service.\n    try {\n      refs.push(...(await prismaForeignKeys(service.dir)))\n    } catch (err) {\n      recordExtractionError('prisma foreign-key extraction', service.dir, err)\n    }\n    refs.push(...modelRefs)\n\n    for (const ref of refs) {\n      const childId = infraId('sql-table', ref.childTable)\n      const parentId = infraId('sql-table', ref.parentTable)\n      // A self-referential FK (a tree's `parent_id`) would be a self-loop; the\n      // graph disallows them, and a table referencing itself carries no cross-table\n      // blast radius, so it is skipped rather than emitted.\n      if (childId === parentId) continue\n\n      nodesAdded += ensureTableNode(graph, childId, ref.childTable)\n      nodesAdded += ensureTableNode(graph, parentId, ref.parentTable)\n\n      const edgeId = extractedEdgeId(childId, parentId, EdgeType.REFERENCES)\n      if (graph.hasEdge(edgeId)) continue\n      const edge: GraphEdge = {\n        id: edgeId,\n        source: childId,\n        target: parentId,\n        type: EdgeType.REFERENCES,\n        provenance: Provenance.EXTRACTED,\n        confidence: confidenceForExtracted('structural'),\n        evidence: ref.evidence,\n      }\n      graph.addEdgeWithKey(edgeId, childId, parentId, edge)\n      edgesAdded++\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n\n// Mint a bare `sql-table` InfraNode if the FK named a table nothing else did.\n// Idempotent — same `infra:sql-table:<name>` id the column/table extractors and\n// OTLP use, so it fuses onto the existing node and never twins. Returns 1 when a\n// node was minted, 0 when it already existed.\nfunction ensureTableNode(graph: NeatGraph, id: string, name: string): number {\n  if (graph.hasNode(id)) return 0\n  const node: InfraNode = {\n    id,\n    type: NodeType.InfraNode,\n    name,\n    provider: 'self',\n    kind: 'sql-table',\n  }\n  graph.addNode(id, node)\n  return 1\n}\n","import type { NeatGraph } from '../../graph.js'\nimport { type DiscoveredService } from '../shared.js'\nimport { addComposeInfra } from './docker-compose.js'\nimport { addDockerfileRuntimes } from './dockerfile.js'\nimport { addTerraformResources } from './terraform.js'\nimport { addK8sResources } from './k8s.js'\nimport { addCloudflareWorkers } from './cloudflare.js'\nimport { addVercelServices } from './vercel.js'\nimport { addRailwayServices } from './railway.js'\nimport { addSupabaseProjects } from './supabase.js'\nimport { addNginxProxies } from './nginx.js'\n\nexport interface InfraExtractResult {\n  nodesAdded: number\n  edgesAdded: number\n}\n\n// Phase 5 — infrastructure. Runs after services so RUNS_ON edges have a\n// ServiceNode to anchor on. Each sub-source contributes its own nodes/edges\n// independently. The platform producers (`cloudflare.ts`, `vercel.ts`,\n// `railway.ts`, `supabase.ts`) also tag existing ServiceNode/FileNode\n// attributes (`platform`/`platformName`, ADR-133) rather than only adding new\n// nodes/edges — property updates on existing nodes are allowed per ADR-030.\nexport async function addInfra(\n  graph: NeatGraph,\n  scanPath: string,\n  services: DiscoveredService[],\n): Promise<InfraExtractResult> {\n  const compose = await addComposeInfra(graph, scanPath, services)\n  const dockerfile = await addDockerfileRuntimes(graph, services, scanPath)\n  const terraform = await addTerraformResources(graph, scanPath)\n  const k8s = await addK8sResources(graph, scanPath)\n  const cloudflare = await addCloudflareWorkers(graph, services, scanPath)\n  const vercel = await addVercelServices(graph, services, scanPath)\n  const railway = await addRailwayServices(graph, services, scanPath)\n  const supabase = await addSupabaseProjects(graph, services, scanPath)\n  const nginx = await addNginxProxies(graph, services)\n\n  return {\n    nodesAdded:\n      compose.nodesAdded +\n      dockerfile.nodesAdded +\n      terraform.nodesAdded +\n      k8s.nodesAdded +\n      cloudflare.nodesAdded +\n      vercel.nodesAdded +\n      railway.nodesAdded +\n      supabase.nodesAdded +\n      nginx.nodesAdded,\n    edgesAdded:\n      compose.edgesAdded +\n      dockerfile.edgesAdded +\n      terraform.edgesAdded +\n      k8s.edgesAdded +\n      cloudflare.edgesAdded +\n      vercel.edgesAdded +\n      railway.edgesAdded +\n      supabase.edgesAdded +\n      nginx.edgesAdded,\n  }\n}\n","import path from 'node:path'\nimport type { GraphEdge } from '@neat.is/types'\nimport { EdgeType, Provenance, confidenceForExtracted } from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { exists, makeEdgeId, readYaml, type DiscoveredService } from '../shared.js'\nimport { recordExtractionError } from '../errors.js'\nimport { classifyImage, makeInfraNode } from './shared.js'\n\ninterface ComposeService {\n  image?: string\n  build?: string | { context?: string }\n  depends_on?: string[] | Record<string, unknown>\n}\n\ninterface ComposeFile {\n  services?: Record<string, ComposeService>\n}\n\nfunction dependsOnList(value: ComposeService['depends_on']): string[] {\n  if (!value) return []\n  if (Array.isArray(value)) return value\n  return Object.keys(value)\n}\n\nfunction serviceNameToServiceNode(\n  name: string,\n  services: DiscoveredService[],\n): string | null {\n  for (const s of services) {\n    if (s.node.name === name || path.basename(s.dir) === name) return s.node.id\n  }\n  return null\n}\n\n// Project-level docker-compose.yml describes deployment topology. Each compose\n// service that is *not* one of the discovered ServiceNodes becomes an\n// InfraNode (databases, brokers, caches). depends_on lists become DEPENDS_ON\n// edges from the dependent to its dependency, regardless of whether the\n// endpoint is a ServiceNode or InfraNode — the edge itself is the deployment\n// fact, not the role.\nexport async function addComposeInfra(\n  graph: NeatGraph,\n  scanPath: string,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  let composePath: string | null = null\n  for (const name of ['docker-compose.yml', 'docker-compose.yaml']) {\n    const abs = path.join(scanPath, name)\n    if (await exists(abs)) {\n      composePath = abs\n      break\n    }\n  }\n  if (!composePath) return { nodesAdded, edgesAdded }\n\n  let compose: ComposeFile\n  try {\n    compose = await readYaml<ComposeFile>(composePath)\n  } catch (err) {\n    recordExtractionError(\n      'infra docker-compose',\n      path.relative(scanPath, composePath),\n      err,\n    )\n    return { nodesAdded, edgesAdded }\n  }\n  if (!compose?.services) return { nodesAdded, edgesAdded }\n  const evidenceFile = path.relative(scanPath, composePath).split(path.sep).join('/')\n\n  const composeNameToNodeId = new Map<string, string>()\n  for (const [composeName, svc] of Object.entries(compose.services)) {\n    const matchedServiceId = serviceNameToServiceNode(composeName, services)\n    if (matchedServiceId) {\n      composeNameToNodeId.set(composeName, matchedServiceId)\n      continue\n    }\n    const kind = svc.image ? classifyImage(svc.image) : 'container'\n    const node = makeInfraNode(kind, composeName)\n    if (!graph.hasNode(node.id)) {\n      graph.addNode(node.id, node)\n      nodesAdded++\n    }\n    composeNameToNodeId.set(composeName, node.id)\n  }\n\n  for (const [composeName, svc] of Object.entries(compose.services)) {\n    const sourceId = composeNameToNodeId.get(composeName)\n    if (!sourceId) continue\n    for (const dep of dependsOnList(svc.depends_on)) {\n      const targetId = composeNameToNodeId.get(dep)\n      if (!targetId) continue\n      const edgeId = makeEdgeId(sourceId, targetId, EdgeType.DEPENDS_ON)\n      if (graph.hasEdge(edgeId)) continue\n      // depends_on declaration from docker-compose.yml — structural deployment\n      // fact, structural tier per ADR-066.\n      const edge: GraphEdge = {\n        id: edgeId,\n        source: sourceId,\n        target: targetId,\n        type: EdgeType.DEPENDS_ON,\n        provenance: Provenance.EXTRACTED,\n        confidence: confidenceForExtracted('structural'),\n        evidence: { file: evidenceFile },\n      }\n      graph.addEdgeWithKey(edgeId, edge.source, edge.target, edge)\n      edgesAdded++\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import path from 'node:path'\nimport { promises as fs } from 'node:fs'\nimport type { GraphEdge } from '@neat.is/types'\nimport { EdgeType, Provenance, confidenceForExtracted } from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { exists, makeEdgeId, type DiscoveredService } from '../shared.js'\nimport { recordExtractionError } from '../errors.js'\nimport { makeInfraNode } from './shared.js'\nimport { ensureFileNode, toPosix } from '../calls/shared.js'\n\ninterface DockerfileFacts {\n  image: string | null\n  // Ports declared with `EXPOSE`, in declaration order, deduped. Each one is a\n  // network endpoint the container listens on — the structural answer to \"what\n  // is this service reachable at\".\n  ports: number[]\n  // The trimmed `ENTRYPOINT` / `CMD` line that names the process the container\n  // runs. Carried as edge evidence so the entrypoint is queryable instead of\n  // being a silent fact only the Dockerfile knows.\n  entrypoint: string | null\n}\n\n// Read the runtime-shaping instructions out of a Dockerfile in one pass:\n//\n//   - FROM   → the runtime image. Multi-stage builds report the *runtime* image\n//              (the last FROM that isn't `scratch` / a stage alias).\n//   - EXPOSE → the ports the container listens on (`EXPOSE 8080 9090`,\n//              `EXPOSE 8080/tcp`).\n//   - CMD / ENTRYPOINT → the process the container runs. ENTRYPOINT wins when\n//              both are present, matching Docker's precedence.\nfunction readDockerfile(content: string): DockerfileFacts {\n  let image: string | null = null\n  const ports: number[] = []\n  let cmd: string | null = null\n  let entrypoint: string | null = null\n  for (const raw of content.split('\\n')) {\n    const line = raw.trim()\n    if (!line || line.startsWith('#')) continue\n    if (/^from\\s+/i.test(line)) {\n      const candidate = line.split(/\\s+/)[1]\n      if (candidate && candidate.toLowerCase() !== 'scratch') image = candidate\n    } else if (/^expose\\s+/i.test(line)) {\n      for (const token of line.split(/\\s+/).slice(1)) {\n        const port = Number.parseInt(token.split('/')[0]!, 10)\n        if (Number.isInteger(port) && !ports.includes(port)) ports.push(port)\n      }\n    } else if (/^entrypoint\\s+/i.test(line)) {\n      entrypoint = line\n    } else if (/^cmd\\s+/i.test(line)) {\n      cmd = line\n    }\n  }\n  return { image, ports, entrypoint: entrypoint ?? cmd }\n}\n\n// For each ServiceNode that has a Dockerfile in its dir, emit a\n// `infra:container-image:<image>` InfraNode and a RUNS_ON edge from the\n// service to the image.\nexport async function addDockerfileRuntimes(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n  scanPath: string,\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    const dockerfilePath = path.join(service.dir, 'Dockerfile')\n    if (!(await exists(dockerfilePath))) continue\n    let content: string\n    try {\n      content = await fs.readFile(dockerfilePath, 'utf8')\n    } catch (err) {\n      recordExtractionError(\n        'infra dockerfile',\n        path.relative(scanPath, dockerfilePath),\n        err,\n      )\n      continue\n    }\n    const facts = readDockerfile(content)\n    if (!facts.image) continue\n\n    const node = makeInfraNode('container-image', facts.image)\n    if (!graph.hasNode(node.id)) {\n      graph.addNode(node.id, node)\n      nodesAdded++\n    }\n\n    // file-awareness §1 — the Dockerfile IS the file that declares the runtime;\n    // anchor the infra edges on a FileNode for it, not on the service. The file\n    // node is service-scoped, so two services that both `FROM node:20` keep\n    // distinct entrypoints and exposed ports instead of colliding on the shared\n    // image node.\n    const relDockerfile = toPosix(path.relative(service.dir, dockerfilePath))\n    const evidenceFile = toPosix(path.relative(scanPath, dockerfilePath))\n    const { fileNodeId, nodesAdded: fn, edgesAdded: fe } = ensureFileNode(\n      graph,\n      service.pkg.name,\n      service.node.id,\n      relDockerfile,\n    )\n    nodesAdded += fn\n    edgesAdded += fe\n\n    // RUNS_ON carries the runtime image, and — when the Dockerfile declares one\n    // — the entrypoint/CMD line as evidence.snippet, so the process the\n    // container runs is queryable instead of a silent fact.\n    const edgeId = makeEdgeId(fileNodeId, node.id, EdgeType.RUNS_ON)\n    if (!graph.hasEdge(edgeId)) {\n      const edge: GraphEdge = {\n        id: edgeId,\n        source: fileNodeId,\n        target: node.id,\n        type: EdgeType.RUNS_ON,\n        provenance: Provenance.EXTRACTED,\n        confidence: confidenceForExtracted('structural'),\n        evidence: {\n          file: evidenceFile,\n          ...(facts.entrypoint ? { snippet: facts.entrypoint.slice(0, 120) } : {}),\n        },\n      }\n      graph.addEdgeWithKey(edgeId, edge.source, edge.target, edge)\n      edgesAdded++\n    }\n\n    // Each EXPOSE port becomes an `infra:port:<n>` node the Dockerfile\n    // CONNECTS_TO — the structural answer to \"what is this service reachable\n    // at\". Without this, a declared listener is a fact only the Dockerfile\n    // knows; with it, the port is a first-class node the topology can reach.\n    for (const port of facts.ports) {\n      const portNode = makeInfraNode('port', String(port))\n      if (!graph.hasNode(portNode.id)) {\n        graph.addNode(portNode.id, portNode)\n        nodesAdded++\n      }\n      const portEdgeId = makeEdgeId(fileNodeId, portNode.id, EdgeType.CONNECTS_TO)\n      if (graph.hasEdge(portEdgeId)) continue\n      const portEdge: GraphEdge = {\n        id: portEdgeId,\n        source: fileNodeId,\n        target: portNode.id,\n        type: EdgeType.CONNECTS_TO,\n        provenance: Provenance.EXTRACTED,\n        confidence: confidenceForExtracted('structural'),\n        evidence: { file: evidenceFile, snippet: `EXPOSE ${port}` },\n      }\n      graph.addEdgeWithKey(portEdgeId, portEdge.source, portEdge.target, portEdge)\n      edgesAdded++\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { GraphEdge } from '@neat.is/types'\nimport { EdgeType, Provenance, confidenceForExtracted } from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { IGNORED_DIRS, isPythonVenvDir, makeEdgeId } from '../shared.js'\nimport { toPosix } from '../calls/shared.js'\nimport { makeInfraNode } from './shared.js'\n\n// Light pass: catalogue `resource \"aws_*\" \"name\"` blocks in any *.tf file and\n// wire the references between them. We don't run a real Terraform backend, but\n// the body of every resource block names the other resources it consumes\n// (`aws_db_instance.main.endpoint`, `${aws_security_group.db.id}`, …). Those\n// `<type>.<name>` references are the structural fact that turns an edgeless\n// catalogue into a topology: a resource nothing points at is declared-but-unused,\n// a resource something points at is in use. Without this, an RDS instance the\n// app server depends on looks identical to a forgotten S3 bucket.\nconst RESOURCE_RE = /resource\\s+\"(aws_[A-Za-z0-9_]+)\"\\s+\"([A-Za-z0-9_-]+)\"/g\n// A reference to another declared resource. The negative look-behind keeps us\n// from matching the tail of a longer identifier (`my_aws_thing.x`).\nconst REFERENCE_RE = /(?<![\\w.])(aws_[A-Za-z0-9_]+)\\.([A-Za-z0-9_-]+)/g\n\ninterface TfResource {\n  type: string\n  name: string\n  nodeId: string\n  body: string\n  bodyOffset: number\n}\n\nasync function walkTfFiles(start: string, depth = 0, max = 5): Promise<string[]> {\n  if (depth > max) return []\n  const out: string[] = []\n  const entries = await fs.readdir(start, { withFileTypes: true }).catch(() => [])\n  for (const entry of entries) {\n    if (entry.isDirectory()) {\n      if (IGNORED_DIRS.has(entry.name) || entry.name === '.terraform') continue\n      const child = path.join(start, entry.name)\n      if (await isPythonVenvDir(child)) continue\n      out.push(...(await walkTfFiles(child, depth + 1, max)))\n    } else if (entry.isFile() && entry.name.endsWith('.tf')) {\n      out.push(path.join(start, entry.name))\n    }\n  }\n  return out\n}\n\n// Find the index just past the `}` that closes the block whose opening `{`\n// sits at or after `from`. Returns the body span (exclusive of the braces).\n// Balanced-brace scan — good enough for HCL, which doesn't put bare braces in\n// string literals often enough to matter for a reference catalogue.\nfunction blockBody(content: string, from: number): { body: string; offset: number } | null {\n  const open = content.indexOf('{', from)\n  if (open === -1) return null\n  let depth = 0\n  for (let i = open; i < content.length; i++) {\n    const ch = content[i]\n    if (ch === '{') depth++\n    else if (ch === '}') {\n      depth--\n      if (depth === 0) return { body: content.slice(open + 1, i), offset: open + 1 }\n    }\n  }\n  return null\n}\n\nfunction lineAt(content: string, index: number): number {\n  let line = 1\n  for (let i = 0; i < index && i < content.length; i++) {\n    if (content[i] === '\\n') line++\n  }\n  return line\n}\n\nexport async function addTerraformResources(\n  graph: NeatGraph,\n  scanPath: string,\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n  const files = await walkTfFiles(scanPath)\n  for (const file of files) {\n    const content = await fs.readFile(file, 'utf8')\n    const evidenceFile = toPosix(path.relative(scanPath, file))\n\n    // First pass: register every resource as a node and remember its body so\n    // the second pass can resolve references against the set of declared names.\n    const resources: TfResource[] = []\n    const byKey = new Map<string, TfResource>()\n    RESOURCE_RE.lastIndex = 0\n    let m: RegExpExecArray | null\n    while ((m = RESOURCE_RE.exec(content)) !== null) {\n      const type = m[1]!\n      const name = m[2]!\n      const node = makeInfraNode(type, name, 'aws')\n      if (!graph.hasNode(node.id)) {\n        graph.addNode(node.id, node)\n        nodesAdded++\n      }\n      const span = blockBody(content, RESOURCE_RE.lastIndex)\n      const resource: TfResource = {\n        type,\n        name,\n        nodeId: node.id,\n        body: span?.body ?? '',\n        bodyOffset: span?.offset ?? RESOURCE_RE.lastIndex,\n      }\n      resources.push(resource)\n      byKey.set(`${type}.${name}`, resource)\n    }\n\n    // Second pass: a `<type>.<name>` reference inside a resource body that\n    // names another declared resource becomes a DEPENDS_ON edge from the\n    // referencing resource to the one it consumes. Structural tier (ADR-066) —\n    // the HCL literally says it depends on it.\n    for (const resource of resources) {\n      const seen = new Set<string>()\n      REFERENCE_RE.lastIndex = 0\n      let ref: RegExpExecArray | null\n      while ((ref = REFERENCE_RE.exec(resource.body)) !== null) {\n        const key = `${ref[1]!}.${ref[2]!}`\n        if (key === `${resource.type}.${resource.name}`) continue\n        const target = byKey.get(key)\n        if (!target) continue\n        if (seen.has(target.nodeId)) continue\n        seen.add(target.nodeId)\n        const edgeId = makeEdgeId(resource.nodeId, target.nodeId, EdgeType.DEPENDS_ON)\n        if (graph.hasEdge(edgeId)) continue\n        const line = lineAt(content, resource.bodyOffset + ref.index)\n        const edge: GraphEdge = {\n          id: edgeId,\n          source: resource.nodeId,\n          target: target.nodeId,\n          type: EdgeType.DEPENDS_ON,\n          provenance: Provenance.EXTRACTED,\n          confidence: confidenceForExtracted('structural'),\n          evidence: { file: evidenceFile, line, snippet: key },\n        }\n        graph.addEdgeWithKey(edgeId, edge.source, edge.target, edge)\n        edgesAdded++\n      }\n    }\n  }\n  return { nodesAdded, edgesAdded }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { parseAllDocuments } from 'yaml'\nimport { EdgeType, serviceId } from '@neat.is/types'\nimport type { InfraNode, ServiceNode } from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { CONFIG_FILE_EXTENSIONS, IGNORED_DIRS, isPythonVenvDir } from '../shared.js'\nimport { toPosix } from '../calls/shared.js'\nimport { emitPlatformResourceEdge, lineContaining, makeInfraNode } from './shared.js'\n\ninterface K8sDoc {\n  kind?: string\n  metadata?: { name?: string; namespace?: string }\n  spec?: {\n    replicas?: number\n    template?: { spec?: { containers?: Array<{ image?: string }> } }\n  }\n}\n\nconst K8S_KIND_TO_INFRA_KIND: Record<string, string> = {\n  Service: 'k8s-service',\n  Deployment: 'k8s-deployment',\n  StatefulSet: 'k8s-statefulset',\n  DaemonSet: 'k8s-daemonset',\n  CronJob: 'k8s-cronjob',\n  Job: 'k8s-job',\n  Ingress: 'k8s-ingress',\n}\n\n// The kinds that carry a pod template we read the declared image + replica count\n// from. Service / Ingress / Job-style kinds have neither (a Job/CronJob nests its\n// template a level deeper and is left for a later rung).\nconst WORKLOAD_KINDS = new Set(['Deployment', 'StatefulSet', 'DaemonSet'])\n\nasync function walkYamlFiles(start: string, depth = 0, max = 5): Promise<string[]> {\n  if (depth > max) return []\n  const out: string[] = []\n  const entries = await fs.readdir(start, { withFileTypes: true }).catch(() => [])\n  for (const entry of entries) {\n    if (entry.isDirectory()) {\n      if (IGNORED_DIRS.has(entry.name)) continue\n      const child = path.join(start, entry.name)\n      if (await isPythonVenvDir(child)) continue\n      out.push(...(await walkYamlFiles(child, depth + 1, max)))\n    } else if (entry.isFile() && CONFIG_FILE_EXTENSIONS.has(path.extname(entry.name))) {\n      out.push(path.join(start, entry.name))\n    }\n  }\n  return out\n}\n\n// The k8s deployment substrate — the DECLARED half. Reads workload manifests\n// (multi-document YAML with a `kind`/`metadata.name`) and records the desired\n// deploy state: the container image and replica count a Deployment/StatefulSet/\n// DaemonSet declares. The declared state is stamped onto the `service:<name>` node\n// the workload runs (`declaredImage`/`declaredReplicas`), where the k8s observed\n// reader stamps the running image / ready replicas — the two provenances fuse on\n// one node so the divergence detector can name a declared-vs-running deploy drift,\n// including the stuck rollout that mints no incident (service still up on the old\n// image). The workload also gets its own `infra:k8s-deployment:<name>` InfraNode\n// with image/replicas + a RUNS_ON edge, for topology and blast-radius.\n//\n// The InfraNode is keyed NAME-ONLY (`infraId(kind, metadata.name)`), not\n// `<ns>/<name>`: a manifest frequently omits `metadata.namespace` (relying on\n// `kubectl apply -n`), so the name is the only key the declared manifest and the\n// live cluster can both produce, and it matches NEAT's name-based identity (a\n// ServiceNode is `service:<name>`, ADR-010). The namespace rides as an attribute.\nexport async function addK8sResources(\n  graph: NeatGraph,\n  scanPath: string,\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n  const files = await walkYamlFiles(scanPath)\n  for (const file of files) {\n    const content = await fs.readFile(file, 'utf8')\n    let docs: K8sDoc[]\n    try {\n      docs = parseAllDocuments(content).map((d) => d.toJSON() as K8sDoc)\n    } catch {\n      continue\n    }\n    const relFile = toPosix(path.relative(scanPath, file))\n    for (const doc of docs) {\n      if (!doc?.kind || !doc.metadata?.name) continue\n      const infraKind = K8S_KIND_TO_INFRA_KIND[doc.kind]\n      if (!infraKind) continue\n      const name = doc.metadata.name\n\n      const isWorkload = WORKLOAD_KINDS.has(doc.kind)\n      const image = isWorkload ? doc.spec?.template?.spec?.containers?.[0]?.image : undefined\n      const replicas =\n        isWorkload && typeof doc.spec?.replicas === 'number' ? doc.spec.replicas : undefined\n\n      const base = makeInfraNode(infraKind, name, 'kubernetes')\n      const node: InfraNode = {\n        ...base,\n        ...(doc.metadata.namespace ? { namespace: doc.metadata.namespace } : {}),\n        ...(image ? { image } : {}),\n        ...(replicas !== undefined ? { replicas } : {}),\n      }\n      if (!graph.hasNode(node.id)) {\n        graph.addNode(node.id, node)\n        nodesAdded++\n      }\n\n      // Stamp the declared deploy state on the ServiceNode the workload runs — the\n      // node the observed cluster reader stamps running-image/ready onto, so the two\n      // fuse there. Only when the service already exists: no phantom, no dangle.\n      if (isWorkload) {\n        const svcId = serviceId(name)\n        if (graph.hasNode(svcId)) {\n          const svc = graph.getNodeAttributes(svcId) as ServiceNode\n          graph.replaceNodeAttributes(svcId, {\n            ...svc,\n            platform: svc.platform ?? 'kubernetes',\n            ...(image ? { declaredImage: image } : {}),\n            ...(replicas !== undefined ? { declaredReplicas: replicas } : {}),\n          })\n          // Topology edge — the service runs on this declared k8s workload. The\n          // InfraNode already exists (enriched above), so this only adds the edge.\n          edgesAdded += emitPlatformResourceEdge(\n            graph,\n            svcId,\n            EdgeType.RUNS_ON,\n            infraKind,\n            name,\n            'kubernetes',\n            relFile,\n            lineContaining(content, image),\n          ).edgesAdded\n        }\n      }\n    }\n  }\n  return { nodesAdded, edgesAdded }\n}\n","// Cloudflare Workers/Pages extraction (ADR-133, docs/contracts/static-extraction.md).\n//\n// Reads a service's `wrangler.toml`/`wrangler.jsonc`/`wrangler.json` and stamps\n// the `platform: cloudflare` identifier every downstream consumer keys on: the\n// ServiceNode (the frontend's icon key at the service-rollup level) and the\n// Worker's entry FileNode, which also carries `platformName` — the Worker's own\n// script name, the only identifier Cloudflare's own telemetry carries and what\n// the Cloudflare connector's resolveTarget looks up against\n// (docs/contracts/connectors.md §4a).\n//\n// Declared resources (bindings, routes, cron triggers, env-var names) become\n// InfraNodes wired from the entry file, the same shape dockerfile.ts/k8s.ts/\n// docker-compose.ts already use — no new NodeType. Per-environment `[env.X]`\n// wrangler sections are out of scope for v1; only top-level config is read.\n\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport type { FileNode, GraphEdge, ServiceNode } from '@neat.is/types'\nimport { EdgeType, EdgeTypeValue, Provenance, confidenceForExtracted } from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { exists, maskCommentsInSource, makeEdgeId, type DiscoveredService } from '../shared.js'\nimport { recordExtractionError } from '../errors.js'\nimport { ensureFileNode, toPosix } from '../calls/shared.js'\nimport { makeInfraNode } from './shared.js'\n\ninterface WranglerBindingLike {\n  binding?: string\n  name?: string\n  queue?: string\n}\n\ninterface WranglerRouteLike {\n  pattern?: string\n}\n\ninterface WranglerServiceBinding {\n  binding?: string\n  service?: string\n}\n\ninterface WranglerConfig {\n  name?: string\n  main?: string\n  compatibility_date?: string\n  routes?: (string | WranglerRouteLike)[]\n  route?: string | WranglerRouteLike\n  kv_namespaces?: WranglerBindingLike[]\n  d1_databases?: WranglerBindingLike[]\n  r2_buckets?: WranglerBindingLike[]\n  durable_objects?: { bindings?: WranglerBindingLike[] }\n  queues?: { producers?: WranglerBindingLike[]; consumers?: WranglerBindingLike[] }\n  triggers?: { crons?: string[] }\n  services?: WranglerServiceBinding[]\n  vars?: Record<string, unknown>\n}\n\ninterface WranglerRead {\n  config: WranglerConfig\n  relFile: string\n  raw: string\n}\n\nconst WRANGLER_FILENAMES = ['wrangler.toml', 'wrangler.jsonc', 'wrangler.json']\n\nasync function readWranglerConfig(dir: string): Promise<WranglerRead | null> {\n  for (const filename of WRANGLER_FILENAMES) {\n    const abs = path.join(dir, filename)\n    if (!(await exists(abs))) continue\n    const raw = await fs.readFile(abs, 'utf8')\n    const config =\n      filename === 'wrangler.toml'\n        ? (parseToml(raw) as unknown as WranglerConfig)\n        : (JSON.parse(maskCommentsInSource(raw)) as WranglerConfig)\n    return { config, relFile: filename, raw }\n  }\n  return null\n}\n\n// Best-effort 1-indexed line for a declared value — a simple text search, the\n// same \"read config as data\" discipline `proto.ts`'s brace-balanced scan and\n// `terraform.ts`'s `lineAt` already use rather than a real TOML/JSONC AST.\nfunction lineContaining(raw: string, needle: string | undefined): number | undefined {\n  if (!needle) return undefined\n  const idx = raw.indexOf(needle)\n  if (idx === -1) return undefined\n  let line = 1\n  for (let i = 0; i < idx; i++) if (raw[i] === '\\n') line++\n  return line\n}\n\nfunction normalizeRoutes(config: WranglerConfig): string[] {\n  const out: string[] = []\n  const pushOne = (r: unknown): void => {\n    if (typeof r === 'string') out.push(r)\n    else if (r && typeof r === 'object' && typeof (r as WranglerRouteLike).pattern === 'string') {\n      out.push((r as WranglerRouteLike).pattern!)\n    }\n  }\n  if (Array.isArray(config.routes)) config.routes.forEach(pushOne)\n  else if (config.route) pushOne(config.route)\n  return out\n}\n\n// One declared-resource InfraNode + edge from the entry anchor (FileNode, or\n// the ServiceNode itself when no entry file resolved — the honest\n// service-level fallback file-awareness.md already names for this case).\nfunction addResourceEdge(\n  graph: NeatGraph,\n  anchorId: string,\n  edgeType: EdgeTypeValue,\n  kind: string,\n  name: string,\n  evidenceFile: string,\n  line: number | undefined,\n): { nodesAdded: number; edgesAdded: number } {\n  let nodesAdded = 0\n  let edgesAdded = 0\n  const node = makeInfraNode(kind, name, 'cloudflare')\n  if (!graph.hasNode(node.id)) {\n    graph.addNode(node.id, node)\n    nodesAdded++\n  }\n  if (node.id === anchorId) return { nodesAdded, edgesAdded } // no self-loops\n  const edgeId = makeEdgeId(anchorId, node.id, edgeType)\n  if (!graph.hasEdge(edgeId)) {\n    const edge: GraphEdge = {\n      id: edgeId,\n      source: anchorId,\n      target: node.id,\n      type: edgeType,\n      provenance: Provenance.EXTRACTED,\n      confidence: confidenceForExtracted('structural'),\n      evidence: { file: evidenceFile, ...(line !== undefined ? { line } : {}) },\n    }\n    graph.addEdgeWithKey(edgeId, edge.source, edge.target, edge)\n    edgesAdded++\n  }\n  return { nodesAdded, edgesAdded }\n}\n\ninterface DiscoveredWorker {\n  service: DiscoveredService\n  config: WranglerConfig\n  relFile: string\n  raw: string\n  evidenceFile: string\n}\n\nexport async function addCloudflareWorkers(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n  scanPath: string,\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  // Pass 1 — read every service's wrangler config (if any) before writing a\n  // single node, so pass 2's service-binding resolution sees the full\n  // worker-name → entry-file map for this scan, same discipline `route-match.ts`\n  // uses running routes before calls.\n  const discovered: DiscoveredWorker[] = []\n  const workerIndex = new Map<string, { anchorId: string }>()\n\n  for (const service of services) {\n    let read: WranglerRead | null\n    try {\n      read = await readWranglerConfig(service.dir)\n    } catch (err) {\n      recordExtractionError('infra cloudflare', path.relative(scanPath, service.dir), err)\n      continue\n    }\n    if (!read || !read.config.name) continue\n\n    const evidenceFile = toPosix(path.relative(scanPath, path.join(service.dir, read.relFile)))\n    discovered.push({ service, config: read.config, relFile: read.relFile, raw: read.raw, evidenceFile })\n  }\n\n  // Tag every ServiceNode + entry FileNode first, populating workerIndex, so\n  // pass 2's service-binding resolution can target a real FileNode even when\n  // the referenced Worker is later in `services` than the one declaring the\n  // binding.\n  for (const worker of discovered) {\n    const { service, config } = worker\n\n    const serviceNode = graph.getNodeAttributes(service.node.id) as ServiceNode\n    if (serviceNode.platform !== 'cloudflare') {\n      const updated: ServiceNode = { ...serviceNode, platform: 'cloudflare' }\n      graph.replaceNodeAttributes(service.node.id, updated)\n    }\n\n    let anchorId = service.node.id\n    if (config.main) {\n      const entryRelPath = toPosix(path.normalize(config.main))\n      const { fileNodeId, nodesAdded: fn, edgesAdded: fe } = ensureFileNode(\n        graph,\n        service.pkg.name,\n        service.node.id,\n        entryRelPath,\n      )\n      nodesAdded += fn\n      edgesAdded += fe\n      const fileNode = graph.getNodeAttributes(fileNodeId) as FileNode\n      if (fileNode.platform !== 'cloudflare' || fileNode.platformName !== config.name) {\n        const updated: FileNode = { ...fileNode, platform: 'cloudflare', platformName: config.name }\n        graph.replaceNodeAttributes(fileNodeId, updated)\n      }\n      anchorId = fileNodeId\n    }\n\n    workerIndex.set(config.name!, { anchorId })\n  }\n\n  // Pass 2 — declared resources, wired from each worker's anchor (entry\n  // FileNode, or the ServiceNode when `main` was absent).\n  for (const worker of discovered) {\n    const { config, evidenceFile, raw } = worker\n    const anchorId = workerIndex.get(config.name!)!.anchorId\n\n    // Runtime marker — one shared node every Cloudflare Worker in this scan\n    // RUNS_ON, compat date carried as evidence.snippet (mirrors dockerfile.ts's\n    // image-node + entrypoint-snippet pattern).\n    const runtimeNode = makeInfraNode('workerd', 'cloudflare', 'cloudflare')\n    if (!graph.hasNode(runtimeNode.id)) {\n      graph.addNode(runtimeNode.id, runtimeNode)\n      nodesAdded++\n    }\n    if (runtimeNode.id !== anchorId) {\n      const runsOnId = makeEdgeId(anchorId, runtimeNode.id, EdgeType.RUNS_ON)\n      if (!graph.hasEdge(runsOnId)) {\n        const edge: GraphEdge = {\n          id: runsOnId,\n          source: anchorId,\n          target: runtimeNode.id,\n          type: EdgeType.RUNS_ON,\n          provenance: Provenance.EXTRACTED,\n          confidence: confidenceForExtracted('structural'),\n          evidence: {\n            file: evidenceFile,\n            ...(config.compatibility_date\n              ? { snippet: `compatibility_date = ${config.compatibility_date}`.slice(0, 120) }\n              : {}),\n          },\n        }\n        graph.addEdgeWithKey(runsOnId, edge.source, edge.target, edge)\n        edgesAdded++\n      }\n    }\n\n    // Routes / custom domains — network-reachability, same CONNECTS_TO\n    // semantics dockerfile.ts's EXPOSE→port edge already uses.\n    for (const route of normalizeRoutes(config)) {\n      const result = addResourceEdge(\n        graph,\n        anchorId,\n        EdgeType.CONNECTS_TO,\n        'cloudflare-route',\n        route,\n        evidenceFile,\n        lineContaining(raw, route),\n      )\n      nodesAdded += result.nodesAdded\n      edgesAdded += result.edgesAdded\n    }\n\n    // Bindings — declared runtime dependencies, DEPENDS_ON.\n    const bindingGroups: { kind: string; entries: WranglerBindingLike[]; nameOf: (b: WranglerBindingLike) => string | undefined }[] = [\n      { kind: 'cloudflare-kv', entries: config.kv_namespaces ?? [], nameOf: (b) => b.binding },\n      { kind: 'cloudflare-d1', entries: config.d1_databases ?? [], nameOf: (b) => b.binding },\n      { kind: 'cloudflare-r2', entries: config.r2_buckets ?? [], nameOf: (b) => b.binding },\n      { kind: 'cloudflare-durable-object', entries: config.durable_objects?.bindings ?? [], nameOf: (b) => b.name },\n      { kind: 'cloudflare-queue', entries: config.queues?.producers ?? [], nameOf: (b) => b.queue },\n      { kind: 'cloudflare-queue', entries: config.queues?.consumers ?? [], nameOf: (b) => b.queue },\n    ]\n    for (const group of bindingGroups) {\n      for (const entry of group.entries) {\n        const name = group.nameOf(entry)\n        if (!name) continue\n        const result = addResourceEdge(\n          graph,\n          anchorId,\n          EdgeType.DEPENDS_ON,\n          group.kind,\n          name,\n          evidenceFile,\n          lineContaining(raw, name),\n        )\n        nodesAdded += result.nodesAdded\n        edgesAdded += result.edgesAdded\n      }\n    }\n\n    // Cron triggers.\n    for (const cron of config.triggers?.crons ?? []) {\n      const result = addResourceEdge(\n        graph,\n        anchorId,\n        EdgeType.DEPENDS_ON,\n        'cloudflare-cron',\n        cron,\n        evidenceFile,\n        lineContaining(raw, cron),\n      )\n      nodesAdded += result.nodesAdded\n      edgesAdded += result.edgesAdded\n    }\n\n    // Declared env vars — name only, value never read (ADR-016 spirit).\n    for (const varName of Object.keys(config.vars ?? {})) {\n      const result = addResourceEdge(\n        graph,\n        anchorId,\n        EdgeType.DEPENDS_ON,\n        'cloudflare-env-var',\n        varName,\n        evidenceFile,\n        lineContaining(raw, varName),\n      )\n      nodesAdded += result.nodesAdded\n      edgesAdded += result.edgesAdded\n    }\n\n    // Service bindings — resolve directly onto the target Worker's own entry\n    // node when it's tagged in this same scan (CALLS: this Worker can invoke\n    // that one); otherwise an honest InfraNode fallback, never guessed.\n    for (const svc of config.services ?? []) {\n      if (!svc.service) continue\n      const target = workerIndex.get(svc.service)\n      if (target && target.anchorId !== anchorId) {\n        const edgeId = makeEdgeId(anchorId, target.anchorId, EdgeType.CALLS)\n        if (!graph.hasEdge(edgeId)) {\n          const edge: GraphEdge = {\n            id: edgeId,\n            source: anchorId,\n            target: target.anchorId,\n            type: EdgeType.CALLS,\n            provenance: Provenance.EXTRACTED,\n            confidence: confidenceForExtracted('structural'),\n            evidence: { file: evidenceFile, line: lineContaining(raw, svc.service) },\n          }\n          graph.addEdgeWithKey(edgeId, edge.source, edge.target, edge)\n          edgesAdded++\n        }\n        continue\n      }\n      const result = addResourceEdge(\n        graph,\n        anchorId,\n        EdgeType.DEPENDS_ON,\n        'cloudflare-service-binding',\n        svc.service,\n        evidenceFile,\n        lineContaining(raw, svc.service),\n      )\n      nodesAdded += result.nodesAdded\n      edgesAdded += result.edgesAdded\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","// Vercel project extraction. Stamps the `platform: vercel` identifier the\n// frontend service-rollup badge keys on (static-extraction.md, mirroring ADR-133\n// for Cloudflare) whenever a service carries a `vercel.json`/`vercel.jsonc` or a\n// linked `.vercel/project.json`, and models the config's declared resources —\n// crons, env-var names, routes/rewrites — as InfraNodes wired from the\n// ServiceNode. No new NodeType; env-var values are never read (ADR-016 spirit),\n// only names. Vercel apps have no single Worker-style entry file, so the tag and\n// the resource edges anchor on the ServiceNode itself.\n\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { ServiceNode } from '@neat.is/types'\nimport { EdgeType, EdgeTypeValue } from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { exists, maskCommentsInSource, type DiscoveredService } from '../shared.js'\nimport { recordExtractionError } from '../errors.js'\nimport { toPosix } from '../calls/shared.js'\nimport { emitPlatformResourceEdge, lineContaining } from './shared.js'\n\ninterface VercelCron {\n  path?: string\n  schedule?: string\n}\n\ninterface VercelRoute {\n  source?: string\n  src?: string\n}\n\ninterface VercelConfig {\n  crons?: VercelCron[]\n  env?: Record<string, unknown>\n  build?: { env?: Record<string, unknown> }\n  rewrites?: VercelRoute[]\n  redirects?: VercelRoute[]\n  routes?: VercelRoute[]\n}\n\nconst VERCEL_CONFIG_FILENAMES = ['vercel.json', 'vercel.jsonc']\n\ninterface VercelRead {\n  config: VercelConfig\n  relFile: string\n  raw: string\n}\n\nasync function readVercelConfig(dir: string): Promise<VercelRead | null> {\n  for (const filename of VERCEL_CONFIG_FILENAMES) {\n    const abs = path.join(dir, filename)\n    if (!(await exists(abs))) continue\n    const raw = await fs.readFile(abs, 'utf8')\n    const config = JSON.parse(maskCommentsInSource(raw)) as VercelConfig\n    return { config, relFile: filename, raw }\n  }\n  return null\n}\n\n// `vercel link` writes `.vercel/project.json` — a strong platform signal even\n// when the repo carries no vercel.json, and the only place the human-readable\n// project name lives (the equivalent of a Worker's script name).\nasync function readLinkedProjectName(dir: string): Promise<string | undefined> {\n  const abs = path.join(dir, '.vercel', 'project.json')\n  if (!(await exists(abs))) return undefined\n  const parsed = JSON.parse(await fs.readFile(abs, 'utf8')) as { projectName?: unknown }\n  return typeof parsed.projectName === 'string' ? parsed.projectName : undefined\n}\n\nfunction routeSource(route: VercelRoute): string | undefined {\n  return route.source ?? route.src\n}\n\nexport async function addVercelServices(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n  scanPath: string,\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    let read: VercelRead | null = null\n    let projectName: string | undefined\n    try {\n      read = await readVercelConfig(service.dir)\n      projectName = await readLinkedProjectName(service.dir)\n    } catch (err) {\n      recordExtractionError('infra vercel', path.relative(scanPath, service.dir), err)\n      continue\n    }\n    // A Vercel service is one with a vercel.json or a linked .vercel/project.json.\n    if (!read && !projectName) continue\n\n    const serviceNode = graph.getNodeAttributes(service.node.id) as ServiceNode\n    if (serviceNode.platform !== 'vercel' || (projectName && serviceNode.platformName !== projectName)) {\n      const updated: ServiceNode = {\n        ...serviceNode,\n        platform: 'vercel',\n        ...(projectName ? { platformName: projectName } : {}),\n      }\n      graph.replaceNodeAttributes(service.node.id, updated)\n    }\n\n    const anchorId = service.node.id\n    if (!read) continue // linked but no config file to mine resources from\n    const { config, relFile, raw } = read\n    const evidenceFile = toPosix(path.relative(scanPath, path.join(service.dir, relFile)))\n\n    const add = (edgeType: EdgeTypeValue, kind: string, name: string | undefined): void => {\n      if (!name) return\n      const result = emitPlatformResourceEdge(\n        graph,\n        anchorId,\n        edgeType,\n        kind,\n        name,\n        'vercel',\n        evidenceFile,\n        lineContaining(raw, name),\n      )\n      nodesAdded += result.nodesAdded\n      edgesAdded += result.edgesAdded\n    }\n\n    // Runtime marker — one shared node every Vercel service RUNS_ON.\n    add(EdgeType.RUNS_ON, 'vercel', 'vercel')\n\n    // Scheduled functions.\n    for (const cron of config.crons ?? []) add(EdgeType.DEPENDS_ON, 'vercel-cron', cron.path ?? cron.schedule)\n\n    // Declared env vars — names only, value never read.\n    for (const varName of Object.keys(config.env ?? {})) add(EdgeType.DEPENDS_ON, 'vercel-env-var', varName)\n    for (const varName of Object.keys(config.build?.env ?? {})) add(EdgeType.DEPENDS_ON, 'vercel-env-var', varName)\n\n    // Routes / rewrites / redirects — network-reachability, CONNECTS_TO.\n    for (const route of [...(config.rewrites ?? []), ...(config.redirects ?? []), ...(config.routes ?? [])]) {\n      add(EdgeType.CONNECTS_TO, 'vercel-route', routeSource(route))\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","// Railway service extraction. Stamps the `platform: railway` identifier the\n// frontend service-rollup badge keys on (mirroring ADR-133 for Cloudflare) when a\n// service carries a `railway.toml`/`railway.json`/`railway.jsonc`, and models the\n// config's declared surfaces — the healthcheck path and a cron schedule — as\n// InfraNodes wired from the ServiceNode. No new NodeType. Railway's config names\n// no service (that lives in Railway's own system, which the connector resolves by\n// deploymentId), so no platformName is stamped here.\n\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport type { ServiceNode } from '@neat.is/types'\nimport { EdgeType, EdgeTypeValue } from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { exists, maskCommentsInSource, type DiscoveredService } from '../shared.js'\nimport { recordExtractionError } from '../errors.js'\nimport { toPosix } from '../calls/shared.js'\nimport { emitPlatformResourceEdge, lineContaining } from './shared.js'\n\ninterface RailwayDeploy {\n  healthcheckPath?: string\n  cronSchedule?: string\n}\n\ninterface RailwayConfig {\n  deploy?: RailwayDeploy\n}\n\nconst RAILWAY_FILENAMES = ['railway.toml', 'railway.json', 'railway.jsonc']\n\ninterface RailwayRead {\n  config: RailwayConfig\n  relFile: string\n  raw: string\n}\n\nasync function readRailwayConfig(dir: string): Promise<RailwayRead | null> {\n  for (const filename of RAILWAY_FILENAMES) {\n    const abs = path.join(dir, filename)\n    if (!(await exists(abs))) continue\n    const raw = await fs.readFile(abs, 'utf8')\n    const config =\n      filename === 'railway.toml'\n        ? (parseToml(raw) as unknown as RailwayConfig)\n        : (JSON.parse(maskCommentsInSource(raw)) as RailwayConfig)\n    return { config, relFile: filename, raw }\n  }\n  return null\n}\n\nexport async function addRailwayServices(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n  scanPath: string,\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    let read: RailwayRead | null = null\n    try {\n      read = await readRailwayConfig(service.dir)\n    } catch (err) {\n      recordExtractionError('infra railway', path.relative(scanPath, service.dir), err)\n      continue\n    }\n    if (!read) continue\n\n    const serviceNode = graph.getNodeAttributes(service.node.id) as ServiceNode\n    if (serviceNode.platform !== 'railway') {\n      graph.replaceNodeAttributes(service.node.id, { ...serviceNode, platform: 'railway' })\n    }\n\n    const anchorId = service.node.id\n    const { config, relFile, raw } = read\n    const evidenceFile = toPosix(path.relative(scanPath, path.join(service.dir, relFile)))\n\n    const add = (edgeType: EdgeTypeValue, kind: string, name: string | undefined): void => {\n      if (!name) return\n      const result = emitPlatformResourceEdge(\n        graph,\n        anchorId,\n        edgeType,\n        kind,\n        name,\n        'railway',\n        evidenceFile,\n        lineContaining(raw, name),\n      )\n      nodesAdded += result.nodesAdded\n      edgesAdded += result.edgesAdded\n    }\n\n    add(EdgeType.RUNS_ON, 'railway', 'railway')\n    add(EdgeType.CONNECTS_TO, 'railway-route', config.deploy?.healthcheckPath)\n    add(EdgeType.DEPENDS_ON, 'railway-cron', config.deploy?.cronSchedule)\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","// Supabase project extraction. Stamps the `platform: supabase` identifier the\n// frontend service-rollup badge keys on (mirroring ADR-133 for Cloudflare) when a\n// service carries a `supabase/config.toml`, using the config's `project_id` as\n// platformName (the ref the Supabase connector resolves against), and models the\n// declared surfaces — edge functions, storage, auth — as InfraNodes wired from\n// the ServiceNode. No new NodeType.\n\nimport { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport type { ServiceNode } from '@neat.is/types'\nimport { EdgeType, EdgeTypeValue } from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { exists, type DiscoveredService } from '../shared.js'\nimport { recordExtractionError } from '../errors.js'\nimport { toPosix } from '../calls/shared.js'\nimport { emitPlatformResourceEdge, lineContaining } from './shared.js'\n\ninterface SupabaseConfig {\n  project_id?: string\n  functions?: Record<string, unknown>\n  storage?: Record<string, unknown>\n  auth?: Record<string, unknown>\n}\n\ninterface SupabaseRead {\n  config: SupabaseConfig\n  relFile: string\n  raw: string\n}\n\n// Supabase's config lives at <service>/supabase/config.toml, not the service root.\nasync function readSupabaseConfig(dir: string): Promise<SupabaseRead | null> {\n  const relFile = path.join('supabase', 'config.toml')\n  const abs = path.join(dir, relFile)\n  if (!(await exists(abs))) return null\n  const raw = await fs.readFile(abs, 'utf8')\n  const config = parseToml(raw) as unknown as SupabaseConfig\n  return { config, relFile, raw }\n}\n\nexport async function addSupabaseProjects(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n  scanPath: string,\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    let read: SupabaseRead | null = null\n    try {\n      read = await readSupabaseConfig(service.dir)\n    } catch (err) {\n      recordExtractionError('infra supabase', path.relative(scanPath, service.dir), err)\n      continue\n    }\n    if (!read) continue\n\n    const { config, relFile, raw } = read\n    const projectId = typeof config.project_id === 'string' ? config.project_id : undefined\n\n    const serviceNode = graph.getNodeAttributes(service.node.id) as ServiceNode\n    if (serviceNode.platform !== 'supabase' || (projectId && serviceNode.platformName !== projectId)) {\n      graph.replaceNodeAttributes(service.node.id, {\n        ...serviceNode,\n        platform: 'supabase',\n        ...(projectId ? { platformName: projectId } : {}),\n      })\n    }\n\n    const anchorId = service.node.id\n    const evidenceFile = toPosix(path.relative(scanPath, path.join(service.dir, relFile)))\n\n    const add = (edgeType: EdgeTypeValue, kind: string, name: string | undefined): void => {\n      if (!name) return\n      const result = emitPlatformResourceEdge(\n        graph,\n        anchorId,\n        edgeType,\n        kind,\n        name,\n        'supabase',\n        evidenceFile,\n        lineContaining(raw, name),\n      )\n      nodesAdded += result.nodesAdded\n      edgesAdded += result.edgesAdded\n    }\n\n    add(EdgeType.RUNS_ON, 'supabase', 'supabase')\n    // Edge functions — each [functions.X] section becomes a declared function.\n    for (const fn of Object.keys(config.functions ?? {})) add(EdgeType.DEPENDS_ON, 'supabase-function', fn)\n    // Managed surfaces the project declares.\n    if (config.storage) add(EdgeType.DEPENDS_ON, 'supabase-storage', 'storage')\n    if (config.auth) add(EdgeType.DEPENDS_ON, 'supabase-auth', 'auth')\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport type { GraphEdge, RouteNode, ServiceNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  routeId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { makeEdgeId, type DiscoveredService } from '../shared.js'\nimport { recordExtractionError, noteExtractedDropped } from '../errors.js'\nimport { ensureFileNode, snippet, toPosix } from '../calls/shared.js'\n\n// nginx `proxy_pass` — config as a source. A front end that is only nginx (or\n// OpenResty) hands requests to a service through its config:\n//\n//   location /api/v1/ {\n//     proxy_pass http://ts-gateway-service:18888;\n//   }\n//\n// For each service directory carrying an nginx config (`nginx.conf`,\n// `conf/nginx.conf`, `conf.d/*.conf`), each `location` whose block holds a\n// literal `proxy_pass http(s)://<host>[:port][/path]` mints:\n//   - a RouteNode for the location path on that service (ALL), when the location\n//     is a plain or exact (`=`) path; a regex location (`~`, `~*`) has no path\n//     template, so it gets no route, though its proxy edge still stands;\n//   - `file ──CALLS──▶ service` from the config file to the service <host> names,\n//     matched against service names, directory names and aliases. A host naming an\n//     `upstream` block resolves through that block's `server` hosts.\n// A host from a variable (`proxy_pass http://$backend`) is recorded as a drop with\n// its reason; a literal host naming no service in the graph gets no edge. A\n// location served by Lua (`content_by_lua*`) or by files has no proxy_pass and\n// mints nothing here.\n\nconst CONFIG_CANDIDATES = ['nginx.conf', path.join('conf', 'nginx.conf')]\n\ninterface Token {\n  text: string\n  line: number\n}\n\n// nginx's grammar: words, quoted strings, `;`, `{`, `}`, and `#` comments.\nfunction tokenize(text: string): Token[] {\n  const out: Token[] = []\n  let i = 0\n  let line = 1\n  while (i < text.length) {\n    const c = text[i]!\n    if (c === '\\n') {\n      line++\n      i++\n    } else if (/\\s/.test(c)) {\n      i++\n    } else if (c === '#') {\n      while (i < text.length && text[i] !== '\\n') i++\n    } else if (c === ';' || c === '{' || c === '}') {\n      out.push({ text: c, line })\n      i++\n    } else if (c === '\"' || c === \"'\") {\n      const start = line\n      let j = i + 1\n      let s = ''\n      while (j < text.length && text[j] !== c) {\n        if (text[j] === '\\\\' && j + 1 < text.length) j++\n        if (text[j] === '\\n') line++\n        s += text[j]\n        j++\n      }\n      out.push({ text: s, line: start })\n      i = j + 1\n    } else {\n      let j = i\n      while (j < text.length && !/[\\s;{}#]/.test(text[j]!)) j++\n      out.push({ text: text.slice(i, j), line })\n      i = j\n    }\n  }\n  return out\n}\n\ninterface Directive {\n  name: string\n  args: string[]\n  line: number\n  block?: Directive[]\n}\n\nfunction parseBlock(tokens: Token[], pos: { i: number }): Directive[] {\n  const out: Directive[] = []\n  while (pos.i < tokens.length) {\n    const t = tokens[pos.i]!\n    if (t.text === '}') {\n      pos.i++\n      return out\n    }\n    const words: Token[] = []\n    while (pos.i < tokens.length && ![';', '{', '}'].includes(tokens[pos.i]!.text)) {\n      words.push(tokens[pos.i]!)\n      pos.i++\n    }\n    const end = tokens[pos.i]\n    if (!words.length) {\n      pos.i++\n      continue\n    }\n    const d: Directive = { name: words[0]!.text, args: words.slice(1).map((w) => w.text), line: words[0]!.line }\n    if (end?.text === '{') {\n      pos.i++\n      // A Lua block (`content_by_lua_block { … }`) holds Lua, not nginx syntax;\n      // skip to its matching brace.\n      if (d.name.endsWith('_by_lua_block')) {\n        let depth = 1\n        while (pos.i < tokens.length && depth > 0) {\n          if (tokens[pos.i]!.text === '{') depth++\n          else if (tokens[pos.i]!.text === '}') depth--\n          pos.i++\n        }\n      } else {\n        d.block = parseBlock(tokens, pos)\n      }\n    } else if (end?.text === ';') {\n      pos.i++\n    }\n    out.push(d)\n  }\n  return out\n}\n\nexport interface NginxProxy {\n  // The location's path template, or null for a regex location.\n  locationPath: string | null\n  // The proxied hosts (an upstream resolves to its servers), or null when the\n  // proxy_pass host is a variable.\n  hosts: string[] | null\n  target: string\n  line: number\n}\n\nfunction walkDirectives(ds: Directive[], visit: (d: Directive) => void): void {\n  for (const d of ds) {\n    visit(d)\n    if (d.block) walkDirectives(d.block, visit)\n  }\n}\n\n/** The proxy_pass locations one nginx config declares. */\nexport function nginxProxiesFromConfig(text: string): NginxProxy[] {\n  const root = parseBlock(tokenize(text), { i: 0 })\n  const upstreams = new Map<string, string[]>()\n  walkDirectives(root, (d) => {\n    if (d.name !== 'upstream' || !d.args[0] || !d.block) return\n    const hosts = d.block\n      .filter((s) => s.name === 'server' && s.args[0])\n      .map((s) => s.args[0]!.replace(/^[a-z]+:\\/\\//i, '').replace(/:\\d+$/, ''))\n    upstreams.set(d.args[0], hosts)\n  })\n\n  const out: NginxProxy[] = []\n  walkDirectives(root, (d) => {\n    if (d.name !== 'location' || !d.block) return\n    const proxy = d.block.find((s) => s.name === 'proxy_pass' && s.args[0])\n    if (!proxy) return\n    const [modifier, maybePath] = d.args\n    const isRegex = modifier === '~' || modifier === '~*'\n    const rawPath = modifier === '=' || modifier === '^~' || isRegex ? maybePath : modifier\n    const locationPath = !isRegex && rawPath && rawPath.startsWith('/') ? rawPath : null\n    const target = proxy.args[0]!\n    const m = /^https?:\\/\\/([^/:]+)/i.exec(target)\n    let hosts: string[] | null = null\n    if (m && !m[1]!.includes('$')) {\n      const host = m[1]!\n      hosts = upstreams.get(host) ?? [host]\n    }\n    out.push({ locationPath, hosts, target, line: proxy.line })\n  })\n  return out\n}\n\nasync function configFiles(dir: string): Promise<string[]> {\n  const out: string[] = []\n  for (const rel of CONFIG_CANDIDATES) {\n    const p = path.join(dir, rel)\n    if (await fs.stat(p).then((s) => s.isFile()).catch(() => false)) out.push(p)\n  }\n  const confd = path.join(dir, 'conf.d')\n  for (const name of await fs.readdir(confd).catch(() => [] as string[])) {\n    if (name.endsWith('.conf')) out.push(path.join(confd, name))\n  }\n  return out\n}\n\n/** Gateway-style edges from nginx configs in service directories. */\nexport async function addNginxProxies(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  // Host → service: service names, directory names, and aliases.\n  const hostToService = new Map<string, string>()\n  for (const s of services) {\n    hostToService.set(s.pkg.name, s.node.id)\n    hostToService.set(path.basename(s.dir), s.node.id)\n    const node = graph.hasNode(s.node.id) ? (graph.getNodeAttributes(s.node.id) as ServiceNode) : s.node\n    for (const a of node.aliases ?? []) if (!hostToService.has(a)) hostToService.set(a, s.node.id)\n  }\n\n  let nodesAdded = 0\n  let edgesAdded = 0\n  for (const service of services) {\n    for (const abs of await configFiles(service.dir)) {\n      const text = await fs.readFile(abs, 'utf8').catch(() => null)\n      if (text === null || !text.includes('proxy_pass')) continue\n      let proxies: NginxProxy[]\n      try {\n        proxies = nginxProxiesFromConfig(text)\n      } catch (err) {\n        recordExtractionError('nginx config extraction', abs, err)\n        continue\n      }\n      if (proxies.length === 0) continue\n      const relFile = toPosix(path.relative(service.dir, abs))\n      const { fileNodeId, nodesAdded: n, edgesAdded: e } = ensureFileNode(\n        graph,\n        service.pkg.name,\n        service.node.id,\n        relFile,\n      )\n      nodesAdded += n\n      edgesAdded += e\n\n      for (const p of proxies) {\n        const ev = { file: relFile, line: p.line, snippet: snippet(text, p.line) }\n        if (p.locationPath) {\n          const rid = routeId(service.pkg.name, 'ALL', p.locationPath)\n          if (!graph.hasNode(rid)) {\n            const node: RouteNode = {\n              id: rid,\n              type: NodeType.RouteNode,\n              name: `ALL ${p.locationPath}`,\n              service: service.pkg.name,\n              method: 'ALL',\n              pathTemplate: p.locationPath,\n              path: relFile,\n              line: p.line,\n              framework: 'nginx',\n              discoveredVia: 'static',\n            }\n            graph.addNode(rid, node)\n            nodesAdded++\n          }\n          const containsId = extractedEdgeId(service.node.id, rid, EdgeType.CONTAINS)\n          if (!graph.hasEdge(containsId)) {\n            const edge: GraphEdge = {\n              id: containsId,\n              source: service.node.id,\n              target: rid,\n              type: EdgeType.CONTAINS,\n              provenance: Provenance.EXTRACTED,\n              confidence: confidenceForExtracted('structural'),\n              evidence: ev,\n            }\n            graph.addEdgeWithKey(containsId, service.node.id, rid, edge)\n            edgesAdded++\n          }\n        }\n\n        if (p.hosts === null) {\n          noteExtractedDropped({\n            source: fileNodeId,\n            target: 'service:unresolved',\n            type: EdgeType.CALLS,\n            confidence: confidenceForExtracted('reconstructed-approximate'),\n            confidenceKind: 'reconstructed-approximate',\n            evidence: { ...ev, approximate: true, reason: `proxy_pass host isn't literal: ${p.target}` },\n          })\n          continue\n        }\n        for (const host of p.hosts) {\n          const target = hostToService.get(host)\n          if (!target || target === service.node.id) continue\n          const edgeId = makeEdgeId(fileNodeId, target, EdgeType.CALLS)\n          if (graph.hasEdge(edgeId)) continue\n          const edge: GraphEdge = {\n            id: edgeId,\n            source: fileNodeId,\n            target,\n            type: EdgeType.CALLS,\n            provenance: Provenance.EXTRACTED,\n            confidence: confidenceForExtracted('structural'),\n            evidence: { ...ev, ...(p.locationPath ? { pathTemplate: p.locationPath } : {}) },\n          }\n          graph.addEdgeWithKey(edgeId, fileNodeId, target, edge)\n          edgesAdded++\n        }\n      }\n    }\n  }\n  return { nodesAdded, edgesAdded }\n}\n","import path from 'node:path'\nimport Parser from 'tree-sitter'\nimport JavaScript from 'tree-sitter-javascript'\nimport type { EdgeEvidence, GraphEdge, InfraNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  infraId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport { isTestPath, type DiscoveredService } from './shared.js'\nimport { recordExtractionError } from './errors.js'\nimport { GRAMMAR_BY_EXT, parseSource } from './symbols.js'\nimport {\n  ensureFileNode,\n  loadSourceFiles,\n  snippet,\n  toPosix,\n  type SourceFile,\n} from './calls/shared.js'\nimport { foldColumns } from '../columns.js'\n\n// Zod-as-contract declared-shape recognizer (ADR-170). For an app that treats\n// Zod as the source of truth, the declared shape is invisible to the graph — a\n// `const UserSchema` bound to a `z.object` shape is not even a SymbolNode\n// (`collectSymbolDefs` mints a `const` only for a function value or a bare wrapper\n// handed one, never a method-call result). This producer reads the top-level `z.object` / `z.enum` shape\n// literals and mints each as an `InfraNode` of kind `zod-schema`, its fields\n// folded on as `ColumnAttr` — the same column grain a `sql-table` node carries\n// (ADR-157 §3), so a future declared-vs-observed field comparison has a static\n// twin to land on.\n//\n//   A module-level  const UserSchema = z.object  whose body is\n//   { id: z.string(), age: z.number() }  becomes an InfraNode\n//   infra:zod-schema:UserSchema  with columns [id, age].\n//\n// A dedicated `zod-schema` kind — NOT a new NodeType and NOT a SymbolKind\n// (minting Zod consts as symbols would ripple into symbol-edges.ts, symbol-grain\n// OBSERVED fusion, and divergences.ts). `kind` is an open string, so this is a\n// zero-schema-version change, and the read is EXTRACTED-only (no OBSERVED fusion:\n// a runtime parse failure is not observed at field grain today).\n//\n// Scope is deliberately narrow — only a literal top-level `z.object` or `z.enum`\n// shape bound directly to a module-level `const`. Composed / computed forms\n// (`.extend`, `.merge`, `.pick`, unions, refinements, spreads, computed keys)\n// name a partial or dynamic field set, so claiming them would misrepresent the\n// contract — they are left unclaimed rather than guessed, a follow-on rung.\n// Object-literal keys are read the way `calls/drizzle.ts` `columnsFromObject`\n// reads a table's second-argument object.\n//\n// NOTE: comments here name the forms as `z.object` / `z.enum` without a trailing\n// call paren on purpose — the Rule-5 audit (contracts.test.ts) forbids the literal\n// `z.<object|enum>(` token in core/mcp src to stop schema *definitions* leaking in.\n// This file recognizes those shapes, it does not define any.\n\nconst ZOD_IMPORT_RE = /\\bzod\\b/\n// The conventional binding names for the Zod namespace: `import { z } from 'zod'`\n// and `import * as z from 'zod'` (or `zod`). Any other alias is left unclaimed.\nconst ZOD_OBJECTS = new Set(['z', 'zod'])\n\n// A schema recognized in one file: the InfraNode id it implies, its display\n// name, and the declared top-level field set at code-name fidelity.\nexport interface ZodShape {\n  infraId: string\n  name: string\n  fields: string[]\n  evidence: EdgeEvidence\n}\n\nfunction parserForExt(ext: string): Parser {\n  const p = new Parser()\n  p.setLanguage(GRAMMAR_BY_EXT[ext] ?? JavaScript)\n  return p\n}\n\nfunction namedChildren(node: Parser.SyntaxNode): Parser.SyntaxNode[] {\n  const out: Parser.SyntaxNode[] = []\n  for (let i = 0; i < node.namedChildCount; i++) {\n    const c = node.namedChild(i)\n    if (c) out.push(c)\n  }\n  return out\n}\n\n// The literal text inside a `string` node (quotes stripped). Null for a template\n// / interpolated string — never guessed at. (Cloned from calls/drizzle.ts.)\nfunction stringLiteralText(node: Parser.SyntaxNode | null): string | null {\n  if (!node || node.type !== 'string') return null\n  for (const child of namedChildren(node)) {\n    if (child.type === 'string_fragment') return child.text\n  }\n  return '' // an empty '' literal has no string_fragment child\n}\n\n// A pair key → its field-name string (a bare `id:` or a quoted `'id':`).\nfunction keyName(key: Parser.SyntaxNode | null): string | null {\n  if (!key) return null\n  if (key.type === 'property_identifier') return key.text\n  if (key.type === 'string') return stringLiteralText(key)\n  return null\n}\n\n// `z.object` / `z.enum` classification for a call, or null when the callee is\n// not a `<z|zod>.object` / `<z|zod>.enum` member expression.\nfunction zodCallKind(call: Parser.SyntaxNode): 'object' | 'enum' | null {\n  const fn = call.childForFieldName('function')\n  if (fn?.type !== 'member_expression') return null\n  const obj = fn.childForFieldName('object')\n  const prop = fn.childForFieldName('property')\n  if (obj?.type !== 'identifier' || !ZOD_OBJECTS.has(obj.text)) return null\n  if (prop?.type !== 'property_identifier') return null\n  if (prop.text === 'object') return 'object'\n  if (prop.text === 'enum') return 'enum'\n  return null\n}\n\n// The first positional argument node of a call, or null.\nfunction firstArg(call: Parser.SyntaxNode): Parser.SyntaxNode | null {\n  const args = call.childForFieldName('arguments')\n  if (!args) return null\n  return namedChildren(args)[0] ?? null\n}\n\n// The declared field names of a `z.object` shape literal, or null when the\n// object is a composed / computed form (a spread or a computed key) — those name\n// a partial or dynamic set, so the whole schema is left unclaimed.\nfunction fieldsFromObject(obj: Parser.SyntaxNode): string[] | null {\n  const out: string[] = []\n  const seen = new Set<string>()\n  for (const child of namedChildren(obj)) {\n    if (child.type === 'spread_element') return null\n    if (child.type !== 'pair') continue\n    const key = child.childForFieldName('key')\n    if (key?.type === 'computed_property_name') return null\n    const name = keyName(key)\n    if (name && !seen.has(name)) {\n      seen.add(name)\n      out.push(name)\n    }\n  }\n  return out\n}\n\n// The declared member set of a `z.enum` shape literal, or null when a member is\n// not a plain string literal (a spread or a computed value) — left unclaimed.\nfunction membersFromEnum(arr: Parser.SyntaxNode): string[] | null {\n  const out: string[] = []\n  const seen = new Set<string>()\n  for (const child of namedChildren(arr)) {\n    if (child.type !== 'string') return null\n    const value = stringLiteralText(child)\n    if (value !== null && value !== '' && !seen.has(value)) {\n      seen.add(value)\n      out.push(value)\n    }\n  }\n  return out.length > 0 ? out : null\n}\n\n// Every top-level `const <Name>` bound directly to a `z.object` / `z.enum` shape\n// literal in the program, as its schema name and the bound call node. Direct\n// binding is the claim gate: a `.extend` / `.merge` wrapper makes the declarator's\n// value the wrapping call, not the recognized shape call, so a composed form never\n// matches.\nfunction topLevelSchemas(root: Parser.SyntaxNode): { name: string; call: Parser.SyntaxNode }[] {\n  const out: { name: string; call: Parser.SyntaxNode }[] = []\n  for (const stmt of namedChildren(root)) {\n    // Unwrap `export const …` to the declaration it fronts.\n    const decl = stmt.type === 'export_statement' ? stmt.childForFieldName('declaration') : stmt\n    if (decl?.type !== 'lexical_declaration' && decl?.type !== 'variable_declaration') continue\n    for (const declarator of namedChildren(decl)) {\n      if (declarator.type !== 'variable_declarator') continue\n      const name = declarator.childForFieldName('name')\n      const value = declarator.childForFieldName('value')\n      if (name?.type !== 'identifier' || value?.type !== 'call_expression') continue\n      if (zodCallKind(value) === null) continue\n      out.push({ name: name.text, call: value })\n    }\n  }\n  return out\n}\n\nexport function zodShapesFromFile(file: SourceFile, serviceDir: string): ZodShape[] {\n  if (!ZOD_IMPORT_RE.test(file.content)) return []\n  const tree = parseSource(parserForExt(path.extname(file.path)), file.content)\n  const out: ZodShape[] = []\n  const seen = new Set<string>()\n\n  for (const { name, call } of topLevelSchemas(tree.rootNode)) {\n    const kind = zodCallKind(call)\n    const arg = firstArg(call)\n    let fields: string[] | null = null\n    if (kind === 'object' && arg?.type === 'object') fields = fieldsFromObject(arg)\n    else if (kind === 'enum' && arg?.type === 'array') fields = membersFromEnum(arg)\n    // A composed / computed form (fields === null) or a non-literal argument is\n    // left unclaimed — no node, rather than a partial contract.\n    if (fields === null) continue\n    if (seen.has(name)) continue\n    seen.add(name)\n    const line = call.startPosition.row + 1\n    out.push({\n      infraId: infraId('zod-schema', name),\n      name,\n      fields,\n      evidence: {\n        file: path.relative(serviceDir, file.path),\n        line,\n        snippet: snippet(file.content, line),\n      },\n    })\n  }\n  return out\n}\n\nexport interface ZodExtractResult {\n  nodesAdded: number\n  edgesAdded: number\n}\n\n// Standalone extraction phase (registered in extract/index.ts). Gated per service\n// on the `zod` dependency — a service that doesn't declare Zod is skipped. Each\n// recognized schema mints an `infra:zod-schema:<name>` InfraNode with its fields\n// folded on as EXTRACTED `ColumnAttr` (via the read-only `foldColumns`), owned by\n// its file through a `file ──CONTAINS──▶ zod-schema` edge — the same containment\n// spine symbols use under files (file-awareness.md §2). CONTAINS is structural,\n// divergence-excluded, so the node carries no spurious `missing-observed` finding.\nexport async function addZodShapes(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<ZodExtractResult> {\n  let nodesAdded = 0\n  let edgesAdded = 0\n\n  for (const service of services) {\n    const deps = {\n      ...(service.pkg.dependencies ?? {}),\n      ...(service.pkg.devDependencies ?? {}),\n    }\n    if (deps['zod'] === undefined) continue\n\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n    for (const file of files) {\n      // Test scope is excluded from outbound inference the same way the CALLS\n      // producers exclude it (ADR-065 #1) — a fixture schema is not app surface.\n      if (isTestPath(file.path)) continue\n      let shapes: ZodShape[]\n      try {\n        shapes = zodShapesFromFile(file, service.dir)\n      } catch (err) {\n        recordExtractionError('zod shape extraction', file.path, err)\n        continue\n      }\n      for (const shape of shapes) {\n        if (!graph.hasNode(shape.infraId)) {\n          const node: InfraNode = {\n            id: shape.infraId,\n            type: NodeType.InfraNode,\n            name: shape.name,\n            provider: 'self',\n            kind: 'zod-schema',\n          }\n          graph.addNode(node.id, node)\n          nodesAdded++\n        }\n\n        // Fold the declared fields onto the node as EXTRACTED columns (ADR-157 §3\n        // grain), read-only through `foldColumns`. Mutation is allowed here —\n        // extract/* is a lifecycle authority (lifecycle.md §3).\n        if (shape.fields.length > 0) {\n          const node = graph.getNodeAttributes(shape.infraId) as InfraNode\n          if (node.type === NodeType.InfraNode) {\n            graph.replaceNodeAttributes(shape.infraId, {\n              ...node,\n              columns: foldColumns(\n                node.columns,\n                shape.fields,\n                Provenance.EXTRACTED,\n                confidenceForExtracted('structural'),\n              ),\n            })\n          }\n        }\n\n        // File-first ownership (file-awareness.md §1–2): the schema is owned by\n        // the file it is declared in, through a `file ──CONTAINS──▶ zod-schema`\n        // edge alongside the `service ──CONTAINS──▶ file` edge ensureFileNode mints.\n        const relFile = toPosix(shape.evidence.file)\n        const { fileNodeId, nodesAdded: n, edgesAdded: e } = ensureFileNode(\n          graph,\n          service.pkg.name,\n          service.node.id,\n          relFile,\n        )\n        nodesAdded += n\n        edgesAdded += e\n        const edgeId = extractedEdgeId(fileNodeId, shape.infraId, EdgeType.CONTAINS)\n        if (!graph.hasEdge(edgeId)) {\n          const edge: GraphEdge = {\n            id: edgeId,\n            source: fileNodeId,\n            target: shape.infraId,\n            type: EdgeType.CONTAINS,\n            provenance: Provenance.EXTRACTED,\n            confidence: confidenceForExtracted('structural'),\n            evidence: shape.evidence,\n          }\n          graph.addEdgeWithKey(edgeId, fileNodeId, shape.infraId, edge)\n          edgesAdded++\n        }\n      }\n    }\n  }\n\n  return { nodesAdded, edgesAdded }\n}\n","import type { GraphNode, InfraNode } from '@neat.is/types'\nimport { NodeType } from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\nimport type { DiscoveredService } from './shared.js'\nimport { findFirst, readIfExists } from './databases/shared.js'\n\n// firestore.rules guard-set producer (ADR-169). A **standalone** extract phase —\n// not a `calls/` producer — that reads each service's checked-in `firestore.rules`\n// as a declared artifact and folds a `guardedFields` set onto the\n// `firestore-collection` InfraNodes the F1 recognizer (ADR-167) mints in the calls\n// phase. Reading a checked-in rules file as text is the same read-polyglot-as-data\n// discipline `calls/prisma.ts` follows for `schema.prisma`.\n//\n// The `field-guard` policy (ADR-169, packages/core/src/policy.ts) is the consumer:\n// it asserts every client-written column on a collection appears in that\n// collection's `guardedFields`. The load-bearing rule is honesty about what the\n// scanner can and cannot reduce — a guard that is condition-based,\n// function-indirected, or otherwise not an explicit field list leaves the\n// collection INDETERMINATE (no `guardedFields` folded), and the policy then stays\n// silent rather than firing a false positive.\n\nexport const FIRESTORE_COLLECTION_KIND = 'firestore-collection'\n\n// The write-family rule methods. A guard only matters on the write path — a read\n// rule constrains no field the code writes, so it never contributes.\nconst WRITE_METHODS = new Set(['write', 'create', 'update'])\n\n// Strip `//` line and `/* */` block comments, honoring string literals so a `/`\n// inside a quoted path or message is not mistaken for a comment.\nfunction stripComments(src: string): string {\n  let out = ''\n  let i = 0\n  const n = src.length\n  let inStr: string | null = null\n  while (i < n) {\n    const ch = src[i]!\n    const next = src[i + 1]\n    if (inStr) {\n      out += ch\n      if (ch === '\\\\') {\n        out += next ?? ''\n        i += 2\n        continue\n      }\n      if (ch === inStr) inStr = null\n      i++\n      continue\n    }\n    if (ch === '\"' || ch === \"'\") {\n      inStr = ch\n      out += ch\n      i++\n      continue\n    }\n    if (ch === '/' && next === '/') {\n      while (i < n && src[i] !== '\\n') i++\n      continue\n    }\n    if (ch === '/' && next === '*') {\n      i += 2\n      while (i < n && !(src[i] === '*' && src[i + 1] === '/')) i++\n      i += 2\n      continue\n    }\n    out += ch\n    i++\n  }\n  return out\n}\n\nfunction segmentsFromMatchPath(pathToken: string): string[] {\n  return pathToken.split('/').filter((s) => s.length > 0)\n}\n\n// A recursive-wildcard segment — `{document=**}` — matches every path below the match,\n// not one document id. It looks identical to `{orgId}` once wildcards are stripped, so\n// it has to be recognised before the key is built.\nfunction isRecursiveWildcard(seg: string): boolean {\n  return /^\\{[^}]*=\\s*\\*\\*\\}$/.test(seg)\n}\n\n// Normalize a sequence of match-path segments to the collection join key: strip\n// the standard `/databases/{db}/documents` root wrapper, drop `{wildcard}`\n// document-id segments, lowercase the remaining collection names, join with `/`.\n// A nested `/users/{userId}/posts/{postId}` becomes `users/posts`. Field names in\n// the graph are lowercased by `foldColumns`, so the key is lowercased too, keeping\n// the join case-insensitive.\nfunction collectionKeyFromSegments(segments: string[]): string {\n  let segs = segments\n  if (\n    segs.length >= 3 &&\n    segs[0] === 'databases' &&\n    /^\\{.*\\}$/.test(segs[1]!) &&\n    segs[2] === 'documents'\n  ) {\n    segs = segs.slice(3)\n  }\n  return segs\n    .filter((seg) => !/^\\{.*\\}$/.test(seg))\n    .map((seg) => seg.toLowerCase())\n    .join('/')\n}\n\n// A `firestore-collection` InfraNode's `name` is its collection path (F1 names it\n// from the code call site). Normalize it the same way as the rules match path so\n// the two join, regardless of whether F1 carries wildcard segments verbatim.\nfunction collectionKeyFromName(name: string): string {\n  return collectionKeyFromSegments(name.split('/').filter((s) => s.length > 0))\n}\n\n// Pull the explicit field-name literals out of a rule condition — the string\n// arguments to `keys().hasAll([...])` / `hasOnly([...])` / `hasAny([...])`. These\n// are the fields the rules explicitly name; any other condition shape (a function\n// call, an `request.auth` check, a comparison) names no field and contributes\n// nothing. Field names are lowercased to match `foldColumns`.\n//\n// A **negated** call is skipped rather than read. `!keys().hasAny(['ownerId'])` is a\n// denylist: it names the fields a write may NOT carry, which is the inverse of the\n// set this function exists to collect. Reading it as an allowlist would record the\n// forbidden fields as guarded and then flag every legitimately written field as\n// unguarded — a false claim, which is the one thing the never-guess bar forbids\n// (static-extraction.md §Firestore rules). Skipping it contributes no fields, so a\n// rule whose only field reference is negated reduces to nothing and its collection\n// goes indeterminate — silence, which is the documented degradation.\n//\n// A positive call alongside a negated one still counts: `hasOnly([a,b]) && !hasAny([c])`\n// names a real allowlist in its first clause.\nfunction fieldsFromCondition(cond: string): string[] {\n  const out: string[] = []\n  const callRe = /(!\\s*)?\\b(?:hasAll|hasOnly|hasAny)\\s*\\(\\s*\\[([^\\]]*)\\]\\s*\\)/g\n  let m: RegExpExecArray | null\n  while ((m = callRe.exec(cond)) !== null) {\n    // The `!` can sit anywhere left of the receiver chain (`!request.resource...hasAny`),\n    // so the capture above only catches it when adjacent. Walk back over the receiver\n    // to find a negation that applies to this call.\n    if (m[1] !== undefined || isNegatedAt(cond, m.index)) continue\n    const inner = m[2]!\n    const litRe = /'([^']*)'|\"([^\"]*)\"/g\n    let lm: RegExpExecArray | null\n    while ((lm = litRe.exec(inner)) !== null) {\n      const val = lm[1] ?? lm[2] ?? ''\n      if (val.length > 0) out.push(val.toLowerCase())\n    }\n  }\n  return out\n}\n\n// True when the call starting at `idx` is negated. Firestore conditions put the `!`\n// before the whole receiver chain — `!request.resource.data.keys().hasAny([...])` — so\n// the marker is not adjacent to the matched call. Walk left over the chain (identifiers,\n// dots, and the balanced `()` of intermediate calls like `keys()`) and report whether\n// the first character that isn't part of it is a `!`.\nfunction isNegatedAt(cond: string, idx: number): boolean {\n  let i = idx - 1\n  while (i >= 0) {\n    const ch = cond[i]!\n    if (ch === ')') {\n      // Skip a balanced intermediate call, e.g. the `()` of `.keys()`.\n      let depth = 1\n      i--\n      while (i >= 0 && depth > 0) {\n        if (cond[i] === ')') depth++\n        else if (cond[i] === '(') depth--\n        i--\n      }\n      continue\n    }\n    if (/[A-Za-z0-9_$.\\]['\"]/.test(ch) || ch === ' ') {\n      i--\n      continue\n    }\n    return ch === '!'\n  }\n  return false\n}\n\n// Parse a `firestore.rules` file into a map of collection key → the explicit set\n// of guarded fields on its write path. Pure over the file content so a test can\n// drive it without touching the filesystem, mirroring `prismaColumnsFromSchema`.\n//\n// A collection appears in the result ONLY when at least one write-family rule\n// reduces to an explicit field list AND no write-family rule on the same\n// collection is non-reducible. Any condition-based / function-indirected write\n// guard poisons the collection to INDETERMINATE — it is omitted, and the check\n// stays silent. This is the conservative choice: we opine only where the rules\n// give us an explicit set to opine with.\nexport function parseFirestoreRules(content: string): Map<string, string[]> {\n  const src = stripComments(content)\n\n  // One positional scan interleaving, in document order: a `match <path> {`\n  // opener (which consumes its own brace), an `allow …;` statement, a bare `{`\n  // (a `service {` / `function …() {` block), and a `}` closer. The wildcard\n  // `{userId}` inside a match path is matched as part of the path, so it is not\n  // mistaken for the block-opening brace.\n  const tokenRe = /match\\s+((?:\\/(?:\\{[^}]*\\}|[^\\s/{}]+))+)\\s*\\{|allow\\b([^;{}]*);|(\\{)|(\\})/g\n\n  interface Frame {\n    depth: number\n    segs: string[]\n    /** True when this match path contains a recursive wildcard (`{document=**}`). */\n    recursive: boolean\n  }\n  const matchStack: Frame[] = []\n  let depth = 0\n\n  const determinate = new Map<string, Set<string>>()\n  const indeterminate = new Set<string>()\n\n  const currentKey = (): string =>\n    collectionKeyFromSegments(matchStack.flatMap((f) => f.segs))\n\n  let m: RegExpExecArray | null\n  while ((m = tokenRe.exec(src)) !== null) {\n    if (m[1] !== undefined) {\n      // `match <path> {` — opens a block and consumes its brace.\n      depth++\n      const segs = segmentsFromMatchPath(m[1])\n      matchStack.push({ depth, segs, recursive: segs.some(isRecursiveWildcard) })\n      continue\n    }\n    if (m[2] !== undefined) {\n      // `allow <methods> [: if <cond>] ;`\n      const body = m[2]\n      const colon = body.indexOf(':')\n      const methodsPart = colon === -1 ? body : body.slice(0, colon)\n      const methods = methodsPart\n        .split(',')\n        .map((s) => s.trim().toLowerCase())\n        .filter(Boolean)\n      if (!methods.some((mm) => WRITE_METHODS.has(mm))) continue\n      const key = currentKey()\n      if (key.length === 0) continue\n      // A recursive wildcard spans every collection below the match, so whatever field\n      // list the rule names cannot be attributed to the one collection the stripped key\n      // happens to spell — `/orgs/{document=**}` strips to `orgs` exactly as\n      // `/orgs/{orgId}` does, and filing a sweeping rule under the narrow path is a\n      // false claim. Indeterminate, per the never-guess bar.\n      if (matchStack.some((f) => f.recursive)) {\n        indeterminate.add(key)\n        continue\n      }\n      const cond = colon === -1 ? '' : body.slice(colon + 1)\n      const fields = fieldsFromCondition(cond)\n      if (fields.length > 0) {\n        const set = determinate.get(key) ?? new Set<string>()\n        for (const f of fields) set.add(f)\n        determinate.set(key, set)\n      } else {\n        // A write-family rule with no reducible field list — condition-based or\n        // function-indirected. Indeterminate.\n        indeterminate.add(key)\n      }\n      continue\n    }\n    if (m[3] !== undefined) {\n      // A bare `{` (a `service {` / `function {` block).\n      depth++\n      continue\n    }\n    if (m[4] !== undefined) {\n      // A `}` closer. Pop the match frame opened at this depth, if any.\n      if (matchStack.length > 0 && matchStack[matchStack.length - 1]!.depth === depth) {\n        matchStack.pop()\n      }\n      depth--\n      continue\n    }\n  }\n\n  const out = new Map<string, string[]>()\n  for (const [key, set] of determinate) {\n    if (indeterminate.has(key)) continue\n    out.set(key, [...set].sort())\n  }\n  return out\n}\n\n// Standalone extract phase (ADR-169). Reads every service's `firestore.rules` and\n// folds the parsed `guardedFields` onto the matching `firestore-collection`\n// InfraNodes. Adds no nodes or edges — it only enriches existing ones — so it\n// contributes nothing to the extract counts. Inert until the F1 recognizer\n// (ADR-167) has minted `firestore-collection` nodes; when it hasn't, there is\n// nothing to fold onto and this is a no-op. Mutation is allowed here — extract/*\n// is a lifecycle authority (lifecycle.md §3).\nexport async function addFirestoreRules(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n): Promise<{ nodesAdded: number; edgesAdded: number }> {\n  // Merge every service's parsed rules into one collection-key → guarded-fields\n  // map. A monorepo can hold a single `firestore.rules` governing collections\n  // named across services; folding by collection key keeps the join independent\n  // of which service's calls minted the node.\n  const guards = new Map<string, Set<string>>()\n  for (const service of services) {\n    const rulesPath = await findFirst(service.dir, ['firestore.rules'])\n    if (!rulesPath) continue\n    const content = await readIfExists(rulesPath)\n    if (!content) continue\n    for (const [key, fields] of parseFirestoreRules(content)) {\n      const set = guards.get(key) ?? new Set<string>()\n      for (const f of fields) set.add(f)\n      guards.set(key, set)\n    }\n  }\n  if (guards.size === 0) return { nodesAdded: 0, edgesAdded: 0 }\n\n  graph.forEachNode((id, attrs) => {\n    const node = attrs as GraphNode\n    if (node.type !== NodeType.InfraNode) return\n    if (node.kind !== FIRESTORE_COLLECTION_KIND) return\n    const fields = guards.get(collectionKeyFromName(node.name))\n    if (!fields || fields.size === 0) return\n    graph.replaceNodeAttributes(id, {\n      ...node,\n      guardedFields: [...fields].sort(),\n    } as InfraNode)\n  })\n\n  return { nodesAdded: 0, edgesAdded: 0 }\n}\n","import { promises as fs } from 'node:fs'\nimport path from 'node:path'\nimport { parse as parseToml } from 'smol-toml'\nimport { parse as parseYaml } from 'yaml'\nimport type { DependencyNode, GraphEdge, GraphNode, ServiceNode } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  dependencyId,\n  isDependencyNodeId,\n  isDependencySymbolId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { exists, makeEdgeId, type DiscoveredService } from '../shared.js'\nimport { recordExtractionError } from '../errors.js'\nimport { resolveGoMod } from './go-mod.js'\nimport { resolveNpmLock } from './npm-lock.js'\nimport { resolvePnpmLock } from './pnpm-lock.js'\nimport { resolveYarnLock } from './yarn-lock.js'\nimport {\n  resolvePoetryLock,\n  resolveRequirementsPins,\n  resolveUvLock,\n  type PoetryProject,\n} from './python-lock.js'\nimport { purlFor, type ResolvedDependency, type ServiceInventory } from './resolved.js'\n\n// Dependency inventory (ADR-274, docs/contracts/dependency-inventory.md). Reads\n// each service's lockfile and mints one DependencyNode per resolved package\n// version, plus a `service ──DEPENDS_ON──▶ dep` edge carrying the per-service\n// facts. The producer owns those edges: each pass replaces a service's set, and\n// a version no service depends on any more is dropped.\n\nconst EXACT_SEMVER = /^v?\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.-]+)?$/\n\nasync function readText(p: string): Promise<string | null> {\n  try {\n    return await fs.readFile(p, 'utf8')\n  } catch {\n    return null\n  }\n}\n\n// The JS lockfiles NEAT reads, in the order it prefers them when one directory\n// holds more than one.\nconst JS_LOCKFILES = ['package-lock.json', 'pnpm-lock.yaml', 'yarn.lock'] as const\ntype JsLockfile = (typeof JS_LOCKFILES)[number]\n\n// The nearest JS lockfile at or above the service directory, without leaving the\n// scan root (a workspace's lockfile sits at the workspace root).\nasync function nearestJsLock(serviceDir: string, scanPath: string): Promise<{ path: string; kind: JsLockfile } | null> {\n  const root = path.resolve(scanPath)\n  let dir = path.resolve(serviceDir)\n  for (;;) {\n    for (const kind of JS_LOCKFILES) {\n      const candidate = path.join(dir, kind)\n      if (await exists(candidate)) return { path: candidate, kind }\n    }\n    if (dir === root || !dir.startsWith(root)) return null\n    const up = path.dirname(dir)\n    if (up === dir) return null\n    dir = up\n  }\n}\n\nfunction exactPins(deps: Record<string, string> | undefined, ecosystem: ResolvedDependency['ecosystem']): ResolvedDependency[] {\n  return Object.entries(deps ?? {})\n    .filter(([, v]) => EXACT_SEMVER.test(v.trim()))\n    .map(([name, v]) => ({\n      ecosystem,\n      name,\n      version: v.trim().replace(/^v/, ''),\n      scope: 'direct' as const,\n      dev: false,\n      introducedBy: [],\n    }))\n}\n\nasync function npmInventory(svc: DiscoveredService, scanPath: string): Promise<ServiceInventory | null> {\n  const lock = await nearestJsLock(svc.dir, scanPath)\n  if (lock) {\n    const raw = await readText(lock.path)\n    if (raw !== null) {\n      try {\n        const serviceKey = path.relative(path.dirname(lock.path), svc.dir).split(path.sep).join('/')\n        const inv =\n          lock.kind === 'package-lock.json'\n            ? resolveNpmLock(JSON.parse(raw), lock.path, serviceKey, svc.pkg)\n            : lock.kind === 'pnpm-lock.yaml'\n              ? resolvePnpmLock(parseYaml(raw), lock.path, serviceKey)\n              : resolveYarnLock(raw, lock.path, svc.pkg, { ownsLockfile: serviceKey === '' })\n        if (inv) return inv\n      } catch (err) {\n        recordExtractionError('dependencies', path.relative(scanPath, lock.path), err)\n      }\n    }\n  }\n  const pins = exactPins(svc.pkg.dependencies, 'npm')\n  return { source: path.join(svc.dir, 'package.json'), resolution: 'partial', dependencies: pins }\n}\n\nasync function pythonInventory(svc: DiscoveredService, scanPath: string): Promise<ServiceInventory | null> {\n  const uvPath = path.join(svc.dir, 'uv.lock')\n  const uv = await readText(uvPath)\n  if (uv !== null) {\n    try {\n      const inv = resolveUvLock(parseToml(uv) as never, uvPath, svc.node.name)\n      if (inv) return inv\n    } catch (err) {\n      recordExtractionError('dependencies', path.relative(scanPath, uvPath), err)\n    }\n  }\n  const poetryPath = path.join(svc.dir, 'poetry.lock')\n  const poetry = await readText(poetryPath)\n  if (poetry !== null) {\n    try {\n      const pyprojectRaw = await readText(path.join(svc.dir, 'pyproject.toml'))\n      const pyproject = (pyprojectRaw ? parseToml(pyprojectRaw) : {}) as PoetryProject\n      return resolvePoetryLock(parseToml(poetry) as never, poetryPath, pyproject)\n    } catch (err) {\n      recordExtractionError('dependencies', path.relative(scanPath, poetryPath), err)\n    }\n  }\n  const reqPath = path.join(svc.dir, 'requirements.txt')\n  const req = await readText(reqPath)\n  if (req !== null) return resolveRequirementsPins(req, reqPath)\n  return null\n}\n\n// The nearest go.mod at or above the service directory: a Go binary under\n// cmd/<name> shares its module root's go.mod (ADR-255).\nasync function goInventory(svc: DiscoveredService, scanPath: string): Promise<ServiceInventory | null> {\n  const root = path.resolve(scanPath)\n  let dir = path.resolve(svc.dir)\n  for (;;) {\n    const modPath = path.join(dir, 'go.mod')\n    const source = await readText(modPath)\n    if (source !== null) return resolveGoMod(source, modPath)\n    if (dir === root || !dir.startsWith(root)) return null\n    const up = path.dirname(dir)\n    if (up === dir) return null\n    dir = up\n  }\n}\n\nasync function inventoryFor(svc: DiscoveredService, scanPath: string): Promise<ServiceInventory | null> {\n  if (svc.node.language === 'python') return pythonInventory(svc, scanPath)\n  if (svc.node.language === 'go') return goInventory(svc, scanPath)\n  if (await exists(path.join(svc.dir, 'package.json'))) return npmInventory(svc, scanPath)\n  // Other ecosystems (Go, then the rest) join in later passes.\n  return null\n}\n\nexport interface DependencyPhaseResult {\n  nodesAdded: number\n  edgesAdded: number\n  edgesRemoved: number\n  nodesRemoved: number\n}\n\nexport async function addDependencies(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n  scanPath: string,\n): Promise<DependencyPhaseResult> {\n  const result: DependencyPhaseResult = { nodesAdded: 0, edgesAdded: 0, edgesRemoved: 0, nodesRemoved: 0 }\n\n  for (const svc of services) {\n    const svcId = svc.node.id\n    if (!graph.hasNode(svcId)) continue\n    let inv: ServiceInventory | null\n    try {\n      inv = await inventoryFor(svc, scanPath)\n    } catch (err) {\n      recordExtractionError('dependencies', path.relative(scanPath, svc.dir) || '.', err)\n      continue\n    }\n    if (!inv) continue\n\n    const evidenceFile = path.relative(scanPath, inv.source).split(path.sep).join('/')\n    const wanted = new Map<string, ResolvedDependency>()\n    for (const d of inv.dependencies) wanted.set(dependencyId(d.ecosystem, d.name, d.version), d)\n\n    // Replace this service's dependency edges with the ones this pass resolved.\n    for (const edgeId of [...graph.outboundEdges(svcId)]) {\n      const e = graph.getEdgeAttributes(edgeId) as GraphEdge\n      if (e.type !== EdgeType.DEPENDS_ON || e.provenance !== Provenance.EXTRACTED) continue\n      if (!isDependencyNodeId(e.target) || wanted.has(e.target)) continue\n      graph.dropEdge(edgeId)\n      result.edgesRemoved++\n    }\n\n    for (const [depId, d] of wanted) {\n      if (!graph.hasNode(depId)) {\n        const node: DependencyNode = {\n          id: depId,\n          type: NodeType.DependencyNode,\n          name: d.name,\n          ecosystem: d.ecosystem,\n          version: d.version,\n          purl: purlFor(d.ecosystem, d.name, d.version),\n          discoveredVia: 'static',\n        }\n        graph.addNode(depId, node as GraphNode)\n        result.nodesAdded++\n      }\n      const edgeId = makeEdgeId(svcId, depId, EdgeType.DEPENDS_ON)\n      const edge: GraphEdge = {\n        id: edgeId,\n        source: svcId,\n        target: depId,\n        type: EdgeType.DEPENDS_ON,\n        provenance: Provenance.EXTRACTED,\n        confidence: confidenceForExtracted('structural'),\n        evidence: { file: evidenceFile },\n        dependency: { scope: d.scope, dev: d.dev, introducedBy: d.introducedBy },\n      }\n      if (graph.hasEdge(edgeId)) {\n        graph.replaceEdgeAttributes(edgeId, edge)\n      } else {\n        graph.addEdgeWithKey(edgeId, svcId, depId, edge)\n        result.edgesAdded++\n      }\n    }\n\n    graph.mergeNodeAttributes(svcId, { dependencyResolution: inv.resolution } as Partial<ServiceNode>)\n  }\n\n  // A version no service depends on any more leaves the graph. Only DEPENDS_ON\n  // counts: a first-party IMPORTS edge (imports-to-deps.ts) is rebuilt after this\n  // phase, so a leftover one must not keep a dropped version alive.\n  const orphans: string[] = []\n  graph.forEachNode((id, attrs) => {\n    if ((attrs as GraphNode).type !== NodeType.DependencyNode) return\n    const depended = graph.someInEdge(id, (_e, a) => (a as GraphEdge).type === EdgeType.DEPENDS_ON)\n    if (!depended) orphans.push(id)\n  })\n  for (const id of orphans) {\n    // Its extracted code goes with it (dependency-symbols, ADR-274).\n    for (const sym of graph.outNeighbors(id).filter(isDependencySymbolId)) {\n      graph.dropNode(sym)\n      result.nodesRemoved++\n    }\n    graph.dropNode(id)\n    result.nodesRemoved++\n  }\n  return result\n}\n","import type { ResolvedDependency, ServiceInventory } from './resolved.js'\n\n// go.mod as a resolved inventory (dependency-inventory.md §3). Since Go 1.17 a\n// module's go.mod lists every module its build needs. Direct requirements carry\n// no comment, and the rest are marked `// indirect`. So for `go >= 1.17` the\n// require list is the resolved build list. Before 1.17 indirect requirements\n// can be missing, and the inventory is `partial`.\n//\n// go.mod doesn't record which direct requirement pulls an indirect one in (that\n// takes `go mod graph`), so `introducedBy` stays empty for Go. `replace`\n// directives that point at another module version substitute that version, and\n// ones that point at a local path are first-party code and drop out.\n//\n// The Go standard library is not listed: the toolchain that actually builds the\n// service isn't recorded in go.mod (the `go` line is a minimum), so NEAT doesn't\n// guess it.\n\ninterface Requirement {\n  module: string\n  version: string\n  indirect: boolean\n}\n\nfunction stripComment(line: string): { code: string; comment: string } {\n  const at = line.indexOf('//')\n  return at < 0 ? { code: line.trim(), comment: '' } : { code: line.slice(0, at).trim(), comment: line.slice(at + 2).trim() }\n}\n\nfunction parseDirectiveLines(source: string, directive: 'require' | 'replace'): Array<{ code: string; comment: string }> {\n  const out: Array<{ code: string; comment: string }> = []\n  const lines = source.split(/\\r?\\n/)\n  for (let i = 0; i < lines.length; i++) {\n    const { code, comment } = stripComment(lines[i] ?? '')\n    if (code === `${directive} (`) {\n      for (i++; i < lines.length; i++) {\n        const inner = stripComment(lines[i] ?? '')\n        if (inner.code === ')') break\n        if (inner.code) out.push(inner)\n      }\n      continue\n    }\n    if (code.startsWith(`${directive} `)) out.push({ code: code.slice(directive.length + 1).trim(), comment })\n  }\n  return out\n}\n\nfunction goVersionAtLeast(v: string | undefined, major: number, minor: number): boolean {\n  const m = /^(\\d+)\\.(\\d+)/.exec(v ?? '')\n  if (!m) return false\n  const [maj, min] = [Number(m[1]), Number(m[2])]\n  return maj > major || (maj === major && min >= minor)\n}\n\n// OSV's Go ranges carry versions without the `v` prefix.\nfunction osvVersion(v: string): string {\n  return v.startsWith('v') ? v.slice(1) : v\n}\n\nexport function resolveGoMod(source: string, sourcePath: string): ServiceInventory | null {\n  const goLine = /^\\s*go\\s+(\\S+)/m.exec(source)?.[1]\n  if (!/^\\s*module\\s+\\S+/m.test(source)) return null\n\n  const requirements: Requirement[] = []\n  for (const { code, comment } of parseDirectiveLines(source, 'require')) {\n    const m = /^(\\S+)\\s+(v\\S+)$/.exec(code)\n    if (m?.[1] && m[2]) requirements.push({ module: m[1], version: m[2], indirect: /\\bindirect\\b/.test(comment) })\n  }\n\n  // `old [v] => new v` substitutes a module version. `old [v] => ./path` is a local\n  // replacement: first-party code, not a dependency.\n  const replaced = new Map<string, { module: string; version: string } | 'local'>()\n  for (const { code } of parseDirectiveLines(source, 'replace')) {\n    const m = /^(\\S+)(?:\\s+(v\\S+))?\\s*=>\\s*(\\S+)(?:\\s+(v\\S+))?$/.exec(code)\n    if (!m?.[1] || !m[3]) continue\n    const key = m[2] ? `${m[1]}@${m[2]}` : m[1]\n    replaced.set(key, m[4] ? { module: m[3], version: m[4] } : 'local')\n  }\n\n  const dependencies: ResolvedDependency[] = []\n  for (const r of requirements) {\n    const rep = replaced.get(`${r.module}@${r.version}`) ?? replaced.get(r.module)\n    if (rep === 'local') continue\n    const target = rep ?? { module: r.module, version: r.version }\n    dependencies.push({\n      ecosystem: 'Go',\n      name: target.module,\n      version: osvVersion(target.version),\n      scope: r.indirect ? 'transitive' : 'direct',\n      dev: false,\n      introducedBy: [],\n    })\n  }\n  return {\n    source: sourcePath,\n    resolution: goVersionAtLeast(goLine, 1, 17) ? 'complete' : 'partial',\n    dependencies,\n  }\n}\n","import path from 'node:path'\nimport { TreeFold, type ServiceInventory } from './resolved.js'\n\n// package-lock.json v2/v3 (dependency-inventory.md §3). The `packages` map is\n// keyed by install path: \"\" for the lockfile's root, \"node_modules/a\",\n// \"node_modules/a/node_modules/b\", and a workspace's own path (\"packages/api\").\n// v1 lockfiles (npm 6) have no `packages` map and are reported as unsupported,\n// so the service falls back to exact pins.\n\ninterface LockEntry {\n  name?: string\n  version?: string\n  link?: boolean\n  resolved?: string\n  dev?: boolean\n  dependencies?: Record<string, string>\n  optionalDependencies?: Record<string, string>\n  peerDependencies?: Record<string, string>\n  peerDependenciesMeta?: Record<string, { optional?: boolean }>\n}\n\ninterface PackageLock {\n  lockfileVersion?: number\n  packages?: Record<string, LockEntry>\n}\n\nexport interface ServiceManifest {\n  dependencies?: Record<string, string>\n  optionalDependencies?: Record<string, string>\n  devDependencies?: Record<string, string>\n}\n\n// The install path one level up the node_modules chain: \"a/node_modules/b\" → \"a\",\n// \"node_modules/a\" → \"\", \"packages/api\" → \"\".\nfunction parentKey(key: string): string {\n  const at = key.lastIndexOf('node_modules/')\n  if (at <= 0) return ''\n  return key.slice(0, at - 1)\n}\n\n// Node's resolution algorithm, over lockfile keys: look in the requester's own\n// node_modules, then each ancestor's, ending at the root.\nfunction locate(packages: Record<string, LockEntry>, fromKey: string, name: string): string | null {\n  let base = fromKey\n  for (;;) {\n    const candidate = `${base ? `${base}/` : ''}node_modules/${name}`\n    if (packages[candidate]) return candidate\n    if (base === '') return null\n    base = parentKey(base)\n  }\n}\n\nfunction nameOf(key: string, entry: LockEntry): string {\n  if (entry.name) return entry.name\n  const at = key.lastIndexOf('node_modules/')\n  return at >= 0 ? key.slice(at + 'node_modules/'.length) : path.posix.basename(key)\n}\n\nfunction childNames(entry: LockEntry): string[] {\n  const peers = Object.keys(entry.peerDependencies ?? {}).filter(\n    (n) => !entry.peerDependenciesMeta?.[n]?.optional,\n  )\n  return [\n    ...Object.keys(entry.dependencies ?? {}),\n    ...Object.keys(entry.optionalDependencies ?? {}),\n    ...peers,\n  ]\n}\n\n/**\n * Resolve one service's dependency tree from a package-lock.json. `serviceKey`\n * is the service directory relative to the lockfile's directory (\"\" when they're\n * the same). Returns null when the lockfile can't answer for this service: a v1\n * lockfile, or a workspace the lockfile doesn't list.\n */\nexport function resolveNpmLock(\n  lock: PackageLock,\n  lockPath: string,\n  serviceKey: string,\n  manifest: ServiceManifest,\n): ServiceInventory | null {\n  const packages = lock.packages\n  if (!packages || (lock.lockfileVersion ?? 0) < 2) return null\n  if (serviceKey !== '' && !packages[serviceKey]) return null\n\n  const fold = new TreeFold('npm')\n  const roots: Array<{ name: string; dev: boolean }> = [\n    ...Object.keys(manifest.dependencies ?? {}).map((name) => ({ name, dev: false })),\n    ...Object.keys(manifest.optionalDependencies ?? {}).map((name) => ({ name, dev: false })),\n    ...Object.keys(manifest.devDependencies ?? {})\n      .filter((n) => !(manifest.dependencies ?? {})[n])\n      .map((name) => ({ name, dev: true })),\n  ]\n\n  // A workspace link resolves to the linked package's own path. Workspace\n  // packages are first-party code, so they aren't dependencies themselves, but\n  // what they depend on runs in the service, so the walk goes through them.\n  const follow = (key: string): { key: string; entry: LockEntry } | null => {\n    const entry = packages[key]\n    if (!entry) return null\n    if (entry.link && entry.resolved) {\n      const target = packages[entry.resolved]\n      return target ? { key: entry.resolved, entry: { ...target, link: true } } : null\n    }\n    return { key, entry }\n  }\n\n  for (const root of roots) {\n    const start = locate(packages, serviceKey, root.name)\n    if (!start) continue\n    const queue: Array<{ key: string; isDirect: boolean }> = [{ key: start, isDirect: true }]\n    const seen = new Set<string>()\n    while (queue.length > 0) {\n      const { key, isDirect } = queue.shift()!\n      if (seen.has(key)) continue\n      seen.add(key)\n      const hit = follow(key)\n      if (!hit) continue\n      const { entry } = hit\n      if (!entry.link && entry.version) {\n        const changed = fold.visit(nameOf(key, entry), entry.version, {\n          direct: root.name,\n          dev: root.dev,\n          isDirect,\n        })\n        // Already folded under this root with nothing new to record: its subtree\n        // was walked from here before.\n        if (!changed && !isDirect) continue\n      }\n      for (const child of childNames(entry)) {\n        const childKey = locate(packages, hit.key, child)\n        if (childKey && !seen.has(childKey)) queue.push({ key: childKey, isDirect: false })\n      }\n    }\n  }\n\n  return { source: lockPath, resolution: 'complete', dependencies: fold.result() }\n}\n","// One resolved dependency of one service, before it becomes graph state\n// (dependency-inventory.md §1–2). Parsers produce these; index.ts turns them into\n// a DependencyNode plus the service's DEPENDS_ON edge.\nexport interface ResolvedDependency {\n  ecosystem: 'npm' | 'PyPI' | 'Go'\n  name: string\n  version: string\n  scope: 'direct' | 'transitive'\n  dev: boolean\n  // Direct dependency names whose subtree pulls this one in. Empty when direct.\n  introducedBy: string[]\n}\n\nexport interface ServiceInventory {\n  // Absolute path of the lockfile or manifest that resolved the inventory.\n  source: string\n  resolution: 'complete' | 'partial'\n  dependencies: ResolvedDependency[]\n}\n\n// Walks a resolved dependency tree from a service's direct dependencies and\n// folds every path into one record per (name, version). A version is `dev` only\n// when every path to it starts at a dev dependency, and `introducedBy` collects\n// the direct dependencies whose subtree reaches it.\nexport class TreeFold {\n  private readonly byKey = new Map<string, ResolvedDependency & { prodPath: boolean }>()\n\n  constructor(private readonly ecosystem: ResolvedDependency['ecosystem']) {}\n\n  visit(name: string, version: string, via: { direct: string; dev: boolean; isDirect: boolean }): boolean {\n    const key = `${name}@${version}`\n    const cur = this.byKey.get(key)\n    if (!cur) {\n      this.byKey.set(key, {\n        ecosystem: this.ecosystem,\n        name,\n        version,\n        scope: via.isDirect ? 'direct' : 'transitive',\n        dev: via.dev,\n        introducedBy: via.isDirect ? [] : [via.direct],\n        prodPath: !via.dev,\n      })\n      return true\n    }\n    let changed = false\n    if (via.isDirect && cur.scope !== 'direct') {\n      cur.scope = 'direct'\n      changed = true\n    }\n    if (!via.isDirect && !cur.introducedBy.includes(via.direct)) {\n      cur.introducedBy.push(via.direct)\n      changed = true\n    }\n    if (!via.dev && !cur.prodPath) {\n      cur.prodPath = true\n      cur.dev = false\n      changed = true\n    }\n    return changed\n  }\n\n  // A locked package no walk reached (an unrecorded peer). Kept as transitive\n  // with no known introducer, and treated as production, the conservative\n  // reading. Never overrides a version a walk already reached.\n  visitUnattributed(name: string, version: string): void {\n    const key = `${name}@${version}`\n    if (this.byKey.has(key)) return\n    this.byKey.set(key, {\n      ecosystem: this.ecosystem,\n      name,\n      version,\n      scope: 'transitive',\n      dev: false,\n      introducedBy: [],\n      prodPath: true,\n    })\n  }\n\n  result(): ResolvedDependency[] {\n    return [...this.byKey.values()]\n      .map(({ prodPath: _p, ...d }) => ({\n        ...d,\n        // A direct dependency is introduced by nothing, even if another direct\n        // dependency also pulls it in.\n        introducedBy: d.scope === 'direct' ? [] : [...d.introducedBy].sort(),\n      }))\n      .sort((a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version))\n  }\n}\n\n// PEP 503 name normalization. OSV keys PyPI advisories by the normalized name,\n// so the node's name is normalized too, and `Jinja2`, `jinja2` and `jinja_2`\n// can't become three nodes.\nexport function normalizePypiName(name: string): string {\n  return name.replace(/[-_.]+/g, '-').toLowerCase()\n}\n\nexport function purlFor(ecosystem: ResolvedDependency['ecosystem'], name: string, version: string): string {\n  if (ecosystem === 'npm') {\n    const encoded = name.startsWith('@') ? `%40${name.slice(1)}` : name\n    return `pkg:npm/${encoded}@${version}`\n  }\n  if (ecosystem === 'Go') return `pkg:golang/${name}@v${version}`\n  return `pkg:pypi/${name}@${version}`\n}\n","import path from 'node:path'\nimport { TreeFold, type ServiceInventory } from './resolved.js'\n\n// pnpm-lock.yaml, lockfile versions 6 and 9 (dependency-inventory.md §3).\n//\n// `importers` maps each workspace path (\".\" for the root) to its direct\n// dependencies, each `{ specifier, version }`. The tree lives in `snapshots`\n// (v9) or `packages` (v6, keys prefixed with \"/\"), keyed by\n// `name@version(peer@x)…`. The peer suffix belongs to the key, so the same version\n// installed against two peer sets is two keys and one DependencyNode.\n// A `link:` version is a workspace package: first-party code, walked through\n// rather than counted.\n\ntype DepMap = Record<string, string | { specifier?: string; version: string }>\n\ninterface Importer {\n  dependencies?: DepMap\n  optionalDependencies?: DepMap\n  devDependencies?: DepMap\n}\n\ninterface SnapshotEntry {\n  dependencies?: Record<string, string>\n  optionalDependencies?: Record<string, string>\n}\n\ninterface PnpmLock extends Importer {\n  lockfileVersion?: string | number\n  importers?: Record<string, Importer>\n  packages?: Record<string, SnapshotEntry>\n  snapshots?: Record<string, SnapshotEntry>\n}\n\nfunction versionRef(v: DepMap[string]): string {\n  return typeof v === 'string' ? v : v.version\n}\n\n// The snapshot key a dependency reference points at. Usually `name@ref`. An\n// alias (`npm:other@1.0.0`, or v9's bare `other@1.0.0`) and a v6 path (`/x@1.0.0`)\n// already name the target package.\nfunction snapshotKey(name: string, ref: string): string {\n  if (ref.startsWith('/')) return ref.slice(1)\n  if (ref.startsWith('npm:')) return ref.slice(4)\n  if (/^[^\\d]/.test(ref) && ref.includes('@')) return ref\n  return `${name}@${ref}`\n}\n\n// `@scope/name@1.2.3(peer@1)` → { name: '@scope/name', version: '1.2.3' }.\nfunction parseKey(key: string): { name: string; version: string } | null {\n  const at = key.indexOf('@', key.startsWith('@') ? 1 : 0)\n  if (at <= 0) return null\n  const rest = key.slice(at + 1)\n  const paren = rest.indexOf('(')\n  const version = paren >= 0 ? rest.slice(0, paren) : rest\n  return version ? { name: key.slice(0, at), version } : null\n}\n\nfunction children(entry: SnapshotEntry | Importer): Array<[string, string]> {\n  return [\n    ...Object.entries(entry.dependencies ?? {}),\n    ...Object.entries(entry.optionalDependencies ?? {}),\n  ].map(([n, v]) => [n, versionRef(v as DepMap[string])])\n}\n\n/**\n * Resolve one service's tree. `importerKey` is the service directory relative to\n * the lockfile's directory (\"\" for the same directory). Returns null when the\n * lockfile has no importer for the service, or is a version this doesn't read\n * (pnpm 7's v5 format).\n */\nexport function resolvePnpmLock(lock: PnpmLock, lockPath: string, importerKey: string): ServiceInventory | null {\n  const major = Number(String(lock.lockfileVersion ?? '0').split('.')[0])\n  if (!(major >= 6)) return null\n  const importers: Record<string, Importer> = lock.importers ?? {\n    '.': { dependencies: lock.dependencies, optionalDependencies: lock.optionalDependencies, devDependencies: lock.devDependencies },\n  }\n  const ownKey = importerKey === '' ? '.' : importerKey\n  const importer = importers[ownKey]\n  if (!importer) return null\n\n  const snapshots: Record<string, SnapshotEntry> = {}\n  if (lock.snapshots) Object.assign(snapshots, lock.snapshots)\n  else for (const [k, v] of Object.entries(lock.packages ?? {})) snapshots[k.startsWith('/') ? k.slice(1) : k] = v\n\n  const fold = new TreeFold('npm')\n  const roots: Array<{ name: string; ref: string; dev: boolean; from: string }> = [\n    ...children(importer).map(([name, ref]) => ({ name, ref, dev: false, from: ownKey })),\n    ...Object.entries(importer.devDependencies ?? {})\n      .filter(([n]) => !(importer.dependencies ?? {})[n])\n      .map(([name, v]) => ({ name, ref: versionRef(v), dev: true, from: ownKey })),\n  ]\n\n  for (const root of roots) {\n    // Work items are either a snapshot key or a linked workspace importer.\n    const queue: Array<{ kind: 'pkg'; key: string; isDirect: boolean } | { kind: 'ws'; key: string }> = []\n    const enqueueRef = (name: string, ref: string, from: string, isDirect: boolean) => {\n      if (ref.startsWith('link:')) {\n        const target = path.posix.normalize(path.posix.join(from === '.' ? '' : from, ref.slice(5))) || '.'\n        queue.push({ kind: 'ws', key: target })\n      } else {\n        queue.push({ kind: 'pkg', key: snapshotKey(name, ref), isDirect })\n      }\n    }\n    enqueueRef(root.name, root.ref, root.from, true)\n    const seen = new Set<string>()\n    while (queue.length > 0) {\n      const item = queue.shift()!\n      const seenKey = `${item.kind}:${item.key}`\n      if (seen.has(seenKey)) continue\n      seen.add(seenKey)\n      if (item.kind === 'ws') {\n        const ws = importers[item.key]\n        if (!ws) continue\n        for (const [n, r] of children(ws)) enqueueRef(n, r, item.key, false)\n        continue\n      }\n      const parsed = parseKey(item.key)\n      if (!parsed) continue\n      fold.visit(parsed.name, parsed.version, { direct: root.name, dev: root.dev, isDirect: item.isDirect })\n      const entry = snapshots[item.key]\n      if (!entry) continue\n      for (const [n, r] of children(entry)) enqueueRef(n, r, '.', false)\n    }\n  }\n  return { source: lockPath, resolution: 'complete', dependencies: fold.result() }\n}\n","import { parse as parseYaml } from 'yaml'\nimport type { ServiceManifest } from './npm-lock.js'\nimport { TreeFold, type ServiceInventory } from './resolved.js'\n\n// yarn.lock, classic (v1) and Berry (v2+) (dependency-inventory.md §3). Both key\n// each resolved package by the descriptors (`name@range`) that resolved to it,\n// so the walk is: a manifest range → its descriptor → the entry → that entry's\n// dependency ranges → their descriptors. Berry also lists the workspaces\n// themselves (`name@workspace:path`). Those are first-party code: walked through,\n// never counted.\n\ninterface YarnEntry {\n  name: string\n  version: string\n  deps: Array<[string, string]>\n  workspace: boolean\n}\n\n// `\"@scope/a@^1.0.0\", a@npm:^1.1.0` → ['@scope/a@^1.0.0', 'a@npm:^1.1.0']\nfunction splitDescriptors(header: string): string[] {\n  return header\n    .split(',')\n    .map((d) => d.trim().replace(/^\"|\"$/g, ''))\n    .filter(Boolean)\n}\n\nfunction descriptorName(descriptor: string): string {\n  const at = descriptor.indexOf('@', descriptor.startsWith('@') ? 1 : 0)\n  return at > 0 ? descriptor.slice(0, at) : descriptor\n}\n\nfunction unquote(s: string): string {\n  return s.trim().replace(/^\"|\"$/g, '')\n}\n\nexport function parseYarnV1(text: string): Map<string, YarnEntry> {\n  const out = new Map<string, YarnEntry>()\n  let descriptors: string[] = []\n  let entry: YarnEntry | null = null\n  let section: 'deps' | null = null\n  const flush = () => {\n    if (entry) for (const d of descriptors) out.set(d, entry)\n  }\n  for (const line of text.split(/\\r?\\n/)) {\n    if (!line.trim() || line.startsWith('#')) continue\n    if (!line.startsWith(' ')) {\n      flush()\n      descriptors = splitDescriptors(line.replace(/:\\s*$/, ''))\n      entry = { name: descriptorName(descriptors[0] ?? ''), version: '', deps: [], workspace: false }\n      section = null\n      continue\n    }\n    if (!entry) continue\n    if (/^ {2}\\S/.test(line)) {\n      const t = line.trim()\n      section = t === 'dependencies:' || t === 'optionalDependencies:' ? 'deps' : null\n      const v = /^version\\s+(.+)$/.exec(t)\n      if (v?.[1]) entry.version = unquote(v[1])\n      continue\n    }\n    if (section === 'deps' && /^ {4}\\S/.test(line)) {\n      const m = /^\\s+(\"?[^\"\\s]+\"?)\\s+(.+)$/.exec(line)\n      if (m?.[1] && m[2]) entry.deps.push([unquote(m[1]), unquote(m[2])])\n    }\n  }\n  flush()\n  return out\n}\n\ninterface BerryEntry {\n  version?: string\n  resolution?: string\n  dependencies?: Record<string, string>\n  peerDependencies?: Record<string, string>\n}\n\nexport function parseYarnBerry(text: string): Map<string, YarnEntry> {\n  const doc = (parseYaml(text) ?? {}) as Record<string, BerryEntry>\n  const out = new Map<string, YarnEntry>()\n  for (const [header, value] of Object.entries(doc)) {\n    if (header === '__metadata' || !value || typeof value !== 'object') continue\n    const descriptors = splitDescriptors(header)\n    const resolution = value.resolution ?? descriptors[0] ?? ''\n    const entry: YarnEntry = {\n      name: descriptorName(resolution),\n      version: String(value.version ?? ''),\n      deps: Object.entries(value.dependencies ?? {}),\n      workspace: resolution.includes('@workspace:') || resolution.includes('@link:'),\n    }\n    for (const d of descriptors) out.set(d, entry)\n  }\n  return out\n}\n\nexport function isYarnBerry(text: string): boolean {\n  return /^__metadata:/m.test(text)\n}\n\nfunction lookup(entries: Map<string, YarnEntry>, name: string, range: string): YarnEntry | undefined {\n  return (\n    entries.get(`${name}@${range}`) ??\n    entries.get(`${name}@npm:${range}`) ??\n    // Berry writes `npm:` into dependency values for aliases; v1 doesn't.\n    (range.startsWith('npm:') ? entries.get(`${name}@${range.slice(4)}`) : undefined)\n  )\n}\n\n/**\n * Resolve one service's tree from its manifest's direct ranges. In yarn v1 a\n * workspace sibling isn't in the lockfile, so a dependency on one resolves to\n * nothing here and its subtree isn't attributed to this service.\n */\nexport function resolveYarnLock(\n  text: string,\n  lockPath: string,\n  manifest: ServiceManifest,\n  opts: { ownsLockfile: boolean } = { ownsLockfile: true },\n): ServiceInventory {\n  const entries = isYarnBerry(text) ? parseYarnBerry(text) : parseYarnV1(text)\n  const fold = new TreeFold('npm')\n  const roots: Array<{ name: string; range: string; dev: boolean }> = [\n    ...Object.entries(manifest.dependencies ?? {}).map(([name, range]) => ({ name, range, dev: false })),\n    ...Object.entries(manifest.optionalDependencies ?? {}).map(([name, range]) => ({ name, range, dev: false })),\n    ...Object.entries(manifest.devDependencies ?? {})\n      .filter(([n]) => !(manifest.dependencies ?? {})[n])\n      .map(([name, range]) => ({ name, range, dev: true })),\n  ]\n  for (const root of roots) {\n    const queue: Array<{ entry: YarnEntry; isDirect: boolean }> = []\n    const first = lookup(entries, root.name, root.range)\n    if (first) queue.push({ entry: first, isDirect: true })\n    const seen = new Set<YarnEntry>()\n    while (queue.length > 0) {\n      const { entry, isDirect } = queue.shift()!\n      if (seen.has(entry)) continue\n      seen.add(entry)\n      if (!entry.workspace && entry.version) {\n        fold.visit(entry.name, entry.version, { direct: root.name, dev: root.dev, isDirect })\n      }\n      for (const [n, r] of entry.deps) {\n        const next = lookup(entries, n, r)\n        if (next && !seen.has(next)) queue.push({ entry: next, isDirect: false })\n      }\n    }\n  }\n  // Yarn v1 installs and locks peer dependencies without recording the peer edge,\n  // so no walk from the manifest reaches them. When the lockfile belongs to this\n  // service alone, everything it locks is installed for this service: an entry\n  // the walk missed is still present, so it is kept as transitive with no\n  // known introducer. A workspace lockfile is shared, so there the missed\n  // entries could belong to a sibling and are left out.\n  if (opts.ownsLockfile) {\n    for (const entry of new Set(entries.values())) {\n      if (entry.workspace || !entry.version) continue\n      fold.visitUnattributed(entry.name, entry.version)\n    }\n  }\n  return { source: lockPath, resolution: 'complete', dependencies: fold.result() }\n}\n","import { TreeFold, normalizePypiName, type ServiceInventory } from './resolved.js'\n\n// Python lockfiles (dependency-inventory.md §3): poetry.lock and uv.lock resolve\n// the whole tree; a requirements.txt resolves only what it pins exactly.\n\ninterface LockedPackage {\n  name: string\n  version: string\n  // Normalized names of what this package depends on.\n  deps: string[]\n}\n\nfunction walk(\n  packages: Map<string, LockedPackage>,\n  roots: Array<{ name: string; dev: boolean }>,\n): TreeFold {\n  const fold = new TreeFold('PyPI')\n  for (const root of roots) {\n    const queue: Array<{ name: string; isDirect: boolean }> = [{ name: root.name, isDirect: true }]\n    const seen = new Set<string>()\n    while (queue.length > 0) {\n      const { name, isDirect } = queue.shift()!\n      if (seen.has(name)) continue\n      seen.add(name)\n      const pkg = packages.get(name)\n      if (!pkg) continue\n      fold.visit(pkg.name, pkg.version, { direct: root.name, dev: root.dev, isDirect })\n      for (const d of pkg.deps) if (!seen.has(d)) queue.push({ name: d, isDirect: false })\n    }\n  }\n  return fold\n}\n\n// Strip extras and markers from a dependency name: \"requests[socks] ; python_version<'4'\".\nfunction bareName(spec: string): string {\n  return normalizePypiName(spec.split(/[\\s\\[;<>=!~(]/, 1)[0] ?? spec)\n}\n\n// --- poetry.lock -----------------------------------------------------------\n\ninterface PoetryLock {\n  package?: Array<{ name: string; version: string; dependencies?: Record<string, unknown> }>\n}\n\nexport interface PoetryProject {\n  tool?: {\n    poetry?: {\n      dependencies?: Record<string, unknown>\n      'dev-dependencies'?: Record<string, unknown>\n      group?: Record<string, { dependencies?: Record<string, unknown> }>\n    }\n  }\n  project?: { dependencies?: string[]; 'optional-dependencies'?: Record<string, string[]> }\n  'dependency-groups'?: Record<string, unknown[]>\n}\n\nexport function resolvePoetryLock(lock: PoetryLock, lockPath: string, pyproject: PoetryProject): ServiceInventory {\n  const packages = new Map<string, LockedPackage>()\n  for (const p of lock.package ?? []) {\n    const name = normalizePypiName(p.name)\n    packages.set(name, { name, version: p.version, deps: Object.keys(p.dependencies ?? {}).map(normalizePypiName) })\n  }\n  const poetry = pyproject.tool?.poetry\n  const prod = new Set<string>([\n    ...Object.keys(poetry?.dependencies ?? {}),\n    ...(pyproject.project?.dependencies ?? []),\n  ].map(bareName))\n  prod.delete('python')\n  const dev = new Set<string>()\n  for (const n of Object.keys(poetry?.['dev-dependencies'] ?? {})) dev.add(bareName(n))\n  for (const g of Object.values(poetry?.group ?? {})) {\n    for (const n of Object.keys(g.dependencies ?? {})) dev.add(bareName(n))\n  }\n  const roots = [\n    ...[...prod].map((name) => ({ name, dev: false })),\n    ...[...dev].filter((n) => !prod.has(n)).map((name) => ({ name, dev: true })),\n  ]\n  return { source: lockPath, resolution: 'complete', dependencies: walk(packages, roots).result() }\n}\n\n// --- uv.lock ---------------------------------------------------------------\n\ninterface UvLock {\n  package?: Array<{\n    name: string\n    version?: string\n    source?: Record<string, unknown>\n    dependencies?: Array<{ name: string }>\n    'optional-dependencies'?: Record<string, Array<{ name: string }>>\n    'dev-dependencies'?: Record<string, Array<{ name: string }>>\n  }>\n}\n\n/**\n * uv.lock lists the project itself as a package whose source is `editable` or\n * `virtual` at \".\". Its dependencies are the direct ones, and its\n * dev-dependencies groups are dev. Returns null when the project entry isn't\n * there.\n */\nexport function resolveUvLock(lock: UvLock, lockPath: string, serviceName: string): ServiceInventory | null {\n  const entries = lock.package ?? []\n  const own = normalizePypiName(serviceName)\n  const project =\n    entries.find((p) => normalizePypiName(p.name) === own && (p.source?.editable !== undefined || p.source?.virtual !== undefined)) ??\n    entries.find((p) => p.source?.editable === '.' || p.source?.virtual === '.')\n  if (!project) return null\n  const packages = new Map<string, LockedPackage>()\n  for (const p of entries) {\n    if (p === project || !p.version) continue\n    const name = normalizePypiName(p.name)\n    const deps = [\n      ...(p.dependencies ?? []),\n      ...Object.values(p['optional-dependencies'] ?? {}).flat(),\n    ].map((d) => normalizePypiName(d.name))\n    packages.set(name, { name, version: p.version, deps })\n  }\n  const prod = new Set((project.dependencies ?? []).map((d) => normalizePypiName(d.name)))\n  const dev = new Set(Object.values(project['dev-dependencies'] ?? {}).flat().map((d) => normalizePypiName(d.name)))\n  const roots = [\n    ...[...prod].map((name) => ({ name, dev: false })),\n    ...[...dev].filter((n) => !prod.has(n)).map((name) => ({ name, dev: true })),\n  ]\n  return { source: lockPath, resolution: 'complete', dependencies: walk(packages, roots).result() }\n}\n\n// --- requirements.txt ------------------------------------------------------\n\n/**\n * Exact pins only (`name==1.2.3`). A file compiled by pip-compile records why a\n * pin is there in `# via` comments. A pin \"via\" other packages is transitive,\n * and one via `-r` / `-c` or nothing is direct. Without a lockfile the tree\n * isn't known, so the result is always `partial`.\n */\nexport function resolveRequirementsPins(content: string, sourcePath: string): ServiceInventory {\n  const lines = content.split(/\\r?\\n/)\n  const pins: Array<{ name: string; version: string; via: string[] }> = []\n  let current: { name: string; version: string; via: string[] } | null = null\n  let inVia = false\n  for (const raw of lines) {\n    const line = raw.trim()\n    const pin = /^([A-Za-z0-9][A-Za-z0-9._-]*)(?:\\[[^\\]]*\\])?\\s*==\\s*([^\\s;#\\\\]+)/.exec(line)\n    if (pin && pin[1] && pin[2]) {\n      const entry = { name: normalizePypiName(pin[1]), version: pin[2], via: [] as string[] }\n      pins.push(entry)\n      current = entry\n      inVia = false\n      const inline = /#\\s*via\\s+(.+)$/.exec(line)\n      if (inline?.[1]) entry.via.push(...inline[1].split(',').map((s) => s.trim()))\n      continue\n    }\n    if (!current || !line.startsWith('#')) {\n      if (line && !line.startsWith('#')) current = null\n      continue\n    }\n    const body = line.replace(/^#\\s*/, '')\n    if (/^via\\b/.test(body)) {\n      inVia = true\n      const rest = body.replace(/^via\\s*/, '')\n      if (rest) current.via.push(rest)\n    } else if (inVia && body) {\n      current.via.push(body)\n    }\n  }\n  const pinned = new Set(pins.map((p) => p.name))\n  const parentsOf = new Map<string, string[]>()\n  for (const p of pins) {\n    parentsOf.set(\n      p.name,\n      p.via\n        .filter((v) => !v.startsWith('-r') && !v.startsWith('-c') && !v.includes('.txt') && !v.includes('.in'))\n        .map(bareName)\n        .filter((n) => pinned.has(n) && n !== p.name),\n    )\n  }\n  const isDirect = (name: string) => (parentsOf.get(name) ?? []).length === 0\n  // `# via` names the immediate parents. introducedBy names the direct\n  // dependencies at the top of those chains.\n  const directAncestors = (name: string): string[] => {\n    const out = new Set<string>()\n    const seen = new Set<string>([name])\n    const queue = [...(parentsOf.get(name) ?? [])]\n    while (queue.length > 0) {\n      const n = queue.shift()!\n      if (seen.has(n)) continue\n      seen.add(n)\n      if (isDirect(n)) out.add(n)\n      else queue.push(...(parentsOf.get(n) ?? []))\n    }\n    return [...out].sort()\n  }\n  const dependencies = pins.map((p) => {\n    const direct = isDirect(p.name)\n    return {\n      ecosystem: 'PyPI' as const,\n      name: p.name,\n      version: p.version,\n      scope: direct ? ('direct' as const) : ('transitive' as const),\n      dev: false,\n      introducedBy: direct ? [] : directAncestors(p.name),\n    }\n  })\n  return { source: sourcePath, resolution: 'partial', dependencies }\n}\n","import path from 'node:path'\nimport type Parser from 'tree-sitter'\nimport type { DependencyNode, GraphEdge } from '@neat.is/types'\nimport {\n  EdgeType,\n  NodeType,\n  Provenance,\n  confidenceForExtracted,\n  extractedEdgeId,\n  fileId,\n  isDependencyNodeId,\n} from '@neat.is/types'\nimport type { NeatGraph } from '../../graph.js'\nimport { isTestPath, type DiscoveredService } from '../shared.js'\nimport { recordExtractionError } from '../errors.js'\nimport { loadSourceFiles, toPosix } from '../calls/shared.js'\nimport {\n  collectGoImports,\n  collectJsImports,\n  collectPyBareImports,\n  collectPyImports,\n  loadTsPathConfig,\n  makeGoParser,\n  makeJsParser,\n  makePyParser,\n  parseSource,\n  resolveJsImport,\n  type RawImport,\n  type RawPyImport,\n} from '../imports.js'\nimport { normalizePypiName } from './resolved.js'\nimport { findPythonDistribution, pythonTopLevelModules } from '../dependency-symbols/locate.js'\n\n// First-party imports of a package become EXTRACTED `file ──IMPORTS──▶ dep:`\n// edges (ADR-274, dependency-inventory.md §4). This is the `imported`\n// reachability level: the finding's package is pulled into code the service\n// runs, not just sitting in the lockfile. Runs after addDependencies, since it\n// matches imports against the DependencyNodes that phase minted.\n//\n// Matching only ever lands on a package the service declares, so first-party\n// imports filter themselves out. The producer owns its edges: every pass drops a\n// service's file→dep IMPORTS edges and rebuilds them.\n\ninterface Hit {\n  depId: string\n  line: number\n  snippet: string\n  specifier: string\n  bindings: string[]\n}\n\n// One service's dependency versions by ecosystem and name. A name with several\n// versions (a transitive duplicate) resolves to the direct one; with no direct\n// one there's no telling which copy an import gets, so that name is left out\n// rather than guessed.\nfunction depsOf(graph: NeatGraph, serviceId: string): Map<string, Map<string, string>> {\n  const byName = new Map<string, Map<string, { id: string; direct: boolean }[]>>()\n  graph.forEachOutEdge(serviceId, (_e, attrs, _src, target) => {\n    const edge = attrs as GraphEdge\n    if (edge.type !== EdgeType.DEPENDS_ON || !isDependencyNodeId(target)) return\n    const dep = graph.getNodeAttributes(target) as DependencyNode\n    if (dep.type !== NodeType.DependencyNode) return\n    const eco = byName.get(dep.ecosystem) ?? new Map()\n    byName.set(dep.ecosystem, eco)\n    const name = dep.ecosystem === 'PyPI' ? normalizePypiName(dep.name) : dep.name\n    const list = eco.get(name) ?? []\n    list.push({ id: target, direct: edge.dependency?.scope === 'direct' })\n    eco.set(name, list)\n  })\n  const out = new Map<string, Map<string, string>>()\n  for (const [eco, names] of byName) {\n    const picked = new Map<string, string>()\n    for (const [name, list] of names) {\n      const direct = list.filter((d) => d.direct)\n      if (direct.length === 1) picked.set(name, direct[0]!.id)\n      else if (list.length === 1) picked.set(name, list[0]!.id)\n    }\n    out.set(eco, picked)\n  }\n  return out\n}\n\n// `lodash/template` → `lodash`, `@scope/pkg/sub` → `@scope/pkg`. Null for a\n// relative, absolute or `node:` specifier, none of which is a package.\nfunction npmPackageName(specifier: string): string | null {\n  if (specifier.startsWith('.') || specifier.startsWith('/') || specifier.startsWith('node:')) return null\n  const parts = specifier.split('/')\n  if (specifier.startsWith('@')) return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : null\n  return parts[0] || null\n}\n\n// `import type` carries no runtime code, so it doesn't make a package reachable.\nconst TYPE_ONLY = /^import\\s+type[\\s{]/\n\nasync function jsHits(\n  imports: RawImport[],\n  deps: Map<string, string>,\n  importerDir: string,\n  service: DiscoveredService,\n  tsPaths: Awaited<ReturnType<typeof loadTsPathConfig>>,\n): Promise<Hit[]> {\n  const hits: Hit[] = []\n  for (const imp of imports) {\n    if (TYPE_ONLY.test(imp.snippet)) continue\n    const name = npmPackageName(imp.specifier)\n    if (!name) continue\n    const depId = deps.get(name)\n    if (!depId) continue\n    // A tsconfig path alias that resolves inside the service is first-party,\n    // even when its prefix looks like a package name.\n    if ((await resolveJsImport(imp.specifier, importerDir, service.dir, tsPaths)) !== null) continue\n    hits.push({ depId, line: imp.line, snippet: imp.snippet, specifier: imp.specifier, bindings: imp.bindings ?? [] })\n  }\n  return hits\n}\n\nfunction pyHits(imports: RawPyImport[], deps: Map<string, string>): Hit[] {\n  const hits: Hit[] = []\n  for (const imp of imports) {\n    if (imp.level > 0 || !imp.modulePath) continue\n    // The top-level module name, matched to the distribution name or, when the\n    // distribution is installed, to the import names it provides. A module that\n    // matches neither gets no edge.\n    const top = normalizePypiName(imp.modulePath.split('.')[0]!)\n    const depId = deps.get(top)\n    if (!depId) continue\n    hits.push({ depId, line: imp.line, snippet: imp.snippet, specifier: imp.modulePath, bindings: imp.bindings ?? [] })\n  }\n  return hits\n}\n\n// The longest declared module path that is the import path or a prefix of it at\n// a `/` boundary: `github.com/a/b/sub` belongs to module `github.com/a/b`.\nfunction goHits(imports: RawImport[], deps: Map<string, string>): Hit[] {\n  const names = [...deps.keys()].sort((a, b) => b.length - a.length)\n  const hits: Hit[] = []\n  for (const imp of imports) {\n    const mod = names.find((n) => imp.specifier === n || imp.specifier.startsWith(n + '/'))\n    if (!mod) continue\n    hits.push({ depId: deps.get(mod)!, line: imp.line, snippet: imp.snippet, specifier: imp.specifier, bindings: imp.bindings ?? [] })\n  }\n  return hits\n}\n\nfunction parseWith<T>(parser: Parser, source: string, collect: (root: Parser.SyntaxNode, out: T[]) => void, out: T[]): void {\n  collect(parseSource(parser, source).rootNode, out)\n}\n\n// PyPI distributions whose import name isn't their own (`yaml` from PyYAML, `PIL`\n// from Pillow), read from the installed copy's `top_level.txt` or RECORD. A\n// module two installed distributions both claim (a namespace package) is left\n// unmatched rather than given to either.\nasync function addPypiModuleNames(\n  pypi: Map<string, string>,\n  graph: NeatGraph,\n  serviceDir: string,\n  scanPath: string,\n): Promise<Map<string, string>> {\n  const claims = new Map<string, Set<string>>()\n  for (const depId of [...new Set(pypi.values())].sort()) {\n    const dep = graph.getNodeAttributes(depId) as DependencyNode\n    const dist = await findPythonDistribution(dep, [serviceDir], scanPath)\n    if (!dist) continue\n    for (const mod of await pythonTopLevelModules(dist)) {\n      const key = normalizePypiName(mod)\n      const set = claims.get(key) ?? new Set<string>()\n      set.add(depId)\n      claims.set(key, set)\n    }\n  }\n  const out = new Map(pypi)\n  for (const [key, ids] of claims) {\n    if (!out.has(key) && ids.size === 1) out.set(key, [...ids][0]!)\n  }\n  return out\n}\n\nexport async function addDependencyImports(\n  graph: NeatGraph,\n  services: DiscoveredService[],\n  scanPath?: string,\n): Promise<{ edgesAdded: number; edgesRemoved: number }> {\n  const jsParser = makeJsParser()\n  const pyParser = makePyParser()\n  const goParser = makeGoParser()\n  let edgesAdded = 0\n  let edgesRemoved = 0\n\n  for (const service of services) {\n    const svcName = service.pkg.name\n    if (!svcName || !graph.hasNode(service.node.id)) continue\n\n    // This service's file→dep IMPORTS edges from earlier passes. The ones this pass\n    // mints again are updated in place; whatever is left at the end is dropped.\n    const filePrefix = fileId(svcName, '')\n    const stale = new Set<string>()\n    graph.forEachEdge((id, attrs, source, target) => {\n      const e = attrs as GraphEdge\n      if (e.type === EdgeType.IMPORTS && e.provenance === Provenance.EXTRACTED && isDependencyNodeId(target) && source.startsWith(filePrefix)) {\n        stale.add(id)\n      }\n    })\n    const dropStale = () => {\n      for (const id of stale) graph.dropEdge(id)\n      edgesRemoved += stale.size\n    }\n\n    const deps = depsOf(graph, service.node.id)\n    if (deps.size === 0) {\n      dropStale()\n      continue\n    }\n    const npm = deps.get('npm') ?? new Map<string, string>()\n    const pypiByDist = deps.get('PyPI') ?? new Map<string, string>()\n    const pypi = pypiByDist.size\n      ? await addPypiModuleNames(pypiByDist, graph, service.dir, scanPath ?? service.dir)\n      : pypiByDist\n    const golang = deps.get('Go') ?? new Map<string, string>()\n    const tsPaths = npm.size ? await loadTsPathConfig(service.dir) : null\n    const files = await loadSourceFiles(service.dir, service.excludeDirs)\n\n    for (const file of [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))) {\n      // Test files don't make a package reachable from what runs (ADR-065 §1).\n      if (isTestPath(file.path)) continue\n      const relFile = toPosix(path.relative(service.dir, file.path))\n      const importer = fileId(svcName, relFile)\n      if (!graph.hasNode(importer)) continue\n      const ext = path.extname(file.path)\n\n      let hits: Hit[]\n      try {\n        if (ext === '.py') {\n          if (!pypi.size) continue\n          const imports: RawPyImport[] = []\n          parseWith(pyParser, file.content, collectPyImports, imports)\n          parseWith(pyParser, file.content, collectPyBareImports, imports)\n          hits = pyHits(imports, pypi)\n        } else if (ext === '.go') {\n          if (!golang.size) continue\n          const imports: RawImport[] = []\n          parseWith(goParser, file.content, collectGoImports, imports)\n          hits = goHits(imports, golang)\n        } else if (['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx'].includes(ext)) {\n          if (!npm.size) continue\n          const imports: RawImport[] = []\n          parseWith(jsParser, file.content, collectJsImports, imports)\n          hits = await jsHits(imports, npm, path.dirname(file.path), service, tsPaths)\n        } else continue\n      } catch (err) {\n        recordExtractionError('dependency imports', file.path, err)\n        continue\n      }\n\n      // One edge per (file, dependency): the earliest line, every binding.\n      const perDep = new Map<string, Hit>()\n      for (const h of hits) {\n        const prev = perDep.get(h.depId)\n        if (!prev) {\n          perDep.set(h.depId, { ...h, bindings: [...h.bindings] })\n          continue\n        }\n        const merged = [...prev.bindings, ...h.bindings]\n        const first = h.line < prev.line ? h : prev\n        perDep.set(h.depId, { ...first, bindings: merged })\n      }\n\n      for (const depId of [...perDep.keys()].sort()) {\n        const h = perDep.get(depId)!\n        const edgeId = extractedEdgeId(importer, depId, EdgeType.IMPORTS)\n        const edge: GraphEdge = {\n          id: edgeId,\n          source: importer,\n          target: depId,\n          type: EdgeType.IMPORTS,\n          provenance: Provenance.EXTRACTED,\n          confidence: confidenceForExtracted('structural'),\n          evidence: {\n            file: relFile,\n            line: h.line,\n            snippet: h.snippet,\n            specifier: h.specifier,\n            bindings: [...new Set(h.bindings)].sort(),\n          },\n        }\n        if (graph.hasEdge(edgeId)) {\n          graph.replaceEdgeAttributes(edgeId, edge)\n          stale.delete(edgeId)\n          continue\n        }\n        graph.addEdgeWithKey(edgeId, importer, depId, edge)\n        edgesAdded++\n      }\n    }\n    dropStale()\n  }\n  return { edgesAdded, edgesRemoved }\n}\n","import { promises as fs } from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport { isPackageSource } from '../../advisories/fixdiff.js'\nimport { normalizePypiName } from '../dependencies/resolved.js'\nimport type { DependencyRef } from './extract.js'\n\n// Finds the installed copy of a dependency version and reads its own source\n// (dependency-inventory.md §5). Read-only: nothing is installed, imported or run.\n// A copy whose version doesn't match the one asked for is not used, so a symbol\n// is never minted for a version from different code.\n//\n// Installed copies only. Fetching the registry release when nothing is installed\n// is the advisory cache's job (advisory-cache.md §4) and lands separately.\n\nconst MAX_FILE_BYTES = 2 * 1024 * 1024\nconst MAX_FILES = 10_000\n\nexport interface LocatedSource {\n  // Where the copy was found, for diagnostics. Never written into the graph.\n  root: string\n  files: Map<string, string>\n  // The package's own manifest, where it has one (npm `package.json`): its\n  // `main` / `exports` name the entry files an import lands on.\n  manifest?: unknown\n}\n\nasync function readJson(p: string): Promise<unknown> {\n  try {\n    return JSON.parse(await fs.readFile(p, 'utf8'))\n  } catch {\n    return null\n  }\n}\n\nasync function isDir(p: string): Promise<boolean> {\n  try {\n    return (await fs.stat(p)).isDirectory()\n  } catch {\n    return false\n  }\n}\n\n// The directories from `start` up to and including `stop` (or the filesystem\n// root when `start` isn't under `stop`).\nfunction ancestors(start: string, stop: string): string[] {\n  const out: string[] = []\n  const root = path.resolve(stop)\n  let dir = path.resolve(start)\n  for (;;) {\n    out.push(dir)\n    if (dir === root || !dir.startsWith(root)) break\n    const up = path.dirname(dir)\n    if (up === dir) break\n    dir = up\n  }\n  return out\n}\n\n// Every package-source file under `root`, keyed by its posix path relative to it.\n// Null when the package is too big to read whole: a partial symbol set would read\n// as complete.\nasync function readTree(root: string, keep: (rel: string) => boolean = isPackageSource): Promise<Map<string, string> | null> {\n  const files = new Map<string, string>()\n  const walk = async (dir: string): Promise<boolean> => {\n    let entries: import('node:fs').Dirent[]\n    try {\n      entries = await fs.readdir(dir, { withFileTypes: true })\n    } catch {\n      return true\n    }\n    entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))\n    for (const e of entries) {\n      const abs = path.join(dir, e.name)\n      if (e.isDirectory()) {\n        // A nested node_modules is another package's code.\n        if (e.name === 'node_modules' || e.name === '.git') continue\n        if (!(await walk(abs))) return false\n      } else if (e.isFile()) {\n        const rel = path.relative(root, abs).split(path.sep).join('/')\n        if (!keep(rel)) continue\n        const st = await fs.stat(abs)\n        if (st.size > MAX_FILE_BYTES) continue\n        if (files.size >= MAX_FILES) return false\n        files.set(rel, await fs.readFile(abs, 'utf8'))\n      }\n    }\n    return true\n  }\n  return (await walk(root)) ? files : null\n}\n\n// ── npm ─────────────────────────────────────────────────────────────────────\n\nasync function locateNpm(dep: DependencyRef, searchFrom: string[], scanPath: string): Promise<LocatedSource | null> {\n  const seen = new Set<string>()\n  for (const start of searchFrom) {\n    for (const dir of ancestors(start, scanPath)) {\n      const pkgDir = path.join(dir, 'node_modules', ...dep.name.split('/'))\n      if (seen.has(pkgDir)) continue\n      seen.add(pkgDir)\n      const pkg = (await readJson(path.join(pkgDir, 'package.json'))) as { version?: string } | null\n      if (pkg?.version !== dep.version) continue\n      const files = await readTree(pkgDir)\n      return files ? { root: pkgDir, files, manifest: pkg } : null\n    }\n  }\n  return null\n}\n\n// ── PyPI ────────────────────────────────────────────────────────────────────\n\nasync function sitePackagesDirs(searchFrom: string[], scanPath: string, env: NodeJS.ProcessEnv): Promise<string[]> {\n  const venvs: string[] = []\n  if (env.VIRTUAL_ENV) venvs.push(env.VIRTUAL_ENV)\n  for (const start of searchFrom) {\n    for (const dir of ancestors(start, scanPath)) {\n      for (const name of ['.venv', 'venv', 'env']) venvs.push(path.join(dir, name))\n    }\n  }\n  const out: string[] = []\n  for (const venv of [...new Set(venvs)]) {\n    const win = path.join(venv, 'Lib', 'site-packages')\n    if (await isDir(win)) out.push(win)\n    const lib = path.join(venv, 'lib')\n    let entries: string[] = []\n    try {\n      entries = (await fs.readdir(lib)).filter((n) => /^python\\d/.test(n)).sort()\n    } catch {\n      continue\n    }\n    for (const py of entries) {\n      const sp = path.join(lib, py, 'site-packages')\n      if (await isDir(sp)) out.push(sp)\n    }\n  }\n  return out\n}\n\nexport interface PythonDistribution {\n  sitePackages: string\n  distInfo: string\n}\n\n// The installed `<name>-<version>.dist-info` for a PyPI dependency version.\nexport async function findPythonDistribution(\n  dep: DependencyRef,\n  searchFrom: string[],\n  scanPath: string,\n  env: NodeJS.ProcessEnv = process.env,\n): Promise<PythonDistribution | null> {\n  const want = normalizePypiName(dep.name)\n  for (const sp of await sitePackagesDirs(searchFrom, scanPath, env)) {\n    let entries: string[]\n    try {\n      entries = (await fs.readdir(sp)).sort()\n    } catch {\n      continue\n    }\n    for (const entry of entries) {\n      const m = /^(.+)-([^-]+)\\.dist-info$/.exec(entry)\n      if (!m || normalizePypiName(m[1]!) !== want || m[2] !== dep.version) continue\n      return { sitePackages: sp, distInfo: path.join(sp, entry) }\n    }\n  }\n  return null\n}\n\n// The files a distribution installed, from its RECORD, package-relative to\n// site-packages. Scripts outside site-packages (`../../bin/…`) and the metadata\n// directory are left out.\nasync function recordFiles(dist: PythonDistribution): Promise<string[]> {\n  let raw: string\n  try {\n    raw = await fs.readFile(path.join(dist.distInfo, 'RECORD'), 'utf8')\n  } catch {\n    return []\n  }\n  const metaDir = path.basename(dist.distInfo)\n  return raw\n    .split('\\n')\n    .map((l) => l.split(',')[0]!.trim())\n    .filter((p) => p && !p.startsWith('..') && !p.startsWith('/') && !p.startsWith(`${metaDir}/`))\n    .sort()\n}\n\n/**\n * The top-level import names a distribution provides (`yaml` for PyYAML, `PIL`\n * for Pillow): its `top_level.txt`, else the first path segment of each module\n * its RECORD lists. Empty when it isn't installed or says nothing.\n */\nexport async function pythonTopLevelModules(dist: PythonDistribution): Promise<string[]> {\n  try {\n    const raw = await fs.readFile(path.join(dist.distInfo, 'top_level.txt'), 'utf8')\n    const names = raw.split('\\n').map((l) => l.trim()).filter(Boolean)\n    if (names.length) return [...new Set(names)].sort()\n  } catch {\n    // no top_level.txt: fall through to RECORD\n  }\n  const names = new Set<string>()\n  for (const p of await recordFiles(dist)) {\n    const head = p.split('/')[0]!\n    if (head.endsWith('.data') || head === '__pycache__') continue\n    if (p.includes('/')) names.add(head)\n    else if (head.endsWith('.py')) names.add(head.slice(0, -3))\n  }\n  return [...names].sort()\n}\n\nasync function locatePypi(dep: DependencyRef, searchFrom: string[], scanPath: string, env: NodeJS.ProcessEnv): Promise<LocatedSource | null> {\n  const dist = await findPythonDistribution(dep, searchFrom, scanPath, env)\n  if (!dist) return null\n  const listed = (await recordFiles(dist)).filter(isPackageSource)\n  if (listed.length > MAX_FILES) return null\n  const files = new Map<string, string>()\n  for (const rel of listed) {\n    const abs = path.join(dist.sitePackages, ...rel.split('/'))\n    try {\n      if ((await fs.stat(abs)).size > MAX_FILE_BYTES) continue\n      files.set(rel, await fs.readFile(abs, 'utf8'))\n    } catch {\n      // listed but gone: the install is partial, read what's there\n    }\n  }\n  return { root: dist.distInfo, files }\n}\n\n// ── Go ──────────────────────────────────────────────────────────────────────\n\n// The module cache escapes an uppercase letter as `!` plus its lowercase.\nfunction escapeGoModulePath(p: string): string {\n  return p.replace(/[A-Z]/g, (c) => `!${c.toLowerCase()}`)\n}\n\nfunction goModCache(env: NodeJS.ProcessEnv): string {\n  if (env.GOMODCACHE) return env.GOMODCACHE\n  const gopath = (env.GOPATH ?? '').split(path.delimiter).find(Boolean) ?? path.join(os.homedir(), 'go')\n  return path.join(gopath, 'pkg', 'mod')\n}\n\nasync function locateGo(dep: DependencyRef, env: NodeJS.ProcessEnv): Promise<LocatedSource | null> {\n  const version = dep.version.startsWith('v') ? dep.version : `v${dep.version}`\n  const dir = path.join(goModCache(env), `${escapeGoModulePath(dep.name)}@${version}`)\n  if (!(await isDir(dir))) return null\n  const files = await readTree(dir)\n  return files ? { root: dir, files } : null\n}\n\n/**\n * The installed source of one dependency version, or null when no matching copy\n * is installed (or it's too large to read whole). `searchFrom` are the\n * directories of the services that depend on it; the search walks up from each\n * to `scanPath`.\n */\nexport async function locateInstalledSource(\n  dep: DependencyRef,\n  searchFrom: string[],\n  scanPath: string,\n  env: NodeJS.ProcessEnv = process.env,\n): Promise<LocatedSource | null> {\n  if (dep.ecosystem === 'npm') return locateNpm(dep, searchFrom, scanPath)\n  if (dep.ecosystem === 'PyPI') return locatePypi(dep, searchFrom, scanPath, env)\n  if (dep.ecosystem === 'Go') return locateGo(dep, env)\n  return null\n}\n","import { existsSync } from 'node:fs'\nimport path from 'node:path'\nimport type { FileNode, GraphEdge, GraphNode } from '@neat.is/types'\nimport { NodeType, Provenance, isDependencyNodeId } from '@neat.is/types'\nimport type { NeatGraph } from '../graph.js'\n\n// Drop any FileNode left with no edges. A FileNode exists to originate a\n// relationship (file-awareness.md §1); once its CALLS / CONTAINS edges are\n// retired and no OBSERVED traffic remains, the bare node carries nothing and\n// goes too. Called after edge retirement so the snapshot stays consistent with\n// what's on disk. Returns the count dropped.\nfunction dropOrphanedFileNodes(graph: NeatGraph, source?: string): number {\n  const orphans: string[] = []\n  graph.forEachNode((id, attrs) => {\n    const node = attrs as GraphNode\n    if (node.type !== NodeType.FileNode) return\n    // Same scope rule as the edge sweep (ADR-233): a pass doesn't clean up after\n    // a source it didn't read. Otherwise a restored file whose edges another\n    // pass hasn't rebuilt yet is dropped by whichever repo syncs first.\n    if (source && (node as FileNode).source !== source) return\n    if (graph.inboundEdges(id).length === 0 && graph.outboundEdges(id).length === 0) {\n      orphans.push(id)\n    }\n  })\n  for (const id of orphans) graph.dropNode(id)\n  return orphans.length\n}\n\n// Drop every EXTRACTED edge whose evidence.file matches the given path, then\n// sweep any FileNode the retirement left orphaned. Called from watch.ts before\n// re-running an extract phase, so the producer's idempotent re-write recreates\n// only the edges that still apply. Edges from the deleted code stay deleted.\n// See docs/contracts/static-extraction.md §Ghost-edge cleanup. Mutation\n// authority lives under extract/* per ADR-030, so the dropEdge call must happen\n// here, not in watch.ts. The returned count is edges dropped (FileNode cleanup\n// is a structural side effect, not a ghost-edge count).\nexport function retireEdgesByFile(graph: NeatGraph, file: string): number {\n  const normalized = file.split('\\\\').join('/')\n  const toDrop: string[] = []\n  graph.forEachEdge((id, attrs) => {\n    const edge = attrs as GraphEdge\n    if (edge.provenance !== Provenance.EXTRACTED) return\n    if (!edge.evidence?.file) return\n    // A dependency's own `index.js` isn't the repo file of that name.\n    if (isDependencyNodeId(edge.source)) return\n    if (edge.evidence.file === normalized) toDrop.push(id)\n  })\n  for (const id of toDrop) graph.dropEdge(id)\n  dropOrphanedFileNodes(graph)\n  return toDrop.length\n}\n\n// #140 — full-pass cleanup. Walk every EXTRACTED edge in the graph; if its\n// `evidence.file` cannot be resolved on disk against the scan root or any\n// discovered service directory, drop it. extractFromDirectory calls this at\n// the end of every pass so a daemon bootstrap (or a re-init after the\n// operator deleted some source) gets a snapshot consistent with what's\n// actually on disk.\n//\n// Handles the deleted-file half of the ghost-edge bug. The edited-file half\n// (file still exists, producer no longer emits the edge) is handled by\n// watch.ts's per-file `retireEdgesByFile` on the mtime trigger.\n//\n// Path resolution is tolerant: producers in this tree are inconsistent about\n// whether `evidence.file` is scanPath-relative (configs, databases, infra)\n// or service-dir-relative (calls/*). We try every candidate base before\n// concluding the file is gone — the cost is one extra `existsSync` per\n// service dir per ghost candidate, which is cheap.\n\n// A pass may only retire what its own source produced (ADR-233).\n//\n// The sweep's reach is the whole graph; its evidence is one directory. That is\n// sound while the graph has one source and the pass is scanning it — a local\n// daemon — and wrong the moment it doesn't. A hosted daemon breaks both halves:\n// each bound repo is cloned to its own temp dir and extracted into the same\n// graph, so repo B's pass finds none of repo A's files and retires them\n// (#1294); and the boot pass runs over a path that holds no source at all, so\n// it retires every restored edge (#1291).\n//\n// So a pass that names a source retires only the files carrying that source,\n// and a pass that names none behaves exactly as it always has — which is every\n// local daemon, untouched.\n//\n// A file carrying *no* source is out of scope too, not judged by existence.\n// That looks over-cautious and isn't: a snapshot written before this field\n// existed has no sources on it at all, so judging those the old way would have\n// the first repo to sync after an upgrade sweep every other repo's restored\n// files — the bug, surviving its own fix, once. Unowned files are instead\n// claimed by the first pass that reads one (`ensureFileNode`), and are\n// retirable from then on.\n//\n// The cost is bounded and worth naming: a file deleted from a repo while the\n// daemon was down, and never read again, stays unowned and so is never retired.\n// It lingers as a ghost rather than taking a live repo's graph down with it.\nfunction outOfScope(graph: NeatGraph, edge: GraphEdge, source: string | undefined): boolean {\n  if (!source) return false\n  // The file an edge is about is its origin for a call, and its target for the\n  // service ──CONTAINS──▶ file edge.\n  for (const endpoint of [edge.source, edge.target]) {\n    if (!graph.hasNode(endpoint)) continue\n    const node = graph.getNodeAttributes(endpoint) as GraphNode\n    if (node.type !== NodeType.FileNode) continue\n    return (node as FileNode).source !== source\n  }\n  return false\n}\n\nexport function retireExtractedEdgesByMissingFile(\n  graph: NeatGraph,\n  scanPath: string,\n  serviceDirs: readonly string[] = [],\n  source?: string,\n): number {\n  const toDrop: string[] = []\n  const bases = [scanPath, ...serviceDirs]\n  graph.forEachEdge((id, attrs) => {\n    const edge = attrs as GraphEdge\n    if (edge.provenance !== Provenance.EXTRACTED) return\n    if (outOfScope(graph, edge, source)) return\n    // An edge out of dependency code (ADR-274) points at a file in the package,\n    // not the repo, and the dependency-symbols phase replaces those edges itself.\n    if (isDependencyNodeId(edge.source)) return\n    const evidenceFile = edge.evidence?.file\n    if (!evidenceFile) return\n    if (path.isAbsolute(evidenceFile)) {\n      if (!existsSync(evidenceFile)) toDrop.push(id)\n      return\n    }\n    // Tolerant: the file is \"present\" if any base resolves it.\n    const found = bases.some((base) => existsSync(path.join(base, evidenceFile)))\n    if (!found) toDrop.push(id)\n  })\n  for (const id of toDrop) graph.dropEdge(id)\n  dropOrphanedFileNodes(graph, source)\n  return toDrop.length\n}\n","// The fix-apply step (ADR-274): take a security card's proposed fix.action (G2,\n// advisories/fix-action.ts) and apply it to the manifest and lockfile, then\n// re-verify with scan_diff (G1, security-diff.ts) that the card's advisory is\n// gone and no new one was introduced. This is the line between NEAT flagging a\n// vulnerability and NEAT fixing it.\n//\n// The lockfile write is the remediation exception to the \"lockfiles never\n// written\" rule (ADR-047): extraction and instrumentation still never touch a\n// lockfile; this deliberate, user-or-agent-triggered fix does.\n//\n// How the fix is made:\n// - The manifest edit is deterministic: a direct dependency's spec moves to the\n//   fixed version (keeping its range operator), and a transitive one is pinned\n//   through an npm `override`, which needs no parent resolution.\n// - The lockfile is then regenerated by npm's own resolver\n//   (`npm install --package-lock-only --ignore-scripts`), so the result is a\n//   complete, consistent, `npm ci`-installable lockfile with correct integrity\n//   and the dependency's own subtree. A hand-edited version field would clear\n//   the CVE but leave a lockfile that will not install when a bump changes the\n//   dependency's own dependencies; a fix that will not install is not a fix.\n//   `--package-lock-only` writes no node_modules and `--ignore-scripts` runs no\n//   install scripts, so no third-party code executes here.\n//\n// Scope: npm only in v0 (PyPI and Go follow); the security axis only (scan_diff\n// re-verifies the vulnerability set, the project's own tests are the separate\n// 0-regression check); and only `bump-to-fixedIn`. `remove-or-replace` has no\n// deterministic target (a breaking bump or no fix at all), so it is reported,\n// never guessed, and a caller never reads \"not handled\" as \"fixed\".\n\nimport { promises as fs } from 'node:fs'\nimport { execFileSync } from 'node:child_process'\nimport path from 'node:path'\nimport type { SecurityCard, SecurityDiff, SecurityFixAction } from '@neat.is/types'\nimport { scanDiffLocal, type ScanDiffOptions } from './security-diff.js'\n\nexport interface FileEdit {\n  // Repo-relative path of the edited file.\n  file: string\n  change: 'manifest-spec' | 'manifest-override' | 'lockfile-regenerated'\n  dependency: string\n  from: string\n  to: string\n}\n\nexport type ApplyOutcome =\n  | { applied: true; action: SecurityFixAction; edits: FileEdit[] }\n  | { applied: false; action?: SecurityFixAction; reason: string }\n\nexport interface ApplyOptions {\n  // The repo-relative directory that holds package.json / package-lock.json.\n  // Default: the directory of the card's dependency.manifest.file.\n  manifestDir?: string\n  // Regenerate the lockfile after the manifest edit. Default: npm\n  // install --package-lock-only --ignore-scripts in the manifest directory.\n  // Injected so the manifest edit is unit-tested without invoking npm.\n  regenerateLock?: (manifestDirAbs: string) => void | Promise<void>\n}\n\ninterface PackageJson {\n  dependencies?: Record<string, string>\n  devDependencies?: Record<string, string>\n  optionalDependencies?: Record<string, string>\n  overrides?: Record<string, string>\n  [k: string]: unknown\n}\n\ninterface LockPkg {\n  version?: string\n  [k: string]: unknown\n}\n\ninterface LockFile {\n  packages?: Record<string, LockPkg>\n  [k: string]: unknown\n}\n\nconst DIRECT_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies'] as const\nconst hasOwn = (o: object, k: string) => Object.prototype.hasOwnProperty.call(o, k)\n\nfunction npmRegenerate(manifestDirAbs: string): void {\n  execFileSync('npm', ['install', '--package-lock-only', '--ignore-scripts', '--no-audit', '--no-fund'], {\n    cwd: manifestDirAbs,\n    stdio: 'ignore',\n  })\n}\n\n// Keep the user's range operator (^, ~, >=, exact pin) and move only the version,\n// so an applied fix reads like the bump a maintainer would have made.\nfunction bumpSpec(prev: string, to: string): string {\n  const op = (/^[\\^~>=< ]+/.exec(prev) ?? [''])[0].trim()\n  return `${op}${to}`\n}\n\n// The resolved version of a package in the lockfile (the first copy found),\n// used only to skip a dependency already at the target.\nfunction lockVersion(lock: LockFile, name: string): string | undefined {\n  for (const [loc, meta] of Object.entries(lock.packages ?? {})) {\n    if ((loc.startsWith('node_modules/') || loc.includes('/node_modules/')) && meta && typeof meta === 'object') {\n      if (loc.slice(loc.lastIndexOf('node_modules/') + 'node_modules/'.length) === name && meta.version) return meta.version\n    }\n  }\n  return undefined\n}\n\n/**\n * Apply a card's fix to the working tree. Edits the manifest deterministically\n * and regenerates the lockfile with npm. Returns applied:false with a reason for\n * anything it will not fix, so a caller never reads \"not handled\" as \"fixed\".\n */\nexport async function applyFixAction(scanPath: string, card: SecurityCard, opts: ApplyOptions = {}): Promise<ApplyOutcome> {\n  const action = card.fix.action\n  const dep = card.dependency\n  if (!action) return { applied: false, reason: 'the card carries no fix action' }\n  if (action.kind !== 'bump-to-fixedIn') {\n    const major = action.majorTo ? `; a fix exists at ${action.majorTo}, but it is a breaking bump` : ''\n    return { applied: false, action, reason: `fix is ${action.kind}: ${action.reason}${major}` }\n  }\n  if (dep.ecosystem !== 'npm') {\n    return { applied: false, action, reason: `ecosystem ${dep.ecosystem} is not supported yet (npm only in v0)` }\n  }\n\n  const manifestDir = opts.manifestDir ?? path.dirname(dep.manifest.file)\n  const pkgRel = path.join(manifestDir, 'package.json')\n  const lockRel = path.join(manifestDir, 'package-lock.json')\n  const dirAbs = path.resolve(scanPath, manifestDir)\n  const pkgAbs = path.resolve(scanPath, pkgRel)\n  const lockAbs = path.resolve(scanPath, lockRel)\n\n  let pkg: PackageJson\n  try {\n    pkg = JSON.parse(await fs.readFile(pkgAbs, 'utf8')) as PackageJson\n  } catch {\n    return { applied: false, action, reason: `could not read package.json at ${pkgRel}` }\n  }\n  let before: string | undefined\n  try {\n    before = lockVersion(JSON.parse(await fs.readFile(lockAbs, 'utf8')) as LockFile, dep.name)\n  } catch {\n    return { applied: false, action, reason: `could not read package-lock.json at ${lockRel}` }\n  }\n  if (before === action.to) return { applied: false, action, reason: `already at ${action.to}` }\n\n  const edits: FileEdit[] = []\n  const directField = DIRECT_FIELDS.find((f) => pkg[f] && hasOwn(pkg[f] as object, dep.name))\n  if (directField) {\n    const field = pkg[directField] as Record<string, string>\n    const prev = String(field[dep.name])\n    const next = bumpSpec(prev, action.to)\n    if (next !== prev) {\n      field[dep.name] = next\n      edits.push({ file: pkgRel, change: 'manifest-spec', dependency: dep.name, from: prev, to: next })\n    }\n  } else {\n    pkg.overrides = pkg.overrides ?? {}\n    const prev = pkg.overrides[dep.name] !== undefined ? String(pkg.overrides[dep.name]) : ''\n    if (prev !== action.to) {\n      pkg.overrides[dep.name] = action.to\n      edits.push({ file: pkgRel, change: 'manifest-override', dependency: dep.name, from: prev, to: action.to })\n    }\n  }\n  await fs.writeFile(pkgAbs, `${JSON.stringify(pkg, null, 2)}\\n`)\n\n  // Regenerate the lockfile so it is complete and installable, not just version-bumped.\n  await (opts.regenerateLock ?? npmRegenerate)(dirAbs)\n  edits.push({ file: lockRel, change: 'lockfile-regenerated', dependency: dep.name, from: before ?? '', to: action.to })\n\n  return { applied: true, action, edits }\n}\n\nexport interface DepApplyResult {\n  dependencyId: string\n  // The manifest.file the deduped cards shared.\n  manifest: string\n  outcome: ApplyOutcome\n}\n\n/**\n * Apply the fixes for a set of cards, once per (dependency, manifest). After the\n * reconcile step every card of a dependency carries the same fix.action, and\n * there are several cards per dependency (one per service and advisory), so a\n * naive per-card loop would apply the same bump many times. This dedups by\n * (dependency.id, manifest.file) and applies each dependency's bump once, in a\n * stable order. Each card derives its own manifest location from the card, so a\n * dependency in two services edits each service's manifest.\n */\nexport async function applyFixes(\n  scanPath: string,\n  cards: SecurityCard[],\n  opts: Pick<ApplyOptions, 'regenerateLock'> = {},\n): Promise<DepApplyResult[]> {\n  const seen = new Map<string, SecurityCard>()\n  for (const c of cards) {\n    const key = `${c.dependency.id}\\u0000${c.dependency.manifest.file}`\n    if (!seen.has(key)) seen.set(key, c)\n  }\n  const out: DepApplyResult[] = []\n  for (const key of [...seen.keys()].sort()) {\n    const c = seen.get(key)!\n    out.push({ dependencyId: c.dependency.id, manifest: c.dependency.manifest.file, outcome: await applyFixAction(scanPath, c, opts) })\n  }\n  return out\n}\n\nexport interface ReverifyResult {\n  outcome: ApplyOutcome\n  // Present only when the fix was applied.\n  reverify?: SecurityDiff\n  // The card's advisory is gone (in `removed`) and the change introduced none.\n  cleared?: boolean\n}\n\n/**\n * Apply the card's fix to the working tree, then scan_diff HEAD (the committed,\n * still-vulnerable state) against the working tree. `cleared` is true when the\n * card's advisory moved to `removed` and no new finding was introduced. Security\n * axis only; the project's own tests are the separate 0-regression check.\n */\nexport async function applyAndReverify(\n  scanPath: string,\n  card: SecurityCard,\n  opts: ApplyOptions & ScanDiffOptions = {},\n): Promise<ReverifyResult> {\n  const { manifestDir, regenerateLock, ...scanOpts } = opts\n  const applyOpts: ApplyOptions = { ...(manifestDir ? { manifestDir } : {}), ...(regenerateLock ? { regenerateLock } : {}) }\n  const outcome = await applyFixAction(scanPath, card, applyOpts)\n  if (!outcome.applied) return { outcome }\n  const reverify = await scanDiffLocal(scanPath, { base: 'HEAD' }, scanOpts)\n  const cleared = reverify.removed.some((e) => e.advisoryId === card.advisory.id) && reverify.introduced.length === 0\n  return { outcome, reverify, cleared }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAKM,kBAOO;AAZb;AAAA;AAAA;AAKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEtC,IAAM,gBAAgC,iCAAiB;AAAA;AAAA;;;ACZ9D,IAmBA,oBAiFM,sBAWA;AA/GN;AAAA;AAAA;AAAA;AAmBA,yBAAgC;AAiFhC,IAAM,uBAA8C;AAAA,MAClD;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAMA,IAAM,gCAAgC,IAAI;AAAA,MACxC,uBAAuB,qBAAqB,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC;AAAA,IAC9E;AAAA;AAAA;;;AC2TO,SAAS,sBAAsB,KAA4B;AAChE,MAAI,OAAO,QAAQ,YAAY,IAAI,WAAW,EAAG,QAAO;AACxD,MAAI,YAAY,KAAK,GAAG,EAAG,QAAO;AAClC,QAAM,Q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AC;AAErH,SAAO,EAAE,SAAS,MAAM,QAAQ,MAAM;AACxC;AAkBA,eAAsB,WACpB,UACA,OACA,OAA6C,CAAC,GACnB;AAC3B,QAAM,OAAO,oBAAI,IAA0B;AAC3C,aAAW,KAAK,OAAO;AACrB,UAAM,MAAM,GAAG,EAAE,WAAW,EAAE,KAAS,EAAE,WAAW,SAAS,IAAI;AACjE,QAAI,CAAC,KAAK,IAAI,GAAG,EAAG,MAAK,IAAI,KAAK,CAAC;AAAA,EACrC;AACA,QAAM,MAAwB,CAAC;AAC/B,aAAW,OAAO,CAAC,GAAG,KAAK,KAAK,CAAC,EAAE,KAAK,GAAG;AACzC,UAAM,IAAI,KAAK,IAAI,GAAG;AACtB,QAAI,KAAK,EAAE,cAAc,EAAE,WAAW,IAAI,UAAU,EAAE,WAAW,SAAS,MAAM,SAAS,MAAM,eAAe,UAAU,GAAG,IAAI,EAAE,CAAC;AAAA,EACpI;AACA,SAAO;AACT;AAgBA,eAAsB,iBACpB,UACA,MACA,OAAuC,CAAC,GACf;AACzB,QAAM,EAAE,aAAa,gBAAgB,GAAG,SAAS,IAAI;AACrD,QAAM,YAA0B,EAAE,GAAI,cAAc,EAAE,YAAY,IAAI,CAAC,GAAI,GAAI,iBAAiB,EAAE,eAAe,IAAI,CAAC,EAAG;AACzH,QAAM,UAAU,MAAM,eAAe,UAAU,MAAM,SAAS;AAC9D,MAAI,CAAC,QAAQ,QAAS,QAAO,EAAE,QAAQ;AACvC,QAAM,WAAW,MAAM,cAAc,UAAU,EAAE,MAAM,OAAO,GAAG,QAAQ;AACzE,QAAM,UAAU,SAAS,QAAQ,KAAK,CAAC,MAAM,EAAE,eAAe,KAAK,SAAS,EAAE,KAAK,SAAS,WAAW,WAAW;AAClH,SAAO,EAAE,SAAS,UAAU,QAAQ;AACtC;","names":["import_node_path","import_node_zlib","import_types","semver","v","fs","path","parseYaml","import_semver","semver","serviceId","serviceName","path","import_types","import_types","import_node_fs","import_node_path","import_semver","import_node_path","import_tree_sitter","import_semver","import_node_path","import_types","import_node_fs","import_node_path","fs","path","fs","path","import_node_fs","import_node_path","import_types","import_node_fs","import_node_path","fs","path","ignore","isDir","path","excluded","walk","fs","entry","serviceName","TypeScript","JavaScript","Python","Go","Ruby","Php","CSharp","Java","Rust","Cpp","firstChildOfType","nameOf","parsers","parserForExt","Parser","path","path","Parser","walk","semver","pep440Cmp","semverCmp","semver","sameName","zlib","path","os","fs","entry","path","import_node_fs","import_node_os","import_node_path","import_types","GraphDefault","import_node_fs","import_node_path","import_node_fs","import_node_path","import_node_fs","import_node_path","import_types","import_node_fs","import_node_os","import_node_path","import_semver","path","os","semver","fs","import_types","import_types","frontierId","import_types","import_node_path","import_tree_sitter","import_tree_sitter_javascript","import_tree_sitter_python","import_tree_sitter_go","import_tree_sitter_ruby","import_tree_sitter_php","import_tree_sitter_rust","import_types","import_node_fs","import_node_path","import_types","module","walk","fs","path","import_node_path","import_node_fs","import_tree_sitter","import_tree_sitter_javascript","import_tree_sitter_python","import_tree_sitter_go","import_types","PARSE_CHUNK","parseSource","Parser","JavaScript","Python","Go","firstArg","fs","path","entry","serviceName","snippet","goImports","PARSE_CHUNK","parseSource","makeJsParser","Parser","JavaScript","makePyParser","Python","makeGoParser","Go","Ruby","Php","Rust","fn","leaf","path","parseSource","path","collect","plural","makeJsParser","makePyParser","makeGoParser","import_types","entry","import_types","import_types","import_types","frontierId","serviceId","frontierId","serviceId","import_node_fs","import_node_path","import_ignore","import_minimatch","import_types","import_node_fs","import_node_path","entry","path","fs","parseToml","import_node_fs","import_node_path","import_types","walk","fs","entry","path","module","import_node_fs","import_node_path","import_types","fs","path","import_node_path","import_types","path","import_node_fs","import_node_path","import_types","fs","entry","path","import_node_fs","import_node_path","import_types","path","fs","import_node_fs","import_node_path","import_types","fs","entry","path","import_node_fs","import_node_path","import_smol_toml","import_types","path","parseToml","fs","import_node_fs","import_node_path","import_types","path","fs","import_node_fs","import_node_path","import_types","fs","entry","path","import_node_fs","import_node_path","path","fs","path","fs","ignore","entry","import_node_path","import_node_fs","import_yaml","import_types","serviceId","path","fs","entry","import_node_path","path","import_node_path","import_tree_sitter","import_types","walk","parsers","Parser","serviceName","path","import_node_path","import_tree_sitter","import_types","Parser","serviceName","path","walk","import_node_path","import_tree_sitter","import_types","Parser","path","t","import_node_path","import_tree_sitter","import_types","stringLiteralText","parsers","parserForExt","Parser","path","fn","import_node_path","import_types","import_node_path","parse","path","import_node_fs","import_node_path","import_node_fs","import_node_path","fs","path","parse","fs","entry","path","import_node_path","parse","path","parse","parse","import_node_path","parse","path","entry","parse","import_node_path","parse","path","entry","import_node_fs","import_node_path","path","fs","parse","import_node_fs","import_node_path","import_yaml","parse","path","fs","import_node_path","parse","path","serviceName","path","import_node_fs","import_node_path","import_types","excluded","path","walk","fs","entry","configFiles","import_node_fs","import_node_path","import_types","import_yaml","isRecord","parseYaml","STRING_LITERAL_RE","path","fs","node","import_node_path","import_tree_sitter","import_tree_sitter_java","import_types","PARSE_CHUNK","parseSource","Parser","Java","path","import_node_path","import_tree_sitter","import_tree_sitter_python","import_types","PARSE_CHUNK","parseSource","walk","entry","Parser","Python","path","import_node_fs","import_node_path","import_yaml","import_types","CONFIG_FILES","HTTP_METHODS","resolvePlaceholders","path","fs","edge","import_node_fs","import_node_path","import_types","lineAt","serviceName","excluded","path","walk","fs","entry","import_types","import_node_path","import_tree_sitter","import_tree_sitter_javascript","import_tree_sitter_typescript","import_tree_sitter_python","import_types","PARSE_CHUNK","parseSource","GRAMMAR_BY_EXT","TypeScript","JavaScript","Python","Parser","path","import_node_path","import_tree_sitter","import_tree_sitter_javascript","import_types","PARSE_CHUNK","parseSource","makeJsParser","Parser","JavaScript","walk","entry","path","dedupKey","fileNodeId","n","e","import_node_path","import_types","path","import_node_path","import_types","path","import_node_path","import_types","findAll","path","import_node_path","import_types","readImports","path","import_node_path","import_types","readImports","path","import_node_path","import_tree_sitter","import_tree_sitter_javascript","import_types","parserForExt","Parser","JavaScript","stringLiteralText","walk","path","collect","entry","import_node_path","import_types","path","import_node_path","import_tree_sitter","import_tree_sitter_python","import_types","PARSE_CHUNK","makePyParser","Parser","Python","parseSource","namedChildren","pyStaticStringText","walk","path","import_node_path","import_tree_sitter","import_tree_sitter_python","import_types","PARSE_CHUNK","makePyParser","Parser","Python","parseSource","namedChildren","walk","pyStaticStringText","path","import_node_path","import_tree_sitter","import_tree_sitter_python","import_types","PARSE_CHUNK","makePyParser","Parser","Python","parseSource","namedChildren","pyStaticStringText","walk","path","import_node_path","import_tree_sitter","import_tree_sitter_javascript","import_types","parserForExt","Parser","JavaScript","namedChildren","stringLiteralText","keyName","path","walk","tableName","import_node_path","import_types","path","import_node_path","import_tree_sitter","import_tree_sitter_ruby","import_types","PARSE_CHUNK","makeRubyParser","Parser","Ruby","parseSource","walk","rubyLiteral","rubyArgs","rubyPositional","rubyKwarg","path","import_node_path","import_tree_sitter","import_tree_sitter_php","import_types","PARSE_CHUNK","makePhpParser","Parser","Php","parseSource","walk","phpStaticString","phpArgumentValues","phpFirstString","pluralize","tableize","path","modelTable","import_node_path","import_tree_sitter","import_tree_sitter_go","import_types","PARSE_CHUNK","makeGoParser","Parser","Go","parseSource","walk","path","import_node_path","import_tree_sitter","import_tree_sitter_go","import_types","PARSE_CHUNK","makeGoParser","Parser","Go","parseSource","walk","pluralize","path","import_node_path","import_tree_sitter","import_tree_sitter_c_sharp","import_types","PARSE_CHUNK","Parser","CSharp","parseSource","walk","firstArg","path","import_node_path","import_tree_sitter","import_tree_sitter_javascript","import_types","parserForExt","Parser","JavaScript","namedChildren","stringLiteralValue","path","walk","import_node_path","import_tree_sitter","import_tree_sitter_python","import_types","PARSE_CHUNK","makePyParser","Parser","Python","parseSource","namedChildren","walk","enclosingFunction","nearestAssignmentValue","path","import_node_path","import_tree_sitter","import_tree_sitter_java","import_types","PARSE_CHUNK","parseSource","walk","endpoint","path","Parser","Java","import_node_path","import_tree_sitter","import_tree_sitter_java","import_types","PARSE_CHUNK","HTTP_METHODS","parseSource","makeJavaParser","Parser","Java","walk","stringLiteral","buildRouteIndex","path","import_types","import_node_path","import_types","path","import_node_path","import_node_fs","import_types","path","fs","import_node_fs","import_node_path","import_types","fs","entry","path","lineAt","import_node_fs","import_node_path","import_yaml","import_types","walkYamlFiles","fs","entry","path","import_node_fs","import_node_path","import_smol_toml","import_types","path","fs","parseToml","lineContaining","entry","import_node_fs","import_node_path","import_types","path","fs","import_node_fs","import_node_path","import_smol_toml","import_types","path","fs","parseToml","import_node_fs","import_node_path","import_smol_toml","import_types","path","fs","parseToml","import_node_fs","import_node_path","import_types","path","fs","import_node_path","import_tree_sitter","import_tree_sitter_javascript","import_types","parserForExt","Parser","JavaScript","namedChildren","stringLiteralText","keyName","path","import_types","import_node_fs","import_node_path","import_smol_toml","import_yaml","import_types","import_node_path","entry","path","import_node_path","entry","path","import_yaml","entry","parseYaml","walk","serviceName","entry","fs","path","parseYaml","parseToml","import_node_path","import_types","import_node_fs","import_node_os","import_node_path","fs","path","path","fs","entry","names","serviceId","collect","parseSource","path","import_node_path","import_node_fs","import_node_path","import_types","endpoint","path","path","serviceName","path","fs","git","entry","os","import_node_fs","import_node_path","path","fs"]}