Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

57.8 KB
Raw Blame
{ inputs, ... }:
{
  perSystem =
    { system, ... }:
    let
      inherit (inputs)
        nixpkgs
        fenix
        crane
        ;
      pkgs = import nixpkgs {
        system = system;
      };
      isDarwin = pkgs.stdenv.isDarwin;
      isLinux = pkgs.stdenv.isLinux;

      # ── cloud-storage (Rust backend) ──────────────────────────────

      rustToolchain = fenix.packages.${system}.fromToolchainFile {
        file = ../rust-toolchain.toml;
        sha256 = "sha256-qqF33vNuAdU5vua96VKVIwuc43j4EFeEXbjQ6+l4mO4=";
      };

      craneLib = (crane.mkLib pkgs).overrideToolchain rustToolchain;

      libraries =
        with pkgs;
        [
          openssl
          openssl.dev
          # librdkafka 2.12's cmake config header always defines
          # WITH_OAUTHBEARER_OIDC (via #cmakedefine01), and rdkafka_conf.c
          # guards its curl include with #ifdef instead of #if, so the bundled
          # cmake-build needs curl headers even with WITH_CURL=0. Headers only;
          # nothing links against libcurl.
          curl.dev
          glib
          glib.dev
          libclang
          xz.out
        ]
        ++ pkgs.lib.optionals isDarwin [
          libiconv
        ];

      # Do not add glibc.dev directly to buildInputs/libraries on Linux. The
      # GCC wrapper already adds glibc headers as an -idirafter path; adding
      # glibc.dev through the setup hook turns it into an early -isystem path,
      # which breaks libstdc++'s #include_next <stdlib.h> while building C++
      # sources such as bundled librdkafka.

      # Include Cargo sources plus the .sqlx offline query cache.
      sqlxFilter = path: _type: builtins.match ".*\\.sqlx/.*\\.json$" path != null;
      pdfiumFilter = path: _type: builtins.match ".*pdfium-lib/.*\\.(so|dylib)$" path != null;
      # `.sh` is required so `include_str!` of
      # `crates/agent_harness/container/ensure_ready.sh` survives the prune;
      # `.ttf` and `.xml` for the fonts and preset shape definitions that
      # `crates/pptx_engine` embeds with `include_bytes!`; `.graphql` for the
      # `static_assets/schema.graphql` that `cache-core`'s build script reads;
      # `.jsonl` for the recorded sessions `agent_fold` tests embed; `.mjs`
      # for the Deno bootstrap and timer shims;
      # `.proto` for the protobuf files the `whatsmeow_proto` and
      # `whatsmeow_signal` build scripts compile.
      assetFilter =
        path: _type:
        builtins.match ".*\\.(md|html|txt|json|jsonl|canvas|sql|sh|ttf|xml|graphql|mjs|proto)$" path != null;
      # `crates/routine_program` embeds its starter programs with `include_str!`.
      # Only these `.ts` files: matching every `.ts` would pull the web app into
      # the Rust source hash.
      routineStartersFilter =
        path: _type: builtins.match ".*/crates/routine_program/src/starters/[^/]*\\.ts$" (toString path) != null;
      # Rust templates (askama, minijinja) include their stylesheets, such as
      # `services/mcp_auth_proxy/templates/broker_page.css`. Only `templates/`
      # stylesheets under Rust crates and services: matching every `.css` would
      # pull the web app into the Rust source hash.
      templateCssFilter =
        path: _type:
        builtins.match ".*/(crates|services)/[^/]+/templates/.*\\.css$" (toString path) != null;
      # Rust local HTTP clients embed only the public proxy CA, never its keys.
      localCaFilter = path: _type: pkgs.lib.hasSuffix "/infra/local/certs/ca.pem" (toString path);
      binFilter = path: _type: builtins.match ".*\\.bin$" path != null;
      srcFilter =
        path: type:
        (sqlxFilter path type)
        || (localCaFilter path type)
        || (pdfiumFilter path type)
        || (assetFilter path type)
        || (routineStartersFilter path type)
        || (templateCssFilter path type)
        || (binFilter path type)
        || (craneLib.filterCargoSources path type);
      cloudStorageSrc = pkgs.lib.cleanSourceWith {
        src = ../.;
        filter = srcFilter;
      };
      src = cloudStorageSrc;

      # ── Per-artifact pruned deploy sources ────────────────────────
      # .github/workspace-dep-closures.json (generated by `just hakari` via
      # tooling/xtask, drift-checked in CI) maps every workspace
      # crate to its transitive workspace dependency
      # closure. Each deploy leaf builds from a tree where only the crates in
      # its closure keep real sources; every other member is reduced to its
      # manifest plus a crane stub target. A leaf's store hash then only
      # moves when a crate it actually depends on changes — an email-only
      # change leaves the other deploy derivations as pure substitutions
      # from Namespace's Nix cache instead of full workspace-subgraph rebuilds.
      # Manifest or Cargo.lock changes still invalidate every leaf (the stub
      # layer embeds them all); those are the rare structural commits.
      #
      # Soundness: a stale map fails loud, not silent. A missing closure
      # crate means its stub (empty lib) gets compiled and the dependent
      # crate fails to resolve its items; a deleted dir fails at eval. CI
      # regenerates the map and rejects drift before merge.
      workspaceDepClosures =
        (builtins.fromJSON (builtins.readFile ../.github/workspace-dep-closures.json)).closures;

      # Manifests + Cargo.lock + stub targets for every member, shared by all
      # pruned sources; only changes when a manifest or the lock changes.
      deployDummySrc = craneLib.mkDummySrc { inherit src; };

      # Real sources of one workspace crate dir, same filter as the full tree
      # (keeps per-crate assets: pdfium blobs, .sql migrations, templates).
      crateDirSrc =
        dir:
        pkgs.lib.cleanSourceWith {
          src = ../. + "/${dir}";
          filter = srcFilter;
          name = "crate-${builtins.replaceStrings [ "/" ] [ "-" ] dir}";
        };

      # Workspace-root files that crates read across crate boundaries: the
      # .sqlx offline cache (sqlx macros resolve it from the workspace root),
      # shared assets under static_assets/ (include_bytes!-ed from workspace
      # crates), and the [patch.crates-io] crates under vendor/, which
      # mkDummySrc would otherwise stub out. Included in every pruned source, so a
      # sqlx prepare still invalidates all leaves — coarser than ideal, but
      # the query-to-crate mapping is not recoverable from the file names.
      rootDepsSrc = pkgs.lib.cleanSourceWith {
        src = ../.;
        name = "cloud-storage-root-deps";
        filter =
          path: type:
          let
            rel = pkgs.lib.removePrefix ((toString ../.) + "/") (toString path);
          in
          (rel == "infra")
          || (rel == "infra/local")
          || (rel == "infra/local/certs")
          || (localCaFilter path type)
          || (rel == ".sqlx")
          || (pkgs.lib.hasPrefix ".sqlx/" rel)
          || (rel == "static_assets")
          || (pkgs.lib.hasPrefix "static_assets/" rel)
          || (rel == "vendor")
          || (rel == "vendor/utoipa-swagger-ui")
          || (pkgs.lib.hasPrefix "vendor/utoipa-swagger-ui/" rel)
          || (
            type == "regular"
            && !(pkgs.lib.hasInfix "/" rel)
            && ((assetFilter path type) || (binFilter path type))
          );
      };

      prunedDeploySrc =
        pname: rootPackage:
        let
          # Generator emits dirs sorted, so parents always precede nested
          # members and overlays land inside already-materialised parents.
          dirs =
            workspaceDepClosures.${rootPackage} or (throw (
              "No '${rootPackage}' entry in .github/workspace-dep-closures.json; "
              + "run `just hakari` from the repository root and commit the result."
            ));
          overlays = pkgs.lib.concatMapStrings (dir: ''
            rm -rf "$out/${dir}"
            cp -rT ${crateDirSrc dir} "$out/${dir}"
            chmod -R +w "$out/${dir}"
          '') dirs;
        in
        pkgs.runCommand "cloud-storage-src-${pname}" { } ''
          cp -rT ${deployDummySrc} $out
          chmod -R +w $out
          cp -rfT ${rootDepsSrc} $out
          chmod -R +w $out
          ${overlays}
        '';

      # ── Code-mode assets ──────────────────────────────────────────
      # crates/code_mode_assets embeds the Deno SDK bundle and agent SDK docs.
      # Its build script runs the generator itself unless CODE_MODE_ASSETS_DIR
      # names prebuilt assets, as every Nix build of it does: the sandbox has
      # no network for a bun install. Keep this filter in step with the build
      # script's GENERATOR_INPUTS.
      jsNodeModules = pkgs.callPackage ../nix-support/node_modules.nix { src = ../.; };

      codeModeAssetsSrc = pkgs.lib.cleanSourceWith {
        src = ../.;
        name = "code-mode-assets-src";
        filter =
          path: type:
          let
            rel = pkgs.lib.removePrefix ((toString ../.) + "/") (toString path);
            segments = pkgs.lib.splitString "/" rel;
            isUnder = directory: rel == directory || pkgs.lib.hasPrefix "${directory}/" rel;
          in
          !(builtins.elem "node_modules" segments)
          && !(builtins.elem "dist" segments)
          && (
            builtins.elem rel [
              "bun.lock"
              "package.json"
              "packages"
            ]
            || builtins.any isUnder [
              "packages/code-mode-sdk"
              "packages/sdk"
              "packages/sdk-docs"
            ]
          );
      };

      codeModeAssets = pkgs.stdenvNoCC.mkDerivation {
        pname = "code-mode-assets";
        version = "0.1.0";
        src = codeModeAssetsSrc;
        nativeBuildInputs = [ pkgs.bun ];
        dontConfigure = true;
        buildPhase = ''
          runHook preBuild
          export HOME="$TMPDIR/home"
          mkdir -p "$HOME"
          for project in . packages/sdk packages/sdk-docs packages/code-mode-sdk; do
            if [ -d "${jsNodeModules}/$project/node_modules" ]; then
              cp -a "${jsNodeModules}/$project/node_modules" "$project/"
            fi
          done
          bun packages/code-mode-sdk/scripts/generate.ts "$out"
          runHook postBuild
        '';
        dontInstall = true;
        dontFixup = true;
      };

      codeModeAssetsEnv = {
        CODE_MODE_ASSETS_DIR = "${codeModeAssets}";
      };

      commonArgs = {
        inherit src;
        pname = "cloud-storage";
        version = "0.1.0";
        strictDeps = true;
        buildInputs = libraries;
        # Cargo/crane need git in the sandbox to fetch git dependencies.
        # Without this, CI can fall back to host /usr/lib/git-core helpers,
        # which are not ABI-compatible with Nix-provided glibc.
        nativeBuildInputs =
          with pkgs;
          [
            cmake
            git
            pkg-config
          ]
          ++ pkgs.lib.optionals isLinux [ mold ];
        LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";
        OPENSSL_NO_VENDOR = "1";
        SQLX_OFFLINE = "true";
        # Keep vendoring independent of the generated src derivation and pin
        # git dependencies so Nix does not fall back to host git helpers in CI.
        cargoVendorDir = craneLib.vendorCargoDeps {
          src = ../.;
          cargoLock = ../Cargo.lock;
          outputHashes = import ../nix-support/root-cargo-output-hashes.nix;
        };
        RUSTFLAGS = pkgs.lib.optionalString isLinux "-C link-arg=-fuse-ld=mold";
        # Build deps + workspace + bins in dev profile so the test job (which runs
        # `cargo nextest` outside the sandbox using the test profile, inheriting dev)
        # can reuse the restored target/debug/ instead of recompiling all deps.
        CARGO_PROFILE = "dev";
      }
      // pkgs.lib.optionalAttrs isLinux {
        LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libraries}";
        BINDGEN_EXTRA_CLANG_ARGS = "-I${pkgs.glibc.dev}/include -I${pkgs.gcc.cc}/lib/gcc/${pkgs.stdenv.hostPlatform.config}/${pkgs.gcc.version}/include";
      };

      # Pre-built third-party deps cached by Namespace; hash is driven by Cargo.lock
      # (workspace member sources are stubbed by crane), so it survives most PRs.
      # --all-features matches the test job (cargo nextest --all-features) and clippy
      # so all consumers share the same dep feature unification.
      cargoArtifacts = craneLib.buildDepsOnly (
        commonArgs
        // {
          cargoExtraArgs = "--locked --all-features";
        }
      );

      # Layered atop cargoArtifacts: pre-compile every workspace lib crate so
      # downstream derivations (openApiBins, clippy) inherit a warm target/. The
      # hash is per-source so Namespace's Nix cache only hits when the SHA
      # matches across CI workflows — but since code-check-cloud-storage and
      # web-app-check-main both run on the same SHA, whichever finishes first
      # populates the cache for the other.
      # sync_service is checked separately with its supported default feature
      # set because its KV and R2 storage features are mutually exclusive.
      workspaceArtifacts = craneLib.cargoBuild (
        commonArgs
        // codeModeAssetsEnv
        // {
          inherit cargoArtifacts;
          pname = "cloud-storage-workspace";
          doCheck = false;
          doInstallCargoArtifacts = true;
          cargoExtraArgs = "--locked --all-features --workspace --lib --exclude sync_service";
          # Keep RUSTFLAGS identical to cargoArtifacts: any difference changes
          # cargo's fingerprint and recompiles every dependency in this layer.
          # The clippy checks enforce `-D warnings`.
          RUSTDOCFLAGS = "-Dwarnings";
        }
      );

      cloudStorageCargoToml = builtins.fromTOML (builtins.readFile ../Cargo.toml);
      cloudStorageWorkspaceMembers =
        cloudStorageCargoToml.workspace.members or (throw "Cargo.toml is missing workspace.members");

      dopplerConfigBinNames =
        let
          dopplerConfigPath = "src/doppler_config.rs";
          matchingDopplerBins =
            member:
            let
              memberDir = ../. + "/${member}";
              manifestFile = memberDir + "/Cargo.toml";
              hasConfig = builtins.pathExists (memberDir + "/src/config.rs");
              hasDopplerConfig = builtins.pathExists (memberDir + "/${dopplerConfigPath}");
              manifest = builtins.fromTOML (builtins.readFile manifestFile);
              matchingBins = builtins.filter (bin: (bin.path or null) == dopplerConfigPath) (manifest.bin or [ ]);
              missingNameError = "cloud-storage workspace member '${member}' has a ${dopplerConfigPath} bin without a name";
              matchingBinNames = map (bin: bin.name or (throw missingNameError)) matchingBins;
            in
            if !hasDopplerConfig then
              [ ]
            else if !(builtins.pathExists manifestFile) then
              throw "cloud-storage workspace member '${member}' has ${dopplerConfigPath} but no Cargo.toml"
            else if matchingBinNames == [ ] then
              throw (
                "cloud-storage workspace member '${member}' has ${dopplerConfigPath} "
                + "but no [[bin]] with path = \"${dopplerConfigPath}\""
              )
            else if !hasConfig then
              [ ]
            else
              matchingBinNames;
        in
        pkgs.lib.unique (pkgs.lib.concatMap matchingDopplerBins cloudStorageWorkspaceMembers);

      dopplerConfigBinPackages = builtins.listToAttrs (
        map (
          binName:
          pkgs.lib.nameValuePair "doppler-config-bin-${binName}" (
            craneLib.buildPackage (
              commonArgs
              // codeModeAssetsEnv
              // {
                # Reuse the dependency-only layer, then compile only this
                # Doppler config binary and the local crates it actually uses.
                inherit cargoArtifacts;
                pname = "cloud-storage-doppler-config-${binName}";
                doCheck = false;
                cargoExtraArgs = pkgs.lib.concatStringsSep " " [
                  "--locked"
                  "--all-features"
                  "--bin ${binName}"
                ];
              }
            )
          )
        ) dopplerConfigBinNames
      );

      dopplerConfigBins = pkgs.symlinkJoin {
        name = "cloud-storage-doppler-config";
        paths = builtins.attrValues dopplerConfigBinPackages;
      };

      openApiBins = craneLib.buildPackage (
        commonArgs
        // codeModeAssetsEnv
        // {
          cargoArtifacts = workspaceArtifacts;
          pname = "cloud-storage-openapi";
          doCheck = false;
          cargoExtraArgs = pkgs.lib.concatStringsSep " " [
            "--locked"
            "--all-features"
            "--bin document_storage_service_openapi"
            "--bin properties_service_openapi"
            "--bin agent_harness_cognition_openapi"
            "--bin authentication_service_openapi"
            "--bin notification_service_openapi"
            "--bin static_file_service_openapi"
            "--bin connection_gateway_openapi"
            "--bin contacts_service_openapi"
            "--bin unfurl_service_openapi"
            "--bin calendar_service_openapi"
            "--bin email_service_openapi"
            "--bin search_service_openapi"
            "--bin scheduled_action_openapi"
            "--bin gen_tool_schemas"
          ];
        }
      );

      # Pre-built nextest archive — packages all compiled test binaries plus their
      # metadata into a single tar.zst. CI fetches this archive and runs
      # `cargo nextest run --archive-file` outside the sandbox so tests can hit
      # postgres/redis services. Built in Nix and cached by Namespace.
      nextestArchive = craneLib.mkCargoDerivation (
        commonArgs
        // codeModeAssetsEnv
        // {
          cargoArtifacts = workspaceArtifacts;
          pname = "cloud-storage-nextest-archive";
          doCheck = false;
          nativeBuildInputs = commonArgs.nativeBuildInputs or [ ] ++ [ pkgs.cargo-nextest ];
          buildPhaseCargoCommand = ''
            cargo nextest archive \
              --cargo-profile dev \
              --locked --all-features \
              --workspace --lib --bins --tests \
              --exclude sync_service \
              --archive-file nextest-archive.tar.zst
          '';
          installPhaseCommand = ''
            mkdir -p $out
            cp nextest-archive.tar.zst $out/
          '';
        }
      );

      deployServiceBinaryDefinitions = [
        {
          serviceName = "agent-harness-service";
          packageName = "agent_harness_service";
          binaries = [ "agent_harness_service" ];
        }
        {
          serviceName = "authentication-service";
          packageName = "authentication_service";
          binaries = [ "authentication_service" ];
        }
        {
          serviceName = "calendar-service";
          packageName = "calendar_service";
          binaries = [ "calendar_service" ];
        }
        {
          serviceName = "connection-gateway";
          packageName = "connection_gateway";
          binaries = [ "connection_gateway_service" ];
        }
        {
          serviceName = "contacts-service";
          packageName = "contacts_service";
          binaries = [ "contacts_service" ];
        }
        {
          serviceName = "convert-service";
          packageName = "convert_service";
          binaries = [ "convert_service" ];
        }
        {
          serviceName = "document-storage-service";
          packageName = "document_storage_service";
          binaries = [ "document_storage_service" ];
        }
        {
          serviceName = "slack-import-worker";
          packageName = "slack_import_worker";
          binaries = [ "slack_import_worker" ];
        }
        {
          serviceName = "email-service";
          packageName = "email_service";
          binaries = [
            "email_service"
            "pubsub_workers"
          ];
        }
        {
          serviceName = "email-focus-worker";
          packageName = "email_focus_worker";
          binaries = [ "email_focus_worker" ];
        }
        {
          serviceName = "image-proxy-service";
          packageName = "image_proxy_service";
          binaries = [ "image_proxy_service" ];
        }
        {
          serviceName = "notification-service";
          packageName = "notification_service";
          binaries = [ "notification_service" ];
        }
        {
          serviceName = "search-processing-service";
          packageName = "search_processing_service";
          binaries = [ "search_processing_service" ];
        }
        {
          serviceName = "static-file-service";
          packageName = "static_file_service";
          binaries = [ "static_file_service" ];
        }
        {
          serviceName = "unfurl-service";
          packageName = "unfurl_service";
          binaries = [ "unfurl_service" ];
        }
        {
          serviceName = "whatsapp-session-service";
          packageName = "whatsapp_session_service";
          binaries = [ "whatsapp_session_service" ];
        }
      ];

      localStackBinaryDefinitions = [
        {
          serviceName = "local-authentication";
          packageName = "authentication_service";
          binaries = [ "authentication_service" ];
          featureArgs = "--no-default-features --features return_passwordless_code";
        }
        {
          serviceName = "local-search-processing";
          packageName = "search_processing_service";
          binaries = [ "search_processing_service" ];
          featureArgs = "--no-default-features --features processing,service";
        }
        {
          serviceName = "local-upload-finalizer";
          packageName = "document_upload_finalizer_handler";
          binaries = [ "document_upload_finalizer_local_worker" ];
        }
        {
          serviceName = "local-agent-trigger";
          packageName = "agent_trigger_service";
          binaries = [ "agent_trigger_service" ];
        }
        {
          serviceName = "local-seed-cli";
          packageName = "seed_cli";
          binaries = [ "seed_cli" ];
        }
      ];

      deployBinaryCargoExtraArgs =
        "--locked "
        + pkgs.lib.concatMapStringsSep " " (
          def:
          "--package ${def.packageName} "
          + pkgs.lib.concatMapStringsSep " " (binary: "--bin ${binary}") def.binaries
        ) deployServiceBinaryDefinitions;

      deployCargoArtifacts = craneLib.buildDepsOnly (
        commonArgs
        // {
          pname = "cloud-storage-deploy-deps";
          doCheck = false;
          # buildDepsOnly runs a cargo check in buildPhase by default; keep this
          # warm artifact to release deps only.
          cargoCheckCommand = "true";
          cargoExtraArgs = deployBinaryCargoExtraArgs;
          CARGO_PROFILE = "release";
        }
      );

      deployServiceBinaryPackage =
        {
          serviceName,
          packageName,
          binaries,
          featureArgs ? "",
        }:
        craneLib.buildPackage (
          commonArgs
          # Only services that embed the assets depend on them, so an SDK
          # change leaves the other deploy derivations cached.
          // pkgs.lib.optionalAttrs (builtins.elem "crates/code_mode_assets" (
            workspaceDepClosures.${packageName} or [ ]
          )) codeModeAssetsEnv
          // {
            # Pruned source: this derivation only rebuilds when a crate in
            # the service's own workspace closure changes.
            src = prunedDeploySrc "service-${serviceName}" packageName;
            cargoArtifacts = deployCargoArtifacts;
            pname = "cloud-storage-${serviceName}-binaries";
            doCheck = false;
            cargoExtraArgs =
              "--locked --package ${packageName} "
              + pkgs.lib.concatMapStringsSep " " (binary: "--bin ${binary}") binaries
              + pkgs.lib.optionalString (featureArgs != "") " ${featureArgs}";
            CARGO_PROFILE = "release";
            installPhaseCommand = ''
              mkdir -p $out/bin
              for binary in ${pkgs.lib.concatStringsSep " " binaries}; do
                cp target/release/$binary $out/bin/$binary
                ${pkgs.binutils}/bin/strip $out/bin/$binary || true
              done
            '';
          }
        );

      deployServiceBinaryPackages = pkgs.lib.listToAttrs (
        map (def: {
          name = "deploy-service-binaries-${def.serviceName}";
          value = deployServiceBinaryPackage def;
        }) deployServiceBinaryDefinitions
      );

      # DSS and its worker are separate Cargo packages with separate pruned
      # source closures, but CI hands both binaries to the same Pulumi stack.
      # Bundle only the deploy output; local-stack-binaries keeps the worker
      # opt-in by continuing to use the unbundled deployServiceBinaryPackages.
      documentStorageDeployBinaries =
        let
          cfg = builtins.fromJSON (builtins.readFile ../.github/services-config.json);
          checkBinaries = pkgs.lib.concatMapStringsSep "\n" (binary: ''
            test -x "$out/bin/${binary}" || {
              echo "Missing deploy binary: ${binary}" >&2
              exit 1
            }
          '') cfg.services.document-storage-service.deploy_binaries;
        in
        pkgs.runCommand "cloud-storage-document-storage-service-deploy-binaries" { } ''
          mkdir -p $out/bin
          cp ${deployServiceBinaryPackages.deploy-service-binaries-document-storage-service}/bin/* $out/bin/
          cp ${deployServiceBinaryPackages.deploy-service-binaries-slack-import-worker}/bin/* $out/bin/
          ${checkBinaries}
        '';

      # Same for the email service and its Focus worker.
      emailServiceDeployBinaries =
        let
          cfg = builtins.fromJSON (builtins.readFile ../.github/services-config.json);
          checkBinaries = pkgs.lib.concatMapStringsSep "\n" (binary: ''
            test -x "$out/bin/${binary}" || {
              echo "Missing deploy binary: ${binary}" >&2
              exit 1
            }
          '') cfg.services.email-service.deploy_binaries;
        in
        pkgs.runCommand "cloud-storage-email-service-deploy-binaries" { } ''
          mkdir -p $out/bin
          cp ${deployServiceBinaryPackages.deploy-service-binaries-email-service}/bin/* $out/bin/
          cp ${deployServiceBinaryPackages.deploy-service-binaries-email-focus-worker}/bin/* $out/bin/
          ${checkBinaries}
        '';

      localStackBinaryPackages = pkgs.lib.listToAttrs (
        map (def: {
          name = "local-stack-binaries-${def.serviceName}";
          value = deployServiceBinaryPackage def;
        }) localStackBinaryDefinitions
      );

      localStackDeployServiceNames = [
        "agent-harness-service"
        "calendar-service"
        "connection-gateway"
        "contacts-service"
        "document-storage-service"
        "email-service"
        "image-proxy-service"
        "notification-service"
        "static-file-service"
        "unfurl-service"
        "whatsapp-session-service"
      ];

      localStackBinaries = pkgs.buildEnv {
        name = "local-stack-binaries";
        pathsToLink = [ "/bin" ];
        paths =
          pkgs.lib.attrValues localStackBinaryPackages
          ++ map (
            serviceName: deployServiceBinaryPackages."deploy-service-binaries-${serviceName}"
          ) localStackDeployServiceNames;
      };

      # ── Lambda builds (crane + cargo-zigbuild) ─────────────────────
      # SPIKE: build a Rust Lambda handler reproducibly under nix/crane so
      # lambdas ride the same content-addressed cache as the service binaries
      # (Namespace Nix store volume) instead of a cargo-in-checkout that
      # recompiles the workspace every run. cargo-zigbuild pins the Lambda
      # glibc via a target *suffix* (no toolchain swap; host triple == lambda
      # triple, so no extra rust-std). The binary is renamed `bootstrap` and
      # zipped for the provided.al2/al2023 custom runtime.
      lambdaTarget = "x86_64-unknown-linux-gnu";
      # glibc 2.26 == Amazon Linux 2; forward-compatible with al2023.
      lambdaZigTarget = "${lambdaTarget}.2.26";

      callRecordingPreviewFfmpegLayer =
        let
          ffmpegVersion = "7.0.2";
          # johnvansickle.com is the upstream but has had multi-hour outages.
          # The GitHub copies are byte-identical (the hash enforces it) and
          # pinned to commits; fetchurl tries each URL in order.
          ffmpegArchive = pkgs.fetchurl {
            urls = [
              "https://raw.githubusercontent.com/1871847400/mikufans/95396855e335ba04b6fb300a5a688a1ac753ffea/docker/backend/ffmpeg-${ffmpegVersion}-amd64-static.tar.xz"
              "https://raw.githubusercontent.com/DAIRO-HY/DairoMusicSearch/e49a8c67aaa4ed1cd4e0d655052ee2d65c1aef8e/document/docker/ffmpeg-${ffmpegVersion}-amd64-static.tar.xz"
              "https://johnvansickle.com/ffmpeg/releases/ffmpeg-${ffmpegVersion}-amd64-static.tar.xz"
            ];
            hash = "sha256-q9qNd86DCRQfg6uO3wWWg0CHxSRn9rrfN2pqKkyHz2c=";
          };
        in
        pkgs.runCommand "call-recording-preview-ffmpeg-layer"
          {
            nativeBuildInputs = [
              pkgs.coreutils
              pkgs.gnutar
              pkgs.unzip
              pkgs.xz
              pkgs.zip
            ];
          }
          ''
            set -euo pipefail

            archive_dir="ffmpeg-${ffmpegVersion}-amd64-static"
            mkdir -p extract package/bin "$out/call_recording_preview_handler"
            tar -xJf ${ffmpegArchive} -C extract \
              "$archive_dir/ffmpeg" \
              "$archive_dir/ffprobe"
            install -m 0755 "extract/$archive_dir/ffmpeg" package/bin/ffmpeg
            install -m 0755 "extract/$archive_dir/ffprobe" package/bin/ffprobe
            touch -h -d @315532800 package/bin/ffmpeg package/bin/ffprobe

            (
              cd package
              zip -9 -q -X "$out/call_recording_preview_handler/ffmpeg-layer.zip" bin/ffmpeg bin/ffprobe
            )
            unzip -tqq "$out/call_recording_preview_handler/ffmpeg-layer.zip" >/dev/null
          '';

      # cargo hashes the linker path into every crate's fingerprint, and zigbuild
      # writes its linker wrapper under its cache directory. Under $TMPDIR, which
      # is random per build on the CI runners, no handler could reuse the shared
      # dependency layer. /tmp isn't usable instead because it isn't private there.
      # Generating the wrappers into the store gives every build one path, and
      # zigbuild only rewrites a wrapper whose content differs.
      zigbuildWrappers =
        pkgs.runCommand "cargo-zigbuild-wrappers"
          {
            nativeBuildInputs = [
              rustToolchain
              pkgs.cargo-zigbuild
              pkgs.zig
            ];
          }
          ''
            export HOME="$TMPDIR/home" XDG_CACHE_HOME="$TMPDIR/xdg"
            export ZIG_GLOBAL_CACHE_DIR="$TMPDIR/zig" ZIG_LOCAL_CACHE_DIR="$TMPDIR/zig"
            export CARGO_ZIGBUILD_CACHE_DIR="$out"
            mkdir -p "$HOME" src
            printf '[package]\nname = "probe"\nversion = "0.0.0"\nedition = "2021"\n' > Cargo.toml
            echo 'fn main() {}' > src/main.rs
            cargo zigbuild --release --offline --target ${lambdaZigTarget}
          '';

      lambdaCommonArgs = commonArgs // {
        # zig links the final binary (cargo-zigbuild); drop the host-only mold arg.
        RUSTFLAGS = "";
        CARGO_PROFILE = "release";
        # cargo-zigbuild compiles C with zig cc, which ignores the Nix
        # cc-wrapper's NIX_CFLAGS_COMPILE — so the curl.dev headers that
        # buildInputs provides to host builds (see the note on `libraries`;
        # librdkafka 2.12 needs curl headers even with WITH_CURL=0) are
        # invisible here. Pass the include path explicitly; cc-rs and
        # cmake-rs both honor CFLAGS/CXXFLAGS.
        CFLAGS = "-I${pkgs.curl.dev}/include";
        CXXFLAGS = "-I${pkgs.curl.dev}/include";
        # commonArgs pins OPENSSL_NO_VENDOR=1 so host builds use the Nix
        # openssl, and openssl-sys honors that env var even when the crate's
        # `vendored` feature (rdkafka `ssl-vendored`) is enabled. Lambdas
        # can't use the Nix openssl: its shared libs need glibc >= 2.38
        # symbols while zig links against the pinned Lambda glibc, and the
        # /nix/store rpath doesn't exist in the Lambda runtime anyway. Flip
        # the override off so openssl-src compiles OpenSSL with zig cc
        # against the pinned glibc and links it statically — same idea as
        # AWS_LC_SYS_CMAKE_BUILDER above.
        OPENSSL_NO_VENDOR = "0";
        # Lambdas don't need max opt; matches the cargo-lambda CI setting.
        CARGO_PROFILE_RELEASE_OPT_LEVEL = "2";
        # aws-lc-sys (aws-lc-rs / rustls default crypto, pulled via aws-sdk &
        # sqlx) has a cc-builder guard that rejects the zig C compiler. Force
        # its cmake builder instead, which has no such guard and still compiles
        # the C against the zig-pinned glibc. cmake + nasm are its build deps.
        AWS_LC_SYS_CMAKE_BUILDER = "1";
        nativeBuildInputs = (commonArgs.nativeBuildInputs or [ ]) ++ [
          pkgs.cargo-zigbuild
          pkgs.zig
          pkgs.cmake
          pkgs.nasm
          # openssl-src (vendored OpenSSL, see OPENSSL_NO_VENDOR below) runs
          # OpenSSL's perl-based Configure.
          pkgs.perl
        ];
        # zig needs a writable cache inside the sandbox ($HOME is read-only).
        preBuild = ''
          export ZIG_GLOBAL_CACHE_DIR="$TMPDIR/zig-cache"
          export ZIG_LOCAL_CACHE_DIR="$TMPDIR/zig-cache"
          export XDG_CACHE_HOME="$TMPDIR/xdg"
          export CARGO_ZIGBUILD_CACHE_DIR=${zigbuildWrappers}

          # Inherited cargoArtifacts can carry CMake configure state
          # (CMakeCache.txt / CMakeFiles) from the deps-only layer, which
          # records paths from the build that made it, and CMake hard-fails
          # validating a cached compiler that is gone ("is not a full path to
          # an existing compiler tool"). Drop the configure state so a
          # build-script re-run reconfigures cleanly;
          # crates whose fingerprints are clean never read it, so this costs
          # nothing on the cached path. (Today aws-lc-sys is the only cmake
          # crate in the graph, via AWS_LC_SYS_CMAKE_BUILDER below.)
          tdir="''${CARGO_TARGET_DIR:-target}"
          if [ -d "$tdir" ]; then
            while IFS= read -r -d "" cache; do
              dir="$(dirname "$cache")"
              echo "purging stale cmake configure state in $dir"
              rm -rf "$dir/CMakeFiles" "$cache"
            done < <(find "$tdir" -name CMakeCache.txt -print0)
          fi
        '';
      };

      # Every handler deployed as a lambda, read straight from the deploy
      # config so the flake never drifts from services-config.json. For every
      # handler, crate name == dir name == deploy_lambdas entry.
      lambdaNames =
        let
          cfg = builtins.fromJSON (builtins.readFile ../.github/services-config.json);
        in
        pkgs.lib.unique (
          pkgs.lib.concatMap (svc: svc.deploy_lambdas or [ ]) (pkgs.lib.attrValues cfg.services)
        );

      # One shared dep closure for all lambda handlers. Build it with the same
      # cargo-zigbuild target used by the final packages; Cargo fingerprints the
      # `.2.26` target separately from the plain triple, so warming the plain
      # target does not help the deploy builds. Select with --bin, as
      # deployLambdaPackage does: without --package cargo resolves features across
      # the workspace, and any other selection gives units the handlers can't reuse.
      lambdaDeployCargoArtifacts = craneLib.buildDepsOnly (
        lambdaCommonArgs
        // {
          pname = "cloud-storage-lambda-deps";
          doCheck = false;
          # buildDepsOnly runs a cargo check in buildPhase by default; keep this
          # warm artifact to release deps only.
          cargoCheckCommand = "true";
          cargoBuildCommand = "cargo zigbuild --release";
          cargoExtraArgs =
            "--locked --target ${lambdaZigTarget} "
            + pkgs.lib.concatMapStringsSep " " (n: "--bin ${n}") lambdaNames;
        }
      );

      # bin name == crate name == handler dir name (see per-lambda justfiles).
      deployLambdaPackage =
        lambdaName:
        craneLib.buildPackage (
          lambdaCommonArgs
          // {
            # Pruned source: this derivation only rebuilds when a crate in
            # the handler's own workspace closure changes.
            src = prunedDeploySrc "lambda-${lambdaName}" lambdaName;
            cargoArtifacts = lambdaDeployCargoArtifacts;
            pname = "cloud-storage-lambda-${lambdaName}";
            doCheck = false;
            # cargo-zigbuild links the final binary against the pinned Lambda
            # glibc, selected via the `.2.26` target suffix.
            cargoBuildCommand = "cargo zigbuild --release";
            cargoExtraArgs = "--locked --target ${lambdaZigTarget} --bin ${lambdaName}";
            # Emit the Lambda custom-runtime artifact: a zip whose single entry
            # is named `bootstrap`, mirroring cargo-lambda's
            # target/lambda/<name>/bootstrap.zip layout. zigbuild writes to
            # target/<triple>/release (suffix stripped from the dir name).
            installPhaseCommand = ''
              mkdir -p "$out/${lambdaName}"
              cp "target/${lambdaTarget}/release/${lambdaName}" bootstrap
              ${pkgs.binutils}/bin/strip bootstrap || true
              ${pkgs.zip}/bin/zip -j -X "$out/${lambdaName}/bootstrap.zip" bootstrap
              ${pkgs.lib.optionalString (lambdaName == "document_text_extractor") ''
                # Mirror the handler justfile's `cargo lambda build --include
                # ./pdfium-lib/linux`: at runtime the binary dlopen's
                # ./pdfium-lib/linux/libpdfium.so relative to the Lambda task
                # root, so the blob has to ride along in bootstrap.zip at that
                # same relative path.
                ( cd services/${lambdaName} && ${pkgs.zip}/bin/zip -r -X "$out/${lambdaName}/bootstrap.zip" pdfium-lib/linux )
              ''}
              ${pkgs.lib.optionalString (lambdaName == "call_recording_preview_handler") ''
                cp "${callRecordingPreviewFfmpegLayer}/${lambdaName}/ffmpeg-layer.zip" "$out/${lambdaName}/ffmpeg-layer.zip"
              ''}
            '';
          }
        );

      deployLambdaPackages = pkgs.lib.listToAttrs (
        map (n: {
          name = "deploy-lambda-${n}";
          value = deployLambdaPackage n;
        }) lambdaNames
      );

      # The Namespace CLI, the other sandbox provider crates/agent_harness
      # talks to. Only used to mint the bearer tokens its Compute API wants
      # (`just namespace-token`); the harness itself speaks the API directly.
      # Not in nixpkgs either, and shipped as goreleaser tarballs rather than
      # bare binaries, so this unpacks and takes just the nsc binary.
      nsc =
        let
          version = "0.0.551";
          asset =
            {
              x86_64-linux = {
                arch = "linux_amd64";
                hash = "sha256-2Ip69WLe+VgbF2E74r4A4ZFfygMfiV+SMqgtGs87b7I=";
              };
              aarch64-linux = {
                arch = "linux_arm64";
                hash = "sha256-0+KpniE+7nQsFip1Tg5Z42xjAOlhPpdfmwEhQh5Ep4c=";
              };
              x86_64-darwin = {
                arch = "darwin_amd64";
                hash = "sha256-tpv81Cu1/7b2vq4Tiw4Z7pqCI3SCCiEKRRgJ2rEcX+g=";
              };
              aarch64-darwin = {
                arch = "darwin_arm64";
                hash = "sha256-x3FYe8DT+5U4D506ioSUfmiT5unG6CGMiGf4r/9jPpc=";
              };
            }
            .${system};
        in
        pkgs.stdenvNoCC.mkDerivation {
          pname = "nsc";
          inherit version;
          src = pkgs.fetchurl {
            url = "https://github.com/namespacelabs/foundation/releases/download/v${version}/nsc_${version}_${asset.arch}.tar.gz";
            inherit (asset) hash;
          };
          sourceRoot = ".";
          nativeBuildInputs = pkgs.lib.optionals isLinux [ pkgs.autoPatchelfHook ];
          installPhase = ''
            runHook preInstall
            install -Dm755 nsc $out/bin/nsc
            runHook postInstall
          '';
        };

      # The Daytona CLI (sandbox snapshots for crates/agent_harness) is not in
      # nixpkgs and is only published as prebuilt release binaries, so this
      # installs the asset rather than building from source. Pinned instead of
      # tracking `latest` so the shell stays reproducible; bump the version and
      # the four hashes together.
      daytona =
        let
          version = "0.203.0";
          asset =
            {
              x86_64-linux = {
                arch = "linux-amd64";
                hash = "sha256-5r+K1OgFcw1BF1sNJwdlbc0rGAVZSy16eEiCvQ/X8DI=";
              };
              aarch64-linux = {
                arch = "linux-arm64";
                hash = "sha256-bQa4KpU3gYf2m9+6ClG1qiCa5W+MjX/XgiCv59b1ptA=";
              };
              x86_64-darwin = {
                arch = "darwin-amd64";
                hash = "sha256-mcygBoN89RsMDmakGy8LEi1XgNc/+g4ImqaTEuPZrW4=";
              };
              aarch64-darwin = {
                arch = "darwin-arm64";
                hash = "sha256-X29vyGaEGQZN9bNb17SCrIlf3zmtMgaJmKThK7cY2kc=";
              };
            }
            .${system};
        in
        pkgs.stdenvNoCC.mkDerivation {
          pname = "daytona";
          inherit version;
          src = pkgs.fetchurl {
            url = "https://github.com/daytona/clients/releases/download/v${version}/daytona-${asset.arch}";
            inherit (asset) hash;
          };
          dontUnpack = true;
          # The Linux builds are cgo, so they need their interpreter and
          # libc rewritten to the store.
          nativeBuildInputs = pkgs.lib.optionals isLinux [ pkgs.autoPatchelfHook ];
          installPhase = ''
            runHook preInstall
            install -Dm755 $src $out/bin/daytona
            runHook postInstall
          '';
        };

      # GoAlert MCP server (github.com/amitray007/goalert-mcp, MIT), built from
      # the reviewed v0.1.0 commit rather than the npm tarball. Bump `rev`,
      # `hash` and `npmDepsHash` together, after re-reviewing the source.
      goalert-mcp = pkgs.buildNpmPackage {
        pname = "goalert-mcp";
        version = "0.1.0";
        src = pkgs.fetchFromGitHub {
          owner = "amitray007";
          repo = "goalert-mcp";
          rev = "c8c285f35ce31426c576a69c25f5bb1a365a7565";
          hash = "sha256-TDBI06V6boZ3RihwirGchDcKkZ7nKCyyB1pEebqEMiU=";
        };
        npmDepsHash = "sha256-PhanjTUmHoXzXsu9H3wKWVrZ89tfk8T4/QYdFcMGZ+M=";
        nodejs = pkgs.nodejs_24;
        # Only dev dependencies (esbuild, fsevents) ship install scripts.
        npmFlags = [ "--ignore-scripts" ];
        meta.mainProgram = "goalert-mcp";
      };

      # Starts goalert-mcp against Macro's GoAlert with the admin login read
      # from Doppler at launch, read-only unless GOALERT_READ_ONLY=false.
      goalert-mcp-macro = pkgs.writeShellApplication {
        name = "goalert-mcp-macro";
        runtimeInputs = [ pkgs.doppler ];
        text = ''
          GOALERT_PASSWORD="$(doppler secrets get GOALERT_ADMIN_PASSWORD --project observability --config prd --plain)"
          export GOALERT_PASSWORD
          export GOALERT_BASE_URL=https://oncall.macro-internal.com
          export GOALERT_USERNAME=admin
          export GOALERT_READ_ONLY="''${GOALERT_READ_ONLY:-true}"
          exec ${pkgs.lib.getExe goalert-mcp} "$@"
        '';
      };

      shellTools =
        with pkgs;
        [
          daytona
          goalert-mcp
          goalert-mcp-macro
          nsc
          parallel
          docker-compose
          # `just run_local` opens a quick tunnel to the agent egress proxy so
          # Cursor cloud agents can dial a local stack's MCP servers.
          cloudflared
          curl
          openssh
          wget
          kcat
          xz
          unzip
          zip
          cargo-info
          cargo-udeps
          cargo-tauri
          cargo-lambda
          cargo-zigbuild
          zig
          cmake
          nasm
          # openssl-src (vendored OpenSSL for zigbuild cross builds, see the
          # OPENSSL_NO_VENDOR notes above) runs OpenSSL's perl-based Configure.
          perl
          (writeShellScriptBin "rustup" ''
            set -euo pipefail
            rustc_path="$(${coreutils}/bin/readlink -f "$(command -v rustc)")"
            toolchain="$(${coreutils}/bin/basename "$(${coreutils}/bin/dirname "$(${coreutils}/bin/dirname "$rustc_path")")")"
            case "$1 $2" in
              "toolchain list") echo "$toolchain (default)" ;;
              "toolchain add") exit 0 ;;
              "target list") echo "x86_64-unknown-linux-gnu (installed)"; echo "aarch64-unknown-linux-gnu"; echo "wasm32-unknown-unknown (installed)" ;;
              "target add") exit 0 ;;
              "component list") echo "rust-src-x86_64-unknown-linux-gnu (installed)"; echo "clippy-x86_64-unknown-linux-gnu (installed)" ;;
              "component add") exit 0 ;;
              *) echo "rustup shim only supports commands used by cross" >&2; exit 1 ;;
            esac
          '')
          cargo-cross
          cargo-deny
          cargo-nextest
          cargo-expand
          binaryen
          # Match Cargo.lock so parallel wasm-pack builds do not race to
          # install a replacement CLI into their shared cache.
          wasm-bindgen-cli_0_2_126
          wasm-pack
          pkg-config
          bacon
          just
          just-lsp
          taplo
          bun
          brotli
          pnpm
          postgresql
          sqlx-cli
          typescript-language-server
          nodejs_24
          pulumi
          pulumiPackages.pulumi-nodejs
          pulumiPackages.pulumi-aws-native
          playwright
          playwright-mcp
          doppler
          biome
          jq
          prek
          gitleaks
          # TEMP: nixpkgs stripe-cli 1.43.2 checkPhase fails in the sandbox
          # (TestResolvePluginForInstallSucceedsForGAPluginWhenNotLoggedIn).
          # stripe-cli
          sccache
          rustToolchain
          python3
        ]
        ++ pkgs.lib.optionals isLinux [
          mold
          docker
          fuse-overlayfs
        ];

    in
    {
      checks = {
        code-mode-assets = codeModeAssets;
        # Deploy builds compile [patch.crates-io] crates from the pruned
        # source, so their real code (not mkDummySrc's stubs) must be there.
        pruned-deploy-src-vendored-patches = pkgs.runCommand "cloud-storage-pruned-vendored-patches" { } ''
          grep -q "fn write_embed_code" \
            ${prunedDeploySrc "service-agent-harness-service" "agent_harness_service"}/vendor/utoipa-swagger-ui/build.rs
          touch $out
        '';
        fmt = craneLib.cargoFmt {
          inherit src;
          pname = "cloud-storage";
          version = "0.1.0";
        };
        clippy = craneLib.cargoClippy (
          commonArgs
          // codeModeAssetsEnv
          // {
            cargoArtifacts = workspaceArtifacts;
            cargoClippyExtraArgs = "--workspace --all-features --exclude sync_service -- -D warnings";
            RUSTDOCFLAGS = "-Dwarnings";
          }
        );
        clippy-sync-service = craneLib.cargoClippy (
          commonArgs
          // codeModeAssetsEnv
          // {
            cargoArtifacts = workspaceArtifacts;
            cargoClippyExtraArgs = "-p sync_service -- -D warnings -A clippy::unnecessary_map_or -A clippy::collapsible_if";
            RUSTDOCFLAGS = "-Dwarnings";
          }
        );
        doppler-config-bins = dopplerConfigBins;
        gen-api =
          let
            openApiFiles = pkgs.lib.cleanSourceWith {
              src = ../apps/web/src/lib/service-clients;
              filter = path: type: type == "directory" || pkgs.lib.hasSuffix "openapi.json" (baseNameOf path);
            };
            crateToDir = {
              document_storage_service = "service-storage";
              properties_service = "service-properties";
              agent_harness_cognition = "service-cognition";
              authentication_service = "service-auth";
              notification_service = "service-notification";
              static_file_service = "service-static-files";
              connection_gateway = "service-connection";
              contacts_service = "service-contacts";
              unfurl_service = "service-unfurl";
              calendar_service = "service-calendar";
              email_service = "service-email";
              search_service = "service-search";
              scheduled_action = "service-scheduled-action";
            };
            checkScript = pkgs.lib.concatStringsSep "\n" (
              pkgs.lib.mapAttrsToList (crate: dir: ''
                echo -n "Checking ${dir}/openapi.json ... "
                if ! diff \
                  <("${openApiBins}/bin/${crate}_openapi" | ${pkgs.jq}/bin/jq --sort-keys .) \
                  <(${pkgs.jq}/bin/jq --sort-keys . < "${openApiFiles}/${dir}/openapi.json"); then
                  echo "FAIL: run 'bun run gen-api' and commit the result"
                  exit 1
                fi
                echo "ok"
              '') crateToDir
            );
          in
          pkgs.runCommand "cloud-storage-gen-api-check" { RUST_LOG = "error"; } ''
            ${checkScript}
            touch $out
          '';
      };

      packages = {
        inherit
          cargoArtifacts
          callRecordingPreviewFfmpegLayer
          workspaceArtifacts
          deployCargoArtifacts
          lambdaDeployCargoArtifacts
          openApiBins
          dopplerConfigBins
          nextestArchive
          goalert-mcp
          goalert-mcp-macro
          ;
        default = cargoArtifacts;
        code-mode-assets = codeModeAssets;
        macro-js-node-modules = jsNodeModules;
      }
      // dopplerConfigBinPackages
      // deployServiceBinaryPackages
      // {
        deploy-service-binaries-document-storage-service = documentStorageDeployBinaries;
        deploy-service-binaries-email-service = emailServiceDeployBinaries;
      }
      // deployLambdaPackages
      // pkgs.lib.optionalAttrs isLinux {
        local-stack-binaries = localStackBinaries;
      };

      devShells = {
        default =
          let
            pkgConfigPath = pkgs.lib.makeSearchPath "lib/pkgconfig" [
              pkgs.openssl.dev
            ];
          in
          pkgs.mkShell (
            {
              buildInputs = shellTools ++ libraries;
              PKG_CONFIG_PATH = pkgConfigPath;
              # Cargo build scripts use the Nix pkg-config wrapper, which prefers
              # the target-specific search path when PKG_CONFIG_PATH_FOR_TARGET is set.
              # librdkafka is built from the bundled sources via rdkafka's
              # cmake-build feature, so no system librdkafka.pc is needed here.
              PKG_CONFIG_PATH_FOR_TARGET = pkgConfigPath;
              LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";
              RUSTC_WRAPPER = "${pkgs.sccache}/bin/sccache";
              # Local dev shells favor reusable sccache artifacts across JJ
              # workspaces. CI derivations do not inherit devShell attributes.
              CARGO_INCREMENTAL = "0";
              SCCACHE_CACHE_SIZE = "30G";
              # Namespace CI runners preserve Cargo's ignored target directory.
              # A flake update can change the Nix C compiler while leaving CMake
              # configure state behind; CMake then drops its command-line cache
              # entries while switching compilers, breaking aws-lc and librdkafka.
              # Remove only caches configured by another compiler so ordinary
              # shell entry keeps reusable native build state.
              shellHook = ''
                if command -v prek >/dev/null 2>&1; then
                  repo_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
                  if [ -n "$repo_root" ] && [ -f "$repo_root/.pre-commit-config.yaml" ]; then
                    # Install into .git/hooks. If Cursor Cloud owns core.hooksPath,
                    # unset it only for this install so we do not overwrite the
                    # dispatcher; git still runs our hook via that dispatcher.
                    hooks_path="$(git -C "$repo_root" config --get core.hooksPath || true)"
                    cursor_hooks=""
                    if [ -n "$hooks_path" ] && [ -f "$hooks_path/.cursor-original-hooks-path" ]; then
                      cursor_hooks="$hooks_path"
                      git -C "$repo_root" config --local --unset-all core.hooksPath || true
                    fi
                    if ! (cd "$repo_root" && prek install --overwrite >/dev/null); then
                      echo "warning: prek hook install failed" >&2
                    fi
                    if [ -n "$cursor_hooks" ]; then
                      git -C "$repo_root" config --local core.hooksPath "$cursor_hooks"
                    fi
                  fi
                fi
              ''
              + pkgs.lib.optionalString isLinux ''
                target_dir="''${CARGO_TARGET_DIR:-target}"
                current_cc="$(type -P "''${CC:-cc}" || true)"
                if [ -n "$current_cc" ] && [ -d "$target_dir" ]; then
                  while IFS= read -r -d "" cache; do
                    cached_cc=""
                    while IFS="=" read -r key value; do
                      case "$key" in
                        CMAKE_C_COMPILER:*) cached_cc="$value"; break ;;
                      esac
                    done < "$cache"
                    if [ -n "$cached_cc" ] && [ "$cached_cc" != "$current_cc" ]; then
                      dir="$(dirname "$cache")"
                      echo "purging stale CMake state in $dir ($cached_cc != $current_cc)"
                      rm -rf "$dir/CMakeFiles" "$cache"
                    fi
                  done < <(find "$target_dir" -name CMakeCache.txt -print0)
                fi
              '';
              # rdkafka's ssl-vendored feature exists for the Lambda
              # derivations (see lambdaCommonArgs); local builds keep using
              # the Nix openssl instead of vendoring, which would need perl
              # on PATH and a from-source OpenSSL compile.
              OPENSSL_NO_VENDOR = "1";
              # Keep local cargo-lambda builds on the same aws-lc-sys path as
              # the Nix lambda derivations. The default cc builder rejects
              # cargo-lambda/cargo-zigbuild's Zig cc wrapper.
              AWS_LC_SYS_CMAKE_BUILDER = "1";
              # Android builds compile with the NDK's clang, which the cc
              # builder accepts. The CMake builder needs CMake to locate the
              # NDK itself, which fails in the tauri-android shell ("Neither
              # the NDK or a standalone toolchain was found").
              AWS_LC_SYS_CMAKE_BUILDER_aarch64_linux_android = "0";
              AWS_LC_SYS_CMAKE_BUILDER_armv7_linux_androideabi = "0";
              AWS_LC_SYS_CMAKE_BUILDER_i686_linux_android = "0";
              AWS_LC_SYS_CMAKE_BUILDER_x86_64_linux_android = "0";
              # cargo-zigbuild compiles C with zig cc, which ignores the Nix
              # cc-wrapper's NIX_CFLAGS_COMPILE — so the curl.dev headers that
              # buildInputs provides to host builds (see the note on `libraries`;
              # librdkafka 2.12 needs curl headers even with WITH_CURL=0) are
              # invisible to zigbuild cross builds. cc-rs and cmake-rs honor
              # these target-scoped forms, so only the Linux cross targets get
              # the include path; host builds keep their Nix cc-wrapper flags.
              CFLAGS_aarch64_unknown_linux_gnu = "-I${pkgs.curl.dev}/include";
              CXXFLAGS_aarch64_unknown_linux_gnu = "-I${pkgs.curl.dev}/include";
              CFLAGS_x86_64_unknown_linux_gnu = "-I${pkgs.curl.dev}/include";
              CXXFLAGS_x86_64_unknown_linux_gnu = "-I${pkgs.curl.dev}/include";
              # Default for local SQLx/cargo workflows so individual crates do
              # not need their own .env files. The run-local/run-dev env
              # resolver ignores this localhost default: run-dev needs
              # Doppler's dev DATABASE_URL, run-local its container-side URL.
              DATABASE_URL = "postgres://user:password@localhost:5432/macrodb";
            }
            // pkgs.lib.optionalAttrs isDarwin {
              # The bundled librdkafka C++ build is a native macOS build.
              # cmake-rs supplies an `arm64-apple-macosx` target flag, while
              # the Nix clang wrapper is configured for `arm64-apple-darwin`.
              # Passing both through the wrapper makes Apple SDK headers
              # incompatible with Nix's libc++ headers. Use Apple's compiler
              # for native host C/C++ builds; Nix still supplies the SDK,
              # dependency flags, and cross-compilation toolchain.
              CC = "/usr/bin/clang";
              CXX = "/usr/bin/clang++";
            }
            // pkgs.lib.optionalAttrs isLinux {
              LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libraries}";
              BINDGEN_EXTRA_CLANG_ARGS = "-I${pkgs.glibc.dev}/include -I${pkgs.gcc.cc}/lib/gcc/${pkgs.stdenv.hostPlatform.config}/${pkgs.gcc.version}/include";
            }
          );

        # Keep release builds independent of optional developer tools in the
        # default shell. In particular, adding Hermes there must not make
        # macrod releases fetch or realize Hermes and its Python/npm closure.
        agent-daemon = pkgs.mkShell {
          packages = [
            rustToolchain
            pkgs.cargo-zigbuild
            pkgs.zig
            pkgs.cmake
            pkgs.perl
            pkgs.pkg-config
            pkgs.sccache
            nsc
          ];
          RUSTC_WRAPPER = "${pkgs.sccache}/bin/sccache";
          CARGO_INCREMENTAL = "0";
          AWS_LC_SYS_CMAKE_BUILDER = "1";
        };
      };
    };
}