From d45f51e6d7ddbe8d32e765e0bd349f49926a8783 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Fri, 27 Nov 2026 21:55:02 -0800 Subject: [PATCH 01/23] feat(hub): store learnings in a dedicated database scoped by repository ID Hub now keeps learnings in their own PostgreSQL database with a separate login, scoped by GitHub repository ID so renames keep their history. Azure installs provision the learning login and secret, Hub CI installs the learning runtime, and decision review snapshots are fenced against concurrent learning checkpoints. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .github/workflows/hub-ci.yml | 5 +- hub/.devcontainer/compose.yaml | 4 + .../decision-walkthrough.compose.yaml | 1 + hub/.devcontainer/learning-role.sql | 2 + .../hub/routes/learnings-flow.test.tsx | 22 + .../view-models/settings-learnings/index.ts | 4 +- hub/docs/database.md | 17 +- hub/docs/decision-model-control-plane.md | 2 + hub/docs/deployment.md | 13 +- hub/docs/development.md | 33 +- hub/docs/learning-foundation.md | 28 +- hub/docs/testing-and-operations.md | 2 +- hub/schema/decision-review-snapshot.prisma | 19 + .../migration.sql | 18 + hub/schema/repository.prisma | 1 + hub/script/check-image/index.ts | 3 + .../create-artifact-storage/index.test.ts | 128 ++-- .../index.test.ts | 6 +- .../index.ts | 1 + .../index.test.ts | 25 +- .../index.ts | 10 +- .../index.db.test.ts | 590 ++++++++++++++++++ .../index.test.ts | 216 ++++++- .../index.ts | 216 ++++--- .../prepare-decision-taskset/index.ts | 22 +- hub/server/domains/decision-model/types.ts | 23 +- .../index.test.ts | 14 +- .../create-hub-review-collection/index.ts | 15 +- .../index.test.ts | 180 +++++- .../create-learning-job-processors/index.ts | 55 +- .../index.test.ts | 43 +- .../index.ts | 15 +- .../execute-learning-decision/index.test.ts | 44 +- .../execute-learning-decision/index.ts | 25 +- .../get-learning-overview/index.test.ts | 117 +++- .../learning/get-learning-overview/index.ts | 86 ++- .../get-learning-repository-scope/index.ts | 18 + .../learning-store-arguments/index.ts | 17 + .../prepare-learning-store/index.test.ts | 28 +- .../learning/prepare-learning-store/index.ts | 7 +- .../process-learning-run/index.test.ts | 39 +- .../learning/process-learning-run/index.ts | 30 +- .../index.test.ts | 339 +++++++++- .../process-review-comment-redaction/index.ts | 58 +- .../read-learning-configuration/index.ts | 2 + .../index.test.ts | 28 +- .../index.ts | 13 +- .../redact-legacy-review-comment/index.ts | 48 ++ .../review-comment-learning-source/types.ts | 2 + hub/server/index.ts | 1 + .../index.test.ts | 37 +- .../run-learning-command/index.test.ts | 536 +++++++++++++++- .../learning/run-learning-command/index.ts | 176 +++++- .../with-learning-execution-lock/index.ts | 2 + .../get-decision-review-snapshot/index.ts | 11 + .../index.db.test.ts | 46 ++ .../save-decision-review-snapshot/index.ts | 41 ++ .../index.ts | 2 +- .../index.db.test.ts | 7 +- .../list-due-learning-repositories/index.ts | 2 +- .../find-repository-github-id/index.ts | 11 + .../index.ts | 35 +- hub/server/routes/api/learnings/index.test.ts | 6 +- .../learnings/respond-learning-error/index.ts | 7 +- .../load-secret-environment/index.test.ts | 11 +- .../azure-entrypoint/run/index.test.ts | 35 ++ .../scripts/azure-entrypoint/run/index.ts | 23 +- .../grant-learning-database-access/index.ts | 48 ++ .../provision-database-access/index.ts | 20 +- .../index.ts | 53 ++ .../seed-decision-model-walkthrough/index.ts | 126 +++- hub/server/scripts/setup/index.test.ts | 48 +- hub/server/scripts/setup/index.ts | 47 +- .../index.test.ts | 140 ++++- .../parse-azure-secret-configuration/index.ts | 16 +- .../parse-azure-secret-configuration/types.ts | 2 +- .../index.db.test.ts | 195 ++++++ hub/test/fixtures/learning/report-runtime.mjs | 39 +- infrastructure/README.md | 14 +- infrastructure/azure/application.tf | 1 + infrastructure/azure/install/index.test.ts | 93 ++- infrastructure/azure/install/index.ts | 15 +- infrastructure/azure/install/inputs/index.ts | 20 +- .../azure/install/provision/index.ts | 264 ++++---- infrastructure/azure/install/secrets/index.ts | 21 + .../azure/installation.tfvars.example | 6 + infrastructure/azure/post/configure/index.ts | 11 +- infrastructure/azure/post/index.test.ts | 31 +- infrastructure/azure/post/index.ts | 3 + infrastructure/azure/post/types.ts | 1 + infrastructure/azure/provision/main.tf | 14 +- .../provision/tests/provision.tftest.hcl | 42 +- infrastructure/azure/roles.tf | 2 +- infrastructure/azure/setup.tf | 9 +- .../azure/tests/deployment.tftest.hcl | 27 +- infrastructure/azure/variables.tf | 26 +- scripts/check-ci-workflows/index.test.ts | 13 + scripts/check-ci-workflows/index.ts | 7 + 98 files changed, 4366 insertions(+), 611 deletions(-) create mode 100644 hub/.devcontainer/learning-role.sql create mode 100644 hub/schema/decision-review-snapshot.prisma create mode 100644 hub/schema/migrations/20261220160000_add_decision_review_snapshot/migration.sql create mode 100644 hub/server/domains/decision-model/create-hub-decision-taskset-source/index.db.test.ts create mode 100644 hub/server/domains/learning/get-learning-repository-scope/index.ts create mode 100644 hub/server/domains/learning/learning-store-arguments/index.ts create mode 100644 hub/server/domains/learning/redact-legacy-review-comment/index.ts create mode 100644 hub/server/repositories/decision-review-snapshots/get-decision-review-snapshot/index.ts create mode 100644 hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.db.test.ts create mode 100644 hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.ts create mode 100644 hub/server/repositories/repository-access/find-repository-github-id/index.ts create mode 100644 hub/server/scripts/grant-learning-database-access/index.ts create mode 100644 hub/server/scripts/provision-learning-database-access/index.ts create mode 100644 hub/test/database/decision-review-snapshot-migration/index.db.test.ts diff --git a/.github/workflows/hub-ci.yml b/.github/workflows/hub-ci.yml index ab189513c..759a531c6 100644 --- a/.github/workflows/hub-ci.yml +++ b/.github/workflows/hub-ci.yml @@ -41,8 +41,11 @@ jobs: with: node-version: ${{ matrix.node }} cache: npm - cache-dependency-path: hub/package-lock.json + cache-dependency-path: | + hub/package-lock.json + packages/learning/package-lock.json - run: npm ci --engine-strict + - run: npm ci --prefix ../packages/learning --ignore-scripts --engine-strict - run: npm run ${{ matrix.command }} env: TEST_DATABASE_URL: ${{ matrix.command == 'test:database' && 'postgresql://replica:replica@127.0.0.1:5432/postgres' || '' }} diff --git a/hub/.devcontainer/compose.yaml b/hub/.devcontainer/compose.yaml index 90c91021e..a0a98bdc0 100644 --- a/hub/.devcontainer/compose.yaml +++ b/hub/.devcontainer/compose.yaml @@ -8,6 +8,7 @@ services: working_dir: /workspaces/replica/hub volumes: - ../..:/workspaces/replica:cached + - postgres-socket:/var/run/postgresql:ro environment: DATABASE_URL: postgresql://replica:replica@db:5432/replica TEST_DATABASE_URL: postgresql://replica:replica@db:5432/postgres @@ -26,6 +27,8 @@ services: - "127.0.0.1:5432:5432" volumes: - postgres-data:/var/lib/postgresql + - postgres-socket:/var/run/postgresql + - ./learning-role.sql:/docker-entrypoint-initdb.d/learning-role.sql:ro healthcheck: test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U replica -d replica"] interval: 5s @@ -34,3 +37,4 @@ services: volumes: postgres-data: + postgres-socket: diff --git a/hub/.devcontainer/decision-walkthrough.compose.yaml b/hub/.devcontainer/decision-walkthrough.compose.yaml index b8362fd16..f8e21fc83 100644 --- a/hub/.devcontainer/decision-walkthrough.compose.yaml +++ b/hub/.devcontainer/decision-walkthrough.compose.yaml @@ -11,6 +11,7 @@ services: ARTIFACT_STORAGE_PROVIDER: filesystem ARTIFACT_STORAGE_DIRECTORY: /workspaces/replica/hub/storage/decision-walkthrough-artifacts REPLICA_LEARNING_ROOT: /workspaces/replica/hub/storage/decision-walkthrough-learning + REPLICA_LEARNING_DATABASE_URL: "" REPLICA_LEARNING_CLI: /workspaces/replica/packages/learning/bin/replica-learning.mjs REPLICA_DECISION_RUNTIME_URL: http://127.0.0.1:8010 REPLICA_DECISION_RUNTIME_AUTHENTICATION: environment-token diff --git a/hub/.devcontainer/learning-role.sql b/hub/.devcontainer/learning-role.sql new file mode 100644 index 000000000..06ef280ec --- /dev/null +++ b/hub/.devcontainer/learning-role.sql @@ -0,0 +1,2 @@ +CREATE ROLE replica_learning_runtime LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD 'replica-learning-dev'; +GRANT CONNECT ON DATABASE replica TO replica_learning_runtime; diff --git a/hub/client/application/hub/routes/learnings-flow.test.tsx b/hub/client/application/hub/routes/learnings-flow.test.tsx index 663499f0a..db77c3a29 100644 --- a/hub/client/application/hub/routes/learnings-flow.test.tsx +++ b/hub/client/application/hub/routes/learnings-flow.test.tsx @@ -315,6 +315,28 @@ describe("Learnings frontend integration", () => { ).toBeVisible() }) + it("shows migration redaction follow-ups to the repository administrator after reload", async () => { + const server = stubHubFetch(...learningsWorkspace()) + const notice = + "Rebuild learning mem_111111111111111111111111. Follow up on export exp_222222222222222222222222 at private/exports/team.json." + let loads = 0 + server.use( + http.get("/api/repositories/2001/learnings", () => { + loads++ + return Response.json({ + ...learningsResponse(), + loadError: notice, + }) + }), + ) + const router = await renderHubFlow(server, "/repositories/2001/learnings") + + expect(await screen.findByText(notice)).toBeVisible() + await router.settle(() => router.revalidate()) + expect(loads).toBe(2) + expect(screen.getByText(notice)).toBeVisible() + }) + it("posts a run only to the dedicated repository endpoint", async () => { const server = stubHubFetch(...learningsWorkspace()) const runRequests = vi.fn() diff --git a/hub/client/application/hub/view-models/settings-learnings/index.ts b/hub/client/application/hub/view-models/settings-learnings/index.ts index cb51aa0ef..7753f42bd 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.ts @@ -350,9 +350,7 @@ export function settingsLearnings( path: `/repositories/${repositoryId}/learnings/runs`, available: state.permissions.requestRun && state.runAvailable, }, - loadError: state.loadError - ? `Hub could not read this repository's learnings: ${state.loadError}` - : null, + loadError: state.loadError, identityNotice: state.identityReviewCount > 0 ? "Earlier suggestions or accepted learnings need identity revalidation. Hub keeps their history, but agents cannot use those versions. Find learnings again, then review any rebuilt suggestions." diff --git a/hub/docs/database.md b/hub/docs/database.md index 08c020a45..2de6b11d5 100644 --- a/hub/docs/database.md +++ b/hub/docs/database.md @@ -92,6 +92,8 @@ Review threads bind one non-removed repository, one reviewable prototype, and on Decision-model tables store repository settings, pinned input digests, runtime job and candidate references, promotion generations, Build evaluation references, and decimal usage or cost metadata. They do not store credentials, screenshots, tasksets, adapters, evaluation reports, or model weights. Database checks enforce training bounds, positive promotion generations, nonnegative usage and cost, and complete quantity/unit and amount/currency pairs. +For PostgreSQL learning stores, the latest decision-review snapshot keeps its content digest, snapshot ID, and capture time per repository. It contains no review text and is removed with its repository. SQLite keeps this checkpoint in its existing store directory; see [learning storage](learning-foundation.md). + Candidate rows also store the runtime's held-out baseline and candidate metrics, per-learning metric changes, and an optional administrator rejection. Rejection fields must be absent together or include a time and reason. Build evaluation rows keep typed page-level findings in their bounded summary rather than copying screenshot bytes. Runtime copy rows keep content-free provider references and provenance selectors. Runtime deletion rows keep selectors, pending and failure counts, safe receipt metadata, and completion times. They never store evidence bodies, screenshots, labels, prompts, adapters, or model artifacts. @@ -104,16 +106,17 @@ Validate schema changes on both a fresh database and an upgrade from the exact b The Azure installation separates database provisioning, migrations, and normal data access: -| Principal | Access | -| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Administrator | One-time database and role provisioning; never passed to Hub or its setup job. | -| `replica_migration` | Can create schemas in this database and owns `public`, `bullmq`, and their migration-created objects. Runs setup, not the long-running app. | -| `replica_runtime` | Uses both schemas, reads/writes application and queue data, uses sequences and executes queue functions. Cannot create schemas, change permanent schema objects, create roles, truncate tables, or change migration ledgers. BullMQ requires read access to its ledger and temporary-table permission for bulk jobs. | +| Principal | Access | +| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Administrator | One-time database and role provisioning; never passed to Hub or its setup job. | +| `replica_migration` | Can create schemas in this database and owns `public`, `bullmq`, and their migration-created objects. Runs setup, not the long-running app. | +| `replica_runtime` | Uses both schemas, reads/writes application and queue data, uses sequences and executes queue functions. Cannot create schemas, change permanent schema objects, create roles, truncate tables, or change migration ledgers. BullMQ requires read access to its ledger and temporary-table permission for bulk jobs. | +| `replica_learning_runtime` | Uses the separate learning schema for learning operations. It does not access Hub application or queue data. | -`server/scripts/provision-database-access/` creates the two login roles and schema ownership on a fresh database. It requires administrator access over the private database network and separate passwords of at least 16 characters. Existing roles, public tables, or a pre-existing BullMQ schema cause failure and rollback rather than adopting unknown permissions. Use a reviewed ownership migration for existing installations. +`server/scripts/provision-database-access/` creates the three login roles and schema ownership on a fresh database. It requires administrator access over the private database network and separate passwords of at least 16 characters. Existing roles, public tables, or a pre-existing BullMQ schema cause failure and rollback rather than adopting unknown permissions. Use a reviewed ownership migration for existing installations. When `DATABASE_RUNTIME_ROLE=replica_runtime`, setup runs `server/scripts/grant-runtime-database-access/` after Prisma and BullMQ setup. That script initializes the two queues' lazy ID sequences before granting data access, so runtime never needs permanent schema creation rights. It refreshes grants for newly migrated tables, sequences, and functions, excludes the Prisma ledger, and permits only reading BullMQ's ledger. Product additions that need other database capabilities must explicitly update and verify this contract. -Local development keeps its existing database user and leaves `DATABASE_RUNTIME_ROLE` unset. See the [Azure installation guide](../../infrastructure/README.md) for private-network provisioning, secret references, release ordering, and recovery. +Local development keeps its existing database user and leaves `DATABASE_RUNTIME_ROLE` unset. See the [learning package guide](../../packages/learning/README.md) for learning database privileges and the [Azure installation guide](../../infrastructure/README.md) for fresh and existing-install provisioning, secret references, release ordering, and recovery. The [database-enabled test projects](testing-and-operations.md#parallel-database-tests) use separate databases for every project, worker, and test run. Setup deploys the committed migrations and clears records before each case. Tests do not use the development database for records. diff --git a/hub/docs/decision-model-control-plane.md b/hub/docs/decision-model-control-plane.md index 0db35fd47..0e86adb40 100644 --- a/hub/docs/decision-model-control-plane.md +++ b/hub/docs/decision-model-control-plane.md @@ -70,6 +70,8 @@ Saved Build evaluations list the persisted page-level findings. Each finding nam Training withdrawal is selector-based. Hub records the export, grant, evidence, and taskset identifiers, enumerates content-free copy references from the repository's configured runtime, requests deletion, and persists the durable receipt. Pending and completed revocations block taskset upload, training, promotion, rollback, and evaluation for matching inputs. A scheduled recovery pass polls pending receipts after restart. The overview exposes only safe selectors, state, pending and failure counts, and receipt times; PostgreSQL never stores screenshots, learning text, labels, prompts, adapters, or model bytes from the receipt flow. +When a repository's learning store cannot be read, including when its GitHub ID is missing, withdrawal discovery remains pending against its saved training jobs. The scheduled job reports failure and retries discovery, while still processing withdrawals and deletion receipts from other repositories. Operators must restore the repository's verified GitHub ID or repair its store before Hub can determine which runtime copies need deletion. + ## Agent visual critic The prototype canvas exposes `evaluate_prototype` for an authoring agent to request explicit visual feedback while iterating. The action accepts only bounded PNG captures for named routes and the supported desktop or narrow, light or dark view combinations. Agents capture those images through the isolated browser canvas or the existing Replica Build capture path. The action never sends the user's prompt, Copilot session ID, local preview origin, Hub credential, or runtime credential. diff --git a/hub/docs/deployment.md b/hub/docs/deployment.md index 8e860f308..c5ec09b5e 100644 --- a/hub/docs/deployment.md +++ b/hub/docs/deployment.md @@ -4,7 +4,7 @@ The Hub image runs the frontend, API, and both workers together. It can expose G ## Image and runtime -Build from the repository root with `docker build -f hub/Dockerfile -t replica-hub:check .`. When an npm proxy is required, add `--build-arg NPM_REGISTRY=https://YOUR_PROXY/`. This resolves locked dependency versions through that registry without changing the source lockfiles; the registry URL must not contain credentials. The image runs as a non-root user and contains compiled application code, migration tooling, and the separately installed `replica-learning` command. Mount persistent local storage at `/app/storage` before repository learning stores are enabled. Publish and deploy the same image digest for setup and Hub. +Build from the repository root with `docker build -f hub/Dockerfile -t replica-hub:check .`. When an npm proxy is required, add `--build-arg NPM_REGISTRY=https://YOUR_PROXY/`. This resolves locked dependency versions through that registry without changing the source lockfiles; the registry URL must not contain credentials. The image runs as a non-root user and contains compiled application code, migration tooling, and the separately installed `replica-learning` command. SQLite learning stores need persistent local storage at `/app/storage`; PostgreSQL learning stores do not. Publish and deploy the same image digest for setup and Hub. Host npm configuration is not inherited by the image build. Without `NPM_REGISTRY`, the container needs public npm access. Where that access is not allowed, supply your approved proxy using the build argument above. Explicit scoped registry mappings in copied `.npmrc` files still apply. @@ -16,6 +16,9 @@ Publishing is an explicit operator step, not a side effect of CI. From the appro | `HOST`, `PORT` | Source defaults to `127.0.0.1:3001`; the image binds `0.0.0.0:3001`. | | `DATABASE_URL` | PostgreSQL connection URL, required for combined, worker, and setup modes. Configure verified TLS for remote databases. | | `DATABASE_RUNTIME_ROLE` | Setup-only opt-in for separate database roles: exactly `replica_runtime`. See [database access](database.md#deployment-database-roles). | +| `REPLICA_LEARNING_DATABASE_URL` | Optional protected URL for the separate learning runtime login. See [learning storage](learning-foundation.md#private-storage). | +| `REPLICA_LEARNING_MIGRATION_DATABASE_URL` | Setup-only privileged URL for the package's learning schema migration. Never supply it to the running Hub. | +| `REPLICA_LEARNING_RUNTIME_ROLE` | Setup-only learning grants role: exactly `replica_learning_runtime`. | | `CLIENT_DIRECTORY` | Absolute directory containing built frontend assets and `index.html`; the image uses `/app/dist/client`. Leave unset for the development API. | | `SHUTDOWN_TIMEOUT_MS` | Request and worker drain deadline, default 30000 milliseconds. Allow another five seconds for telemetry flushing. | | `ON_DEMAND_JOB_CONCURRENCY`, `SCHEDULED_JOB_CONCURRENCY` | Independent worker concurrency, as described in [Background jobs](background-jobs.md). | @@ -50,9 +53,9 @@ On termination, combined mode stops all three roles and drains work within the c ### Azure startup secret retrieval -The Azure installation invokes `node dist/server/scripts/azure-entrypoint/index.js runtime`, `setup`, or `provision` instead of using platform-managed Key Vault references. Rebuild and publish the image from this source before applying these commands; earlier images do not contain this entrypoint. `AZURE_CLIENT_ID` explicitly selects the assigned workload identity. `AZURE_KEY_VAULT_SECRET_REFERENCES` is a non-secret JSON map of destination environment names to public-cloud HTTPS Key Vault secret URLs. The entrypoint validates all references, reads their values through the selected identity, and populates the workload's in-memory environment before importing its existing entrypoint. Retrieved secret values never enter Terraform inputs, Azure container configuration, or startup logs. +The Azure installation invokes `node dist/server/scripts/azure-entrypoint/index.js runtime`, `setup`, `provision`, or `provision-learning` instead of using platform-managed Key Vault references. Rebuild and publish the image from this source before applying these commands; earlier images do not contain this entrypoint. `AZURE_CLIENT_ID` explicitly selects the assigned workload identity. `AZURE_KEY_VAULT_SECRET_REFERENCES` is a non-secret JSON map of destination environment names to public-cloud HTTPS Key Vault secret URLs. The entrypoint validates all references, reads their values through the selected identity, and populates the workload's in-memory environment before importing its existing entrypoint. Retrieved secret values never enter Terraform inputs, Azure container configuration, or startup logs. -Runtime and setup require `DATABASE_URL`; setup accepts no additional references. Provisioning requires exactly `DATABASE_URL`, `HUB_MIGRATION_PASSWORD`, and `HUB_RUNTIME_PASSWORD`, with versioned URLs. Runtime may additionally reference validated configuration names, but references cannot replace deployment-owned fields or already-defined values. Retrieval has a shared 30-second startup deadline and cancellation support. Failure prevents workload imports and database work; it does not fall back to operator credentials, a system-assigned identity, or old environment values. +Runtime and setup require `DATABASE_URL`; setup may also receive `REPLICA_LEARNING_MIGRATION_DATABASE_URL`. Fresh provisioning requires exactly `DATABASE_URL`, `HUB_MIGRATION_PASSWORD`, `HUB_RUNTIME_PASSWORD`, and `HUB_LEARNING_PASSWORD`, with versioned URLs. Existing-install learning provisioning requires only `DATABASE_URL` and `HUB_LEARNING_PASSWORD`. Runtime may additionally reference validated configuration names, but references cannot replace deployment-owned fields or already-defined values. Retrieval has a shared 30-second startup deadline and cancellation support. Failure prevents workload imports and database work; it does not fall back to operator credentials, a system-assigned identity, or old environment values. Versioned references make rotation explicit. An unversioned runtime/setup URL is resolved once at startup; there is no background refresh or automatic revision restart. Use the installation's serialized release procedure to load a rotated value. Source development, local image runs with directly supplied protected environment values, and the existing setup/provisioning scripts retain their original entrypoints and behavior. @@ -62,11 +65,11 @@ The Azure entrypoint also supports the scoped [GitHub author repair and webhook Run `npm run setup` from `hub/`, or invoke `node dist/server/scripts/setup/index.js` inside the image. Normal API and worker startup never runs setup. -The script holds a PostgreSQL session advisory lock across Prisma migrations, BullMQ migrations, and schedule registration. While the lock connection is healthy, a competing setup fails without starting those steps. Losing that connection releases the lock immediately and requests termination of the current step; child termination can take up to five seconds. The lock alone cannot exclude another invocation during that interval. Setup waits for child cleanup and exits unsuccessfully; logs identify the step without exposing migration-tool diagnostics that could contain secrets. +The script holds a PostgreSQL session advisory lock across Prisma migrations, BullMQ migrations, schedule registration, and the optional learning schema migration and grants. While the lock connection is healthy, a competing setup fails without starting those steps. Losing that connection releases the lock immediately and requests termination of the current step; child termination can take up to five seconds. The lock alone cannot exclude another invocation during that interval. Setup waits for child cleanup and exits unsuccessfully; logs identify the step without exposing migration-tool diagnostics that could contain secrets. Only setup scripts should modify migration and schedule state during a release. `npm run jobs:setup` remains a development-only shortcut that does not acquire the full release lock. Operational entry points live under `server/scripts/`; domains do not invoke them. -Migrations are not one transaction across both schemas. Fix the failed step and retry setup before starting the new image. This repository-access upgrade requires a maintenance window: stop all old API and worker processes before setup and the new deployment. Older binaries do not enforce the new access fence. Application rollback changes the image, not the database schema; a rollback must also preserve the access policy. +Migrations are not one transaction across schemas. Fix the failed step and retry setup before starting the new image. This repository-access upgrade requires a maintenance window: stop all old API and worker processes before setup and the new deployment. Older binaries do not enforce the new access fence. Application rollback changes the image, not the database schema; a rollback must also preserve the access policy. The deployment orchestrator owns serialization of the complete release, including setup and rollout. It must retain exclusion after failure and confirm that prior setup executions and database work have stopped before allowing a retry. Do not invoke production setup outside that serialized procedure. The advisory lock is an additional check for concurrent setup, not a replacement for release serialization or a guarantee of exactly-once jobs. Release orchestration must also define old/new worker overlap. See [Background jobs](background-jobs.md#schedules-and-delivery-guarantees). diff --git a/hub/docs/development.md b/hub/docs/development.md index 9ebbf9745..1c5d50ce2 100644 --- a/hub/docs/development.md +++ b/hub/docs/development.md @@ -16,6 +16,19 @@ The repository is mounted at `/workspaces/replica`, with `hub/` as the working d After the container opens and PostgreSQL is healthy, install the separate learning runtime with `npm ci --prefix ../packages/learning --engine-strict`, then run `npm run setup` before starting `npm run dev:api`. Run setup again after pulling new migrations. +Learning uses SQLite by default, including after recreating an existing devcontainer. To use PostgreSQL instead, first stop Hub and all older clients and follow the [offline import and verification procedure](learning-foundation.md#private-storage) for every existing learning store. Keep SQLite selected if any history cannot be recovered or verified. + +New devcontainer databases create a separate local learning login. If the PostgreSQL volume predates this configuration, check whether `replica_learning_runtime` exists. If it is absent, run `docker compose -f .devcontainer/compose.yaml exec db psql -U replica -d replica -f /docker-entrypoint-initdb.d/learning-role.sql` once from `hub/` on the host. Do not overwrite or adopt an existing role without reviewing its ownership and permissions. The included password is for this local container only. + +Inside the devcontainer, initialize the learning schema and grant the local role access before importing: + +```sh +REPLICA_LEARNING_MIGRATION_DATABASE_URL='postgresql://replica:replica@localhost/replica?host=%2Fvar%2Frun%2Fpostgresql' \ +REPLICA_LEARNING_RUNTIME_ROLE=replica_learning_runtime npm run setup +``` + +For the offline import, provide `REPLICA_LEARNING_DATABASE_URL='postgresql://replica_learning_runtime:replica-learning-dev@localhost/replica?host=%2Fvar%2Frun%2Fpostgresql'` only to the import command. After verifying all imported stores, explicitly set that runtime URL in the Hub process environment or its private `.env` before starting Hub and its workers. Repeat the setup command above after pulling learning migrations. The URL uses a shared Unix socket, not the remote `db` TCP hostname; the learning provider allows local sockets without TLS. These development credentials and socket are not suitable for a hosted deployment. Do not restart older clients against the retained SQLite copies. + ## Local Node.js Use npm and a Node.js version supported by `engines.node` in `hub/package.json`. From `hub/`, start only the database and copy the local configuration: @@ -149,7 +162,7 @@ The scheduled worker reconciles the configured GitHub installation every 15 minu This walkthrough uses the real Hub API, PostgreSQL, workers, artifact and learning stores, and the customer-operated reference runtime. Its deterministic fixture backend ignores image content. Use it to check orchestration and interface behavior only; do not treat its metrics or findings as model-quality evidence. -The filesystem artifact provider requires Linux. The walkthrough Compose override runs Hub and the fixture runtime on one private Docker network, so the same commands work with Docker Desktop and native Linux Docker Engine. From the repository root, create a private runtime token and state directory: +The filesystem artifact provider requires Linux. The walkthrough Compose override runs Hub and the fixture runtime on one private Docker network, so the same commands work with Docker Desktop and native Linux Docker Engine. It uses a separate SQLite learning store so the fixture can be reset without changing PostgreSQL learning history. From the repository root, create a private runtime token and state directory: ```sh mkdir -p hub/.local/decision-runtime @@ -192,14 +205,26 @@ docker compose -f hub/.devcontainer/compose.yaml exec -T app \ ./node_modules/.bin/react-router dev --host 0.0.0.0 ``` +Choose a dedicated disposable GitHub repository for this local fixture. Do not use a repository whose Hub data or learnings you need to keep. Look up its exact name and numeric ID with your GitHub CLI sign-in: + +```sh +gh api repos/OWNER/REPOSITORY | python3 -c 'import json, sys; repo = json.load(sys.stdin); print(repo["full_name"], repo["id"])' +``` + +Set the returned values below. The seed uses them only for this local fixture; it does not read or write the GitHub repository. It refuses to reuse an ID already assigned to another Hub repository or change the ID of an existing walkthrough. + Open , choose **Sign in as local developer**, then seed the walkthrough: ```sh -docker compose -f hub/.devcontainer/compose.yaml exec -T app \ - npm run db:seed:decision-walkthrough +export REPLICA_DECISION_WALKTHROUGH_GITHUB_REPOSITORY=OWNER/REPOSITORY +export REPLICA_DECISION_WALKTHROUGH_GITHUB_ID=ID_FROM_GITHUB +docker compose -f hub/.devcontainer/compose.yaml exec -T \ + -e REPLICA_DECISION_WALKTHROUGH_GITHUB_REPOSITORY="$REPLICA_DECISION_WALKTHROUGH_GITHUB_REPOSITORY" \ + -e REPLICA_DECISION_WALKTHROUGH_GITHUB_ID="$REPLICA_DECISION_WALKTHROUGH_GITHUB_ID" \ + app npm run db:seed:decision-walkthrough ``` -The seed resets only `local/decision-walkthrough`. It refuses to run while a walkthrough job is active or after the dedicated fixture runtime has a promotion generation. To restart from the beginning, stop the worker and services, remove only `$REPLICA_RUNTIME_STATE_DIR`, recreate it with mode `0700`, and start the Compose bundle again before reseeding. The seed creates four reviewed prototypes with breaking and fixed Builds distributed across training, development, and test splits; 32 valid screenshots; two reviewer identities; one accepted learning; training consent; and local repository administrator authority. It uses the learning CLI to grant consent, import the real Hub review snapshot, label and consolidate the evidence, and accept the learning. +The seed resets only the dedicated local walkthrough repository. It refuses to run while a walkthrough job is active or after the dedicated fixture runtime has a promotion generation. To restart from the beginning, stop the worker and services, remove only `$REPLICA_RUNTIME_STATE_DIR`, recreate it with mode `0700`, and start the Compose bundle again before reseeding. The seed creates four reviewed prototypes with breaking and fixed Builds distributed across training, development, and test splits; 32 valid screenshots; two reviewer identities; one accepted learning; training consent; and local repository administrator authority. It uses the learning CLI to grant consent, import the real Hub review snapshot, label and consolidate the evidence, and accept the learning. Start the on-demand worker in a third terminal: diff --git a/hub/docs/learning-foundation.md b/hub/docs/learning-foundation.md index 88ce7dde7..494efe3d7 100644 --- a/hub/docs/learning-foundation.md +++ b/hub/docs/learning-foundation.md @@ -22,11 +22,27 @@ Disconnecting removes the connection record and advances the generation. It does `REPLICA_LEARNING_ROOT` defaults to `storage/learning`. It must be a dedicated directory outside every configured static-file root. Hub rejects the filesystem root, the Hub application root, the shared `storage` root, the source public directory, the configured built-client directory and their descendants, files, and paths containing symbolic links. The check runs at startup and again when a repository store is prepared. -The repository learning integration supplies the persisted repository UUID and package scope `github.com/repositories/`. The store primitive creates `/repositories/` with mode `0700` and writes the package's default `config.json` with mode `0600` only when it is absent. Existing configuration remains operator-owned. +Hub uses the persisted GitHub repository ID as the package scope, `github.com/repositories/`. With SQLite, the private directory is `/repositories/`. The store primitive creates that directory with mode `0700` and writes the package's default `config.json` with mode `0600` only when it is absent. Existing configuration remains operator-owned. -Decision commands use an existing store and never create one implicitly. The first complete review import prepares the store. +Set `REPLICA_LEARNING_DATABASE_URL` to select the package's PostgreSQL provider. Hub gives each command a private temporary config and does not create a repository store directory. Setup migrates the package schema with a separate privileged URL and grants the learning runtime login access only to that schema. See [PostgreSQL storage](../../packages/learning/README.md#postgresql-storage). -When GitHub repository scoping first activates, previously authorized learning decisions and queued runs may finish writing to their original legacy repository's private store. The UUID-scoped store stays hidden and is never linked to a new ID-backed repository. +Hub preserves the built-in labeling and consolidation settings in an existing repository `config.json` while that directory remains mounted. For a new PostgreSQL store, an operator can instead place the same package configuration in `/repositories//postgres-config.json`. Keep it private and available to every Hub process. Hub selects PostgreSQL regardless of its `memory` setting. Do not keep both configuration files in one directory. Custom labeler or consolidator modules are not supported in this mode; Hub refuses them instead of silently changing the settings. Without either file, Hub uses its defaults and needs no repository configuration directory. + +Before switching an existing installation, stop Hub and older clients, inventory every repository's existing store, and import each one offline using the package's `import-sqlite` command. Convert a non-SQLite store using `migrate-scope` first. Keep each old directory mounted for its first decision-model preflight after the switch, so Hub can migrate its retry-stable review snapshot metadata into the Hub database. Do not remove the old storage until every destination has been verified, and never restart older clients against the retained copies. Mixed SQLite and PostgreSQL writers are not supported. New PostgreSQL writes are not copied back to SQLite, so rolling back to the old store requires a separate, verified migration. If a local repository directory contains anything other than `postgres-config.json`, Hub refuses to open the PostgreSQL scope until its import receipt exists. A directory that is no longer mounted cannot provide this check, so inventory and import it before removing the mount or activating PostgreSQL. + +Commands for an ID-backed store supply the former UUID-based scope as `--legacy-repository`. SQLite migrates existing records and their lifecycle to the numeric scope before opening them. Other existing providers require the [offline migration](../../packages/learning/README.md#rules). Hub review imports retain the original `repositories/` source separately from the numeric learning scope. This preserves existing evidence and snapshot identities. A repository without a GitHub ID cannot open its learning store for users, run learning, or prepare learning-backed decision-model data. Hub does not infer an ID from a name or expose its stored records. + +To migrate a non-SQLite Hub store, stop Hub and all older clients that can write it. Run `replica-learning migrate-scope --offline --dir /repositories/ --repository github.com/repositories/ --legacy-repository github.com/repositories/`. Verify the copied store before removing any source data. The package guide explains how to restore the previous provider for another repository. + +In SQLite mode, decision commands use an existing store and never create one implicitly. The first complete review import prepares the store. Hub keeps the latest decision-review snapshot ID, capture time, and content digest in the SQLite store directory. A SQLite checkpoint rename already in progress can finish after the execution lock is lost. With PostgreSQL, Hub keeps that checkpoint in its database and writes it on the connection holding the learning execution lock. It records observations even when training consent is off and stores no review text in the checkpoint. + +An ID-less legacy repository remains unavailable for learning. A queued learning run without an ID fails visibly, and decision reconciliation remains pending. Under the learning execution lock, deletion jobs can redact the original UUID-scoped store without making its records available to users. The redaction-only command follows the durable SQLite or PostgreSQL mapping when present and fails closed if ownership is uncertain. Recovery retries failures. It does not assign a GitHub ID or infer ownership from a name. + +When combining histories reveals an earlier redaction, the Learnings page tells repository administrators which exports may still contain removed text and which accepted learnings need rebuilding. The migration command also reports these follow-ups, including on retry; `replica-learning status` retains them for later review. + +SQLite overwrites removed event text in its database pages and checkpoints its write-ahead log when possible. JSON Lines rewrites its event file but cannot erase old bytes from free disk space. Offline provider migrations leave their original store untouched; operators must separately remove any retained copies, backups, or exports after verifying the migrated data. A provider that cannot safely resolve and redact its legacy data leaves the job pending. + +Review snapshot digests include the numeric scope, so a change of GitHub repository identity invalidates a new run or decision-model source pin. A queued learning run from before this change can still use its original snapshot digest. Previously pinned decision-model jobs must be prepared again if their source digest changes. The [local decision-model walkthrough](development.md#walk-through-the-local-decision-model) requires an explicitly selected GitHub repository and its verified ID for its isolated fixture. ## Command boundary @@ -34,9 +50,10 @@ The runner starts Node.js with the configured CLI entry point, appends `--json`, - `PATH`, `HOME`, `LANG`, `LC_ALL`, and `TZ`. - `COPILOT_GITHUB_TOKEN` only for an explicitly token-backed command. +- `REPLICA_LEARNING_DATABASE_URL` only when Hub explicitly selected PostgreSQL. - A new private `TMPDIR`. -Hub passes store paths and repository scope as command arguments, not inherited `REPLICA_LEARNING_*` variables. It does not pass database, authentication, workload-identity, storage, or other deployment credentials. Standard output is limited to 16 MiB, standard error to 1 MiB, and the default deadline is 60 seconds. A timeout, output overflow, cancellation, or surviving descendant kills the command's process group before Hub removes the temporary directory. +Hub passes store paths and repository scope as command arguments. It never inherits ambient `REPLICA_LEARNING_*` variables or passes Hub's database, migration, authentication, workload-identity, storage, or other deployment credentials. Standard output is limited to 16 MiB, standard error to 1 MiB, and the default deadline is 60 seconds. A timeout, output overflow, cancellation, or surviving descendant kills the command's process group before Hub removes the temporary directory. Repository decisions, runs, and redactions use the PostgreSQL advisory-lock primitive for one Hub-wide learning execution at a time and hold the shared repository-authority lock around authority-sensitive package work. Decisions additionally hold a shared session-authority lock from the final live-session check through command exit. Session-ending transactions take only the matching exclusive session lock unless they can also change repository grants, in which case they acquire the repository lock first and the session lock second. A decision that wins keeps both boundaries until its command exits; a competing user-facing authority change returns retryable feedback after a bounded wait. Runs do not hold the session lock, so sign-out and global revocation can proceed during their long work. Runs release the repository lock during labeling, then reacquire it and retry the requester's repository-authority check before consolidation. Losing the execution-lock database connection aborts the operation and its command through the shared signal. This preserves the CLI process boundary without moving package policy into Hub. @@ -60,7 +77,7 @@ The run endpoint requires a usable Copilot connection. It captures and digests o Operators may opt in to automatic runs with `REPLICA_LEARNING_AUTOMATIC_RUNS=true`. One stable BullMQ schedule discovers due repositories daily at 02:00 UTC. Discovery is a no-op while the saved Copilot connection is unavailable, refused, or no longer owned by an administrator. A repository is due when its current thread activity versions differ from the review activity snapshot persisted with its last successful run, or its most recent successful or partially completed run left comments or suggestions unfinished. This comparison does not depend on review or run timestamps, so a review transaction that commits after snapshot capture remains due even when it assigned its timestamps earlier. Repositories without a successful run become due after their first review evidence. -Discovery follows the current repository-scoping state and skips removed or disconnected repositories. It captures the normal complete review snapshot before creating a run, so repository removal during discovery is skipped and later review drift becomes the same visible `snapshot_changed` run failure as an explicit request. A repository whose latest automatic run found missing or ended consent stays out of automatic discovery until a newer explicit administrator run supersedes that failure. It creates at most one active run per repository and dispatches at most 100 due repositories per sweep, ordered by their least recent run with never-run repositories first. A capture or run-creation failure for one repository is reported and does not block later repositories. Automatic jobs stay on the scheduled queue below maintenance-job priority. Before claiming one under the global learning execution lock, the processor defers to queued or recovered user-requested work on the on-demand queue. +Discovery skips repositories without a GitHub ID and removed or disconnected repositories. It captures the normal complete review snapshot before creating a run, so repository removal during discovery is skipped and later review drift becomes the same visible `snapshot_changed` run failure as an explicit request. A repository whose latest automatic run found missing or ended consent stays out of automatic discovery until a newer explicit administrator run supersedes that failure. It creates at most one active run per repository and dispatches at most 100 due repositories per sweep, ordered by their least recent run with never-run repositories first. A capture or run-creation failure for one repository is reported and does not block later repositories. Automatic jobs stay on the scheduled queue below maintenance-job priority. Before claiming one under the global learning execution lock, the processor defers to queued or recovered user-requested work on the on-demand queue. The one-minute recovery sweep re-enqueues queued and interrupted running records on their original queue. Enqueue failures for newly discovered automatic runs are persisted as visible failed runs. Completed run records are retained for 90 days, while each repository's latest run and latest successful scheduling watermark are kept when older records are removed. Schedule setup uses one stable scheduler ID, so repeated setup updates the daily schedule instead of duplicating it. @@ -79,6 +96,7 @@ Soft deletion queues an idempotent package redaction job after the review transa | `REPLICA_COPILOT_GITHUB_INSTALLATION_ID` | Numeric installation ID for that organization. | | `REPLICA_COPILOT_TOKEN` | Required only with `environment-token`; used only for Copilot-backed package commands. Usage is attributed to the GitHub identity represented by this credential. | | `REPLICA_LEARNING_ROOT` | Private learning-store root. Defaults to `storage/learning`. | +| `REPLICA_LEARNING_DATABASE_URL` | Optional protected URL for the separate learning runtime login. When set, Hub uses PostgreSQL. | | `REPLICA_LEARNING_CLI` | Optional package CLI path. Source development defaults to `../packages/learning/bin/replica-learning.mjs` from `hub/`; the image sets `/opt/replica/learning/bin/replica-learning.mjs`. | | `REPLICA_LEARNING_NODE` | Optional Node.js executable. Defaults to the running Node.js executable. | | `REPLICA_LEARNING_AUTOMATIC_RUNS` | Optional `true` / `false` switch. Defaults to `false`. When enabled, due repositories are discovered daily at 02:00 UTC, but no runs are created unless the saved Copilot connection is usable. | diff --git a/hub/docs/testing-and-operations.md b/hub/docs/testing-and-operations.md index f30596d20..da1d1b688 100644 --- a/hub/docs/testing-and-operations.md +++ b/hub/docs/testing-and-operations.md @@ -2,7 +2,7 @@ These checks cover the Hub API, database setup, and frontend. See [Architecture](architecture.md) for the features that are implemented. -Run commands directly from `hub/` after `npm ci`. The database command also needs PostgreSQL and `TEST_DATABASE_URL`, as described in [parallel database tests](#parallel-database-tests): +Run commands directly from `hub/` after `npm ci`. For database tests, also install the learning runtime as described in [Development](development.md), start PostgreSQL, and set `TEST_DATABASE_URL` as described in [parallel database tests](#parallel-database-tests): ```sh npm run lint diff --git a/hub/schema/decision-review-snapshot.prisma b/hub/schema/decision-review-snapshot.prisma new file mode 100644 index 000000000..e97244440 --- /dev/null +++ b/hub/schema/decision-review-snapshot.prisma @@ -0,0 +1,19 @@ +model DecisionReviewSnapshot { + // ID columns + id String @id @default(uuid()) @db.Uuid + repositoryId String @unique @map("repository_id") @db.Uuid + + // Relations + repository Repository @relation(fields: [repositoryId], references: [id], onDelete: Cascade) + + // Attribute columns + digest String @db.VarChar(71) + snapshotId String @map("snapshot_id") @db.Uuid + capturedAt DateTime @map("captured_at") @db.Timestamptz(3) + + // Timestamp columns + createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(3) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(3) + + @@map("decision_review_snapshots") +} diff --git a/hub/schema/migrations/20261220160000_add_decision_review_snapshot/migration.sql b/hub/schema/migrations/20261220160000_add_decision_review_snapshot/migration.sql new file mode 100644 index 000000000..9f196bfc5 --- /dev/null +++ b/hub/schema/migrations/20261220160000_add_decision_review_snapshot/migration.sql @@ -0,0 +1,18 @@ +-- CreateTable +CREATE TABLE "decision_review_snapshots" ( + "id" UUID NOT NULL, + "repository_id" UUID NOT NULL, + "digest" VARCHAR(71) NOT NULL, + "snapshot_id" UUID NOT NULL, + "captured_at" TIMESTAMPTZ(3) NOT NULL, + "created_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "decision_review_snapshots_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "decision_review_snapshots_repository_id_key" ON "decision_review_snapshots"("repository_id"); + +-- AddForeignKey +ALTER TABLE "decision_review_snapshots" ADD CONSTRAINT "decision_review_snapshots_repository_id_fkey" FOREIGN KEY ("repository_id") REFERENCES "repositories"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/hub/schema/repository.prisma b/hub/schema/repository.prisma index 7076a6244..0fdb4796e 100644 --- a/hub/schema/repository.prisma +++ b/hub/schema/repository.prisma @@ -7,6 +7,7 @@ model Repository { learningRuns LearningRun[] learningDecisionOperations LearningDecisionOperation[] decisionModelConfiguration DecisionModelConfiguration? + decisionReviewSnapshot DecisionReviewSnapshot? decisionTrainingJobs DecisionTrainingJob[] decisionCandidates DecisionCandidate[] decisionModelPromotions DecisionModelPromotion[] diff --git a/hub/script/check-image/index.ts b/hub/script/check-image/index.ts index 879910680..ebb826c14 100644 --- a/hub/script/check-image/index.ts +++ b/hub/script/check-image/index.ts @@ -92,6 +92,7 @@ export async function checkImage() { await new Promise((resolve) => setTimeout(resolve, 500)) } const databaseUrl = `DATABASE_URL=postgresql://replica:replica@${database}:5432/replica` + const learningPassword = "replica-learning-image-only" const migrationPassword = "replica-migration-image-only" const runtimePassword = "replica-runtime-image-only" docker( @@ -102,6 +103,8 @@ export async function checkImage() { "-e", databaseUrl, "-e", + `HUB_LEARNING_PASSWORD=${learningPassword}`, + "-e", `HUB_MIGRATION_PASSWORD=${migrationPassword}`, "-e", `HUB_RUNTIME_PASSWORD=${runtimePassword}`, diff --git a/hub/server/domains/artifacts/create-artifact-storage/index.test.ts b/hub/server/domains/artifacts/create-artifact-storage/index.test.ts index d1748fcb7..94c019c6b 100644 --- a/hub/server/domains/artifacts/create-artifact-storage/index.test.ts +++ b/hub/server/domains/artifacts/create-artifact-storage/index.test.ts @@ -11,6 +11,10 @@ vi.mock("../../../integrations/azure-blob/create-azure-blob-artifact-storage", ( createAzureBlobArtifactStorage: vi.fn(), })) +// Filesystem artifact storage needs Linux's /proc/self/fd, so it refuses other +// platforms. +const itOnLinux = it.runIf(process.platform === "linux") + describe("createArtifactStorage()", () => { it("bounds readiness even when the provider ignores its abort signal", async () => { const isReady = vi.fn<(signal: AbortSignal) => Promise>(() => new Promise(() => {})) @@ -30,33 +34,36 @@ describe("createArtifactStorage()", () => { expect(isReady.mock.calls[0]![0].aborted).toBe(true) }, 3_000) - it("publishes complete immutable bytes and explicitly reports missing reads and deletes", async () => { - const directory = resolve(`server/domains/artifacts/.storage-test-${randomUUID()}`) - await mkdir(directory) - onTestFinished(() => rm(directory, { recursive: true, force: true })) - const storage = await createArtifactStorage({ provider: "filesystem", directory }) - const first = Uint8Array.from([0, 255, 7]) - const second = Uint8Array.from([9, 8]) - - const results = await Promise.all([ - storage.write("opaque-key", first), - storage.write("opaque-key", second), - ]) - expect(results.map((result) => result.status).sort()).toEqual(["already-exists", "ok"]) - const result = await storage.read("opaque-key") - expect(result.status).toBe("ok") - if (result.status !== "ok") throw new Error("Expected saved bytes.") - expect(Array.from(result.bytes)).toEqual( - Array.from(results[0]?.status === "ok" ? first : second), - ) - expect(await storage.delete("opaque-key")).toEqual({ status: "ok" }) - expect(await storage.read("opaque-key")).toEqual({ status: "not-found" }) - expect(await storage.delete("opaque-key")).toEqual({ status: "not-found" }) - expect(await storage.write("empty", new Uint8Array())).toEqual({ status: "ok" }) - expect(await storage.read("empty")).toEqual({ status: "ok", bytes: new Uint8Array() }) - }) + itOnLinux( + "publishes complete immutable bytes and explicitly reports missing reads and deletes", + async () => { + const directory = resolve(`server/domains/artifacts/.storage-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { recursive: true, force: true })) + const storage = await createArtifactStorage({ provider: "filesystem", directory }) + const first = Uint8Array.from([0, 255, 7]) + const second = Uint8Array.from([9, 8]) + + const results = await Promise.all([ + storage.write("opaque-key", first), + storage.write("opaque-key", second), + ]) + expect(results.map((result) => result.status).sort()).toEqual(["already-exists", "ok"]) + const result = await storage.read("opaque-key") + expect(result.status).toBe("ok") + if (result.status !== "ok") throw new Error("Expected saved bytes.") + expect(Array.from(result.bytes)).toEqual( + Array.from(results[0]?.status === "ok" ? first : second), + ) + expect(await storage.delete("opaque-key")).toEqual({ status: "ok" }) + expect(await storage.read("opaque-key")).toEqual({ status: "not-found" }) + expect(await storage.delete("opaque-key")).toEqual({ status: "not-found" }) + expect(await storage.write("empty", new Uint8Array())).toEqual({ status: "ok" }) + expect(await storage.read("empty")).toEqual({ status: "ok", bytes: new Uint8Array() }) + }, + ) - it("rejects traversal and encoded path keys before touching storage", async () => { + itOnLinux("rejects traversal and encoded path keys before touching storage", async () => { const directory = resolve(`server/domains/artifacts/.storage-test-${randomUUID()}`) await mkdir(directory) onTestFinished(() => rm(directory, { recursive: true, force: true })) @@ -79,40 +86,43 @@ describe("createArtifactStorage()", () => { } }) - it("refuses symlink leaves and directories without reading or changing the target", async () => { - const directory = resolve(`server/domains/artifacts/.storage-test-${randomUUID()}`) - await mkdir(directory) - onTestFinished(() => rm(directory, { recursive: true, force: true })) - await mkdir(`${directory}/root`) - await writeFile(`${directory}/outside`, "private") - await symlink(`${directory}/outside`, `${directory}/root/key`) - const storage = await createArtifactStorage({ - provider: "filesystem", - directory: `${directory}/root`, - }) + itOnLinux( + "refuses symlink leaves and directories without reading or changing the target", + async () => { + const directory = resolve(`server/domains/artifacts/.storage-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { recursive: true, force: true })) + await mkdir(`${directory}/root`) + await writeFile(`${directory}/outside`, "private") + await symlink(`${directory}/outside`, `${directory}/root/key`) + const storage = await createArtifactStorage({ + provider: "filesystem", + directory: `${directory}/root`, + }) - expect(await storage.read("key")).toEqual({ status: "unavailable" }) - expect(await storage.write("key", Uint8Array.of(1))).toEqual({ status: "already-exists" }) - expect(await storage.delete("key")).toEqual({ status: "unavailable" }) - expect(await readFile(`${directory}/outside`, "utf8")).toBe("private") - await symlink(`${directory}/root`, `${directory}/alias`) - await expect( - createArtifactStorage({ provider: "filesystem", directory: `${directory}/alias` }), - ).rejects.toThrow("Artifact directory is unavailable.") - await expect( - createArtifactStorage({ provider: "filesystem", directory: `${directory}/alias/nested` }), - ).rejects.toThrow("Artifact directory is unavailable.") - await rm(`${directory}/root`, { recursive: true }) - await mkdir(`${directory}/other`) - await writeFile(`${directory}/other/key`, "private") - await symlink(`${directory}/other`, `${directory}/root`) - expect(await storage.read("key")).toEqual({ status: "unavailable" }) - expect(await storage.write("key", Uint8Array.of(1))).toEqual({ status: "unavailable" }) - expect(await storage.delete("key")).toEqual({ status: "unavailable" }) - expect(await readFile(`${directory}/other/key`, "utf8")).toBe("private") - }) + expect(await storage.read("key")).toEqual({ status: "unavailable" }) + expect(await storage.write("key", Uint8Array.of(1))).toEqual({ status: "already-exists" }) + expect(await storage.delete("key")).toEqual({ status: "unavailable" }) + expect(await readFile(`${directory}/outside`, "utf8")).toBe("private") + await symlink(`${directory}/root`, `${directory}/alias`) + await expect( + createArtifactStorage({ provider: "filesystem", directory: `${directory}/alias` }), + ).rejects.toThrow("Artifact directory is unavailable.") + await expect( + createArtifactStorage({ provider: "filesystem", directory: `${directory}/alias/nested` }), + ).rejects.toThrow("Artifact directory is unavailable.") + await rm(`${directory}/root`, { recursive: true }) + await mkdir(`${directory}/other`) + await writeFile(`${directory}/other/key`, "private") + await symlink(`${directory}/other`, `${directory}/root`) + expect(await storage.read("key")).toEqual({ status: "unavailable" }) + expect(await storage.write("key", Uint8Array.of(1))).toEqual({ status: "unavailable" }) + expect(await storage.delete("key")).toEqual({ status: "unavailable" }) + expect(await readFile(`${directory}/other/key`, "utf8")).toBe("private") + }, + ) - it("bounds write and read bytes while accepting the exact limit", async () => { + itOnLinux("bounds write and read bytes while accepting the exact limit", async () => { const directory = resolve(`server/domains/artifacts/.storage-test-${randomUUID()}`) await mkdir(directory) onTestFinished(() => rm(directory, { recursive: true, force: true })) @@ -131,7 +141,7 @@ describe("createArtifactStorage()", () => { expect(await storage.read("large")).toEqual({ status: "too-large" }) }) - it("fails safely when the configured filesystem directory disappears", async () => { + itOnLinux("fails safely when the configured filesystem directory disappears", async () => { const directory = resolve(`server/domains/artifacts/.storage-test-${randomUUID()}`) await mkdir(directory) onTestFinished(() => rm(directory, { recursive: true, force: true })) diff --git a/hub/server/domains/artifacts/create-configured-artifact-storage/index.test.ts b/hub/server/domains/artifacts/create-configured-artifact-storage/index.test.ts index 0c8462bb3..98d0fa4ab 100644 --- a/hub/server/domains/artifacts/create-configured-artifact-storage/index.test.ts +++ b/hub/server/domains/artifacts/create-configured-artifact-storage/index.test.ts @@ -5,8 +5,12 @@ import { describe, expect, it, onTestFinished } from "vitest" import { createConfiguredArtifactStorage } from "." +// Filesystem artifact storage needs Linux's /proc/self/fd, so it refuses other +// platforms. +const itOnLinux = it.runIf(process.platform === "linux") + describe("createConfiguredArtifactStorage()", () => { - it("uses the explicitly supplied filesystem directory", async () => { + itOnLinux("uses the explicitly supplied filesystem directory", async () => { const directory = resolve(`server/domains/artifacts/.storage-test-${randomUUID()}`) await mkdir(directory) onTestFinished(() => rm(directory, { recursive: true, force: true })) diff --git a/hub/server/domains/decision-model/create-configured-decision-model-job-processors/index.ts b/hub/server/domains/decision-model/create-configured-decision-model-job-processors/index.ts index 79cf065d1..c083ec9e0 100644 --- a/hub/server/domains/decision-model/create-configured-decision-model-job-processors/index.ts +++ b/hub/server/domains/decision-model/create-configured-decision-model-job-processors/index.ts @@ -40,6 +40,7 @@ export function createConfiguredDecisionModelJobProcessors( database: prisma, databaseUrl, hubOrigin, + learningDatabaseUrl: learning.learningDatabaseUrl, learningRoot: learning.root, nodePath: learning.nodePath, staticDirectories: learning.staticDirectories, diff --git a/hub/server/domains/decision-model/create-decision-model-job-processors/index.test.ts b/hub/server/domains/decision-model/create-decision-model-job-processors/index.test.ts index b6565729d..02f746cbe 100644 --- a/hub/server/domains/decision-model/create-decision-model-job-processors/index.test.ts +++ b/hub/server/domains/decision-model/create-decision-model-job-processors/index.test.ts @@ -208,7 +208,9 @@ describe("createDecisionModelJobProcessors()", () => { idempotencyKey: "withdrawal-succeeded", }, ] - input.listTrainingWithdrawals = vi.fn().mockResolvedValue(withdrawals) + input.listTrainingWithdrawals = vi + .fn() + .mockResolvedValue({ withdrawals, failedRepositoryIds: [] }) const createOrGetDeletion = vi .fn() .mockRejectedValueOnce(new Error("first failed")) @@ -250,4 +252,25 @@ describe("createDecisionModelJobProcessors()", () => { "Decision runtime withdrawal reconciliation failed", ) }) + + it("retries withdrawal discovery when a repository could not be read", async () => { + const input = dependencies("RUNNING") + const listTrainingWithdrawals = vi + .fn() + .mockResolvedValueOnce({ withdrawals: [], failedRepositoryIds: [repositoryId] }) + .mockResolvedValueOnce({ withdrawals: [], failedRepositoryIds: [] }) + input.listTrainingWithdrawals = listTrainingWithdrawals + const processors = createDecisionModelJobProcessors({ + databaseUrl: "postgresql://localhost/replica", + dependencies: input, + database: { decisionTrainingJob: {} } as never, + logger: { warn: vi.fn(), child: () => ({}) } as never, + }) + + await expect(processors.reconcileDeletions.process({})).rejects.toThrow( + "withdrawal discovery remains pending", + ) + await expect(processors.reconcileDeletions.process({})).resolves.toBeUndefined() + expect(listTrainingWithdrawals).toHaveBeenCalledTimes(2) + }) }) diff --git a/hub/server/domains/decision-model/create-decision-model-job-processors/index.ts b/hub/server/domains/decision-model/create-decision-model-job-processors/index.ts index 759cab225..b06e23d5d 100644 --- a/hub/server/domains/decision-model/create-decision-model-job-processors/index.ts +++ b/hub/server/domains/decision-model/create-decision-model-job-processors/index.ts @@ -142,8 +142,9 @@ export function createDecisionModelJobProcessors(input: { } }) const reconcileDeletions = createJobProcessor(reconcileRuntimeDeletionsJob, async () => { - for (const withdrawal of await (input.dependencies.listTrainingWithdrawals?.() ?? - Promise.resolve([]))) { + const discovery = await (input.dependencies.listTrainingWithdrawals?.() ?? + Promise.resolve({ withdrawals: [], failedRepositoryIds: [] })) + for (const withdrawal of discovery.withdrawals) { try { await processDecisionRuntimeDeletion(withdrawal, input.dependencies) } catch (error) { @@ -171,6 +172,11 @@ export function createDecisionModelJobProcessors(input: { ) } } + if (discovery.failedRepositoryIds.length) { + throw new Error( + `Decision training withdrawal discovery remains pending for ${discovery.failedRepositoryIds.length} repositories.`, + ) + } }) return { run, recover, reconcileDeletions } } diff --git a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.db.test.ts b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.db.test.ts new file mode 100644 index 000000000..450b2f3cc --- /dev/null +++ b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.db.test.ts @@ -0,0 +1,590 @@ +import { execFile } from "node:child_process" +import { randomUUID } from "node:crypto" +import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises" +import { join, resolve } from "node:path" +import { promisify } from "node:util" +import pg from "pg" +import { describe, expect, it, onTestFinished, vi } from "vitest" +import { z } from "zod" + +import { prisma } from "../../../integrations/prisma" +import { runLearningCommand } from "../../../integrations/learning/run-learning-command" +import { createHubReviewCollection } from "../../learning/create-hub-review-collection" +import { prepareLearningStore } from "../../learning/prepare-learning-store" +import { captureRepositoryReviewSnapshot } from "../../review-comments/capture-repository-review-snapshot" +import { createReviewCommentService } from "../../review-comments/create-review-comment-service" +import { getDatabaseUrl } from "../../../../test/database/get-database-url" +import { createHubDecisionTasksetSource } from "." + +const execFileAsync = promisify(execFile) +const cliPath = resolve("../packages/learning/bin/replica-learning.mjs") +const repositoryScope = "github.com/repositories/123456" + +async function workspace() { + const root = resolve("..", `.decision-snapshot-${randomUUID()}`) + await mkdir(root, { recursive: true, mode: 0o700 }) + onTestFinished(() => rm(root, { recursive: true, force: true })) + await execFileAsync("git", ["init", "-q", root]) + await writeFile(join(root, ".gitignore"), ".replica/\n") + const scratch = join(root, ".replica", "scratch") + await mkdir(scratch, { recursive: true, mode: 0o700 }) + vi.stubEnv("TMPDIR", scratch) + vi.stubEnv("TMP", scratch) + vi.stubEnv("TEMP", scratch) + return root +} + +async function learningDatabase(root: string) { + const adminUrl = getDatabaseUrl() + const name = `replica_learning_test_${randomUUID().replaceAll("-", "")}` + const admin = new pg.Client({ connectionString: adminUrl }) + await admin.connect() + try { + await admin.query(`CREATE DATABASE ${pg.escapeIdentifier(name)}`) + } finally { + await admin.end() + } + onTestFinished(async () => { + const cleanup = new pg.Client({ connectionString: adminUrl }) + await cleanup.connect() + try { + await cleanup.query(`DROP DATABASE ${pg.escapeIdentifier(name)} WITH (FORCE)`) + } finally { + await cleanup.end() + } + }) + const url = new URL(adminUrl) + url.pathname = name + await execFileAsync(process.execPath, [cliPath, "migrate", "--json"], { + cwd: root, + env: { + PATH: process.env.PATH, + HOME: process.env.HOME, + TMPDIR: process.env.TMPDIR, + REPLICA_LEARNING_MIGRATION_DATABASE_URL: url.href, + }, + }) + return url.href +} + +async function reviewedRepository() { + const repository = await prisma.repository.create({ + data: { githubRepositoryId: 123456n, nameWithOwner: "team/checkout", defaultBranch: "main" }, + }) + const prototype = await prisma.prototype.create({ + data: { + repositoryId: repository.id, + branchName: "checkout", + name: "Checkout", + registeredAt: new Date(), + }, + }) + const build = await prisma.build.create({ + data: { prototypeId: prototype.id, number: 1, state: "successful" }, + }) + const user = await prisma.user.create({ + data: { profile: { create: { provider: "github", login: "reviewer", name: null } } }, + }) + await createReviewCommentService(prisma).createThread({ + sessionDigest: "a".repeat(64), + repositoryId: repository.id, + prototypeId: prototype.id, + buildNumber: build.number, + body: "Keep the field label visible.", + actor: { userId: user.id, login: "reviewer", name: null }, + anchor: { + schemaVersion: 1, + kind: "element", + route: { pathname: "/checkout", search: "", hash: "" }, + selector: "#email", + accessibleName: "Email", + tagName: "input", + selectedText: "", + rect: { x: 0, y: 0, width: 100, height: 40 }, + viewport: { width: 1280, height: 800, scrollX: 0, scrollY: 0 }, + elementOffset: { x: 0.5, y: 0.5 }, + }, + }) + return { repository, prototype } +} + +function storeArguments(root: string, repositoryId: string) { + return [ + "--dir", + join(root, ".replica", "learning", "repositories", repositoryId), + "--repository", + repositoryScope, + "--legacy-repository", + `github.com/repositories/${repositoryId}`, + ] +} + +async function addGrant( + root: string, + repositoryId: string, + purposes: string[], + learningDatabaseUrl?: string, +) { + if (!learningDatabaseUrl) { + await prepareLearningStore({ + applicationRoot: root, + repositoryKey: repositoryId, + repositoryScope, + root: join(root, ".replica", "learning"), + staticDirectories: [], + }) + } + return (await runLearningCommand( + [ + "grants", + "add", + ...purposes.flatMap((purpose) => ["--purpose", purpose]), + "--basis", + "The team agreed to use review evidence.", + "--by", + "human:reviewer", + ...storeArguments(root, repositoryId), + ], + { cliPath, learningDatabaseUrl }, + )) as { id: string } +} + +async function withdrawTraining(root: string, repositoryId: string, grantId: string) { + await runLearningCommand( + [ + "grants", + "withdraw", + grantId, + "--purpose", + "training", + "--by", + "human:reviewer", + ...storeArguments(root, repositoryId), + ], + { cliPath }, + ) +} + +async function importSqlite(root: string, repositoryId: string, databaseUrl: string) { + await execFileAsync( + process.execPath, + [cliPath, "import-sqlite", "--offline", ...storeArguments(root, repositoryId), "--json"], + { + cwd: root, + env: { + PATH: process.env.PATH, + HOME: process.env.HOME, + TMPDIR: process.env.TMPDIR, + REPLICA_LEARNING_DATABASE_URL: databaseUrl, + }, + }, + ) +} + +function source(root: string, learningDatabaseUrl?: string) { + return createHubDecisionTasksetSource({ + applicationRoot: root, + artifactStorage: {} as never, + cliPath, + database: prisma, + databaseUrl: getDatabaseUrl(), + hubOrigin: "https://hub.example.test", + learningDatabaseUrl, + learningRoot: join(root, ".replica", "learning"), + staticDirectories: [], + }).tasksetSource +} + +function exported(bytes: Uint8Array) { + return JSON.parse(new TextDecoder().decode(bytes)) as { + manifest: { records: { kind: string; id: string; digest: string }[] } + grants: unknown[] + collections: { id: string; snapshotId: string; capturedAt: string }[] + episodes: { timeline: { payload?: { body?: string } }[] }[] + memories: unknown[] + } +} + +async function sqliteWithLegacySnapshot() { + const root = await workspace() + const { repository, prototype } = await reviewedRepository() + const grant = await addGrant(root, repository.id, ["review", "training"]) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + const first = await source(root).exportTrainingEvidence(request) + const [collection] = exported(first.bytes).collections + if (!collection) throw new Error("Expected an initial review collection.") + const path = join( + root, + ".replica", + "learning", + "repositories", + repository.id, + "decision-review-snapshot.json", + ) + const legacy = readableLegacySnapshot(await readFile(path, "utf8")) + if (!legacy) throw new Error("Expected the initial SQLite checkpoint.") + expect(legacy).toMatchObject({ + digest: first.repeatableReviewSnapshotDigest, + snapshotId: collection.snapshotId, + }) + expect(new Date(legacy.capturedAt)).toEqual(new Date(collection.capturedAt)) + await expect( + prisma.decisionReviewSnapshot.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toBeNull() + await withdrawTraining(root, repository.id, grant.id) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Account" } }) + return { root, repository, prototype, request, first, collection, path } +} + +/** + * Invalid legacy files cause older preflights to fail instead of reusing a snapshot. + */ +function readableLegacySnapshot(contents: string) { + try { + const parsed = z + .object({ digest: z.string(), snapshotId: z.uuid(), capturedAt: z.iso.datetime() }) + .strict() + .safeParse(JSON.parse(contents)) + return parsed.success ? parsed.data : null + } catch (error) { + if (error instanceof SyntaxError) return null + throw error + } +} + +describe("createHubDecisionTasksetSource() training exports", () => { + it("retries PostgreSQL exports and imports a returned snapshot as new", async () => { + const root = await workspace() + const databaseUrl = await learningDatabase(root) + const { repository, prototype } = await reviewedRepository() + const grant = await addGrant(root, repository.id, ["review", "training"], databaseUrl) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + const directory = join(root, ".replica", "learning", "repositories", repository.id) + + const first = await source(root, databaseUrl).exportTrainingEvidence(request) + const retry = await source(root, databaseUrl).exportTrainingEvidence(request) + expect(retry).toEqual(first) + expect(first.consentGrantId).toBe(grant.id) + expect(exported(first.bytes).episodes[0]?.timeline[0]?.payload?.body).toBe( + "Keep the field label visible.", + ) + expect(exported(first.bytes).collections).toHaveLength(1) + + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Account" } }) + const changed = await source(root, databaseUrl).exportTrainingEvidence(request) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Checkout" } }) + const returned = await source(root, databaseUrl).exportTrainingEvidence(request) + const returnedRetry = await source(root, databaseUrl).exportTrainingEvidence(request) + + expect(returned.repeatableReviewSnapshotDigest).toBe(first.repeatableReviewSnapshotDigest) + expect(returned.digest).not.toBe(first.digest) + expect(exported(changed.bytes).collections).toHaveLength(2) + expect(exported(returned.bytes).collections).toHaveLength(3) + expect(exported(returned.bytes).collections[2]?.snapshotId).not.toBe( + exported(first.bytes).collections[0]?.snapshotId, + ) + expect(returnedRetry).toEqual(returned) + await expect(access(directory)).rejects.toMatchObject({ code: "ENOENT" }) + }, 60_000) + + it("does not overwrite an unchanged successor after the execution lock is lost", async () => { + const root = await workspace() + const databaseUrl = await learningDatabase(root) + const { repository, prototype } = await reviewedRepository() + await addGrant(root, repository.id, ["review"], databaseUrl) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + const first = await source(root, databaseUrl).exportTrainingEvidence(request) + const checkpoint = await prisma.decisionReviewSnapshot.findUniqueOrThrow({ + where: { repositoryId: repository.id }, + select: { digest: true, snapshotId: true, capturedAt: true }, + }) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Account" } }) + + const gate = new pg.Client({ connectionString: getDatabaseUrl() }) + await gate.connect() + const trigger = `checkpoint_gate_${randomUUID().replaceAll("-", "")}` + let gateHeld = false + let stale: Promise | null = null + try { + // Pause the write while its connection still owns the execution lock. + await gate.query(` + CREATE FUNCTION "${trigger}"() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + PERFORM pg_advisory_xact_lock(1919242348, 201); + RETURN NULL; + END $$; + CREATE TRIGGER "${trigger}" BEFORE UPDATE ON decision_review_snapshots + FOR EACH STATEMENT EXECUTE FUNCTION "${trigger}"(); + `) + await gate.query("SELECT pg_advisory_lock(1919242348, 201)") + gateHeld = true + stale = source(root, databaseUrl).exportTrainingEvidence(request) + void stale.catch(() => {}) + + let blockedPid = 0 + await vi.waitFor( + async () => { + const waiting = await gate.query<{ pid: number }>(` + SELECT waiting.pid + FROM pg_locks AS waiting + JOIN pg_locks AS execution ON execution.pid = waiting.pid + WHERE waiting.locktype = 'advisory' AND waiting.classid = 1919242348 + AND waiting.objid = 201 AND NOT waiting.granted + AND execution.locktype = 'advisory' AND execution.classid = 1919242348 + AND execution.objid = 2 AND execution.granted + AND waiting.database = (SELECT oid FROM pg_database WHERE datname = current_database()) + `) + expect(waiting.rows).toHaveLength(1) + blockedPid = waiting.rows[0]!.pid + }, + { timeout: 10_000 }, + ) + const terminated = await gate.query<{ terminated: boolean }>( + "SELECT pg_terminate_backend($1) AS terminated", + [blockedPid], + ) + expect(terminated.rows).toEqual([{ terminated: true }]) + await expect(stale).rejects.toThrow() + + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Checkout" } }) + await gate.query("SELECT pg_advisory_unlock(1919242348, 201)") + gateHeld = false + const successor = await source(root, databaseUrl).exportTrainingEvidence(request) + expect(successor.repeatableReviewSnapshotDigest).toBe(first.repeatableReviewSnapshotDigest) + await expect( + prisma.decisionReviewSnapshot.findUniqueOrThrow({ + where: { repositoryId: repository.id }, + select: { digest: true, snapshotId: true, capturedAt: true }, + }), + ).resolves.toEqual(checkpoint) + expect(await source(root, databaseUrl).exportTrainingEvidence(request)).toEqual(successor) + } finally { + if (gateHeld) await gate.query("SELECT pg_advisory_unlock(1919242348, 201)") + if (stale) await stale.catch(() => {}) + await gate.query( + `DROP TRIGGER IF EXISTS "${trigger}" ON decision_review_snapshots; DROP FUNCTION IF EXISTS "${trigger}"()`, + ) + await gate.end() + } + }, 60_000) + + it("imports a returned snapshot after a change without training consent", async () => { + const root = await workspace() + const databaseUrl = await learningDatabase(root) + const { repository, prototype } = await reviewedRepository() + const grant = await addGrant(root, repository.id, ["review", "training"], databaseUrl) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + const first = await source(root, databaseUrl).exportTrainingEvidence(request) + + await runLearningCommand( + [ + "grants", + "withdraw", + grant.id, + "--purpose", + "training", + "--by", + "human:reviewer", + ...storeArguments(root, repository.id), + ], + { cliPath, learningDatabaseUrl: databaseUrl }, + ) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Account" } }) + const withheld = await source(root, databaseUrl).exportTrainingEvidence(request) + const status = await runLearningCommand(["status", ...storeArguments(root, repository.id)], { + cliPath, + learningDatabaseUrl: databaseUrl, + }) + expect(withheld.consentGrantId).toBeNull() + expect(withheld.bytes).toHaveLength(0) + expect(withheld.repeatableReviewSnapshotDigest).not.toBe(first.repeatableReviewSnapshotDigest) + expect(status).toMatchObject({ counts: { completeCollections: 1 } }) + + await addGrant(root, repository.id, ["training"], databaseUrl) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Checkout" } }) + const returned = await source(root, databaseUrl).exportTrainingEvidence(request) + const retry = await source(root, databaseUrl).exportTrainingEvidence(request) + + expect(returned.repeatableReviewSnapshotDigest).toBe(first.repeatableReviewSnapshotDigest) + expect(exported(returned.bytes).collections).toHaveLength(2) + expect(exported(returned.bytes).collections[1]?.snapshotId).not.toBe( + exported(first.bytes).collections[0]?.snapshotId, + ) + expect(retry).toEqual(returned) + }, 60_000) + + it("retries the same export after an offline SQLite migration", async () => { + const root = await workspace() + const databaseUrl = await learningDatabase(root) + const { repository } = await reviewedRepository() + await addGrant(root, repository.id, ["review", "training"]) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + const directory = join(root, ".replica", "learning", "repositories", repository.id) + const original = await source(root).exportTrainingEvidence(request) + const originalBundle = exported(original.bytes) + const [collection] = originalBundle.collections + expect(collection).toBeDefined() + const legacy = readableLegacySnapshot( + await readFile(join(directory, "decision-review-snapshot.json"), "utf8"), + ) + if (!legacy) throw new Error("Expected the initial SQLite checkpoint.") + expect(legacy).toMatchObject({ + digest: original.repeatableReviewSnapshotDigest, + snapshotId: collection!.snapshotId, + }) + expect(new Date(legacy.capturedAt)).toEqual(new Date(collection!.capturedAt)) + await expect( + prisma.decisionReviewSnapshot.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toBeNull() + await importSqlite(root, repository.id, databaseUrl) + + const retained = await source(root, databaseUrl).exportTrainingEvidence(request) + await rm(directory, { recursive: true, force: true }) + const unmounted = await source(root, databaseUrl).exportTrainingEvidence(request) + const migratedBundle = exported(retained.bytes) + expect(migratedBundle.collections).toEqual(originalBundle.collections) + expect(migratedBundle.manifest.records).toEqual(originalBundle.manifest.records) + expect(migratedBundle.grants).toEqual(originalBundle.grants) + expect(migratedBundle.episodes).toEqual(originalBundle.episodes) + expect(migratedBundle.memories).toEqual(originalBundle.memories) + expect(unmounted).toEqual(retained) + await expect(access(directory)).rejects.toMatchObject({ code: "ENOENT" }) + }, 60_000) + + it("preserves a no-consent snapshot from the SQLite file during cutover", async () => { + const root = await workspace() + const databaseUrl = await learningDatabase(root) + const { repository, prototype } = await reviewedRepository() + const grant = await addGrant(root, repository.id, ["review", "training"]) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + const directory = join(root, ".replica", "learning", "repositories", repository.id) + const first = await source(root).exportTrainingEvidence(request) + + await runLearningCommand( + [ + "grants", + "withdraw", + grant.id, + "--purpose", + "training", + "--by", + "human:reviewer", + ...storeArguments(root, repository.id), + ], + { cliPath }, + ) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Account" } }) + const withheld = await source(root).exportTrainingEvidence(request) + expect(withheld.bytes).toHaveLength(0) + const legacySnapshot = readableLegacySnapshot( + await readFile(join(directory, "decision-review-snapshot.json"), "utf8"), + ) + expect(legacySnapshot).toMatchObject({ digest: withheld.repeatableReviewSnapshotDigest }) + if (!legacySnapshot) throw new Error("Expected the no-consent SQLite checkpoint.") + await expect( + prisma.decisionReviewSnapshot.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toBeNull() + await importSqlite(root, repository.id, databaseUrl) + + const migrated = await source(root, databaseUrl).exportTrainingEvidence(request) + expect(migrated.consentGrantId).toBeNull() + expect(migrated.bytes).toHaveLength(0) + expect(migrated.repeatableReviewSnapshotDigest).toBe(withheld.repeatableReviewSnapshotDigest) + expect( + await prisma.decisionReviewSnapshot.findUniqueOrThrow({ + where: { repositoryId: repository.id }, + }), + ).toMatchObject({ + ...legacySnapshot, + capturedAt: new Date(legacySnapshot.capturedAt), + }) + await rm(directory, { recursive: true, force: true }) + + await addGrant(root, repository.id, ["training"], databaseUrl) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Checkout" } }) + const returned = await source(root, databaseUrl).exportTrainingEvidence(request) + const retry = await source(root, databaseUrl).exportTrainingEvidence(request) + expect(returned.repeatableReviewSnapshotDigest).toBe(first.repeatableReviewSnapshotDigest) + expect(exported(returned.bytes).collections).toHaveLength(2) + expect(exported(returned.bytes).collections[1]?.snapshotId).not.toBe( + exported(first.bytes).collections[0]?.snapshotId, + ) + expect(retry).toEqual(returned) + }, 60_000) + + it("does not reuse A after an older SQLite writer observes B without consent", async () => { + const { root, repository, prototype, request, first, collection, path } = + await sqliteWithLegacySnapshot() + const snapshot = await captureRepositoryReviewSnapshot(prisma, repository.id) + const changed = createHubReviewCollection(snapshot, "https://hub.example.test", repositoryScope) + expect(changed.digest).not.toBe(first.repeatableReviewSnapshotDigest) + await writeFile( + path, + JSON.stringify({ + digest: changed.digest, + snapshotId: snapshot.snapshotId, + capturedAt: snapshot.capturedAt.toISOString(), + }), + { mode: 0o600 }, + ) + await expect( + prisma.decisionReviewSnapshot.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toBeNull() + + await addGrant(root, repository.id, ["training"]) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Checkout" } }) + const returned = await source(root).exportTrainingEvidence(request) + expect(returned.repeatableReviewSnapshotDigest).toBe(first.repeatableReviewSnapshotDigest) + expect(exported(returned.bytes).collections).toHaveLength(2) + expect(exported(returned.bytes).collections[1]?.snapshotId).not.toBe(collection.snapshotId) + expect(await source(root).exportTrainingEvidence(request)).toEqual(returned) + await expect( + prisma.decisionReviewSnapshot.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toBeNull() + }, 60_000) + + it("updates the SQLite checkpoint when training consent is off", async () => { + const { root, repository, prototype, request, first, collection, path } = + await sqliteWithLegacySnapshot() + const withheld = await source(root).exportTrainingEvidence(request) + expect(withheld.consentGrantId).toBeNull() + expect(withheld.bytes).toHaveLength(0) + expect(withheld.repeatableReviewSnapshotDigest).not.toBe(first.repeatableReviewSnapshotDigest) + + const legacy = readableLegacySnapshot(await readFile(path, "utf8")) + expect(legacy).toMatchObject({ digest: withheld.repeatableReviewSnapshotDigest }) + expect(legacy?.snapshotId).not.toBe(collection.snapshotId) + await expect( + prisma.decisionReviewSnapshot.findUnique({ where: { repositoryId: repository.id } }), + ).resolves.toBeNull() + + await addGrant(root, repository.id, ["training"]) + await prisma.prototype.update({ where: { id: prototype.id }, data: { name: "Checkout" } }) + const returned = await source(root).exportTrainingEvidence(request) + expect(exported(returned.bytes).collections).toHaveLength(2) + expect(exported(returned.bytes).collections[1]?.snapshotId).not.toBe(collection.snapshotId) + expect(await source(root).exportTrainingEvidence(request)).toEqual(returned) + }, 60_000) + + it("does not import evidence without training consent", async () => { + const root = await workspace() + const databaseUrl = await learningDatabase(root) + const { repository } = await reviewedRepository() + await addGrant(root, repository.id, ["review"], databaseUrl) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + + const result = await source(root, databaseUrl).exportTrainingEvidence(request) + const status = await runLearningCommand(["status", ...storeArguments(root, repository.id)], { + cliPath, + learningDatabaseUrl: databaseUrl, + }) + expect(result.consentGrantId).toBeNull() + expect(result.bytes).toHaveLength(0) + expect(status).toMatchObject({ + counts: { episodes: 0, events: 0, completeCollections: 0, incompleteCollections: 0 }, + }) + await expect( + access(join(root, ".replica", "learning", "repositories", repository.id)), + ).rejects.toMatchObject({ code: "ENOENT" }) + }, 60_000) +}) diff --git a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts index bd12f30bb..76688cc18 100644 --- a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts +++ b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts @@ -89,14 +89,21 @@ function storage( } } -function hubSource(artifactStorage: ArtifactStorage) { +function hubSource( + artifactStorage: ArtifactStorage, + githubRepositoryId: bigint | null = 123n, + learningDatabaseUrl?: string, +) { return createHubDecisionTasksetSource({ applicationRoot: process.cwd(), artifactStorage, cliPath: "/replica-learning.mjs", - database: {} as never, + database: { + repository: { findUnique: vi.fn().mockResolvedValue({ githubRepositoryId }) }, + } as never, databaseUrl: "postgresql://test", hubOrigin: "https://hub.example.test", + learningDatabaseUrl, learningRoot: "server/domains/decision-model/create-hub-decision-taskset-source/.learning", staticDirectories: [], stabilizeSnapshot: vi.fn().mockResolvedValue({ @@ -145,11 +152,60 @@ function decodeArchive(bytes: Uint8Array) { } describe("createHubDecisionTasksetSource()", () => { + it("reads training consent from the configured database", async () => { + const learningDatabaseUrl = "postgresql://learning.example/replica" + vi.mocked(prepareLearningStore).mockResolvedValue({ + directory: "/private/learning/repository", + repositoryScope: "github.com/repositories/123", + repositoryId, + }) + vi.mocked(runLearningCommand).mockResolvedValue([ + { + grant: { id: "grant-training", sources: ["hub_review_comments"] }, + activePurposes: ["training"], + expired: false, + }, + ]) + + const result = await hubSource( + storage({}), + 123n, + learningDatabaseUrl, + ).tasksetSource.hasTrainingConsent({ + repositoryId, + actorMembershipId: "44444444-4444-4444-8444-444444444444", + consentGrantId: "grant-training", + }) + + expect(result).toBe(true) + expect(prepareLearningStore).toHaveBeenCalledWith( + expect.objectContaining({ learningDatabaseUrl }), + ) + const [arguments_, options] = vi.mocked(runLearningCommand).mock.calls[0]! + expect(arguments_).not.toContain(learningDatabaseUrl) + expect(options).toMatchObject({ learningDatabaseUrl }) + }) + + it("does not open a learning store for a repository without a GitHub ID", async () => { + const taskset = hubSource(storage({}), null).tasksetSource + + await expect( + taskset.hasTrainingConsent({ + repositoryId, + actorMembershipId: "44444444-4444-4444-8444-444444444444", + consentGrantId: "grant-training", + }), + ).rejects.toMatchObject({ status: 409, code: "learning_ineligible" }) + expect(prepareLearningStore).not.toHaveBeenCalled() + expect(runLearningCommand).not.toHaveBeenCalled() + }) + it("reads active training consent and NOUL learning questions for the requesting member", async () => { const learningId = "mem_111111111111111111111111" vi.mocked(prepareLearningStore).mockResolvedValue({ directory: "/private/learning/repository", - repositoryScope: `github.com/repositories/${repositoryId}`, + repositoryScope: "github.com/repositories/123", + repositoryId, }) vi.mocked(runLearningCommand).mockImplementation((arguments_) => { if (arguments_[0] === "grants") { @@ -268,7 +324,8 @@ describe("createHubDecisionTasksetSource()", () => { .mockRejectedValueOnce(new Error("damaged store")) .mockResolvedValueOnce({ directory: "/private/learning/repository", - repositoryScope: `github.com/repositories/${repositoryId}`, + repositoryScope: "github.com/repositories/123", + repositoryId, }) vi.mocked(runLearningCommand).mockResolvedValue([ { @@ -279,7 +336,98 @@ describe("createHubDecisionTasksetSource()", () => { }, ]) - await expect(source(storage({})).listTrainingWithdrawals()).resolves.toHaveLength(1) + await expect(source(storage({})).listTrainingWithdrawals()).resolves.toMatchObject({ + withdrawals: [expect.objectContaining({ repositoryId })], + failedRepositoryIds: ["aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"], + }) + }) + + it("keeps withdrawal discovery pending for a repository without a GitHub ID", async () => { + vi.mocked(listDecisionWithdrawalSources).mockResolvedValue([ + { + id: repositoryId, + decisionTrainingJobs: [ + { + consentGrantId: "grant-training", + trainingExportId: "export-1", + evidenceDigest: `sha256:${"e".repeat(64)}`, + tasksetDigest: `sha256:${"t".repeat(64)}`, + }, + ], + accessGrants: [], + }, + ] as never) + + await expect( + hubSource(storage({}), null).tasksetSource.listTrainingWithdrawals(), + ).resolves.toEqual({ + withdrawals: [], + failedRepositoryIds: [repositoryId], + }) + expect(prepareLearningStore).not.toHaveBeenCalled() + expect(runLearningCommand).not.toHaveBeenCalled() + }) + + it("retries a training withdrawal after a repository administrator returns", async () => { + const trainingJob = { + consentGrantId: "grant-training", + trainingExportId: "export-1", + evidenceDigest: `sha256:${"e".repeat(64)}`, + tasksetDigest: `sha256:${"d".repeat(64)}`, + } + vi.mocked(listDecisionWithdrawalSources) + .mockResolvedValueOnce([ + { id: repositoryId, decisionTrainingJobs: [trainingJob], accessGrants: [] }, + ] as never) + .mockResolvedValueOnce([ + { + id: repositoryId, + decisionTrainingJobs: [trainingJob], + accessGrants: [ + { + membershipId: "99999999-9999-4999-8999-999999999999", + membership: { user: { profile: { login: "active-admin" } } }, + }, + ], + }, + ] as never) + vi.mocked(prepareLearningStore).mockResolvedValue({ + directory: "/private/learning/repository", + repositoryScope: "github.com/repositories/123", + repositoryId, + }) + vi.mocked(runLearningCommand).mockResolvedValue([ + { + id: "withdrawal-1", + grantId: "grant-training", + purposes: ["training"], + withdrawnBy: { id: "github:mona" }, + }, + ]) + const taskset = source(storage({})) + + await expect(taskset.listTrainingWithdrawals()).resolves.toEqual({ + withdrawals: [], + failedRepositoryIds: [repositoryId], + }) + await expect(taskset.listTrainingWithdrawals()).resolves.toEqual({ + withdrawals: [ + { + repositoryId, + actorMembershipId: "99999999-9999-4999-8999-999999999999", + actorLogin: "mona", + selectors: { + exportId: trainingJob.trainingExportId, + grantId: trainingJob.consentGrantId, + evidenceDigest: trainingJob.evidenceDigest, + tasksetDigest: trainingJob.tasksetDigest, + }, + reason: "Training consent was withdrawn.", + idempotencyKey: `withdrawal:withdrawal-1:${trainingJob.tasksetDigest}`, + }, + ], + failedRepositoryIds: [], + }) }) it("maps training grant withdrawals to idempotent runtime deletion selectors", async () => { @@ -308,7 +456,8 @@ describe("createHubDecisionTasksetSource()", () => { ] as never) vi.mocked(prepareLearningStore).mockResolvedValue({ directory: "/private/learning/repository", - repositoryScope: `github.com/repositories/${repositoryId}`, + repositoryScope: "github.com/repositories/123", + repositoryId, }) vi.mocked(runLearningCommand).mockResolvedValue([ { @@ -320,27 +469,32 @@ describe("createHubDecisionTasksetSource()", () => { }, ]) - await expect(source(storage({})).listTrainingWithdrawals()).resolves.toEqual([ - { - repositoryId, - actorMembershipId: "99999999-9999-4999-8999-999999999999", - actorLogin: "mona", - selectors: { grantId: "grant-secondary" }, - reason: "The repository administrator withdrew training consent.", - idempotencyKey: "withdrawal:withdrawal-1:grant", - }, - ]) + await expect(source(storage({})).listTrainingWithdrawals()).resolves.toEqual({ + withdrawals: [ + { + repositoryId, + actorMembershipId: "99999999-9999-4999-8999-999999999999", + actorLogin: "mona", + selectors: { grantId: "grant-secondary" }, + reason: "The repository administrator withdrew training consent.", + idempotencyKey: "withdrawal:withdrawal-1:grant", + }, + ], + failedRepositoryIds: [], + }) }) it("reports deterministic eligible evidence, task, split, and label counts", async () => { vi.mocked(withLearningExecutionLock).mockImplementation(({ run }) => run(new AbortController().signal, { + client: {} as never, runWithoutRepositoryAuthorityLock: (operation) => operation(), }), ) vi.mocked(prepareLearningStore).mockResolvedValue({ directory: "/private/learning/repository", - repositoryScope: `github.com/repositories/${repositoryId}`, + repositoryScope: "github.com/repositories/123", + repositoryId, }) vi.mocked(captureRepositoryReviewSnapshot).mockResolvedValue({ repository: { id: repositoryId }, @@ -472,6 +626,17 @@ describe("createHubDecisionTasksetSource()", () => { .mock.calls.map(([arguments_]) => arguments_) .filter(([command]) => command === "export"), ).toEqual([expect.arrayContaining(["--preview"]), expect.arrayContaining(["--preview"])]) + for (const [arguments_] of vi.mocked(runLearningCommand).mock.calls) { + if (arguments_[0] === "decision" && arguments_[1] === "taskset") continue + expect(arguments_).toEqual( + expect.arrayContaining([ + "--repository", + "github.com/repositories/123", + "--legacy-repository", + `github.com/repositories/${repositoryId}`, + ]), + ) + } const importCall = vi .mocked(runLearningCommand) .mock.calls.map(([arguments_]) => arguments_) @@ -485,12 +650,14 @@ describe("createHubDecisionTasksetSource()", () => { const privateEvidence = "Do not expose this private learning" vi.mocked(withLearningExecutionLock).mockImplementation(({ run }) => run(new AbortController().signal, { + client: {} as never, runWithoutRepositoryAuthorityLock: (operation) => operation(), }), ) vi.mocked(prepareLearningStore).mockResolvedValue({ directory: "/private/learning/repository", - repositoryScope: `github.com/repositories/${repositoryId}`, + repositoryScope: "github.com/repositories/123", + repositoryId, }) vi.mocked(captureRepositoryReviewSnapshot).mockResolvedValue({ repository: { id: repositoryId }, @@ -552,7 +719,7 @@ describe("createHubDecisionTasksetSource()", () => { expect(JSON.stringify(result)).not.toContain(otherRepositoryId) expect(runLearningCommand).toHaveBeenCalledTimes(1) expect(runLearningCommand).toHaveBeenCalledWith( - expect.arrayContaining(["--repository", `github.com/repositories/${repositoryId}`]), + expect.arrayContaining(["--repository", "github.com/repositories/123"]), expect.anything(), ) }) @@ -560,12 +727,14 @@ describe("createHubDecisionTasksetSource()", () => { it("exports repository-scoped learning evidence deterministically on retry", async () => { vi.mocked(withLearningExecutionLock).mockImplementation(({ run }) => run(new AbortController().signal, { + client: {} as never, runWithoutRepositoryAuthorityLock: (operation) => operation(), }), ) vi.mocked(prepareLearningStore).mockResolvedValue({ directory: "/private/learning/repository", - repositoryScope: `github.com/repositories/${repositoryId}`, + repositoryScope: "github.com/repositories/123", + repositoryId, }) vi.mocked(captureRepositoryReviewSnapshot).mockResolvedValue({ repository: { id: repositoryId }, @@ -644,13 +813,13 @@ describe("createHubDecisionTasksetSource()", () => { ).toEqual([ expect.arrayContaining([ "--repository", - `github.com/repositories/${repositoryId}`, + "github.com/repositories/123", "--purpose", "training", ]), expect.arrayContaining([ "--repository", - `github.com/repositories/${repositoryId}`, + "github.com/repositories/123", "--purpose", "training", ]), @@ -841,7 +1010,8 @@ describe("createHubDecisionTasksetSource()", () => { }) vi.mocked(prepareLearningStore).mockResolvedValue({ directory: "/private/learning/repository", - repositoryScope: `github.com/repositories/${repositoryId}`, + repositoryScope: "github.com/repositories/123", + repositoryId, }) vi.mocked(runLearningCommand).mockResolvedValue({ questions: { diff --git a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts index 5a417f404..cbed8e8ec 100644 --- a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts +++ b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts @@ -15,16 +15,21 @@ import { tmpdir } from "node:os" import { join, resolve } from "node:path" import { z } from "zod" import type { Logger } from "pino" +import type { Client } from "pg" import type { PrismaClient } from "../../../generated/prisma/client.ts" import { runLearningCommand } from "../../../integrations/learning/run-learning-command/index.ts" import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" import type { ArtifactStorage } from "../../artifacts/create-artifact-storage/types.ts" import { createHubReviewCollection } from "../../learning/create-hub-review-collection/index.ts" +import { getLearningRepositoryScope } from "../../learning/get-learning-repository-scope/index.ts" +import { learningStoreArguments } from "../../learning/learning-store-arguments/index.ts" import { prepareLearningStore } from "../../learning/prepare-learning-store/index.ts" import { captureRepositoryReviewSnapshot } from "../../review-comments/capture-repository-review-snapshot/index.ts" import { listDecisionTrainingBuilds } from "../../../repositories/decision-training-builds/list-decision-training-builds/index.ts" import { findDecisionEvaluationBuild } from "../../../repositories/decision-training-builds/find-decision-evaluation-build/index.ts" +import { getDecisionReviewSnapshot } from "../../../repositories/decision-review-snapshots/get-decision-review-snapshot/index.ts" +import { saveDecisionReviewSnapshot } from "../../../repositories/decision-review-snapshots/save-decision-review-snapshot/index.ts" import { listDecisionWithdrawalSources } from "../../../repositories/decision-training-jobs/list-decision-withdrawal-sources/index.ts" import { withLearningExecutionLock } from "../../../integrations/postgres/with-learning-execution-lock/index.ts" import { DecisionModelError } from "../errors.ts" @@ -168,6 +173,7 @@ interface HubDecisionTasksetSourceOptions { database: PrismaClient databaseUrl: string hubOrigin: string + learningDatabaseUrl?: string learningRoot: string nodePath?: string staticDirectories: string[] @@ -240,14 +246,12 @@ function digestJson(value: unknown): string { return sha256(canonicalJson(value)) } -async function stabilizeReviewSnapshot( - directory: string, - digest: string, - capturedAt: Date, -): Promise<{ snapshotId: string; capturedAt: Date }> { - const statePath = join(directory, "decision-review-snapshot.json") +async function readLegacyReviewSnapshot(directory: string) { try { - const handle = await open(statePath, constants.O_RDONLY | constants.O_NOFOLLOW) + const handle = await open( + join(directory, "decision-review-snapshot.json"), + constants.O_RDONLY | constants.O_NOFOLLOW, + ) try { const state = z .object({ @@ -257,20 +261,26 @@ async function stabilizeReviewSnapshot( }) .strict() .parse(JSON.parse(await handle.readFile("utf8"))) - if (state.digest === digest) { - return { snapshotId: state.snapshotId, capturedAt: new Date(state.capturedAt) } - } + return { ...state, capturedAt: new Date(state.capturedAt) } } finally { await handle.close() } } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + return null } - const state = { - digest, - snapshotId: randomUUID(), - capturedAt: capturedAt.toISOString(), - } +} + +async function stabilizeLocalReviewSnapshot( + directory: string, + digest: string, + capturedAt: Date, + signal: AbortSignal, +): Promise<{ snapshotId: string; capturedAt: Date }> { + const previous = await readLegacyReviewSnapshot(directory) + signal.throwIfAborted() + if (previous?.digest === digest) return previous + const next = { digest, snapshotId: randomUUID(), capturedAt } const temporary = join(directory, `.decision-review-snapshot-${randomUUID()}`) const handle = await open( temporary, @@ -278,13 +288,45 @@ async function stabilizeReviewSnapshot( 0o600, ) try { - await handle.writeFile(`${JSON.stringify(state)}\n`) - await handle.sync() + try { + await handle.writeFile(`${JSON.stringify(next)}\n`) + await handle.sync() + } finally { + await handle.close() + } + signal.throwIfAborted() + await rename(temporary, join(directory, "decision-review-snapshot.json")) } finally { - await handle.close() + await rm(temporary, { force: true }) + } + return next +} + +async function stabilizeReviewSnapshot( + database: PrismaClient, + lockClient: Pick, + repositoryId: string, + directory: string, + digest: string, + capturedAt: Date, + signal: AbortSignal, +): Promise<{ snapshotId: string; capturedAt: Date }> { + const stored = await getDecisionReviewSnapshot(database, repositoryId) + signal.throwIfAborted() + const previous = stored ?? (await readLegacyReviewSnapshot(directory)) + signal.throwIfAborted() + if (stored?.digest === digest) return stored + const next = + previous?.digest === digest ? previous : { digest, snapshotId: randomUUID(), capturedAt } + if (!(await saveDecisionReviewSnapshot(lockClient, repositoryId, next, stored))) { + throw new DecisionModelError( + 409, + "taskset_drift", + "The review snapshot changed during taskset preparation. Try again.", + ) } - await rename(temporary, statePath) - return { snapshotId: state.snapshotId, capturedAt } + signal.throwIfAborted() + return next } function stableExport(bundle: Record, snapshotDigest: string) { @@ -456,17 +498,35 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource async function command(arguments_: string[], timeoutMs = 60_000, signal?: AbortSignal) { return runLearningCommand(arguments_, { cliPath: options.cliPath, + learningDatabaseUrl: options.learningDatabaseUrl, nodePath: options.nodePath, signal, timeoutMs, }) } + async function learningScope(repositoryId: string) { + try { + return await getLearningRepositoryScope(options.database, repositoryId) + } catch (error) { + if (error instanceof LearningCommandError && error.code === "repository_scope_unavailable") { + throw new DecisionModelError( + 409, + "learning_ineligible", + "Decision-model learning is unavailable because this repository has no GitHub repository ID.", + { cause: error }, + ) + } + throw error + } + } + async function learningStore(repositoryId: string) { return prepareLearningStore({ applicationRoot, + learningDatabaseUrl: options.learningDatabaseUrl, repositoryKey: repositoryId, - repositoryScope: `github.com/repositories/${repositoryId}`, + repositoryScope: await learningScope(repositoryId), root: options.learningRoot, staticDirectories: options.staticDirectories, }) @@ -740,26 +800,18 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource return { async readAgentLearningAuthority({ repositoryId, actorMembershipId, consentGrantId }) { const store = await learningStore(repositoryId) - const [grants, questionResult] = await Promise.all([ - command([ - "grants", - "list", - "--dir", - store.directory, - "--repository", - store.repositoryScope, - ]).then((value) => grantListSchema.parse(value)), - command([ + const grants = grantListSchema.parse( + await command(["grants", "list", ...learningStoreArguments(store)]), + ) + const questionResult = decisionQuestionsSchema.safeParse( + await command([ "decision", "questions", "--by", `human:${actorMembershipId}`, - "--dir", - store.directory, - "--repository", - store.repositoryScope, - ]).then((value) => decisionQuestionsSchema.safeParse(value)), - ]) + ...learningStoreArguments(store), + ]), + ) if (!questionResult.success) { throw new DecisionModelError( 422, @@ -785,14 +837,7 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource async hasTrainingConsent({ repositoryId, consentGrantId }) { const store = await learningStore(repositoryId) const grants = grantListSchema.parse( - await command([ - "grants", - "list", - "--dir", - store.directory, - "--repository", - store.repositoryScope, - ]), + await command(["grants", "list", ...learningStoreArguments(store)]), ) return grants.some( ({ grant, activePurposes, expired }) => @@ -811,10 +856,7 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource "accepted", "--actor", "system:replica-hub", - "--dir", - store.directory, - "--repository", - store.repositoryScope, + ...learningStoreArguments(store), ]), ) return Object.fromEntries( @@ -826,21 +868,16 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource }, async listTrainingWithdrawals() { const pending = [] + const failedRepositoryIds: string[] = [] for (const repository of await listDecisionWithdrawalSources(options.database)) { let withdrawals: z.infer try { const store = await learningStore(repository.id) withdrawals = withdrawalsSchema.parse( - await command([ - "grants", - "withdrawals", - "--dir", - store.directory, - "--repository", - store.repositoryScope, - ]), + await command(["grants", "withdrawals", ...learningStoreArguments(store)]), ) } catch (error) { + failedRepositoryIds.push(repository.id) options.logger?.warn( { repositoryId: repository.id, @@ -861,7 +898,15 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource ) const actorMembershipId = matchingActorGrant?.membershipId ?? repository.accessGrants[0]?.membershipId - if (!actorMembershipId) continue + if (!actorMembershipId) { + if (!failedRepositoryIds.includes(repository.id)) + failedRepositoryIds.push(repository.id) + options.logger?.warn( + { repositoryId: repository.id }, + "Decision training withdrawal needs an active repository administrator", + ) + continue + } if (!matchingJobs.length) { pending.push({ repositoryId: repository.id, @@ -890,7 +935,7 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource } } } - return pending + return { withdrawals: pending, failedRepositoryIds } }, async preflight({ repositoryId, actorMembershipId }): Promise { const [trainingExport, buildArtifacts] = await Promise.all([ @@ -997,9 +1042,9 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource try { return await withLearningExecutionLock({ databaseUrl: options.databaseUrl, - run: async (signal) => { + run: async (signal, { client }) => { const store = await learningStore(repositoryId) - const common = ["--dir", store.directory, "--repository", store.repositoryScope] + const common = learningStoreArguments(store) const grants = grantListSchema.parse( await command(["grants", "list", ...common], 60_000, signal), ) @@ -1026,15 +1071,47 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource repositoryId, new Date(), ) - const initialReview = createHubReviewCollection(snapshot, options.hubOrigin) - const metadata = await (options.stabilizeSnapshot ?? stabilizeReviewSnapshot)( - store.directory, - initialReview.digest, - snapshot.capturedAt, + if (store.repositoryScope !== (await learningScope(repositoryId))) { + throw new DecisionModelError( + 409, + "taskset_drift", + "The repository learning scope changed during taskset preparation.", + ) + } + const initialReview = createHubReviewCollection( + snapshot, + options.hubOrigin, + store.repositoryScope, ) + const metadata = options.stabilizeSnapshot + ? await options.stabilizeSnapshot( + store.directory, + initialReview.digest, + snapshot.capturedAt, + ) + : options.learningDatabaseUrl + ? await stabilizeReviewSnapshot( + options.database, + client, + repositoryId, + store.directory, + initialReview.digest, + snapshot.capturedAt, + signal, + ) + : await stabilizeLocalReviewSnapshot( + store.directory, + initialReview.digest, + snapshot.capturedAt, + signal, + ) snapshot.snapshotId = metadata.snapshotId snapshot.capturedAt = metadata.capturedAt - const review = createHubReviewCollection(snapshot, options.hubOrigin) + const review = createHubReviewCollection( + snapshot, + options.hubOrigin, + store.repositoryScope, + ) if (!trainingGrantIds.length) { return { bytes: new Uint8Array(), @@ -1254,10 +1331,7 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource "questions", "--by", `human:${actorMembershipId}`, - "--dir", - store.directory, - "--repository", - store.repositoryScope, + ...learningStoreArguments(store), ]), ) if (!questionResult.success) { diff --git a/hub/server/domains/decision-model/prepare-decision-taskset/index.ts b/hub/server/domains/decision-model/prepare-decision-taskset/index.ts index 273da8bb3..d333f3005 100644 --- a/hub/server/domains/decision-model/prepare-decision-taskset/index.ts +++ b/hub/server/domains/decision-model/prepare-decision-taskset/index.ts @@ -1,7 +1,11 @@ import { createHash } from "node:crypto" import { DecisionModelError } from "../errors.ts" -import type { DecisionTrainingPreflight, PreparedDecisionTaskset } from "../types.ts" +import type { + DecisionTrainingPreflight, + DecisionTrainingWithdrawalDiscovery, + PreparedDecisionTaskset, +} from "../types.ts" export interface DecisionTasksetPreparationSource { preflight(input: { @@ -14,21 +18,7 @@ export interface DecisionTasksetPreparationSource { consentGrantId: string }): Promise getAcceptedLearningTexts(repositoryId: string): Promise> - listTrainingWithdrawals(): Promise< - { - repositoryId: string - actorMembershipId: string - actorLogin: string - selectors: { - exportId?: string - grantId?: string - evidenceDigest?: string - tasksetDigest?: string - } - reason: string - idempotencyKey: string - }[] - > + listTrainingWithdrawals(): Promise exportTrainingEvidence(input: { repositoryId: string; actorMembershipId: string }): Promise<{ bytes: Uint8Array consentGrantId: string | null diff --git a/hub/server/domains/decision-model/types.ts b/hub/server/domains/decision-model/types.ts index b3af78b55..a92d3c00b 100644 --- a/hub/server/domains/decision-model/types.ts +++ b/hub/server/domains/decision-model/types.ts @@ -285,6 +285,18 @@ export interface DecisionModelStore { > } +export interface DecisionTrainingWithdrawalDiscovery { + withdrawals: { + repositoryId: string + actorMembershipId: string + actorLogin: string + selectors: DecisionRuntimeDeletionSelectors + reason: string + idempotencyKey: string + }[] + failedRepositoryIds: string[] +} + export interface DecisionModelDependencies { authorization: DecisionModelAuthorization now(): Date @@ -310,16 +322,7 @@ export interface DecisionModelDependencies { runtimeForRepository?: (repositoryId: string) => DecisionRuntimeClient store: DecisionModelStore withControlLock(operation: (signal: AbortSignal) => Promise): Promise - listTrainingWithdrawals?(): Promise< - { - repositoryId: string - actorMembershipId: string - actorLogin: string - selectors: DecisionRuntimeDeletionSelectors - reason: string - idempotencyKey: string - }[] - > + listTrainingWithdrawals?(): Promise } export interface AgentEvaluationScreenshot { diff --git a/hub/server/domains/learning/create-hub-review-collection/index.test.ts b/hub/server/domains/learning/create-hub-review-collection/index.test.ts index bc18e2ccc..b76e30dc7 100644 --- a/hub/server/domains/learning/create-hub-review-collection/index.test.ts +++ b/hub/server/domains/learning/create-hub-review-collection/index.test.ts @@ -4,6 +4,7 @@ import type { RepositoryReviewSnapshot } from "../../review-comments/types" import { createHubReviewCollection } from "." const repositoryId = "11111111-2222-4333-8444-555555555555" +const repositoryScope = "github.com/repositories/123" const prototypeId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa" const author = { userId: "22222222-2222-4222-8222-222222222222", @@ -81,7 +82,7 @@ function snapshot(): RepositoryReviewSnapshot { describe("createHubReviewCollection()", () => { it("writes a complete v1 log with UUID identities, deleted comments, and resolution history", () => { - const result = createHubReviewCollection(snapshot(), "https://hub.example.com") + const result = createHubReviewCollection(snapshot(), "https://hub.example.com", repositoryScope) const call = result.collection.calls[0] if (!call) throw new Error("Expected one collection call.") const thread = call.result.threads[0] @@ -125,8 +126,15 @@ describe("createHubReviewCollection()", () => { laterCapture.capturedAt = new Date("2026-11-13T10:06:00Z") laterCapture.threads[0]!.updatedAt = new Date("2026-11-13T10:06:00Z") laterCapture.threads[0]!.root.updatedAt = new Date("2026-11-13T10:06:00Z") - expect(createHubReviewCollection(laterCapture, "https://hub.example.com").digest).toBe( - result.digest, + expect( + createHubReviewCollection(laterCapture, "https://hub.example.com", repositoryScope).digest, + ).toBe(result.digest) + const otherScope = createHubReviewCollection( + laterCapture, + "https://hub.example.com", + "github.com/repositories/456", ) + expect(otherScope.digest).not.toBe(result.digest) + expect(otherScope.legacyDigest).toBe(result.legacyDigest) }) }) diff --git a/hub/server/domains/learning/create-hub-review-collection/index.ts b/hub/server/domains/learning/create-hub-review-collection/index.ts index bcdc9b1fb..c6f2d7097 100644 --- a/hub/server/domains/learning/create-hub-review-collection/index.ts +++ b/hub/server/domains/learning/create-hub-review-collection/index.ts @@ -77,7 +77,14 @@ function reviewState(snapshot: RepositoryReviewSnapshot) { } } -export function createHubReviewCollection(snapshot: RepositoryReviewSnapshot, hubOrigin: string) { +export function createHubReviewCollection( + snapshot: RepositoryReviewSnapshot, + hubOrigin: string, + repositoryScope: string, +) { + if (!/^github\.com\/repositories\/[1-9][0-9]*$/.test(repositoryScope)) { + throw new Error("The repository learning scope must contain a GitHub repository ID.") + } const target = { hubOrigin, repository: `repositories/${snapshot.repository.id}`, @@ -126,10 +133,14 @@ export function createHubReviewCollection(snapshot: RepositoryReviewSnapshot, hu }, ], } + const legacyDigest = `sha256:${createHash("sha256") + .update(JSON.stringify(reviewState(snapshot))) + .digest("hex")}` as const return { collection, digest: `sha256:${createHash("sha256") - .update(JSON.stringify(reviewState(snapshot))) + .update(JSON.stringify({ repositoryScope, review: reviewState(snapshot) })) .digest("hex")}` as const, + legacyDigest, } } diff --git a/hub/server/domains/learning/create-learning-job-processors/index.test.ts b/hub/server/domains/learning/create-learning-job-processors/index.test.ts index 9da010d95..e71feda6f 100644 --- a/hub/server/domains/learning/create-learning-job-processors/index.test.ts +++ b/hub/server/domains/learning/create-learning-job-processors/index.test.ts @@ -1,16 +1,67 @@ +import { randomUUID } from "node:crypto" +import { chmod, copyFile, mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises" +import { join, resolve } from "node:path" +import { DatabaseSync } from "node:sqlite" + import { describe, expect, it, vi } from "vitest" +import { enqueueRecoverableJob } from "../../../integrations/bullmq/enqueue-recoverable-job" +import * as learningCommand from "../../../integrations/learning/run-learning-command" import { deleteExpiredLearningRuns } from "../../../repositories/learning-runs/delete-expired-learning-runs" +import { redactReviewCommentJob } from "../jobs/redact-review-comment" import { createLearningJobProcessors } from "." -const prisma = { learningRun: {} } +const prisma = { + learningRun: { findMany: vi.fn() }, + learningDecisionOperation: { findMany: vi.fn() }, + repository: { findUnique: vi.fn() }, + reviewComment: { findMany: vi.fn(), updateMany: vi.fn() }, +} vi.mock("../../../integrations/prisma", () => ({ prisma })) vi.mock("../../../repositories/learning-runs/delete-expired-learning-runs", () => ({ deleteExpiredLearningRuns: vi.fn().mockResolvedValue(undefined), })) +vi.mock("../../../integrations/postgres/with-learning-execution-lock", () => ({ + withLearningExecutionLock: ({ run }: { run: (signal: AbortSignal) => Promise }) => + run(new AbortController().signal), +})) +vi.mock("../../../integrations/bullmq/create-job-queue", () => ({ + createJobQueue: vi.fn(() => ({ close: vi.fn() })), +})) +vi.mock("../../../integrations/bullmq/enqueue-recoverable-job", () => ({ + enqueueRecoverableJob: vi.fn(), +})) describe("createLearningJobProcessors()", () => { + it("redacts database comments without creating a local store", async () => { + const root = resolve(`server/domains/learning/.redaction-worker-${randomUUID()}`) + const repositoryId = "11111111-2222-4333-8444-555555555555" + const learningDatabaseUrl = "postgresql://learning.example/replica" + const command = vi.spyOn(learningCommand, "runLearningCommand").mockResolvedValue({}) + prisma.repository.findUnique.mockResolvedValue({ githubRepositoryId: 123n }) + prisma.reviewComment.updateMany.mockResolvedValue({ count: 1 }) + const processors = createLearningJobProcessors( + { + DATABASE_URL: "postgresql://unused.example/replica", + HUB_APPLICATION_ORIGIN: "https://hub.example.com", + REPLICA_LEARNING_DATABASE_URL: learningDatabaseUrl, + REPLICA_LEARNING_ROOT: root, + }, + {} as never, + ) + + await processors.redact.process({ repositoryId, commentId: 101, actor: "human:mona" }) + + expect(command).toHaveBeenCalledOnce() + const [arguments_, options] = command.mock.calls[0]! + expect(arguments_).toEqual(expect.arrayContaining(["redact", "--comment", "101"])) + expect(arguments_).not.toContain(learningDatabaseUrl) + expect(options).toMatchObject({ learningDatabaseUrl }) + expect(prisma.reviewComment.updateMany).toHaveBeenCalledOnce() + await expect(stat(root)).rejects.toMatchObject({ code: "ENOENT" }) + }) + it("prunes run history without initializing learning or Copilot when scheduling is disabled", async () => { const processors = createLearningJobProcessors( { @@ -27,4 +78,131 @@ describe("createLearningJobProcessors()", () => { expect(deleteExpiredLearningRuns).toHaveBeenCalledOnce() expect(deleteExpiredLearningRuns).toHaveBeenCalledWith(prisma, expect.any(Date)) }) + + it("recovers a failed redaction in the ID-less repository's own store", async () => { + await mkdir(resolve(".local"), { recursive: true }) + const root = await mkdtemp(resolve(".local/redaction-worker-")) + const repositoryId = "11111111-2222-4333-8444-555555555555" + const directory = join(root, "repositories", repositoryId) + await mkdir(directory, { recursive: true, mode: 0o700 }) + await copyFile( + resolve("../packages/learning/test/fixtures/legacy-hub-scope.sqlite"), + join(directory, "learning.sqlite"), + ) + await chmod(join(directory, "learning.sqlite"), 0o600) + await writeFile(join(directory, "config.json"), "{", { mode: 0o600 }) + try { + prisma.repository.findUnique.mockResolvedValue({ githubRepositoryId: null }) + prisma.reviewComment.updateMany.mockResolvedValue({ count: 1 }) + const processors = createLearningJobProcessors( + { + DATABASE_URL: "postgresql://unused.example/replica", + HUB_APPLICATION_ORIGIN: "https://hub.example.com", + REPLICA_LEARNING_ROOT: root, + }, + {} as never, + ) + const request = { repositoryId, commentId: 101, actor: "human:mona" } + await expect(processors.redact.process(request)).rejects.toThrow() + expect(prisma.reviewComment.updateMany).not.toHaveBeenCalled() + + await writeFile( + join(directory, "config.json"), + JSON.stringify({ schemaVersion: "replica.learning-config/v1" }), + ) + prisma.learningRun.findMany.mockResolvedValue([]) + prisma.learningDecisionOperation.findMany.mockResolvedValue([]) + prisma.reviewComment.findMany.mockResolvedValue([ + { + publicId: 101, + id: "22222222-2222-4222-8222-222222222222", + deletedAt: new Date("2026-11-13T10:00:00Z"), + authorLogin: "mona", + learningRedactionActor: "human:mona", + thread: { repositoryId }, + }, + ]) + await processors.recover.process({}) + expect(enqueueRecoverableJob).toHaveBeenCalledWith( + expect.anything(), + redactReviewCommentJob, + request, + `learning-redact-${repositoryId}-101`, + ) + await processors.redact.process(request) + + const db = new DatabaseSync(join(directory, "learning.sqlite"), { readOnly: true }) + try { + const events = db.prepare("select body from records where stream = 'events'").all() + expect( + events.some( + (row) => + (JSON.parse(String(row.body)) as { redaction?: { commentId?: number } }).redaction + ?.commentId === 101, + ), + ).toBe(true) + } finally { + db.close() + } + expect(prisma.reviewComment.updateMany).toHaveBeenCalledOnce() + } finally { + await rm(root, { force: true, recursive: true }) + } + }) + + it("uses the repository ID from one lookup for an ID-backed redaction", async () => { + await mkdir(resolve(".local"), { recursive: true }) + const root = await mkdtemp(resolve(".local/redaction-worker-")) + const repositoryId = "11111111-2222-4333-8444-555555555555" + const directory = join(root, "repositories", repositoryId) + await mkdir(directory, { recursive: true, mode: 0o700 }) + await copyFile( + resolve("../packages/learning/test/fixtures/legacy-hub-scope.sqlite"), + join(directory, "learning.sqlite"), + ) + await chmod(join(directory, "learning.sqlite"), 0o600) + await writeFile( + join(directory, "config.json"), + JSON.stringify({ schemaVersion: "replica.learning-config/v1" }), + { mode: 0o600 }, + ) + try { + prisma.repository.findUnique + .mockResolvedValueOnce({ githubRepositoryId: 9007199254740993n }) + .mockResolvedValueOnce({ githubRepositoryId: 2n }) + prisma.reviewComment.updateMany.mockResolvedValue({ count: 1 }) + const processors = createLearningJobProcessors( + { + DATABASE_URL: "postgresql://unused.example/replica", + HUB_APPLICATION_ORIGIN: "https://hub.example.com", + REPLICA_LEARNING_ROOT: root, + }, + {} as never, + ) + + await processors.redact.process({ repositoryId, commentId: 101, actor: "human:mona" }) + + expect(prisma.repository.findUnique).toHaveBeenCalledOnce() + const db = new DatabaseSync(join(directory, "learning.sqlite"), { readOnly: true }) + try { + const events = db + .prepare("select scope_key, body from records where stream = 'events'") + .all() + expect( + events.some( + (row) => + row.scope_key === + '{"host":"github.com","repository":"repositories/9007199254740993"}' && + (JSON.parse(String(row.body)) as { redaction?: { commentId?: number } }).redaction + ?.commentId === 101, + ), + ).toBe(true) + } finally { + db.close() + } + expect(prisma.reviewComment.updateMany).toHaveBeenCalledOnce() + } finally { + await rm(root, { force: true, recursive: true }) + } + }) }) diff --git a/hub/server/domains/learning/create-learning-job-processors/index.ts b/hub/server/domains/learning/create-learning-job-processors/index.ts index 046ab3209..37b93378d 100644 --- a/hub/server/domains/learning/create-learning-job-processors/index.ts +++ b/hub/server/domains/learning/create-learning-job-processors/index.ts @@ -6,6 +6,7 @@ import { getCopilotConnectionStatus } from "../../copilot-connection/get-copilot import { ReviewCommentError } from "../../review-comments/errors.ts" import { authorizeRepositoryAdministration } from "../authorize-repository-administration/index.ts" import { createReviewCommentLearningSource } from "../create-review-comment-learning-source/index.ts" +import { getLearningRepositoryScope } from "../get-learning-repository-scope/index.ts" import { learningRunJob } from "../jobs/learning-run.ts" import { automaticLearningRunPriority } from "../jobs/priorities.ts" import { recoverLearningRunsJob } from "../jobs/recover-learning-runs.ts" @@ -14,6 +15,7 @@ import { scheduleLearningRunsJob } from "../jobs/schedule-learning-runs.ts" import { prepareLearningStore } from "../prepare-learning-store/index.ts" import { processLearningRun } from "../process-learning-run/index.ts" import { processReviewCommentRedaction } from "../process-review-comment-redaction/index.ts" +import { redactLegacyReviewComment } from "../redact-legacy-review-comment/index.ts" import { recoverLearningRunJobs } from "../recover-learning-run-jobs/index.ts" import { reconcileLearningDecisionOperation } from "../reconcile-learning-decision-operation/index.ts" import { readAutomaticLearningRunsEnabled } from "../read-automatic-learning-runs-enabled/index.ts" @@ -49,6 +51,7 @@ import { isEffectiveAdministrator } from "../../../repositories/memberships/is-e import { lockGitHubRepositoryAccessState } from "../../../repositories/github-repository-access-states/lock-github-repository-access-state/index.ts" import { listDeletedReviewComments } from "../../../repositories/review-comments/list-deleted-review-comments/index.ts" import { markReviewCommentLearningRedacted } from "../../../repositories/review-comments/mark-review-comment-learning-redacted/index.ts" +import { findRepositoryGitHubId } from "../../../repositories/repository-access/find-repository-github-id/index.ts" import { createSecurityAudit } from "../../../repositories/security-audits/create-security-audit/index.ts" export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logger: Logger) { @@ -142,21 +145,18 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg hasPendingUserRun: () => hasPendingUserLearningRun(prisma), isRepositoryAvailable: (repositoryId) => prisma.$transaction(async (transaction) => { - const access = await lockGitHubRepositoryAccessState(transaction) - return isLearningRunRepositoryAvailable( - transaction, - repositoryId, - access.scopingActivatedAt !== null, - ) + await lockGitHubRepositoryAccessState(transaction) + return isLearningRunRepositoryAvailable(transaction, repositoryId, true) }), now: () => new Date(), authorizeRepositoryAdministration: (membershipId, repositoryId) => authorizeRepositoryAdministration(prisma, { membershipId, repositoryId }), - prepare: (repositoryId) => + prepare: async (repositoryId) => prepareLearningStore({ applicationRoot: process.cwd(), + learningDatabaseUrl: configuration.learningDatabaseUrl, repositoryKey: repositoryId, - repositoryScope: `github.com/repositories/${repositoryId}`, + repositoryScope: await getLearningRepositoryScope(prisma, repositoryId), root: configuration.root, staticDirectories: configuration.staticDirectories, }), @@ -200,6 +200,7 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg runCommand: (arguments_, options) => runLearningCommand(arguments_, { cliPath: configuration.cliPath, + learningDatabaseUrl: configuration.learningDatabaseUrl, nodePath: configuration.nodePath, ...options, }), @@ -324,17 +325,19 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg repositoryId: operation.repositoryId, }) }), - prepare: (repositoryId) => + prepare: async (repositoryId) => prepareLearningStore({ applicationRoot: process.cwd(), + learningDatabaseUrl: configuration.learningDatabaseUrl, repositoryKey: repositoryId, - repositoryScope: `github.com/repositories/${repositoryId}`, + repositoryScope: await getLearningRepositoryScope(prisma, repositoryId), root: configuration.root, staticDirectories: configuration.staticDirectories, }), runCommand: (arguments_, options) => runLearningCommand(arguments_, { cliPath: configuration.cliPath, + learningDatabaseUrl: configuration.learningDatabaseUrl, nodePath: configuration.nodePath, ...options, }), @@ -375,9 +378,9 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg deleteExpired: (cutoff) => deleteExpiredLearningRuns(prisma, cutoff), listDue: () => prisma.$transaction(async (transaction) => { - const access = await lockGitHubRepositoryAccessState(transaction) + await lockGitHubRepositoryAccessState(transaction) return listDueLearningRepositories(transaction, { - requireGitHubId: access.scopingActivatedAt !== null, + requireGitHubId: true, }) }), capture: async (repositoryId) => { @@ -390,14 +393,8 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg }, create: (input) => prisma.$transaction(async (transaction) => { - const access = await lockGitHubRepositoryAccessState(transaction) - if ( - !(await isLearningRunRepositoryAvailable( - transaction, - input.repositoryId, - access.scopingActivatedAt !== null, - )) - ) { + await lockGitHubRepositoryAccessState(transaction) + if (!(await isLearningRunRepositoryAvailable(transaction, input.repositoryId, true))) { return null } return createLearningRun(transaction, input) @@ -430,20 +427,30 @@ export function createLearningJobProcessors(environment: NodeJS.ProcessEnv, logg const redact = createJobProcessor(redactReviewCommentJob, async (input) => { const { configuration, databaseUrl, prisma } = await dependencies() await processReviewCommentRedaction(input, { + learningDatabaseUrl: configuration.learningDatabaseUrl, root: configuration.root, markComplete: (completed) => markReviewCommentLearningRedacted(prisma, completed), now: () => new Date(), - prepare: (repositoryId) => - prepareLearningStore({ + prepare: async (repositoryId) => { + const repository = await findRepositoryGitHubId(prisma, repositoryId) + if (!repository) throw new Error("The repository for learning redaction no longer exists.") + if (repository.githubRepositoryId == null || repository.githubRepositoryId <= 0n) + return null + return await prepareLearningStore({ applicationRoot: process.cwd(), + learningDatabaseUrl: configuration.learningDatabaseUrl, repositoryKey: repositoryId, - repositoryScope: `github.com/repositories/${repositoryId}`, + repositoryScope: `github.com/repositories/${repository.githubRepositoryId}`, root: configuration.root, staticDirectories: configuration.staticDirectories, - }), + }) + }, + redactLegacy: (request, options) => + redactLegacyReviewComment(request, { ...configuration, ...options }), runCommand: (arguments_, options) => runLearningCommand(arguments_, { cliPath: configuration.cliPath, + learningDatabaseUrl: configuration.learningDatabaseUrl, nodePath: configuration.nodePath, ...options, }), diff --git a/hub/server/domains/learning/create-review-comment-learning-source/index.test.ts b/hub/server/domains/learning/create-review-comment-learning-source/index.test.ts index 4a8c080f2..be09eb047 100644 --- a/hub/server/domains/learning/create-review-comment-learning-source/index.test.ts +++ b/hub/server/domains/learning/create-review-comment-learning-source/index.test.ts @@ -73,7 +73,14 @@ describe("createReviewCommentLearningSource()", () => { deletedAt: capturedAt, } capture.mockResolvedValue(value) - const source = createReviewCommentLearningSource({} as never, "https://hub.example.com") + const source = createReviewCommentLearningSource( + { + repository: { + findUnique: vi.fn().mockResolvedValue({ githubRepositoryId: 9007199254740993n }), + }, + } as never, + "https://hub.example.com", + ) const result = await source.captureCompleteSnapshot({ repositoryId }) const collection = result.collection as { @@ -89,6 +96,40 @@ describe("createReviewCommentLearningSource()", () => { expect(result.reviewActivitySnapshot).toEqual({ "77777777-7777-4777-8777-777777777777": 1, }) + expect(result.repositoryScope).toBe("github.com/repositories/9007199254740993") + }) + + it("does not capture review evidence without a GitHub repository ID", async () => { + const source = createReviewCommentLearningSource( + { + repository: { findUnique: vi.fn().mockResolvedValue({ githubRepositoryId: null }) }, + } as never, + "https://hub.example.com", + ) + + await expect(source.captureCompleteSnapshot({ repositoryId })).rejects.toMatchObject({ + code: "repository_scope_unavailable", + }) + expect(capture).not.toHaveBeenCalled() + }) + + it("does not return a snapshot when the repository scope changes during capture", async () => { + capture.mockResolvedValue(snapshot()) + const source = createReviewCommentLearningSource( + { + repository: { + findUnique: vi + .fn() + .mockResolvedValueOnce({ githubRepositoryId: 123n }) + .mockResolvedValueOnce({ githubRepositoryId: 456n }), + }, + } as never, + "https://hub.example.com", + ) + + await expect(source.captureCompleteSnapshot({ repositoryId })).rejects.toThrow( + "The repository learning scope changed during review capture.", + ) }) it("resolves only evidence whose source and observed comment version match", async () => { diff --git a/hub/server/domains/learning/create-review-comment-learning-source/index.ts b/hub/server/domains/learning/create-review-comment-learning-source/index.ts index a4655f727..9d072494d 100644 --- a/hub/server/domains/learning/create-review-comment-learning-source/index.ts +++ b/hub/server/domains/learning/create-review-comment-learning-source/index.ts @@ -1,6 +1,7 @@ import type { PrismaClient } from "../../../generated/prisma/client.ts" import { captureRepositoryReviewSnapshot } from "../../review-comments/capture-repository-review-snapshot/index.ts" import { createHubReviewCollection } from "../create-hub-review-collection/index.ts" +import { getLearningRepositoryScope } from "../get-learning-repository-scope/index.ts" import type { LearningObservationEvent, ReviewCommentLearningSource, @@ -11,16 +12,26 @@ function eventMap(events: LearningObservationEvent[]) { } export function createReviewCommentLearningSource( - database: Pick, + database: Pick, hubOrigin: string, ): ReviewCommentLearningSource { return { async captureCompleteSnapshot({ repositoryId }) { + const repositoryScope = await getLearningRepositoryScope(database, repositoryId) const snapshot = await captureRepositoryReviewSnapshot(database, repositoryId) - const { collection, digest } = createHubReviewCollection(snapshot, hubOrigin) + if (repositoryScope !== (await getLearningRepositoryScope(database, repositoryId))) { + throw new Error("The repository learning scope changed during review capture.") + } + const { collection, digest, legacyDigest } = createHubReviewCollection( + snapshot, + hubOrigin, + repositoryScope, + ) return { collection, digest, + legacyDigest, + repositoryScope, capturedAt: snapshot.capturedAt, reviewActivitySnapshot: Object.fromEntries( snapshot.threads.map((thread) => [thread.storageId, thread.activityVersion]), diff --git a/hub/server/domains/learning/execute-learning-decision/index.test.ts b/hub/server/domains/learning/execute-learning-decision/index.test.ts index 0ca723e66..9f7bb4886 100644 --- a/hub/server/domains/learning/execute-learning-decision/index.test.ts +++ b/hub/server/domains/learning/execute-learning-decision/index.test.ts @@ -1,6 +1,7 @@ -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises" +import { randomUUID } from "node:crypto" +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" -import { join } from "node:path" +import { join, resolve } from "node:path" import { describe, expect, it, vi } from "vitest" import { runLearningCommand } from "../../../integrations/learning/run-learning-command" @@ -15,6 +16,35 @@ vi.mock("../../../utils/validate-private-storage-root", () => ({ })) describe("executeLearningDecision()", () => { + it("accepts a database learning without creating a local store", async () => { + const directory = resolve(`server/domains/learning/.decision-test-${randomUUID()}`) + const learningDatabaseUrl = "postgresql://learning.example/replica" + vi.mocked(validatePrivateStorageRoot).mockResolvedValue(directory) + vi.mocked(runLearningCommand).mockResolvedValue({}) + + const result = await executeLearningDecision({ + actor: "human:mona", + applicationRoot: "/app", + cliPath: "/app/replica-learning.mjs", + decision: { decision: "accept", digest: `sha256:${"a".repeat(64)}` }, + learningDatabaseUrl, + learningId: "mem_1", + nodePath: "/node", + operationId: "22222222-2222-4222-8222-222222222222", + repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", + root: "/private/learning", + staticDirectories: [], + }) + + expect(result.notice).toBe("Learning accepted.") + const [arguments_, options] = vi.mocked(runLearningCommand).mock.calls[0]! + expect(arguments_).toEqual(expect.arrayContaining(["accept", "mem_1"])) + expect(arguments_).not.toContain(learningDatabaseUrl) + expect(options).toMatchObject({ learningDatabaseUrl }) + await expect(stat(directory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + it("passes a dash-leading reason through a private file instead of process arguments", async () => { const directory = await mkdtemp(join(tmpdir(), "replica-learning-decision-test-")) try { @@ -22,6 +52,14 @@ describe("executeLearningDecision()", () => { vi.mocked(validatePrivateStorageRoot).mockResolvedValue(directory) vi.mocked(runLearningCommand).mockImplementation(async (arguments_) => { expect(arguments_).not.toContain("-private repository context") + expect(arguments_).toEqual( + expect.arrayContaining([ + "--repository", + "github.com/repositories/123", + "--legacy-repository", + "github.com/repositories/11111111-2222-4333-8444-555555555555", + ]), + ) const index = arguments_.indexOf("--reason-file") expect(index).toBeGreaterThan(-1) const path = arguments_[index + 1] @@ -40,6 +78,7 @@ describe("executeLearningDecision()", () => { nodePath: "/node", operationId: "22222222-2222-4222-8222-222222222222", repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", root: "/private/learning", staticDirectories: [], }), @@ -64,6 +103,7 @@ describe("executeLearningDecision()", () => { nodePath: "/node", operationId: "22222222-2222-4222-8222-222222222222", repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", root: "/private/learning", staticDirectories: [], }), diff --git a/hub/server/domains/learning/execute-learning-decision/index.ts b/hub/server/domains/learning/execute-learning-decision/index.ts index 02bf035ba..86d029113 100644 --- a/hub/server/domains/learning/execute-learning-decision/index.ts +++ b/hub/server/domains/learning/execute-learning-decision/index.ts @@ -5,6 +5,7 @@ import { resolve } from "node:path" import { runLearningCommand } from "../../../integrations/learning/run-learning-command/index.ts" import { validatePrivateStorageRoot } from "../../../utils/validate-private-storage-root/index.ts" import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" +import { learningStoreArguments } from "../learning-store-arguments/index.ts" import type { LearningDecision } from "../types.ts" export async function executeLearningDecision(input: { @@ -13,9 +14,11 @@ export async function executeLearningDecision(input: { cliPath: string decision: LearningDecision learningId: string + learningDatabaseUrl?: string nodePath: string operationId: string repositoryId: string + repositoryScope: string root: string signal?: AbortSignal staticDirectories: string[] @@ -30,11 +33,13 @@ export async function executeLearningDecision(input: { publicRoot: resolve(applicationRoot, "public"), }, ) - try { - await access(resolve(directory, "config.json")) - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error - throw new LearningCommandError("not_found", "That learning no longer exists.") + if (!input.learningDatabaseUrl) { + try { + await access(resolve(directory, "config.json")) + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + throw new LearningCommandError("not_found", "That learning no longer exists.") + } } const arguments_ = [input.decision.decision, input.learningId] arguments_.push("--operation-id", input.operationId) @@ -59,13 +64,15 @@ export async function executeLearningDecision(input: { await runLearningCommand( [ ...arguments_, - "--dir", - directory, - "--repository", - `github.com/repositories/${input.repositoryId}`, + ...learningStoreArguments({ + directory, + repositoryId: input.repositoryId, + repositoryScope: input.repositoryScope, + }), ], { cliPath: input.cliPath, + ...(input.learningDatabaseUrl ? { learningDatabaseUrl: input.learningDatabaseUrl } : {}), nodePath: input.nodePath, signal: input.signal, }, diff --git a/hub/server/domains/learning/get-learning-overview/index.test.ts b/hub/server/domains/learning/get-learning-overview/index.test.ts index 38a496784..297baa0e2 100644 --- a/hub/server/domains/learning/get-learning-overview/index.test.ts +++ b/hub/server/domains/learning/get-learning-overview/index.test.ts @@ -19,6 +19,52 @@ describe("getLearningOverview()", () => { vi.mocked(access).mockResolvedValue(undefined) }) + it("reads database learnings without a local configuration", async () => { + vi.mocked(access).mockRejectedValue(Object.assign(new Error("missing"), { code: "ENOENT" })) + vi.mocked(runLearningCommand) + .mockResolvedValueOnce([]) + .mockResolvedValueOnce({}) + .mockResolvedValueOnce({ text: "Useful guidance", memories: [] }) + const learningDatabaseUrl = "postgresql://learning.example/replica" + + const result = await getLearningOverview({ + applicationRoot: "/app", + cliPath: "/app/replica-learning.mjs", + learningDatabaseUrl, + nodePath: "/node", + repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", + root: "/private/learning", + staticDirectories: [], + viewer: "human:mona", + }) + + expect(result.recall.text).toBe("Useful guidance") + expect(runLearningCommand).toHaveBeenCalledTimes(3) + for (const [arguments_, options] of vi.mocked(runLearningCommand).mock.calls) { + expect(arguments_).not.toContain(learningDatabaseUrl) + expect(options).toMatchObject({ learningDatabaseUrl }) + } + }) + + it("returns an empty overview for a missing local store", async () => { + vi.mocked(access).mockRejectedValue(Object.assign(new Error("missing"), { code: "ENOENT" })) + + const result = await getLearningOverview({ + applicationRoot: "/app", + cliPath: "/app/replica-learning.mjs", + nodePath: "/node", + repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", + root: "/private/learning", + staticDirectories: [], + viewer: "human:mona", + }) + + expect(result.suggestions).toEqual([]) + expect(runLearningCommand).not.toHaveBeenCalled() + }) + it("uses only the review source's exact event resolution for displayed evidence", async () => { vi.mocked(runLearningCommand) .mockResolvedValueOnce([ @@ -56,6 +102,7 @@ describe("getLearningOverview()", () => { }, }, ]) + .mockResolvedValueOnce({}) .mockResolvedValueOnce({ text: "", memories: [] }) .mockResolvedValueOnce({ events: [ @@ -91,6 +138,7 @@ describe("getLearningOverview()", () => { evidenceSource: { resolveEvidence }, nodePath: "/node", repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", root: "/private/learning", staticDirectories: [], viewer: "github:mona", @@ -137,6 +185,16 @@ describe("getLearningOverview()", () => { }, ]) expect(result.suggestions[0]?.otherEvidenceCount).toBe(1) + for (const [arguments_] of vi.mocked(runLearningCommand).mock.calls) { + expect(arguments_).toEqual( + expect.arrayContaining([ + "--repository", + "github.com/repositories/123", + "--legacy-repository", + "github.com/repositories/11111111-2222-4333-8444-555555555555", + ]), + ) + } }) it("propagates an inaccessible store instead of reporting an empty overview", async () => { @@ -148,6 +206,7 @@ describe("getLearningOverview()", () => { cliPath: "/app/replica-learning.mjs", nodePath: "/node", repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", root: "/private/learning", staticDirectories: [], viewer: "human:mona", @@ -155,6 +214,60 @@ describe("getLearningOverview()", () => { ).rejects.toMatchObject({ code: "EACCES" }) }) + it("returns migration redaction follow-ups again when the overview reloads", async () => { + const learningId = "mem_111111111111111111111111" + const exportId = "exp_222222222222222222222222" + const destination = "private/exports/team.json" + const followUps = { + memoriesNeedingRebuild: [learningId], + exportsToFollowUp: [ + { + id: exportId, + purpose: "instruction", + destination, + }, + ], + } + vi.mocked(runLearningCommand).mockImplementation((arguments_) => { + if (arguments_[0] === "memories") return Promise.resolve([]) + if (arguments_[0] === "recall") return Promise.resolve({ text: "", memories: [] }) + if (arguments_[0] === "status") + return Promise.resolve({ migrationRedactionFollowUps: followUps }) + throw new Error(`Unexpected learning command: ${arguments_[0]}`) + }) + const input = { + applicationRoot: "/app", + cliPath: "/app/replica-learning.mjs", + nodePath: "/node", + repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", + root: "/private/learning", + staticDirectories: [], + viewer: "human:mona", + } + + const first = await getLearningOverview(input) + const reloaded = await getLearningOverview(input) + for (const result of [first, reloaded]) { + expect(result.loadError).toContain(learningId) + expect(result.loadError).toContain(exportId) + expect(result.loadError).toContain(destination) + } + const statusCalls = vi + .mocked(runLearningCommand) + .mock.calls.filter(([arguments_]) => arguments_[0] === "status") + expect(statusCalls).toHaveLength(2) + for (const [arguments_] of statusCalls) + expect(arguments_).toEqual( + expect.arrayContaining([ + "--repository", + "github.com/repositories/123", + "--legacy-repository", + "github.com/repositories/11111111-2222-4333-8444-555555555555", + ]), + ) + }) + it("loads observations and the repository snapshot once for all suggestions", async () => { function proposal(id: string, eventId: string, commentId: number) { return { @@ -184,6 +297,7 @@ describe("getLearningOverview()", () => { const memories = [proposal("mem_1", "event-1", 17), proposal("mem_2", "event-2", 18)] vi.mocked(runLearningCommand) .mockResolvedValueOnce(memories) + .mockResolvedValueOnce({}) .mockResolvedValueOnce({ text: "", memories: [] }) .mockResolvedValueOnce({ events: [ @@ -209,12 +323,13 @@ describe("getLearningOverview()", () => { evidenceSource: { resolveEvidence }, nodePath: "/node", repositoryId: "11111111-2222-4333-8444-555555555555", + repositoryScope: "github.com/repositories/123", root: "/private/learning", staticDirectories: [], viewer: "human:mona", }) expect(resolveEvidence).toHaveBeenCalledOnce() - expect(vi.mocked(runLearningCommand)).toHaveBeenCalledTimes(3) + expect(vi.mocked(runLearningCommand)).toHaveBeenCalledTimes(4) }) }) diff --git a/hub/server/domains/learning/get-learning-overview/index.ts b/hub/server/domains/learning/get-learning-overview/index.ts index f02c000c9..6067e4858 100644 --- a/hub/server/domains/learning/get-learning-overview/index.ts +++ b/hub/server/domains/learning/get-learning-overview/index.ts @@ -5,6 +5,7 @@ import { z } from "zod" import { runLearningCommand } from "../../../integrations/learning/run-learning-command/index.ts" import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" import { validatePrivateStorageRoot } from "../../../utils/validate-private-storage-root/index.ts" +import { learningStoreArguments } from "../learning-store-arguments/index.ts" import type { ReviewCommentLearningSource } from "../review-comment-learning-source/types.ts" import type { AcceptedLearning, LearningSuggestion } from "../types.ts" @@ -78,6 +79,18 @@ const recallSchema = z memories: z.array(z.object({ id: z.string() }).loose()), }) .loose() +const statusSchema = z + .object({ + migrationRedactionFollowUps: z + .object({ + memoriesNeedingRebuild: z.array(z.string().min(1)), + exportsToFollowUp: z.array( + z.object({ id: z.string().min(1), destination: z.string().min(1) }).loose(), + ), + }) + .optional(), + }) + .loose() const observationsSchema = z .object({ events: z.array( @@ -106,8 +119,10 @@ export async function getLearningOverview(input: { applicationRoot?: string cliPath: string evidenceSource?: Pick + learningDatabaseUrl?: string nodePath: string repositoryId: string + repositoryScope: string root: string staticDirectories: string[] viewer: string @@ -122,33 +137,38 @@ export async function getLearningOverview(input: { publicRoot: resolve(applicationRoot, "public"), }, ) - try { - await access(resolve(directory, "config.json")) - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error - return { - loadError: null, - identityReviewCount: 0, - suggestions: [], - learnings: [], - recall: { text: "", count: 0 }, + if (!input.learningDatabaseUrl) { + try { + await access(resolve(directory, "config.json")) + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + return { + loadError: null, + identityReviewCount: 0, + suggestions: [], + learnings: [], + recall: { text: "", count: 0 }, + } } } - const commandOptions = { cliPath: input.cliPath, nodePath: input.nodePath } - const commonArguments = [ - "--dir", + const commandOptions = { + cliPath: input.cliPath, + nodePath: input.nodePath, + ...(input.learningDatabaseUrl ? { learningDatabaseUrl: input.learningDatabaseUrl } : {}), + } + const commonArguments = learningStoreArguments({ directory, - "--repository", - `github.com/repositories/${input.repositoryId}`, - ] - const [rawMemories, rawRecall] = await Promise.all([ - runLearningCommand(["memories", ...commonArguments], commandOptions), - runLearningCommand( - ["recall", "--preview", "--by", input.viewer, ...commonArguments], - commandOptions, - ), - ]) + repositoryId: input.repositoryId, + repositoryScope: input.repositoryScope, + }) + const rawMemories = await runLearningCommand(["memories", ...commonArguments], commandOptions) + const rawStatus = await runLearningCommand(["status", ...commonArguments], commandOptions) + const rawRecall = await runLearningCommand( + ["recall", "--preview", "--by", input.viewer, ...commonArguments], + commandOptions, + ) const memories = z.array(memorySchema).parse(rawMemories) + const followUps = statusSchema.parse(rawStatus).migrationRedactionFollowUps const recall = recallSchema.parse(rawRecall) const recalledIds = new Set(recall.memories.map((memory) => memory.id)) const records = new Map(memories.map((item) => [item.record.id, item])) @@ -161,10 +181,26 @@ export async function getLearningOverview(input: { item.status.conflicts.length === 0, ) let loadError: string | null = null + if (followUps) { + loadError = + [ + ...followUps.memoriesNeedingRebuild.map( + (id) => `Rebuild learning ${id} because its evidence was removed.`, + ), + ...followUps.exportsToFollowUp.map( + (item) => + `Follow up on export ${item.id} at ${item.destination}; it may contain removed text.`, + ), + ].join(" ") || null + } const suggestions: LearningSuggestion[] = [] if (proposed.length > 0 && !input.evidenceSource) { - loadError = - "Review comment evidence is not available yet, so Hub withheld learning suggestions." + loadError = [ + loadError, + "Review comment evidence is not available yet, so Hub withheld learning suggestions.", + ] + .filter(Boolean) + .join(" ") } else if (input.evidenceSource) { const prepared = proposed.map((item) => { if (!item.record.content || !item.record.reviewDigest) { diff --git a/hub/server/domains/learning/get-learning-repository-scope/index.ts b/hub/server/domains/learning/get-learning-repository-scope/index.ts new file mode 100644 index 000000000..77e99f4c3 --- /dev/null +++ b/hub/server/domains/learning/get-learning-repository-scope/index.ts @@ -0,0 +1,18 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" +import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" +import { findRepositoryGitHubId } from "../../../repositories/repository-access/find-repository-github-id/index.ts" + +export async function getLearningRepositoryScope( + database: Pick, + repositoryId: string, +) { + const repository = await findRepositoryGitHubId(database, repositoryId) + const id = repository?.githubRepositoryId + if (id == null || id <= 0n) { + throw new LearningCommandError( + "repository_scope_unavailable", + "Learnings are unavailable because this repository has no GitHub repository ID.", + ) + } + return `github.com/repositories/${id}` +} diff --git a/hub/server/domains/learning/learning-store-arguments/index.ts b/hub/server/domains/learning/learning-store-arguments/index.ts new file mode 100644 index 000000000..3dc2f3aaf --- /dev/null +++ b/hub/server/domains/learning/learning-store-arguments/index.ts @@ -0,0 +1,17 @@ +export function learningStoreArguments(store: { + directory: string + repositoryScope: string + repositoryId: string +}) { + if (!/^github\.com\/repositories\/[1-9][0-9]*$/.test(store.repositoryScope)) { + throw new Error("The repository learning scope must contain a GitHub repository ID.") + } + return [ + "--dir", + store.directory, + "--repository", + store.repositoryScope, + "--legacy-repository", + `github.com/repositories/${store.repositoryId}`, + ] +} diff --git a/hub/server/domains/learning/prepare-learning-store/index.test.ts b/hub/server/domains/learning/prepare-learning-store/index.test.ts index 5d71313cf..d34e51b15 100644 --- a/hub/server/domains/learning/prepare-learning-store/index.test.ts +++ b/hub/server/domains/learning/prepare-learning-store/index.test.ts @@ -6,6 +6,25 @@ import { describe, expect, it, onTestFinished } from "vitest" import { prepareLearningStore } from "." describe("prepareLearningStore()", () => { + it("uses a database store without creating a local learning directory", async () => { + const applicationRoot = resolve(`server/domains/learning/.store-test-${randomUUID()}`) + const root = resolve(applicationRoot, "learning") + const repositoryKey = randomUUID() + onTestFinished(() => rm(applicationRoot, { force: true, recursive: true })) + + const result = await prepareLearningStore({ + applicationRoot, + learningDatabaseUrl: "postgresql://learning.example/replica", + repositoryKey, + repositoryScope: "github.com/repositories/123", + root, + staticDirectories: [], + }) + + expect(result.repositoryScope).toBe("github.com/repositories/123") + await expect(stat(root)).rejects.toMatchObject({ code: "ENOENT" }) + }) + it.each([ ["source public directory", 0], ["configured client directory", 1], @@ -22,7 +41,7 @@ describe("prepareLearningStore()", () => { prepareLearningStore({ applicationRoot, repositoryKey: randomUUID(), - repositoryScope: "github.com/repositories/replica", + repositoryScope: "github.com/repositories/123", root, staticDirectories, }), @@ -40,14 +59,15 @@ describe("prepareLearningStore()", () => { const result = await prepareLearningStore({ applicationRoot, repositoryKey, - repositoryScope: "github.com/repositories/replica", + repositoryScope: "github.com/repositories/123", root, staticDirectories: [resolve(applicationRoot, "public")], }) expect(result).toEqual({ directory: resolve(root, "repositories", repositoryKey), - repositoryScope: "github.com/repositories/replica", + repositoryScope: "github.com/repositories/123", + repositoryId: repositoryKey, }) expect((await stat(result.directory)).mode & 0o777).toBe(0o700) expect((await stat(resolve(result.directory, "config.json"))).mode & 0o777).toBe(0o600) @@ -60,7 +80,7 @@ describe("prepareLearningStore()", () => { }, }) expect(await readFile(resolve(result.directory, "config.json"), "utf8")).not.toContain( - "github.com/repositories/replica", + "github.com/repositories/123", ) }) }) diff --git a/hub/server/domains/learning/prepare-learning-store/index.ts b/hub/server/domains/learning/prepare-learning-store/index.ts index c5fcf171d..a5655be98 100644 --- a/hub/server/domains/learning/prepare-learning-store/index.ts +++ b/hub/server/domains/learning/prepare-learning-store/index.ts @@ -10,16 +10,18 @@ const repositoryScopeSchema = z .string() .min(1) .max(500) - .regex(/^[a-z0-9.-]+\/repositories\/[A-Za-z0-9_-]+$/) + .regex(/^github\.com\/repositories\/[1-9][0-9]*$/) export async function prepareLearningStore({ applicationRoot = process.cwd(), + learningDatabaseUrl, repositoryKey, repositoryScope, root, staticDirectories, }: { applicationRoot?: string + learningDatabaseUrl?: string repositoryKey: string repositoryScope: string root: string @@ -33,6 +35,7 @@ export async function prepareLearningStore({ name: "REPLICA_LEARNING_ROOT", publicRoot: resolve(applicationRoot, "public"), }) + if (learningDatabaseUrl) return { directory, repositoryScope: scope, repositoryId: key } await mkdir(directory, { mode: 0o700, recursive: true }) await validatePrivateStorageRoot(directory, { applicationRoot, @@ -70,5 +73,5 @@ export async function prepareLearningStore({ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error } - return { directory, repositoryScope: scope } + return { directory, repositoryScope: scope, repositoryId: key } } diff --git a/hub/server/domains/learning/process-learning-run/index.test.ts b/hub/server/domains/learning/process-learning-run/index.test.ts index 56d599013..909e82caf 100644 --- a/hub/server/domains/learning/process-learning-run/index.test.ts +++ b/hub/server/domains/learning/process-learning-run/index.test.ts @@ -43,6 +43,8 @@ function dependencies(overrides: Partial = {}) { capture: vi.fn().mockResolvedValue({ collection: { kind: "replica.hub-review-collection/v1" }, digest: "sha256:snapshot", + legacyDigest: "sha256:legacy-snapshot", + repositoryScope: "github.com/repositories/123", capturedAt: new Date("2026-11-13T09:00:00Z"), reviewActivitySnapshot: {}, }), @@ -57,7 +59,8 @@ function dependencies(overrides: Partial = {}) { authorizeRepositoryAdministration: vi.fn().mockResolvedValue(true), prepare: vi.fn().mockResolvedValue({ directory: "/private/repository", - repositoryScope: "github.com/repositories/repository", + repositoryScope: "github.com/repositories/123", + repositoryId: run.repositoryId, }), runCommand: vi.fn((arguments_: string[]) => { commands.push(arguments_) @@ -114,6 +117,16 @@ describe("processLearningRun()", () => { expect(deps.commands.find((arguments_) => arguments_[0] === "import")).toContain( "--redact-deleted", ) + for (const command of deps.commands) { + expect(command).toEqual( + expect.arrayContaining([ + "--repository", + "github.com/repositories/123", + "--legacy-repository", + `github.com/repositories/${deps.run.repositoryId}`, + ]), + ) + } expect( deps.commands.find((arguments_) => arguments_[0] === "grants" && arguments_[1] === "add"), ).toEqual(expect.arrayContaining(["--by", "human:mona"])) @@ -166,6 +179,7 @@ describe("processLearningRun()", () => { it("resumes a run left running after a worker interruption", async () => { const deps = dependencies() deps.run.state = "RUNNING" + deps.run.snapshotDigest = "sha256:legacy-snapshot" await processLearningRun("11111111-2222-4333-8444-555555555555", deps) @@ -173,6 +187,29 @@ describe("processLearningRun()", () => { expect(deps.finished[0]).toMatchObject({ input: { state: "SUCCEEDED" } }) }) + it("does not consolidate if the repository scope changes during labeling", async () => { + const deps = dependencies() + vi.mocked(deps.prepare) + .mockResolvedValueOnce({ + directory: "/private/repository", + repositoryScope: "github.com/repositories/123", + repositoryId: deps.run.repositoryId, + }) + .mockResolvedValueOnce({ + directory: "/private/repository", + repositoryScope: "github.com/repositories/456", + repositoryId: deps.run.repositoryId, + }) + + await processLearningRun(deps.run.id, deps) + + expect(deps.commands.some((command) => command[0] === "label")).toBe(true) + expect(deps.commands.some((command) => command[0] === "consolidate")).toBe(false) + expect(deps.finished[0]).toMatchObject({ + input: { state: "FAILED", failureCode: "snapshot_changed" }, + }) + }) + it("defers a queued scheduled run before claim while user work is waiting", async () => { const deps = dependencies({ expectedScheduled: true, diff --git a/hub/server/domains/learning/process-learning-run/index.ts b/hub/server/domains/learning/process-learning-run/index.ts index e9603b9e3..79b9329b6 100644 --- a/hub/server/domains/learning/process-learning-run/index.ts +++ b/hub/server/domains/learning/process-learning-run/index.ts @@ -6,6 +6,7 @@ import { z } from "zod" import { classifyPrismaTransactionError } from "../../../integrations/prisma/classify-transaction-error/index.ts" import { LearningCommandError } from "../../../integrations/learning/run-learning-command/errors.ts" import { runWithBoundedRetries } from "../../identity/run-with-bounded-retries/index.ts" +import { learningStoreArguments } from "../learning-store-arguments/index.ts" const grantListSchema = z.array( z @@ -63,6 +64,8 @@ export async function processLearningRun( capture(repositoryId: string): Promise<{ collection: unknown digest: string + legacyDigest: string + repositoryScope: string capturedAt: Date reviewActivitySnapshot: Record }> @@ -95,7 +98,11 @@ export async function processLearningRun( now(): Date hasPendingUserRun(): Promise isRepositoryAvailable(repositoryId: string): Promise - prepare(repositoryId: string): Promise<{ directory: string; repositoryScope: string }> + prepare(repositoryId: string): Promise<{ + directory: string + repositoryScope: string + repositoryId: string + }> authorizeRepositoryAdministration(membershipId: string, repositoryId: string): Promise refuseCredential?(): Promise runCommand( @@ -167,14 +174,23 @@ export async function processLearningRun( actor = `human:${requester}` } const snapshot = await dependencies.capture(current.repositoryId) - if (snapshot.digest !== current.snapshotDigest) { + if ( + snapshot.digest !== current.snapshotDigest && + snapshot.legacyDigest !== current.snapshotDigest + ) { throw new LearningCommandError( "snapshot_changed", "Repository review comments changed before this learning run started. Request another run.", ) } const store = await dependencies.prepare(current.repositoryId) - const common = ["--dir", store.directory, "--repository", store.repositoryScope] + if (store.repositoryScope !== snapshot.repositoryScope) { + throw new LearningCommandError( + "snapshot_changed", + "The repository learning scope changed before this run started. Request another run.", + ) + } + const common = learningStoreArguments(store) const grants = grantListSchema.parse( await dependencies.runCommand(["grants", "list", ...common], { signal }), ) @@ -318,6 +334,14 @@ export async function processLearningRun( : "The person who requested this run is no longer a repository administrator.", ) } + if ( + (await dependencies.prepare(current.repositoryId)).repositoryScope !== store.repositoryScope + ) { + throw new LearningCommandError( + "snapshot_changed", + "The repository learning scope changed during this run. Request another run.", + ) + } const consolidated = consolidateSchema.parse( await dependencies.runCommand( [ diff --git a/hub/server/domains/learning/process-review-comment-redaction/index.test.ts b/hub/server/domains/learning/process-review-comment-redaction/index.test.ts index 26d80124b..c2621ac25 100644 --- a/hub/server/domains/learning/process-review-comment-redaction/index.test.ts +++ b/hub/server/domains/learning/process-review-comment-redaction/index.test.ts @@ -1,18 +1,54 @@ -import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises" +import { randomUUID } from "node:crypto" +import { chmod, copyFile, mkdtemp, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" -import { join } from "node:path" +import { join, resolve } from "node:path" +import { DatabaseSync } from "node:sqlite" import { describe, expect, it, vi } from "vitest" import { processReviewCommentRedaction } from "." +import { redactLegacyReviewComment } from "../redact-legacy-review-comment" +import { runLearningCommand } from "../../../integrations/learning/run-learning-command" type Dependencies = Parameters[1] +type StoredEvent = { + payload?: { commentId?: number; body?: string } + redaction?: { commentId?: number } +} + +const repositoryId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa" async function withLearningLock(run: (signal: AbortSignal) => Promise) { return await run(new AbortController().signal) } describe("processReviewCommentRedaction()", () => { + it("redacts an ID-less database repository without a local configuration", async () => { + const root = resolve(`server/domains/learning/.redaction-${randomUUID()}`) + const input = { repositoryId, commentId: 101, actor: "human:mona" } + const redactLegacy = vi.fn().mockResolvedValue(undefined) + const markComplete = vi.fn().mockResolvedValue(undefined) + + await processReviewCommentRedaction(input, { + learningDatabaseUrl: "postgresql://learning.example/replica", + root, + prepare: vi.fn().mockResolvedValue(null), + redactLegacy, + runCommand: vi.fn(), + markComplete, + now: () => new Date("2026-11-13T10:00:00Z"), + withLock: withLearningLock, + }) + + expect(redactLegacy).toHaveBeenCalledOnce() + expect(redactLegacy.mock.calls[0]?.[0]).toEqual(input) + expect((redactLegacy.mock.calls[0]?.[1] as { signal: AbortSignal }).signal).toBeInstanceOf( + AbortSignal, + ) + expect(markComplete).toHaveBeenCalledOnce() + await expect(stat(root)).rejects.toMatchObject({ code: "ENOENT" }) + }) + it("serializes redaction through the learning lock and does nothing without a store", async () => { let lockCalls = 0 async function withLock(run: (signal: AbortSignal) => Promise) { @@ -21,18 +57,20 @@ describe("processReviewCommentRedaction()", () => { } const prepare = vi.fn().mockResolvedValue({ directory: "/private/repository", - repositoryScope: "github.com/repositories/repository", + repositoryScope: "github.com/repositories/123", + repositoryId, }) const runCommand: Dependencies["runCommand"] = vi.fn() const markComplete = vi.fn().mockResolvedValue(undefined) await processReviewCommentRedaction( - { repositoryId: "repository", commentId: 101, actor: "human:mona" }, + { repositoryId, commentId: 101, actor: "human:mona" }, { root: "/private", markComplete, now: () => new Date("2026-11-13T10:00:00Z"), prepare, + redactLegacy: vi.fn(), runCommand, withLock, }, @@ -46,8 +84,8 @@ describe("processReviewCommentRedaction()", () => { it("redacts by Hub comment ID while holding the store lock", async () => { const root = await mkdtemp(join(tmpdir(), "replica-redaction-")) - await mkdir(join(root, "repositories", "repository"), { recursive: true }) - await writeFile(join(root, "repositories", "repository", "config.json"), "{}") + await mkdir(join(root, "repositories", repositoryId), { recursive: true }) + await writeFile(join(root, "repositories", repositoryId, "config.json"), "{}") try { let lockCalls = 0 async function withLock(run: (signal: AbortSignal) => Promise) { @@ -55,25 +93,27 @@ describe("processReviewCommentRedaction()", () => { return await withLearningLock(run) } const prepare = vi.fn().mockResolvedValue({ - directory: join(root, "repositories", "repository"), - repositoryScope: "github.com/repositories/repository", + directory: join(root, "repositories", repositoryId), + repositoryScope: "github.com/repositories/123", + repositoryId, }) const runCommand: Dependencies["runCommand"] = vi.fn().mockResolvedValue(undefined) const markComplete = vi.fn().mockResolvedValue(undefined) await processReviewCommentRedaction( - { repositoryId: "repository", commentId: 101, actor: "human:mona" }, + { repositoryId, commentId: 101, actor: "human:mona" }, { root, markComplete, now: () => new Date("2026-11-13T10:00:00Z"), prepare, + redactLegacy: vi.fn(), runCommand, withLock, }, ) expect(lockCalls).toBe(1) - expect(prepare).toHaveBeenCalledWith("repository") + expect(prepare).toHaveBeenCalledWith(repositoryId) const [arguments_, options] = vi.mocked(runCommand).mock.calls[0] ?? [] expect(arguments_).toEqual([ "redact", @@ -82,13 +122,15 @@ describe("processReviewCommentRedaction()", () => { "--by", "human:mona", "--dir", - join(root, "repositories", "repository"), + join(root, "repositories", repositoryId), "--repository", - "github.com/repositories/repository", + "github.com/repositories/123", + "--legacy-repository", + `github.com/repositories/${repositoryId}`, ]) expect(options?.signal).toBeInstanceOf(AbortSignal) expect(markComplete).toHaveBeenCalledWith({ - repositoryId: "repository", + repositoryId, commentId: 101, redactedAt: new Date("2026-11-13T10:00:00Z"), }) @@ -99,13 +141,13 @@ describe("processReviewCommentRedaction()", () => { it("keeps redaction pending when the store is inaccessible", async () => { const root = await mkdtemp(join(tmpdir(), "replica-redaction-")) - await mkdir(join(root, "repositories", "repository"), { recursive: true }) - await writeFile(join(root, "repositories", "repository", "config.json"), "{}") + await mkdir(join(root, "repositories", repositoryId), { recursive: true }) + await writeFile(join(root, "repositories", repositoryId, "config.json"), "{}") try { const markComplete = vi.fn() await expect( processReviewCommentRedaction( - { repositoryId: "repository", commentId: 101, actor: "human:mona" }, + { repositoryId, commentId: 101, actor: "human:mona" }, { root, markComplete, @@ -113,6 +155,7 @@ describe("processReviewCommentRedaction()", () => { prepare: vi .fn() .mockRejectedValue(Object.assign(new Error("denied"), { code: "EACCES" })), + redactLegacy: vi.fn(), runCommand: vi.fn(), withLock: withLearningLock, }, @@ -123,4 +166,268 @@ describe("processReviewCommentRedaction()", () => { await rm(root, { recursive: true, force: true }) } }) + + it("retries an ID-less repository's legacy redaction before marking it complete", async () => { + await mkdir(resolve(".local"), { recursive: true }) + const root = await mkdtemp(resolve(".local/redaction-")) + await mkdir(join(root, "repositories", repositoryId), { recursive: true }) + await writeFile(join(root, "repositories", repositoryId, "config.json"), "{}") + try { + const redactLegacy = vi + .fn() + .mockRejectedValueOnce(new Error("interrupted")) + .mockResolvedValueOnce(undefined) + const markComplete = vi.fn() + const dependencies = { + root, + markComplete, + now: () => new Date("2026-11-13T10:00:00Z"), + prepare: vi.fn().mockResolvedValue(null), + redactLegacy, + runCommand: vi.fn(), + withLock: withLearningLock, + } + const input = { repositoryId, commentId: 101, actor: "human:mona" } + + await expect(processReviewCommentRedaction(input, dependencies)).rejects.toThrow( + "interrupted", + ) + expect(markComplete).not.toHaveBeenCalled() + await processReviewCommentRedaction(input, dependencies) + expect(redactLegacy).toHaveBeenCalledTimes(2) + expect(redactLegacy.mock.calls[0]?.[0]).toEqual(input) + expect((redactLegacy.mock.calls[0]?.[1] as { signal: AbortSignal }).signal).toBeInstanceOf( + AbortSignal, + ) + expect(markComplete).toHaveBeenCalledOnce() + expect(dependencies.runCommand).not.toHaveBeenCalled() + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it("removes deleted comment text from the original SQLite store without assigning a GitHub ID", async () => { + await mkdir(resolve(".local"), { recursive: true }) + const root = await mkdtemp(resolve(".local/redaction-")) + const legacyId = "11111111-2222-4333-8444-555555555555" + const directory = join(root, "repositories", legacyId) + const cliPath = resolve("../packages/learning/bin/replica-learning.mjs") + await mkdir(directory, { recursive: true, mode: 0o700 }) + await writeFile( + join(directory, "config.json"), + JSON.stringify({ + schemaVersion: "replica.learning-config/v1", + memory: { provider: "sqlite" }, + }), + { mode: 0o600 }, + ) + try { + await copyFile( + resolve("../packages/learning/test/fixtures/legacy-hub-scope.sqlite"), + join(directory, "learning.sqlite"), + ) + await chmod(join(directory, "learning.sqlite"), 0o600) + const markComplete = vi.fn() + const input = { repositoryId: legacyId, commentId: 101, actor: "human:mona" } + const dependencies = { + root, + prepare: vi.fn().mockResolvedValue(null), + redactLegacy: (request: typeof input, { signal }: { signal: AbortSignal }) => + redactLegacyReviewComment(request, { + root, + staticDirectories: [], + cliPath, + nodePath: process.execPath, + signal, + }), + runCommand: vi.fn(), + markComplete, + now: () => new Date(), + withLock: withLearningLock, + } + + await processReviewCommentRedaction(input, dependencies) + await processReviewCommentRedaction(input, dependencies) + + const db = new DatabaseSync(join(directory, "learning.sqlite"), { readOnly: true }) + try { + const events = db + .prepare("select body from records where stream = 'events'") + .all() + .map((row) => JSON.parse(String(row.body)) as StoredEvent) + expect(events.some((event) => event.redaction?.commentId === 101 && !event.payload)).toBe( + true, + ) + expect(events.some((event) => event.payload?.commentId === 101)).toBe(false) + expect( + events.some((event) => event.payload?.commentId !== 101 && event.payload?.body), + ).toBe(true) + expect(db.prepare("select count(*) as count from scope_migrations").get()).toEqual({ + count: 0, + }) + } finally { + db.close() + } + expect(markComplete).toHaveBeenCalledTimes(2) + const config = JSON.parse(await readFile(join(directory, "config.json"), "utf8")) as { + memory: { provider: string } + } + expect(config.memory.provider).toBe("sqlite") + } finally { + await rm(root, { force: true, recursive: true }) + } + }) + + it("removes deleted comment text from the original JSON Lines store without assigning a GitHub ID", async () => { + await mkdir(resolve(".local"), { recursive: true }) + const root = await mkdtemp(resolve(".local/redaction-")) + const legacyId = "11111111-2222-4333-8444-555555555555" + const directory = join(root, "repositories", legacyId) + const cliPath = resolve("../packages/learning/bin/replica-learning.mjs") + await mkdir(directory, { recursive: true, mode: 0o700 }) + await writeFile( + join(directory, "config.json"), + JSON.stringify({ + schemaVersion: "replica.learning-config/v1", + memory: { provider: "jsonl" }, + }), + { mode: 0o600 }, + ) + try { + const fixtureCopy = join(root, "fixture.sqlite") + await copyFile( + resolve("../packages/learning/test/fixtures/legacy-hub-scope.sqlite"), + fixtureCopy, + ) + const db = new DatabaseSync(fixtureCopy, { readOnly: true }) + try { + const rows = db.prepare("select stream, body from records order by seq").all() + const memories = db.prepare("select body from memory_versions order by seq").all() + await mkdir(join(directory, "v1"), { mode: 0o700 }) + for (const stream of new Set(rows.map((row) => String(row.stream)))) { + const bodies = rows.filter((row) => row.stream === stream).map((row) => row.body) + await writeFile(join(directory, "v1", `${stream}.jsonl`), `${bodies.join("\n")}\n`, { + mode: 0o600, + }) + } + if (memories.length) { + await writeFile( + join(directory, "v1", "memories.jsonl"), + `${memories.map((row) => row.body).join("\n")}\n`, + { mode: 0o600 }, + ) + } + } finally { + db.close() + } + const markComplete = vi.fn() + const input = { repositoryId: legacyId, commentId: 101, actor: "human:mona" } + const dependencies = { + root, + prepare: vi.fn().mockResolvedValue(null), + redactLegacy: (request: typeof input, { signal }: { signal: AbortSignal }) => + redactLegacyReviewComment(request, { + root, + staticDirectories: [], + cliPath, + nodePath: process.execPath, + signal, + }), + runCommand: vi.fn(), + markComplete, + now: () => new Date(), + withLock: withLearningLock, + } + + await processReviewCommentRedaction(input, dependencies) + await processReviewCommentRedaction(input, dependencies) + + const events = (await readFile(join(directory, "v1", "events.jsonl"), "utf8")) + .trim() + .split("\n") + .map((line) => JSON.parse(line) as StoredEvent) + expect(events.some((event) => event.redaction?.commentId === 101 && !event.payload)).toBe( + true, + ) + expect(events.some((event) => event.payload?.commentId === 101)).toBe(false) + expect(events.some((event) => event.payload?.commentId !== 101 && event.payload?.body)).toBe( + true, + ) + expect(markComplete).toHaveBeenCalledTimes(2) + const config = JSON.parse(await readFile(join(directory, "config.json"), "utf8")) as { + memory: { provider: string } + } + expect(config.memory.provider).toBe("jsonl") + } finally { + await rm(root, { force: true, recursive: true }) + } + }) + + it("redacts a migrated SQLite store using its durable UUID mapping", async () => { + await mkdir(resolve(".local"), { recursive: true }) + const root = await mkdtemp(resolve(".local/redaction-")) + const legacyId = "11111111-2222-4333-8444-555555555555" + const directory = join(root, "repositories", legacyId) + const cliPath = resolve("../packages/learning/bin/replica-learning.mjs") + await mkdir(directory, { recursive: true, mode: 0o700 }) + await copyFile( + resolve("../packages/learning/test/fixtures/legacy-hub-scope.sqlite"), + join(directory, "learning.sqlite"), + ) + await chmod(join(directory, "learning.sqlite"), 0o600) + await writeFile( + join(directory, "config.json"), + JSON.stringify({ schemaVersion: "replica.learning-config/v1" }), + { mode: 0o600 }, + ) + try { + await runLearningCommand( + [ + "status", + "--dir", + directory, + "--repository", + "github.com/repositories/123", + "--legacy-repository", + `github.com/repositories/${legacyId}`, + ], + { cliPath }, + ) + const markComplete = vi.fn() + const input = { repositoryId: legacyId, commentId: 101, actor: "human:mona" } + await processReviewCommentRedaction(input, { + root, + prepare: vi.fn().mockResolvedValue(null), + redactLegacy: (request, { signal }) => + redactLegacyReviewComment(request, { + root, + staticDirectories: [], + cliPath, + nodePath: process.execPath, + signal, + }), + runCommand: vi.fn(), + markComplete, + now: () => new Date(), + withLock: withLearningLock, + }) + const db = new DatabaseSync(join(directory, "learning.sqlite"), { readOnly: true }) + try { + const events = db + .prepare("select scope_key, body from records where stream = 'events'") + .all() + expect( + events.some( + (row) => (JSON.parse(String(row.body)) as StoredEvent).redaction?.commentId === 101, + ), + ).toBe(true) + expect(events.every((row) => String(row.scope_key).includes("repositories/123"))).toBe(true) + } finally { + db.close() + } + expect(markComplete).toHaveBeenCalledOnce() + } finally { + await rm(root, { force: true, recursive: true }) + } + }) }) diff --git a/hub/server/domains/learning/process-review-comment-redaction/index.ts b/hub/server/domains/learning/process-review-comment-redaction/index.ts index 288e83808..79ef82116 100644 --- a/hub/server/domains/learning/process-review-comment-redaction/index.ts +++ b/hub/server/domains/learning/process-review-comment-redaction/index.ts @@ -1,11 +1,23 @@ import { access } from "node:fs/promises" import { resolve } from "node:path" +import { z } from "zod" + +import { learningStoreArguments } from "../learning-store-arguments/index.ts" export async function processReviewCommentRedaction( input: { repositoryId: string; commentId: number; actor: string }, dependencies: { + learningDatabaseUrl?: string root: string - prepare(repositoryId: string): Promise<{ directory: string; repositoryScope: string }> + prepare(repositoryId: string): Promise<{ + directory: string + repositoryScope: string + repositoryId: string + } | null> + redactLegacy( + input: { repositoryId: string; commentId: number; actor: string }, + options: { signal: AbortSignal }, + ): Promise runCommand(arguments_: string[], options: { signal: AbortSignal }): Promise markComplete(input: { repositoryId: string @@ -16,29 +28,33 @@ export async function processReviewCommentRedaction( withLock(run: (signal: AbortSignal) => Promise): Promise }, ) { + const repositoryId = z.uuid().parse(input.repositoryId) await dependencies.withLock(async (signal) => { - const directory = resolve(dependencies.root, "repositories", input.repositoryId) - try { - await access(resolve(directory, "config.json")) - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error - return + const directory = resolve(dependencies.root, "repositories", repositoryId) + if (!dependencies.learningDatabaseUrl) { + try { + await access(resolve(directory, "config.json")) + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + return + } } const store = await dependencies.prepare(input.repositoryId) - await dependencies.runCommand( - [ - "redact", - "--comment", - input.commentId.toString(), - "--by", - input.actor, - "--dir", - store.directory, - "--repository", - store.repositoryScope, - ], - { signal }, - ) + if (store) { + await dependencies.runCommand( + [ + "redact", + "--comment", + input.commentId.toString(), + "--by", + input.actor, + ...learningStoreArguments(store), + ], + { signal }, + ) + } else { + await dependencies.redactLegacy(input, { signal }) + } await dependencies.markComplete({ repositoryId: input.repositoryId, commentId: input.commentId, diff --git a/hub/server/domains/learning/read-learning-configuration/index.ts b/hub/server/domains/learning/read-learning-configuration/index.ts index dbb4afd65..2604d670e 100644 --- a/hub/server/domains/learning/read-learning-configuration/index.ts +++ b/hub/server/domains/learning/read-learning-configuration/index.ts @@ -33,6 +33,7 @@ export async function readLearningConfiguration( environment.REPLICA_LEARNING_CLI ?? "../packages/learning/bin/replica-learning.mjs", ) const nodePath = environment.REPLICA_LEARNING_NODE?.trim() || process.execPath + const learningDatabaseUrl = environment.REPLICA_LEARNING_DATABASE_URL?.trim() || undefined let copilotCredentialProvider try { copilotCredentialProvider = createCopilotCredentialProvider(environment) @@ -46,6 +47,7 @@ export async function readLearningConfiguration( automaticRuns, cliPath, copilotCredentialProvider, + learningDatabaseUrl, nodePath, root, staticDirectories: [ diff --git a/hub/server/domains/learning/reconcile-learning-decision-operation/index.test.ts b/hub/server/domains/learning/reconcile-learning-decision-operation/index.test.ts index 4263ddb20..bb1505acc 100644 --- a/hub/server/domains/learning/reconcile-learning-decision-operation/index.test.ts +++ b/hub/server/domains/learning/reconcile-learning-decision-operation/index.test.ts @@ -13,15 +13,16 @@ const operation = { describe("reconcileLearningDecisionOperation()", () => { it("records success when the package store contains the intended decision", async () => { const finish = vi.fn().mockResolvedValue(undefined) + const runCommand = vi.fn().mockResolvedValue({ state: "accepted" }) await reconcileLearningDecisionOperation(operation, { finish, - prepare: vi - .fn() - .mockResolvedValue({ directory: "/private/store", repositoryScope: "github.com/x/y" }), - runCommand: vi.fn().mockResolvedValue({ - state: "accepted", + prepare: vi.fn().mockResolvedValue({ + directory: "/private/store", + repositoryScope: "github.com/repositories/123", + repositoryId: operation.repositoryId, }), + runCommand, withLock: async (run) => await run(new AbortController().signal), }) @@ -31,6 +32,15 @@ describe("reconcileLearningDecisionOperation()", () => { outcome: "succeeded", }), ) + expect(runCommand).toHaveBeenCalledWith( + expect.arrayContaining([ + "--repository", + "github.com/repositories/123", + "--legacy-repository", + `github.com/repositories/${operation.repositoryId}`, + ]), + expect.anything(), + ) }) it("keeps the durable intent pending when the package store cannot be read", async () => { @@ -52,9 +62,11 @@ describe("reconcileLearningDecisionOperation()", () => { await reconcileLearningDecisionOperation(operation, { finish, - prepare: vi - .fn() - .mockResolvedValue({ directory: "/private/store", repositoryScope: "github.com/x/y" }), + prepare: vi.fn().mockResolvedValue({ + directory: "/private/store", + repositoryScope: "github.com/repositories/123", + repositoryId: operation.repositoryId, + }), runCommand: vi.fn().mockResolvedValue({ state: null }), withLock: async (run) => await run(new AbortController().signal), }) diff --git a/hub/server/domains/learning/reconcile-learning-decision-operation/index.ts b/hub/server/domains/learning/reconcile-learning-decision-operation/index.ts index c6ae9360b..6fb83b2e9 100644 --- a/hub/server/domains/learning/reconcile-learning-decision-operation/index.ts +++ b/hub/server/domains/learning/reconcile-learning-decision-operation/index.ts @@ -1,6 +1,8 @@ import { randomUUID } from "node:crypto" import { z } from "zod" +import { learningStoreArguments } from "../learning-store-arguments/index.ts" + const resultSchema = z .object({ state: z.enum(["proposed", "accepted", "rejected", "retired"]).nullable(), @@ -22,7 +24,11 @@ export async function reconcileLearningDecisionOperation( outcome: "succeeded" | "failed" reason?: string }): Promise - prepare(repositoryId: string): Promise<{ directory: string; repositoryScope: string }> + prepare(repositoryId: string): Promise<{ + directory: string + repositoryScope: string + repositoryId: string + }> runCommand(arguments_: string[], options: { signal: AbortSignal }): Promise withLock(run: (signal: AbortSignal) => Promise): Promise }, @@ -44,10 +50,7 @@ export async function reconcileLearningDecisionOperation( operation.learningId, "--operation-id", operation.id, - "--dir", - store.directory, - "--repository", - store.repositoryScope, + ...learningStoreArguments(store), ], { signal }, ), diff --git a/hub/server/domains/learning/redact-legacy-review-comment/index.ts b/hub/server/domains/learning/redact-legacy-review-comment/index.ts new file mode 100644 index 000000000..1134f3bcf --- /dev/null +++ b/hub/server/domains/learning/redact-legacy-review-comment/index.ts @@ -0,0 +1,48 @@ +import { resolve } from "node:path" +import { z } from "zod" + +import { runLearningCommand } from "../../../integrations/learning/run-learning-command/index.ts" +import { validatePrivateStorageRoot } from "../../../utils/validate-private-storage-root/index.ts" + +export async function redactLegacyReviewComment( + input: { repositoryId: string; commentId: number; actor: string }, + options: { + root: string + staticDirectories: string[] + cliPath: string + learningDatabaseUrl?: string + nodePath: string + signal: AbortSignal + }, +) { + const repositoryId = z.uuid().parse(input.repositoryId) + const directory = await validatePrivateStorageRoot( + resolve(options.root, "repositories", repositoryId), + { + applicationRoot: process.cwd(), + excludedDirectories: options.staticDirectories, + name: "REPLICA_LEARNING_ROOT", + publicRoot: resolve(process.cwd(), "public"), + }, + ) + return await runLearningCommand( + [ + "redact", + "--comment", + String(input.commentId), + "--by", + input.actor, + "--dir", + directory, + "--legacy-repository", + `github.com/repositories/${repositoryId}`, + "--legacy-redaction", + ], + { + cliPath: options.cliPath, + nodePath: options.nodePath, + signal: options.signal, + ...(options.learningDatabaseUrl ? { learningDatabaseUrl: options.learningDatabaseUrl } : {}), + }, + ) +} diff --git a/hub/server/domains/learning/review-comment-learning-source/types.ts b/hub/server/domains/learning/review-comment-learning-source/types.ts index 37734c2f0..3cd6e6824 100644 --- a/hub/server/domains/learning/review-comment-learning-source/types.ts +++ b/hub/server/domains/learning/review-comment-learning-source/types.ts @@ -32,6 +32,8 @@ export interface ReviewCommentLearningSource { captureCompleteSnapshot(input: { repositoryId: string }): Promise<{ collection: unknown digest: `sha256:${string}` + legacyDigest: `sha256:${string}` + repositoryScope: string capturedAt: Date reviewActivitySnapshot: Record }> diff --git a/hub/server/index.ts b/hub/server/index.ts index a1c1521b4..c86bea253 100644 --- a/hub/server/index.ts +++ b/hub/server/index.ts @@ -211,6 +211,7 @@ try { database: (await import("./integrations/prisma/index.ts")).prisma, databaseUrl, hubOrigin: applicationOrigin, + learningDatabaseUrl: learningConfiguration.learningDatabaseUrl, learningRoot: learningConfiguration.root, nodePath: learningConfiguration.nodePath, staticDirectories: learningConfiguration.staticDirectories, diff --git a/hub/server/integrations/filesystem/create-filesystem-artifact-storage/index.test.ts b/hub/server/integrations/filesystem/create-filesystem-artifact-storage/index.test.ts index d03af2677..b1f8e9a68 100644 --- a/hub/server/integrations/filesystem/create-filesystem-artifact-storage/index.test.ts +++ b/hub/server/integrations/filesystem/create-filesystem-artifact-storage/index.test.ts @@ -12,22 +12,29 @@ vi.mock("node:fs/promises", async (importOriginal) => ({ import { createFilesystemArtifactStorage } from "." +// Filesystem artifact storage needs Linux's /proc/self/fd, so it refuses other +// platforms. +const itOnLinux = it.runIf(process.platform === "linux") + describe("createFilesystemArtifactStorage()", () => { - it("preserves committed writes and publication failures when staging cleanup fails", async () => { - const directory = resolve(`server/integrations/filesystem/.storage-test-${randomUUID()}`) - await mkdir(directory) - onTestFinished(() => rm(directory, { recursive: true, force: true })) - const reportCleanupFailure = vi.fn() - const storage = await createFilesystemArtifactStorage(directory, 3, reportCleanupFailure) - mocks.unlink.mockRejectedValue(new Error("Private filesystem diagnostics")) + itOnLinux( + "preserves committed writes and publication failures when staging cleanup fails", + async () => { + const directory = resolve(`server/integrations/filesystem/.storage-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { recursive: true, force: true })) + const reportCleanupFailure = vi.fn() + const storage = await createFilesystemArtifactStorage(directory, 3, reportCleanupFailure) + mocks.unlink.mockRejectedValue(new Error("Private filesystem diagnostics")) - expect(await storage.write("key", Uint8Array.of(1, 2))).toEqual({ status: "ok" }) - expect(await readFile(`${directory}/key`)).toEqual(Buffer.from([1, 2])) - expect(reportCleanupFailure).toHaveBeenCalledTimes(1) + expect(await storage.write("key", Uint8Array.of(1, 2))).toEqual({ status: "ok" }) + expect(await readFile(`${directory}/key`)).toEqual(Buffer.from([1, 2])) + expect(reportCleanupFailure).toHaveBeenCalledTimes(1) - expect(await storage.write("key", Uint8Array.of(3))).toEqual({ status: "already-exists" }) - expect(await readFile(`${directory}/key`)).toEqual(Buffer.from([1, 2])) - expect(reportCleanupFailure).toHaveBeenCalledTimes(2) - expect(reportCleanupFailure.mock.calls).toEqual([[], []]) - }) + expect(await storage.write("key", Uint8Array.of(3))).toEqual({ status: "already-exists" }) + expect(await readFile(`${directory}/key`)).toEqual(Buffer.from([1, 2])) + expect(reportCleanupFailure).toHaveBeenCalledTimes(2) + expect(reportCleanupFailure.mock.calls).toEqual([[], []]) + }, + ) }) diff --git a/hub/server/integrations/learning/run-learning-command/index.test.ts b/hub/server/integrations/learning/run-learning-command/index.test.ts index 1b394b248..a63023102 100644 --- a/hub/server/integrations/learning/run-learning-command/index.test.ts +++ b/hub/server/integrations/learning/run-learning-command/index.test.ts @@ -1,12 +1,44 @@ import { randomUUID } from "node:crypto" -import { mkdir, readFile, rm, stat } from "node:fs/promises" -import { resolve } from "node:path" +import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises" +import { isAbsolute, relative, resolve, sep } from "node:path" +import { inspect } from "node:util" import { describe, expect, it, onTestFinished } from "vitest" import { runLearningCommand } from "." +import { LearningCommandError } from "./errors" const fixtures = resolve("test/fixtures/learning") +async function runPasswordFailure(databaseUrl: string, password: string, encodedPassword: string) { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const cliPath = resolve(directory, "fail.mjs") + await writeFile( + cliPath, + ` + const databaseUrl = process.env.REPLICA_LEARNING_DATABASE_URL + const password = ${JSON.stringify(password)} + const encodedPassword = ${JSON.stringify(encodedPassword)} + process.stdout.write(JSON.stringify({ + considered: 3, + receivedDatabaseUrl: Boolean(databaseUrl), + nested: { databaseUrl, password, [password]: encodedPassword }, + })) + process.stderr.write("error (learning_failed): Database failure: " + databaseUrl + " " + password + " " + encodedPassword) + process.exitCode = 1 + `, + ) + + const error: unknown = await runLearningCommand(["label", "--dir", resolve(directory, "store")], { + cliPath, + learningDatabaseUrl: databaseUrl, + environment: { PATH: process.env.PATH }, + }).catch((failure: unknown) => failure) + if (!(error instanceof LearningCommandError)) throw new Error("Expected a command failure.") + return error +} + describe("runLearningCommand()", () => { it("isolates the environment in a private temporary directory and removes it afterward", async () => { const result = (await runLearningCommand(["copilot", "status"], { @@ -18,6 +50,10 @@ describe("runLearningCommand()", () => { LANG: "en_US.UTF-8", LC_ALL: "C", PATH: process.env.PATH, + REPLICA_LEARNING_DATABASE_URL: "ambient-database-url-must-not-leak", + REPLICA_LEARNING_HUB_POSTGRES: "ambient-postgres-must-not-leak", + REPLICA_LEARNING_HUB_REQUIRE_IMPORT: "ambient-import-must-not-leak", + REPLICA_LEARNING_MIGRATION_DATABASE_URL: "migration-url-must-not-leak", REPLICA_LEARNING_ROOT: "/private/learning", REPLICA_LEARNING_SECRET: "must-not-leak", SECRET_FROM_HUB: "must-not-leak", @@ -59,6 +95,390 @@ describe("runLearningCommand()", () => { expect(result.environment.COPILOT_GITHUB_TOKEN).toBeUndefined() }) + it("uses a private Postgres config and passes only explicitly supplied credentials", async () => { + const databaseUrl = "postgres://learning-user:learning-password@localhost/learning" + const nonexistentDirectory = resolve( + `server/integrations/learning/.process-test-${randomUUID()}`, + ) + const result = (await runLearningCommand( + ["consolidate", "--dir", nonexistentDirectory, "--repository", "github.com/repositories/123"], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: databaseUrl, + githubToken: "explicit-token", + environment: { + PATH: process.env.PATH, + COPILOT_GITHUB_TOKEN: "ambient-token-must-not-leak", + REPLICA_LEARNING_DATABASE_URL: "ambient-url-must-not-leak", + REPLICA_LEARNING_MIGRATION_DATABASE_URL: "migration-url-must-not-leak", + DATABASE_URL: "hub-database-url-must-not-leak", + SECRET_FROM_HUB: "hub-secret-must-not-leak", + }, + }, + )) as { + arguments: string[] + config: string + environment: NodeJS.ProcessEnv + temporaryDirectory: string + temporaryDirectoryMode: number + } + + const storeDirectory = result.arguments[2] + if (storeDirectory === undefined) throw new Error("Missing store directory argument.") + const relativeStore = relative(result.temporaryDirectory, storeDirectory) + expect(isAbsolute(storeDirectory)).toBe(true) + expect(isAbsolute(relativeStore)).toBe(false) + expect(relativeStore === ".." || relativeStore.startsWith(`..${sep}`)).toBe(false) + expect(result.arguments).toEqual([ + "consolidate", + "--dir", + storeDirectory, + "--repository", + "github.com/repositories/123", + "--json", + ]) + expect(result.environment).toEqual({ + PATH: process.env.PATH, + TMPDIR: result.temporaryDirectory, + COPILOT_GITHUB_TOKEN: "explicit-token", + REPLICA_LEARNING_DATABASE_URL: databaseUrl, + REPLICA_LEARNING_HUB_POSTGRES: "1", + }) + expect(JSON.parse(result.config)).toMatchObject({ + memory: { provider: "postgres" }, + consolidation: { + options: { + signals: ["visual_quality", "accessibility", "usability", "content", "interaction"], + }, + }, + }) + expect(JSON.parse(result.config)).not.toHaveProperty("memory.requireImport") + for (const secret of [ + databaseUrl, + "learning-password", + "explicit-token", + "migration-url-must-not-leak", + "hub-secret-must-not-leak", + ]) { + expect(result.config).not.toContain(secret) + expect(result.arguments.join(" ")).not.toContain(secret) + } + expect(result.temporaryDirectoryMode).toBe(0o700) + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + + it("preserves an existing SQLite config when opening Postgres", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const configPath = resolve(directory, "config.json") + const config = `${JSON.stringify( + { + schemaVersion: "replica.learning-config/v1", + memory: { provider: "sqlite" }, + consolidation: { options: { minPrototypes: 4, minReviewers: 3 } }, + labeling: { options: { model: "example-model", timeoutMs: 12000 } }, + }, + null, + 2, + )}\n` + await writeFile(configPath, config) + const databaseUrl = "postgres://learning-user:learning-password@localhost/learning" + const token = "explicit-token" + + const result = (await runLearningCommand( + ["consolidate", "--dir", directory, "--repository", "github.com/repositories/123"], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: databaseUrl, + githubToken: token, + environment: { PATH: process.env.PATH }, + }, + )) as { + config: string + environment: NodeJS.ProcessEnv + temporaryDirectory: string + } + + expect(result.config).toBe(config) + expect(result.environment.REPLICA_LEARNING_HUB_POSTGRES).toBe("1") + expect(result.environment.REPLICA_LEARNING_HUB_REQUIRE_IMPORT).toBe("1") + expect(result.config).not.toContain(databaseUrl) + expect(result.config).not.toContain(token) + expect(await readFile(configPath, "utf8")).toBe(config) + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + + it("uses Postgres-only config for a fresh store without requiring import", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const configPath = resolve(directory, "postgres-config.json") + const config = `${JSON.stringify( + { + schemaVersion: "replica.learning-config/v1", + consolidation: { options: { minPrototypes: 4 } }, + labeling: { options: { model: "example-model" } }, + }, + null, + 2, + )}\n` + await writeFile(configPath, config) + const databaseUrl = "postgres://learning-user:learning-password@localhost/learning" + const token = "explicit-token" + + const result = (await runLearningCommand( + ["consolidate", "--dir", directory, "--repository", "github.com/repositories/123"], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: databaseUrl, + githubToken: token, + environment: { PATH: process.env.PATH }, + }, + )) as { + config: string + environment: NodeJS.ProcessEnv + temporaryDirectory: string + } + + expect(result.config).toBe(config) + expect(result.environment.REPLICA_LEARNING_HUB_POSTGRES).toBe("1") + expect(result.environment.REPLICA_LEARNING_HUB_REQUIRE_IMPORT).toBeUndefined() + expect(result.config).not.toContain(databaseUrl) + expect(result.config).not.toContain(token) + expect(await readFile(configPath, "utf8")).toBe(config) + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + + it("rejects a store with both SQLite and Postgres configs", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const sqliteConfig = resolve(directory, "config.json") + const postgresConfig = resolve(directory, "postgres-config.json") + const marker = resolve(directory, "command.json") + await writeFile(sqliteConfig, '{"memory":{"provider":"sqlite"}}\n') + await writeFile(postgresConfig, '{"memory":{"provider":"postgres"}}\n') + + await expect( + runLearningCommand(["consolidate", "--dir", directory, "--fixture-fail-report", marker], { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: "postgres://learning-user:learning-password@localhost/learning", + environment: { PATH: process.env.PATH }, + }), + ).rejects.toBeInstanceOf(LearningCommandError) + + await expect(stat(marker)).rejects.toMatchObject({ code: "ENOENT" }) + expect(await readFile(sqliteConfig, "utf8")).toBe('{"memory":{"provider":"sqlite"}}\n') + expect(await readFile(postgresConfig, "utf8")).toBe('{"memory":{"provider":"postgres"}}\n') + }) + + it("uses the preserved built-in config in the real learning command", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const configPath = resolve(directory, "config.json") + const config = JSON.stringify({ + schemaVersion: "replica.learning-config/v1", + memory: { provider: "sqlite" }, + consolidation: { consolidator: "none" }, + labeling: { options: { model: "example-model" } }, + }) + await writeFile(configPath, config) + + const error: unknown = await runLearningCommand( + ["doctor", "--dir", directory, "--repository", "github.com/repositories/123"], + { + cliPath: resolve("../packages/learning/bin/replica-learning.mjs"), + learningDatabaseUrl: + "postgres://learning-user:learning-password@postgres.example.invalid/learning", + environment: { PATH: process.env.PATH }, + }, + ).catch((failure: unknown) => failure) + + expect(error).toBeInstanceOf(LearningCommandError) + if (!(error instanceof LearningCommandError)) throw new Error("Expected a command failure.") + expect(error.code).toBe("learning_failed") + const result = error.result as { provider: { error: string }; consolidator: { source: string } } + expect(result.provider.error).toContain("sslmode=verify-full") + expect(result.consolidator.source).toBe("built-in none") + expect(await readFile(configPath, "utf8")).toBe(config) + }) + + it("clearly rejects custom learning modules in the real command", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const configPath = resolve(directory, "postgres-config.json") + + for (const selection of [ + { consolidation: { consolidator: { module: "./custom.mjs" } } }, + { labeling: { labeler: { module: "./custom.mjs" } } }, + ]) { + await writeFile( + configPath, + JSON.stringify({ schemaVersion: "replica.learning-config/v1", ...selection }), + ) + const error: unknown = await runLearningCommand( + ["doctor", "--dir", directory, "--repository", "github.com/repositories/123"], + { + cliPath: resolve("../packages/learning/bin/replica-learning.mjs"), + learningDatabaseUrl: "postgres://learning-user:learning-password@localhost/learning", + environment: { PATH: process.env.PATH }, + }, + ).catch((failure: unknown) => failure) + + expect(error).toBeInstanceOf(LearningCommandError) + if (!(error instanceof LearningCommandError)) throw new Error("Expected a command failure.") + expect(error.code).toBe("unsupported") + expect(error.message).toMatch(/built-in.*only/) + } + }) + + it("requires import when the original store directory is nonempty", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const history = resolve(directory, "history.sqlite") + await writeFile(history, "existing learning history") + + const result = (await runLearningCommand( + ["consolidate", "--dir", directory, "--repository", "github.com/repositories/123"], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: "postgres://learning-user:learning-password@localhost/learning", + environment: { PATH: process.env.PATH }, + }, + )) as { arguments: string[]; config: string; temporaryDirectory: string } + + const storeDirectory = result.arguments[2] + if (storeDirectory === undefined) throw new Error("Missing store directory argument.") + const relativeStore = relative(result.temporaryDirectory, storeDirectory) + expect(isAbsolute(storeDirectory)).toBe(true) + expect(isAbsolute(relativeStore)).toBe(false) + expect(relativeStore === ".." || relativeStore.startsWith(`..${sep}`)).toBe(false) + expect(result.arguments).toEqual([ + "consolidate", + "--dir", + storeDirectory, + "--repository", + "github.com/repositories/123", + "--json", + ]) + expect(JSON.parse(result.config)).toMatchObject({ + memory: { provider: "postgres", requireImport: true }, + }) + expect(await readFile(history, "utf8")).toBe("existing learning history") + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + + it("requires import for a nonempty store supplied with an equals sign", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + await writeFile(resolve(directory, "history.sqlite"), "existing learning history") + + const result = (await runLearningCommand( + ["consolidate", `--dir=${directory}`, "--repository", "github.com/repositories/123"], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: "postgres://learning-user:learning-password@localhost/learning", + environment: { PATH: process.env.PATH }, + }, + )) as { arguments: string[]; config: string; temporaryDirectory: string } + + const directoryArgument = result.arguments[1] + if (directoryArgument === undefined) throw new Error("Missing store directory argument.") + const storeDirectory = directoryArgument.slice("--dir=".length) + const relativeStore = relative(result.temporaryDirectory, storeDirectory) + expect(isAbsolute(storeDirectory)).toBe(true) + expect(isAbsolute(relativeStore)).toBe(false) + expect(relativeStore === ".." || relativeStore.startsWith(`..${sep}`)).toBe(false) + expect(result.arguments).toEqual([ + "consolidate", + `--dir=${storeDirectory}`, + "--repository", + "github.com/repositories/123", + "--json", + ]) + expect(JSON.parse(result.config)).toMatchObject({ + memory: { provider: "postgres", requireImport: true }, + }) + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + + it("does not pass the configured learning database URL to a command without a store", async () => { + const databaseUrl = "postgres://learning-user:learning-password@localhost/learning" + const result = (await runLearningCommand(["copilot", "status"], { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: databaseUrl, + environment: { + PATH: process.env.PATH, + COPILOT_GITHUB_TOKEN: "ambient-token-must-not-leak", + REPLICA_LEARNING_MIGRATION_DATABASE_URL: "migration-url-must-not-leak", + }, + })) as { arguments: string[]; environment: NodeJS.ProcessEnv; temporaryDirectory: string } + + expect(result.arguments).toEqual(["copilot", "status", "--json"]) + expect(result.environment).toEqual({ + PATH: process.env.PATH, + TMPDIR: result.temporaryDirectory, + }) + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + + it("retains the original store directory without an explicit learning database URL", async () => { + const result = (await runLearningCommand( + ["consolidate", "--dir", "/existing/sqlite", "--repository", "github.com/repositories/123"], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + environment: { PATH: process.env.PATH, REPLICA_LEARNING_DATABASE_URL: "ambient-url" }, + }, + )) as { arguments: string[]; environment: NodeJS.ProcessEnv } + + expect(result.arguments).toEqual([ + "consolidate", + "--dir", + "/existing/sqlite", + "--repository", + "github.com/repositories/123", + "--json", + ]) + expect(result.environment.REPLICA_LEARNING_DATABASE_URL).toBeUndefined() + }) + + it("removes the private Postgres config after a failed command", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const marker = resolve(directory, "command.json") + + await expect( + runLearningCommand( + ["consolidate", "--dir", "/existing/sqlite", "--fixture-fail-report", marker], + { + cliPath: resolve(fixtures, "report-runtime.mjs"), + learningDatabaseUrl: "postgres://learning-user:learning-password@localhost/learning", + environment: { PATH: process.env.PATH }, + }, + ), + ).rejects.toMatchObject({ code: "invalid_request" }) + + const result = JSON.parse(await readFile(marker, "utf8")) as { + arguments: string[] + config: string + temporaryDirectory: string + } + const storeDirectory = result.arguments[2] + if (storeDirectory === undefined) throw new Error("Missing store directory argument.") + const relativeStore = relative(result.temporaryDirectory, storeDirectory) + expect(isAbsolute(storeDirectory)).toBe(true) + expect(isAbsolute(relativeStore)).toBe(false) + expect(relativeStore === ".." || relativeStore.startsWith(`..${sep}`)).toBe(false) + expect(JSON.parse(result.config)).toMatchObject({ memory: { provider: "postgres" } }) + await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) + }) + it("preserves valid JSON progress from a failed command", async () => { await expect( runLearningCommand(["label"], { @@ -76,6 +496,118 @@ describe("runLearningCommand()", () => { }) }) + it("keeps the database URL and password out of command errors", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const cliPath = resolve(directory, "fail.mjs") + await writeFile( + cliPath, + ` + const databaseUrl = process.env.REPLICA_LEARNING_DATABASE_URL + const encodedPassword = new URL(databaseUrl).password + const password = decodeURIComponent(encodedPassword) + process.stdout.write(JSON.stringify({ + considered: 3, + details: { databaseUrl, password, [password]: encodedPassword }, + })) + process.stderr.write("error (learning_failed): Database connection failed: " + databaseUrl + " " + password + " " + encodedPassword) + process.exitCode = 1 + `, + ) + const password = "learning@password" + const encodedPassword = "learning%40password" + const databaseUrl = `postgres://learning-user:${encodedPassword}@localhost/learning` + + const error: unknown = await runLearningCommand( + ["label", "--dir", resolve(directory, "store")], + { + cliPath, + learningDatabaseUrl: databaseUrl, + environment: { PATH: process.env.PATH }, + }, + ).catch((failure: unknown) => failure) + + expect(error).toBeInstanceOf(LearningCommandError) + if (!(error instanceof LearningCommandError)) throw new Error("Expected a command failure.") + expect(error.code).toBe("learning_failed") + expect(error.result).toMatchObject({ considered: 3 }) + const result = JSON.stringify(error.result) ?? "" + for (const secret of [databaseUrl, password, encodedPassword]) { + expect.soft(error.message).not.toContain(secret) + expect.soft(result).not.toContain(secret) + } + }) + + it("hides query parameter passwords in command errors and progress", async () => { + const password = "query@password" + const encodedPassword = "query%40password" + const databaseUrl = `postgres://learning-user@localhost/learning?password=${encodedPassword}` + + const error = await runPasswordFailure(databaseUrl, password, encodedPassword) + + expect(error).toMatchObject({ + code: "learning_failed", + result: { considered: 3, receivedDatabaseUrl: true }, + }) + const result = JSON.stringify(error.result) ?? "" + for (const secret of [databaseUrl, password, encodedPassword]) { + expect.soft(error.message).not.toContain(secret) + expect.soft(result).not.toContain(secret) + } + }) + + it("hides Unix-socket URL passwords in command errors and progress", async () => { + const password = "socket@password" + const encodedPassword = "socket%40password" + const databaseUrl = `postgresql://learning-user:${encodedPassword}@/learning?host=%2Fvar%2Frun%2Fpostgresql` + + const error = await runPasswordFailure(databaseUrl, password, encodedPassword) + + expect(error).toMatchObject({ + code: "learning_failed", + result: { considered: 3, receivedDatabaseUrl: true }, + }) + const result = JSON.stringify(error.result) ?? "" + for (const secret of [databaseUrl, password, encodedPassword]) { + expect.soft(error.message).not.toContain(secret) + expect.soft(result).not.toContain(secret) + } + }) + + it("does not expose malformed successful output through the error or its cause", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const cliPath = resolve(directory, "malformed.mjs") + await writeFile( + cliPath, + ` + const databaseUrl = process.env.REPLICA_LEARNING_DATABASE_URL + process.stdout.write(new URL(databaseUrl).password) + `, + ) + const password = "parseSecret" + const databaseUrl = `postgres://learning-user:${password}@localhost/learning` + + const error: unknown = await runLearningCommand( + ["label", "--dir", resolve(directory, "store")], + { + cliPath, + learningDatabaseUrl: databaseUrl, + environment: { PATH: process.env.PATH }, + }, + ).catch((failure: unknown) => failure) + + expect(error).toBeInstanceOf(LearningCommandError) + if (!(error instanceof LearningCommandError)) throw new Error("Expected a command failure.") + expect(error.code).toBe("unreadable_output") + const diagnostic = inspect(error, { depth: null }) + for (const secret of [databaseUrl, password]) { + expect.soft(diagnostic).not.toContain(secret) + } + }) + it.each([ ["stdout", "outputLimit"], ["stderr", "errorLimit"], diff --git a/hub/server/integrations/learning/run-learning-command/index.ts b/hub/server/integrations/learning/run-learning-command/index.ts index 512519764..c3683b8aa 100644 --- a/hub/server/integrations/learning/run-learning-command/index.ts +++ b/hub/server/integrations/learning/run-learning-command/index.ts @@ -1,4 +1,5 @@ -import { chmod, mkdtemp, rm, stat } from "node:fs/promises" +import { constants } from "node:fs" +import { chmod, mkdtemp, open, readdir, rm, stat, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" import { join } from "node:path" import { spawn } from "node:child_process" @@ -6,7 +7,14 @@ import { spawn } from "node:child_process" import { LearningCommandError } from "./errors.ts" const passedVariables = new Set(["PATH", "HOME", "LANG", "LC_ALL", "TZ"]) -const childVariables = [...passedVariables, "COPILOT_GITHUB_TOKEN", "TMPDIR"] +const childVariables = [ + ...passedVariables, + "COPILOT_GITHUB_TOKEN", + "REPLICA_LEARNING_DATABASE_URL", + "REPLICA_LEARNING_HUB_POSTGRES", + "REPLICA_LEARNING_HUB_REQUIRE_IMPORT", + "TMPDIR", +] const bootstrap = ` import { pathToFileURL } from "node:url"; const allowed = new Set(${JSON.stringify(childVariables)}); @@ -24,6 +32,8 @@ function commandEnvironment( source: NodeJS.ProcessEnv, temporaryDirectory: string, githubToken?: string, + learningDatabaseUrl?: string, + requireImport = false, ) { const environment: NodeJS.ProcessEnv = { TMPDIR: temporaryDirectory } for (const [name, value] of Object.entries(source)) { @@ -32,15 +42,31 @@ function commandEnvironment( } } if (githubToken) environment.COPILOT_GITHUB_TOKEN = githubToken + if (learningDatabaseUrl) { + environment.REPLICA_LEARNING_DATABASE_URL = learningDatabaseUrl + environment.REPLICA_LEARNING_HUB_POSTGRES = "1" + if (requireImport) environment.REPLICA_LEARNING_HUB_REQUIRE_IMPORT = "1" + } return environment } +/** + * Tells whether signaling a process group failed only because nothing in it is + * running anymore. macOS answers EPERM instead of ESRCH while the group's exited + * processes wait to be cleaned up, so a finished command isn't mistaken for one + * Hub couldn't stop. + */ +function isStoppedGroupError(error: unknown) { + const code = (error as NodeJS.ErrnoException).code + return code === "ESRCH" || (code === "EPERM" && process.platform === "darwin") +} + function stopProcessTree(pid: number | undefined) { if (pid === undefined) return try { process.kill(-pid, "SIGKILL") } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error + if (!isStoppedGroupError(error)) throw error } } @@ -52,7 +78,7 @@ async function stopRemainingProcessGroup(pid: number | undefined) { try { process.kill(-pid, 0) } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ESRCH") return + if (isStoppedGroupError(error)) return throw error } await new Promise((resolve) => { @@ -69,6 +95,7 @@ export async function runLearningCommand( environment = process.env, errorLimit = 1024 * 1024, githubToken, + learningDatabaseUrl, nodePath = process.execPath, outputLimit = 16 * 1024 * 1024, signal, @@ -79,6 +106,7 @@ export async function runLearningCommand( environment?: NodeJS.ProcessEnv errorLimit?: number githubToken?: string + learningDatabaseUrl?: string nodePath?: string outputLimit?: number signal?: AbortSignal @@ -97,14 +125,139 @@ export async function runLearningCommand( const temporaryDirectory = await mkdtemp(join(tmpdir(), "replica-learning-")) await chmod(temporaryDirectory, 0o700) try { + const commandArguments = [...arguments_] + let hasDirectory = false + let requireImport = false + if (learningDatabaseUrl) { + let existingConfig: Buffer | undefined + async function preserveExistingStore(directory: string) { + let entries: string[] + try { + entries = await readdir(directory) + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return + throw error + } + if (entries.some((name) => name !== "postgres-config.json")) requireImport = true + if (entries.includes("config.json") && entries.includes("postgres-config.json")) + throw new LearningCommandError( + "invalid_request", + "Keep only one learning configuration for this repository.", + ) + const name = entries.includes("postgres-config.json") + ? "postgres-config.json" + : entries.includes("config.json") + ? "config.json" + : undefined + if (name) { + const handle = await open( + join(directory, name), + constants.O_RDONLY | constants.O_NOFOLLOW, + ) + try { + const info = await handle.stat() + if (!info.isFile() || info.nlink !== 1) + throw new LearningCommandError( + "invalid_request", + "Learning configuration is invalid.", + ) + existingConfig = await handle.readFile() + } finally { + await handle.close() + } + } + } + for (let index = 0; index < commandArguments.length; index += 1) { + const argument = commandArguments[index] + if (argument === "--dir") { + if (hasDirectory) + throw new LearningCommandError("invalid_request", "Give one learning directory.") + const directory = commandArguments[index + 1] + if (!directory || directory.startsWith("--")) + throw new LearningCommandError("invalid_request", "The learning directory is missing.") + await preserveExistingStore(directory) + commandArguments[++index] = temporaryDirectory + hasDirectory = true + } else if (argument?.startsWith("--dir=")) { + if (hasDirectory) + throw new LearningCommandError("invalid_request", "Give one learning directory.") + await preserveExistingStore(argument.slice("--dir=".length)) + commandArguments[index] = `--dir=${temporaryDirectory}` + hasDirectory = true + } + } + if (hasDirectory) { + await writeFile( + join(temporaryDirectory, "config.json"), + existingConfig ?? + JSON.stringify({ + schemaVersion: "replica.learning-config/v1", + memory: { provider: "postgres", ...(requireImport ? { requireImport: true } : {}) }, + consolidation: { + options: { + signals: [ + "visual_quality", + "accessibility", + "usability", + "content", + "interaction", + ], + }, + }, + }), + { mode: 0o600, flag: "wx" }, + ) + } + } + const secrets = [learningDatabaseUrl, githubToken].filter((value): value is string => + Boolean(value), + ) + let hideDiagnostics = false + if (learningDatabaseUrl) { + try { + let url: URL + try { + url = new URL(learningDatabaseUrl) + } catch { + url = new URL(learningDatabaseUrl.replace("@/", "@replica-placeholder/")) + } + if (!["postgres:", "postgresql:"].includes(url.protocol)) throw new Error() + if (url.password) secrets.push(url.password, decodeURIComponent(url.password)) + for (const part of url.search.slice(1).split("&")) { + const password = new URLSearchParams(part).get("password") + if (password) secrets.push(password, part.slice(part.indexOf("=") + 1)) + } + } catch { + hideDiagnostics = true + } + } + secrets.sort((first, second) => second.length - first.length) + function redact(value: string) { + return secrets.reduce((text, secret) => text.replaceAll(secret, "[redacted]"), value) + } + function redactResult(value: unknown): unknown { + if (typeof value === "string") return redact(value) + if (Array.isArray(value)) return value.map(redactResult) + if (value && typeof value === "object") + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [redact(key), redactResult(item)]), + ) + return value + } return await new Promise((resolve, reject) => { const child = spawn( nodePath, - ["--input-type=module", "--eval", bootstrap, cliPath, ...arguments_, "--json"], + ["--input-type=module", "--eval", bootstrap, cliPath, ...commandArguments, "--json"], { cwd: directory ?? temporaryDirectory, detached: true, - env: commandEnvironment(environment, temporaryDirectory, githubToken), + env: commandEnvironment( + environment, + temporaryDirectory, + githubToken, + hasDirectory ? learningDatabaseUrl : undefined, + requireImport, + ), stdio: ["ignore", "pipe", "pipe"], }, ) @@ -212,13 +365,17 @@ export async function runLearningCommand( return } const stdout = Buffer.concat(output).toString("utf8") - const stderr = Buffer.concat(errors).toString("utf8").trim() + const stderr = redact(Buffer.concat(errors).toString("utf8").trim()) if (code !== 0) { + if (hideDiagnostics) { + reject(new LearningCommandError("learning_failed", "replica-learning failed.")) + return + } const match = errorPattern.exec(stderr) let result: unknown if (stdout.trim()) { try { - result = JSON.parse(stdout) + result = redactResult(JSON.parse(stdout)) } catch { result = undefined } @@ -236,12 +393,11 @@ export async function runLearningCommand( } try { resolve(JSON.parse(stdout)) - } catch (error) { + } catch { reject( new LearningCommandError( "unreadable_output", "replica-learning returned output Hub could not read.", - { cause: error }, ), ) } diff --git a/hub/server/integrations/postgres/with-learning-execution-lock/index.ts b/hub/server/integrations/postgres/with-learning-execution-lock/index.ts index 9db35b37b..86d772051 100644 --- a/hub/server/integrations/postgres/with-learning-execution-lock/index.ts +++ b/hub/server/integrations/postgres/with-learning-execution-lock/index.ts @@ -11,6 +11,7 @@ export async function withLearningExecutionLock({ run: ( signal: AbortSignal, controls: { + client: Pick runWithoutRepositoryAuthorityLock: ( operation: () => Promise, ) => Promise @@ -49,6 +50,7 @@ export async function withLearningExecutionLock({ } controller.signal.throwIfAborted() running = run(controller.signal, { + client, runWithoutRepositoryAuthorityLock: async (operation: () => Promise) => { const unlocked = await client.query<{ unlocked: boolean }>( "SELECT pg_advisory_unlock_shared(1919242348, 3) AS unlocked", diff --git a/hub/server/repositories/decision-review-snapshots/get-decision-review-snapshot/index.ts b/hub/server/repositories/decision-review-snapshots/get-decision-review-snapshot/index.ts new file mode 100644 index 000000000..6ad081acc --- /dev/null +++ b/hub/server/repositories/decision-review-snapshots/get-decision-review-snapshot/index.ts @@ -0,0 +1,11 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export function getDecisionReviewSnapshot( + database: Pick, + repositoryId: string, +) { + return database.decisionReviewSnapshot.findUnique({ + where: { repositoryId }, + select: { digest: true, snapshotId: true, capturedAt: true }, + }) +} diff --git a/hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.db.test.ts b/hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.db.test.ts new file mode 100644 index 000000000..d8372c392 --- /dev/null +++ b/hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.db.test.ts @@ -0,0 +1,46 @@ +import { randomUUID } from "node:crypto" +import pg from "pg" +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { getDatabaseUrl } from "../../../../test/database/get-database-url" +import { saveDecisionReviewSnapshot } from "." + +describe("saveDecisionReviewSnapshot()", () => { + it("keeps the winning checkpoint when a stale writer tries to create or update it", async () => { + const repository = await prisma.repository.create({ + data: { nameWithOwner: "team/checkout", defaultBranch: "main" }, + }) + const first = { + digest: `sha256:${"a".repeat(64)}`, + snapshotId: randomUUID(), + capturedAt: new Date("2026-01-01T00:00:00.000Z"), + } + const changed = { + digest: `sha256:${"b".repeat(64)}`, + snapshotId: randomUUID(), + capturedAt: new Date("2026-01-01T00:01:00.000Z"), + } + const winner = { + ...first, + snapshotId: randomUUID(), + capturedAt: new Date("2026-01-01T00:02:00.000Z"), + } + + const client = new pg.Client({ connectionString: getDatabaseUrl() }) + await client.connect() + try { + expect(await saveDecisionReviewSnapshot(client, repository.id, first, null)).toBe(true) + expect(await saveDecisionReviewSnapshot(client, repository.id, changed, first)).toBe(true) + expect(await saveDecisionReviewSnapshot(client, repository.id, winner, changed)).toBe(true) + + expect(await saveDecisionReviewSnapshot(client, repository.id, changed, null)).toBe(false) + expect(await saveDecisionReviewSnapshot(client, repository.id, changed, first)).toBe(false) + await expect( + prisma.decisionReviewSnapshot.findUniqueOrThrow({ where: { repositoryId: repository.id } }), + ).resolves.toMatchObject(winner) + } finally { + await client.end() + } + }) +}) diff --git a/hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.ts b/hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.ts new file mode 100644 index 000000000..efb8146a5 --- /dev/null +++ b/hub/server/repositories/decision-review-snapshots/save-decision-review-snapshot/index.ts @@ -0,0 +1,41 @@ +import { randomUUID } from "node:crypto" +import type { Client } from "pg" + +interface Snapshot { + digest: string + snapshotId: string + capturedAt: Date +} + +/** Keep the checkpoint write on the session that owns the execution lock. */ +export async function saveDecisionReviewSnapshot( + database: Pick, + repositoryId: string, + snapshot: Snapshot, + previous: Snapshot | null, +) { + // Prisma cannot use the session holding the advisory lock. + const result = previous + ? await database.query( + `UPDATE decision_review_snapshots + SET digest = $1, snapshot_id = $2, captured_at = $3, updated_at = CURRENT_TIMESTAMP + WHERE repository_id = $4 AND digest = $5 AND snapshot_id = $6 AND captured_at = $7`, + [ + snapshot.digest, + snapshot.snapshotId, + snapshot.capturedAt, + repositoryId, + previous.digest, + previous.snapshotId, + previous.capturedAt, + ], + ) + : await database.query( + `INSERT INTO decision_review_snapshots + (id, repository_id, digest, snapshot_id, captured_at) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (repository_id) DO NOTHING`, + [randomUUID(), repositoryId, snapshot.digest, snapshot.snapshotId, snapshot.capturedAt], + ) + return result.rowCount === 1 +} diff --git a/hub/server/repositories/learning-runs/is-learning-run-repository-available/index.ts b/hub/server/repositories/learning-runs/is-learning-run-repository-available/index.ts index 128f8be24..d85bfcca6 100644 --- a/hub/server/repositories/learning-runs/is-learning-run-repository-available/index.ts +++ b/hub/server/repositories/learning-runs/is-learning-run-repository-available/index.ts @@ -10,7 +10,7 @@ export async function isLearningRunRepositoryAvailable( where: { id: repositoryId, removedAt: null, - ...(requireGitHubId ? { githubRepositoryId: { not: null } } : {}), + ...(requireGitHubId ? { githubRepositoryId: { gt: 0n } } : {}), }, })) === 1 ) diff --git a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts index 0b92e14f2..2d3324ab4 100644 --- a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts +++ b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.db.test.ts @@ -323,7 +323,12 @@ describe("listDueLearningRepositories()", () => { it("finds review evidence committed after snapshot capture with an earlier timestamp", async () => { const repositoryId = randomUUID() await prisma.repository.create({ - data: { id: repositoryId, nameWithOwner: "team/during-run", defaultBranch: "main" }, + data: { + id: repositoryId, + githubRepositoryId: 107n, + nameWithOwner: "team/during-run", + defaultBranch: "main", + }, }) const thread = await createReviewEvidence({ repositoryId, diff --git a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts index cc388f0b7..cef8e8719 100644 --- a/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts +++ b/hub/server/repositories/learning-runs/list-due-learning-repositories/index.ts @@ -62,7 +62,7 @@ export function listDueLearningRepositories( WHERE review_threads.repository_id = repositories.id ) review_activity ON true WHERE repositories.removed_at IS NULL - AND (${input.requireGitHubId} = false OR repositories.github_repository_id IS NOT NULL) + AND (${input.requireGitHubId} = false OR repositories.github_repository_id > 0) AND NOT EXISTS ( SELECT 1 FROM learning_runs active_runs diff --git a/hub/server/repositories/repository-access/find-repository-github-id/index.ts b/hub/server/repositories/repository-access/find-repository-github-id/index.ts new file mode 100644 index 000000000..09e16f934 --- /dev/null +++ b/hub/server/repositories/repository-access/find-repository-github-id/index.ts @@ -0,0 +1,11 @@ +import type { Prisma } from "../../../generated/prisma/client.ts" + +export async function findRepositoryGitHubId( + database: Pick, + repositoryId: string, +) { + return await database.repository.findUnique({ + where: { id: repositoryId }, + select: { githubRepositoryId: true }, + }) +} diff --git a/hub/server/routes/api/learnings/create-learnings-route-dependencies/index.ts b/hub/server/routes/api/learnings/create-learnings-route-dependencies/index.ts index 07136ee68..67c75e14b 100644 --- a/hub/server/routes/api/learnings/create-learnings-route-dependencies/index.ts +++ b/hub/server/routes/api/learnings/create-learnings-route-dependencies/index.ts @@ -7,6 +7,7 @@ import { ReviewCommentError } from "../../../../domains/review-comments/errors.t import { executeLearningDecision } from "../../../../domains/learning/execute-learning-decision/index.ts" import { createReviewCommentLearningSource } from "../../../../domains/learning/create-review-comment-learning-source/index.ts" import { getLearningOverview } from "../../../../domains/learning/get-learning-overview/index.ts" +import { getLearningRepositoryScope } from "../../../../domains/learning/get-learning-repository-scope/index.ts" import { learningRunJob } from "../../../../domains/learning/jobs/learning-run.ts" import { redactReviewCommentJob } from "../../../../domains/learning/jobs/redact-review-comment.ts" import type { ReviewCommentLearningSource } from "../../../../domains/learning/review-comment-learning-source/types.ts" @@ -139,15 +140,25 @@ export async function createLearningsRouteDependencies( }, findRepository, getOverview: async ({ repositoryId, viewer }) => { + const repositoryScope = await getLearningRepositoryScope(prisma, repositoryId) try { - return await getLearningOverview({ + const overview = await getLearningOverview({ ...configuration, evidenceSource: source, repositoryId, + repositoryScope, viewer, }) + if (repositoryScope !== (await getLearningRepositoryScope(prisma, repositoryId))) { + throw new LearningCommandError( + "repository_scope_unavailable", + "The repository learning scope changed. Try again.", + ) + } + return overview } catch (error) { if (!(error instanceof LearningCommandError)) throw error + if (error.code === "repository_scope_unavailable") throw error logger.warn( { learningFailureCode: error.code, repositoryId }, "Repository learning overview failed", @@ -187,6 +198,7 @@ export async function createLearningsRouteDependencies( "Repository administrator access is required.", ) } + await getLearningRepositoryScope(prisma, repositoryId) if ((await getCopilot()).state !== "connected") { throw new LearningsError( 409, @@ -198,6 +210,12 @@ export async function createLearningsRouteDependencies( try { snapshot = await source.captureCompleteSnapshot({ repositoryId }) } catch (error) { + if ( + error instanceof LearningCommandError && + error.code === "repository_scope_unavailable" + ) { + throw error + } if (error instanceof ReviewCommentError && error.code === "not_found") { throw new LearningsError(404, "repository_not_found", "Repository not found.", { cause: error, @@ -228,6 +246,14 @@ export async function createLearningsRouteDependencies( }) return null } + if ( + snapshot.repositoryScope !== (await getLearningRepositoryScope(transaction, repositoryId)) + ) { + throw new LearningCommandError( + "repository_scope_unavailable", + "The repository learning scope changed. Try again.", + ) + } const result = await createLearningRun(transaction, { repositoryId, requestedById, @@ -352,6 +378,10 @@ export async function createLearningsRouteDependencies( ) { return false } + const repositoryScope = await getLearningRepositoryScope( + transaction, + input.repositoryId, + ) await createLearningDecisionOperation(transaction, { id: operationId, actorMembershipId, @@ -369,7 +399,7 @@ export async function createLearningsRouteDependencies( outcome: "requested", repositoryId: input.repositoryId, }) - return true + return repositoryScope }) if (!authorized) { await createSecurityAudit(prisma, { @@ -390,6 +420,7 @@ export async function createLearningsRouteDependencies( return executeLearningDecision({ ...configuration, ...input, + repositoryScope: authorized, operationId, signal, }) diff --git a/hub/server/routes/api/learnings/index.test.ts b/hub/server/routes/api/learnings/index.test.ts index 6e3ccb5ff..8fd4419e6 100644 --- a/hub/server/routes/api/learnings/index.test.ts +++ b/hub/server/routes/api/learnings/index.test.ts @@ -159,6 +159,8 @@ describe("learning routes", () => { }) it("maps the repository administrator overview for a Hub member", async () => { + const loadError = + "Rebuild learning mem_111111111111111111111111. Follow up on export exp_222222222222222222222222 at private/exports/team.json." const evidence = { eventId: "review-comment-17", commentId: 17, @@ -198,7 +200,7 @@ describe("learning routes", () => { const deps = dependencies({ automaticRunsEnabled: true, getOverview: vi.fn().mockResolvedValue({ - loadError: null, + loadError, identityReviewCount: 1, suggestions: [suggestion], learnings: [], @@ -233,7 +235,7 @@ describe("learning routes", () => { automaticRunsEnabled: true, usageCredits: "0.021", runAvailable: false, - loadError: null, + loadError, identityReviewCount: 1, suggestions: [suggestion], learnings: [], diff --git a/hub/server/routes/api/learnings/respond-learning-error/index.ts b/hub/server/routes/api/learnings/respond-learning-error/index.ts index f93a9688a..cb5856bd3 100644 --- a/hub/server/routes/api/learnings/respond-learning-error/index.ts +++ b/hub/server/routes/api/learnings/respond-learning-error/index.ts @@ -12,7 +12,12 @@ export function respondLearningError(response: Response, error: unknown): boolea return true } if (error instanceof LearningCommandError) { - const status = staleCodes.has(error.code) ? 409 : notFoundCodes.has(error.code) ? 404 : 422 + const status = + staleCodes.has(error.code) || error.code === "repository_scope_unavailable" + ? 409 + : notFoundCodes.has(error.code) + ? 404 + : 422 response.status(status).json({ code: error.code, error: error.message }) return true } diff --git a/hub/server/scripts/azure-entrypoint/load-secret-environment/index.test.ts b/hub/server/scripts/azure-entrypoint/load-secret-environment/index.test.ts index 4a983bb1d..7a08de1c8 100644 --- a/hub/server/scripts/azure-entrypoint/load-secret-environment/index.test.ts +++ b/hub/server/scripts/azure-entrypoint/load-secret-environment/index.test.ts @@ -135,12 +135,14 @@ describe("loadAzureSecretEnvironment()", () => { vi.useFakeTimers() const version = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" const databaseUrl = `https://fixture.vault.azure.net/secrets/database/${version}` + const learningUrl = `https://fixture.vault.azure.net/secrets/learning/${version}` const migrationUrl = `https://fixture.vault.azure.net/secrets/migration/${version}` const runtimeUrl = `https://fixture.vault.azure.net/secrets/runtime/${version}` const environment: NodeJS.ProcessEnv = { AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000001", AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ DATABASE_URL: databaseUrl, + HUB_LEARNING_PASSWORD: learningUrl, HUB_MIGRATION_PASSWORD: migrationUrl, HUB_RUNTIME_PASSWORD: runtimeUrl, }), @@ -155,9 +157,11 @@ describe("loadAzureSecretEnvironment()", () => { return Promise.resolve( url === databaseUrl ? "synthetic-database-url" - : url === migrationUrl - ? "synthetic-migration-password" - : "synthetic-runtime-password", + : url === learningUrl + ? "synthetic-learning-password" + : url === migrationUrl + ? "synthetic-migration-password" + : "synthetic-runtime-password", ) }) @@ -176,6 +180,7 @@ describe("loadAzureSecretEnvironment()", () => { expect(environment).toEqual({ ...before, DATABASE_URL: "synthetic-database-url", + HUB_LEARNING_PASSWORD: "synthetic-learning-password", HUB_MIGRATION_PASSWORD: "synthetic-migration-password", HUB_RUNTIME_PASSWORD: "synthetic-runtime-password", }) diff --git a/hub/server/scripts/azure-entrypoint/run/index.test.ts b/hub/server/scripts/azure-entrypoint/run/index.test.ts index 8ff0ac778..2690468f9 100644 --- a/hub/server/scripts/azure-entrypoint/run/index.test.ts +++ b/hub/server/scripts/azure-entrypoint/run/index.test.ts @@ -1,6 +1,7 @@ import { beforeEach, describe, expect, it, onTestFinished, vi } from "vitest" import type { provisionDatabaseAccess } from "../../provision-database-access" +import type { provisionLearningDatabaseAccess } from "../../provision-learning-database-access" import type { loadAzureSecretEnvironment } from "../load-secret-environment" const mocks = vi.hoisted(() => ({ @@ -11,6 +12,8 @@ const mocks = vi.hoisted(() => ({ loggerImported: vi.fn(), setup: vi.fn<() => Promise>(), provision: vi.fn(), + provisionLearning: vi.fn(), + provisionLearningImported: vi.fn(), repairImported: vi.fn(), checkImported: vi.fn(), replayImported: vi.fn(), @@ -42,6 +45,10 @@ describe("runAzureEntrypoint()", () => { mocks.provisionImported() return { provisionDatabaseAccess: mocks.provision } }) + vi.doMock("../../provision-learning-database-access", () => { + mocks.provisionLearningImported() + return { provisionLearningDatabaseAccess: mocks.provisionLearning } + }) vi.doMock("../../../integrations/pino", () => { mocks.loggerImported() return { logger: { info: mocks.info } } @@ -113,6 +120,7 @@ describe("runAzureEntrypoint()", () => { DATABASE_URL: "postgresql://synthetic-admin:fixture@database.invalid/replica", HUB_MIGRATION_PASSWORD: "synthetic-migration-password", HUB_RUNTIME_PASSWORD: "synthetic-runtime-password", + HUB_LEARNING_PASSWORD: "synthetic-learning-password", } const environment: NodeJS.ProcessEnv = { NODE_ENV: "production", @@ -186,6 +194,7 @@ describe("runAzureEntrypoint()", () => { databaseUrl: secrets.DATABASE_URL, migrationPassword: secrets.HUB_MIGRATION_PASSWORD, runtimePassword: secrets.HUB_RUNTIME_PASSWORD, + learningPassword: secrets.HUB_LEARNING_PASSWORD, }) expect(mocks.info).toHaveBeenCalledTimes(1) expect(JSON.stringify(mocks.info.mock.calls)).not.toMatch(/synthetic-|postgresql:/) @@ -196,6 +205,32 @@ describe("runAzureEntrypoint()", () => { }, ) + it("provisions only the learning role for an existing installation", async () => { + const originalEnvironment = process.env + process.env = { NODE_ENV: "production" } + onTestFinished(() => { + process.env = originalEnvironment + }) + mocks.loadSecrets.mockImplementation((environment, target) => { + expect(target).toBe("provision-learning") + expect(mocks.provisionLearningImported).not.toHaveBeenCalled() + environment.DATABASE_URL = "postgresql://admin@database.invalid/replica" + environment.HUB_LEARNING_PASSWORD = "synthetic-learning-password" + return Promise.resolve() + }) + mocks.provisionLearning.mockResolvedValue(undefined) + + await runAzureEntrypoint("provision-learning") + + expect(mocks.provisionLearning).toHaveBeenCalledExactlyOnceWith({ + databaseUrl: "postgresql://admin@database.invalid/replica", + learningPassword: "synthetic-learning-password", + }) + expect(mocks.provisionImported).not.toHaveBeenCalled() + expect(mocks.provision).not.toHaveBeenCalled() + expect(mocks.setupImported).not.toHaveBeenCalled() + }) + it.each(["runtime", "setup", "provision"] as const)( "does not import any workload or begin database work after %s secret loading fails", async (target) => { diff --git a/hub/server/scripts/azure-entrypoint/run/index.ts b/hub/server/scripts/azure-entrypoint/run/index.ts index daa739bf1..2def6c533 100644 --- a/hub/server/scripts/azure-entrypoint/run/index.ts +++ b/hub/server/scripts/azure-entrypoint/run/index.ts @@ -5,7 +5,13 @@ export async function runAzureEntrypoint(target: string | undefined): Promise( + `SELECT EXISTS ( + SELECT 1 FROM pg_namespace + WHERE nspname = 'public' AND nspowner = (SELECT oid FROM pg_roles WHERE rolname = 'replica_migration') + ) AND EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'replica_runtime') AS ready`, + ) + if (!existing.rows[0]!.ready) + throw new Error("Learning provisioning requires an existing provisioned Hub database.") + const database = await client.query<{ name: string }>("SELECT current_database() AS name") + await client.query( + `CREATE ROLE replica_learning_runtime LOGIN NOINHERIT NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD ${pg.escapeLiteral(learningPassword)}`, + ) + await client.query( + `GRANT CONNECT ON DATABASE ${pg.escapeIdentifier(database.rows[0]!.name)} TO replica_learning_runtime`, + ) + await client.query("COMMIT") + } finally { + await client.end() + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + try { + await provisionLearningDatabaseAccess({ + databaseUrl: process.env.DATABASE_URL ?? "", + learningPassword: process.env.HUB_LEARNING_PASSWORD ?? "", + }) + logger.info("Learning database access provisioned") + } catch { + logger.fatal("Learning database provisioning failed; check the existing database and roles") + process.exitCode = 1 + } +} diff --git a/hub/server/scripts/seed-decision-model-walkthrough/index.ts b/hub/server/scripts/seed-decision-model-walkthrough/index.ts index 4e25c941b..731331ebc 100644 --- a/hub/server/scripts/seed-decision-model-walkthrough/index.ts +++ b/hub/server/scripts/seed-decision-model-walkthrough/index.ts @@ -6,16 +6,19 @@ import { join, resolve } from "node:path" import { createConfiguredArtifactStorage } from "../../domains/artifacts/create-configured-artifact-storage/index.ts" import { readDecisionRuntimeConfiguration } from "../../domains/decision-model/read-decision-runtime-configuration/index.ts" import { createHubReviewCollection } from "../../domains/learning/create-hub-review-collection/index.ts" +import { learningStoreArguments } from "../../domains/learning/learning-store-arguments/index.ts" import { prepareLearningStore } from "../../domains/learning/prepare-learning-store/index.ts" import { readLearningConfiguration } from "../../domains/learning/read-learning-configuration/index.ts" import { captureRepositoryReviewSnapshot } from "../../domains/review-comments/capture-repository-review-snapshot/index.ts" import { runLearningCommand } from "../../integrations/learning/run-learning-command/index.ts" import { createDecisionRuntimeClient } from "../../integrations/decision-runtime/create-decision-runtime-client/index.ts" import { localDeveloperIdentity } from "../../utils/local-developer-identity/index.ts" +import { validatePrivateStorageRoot } from "../../utils/validate-private-storage-root/index.ts" import { createSolidPng } from "./create-solid-png/index.ts" import { validateResetState, validateSeedEnvironment } from "./validate-seed-environment/index.ts" const repositoryId = "00000000-0000-4000-8000-000000000121" +const repositoryLocalPath = "/workspaces/replica/hub/.local/prototypes/decision-walkthrough" const reviewerUserId = "00000000-0000-4000-8000-000000000122" const reviewerProfileId = "00000000-0000-4000-8000-000000000123" const prototypeIds = [ @@ -77,14 +80,52 @@ if (!localMembership || localMembership.lifecycle !== "ACTIVE") { const storage = await createConfiguredArtifactStorage(process.env) const learning = await readLearningConfiguration(process.env) -const preparedStore = await prepareLearningStore({ - applicationRoot: process.cwd(), - repositoryKey: repositoryId, - repositoryScope: `github.com/repositories/${repositoryId}`, - root: learning.root, - staticDirectories: learning.staticDirectories, +const directory = await validatePrivateStorageRoot( + resolve(learning.root, "repositories", repositoryId), + { + applicationRoot: process.cwd(), + excludedDirectories: learning.staticDirectories, + name: "REPLICA_LEARNING_ROOT", + publicRoot: resolve(process.cwd(), "public"), + }, +) +validateSeedEnvironment(process.env, directory, learning.root) +const githubId = process.env.REPLICA_DECISION_WALKTHROUGH_GITHUB_ID +const githubName = process.env.REPLICA_DECISION_WALKTHROUGH_GITHUB_REPOSITORY +if ( + !githubId || + !/^[1-9][0-9]*$/.test(githubId) || + BigInt(githubId) > 9223372036854775807n || + !githubName || + !/^[a-zA-Z0-9_.-]{1,100}\/[a-zA-Z0-9_.-]{1,100}$/.test(githubName) +) { + await prisma.$disconnect() + throw new Error( + "Set the verified GitHub repository name and ID for the dedicated walkthrough repository.", + ) +} +const githubRepositoryId = BigInt(githubId) +const existingRepository = await prisma.repository.findUnique({ + where: { id: repositoryId }, + select: { githubRepositoryId: true, localPath: true, nameWithOwner: true }, +}) +const existingOwner = await prisma.repository.findUnique({ + where: { githubRepositoryId }, + select: { id: true }, }) -validateSeedEnvironment(process.env, preparedStore.directory, learning.root) +if ( + (existingOwner && existingOwner.id !== repositoryId) || + (existingRepository && existingRepository.localPath !== repositoryLocalPath) || + (existingRepository?.githubRepositoryId != null && + existingRepository.githubRepositoryId !== githubRepositoryId) || + (existingRepository?.githubRepositoryId == null && + existingRepository && + existingRepository.nameWithOwner !== "local/decision-walkthrough") +) { + await prisma.$disconnect() + throw new Error("The walkthrough repository ID is already bound to different repository data.") +} +const repositoryScope = `github.com/repositories/${githubId}` const activeJobs = await prisma.decisionTrainingJob.count({ where: { repositoryId, @@ -100,7 +141,7 @@ if (activeJobs) { } } const runtimeConfiguration = readDecisionRuntimeConfiguration(process.env) -if (!runtimeConfiguration) { +if (!runtimeConfiguration || runtimeConfiguration.environment !== "fixture") { await prisma.$disconnect() throw new Error("Configure the fixture decision runtime before reseeding.") } @@ -111,21 +152,40 @@ try { await prisma.$disconnect() throw error } -await rm(preparedStore.directory, { force: true, recursive: true }) -const store = await prepareLearningStore({ - applicationRoot: process.cwd(), - repositoryKey: repositoryId, - repositoryScope: `github.com/repositories/${repositoryId}`, - root: learning.root, - staticDirectories: learning.staticDirectories, -}) - const startedAt = new Date("2026-11-18T16:00:00.000Z") const finishedAt = new Date("2026-11-18T16:05:00.000Z") const fixedAt = new Date("2026-11-18T17:00:00.000Z") const resolvedAt = new Date("2026-11-18T18:00:00.000Z") await prisma.$transaction(async (database) => { + const updatedRepository = await database.repository.updateMany({ + where: { + id: repositoryId, + localPath: repositoryLocalPath, + OR: [ + { githubRepositoryId }, + { githubRepositoryId: null, nameWithOwner: "local/decision-walkthrough" }, + ], + }, + data: { + githubRepositoryId, + nameWithOwner: githubName, + defaultBranch: "main", + localPath: repositoryLocalPath, + removedAt: null, + }, + }) + if (updatedRepository.count === 0) { + await database.repository.create({ + data: { + id: repositoryId, + githubRepositoryId, + nameWithOwner: githubName, + defaultBranch: "main", + localPath: repositoryLocalPath, + }, + }) + } await database.decisionBuildEvaluation.deleteMany({ where: { repositoryId } }) await database.decisionModelPromotion.deleteMany({ where: { repositoryId } }) await database.decisionCandidate.deleteMany({ where: { repositoryId } }) @@ -165,21 +225,6 @@ await prisma.$transaction(async (database) => { }, update: { provider: "local", login: "mona", name: "Mona" }, }) - await database.repository.upsert({ - where: { id: repositoryId }, - create: { - id: repositoryId, - nameWithOwner: "local/decision-walkthrough", - defaultBranch: "main", - localPath: "/workspaces/replica/hub/.local/prototypes/decision-walkthrough", - }, - update: { - nameWithOwner: "local/decision-walkthrough", - defaultBranch: "main", - localPath: "/workspaces/replica/hub/.local/prototypes/decision-walkthrough", - removedAt: null, - }, - }) await database.repositoryAccessGrant.upsert({ where: { membershipId_repositoryId: { @@ -338,6 +383,15 @@ await prisma.$transaction(async (database) => { } }) +await rm(directory, { force: true, recursive: true }) +const store = await prepareLearningStore({ + applicationRoot: process.cwd(), + repositoryKey: repositoryId, + repositoryScope, + root: learning.root, + staticDirectories: learning.staticDirectories, +}) + const screenshotPaths = [ ["screenshots/desktop.png", 1440, 900, [224, 240, 255]], ["screenshots/desktop-dark.png", 1440, 900, [24, 35, 54]], @@ -363,7 +417,11 @@ for (const [buildIndex, buildId] of buildIds.entries()) { } const snapshot = await captureRepositoryReviewSnapshot(prisma, repositoryId, resolvedAt) -const collection = createHubReviewCollection(snapshot, "http://127.0.0.1:5173").collection +const collection = createHubReviewCollection( + snapshot, + "http://127.0.0.1:5173", + repositoryScope, +).collection const temporary = await mkdtemp(join(tmpdir(), "replica-decision-walkthrough-")) try { const collectionPath = join(temporary, "reviews.json") @@ -395,7 +453,7 @@ try { directory: process.cwd(), nodePath: learning.nodePath, } - const scope = ["--dir", store.directory, "--repository", store.repositoryScope] + const scope = learningStoreArguments(store) const grant = (await runLearningCommand( [ "grants", diff --git a/hub/server/scripts/setup/index.test.ts b/hub/server/scripts/setup/index.test.ts index 27999799f..90945dbab 100644 --- a/hub/server/scripts/setup/index.test.ts +++ b/hub/server/scripts/setup/index.test.ts @@ -1,10 +1,13 @@ import { spawn, type ChildProcess } from "node:child_process" import { EventEmitter } from "node:events" +import { resolve } from "node:path" import { fileURLToPath } from "node:url" import { describe, expect, it, vi } from "vitest" import { setup } from "." +const lock = vi.hoisted(() => ({ active: false })) + vi.mock("dotenv/config", () => ({})) vi.mock("node:child_process", () => ({ spawn: vi.fn() })) vi.mock("../../integrations/pino", () => ({ logger: { info: vi.fn() } })) @@ -15,13 +18,22 @@ vi.mock("../../integrations/postgres/with-setup-lock", () => ({ }: { run: (signal: AbortSignal) => Promise signal: AbortSignal - }) => run(signal), + }) => { + lock.active = true + try { + await run(signal) + } finally { + lock.active = false + } + }, })) describe("setup()", () => { it("passes native job and runtime-grant script paths to Node", async () => { vi.stubEnv("DATABASE_URL", "postgresql://replica_migration@localhost/replica") vi.stubEnv("DATABASE_RUNTIME_ROLE", "replica_runtime") + vi.stubEnv("REPLICA_LEARNING_MIGRATION_DATABASE_URL", undefined) + vi.stubEnv("REPLICA_LEARNING_RUNTIME_ROLE", undefined) vi.mocked(spawn).mockImplementation(() => { const child = new EventEmitter() as ChildProcess child.kill = vi.fn(() => true) @@ -31,6 +43,7 @@ describe("setup()", () => { await setup() + expect(spawn).toHaveBeenCalledTimes(3) expect(spawn).toHaveBeenNthCalledWith( 2, process.execPath, @@ -44,4 +57,37 @@ describe("setup()", () => { { stdio: "ignore" }, ) }) + + it("migrates and grants the learning database under the setup lock", async () => { + const migrationUrl = "postgresql://learning_migration@localhost/replica" + vi.stubEnv("DATABASE_URL", "postgresql://replica_migration@localhost/replica") + vi.stubEnv("DATABASE_RUNTIME_ROLE", undefined) + vi.stubEnv("REPLICA_LEARNING_MIGRATION_DATABASE_URL", migrationUrl) + vi.stubEnv("REPLICA_LEARNING_RUNTIME_ROLE", "replica_learning_runtime") + vi.stubEnv("REPLICA_LEARNING_CLI", "learning-cli.mjs") + vi.mocked(spawn).mockImplementation((_command, arguments_) => { + expect(lock.active).toBe(true) + expect(arguments_).not.toContain(migrationUrl) + const child = new EventEmitter() as ChildProcess + child.kill = vi.fn(() => true) + queueMicrotask(() => child.emit("close", 0)) + return child + }) + + await setup() + + expect(spawn).toHaveBeenCalledTimes(4) + expect(spawn).toHaveBeenNthCalledWith( + 3, + process.execPath, + [resolve("learning-cli.mjs"), "migrate"], + { stdio: "ignore" }, + ) + expect(spawn).toHaveBeenNthCalledWith( + 4, + process.execPath, + [fileURLToPath(new URL("../grant-learning-database-access/index.ts", import.meta.url))], + { stdio: "ignore" }, + ) + }) }) diff --git a/hub/server/scripts/setup/index.ts b/hub/server/scripts/setup/index.ts index e8d931878..2e2d7a196 100644 --- a/hub/server/scripts/setup/index.ts +++ b/hub/server/scripts/setup/index.ts @@ -16,6 +16,14 @@ export async function setup() { ) { throw new Error("Separate roles require replica_runtime and a replica_migration database URL.") } + const learningMigrationUrl = process.env.REPLICA_LEARNING_MIGRATION_DATABASE_URL + const learningRuntimeRole = process.env.REPLICA_LEARNING_RUNTIME_ROLE + if ( + (learningRuntimeRole && learningRuntimeRole !== "replica_learning_runtime") || + (learningRuntimeRole && !learningMigrationUrl) + ) { + throw new Error("Learning runtime grants require the learning migration URL and runtime role.") + } const controller = new AbortController() function stop() { controller.abort() @@ -33,17 +41,40 @@ export async function setup() { `../grant-runtime-database-access/index.${extension}`, import.meta.url, ) + const learningGrantScript = new URL( + `../grant-learning-database-access/index.${extension}`, + import.meta.url, + ) const steps = [ - [resolve("node_modules/prisma/build/index.js"), "migrate", "deploy"], - [fileURLToPath(jobScript)], - ...(process.env.DATABASE_RUNTIME_ROLE ? [[fileURLToPath(grantScript)]] : []), + { + name: "prisma", + args: [resolve("node_modules/prisma/build/index.js"), "migrate", "deploy"], + }, + { name: "jobs", args: [fileURLToPath(jobScript)] }, + ...(process.env.DATABASE_RUNTIME_ROLE + ? [{ name: "runtime-grants", args: [fileURLToPath(grantScript)] }] + : []), + ...(learningMigrationUrl + ? [ + { + name: "learning-migrate", + args: [ + resolve( + process.env.REPLICA_LEARNING_CLI ?? + "../packages/learning/bin/replica-learning.mjs", + ), + "migrate", + ], + }, + ] + : []), + ...(learningRuntimeRole + ? [{ name: "learning-grants", args: [fileURLToPath(learningGrantScript)] }] + : []), ] - for (const [index, args] of steps.entries()) { + for (const { name, args } of steps) { signal.throwIfAborted() - logger.info( - { step: ["prisma", "jobs", "runtime-grants"][index] }, - "Hub setup step started", - ) + logger.info({ step: name }, "Hub setup step started") // Migration tools can include database URLs in diagnostics; keep their output private. const child = spawn(process.execPath, args, { stdio: "ignore" }) let timeout: ReturnType | undefined diff --git a/hub/server/utils/parse-azure-secret-configuration/index.test.ts b/hub/server/utils/parse-azure-secret-configuration/index.test.ts index f615f1bbd..ece5a0fb9 100644 --- a/hub/server/utils/parse-azure-secret-configuration/index.test.ts +++ b/hub/server/utils/parse-azure-secret-configuration/index.test.ts @@ -37,7 +37,7 @@ describe("parseAzureSecretConfiguration()", () => { }) }) - it("accepts exactly the three versioned provisioning references", () => { + it("accepts exactly the versioned provisioning references", () => { const references = { DATABASE_URL: "https://fixture.vault.azure.net/secrets/admin-database/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", @@ -45,6 +45,8 @@ describe("parseAzureSecretConfiguration()", () => { "https://fixture.vault.azure.net/secrets/migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", HUB_RUNTIME_PASSWORD: "https://fixture.vault.azure.net/secrets/runtime-password/cccccccccccccccccccccccccccccccc", + HUB_LEARNING_PASSWORD: + "https://fixture.vault.azure.net/secrets/learning-password/dddddddddddddddddddddddddddddddd", } const environment = { AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000005", @@ -57,6 +59,96 @@ describe("parseAzureSecretConfiguration()", () => { }) }) + it("accepts only the admin URL and learning password for an existing installation", () => { + const references = { + DATABASE_URL: + "https://fixture.vault.azure.net/secrets/admin-database/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + HUB_LEARNING_PASSWORD: + "https://fixture.vault.azure.net/secrets/learning-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + } + const environment = { + AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000005", + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify(references), + } + + expect(parseAzureSecretConfiguration(environment, "provision-learning").references).toEqual( + references, + ) + expect(() => + parseAzureSecretConfiguration( + { + ...environment, + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ + DATABASE_URL: references.DATABASE_URL, + }), + }, + "provision-learning", + ), + ).toThrow() + expect(() => + parseAzureSecretConfiguration( + { + ...environment, + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ + HUB_LEARNING_PASSWORD: references.HUB_LEARNING_PASSWORD, + }), + }, + "provision-learning", + ), + ).toThrow() + expect(() => + parseAzureSecretConfiguration( + { + ...environment, + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ + DATABASE_URL: references.DATABASE_URL, + HUB_RUNTIME_PASSWORD: references.HUB_LEARNING_PASSWORD, + }), + }, + "provision-learning", + ), + ).toThrow() + expect(() => + parseAzureSecretConfiguration( + { + ...environment, + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ + ...references, + HUB_RUNTIME_PASSWORD: references.HUB_LEARNING_PASSWORD, + }), + }, + "provision-learning", + ), + ).toThrow() + }) + + it("requires a versioned learning password for an existing installation", () => { + const environment = { + AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000005", + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ + DATABASE_URL: + "https://fixture.vault.azure.net/secrets/admin-database/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + HUB_LEARNING_PASSWORD: "https://fixture.vault.azure.net/secrets/learning-password", + }), + } + + expect(() => parseAzureSecretConfiguration(environment, "provision-learning")).toThrow() + }) + + it("allows the optional learning migration URL in setup", () => { + const references = { + DATABASE_URL: "https://fixture.vault.azure.net/secrets/migration-database", + REPLICA_LEARNING_MIGRATION_DATABASE_URL: + "https://fixture.vault.azure.net/secrets/learning-migration-database", + } + const environment = { + AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000003", + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify(references), + } + + expect(parseAzureSecretConfiguration(environment, "setup").references).toEqual(references) + }) + it.each([undefined, "", "synthetic-client-token", " 00000000-0000-0000-0000-000000000001"])( "rejects a missing or malformed explicit managed identity", (clientId) => { @@ -94,26 +186,30 @@ describe("parseAzureSecretConfiguration()", () => { expect(() => parseAzureSecretConfiguration(environment, target)).toThrow() }) - it.each(["DATABASE_URL", "HUB_MIGRATION_PASSWORD", "HUB_RUNTIME_PASSWORD"])( - "requires the provisioning reference %s", - (missing) => { - const references: Record = { - DATABASE_URL: - "https://fixture.vault.azure.net/secrets/admin-database/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - HUB_MIGRATION_PASSWORD: - "https://fixture.vault.azure.net/secrets/migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - HUB_RUNTIME_PASSWORD: - "https://fixture.vault.azure.net/secrets/runtime-password/cccccccccccccccccccccccccccccccc", - } - delete references[missing] - const environment = { - AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000005", - AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify(references), - } + it.each([ + "DATABASE_URL", + "HUB_MIGRATION_PASSWORD", + "HUB_RUNTIME_PASSWORD", + "HUB_LEARNING_PASSWORD", + ])("requires the provisioning reference %s", (missing) => { + const references: Record = { + DATABASE_URL: + "https://fixture.vault.azure.net/secrets/admin-database/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + HUB_MIGRATION_PASSWORD: + "https://fixture.vault.azure.net/secrets/migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + HUB_RUNTIME_PASSWORD: + "https://fixture.vault.azure.net/secrets/runtime-password/cccccccccccccccccccccccccccccccc", + HUB_LEARNING_PASSWORD: + "https://fixture.vault.azure.net/secrets/learning-password/dddddddddddddddddddddddddddddddd", + } + delete references[missing] + const environment = { + AZURE_CLIENT_ID: "00000000-0000-0000-0000-000000000005", + AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify(references), + } - expect(() => parseAzureSecretConfiguration(environment, "provision")).toThrow() - }, - ) + expect(() => parseAzureSecretConfiguration(environment, "provision")).toThrow() + }) it.each(["setup", "provision"] as const)( "does not grant additional secret access to %s", @@ -127,6 +223,8 @@ describe("parseAzureSecretConfiguration()", () => { "https://fixture.vault.azure.net/secrets/migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", HUB_RUNTIME_PASSWORD: "https://fixture.vault.azure.net/secrets/runtime-password/cccccccccccccccccccccccccccccccc", + HUB_LEARNING_PASSWORD: + "https://fixture.vault.azure.net/secrets/learning-password/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", } : {}), SERVICE_API_KEY: @@ -150,6 +248,8 @@ describe("parseAzureSecretConfiguration()", () => { HUB_MIGRATION_PASSWORD: "https://fixture.vault.azure.net/secrets/migration-password", HUB_RUNTIME_PASSWORD: "https://fixture.vault.azure.net/secrets/runtime-password/cccccccccccccccccccccccccccccccc", + HUB_LEARNING_PASSWORD: + "https://fixture.vault.azure.net/secrets/learning-password/dddddddddddddddddddddddddddddddd", }), } diff --git a/hub/server/utils/parse-azure-secret-configuration/index.ts b/hub/server/utils/parse-azure-secret-configuration/index.ts index c14d25202..4f7812e71 100644 --- a/hub/server/utils/parse-azure-secret-configuration/index.ts +++ b/hub/server/utils/parse-azure-secret-configuration/index.ts @@ -10,7 +10,7 @@ export function parseAzureSecretConfiguration( const clientId = environment.AZURE_CLIENT_ID const input = environment.AZURE_KEY_VAULT_SECRET_REFERENCES if ( - !["runtime", "setup", "provision"].includes(target) || + !["runtime", "setup", "provision", "provision-learning"].includes(target) || !clientId || !/^[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}$/.test(clientId) || !input || @@ -29,12 +29,17 @@ export function parseAzureSecretConfiguration( const names = entries.map(([name]) => name) const required = target === "provision" - ? ["DATABASE_URL", "HUB_MIGRATION_PASSWORD", "HUB_RUNTIME_PASSWORD"] - : ["DATABASE_URL"] + ? ["DATABASE_URL", "HUB_MIGRATION_PASSWORD", "HUB_RUNTIME_PASSWORD", "HUB_LEARNING_PASSWORD"] + : target === "provision-learning" + ? ["DATABASE_URL", "HUB_LEARNING_PASSWORD"] + : ["DATABASE_URL"] + const allowed = + target === "setup" ? [...required, "REPLICA_LEARNING_MIGRATION_DATABASE_URL"] : required const reserved = new Set([ "AZURE_CLIENT_ID", "AZURE_KEY_VAULT_SECRET_REFERENCES", "DATABASE_RUNTIME_ROLE", + "REPLICA_LEARNING_RUNTIME_ROLE", "NODE_ENV", "RUNTIME_MODE", "HOST", @@ -50,7 +55,7 @@ export function parseAzureSecretConfiguration( !entries.length || entries.length > 64 || required.some((name) => !names.includes(name)) || - (target !== "runtime" && names.some((name) => !required.includes(name))) + (target !== "runtime" && names.some((name) => !allowed.includes(name))) ) { throw invalid() } @@ -64,7 +69,8 @@ export function parseAzureSecretConfiguration( !/^https:\/\/[a-zA-Z0-9-]+\.vault\.azure\.net\/secrets\/[a-zA-Z0-9-]+(?:\/[a-fA-F0-9]{32})?$/.test( url, ) || - (target === "provision" && new URL(url).pathname.split("/").length !== 4) + ((target === "provision" || target === "provision-learning") && + new URL(url).pathname.split("/").length !== 4) ) { throw invalid() } diff --git a/hub/server/utils/parse-azure-secret-configuration/types.ts b/hub/server/utils/parse-azure-secret-configuration/types.ts index b6acaf21e..cb0c099cf 100644 --- a/hub/server/utils/parse-azure-secret-configuration/types.ts +++ b/hub/server/utils/parse-azure-secret-configuration/types.ts @@ -1,4 +1,4 @@ -export type AzureEntrypoint = "runtime" | "setup" | "provision" +export type AzureEntrypoint = "runtime" | "setup" | "provision" | "provision-learning" export interface AzureSecretConfiguration { managedIdentityClientId: string diff --git a/hub/test/database/decision-review-snapshot-migration/index.db.test.ts b/hub/test/database/decision-review-snapshot-migration/index.db.test.ts new file mode 100644 index 000000000..da2753764 --- /dev/null +++ b/hub/test/database/decision-review-snapshot-migration/index.db.test.ts @@ -0,0 +1,195 @@ +import { execFile } from "node:child_process" +import { randomBytes, randomUUID } from "node:crypto" +import { readFile, readdir } from "node:fs/promises" +import { join } from "node:path" +import { fileURLToPath } from "node:url" +import { promisify } from "node:util" +import pg from "pg" +import { describe, expect, it } from "vitest" + +const timeoutMs = 180_000 +const baseMigration = "20261220150000_inbox_unread_lookup" + +describe("decision review snapshot migration", () => { + it( + "preserves the populated base and keeps checkpoints unique to each repository", + async () => { + const adminUrl = process.env.TEST_DATABASE_URL + if (!adminUrl) throw new Error("TEST_DATABASE_URL is required.") + const name = `replica_snapshot_upgrade_${randomBytes(8).toString("hex")}` + const admin = new pg.Client({ connectionString: adminUrl }) + await admin.connect() + let created = false + try { + await admin.query(`CREATE DATABASE ${pg.escapeIdentifier(name)}`) + created = true + const databaseUrl = new URL(adminUrl) + databaseUrl.pathname = name + const database = new pg.Client({ connectionString: databaseUrl.toString() }) + try { + await database.connect() + const hubRoot = fileURLToPath(new URL("../../../", import.meta.url)) + const migrationsRoot = join(hubRoot, "schema/migrations") + const names = (await readdir(migrationsRoot, { withFileTypes: true })) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort() + const checkpointMigrations = names.filter((name) => + name.endsWith("_add_decision_review_snapshot"), + ) + expect(checkpointMigrations).toHaveLength(1) + const checkpointMigration = checkpointMigrations[0]! + const base = names.filter((name) => name <= baseMigration && name !== checkpointMigration) + expect(base.at(-1)).toBe(baseMigration) + expect(checkpointMigration > baseMigration).toBe(true) + + for (const migrationName of base) { + const sql = await readFile(join(migrationsRoot, migrationName, "migration.sql"), "utf8") + if (migrationName === "20261104190000_entra_oidc_authentication") { + const statements = sql.split("\n") + await database.query(statements.slice(0, 2).join("\n")) + await database.query(statements.slice(2).join("\n")) + } else { + await database.query(sql) + } + } + + const retainedRepositoryId = randomUUID() + const removedRepositoryId = randomUUID() + const prototypeId = randomUUID() + const runId = randomUUID() + const reviewDigest = `sha256:${"a".repeat(64)}` + await database.query( + `INSERT INTO repositories (id, github_repository_id, name_with_owner, default_branch) + VALUES ($1, 1001, 'team/retained', 'main'), ($2, 1002, 'team/removed', 'main')`, + [retainedRepositoryId, removedRepositoryId], + ) + await database.query( + `INSERT INTO prototypes (id, repository_id, branch_name, name, registered_at) + VALUES ($1, $2, 'prototype/checkout', 'Checkout', '2026-11-18T12:00:00Z')`, + [prototypeId, retainedRepositoryId], + ) + await database.query( + `INSERT INTO learning_runs + (id, repository_id, snapshot_digest, state, started_at, finished_at) + VALUES ($1, $2, $3, 'SUCCEEDED', '2026-11-18T12:01:00Z', '2026-11-18T12:02:00Z')`, + [runId, retainedRepositoryId, reviewDigest], + ) + async function retainedData() { + const result = await database.query<{ + repository_id: string + name_with_owner: string + prototype_id: string + name: string + run_id: string + state: string + snapshot_digest: string + }>( + `SELECT repository.id AS repository_id, repository.name_with_owner, + prototype.id AS prototype_id, prototype.name, + run.id AS run_id, run.state, run.snapshot_digest + FROM repositories repository + JOIN prototypes prototype ON prototype.repository_id = repository.id + JOIN learning_runs run ON run.repository_id = repository.id + WHERE repository.id = $1`, + [retainedRepositoryId], + ) + return result.rows + } + const before = await retainedData() + expect(before).toEqual([ + { + repository_id: retainedRepositoryId, + name_with_owner: "team/retained", + prototype_id: prototypeId, + name: "Checkout", + run_id: runId, + state: "SUCCEEDED", + snapshot_digest: reviewDigest, + }, + ]) + + const run = promisify(execFile) + const prismaCli = join(hubRoot, "node_modules/prisma/build/index.js") + const options = { + cwd: hubRoot, + env: { ...process.env, DATABASE_URL: databaseUrl.toString() }, + timeout: timeoutMs, + } + for (const migrationName of base) { + await run( + process.execPath, + [ + prismaCli, + "migrate", + "resolve", + "--applied", + migrationName, + "--config", + "prisma7.config.ts", + ], + options, + ) + } + await run( + process.execPath, + [prismaCli, "migrate", "deploy", "--config", "prisma7.config.ts"], + options, + ) + + expect(await retainedData()).toEqual(before) + expect( + ( + await database.query( + `SELECT migration_name FROM _prisma_migrations + WHERE migration_name = $1 AND finished_at IS NOT NULL`, + [checkpointMigration], + ) + ).rows, + ).toEqual([{ migration_name: checkpointMigration }]) + expect((await database.query("SELECT id FROM decision_review_snapshots")).rows).toEqual( + [], + ) + + const keptSnapshotId = randomUUID() + const insert = `INSERT INTO decision_review_snapshots + (id, repository_id, digest, snapshot_id, captured_at) + VALUES ($1, $2, $3, $4, '2026-11-18T12:00:00Z')` + await database.query(insert, [ + randomUUID(), + removedRepositoryId, + reviewDigest, + randomUUID(), + ]) + await expect( + database.query(insert, [randomUUID(), removedRepositoryId, reviewDigest, randomUUID()]), + ).rejects.toMatchObject({ code: "23505" }) + await database.query(insert, [ + randomUUID(), + retainedRepositoryId, + reviewDigest, + keptSnapshotId, + ]) + await database.query("DELETE FROM repositories WHERE id = $1", [removedRepositoryId]) + expect( + ( + await database.query( + "SELECT repository_id, snapshot_id FROM decision_review_snapshots", + ) + ).rows, + ).toEqual([{ repository_id: retainedRepositoryId, snapshot_id: keptSnapshotId }]) + expect(await retainedData()).toEqual(before) + } finally { + await database.end() + } + } finally { + try { + if (created) await admin.query(`DROP DATABASE ${pg.escapeIdentifier(name)} WITH (FORCE)`) + } finally { + await admin.end() + } + } + }, + timeoutMs, + ) +}) diff --git a/hub/test/fixtures/learning/report-runtime.mjs b/hub/test/fixtures/learning/report-runtime.mjs index 5d94813b2..7a5f7d7e5 100644 --- a/hub/test/fixtures/learning/report-runtime.mjs +++ b/hub/test/fixtures/learning/report-runtime.mjs @@ -1,13 +1,34 @@ -import { stat } from "node:fs/promises" +import { readFile, stat, writeFile } from "node:fs/promises" +import { join } from "node:path" const temporaryDirectory = process.env.TMPDIR const status = await stat(temporaryDirectory) +const arguments_ = process.argv.slice(2) +const directoryIndex = arguments_.indexOf("--dir") +const directoryArgument = arguments_.find((argument) => argument.startsWith("--dir=")) +const directory = + directoryIndex !== -1 ? arguments_[directoryIndex + 1] : directoryArgument?.slice("--dir=".length) +let config +if (directory !== undefined) { + try { + config = await readFile(join(directory, "config.json"), "utf8") + } catch (error) { + if (error.code !== "ENOENT") throw error + } +} -process.stdout.write( - JSON.stringify({ - arguments: process.argv.slice(2), - environment: process.env, - temporaryDirectory, - temporaryDirectoryMode: status.mode & 0o777, - }), -) +const report = JSON.stringify({ + arguments: arguments_, + config, + environment: process.env, + temporaryDirectory, + temporaryDirectoryMode: status.mode & 0o777, +}) +const failureIndex = arguments_.indexOf("--fixture-fail-report") +if (failureIndex !== -1) { + await writeFile(arguments_[failureIndex + 1], report) + process.stderr.write("error (invalid_request): fixture failure\n") + process.exitCode = 2 +} else { + process.stdout.write(report) +} diff --git a/infrastructure/README.md b/infrastructure/README.md index abdc756e9..bdf1a8ee5 100644 --- a/infrastructure/README.md +++ b/infrastructure/README.md @@ -61,6 +61,8 @@ It then uses separate protected Terraform state files for the foundation, applic The wizard builds and pushes a Linux AMD64 image and deploys its immutable digest. On first installation, Hub remains absent while a separate private-network job initializes the database roles. This job has its own temporary managed identity and secret-scoped administrator/password access; neither Hub nor normal setup receives administrator access. After success, the wizard records completion in Key Vault and destroys the temporary job, identity, and grants before invoking the existing serialized release procedure. +New installations use the separate PostgreSQL learning login. On an existing installation, the wizard provisions that login separately but keeps SQLite selected. Before import, stop old writers, hold the release lock, and run setup to migrate the learning schema. With the migration URL supplied privately as `REPLICA_LEARNING_MIGRATION_DATABASE_URL`, run `node dist/server/scripts/grant-learning-database-access/index.js` from the Hub image to grant the learning login access. Follow the [learning history migration](../hub/docs/learning-foundation.md) before adding `learning_database_secret` to the private saved inputs and running a serialized update. Keep SQLite selected if the old history cannot be recovered or verified. The wizard never treats an unavailable old revision's disk as proof that no history exists. + The final release stops old revisions, runs migrations and schedule setup, starts Hub, and checks HTTPS readiness. Readiness is not authorization. After installation, use the separate [post-setup menu](#post-setup-configuration) to enable setup access and GitHub sign-in without another build or database setup. Artifact import, hosted previews, and reviews are not available yet. ### Saved configuration and repeat runs @@ -470,13 +472,13 @@ Each installation has its own resource group tagged with its application, instal Two optional modules have separate Terraform states and lifecycles. [`azure/foundation/`](azure/foundation/main.tf) creates an installation-owned ACR and RBAC-enabled Key Vault in a separate resource group, with `AcrPush` and `Key Vault Secrets Officer` grants for the deployment identity. The vault has 90-day soft deletion and purge protection. Pass its registry and vault outputs to the main installation; the main module still accepts existing resources and never owns their teardown. -[`azure/provision/`](azure/provision/main.tf) creates a temporary private-network database-role provisioning job and identity in the installation's Container Apps environment. It accepts the same immutable image and exactly three versioned Key Vault references: `DATABASE_URL` for the administrator, `HUB_MIGRATION_PASSWORD`, and `HUB_RUNTIME_PASSWORD`. Each secret URL must belong to the supplied `vault_id`. Its Azure startup entrypoint retrieves those values through the provisioning identity before importing database provisioning code. Omit `registry_id` for a public image; an existing ACR requires its resource ID and grants only the provisioning identity pull access. The job has one replica, no automatic retries, and a ten-minute timeout. An authorized operator must run it once against a fresh database, verify that exact execution succeeded, and remove the temporary job, identity, and grants before release. Do not rerun it against an installed database or grant its administrator secret to Hub or setup. The existing private-network operator script remains an alternative. +[`azure/provision/`](azure/provision/main.tf) creates a temporary private-network database-role provisioning job and identity in the installation's Container Apps environment. Fresh `provision` requires four versioned Key Vault references: administrator `DATABASE_URL`, `HUB_MIGRATION_PASSWORD`, `HUB_RUNTIME_PASSWORD`, and `HUB_LEARNING_PASSWORD`. For an existing installation, `provision-learning` requires only the administrator URL and learning password. Each secret URL must belong to the supplied `vault_id`. The startup entrypoint retrieves those values through the provisioning identity before importing database provisioning code. Omit `registry_id` for a public image; an existing ACR grants only the provisioning identity pull access. Each job has one replica, no automatic retries, and a ten-minute timeout. Verify the exact successful execution and remove its temporary job, identity, and grants before release. Do not rerun fresh provisioning against an installed database or grant its administrator secret to Hub or setup. Initialize each optional module against its own protected backend state key, review its declared inputs and Terraform plan, and authorize its apply separately. Never share a state key with the main installation. Neither module starts Hub or replaces the serialized release command. The app has external HTTPS ingress and minimum and maximum one replica **per revision**. Multiple-revision mode permits explicit deactivation before releases. Azure's single-revision mode deliberately overlaps old and new processes while readiness is checked, so it is unsuitable for this maintenance-window strategy. Do not activate old revisions alongside the combined worker. This is not a high-availability or zero-downtime installation. -The runtime receives `RUNTIME_MODE=combined`, `HOST=0.0.0.0`, `PORT=3001`, `CLIENT_DIRECTORY=/app/dist/client`, `SHUTDOWN_TIMEOUT_MS=30000`, and `NODE_ENV=production`. Artifacts use `ARTIFACT_STORAGE_PROVIDER=azure`, the provisioned `AZURE_STORAGE_ACCOUNT`, `AZURE_STORAGE_CONTAINER=artifacts`, and Hub's `AZURE_CLIENT_ID`. Optional `runtime_secret_references` map environment names to vault resource IDs and HTTPS secret URLs; at most 63 additional references are allowed because the runtime database URL is the 64th. Vault and secret names in these URLs must fit Azure's 24-character and 127-character limits. Terraform passes the Key Vault URLs, including the runtime database secret reference, as the non-secret JSON map `AZURE_KEY_VAULT_SECRET_REFERENCES`, never as inline secret values or Container Apps Key Vault secret bindings. +The runtime receives `RUNTIME_MODE=combined`, `HOST=0.0.0.0`, `PORT=3001`, `CLIENT_DIRECTORY=/app/dist/client`, `SHUTDOWN_TIMEOUT_MS=30000`, and `NODE_ENV=production`. Artifacts use `ARTIFACT_STORAGE_PROVIDER=azure`, the provisioned `AZURE_STORAGE_ACCOUNT`, `AZURE_STORAGE_CONTAINER=artifacts`, and Hub's `AZURE_CLIENT_ID`. Optional `runtime_secret_references` map environment names to vault resource IDs and HTTPS secret URLs. At most 63 additional references are allowed, or 62 when a learning database is configured, because the database URLs also use reference slots. Vault and secret names in these URLs must fit Azure's 24-character and 127-character limits. Terraform passes the Key Vault URLs, including the runtime database secret references, as the non-secret JSON map `AZURE_KEY_VAULT_SECRET_REFERENCES`, never as inline secret values or Container Apps Key Vault secret bindings. Use the optional `runtime_environment_variables` string map for non-secret Hub settings. Names must start with an uppercase letter and contain only uppercase letters, digits, or underscores, with at most 41 characters. Empty string values are allowed; null values are not. Deployment-owned names, including database credentials, storage settings, and startup identity/reference metadata, cannot be overridden. A name cannot appear in both this map and `runtime_secret_references`. These values go only to Hub, not setup or provisioning. The wizard adds no questions for this map; guided updates preserve it in the private workspace's `installation.tfvars.json`. @@ -495,13 +497,13 @@ These values are stored directly in Terraform state and Container Apps configura Terraform may include an invalid input line in its error output, including any credential supplied on that line. Remove credentials from the input before running Terraform and protect or redact any captured output if a credential was supplied. -Azure containers run `node dist/server/scripts/azure-entrypoint/index.js runtime`, `setup`, or `provision`. The entrypoint validates the complete reference map and explicit managed-identity client ID before fetching anything. It retrieves values directly from Key Vault with that identity, applies them to the workload's in-memory environment only after all reads succeed, then imports the selected workload. Startup secret retrieval has one 30-second deadline, with a bounded exponential retry for transient authorization, throttling, and service errors under the same identity; it stops on cancellation or failure before API/worker startup, database provisioning, or migrations. Secret-retrieval errors do not print token, URL, response-body, or secret contents. Registry pulling still uses Azure's normal managed-identity registry configuration; this does not bypass image-pull, DNS, or access failures. +Azure containers run `node dist/server/scripts/azure-entrypoint/index.js` with `runtime`, `setup`, `provision`, or `provision-learning`. The entrypoint validates the complete reference map and explicit managed-identity client ID before fetching anything. It retrieves values directly from Key Vault with that identity, applies them to the workload's in-memory environment only after all reads succeed, then imports the selected workload. Startup secret retrieval has one 30-second deadline, with a bounded exponential retry for transient authorization, throttling, and service errors under the same identity; it stops on cancellation or failure before API/worker startup, database provisioning, or migrations. Secret-retrieval errors do not print token, URL, response-body, or secret contents. Registry pulling still uses Azure's normal managed-identity registry configuration; this does not bypass image-pull, DNS, or access failures. -Setup can receive only its migration `DATABASE_URL`; provisioning requires exactly its three versioned administrator/password references. Runtime requires its runtime `DATABASE_URL` and may receive validated additional references. References cannot overwrite already-defined environment values or deployment-owned configuration, including the identity and reference-map fields. Existing secret-scoped grants remain unchanged; no vault-wide access is added. Versioned URLs are recommended for deliberate rotation. An unversioned runtime/setup URL selects the latest value only at startup, not through Container Apps' background secret refresh. Restart through a reviewed serialized release to pick up a new version. +Setup receives its migration URL as both `DATABASE_URL` and `REPLICA_LEARNING_MIGRATION_DATABASE_URL`; it needs no runtime credential. Provisioning requires exactly the versioned references for its selected mode. Runtime requires its runtime `DATABASE_URL` and may receive the separate learning URL and validated additional references. References cannot overwrite already-defined environment values or deployment-owned configuration, including the identity and reference-map fields. No vault-wide access is added. Versioned URLs are recommended for deliberate rotation. An unversioned runtime/setup URL selects the latest value only at startup, not through Container Apps' background secret refresh. Restart through a reviewed serialized release to pick up a new version. Terraform ignores only Azure-assigned PostgreSQL availability-zone and Container Apps infrastructure-resource-group values. It still checks other drift and owns both images. The installation output exposes authoritative app, resource-group, and storage-account IDs; before the first release, the app ID is `null`. -The setup job uses the same digest and command `node dist/server/scripts/azure-entrypoint/index.js setup`. Its environment settings are `NODE_ENV=production`, `RUNTIME_MODE=setup`, `DATABASE_RUNTIME_ROLE=replica_runtime`, its own `AZURE_CLIENT_ID`, and a reference map containing only its migration `DATABASE_URL` for `replica_migration`. It receives no artifact configuration or additional runtime secrets. It has one replica, no automatic retries, and a 30-minute timeout. Hub's readiness probe is `/api/ready`; startup and liveness use `/api/health`. Azure allows 60 seconds for termination, covering the 30-second application drain and up to five seconds of telemetry flushing with platform margin. +The setup job uses the same digest and command `node dist/server/scripts/azure-entrypoint/index.js setup`. Its environment settings are `NODE_ENV=production`, `RUNTIME_MODE=setup`, `DATABASE_RUNTIME_ROLE=replica_runtime`, and its own `AZURE_CLIENT_ID`. Its reference map supplies the same `replica_migration` secret as both `DATABASE_URL` and `REPLICA_LEARNING_MIGRATION_DATABASE_URL`. When a PostgreSQL learning database secret is configured, it also sets `REPLICA_LEARNING_RUNTIME_ROLE=replica_learning_runtime`. Setup receives no artifact configuration or additional runtime secrets. It has one replica, no automatic retries, and a 30-minute timeout. Hub's readiness probe is `/api/ready`; startup and liveness use `/api/health`. Azure allows 60 seconds for termination, covering the 30-second application drain and up to five seconds of telemetry flushing with platform margin. Neither workload receives the PostgreSQL administrator credential. A separate, one-time operator script provisions the migration and runtime roles over the private database network. Setup owns schema changes and refreshes the runtime's data permissions after migrations. See [database access](../hub/docs/database.md#deployment-database-roles). Managed identity is used for Blob, Key Vault, and ACR, not database authentication. @@ -543,7 +545,7 @@ node infrastructure/azure/deploy-hub/index.ts bootstrap \ Bootstrap creates infrastructure and the manual setup job with `deploy_hub=false`. No combined app exists yet. Review the configuration and a read-only Terraform plan before authorizing this command: the script applies saved plans without an interactive prompt after checking for deletes/replacements. Command output is kept private because tool diagnostics can contain credentials. Bootstrap refuses any nonempty state so it cannot race a release on an existing installation. If initial provisioning failed partway, inspect the partial state and recover from a separately reviewed plan with `deploy_hub=false`; never use this recovery path after an app has been created. -Before the first release, use an authorized private-network host with Hub's dependencies installed to run `node server/scripts/provision-database-access/index.ts` from `hub/`. Inject the administrator `DATABASE_URL`, `HUB_MIGRATION_PASSWORD`, and `HUB_RUNTIME_PASSWORD` directly from the secret manager without shell tracing or command-line values. Use the same two passwords stored in the workload URL secrets. This first-installation script creates the roles and schemas transactionally and rejects existing roles, public tables, or a pre-existing BullMQ schema; it is not an upgrade or password-rotation command. Remove these environment variables afterward. Do not inject administrator credentials into the setup job. Existing installations require a reviewed ownership/credential migration while Hub is stopped, not rerunning this fresh-database script. +Before the first release, use an authorized private-network host with Hub's dependencies installed to run `node server/scripts/provision-database-access/index.ts` from `hub/`. Inject the administrator `DATABASE_URL`, `HUB_MIGRATION_PASSWORD`, `HUB_RUNTIME_PASSWORD`, and `HUB_LEARNING_PASSWORD` directly from the secret manager without shell tracing or command-line values. Use distinct passwords matching the workload URL secrets. This first-installation script creates the roles and schemas transactionally and rejects existing roles, public tables, or a pre-existing BullMQ schema; it is not an upgrade or password-rotation command. Remove these environment variables afterward. Do not inject administrator credentials into the setup job. Existing installations require a reviewed ownership/credential migration while Hub is stopped, not rerunning this fresh-database script. Use the same release command for the first installation, subsequent image releases, and infrastructure or secret changes: diff --git a/infrastructure/azure/application.tf b/infrastructure/azure/application.tf index d3fd8b00c..c60f5c3cd 100644 --- a/infrastructure/azure/application.tf +++ b/infrastructure/azure/application.tf @@ -52,6 +52,7 @@ locals { AZURE_CLIENT_ID = azurerm_user_assigned_identity.hub.client_id AZURE_KEY_VAULT_SECRET_REFERENCES = jsonencode(merge( { DATABASE_URL = var.runtime_database_secret.secret_id }, + var.learning_database_secret == null ? {} : { REPLICA_LEARNING_DATABASE_URL = var.learning_database_secret.secret_id }, { for name, reference in var.runtime_secret_references : name => reference.secret_id }, )) }, local.github_environment) diff --git a/infrastructure/azure/install/index.test.ts b/infrastructure/azure/install/index.test.ts index ba2674364..0772cb2ea 100644 --- a/infrastructure/azure/install/index.test.ts +++ b/infrastructure/azure/install/index.test.ts @@ -62,6 +62,7 @@ afterEach(async () => { async function scenario({ existing = false, + learningProvisioned = true, releaseFails = false, priorProvisioning = false, provisioningFails = false, @@ -86,9 +87,12 @@ async function scenario({ const image = `registry.azurecr.io/replica-hub@sha256:${"a".repeat(64)}` const events: { command: string[]; env?: NodeJS.ProcessEnv }[] = [] const messages: string[] = [] - const secretValues = new Map( - existing ? [["database-provisioned", config.azure.resourceGroup]] : [], - ) + const secretValues = new Map([ + ...(existing ? [["database-provisioned", config.azure.resourceGroup]] : []), + ...(existing && learningProvisioned + ? [["learning-database-provisioned", config.azure.resourceGroup]] + : []), + ] as [string, string][]) const vaultId = `/subscriptions/${config.azure.subscriptionId}/resourceGroups/foundation/providers/Microsoft.KeyVault/vaults/testvault` const foundation = { vault_id: vaultId, @@ -919,6 +923,18 @@ it("uses one deployment approval for dirty-source publication, nonempty plans, t ), ).toBe(false) expect(s.secretValues.get("database-provisioned")).toBe(s.config.azure.resourceGroup) + expect(s.secretValues.get("learning-database-provisioned")).toBe(s.config.azure.resourceGroup) + const workspace = installationWorkspace(s.config, s.directory) + const provision = JSON.parse(await readFile(join(workspace, "provision.tfvars.json"), "utf8")) + expect(provision.mode).toBe("provision") + expect(Object.keys(provision.secret_urls).sort()).toEqual([ + "DATABASE_URL", + "HUB_LEARNING_PASSWORD", + "HUB_MIGRATION_PASSWORD", + "HUB_RUNTIME_PASSWORD", + ]) + const inputs = JSON.parse(await readFile(join(workspace, "installation.tfvars.json"), "utf8")) + expect(inputs.learning_database_secret.secret_id).toContain("/secrets/postgres-learning-url/") const serialized = JSON.stringify({ commands, messages: s.messages }) for (const [name, value] of s.secretValues) { if (name.includes("password") || name.endsWith("-url")) expect(serialized).not.toContain(value) @@ -1078,6 +1094,77 @@ it("updates an installed app only through the release orchestrator and never rer ).toBe(false) }) +it("provisions only the learning role on a SQLite installation without activating PostgreSQL", async () => { + const s = await scenario({ existing: true, learningProvisioned: false }) + + await installAzure(s.config, s) + + const workspace = installationWorkspace(s.config, s.directory) + const provision = JSON.parse(await readFile(join(workspace, "provision.tfvars.json"), "utf8")) + expect(provision.mode).toBe("provision-learning") + expect(Object.keys(provision.secret_urls).sort()).toEqual([ + "DATABASE_URL", + "HUB_LEARNING_PASSWORD", + ]) + const inputs = JSON.parse(await readFile(join(workspace, "installation.tfvars.json"), "utf8")) + expect(inputs).not.toHaveProperty("learning_database_secret") + expect(s.secretValues.get("learning-database-provisioned")).toBe(s.config.azure.resourceGroup) + expect( + s.events.filter(({ command }) => command.slice(0, 4).join(" ") === "az containerapp job start"), + ).toHaveLength(1) + expect(s.released()).toBe(true) +}) + +it("cleans up a completed learning provisioning job without rerunning it", async () => { + const s = await scenario({ existing: true }) + const run: RunCommand = async (executable, args, options) => { + const result = await s.run(executable, args, options) + if ( + executable === "terraform" && + args[1] === "state" && + options?.env?.TF_DATA_DIR?.endsWith("/learning-provision") + ) + return "azurerm_container_app_job.provision" + return result + } + + await installAzure(s.config, { ...s, run }) + + expect( + s.events.some(({ command }) => command.slice(0, 4).join(" ") === "az containerapp job start"), + ).toBe(false) + expect( + s.events.some( + ({ command, env }) => + command[0] === "terraform" && + command[2] === "plan" && + command.includes("-destroy") && + env?.TF_DATA_DIR?.endsWith("/learning-provision"), + ), + ).toBe(true) + expect(s.released()).toBe(true) +}) + +it("refuses to replay learning provisioning with prior executions but no marker", async () => { + const s = await scenario({ existing: true, learningProvisioned: false, priorProvisioning: true }) + const run: RunCommand = async (executable, args, options) => { + const result = await s.run(executable, args, options) + if ( + executable === "terraform" && + args[1] === "state" && + options?.env?.TF_DATA_DIR?.endsWith("/learning-provision") + ) + return "azurerm_container_app_job.provision" + return result + } + + await expect(installAzure(s.config, { ...s, run })).rejects.toThrow("prior executions") + expect( + s.events.some(({ command }) => command.slice(0, 4).join(" ") === "az containerapp job start"), + ).toBe(false) + expect(s.released()).toBe(false) +}) + it("corrects an image-build proxy under the same installation lease without replaying infrastructure or credentials", async () => { const s = await scenario({ imageFailsOnce: true }) delete s.config.npmRegistry diff --git a/infrastructure/azure/install/index.ts b/infrastructure/azure/install/index.ts index 702770408..91e22fe16 100644 --- a/infrastructure/azure/install/index.ts +++ b/infrastructure/azure/install/index.ts @@ -114,9 +114,10 @@ async function install( "foundation-backend.hcl", "app-backend.hcl", "provision-backend.hcl", + "learning-provision-backend.hcl", ]) await privateFile(join(directory, file)) - for (const module of ["foundation", "app", "provision"]) + for (const module of ["foundation", "app", "provision", "learning-provision"]) await privateDirectory(join(directory, "terraform", module)) const env: NodeJS.ProcessEnv = { ARM_SUBSCRIPTION_ID: config.azure.subscriptionId, @@ -246,6 +247,7 @@ async function install( ) } const appCreated = appState.includes("azurerm_container_app.hub[0]") + const databaseProvisioned = await secrets.provisioned() const variables = join(directory, "installation.tfvars.json") const inputs = { ...postgres, @@ -260,12 +262,20 @@ async function install( acr_id: resources.registry_id, runtime_database_secret: { key_vault_id: resources.vault_id, secret_id: secrets.runtimeUrl }, setup_database_secret: { key_vault_id: resources.vault_id, secret_id: secrets.migrationUrl }, + ...(!appCreated && !databaseProvisioned && !operatorInputs.learning_database_secret + ? { + learning_database_secret: { + key_vault_id: resources.vault_id, + secret_id: secrets.learningUrl, + }, + } + : {}), } await writePrivateFile(variables, JSON.stringify({ ...inputs, ...operatorInputs })) if (!appCreated) { ui.status("Bootstrapping infrastructure with Hub stopped") await app.apply(variables) - } else if (!(await secrets.provisioned())) { + } else if (!databaseProvisioned) { throw new Error( "An app exists without the wizard's database provisioning marker. Review ownership; do not provision database roles again.", ) @@ -284,6 +294,7 @@ async function install( secrets, image, await state.backend("provision"), + await state.backend("learning-provision"), ) // A failed earlier release can retain the release lock. Offer the usual recovery first, // unless the preview step itself retained it and can resume by proof of ownership. diff --git a/infrastructure/azure/install/inputs/index.ts b/infrastructure/azure/install/inputs/index.ts index 57ffadc3d..ad300b341 100644 --- a/infrastructure/azure/install/inputs/index.ts +++ b/infrastructure/azure/install/inputs/index.ts @@ -7,6 +7,7 @@ import type { DeploymentConfig } from "../../../installer/types.ts" type SecretReference = { key_vault_id: string; secret_id: string } interface OperatorInputs { + learning_database_secret?: SecretReference runtime_environment_variables?: Record hub_application_origin?: string github_app_id?: string @@ -56,6 +57,7 @@ export async function readInstallationInputs( ] const optional = [ "runtime_environment_variables", + "learning_database_secret", "hub_application_origin", "github_app_id", "github_client_id", @@ -98,6 +100,18 @@ export async function readInstallationInputs( return { key_vault_id: secret.key_vault_id, secret_id: secret.secret_id } } const result: OperatorInputs = {} + if (inputs.learning_database_secret != null) { + const learning = reference(inputs.learning_database_secret) + const identity = (secret: SecretReference) => + `${secret.key_vault_id}/secrets/${new URL(secret.secret_id).pathname.split("/")[2]}`.toLowerCase() + if ( + [reference(inputs.setup_database_secret), reference(inputs.runtime_database_secret)].some( + (secret) => identity(secret) === identity(learning), + ) + ) + throw invalid() + result.learning_database_secret = learning + } for (const key of ["github_app_id", "github_app_installation_id"] as const) { const value = inputs[key] if (value == null) continue @@ -173,6 +187,9 @@ export async function readInstallationInputs( const reserved = [ "DATABASE_URL", "DATABASE_RUNTIME_ROLE", + "REPLICA_LEARNING_DATABASE_URL", + "REPLICA_LEARNING_MIGRATION_DATABASE_URL", + "REPLICA_LEARNING_RUNTIME_ROLE", "NODE_ENV", "RUNTIME_MODE", "HOST", @@ -191,7 +208,8 @@ export async function readInstallationInputs( typeof inputs.runtime_secret_references !== "object" || inputs.runtime_secret_references === null || Array.isArray(inputs.runtime_secret_references) || - Object.keys(inputs.runtime_secret_references).length > 63 + Object.keys(inputs.runtime_secret_references).length > + (result.learning_database_secret ? 62 : 63) ) throw invalid() const setup = reference(inputs.setup_database_secret) diff --git a/infrastructure/azure/install/provision/index.ts b/infrastructure/azure/install/provision/index.ts index 0fe66d22f..9b6f15faf 100644 --- a/infrastructure/azure/install/provision/index.ts +++ b/infrastructure/azure/install/provision/index.ts @@ -16,22 +16,25 @@ export async function provisionDatabase( secrets: Awaited>, image: string, backend: string, + learningBackend: string, ) { const { run, ui, env, config, directory, azure } = context - const module = terraformModule({ - directory: resolve(import.meta.dirname, "../../provision"), - dataDirectory: join(directory, "terraform", "provision"), - run, - ui, - env, - preapproved: context.approval !== undefined, - retryApply: retryableProvisioningFailure, - signal: context.signal, - findUntracked: existingRoleAssignment(azure, config.azure.subscriptionId), - }) - await module.init(backend) - const complete = await secrets.provisioned() - if (complete && !(await module.state()).length) return + const moduleFor = (name: string) => + terraformModule({ + directory: resolve(import.meta.dirname, "../../provision"), + dataDirectory: join(directory, "terraform", name), + run, + ui, + env, + preapproved: context.approval !== undefined, + retryApply: retryableProvisioningFailure, + signal: context.signal, + findUntracked: existingRoleAssignment(azure, config.azure.subscriptionId), + }) + const freshModule = moduleFor("provision") + const learningModule = moduleFor("learning-provision") + await freshModule.init(backend) + await learningModule.init(learningBackend) const lease = await acquireLease( context, installation.storage_account, @@ -58,113 +61,164 @@ export async function provisionDatabase( ) } const variables = join(directory, "provision.tfvars.json") - await writePrivateFile( - variables, - JSON.stringify({ - subscription_id: config.azure.subscriptionId, - name: config.name, - location: config.azure.location, - resource_group: installation.resource_group, - environment_id: installation.environment_id, - registry_id: foundation.registry_id, - image, - vault_id: foundation.vault_id, - secret_urls: secrets.provisioning, - }), - ) - if (complete) { - const job = await module.output("job_name") - const executions = JSON.parse( - await azure( - "containerapp", - "job", - "execution", - "list", - "--name", - job, - "--resource-group", - installation.resource_group, - ), - ) as { properties: { status: string } }[] - if (executions.some(({ properties }) => !terminal.includes(properties.status))) { - throw new Error( - "A provisioning execution is still running. Temporary access cannot be removed yet.", - ) - } - } else { - await module.apply(variables) - const job = await module.output("job_name") - const executions = JSON.parse( - await azure( - "containerapp", - "job", - "execution", - "list", - "--name", - job, - "--resource-group", - installation.resource_group, - ), - ) as { name: string; properties: { status: string } }[] - if (executions.length) { - throw new Error( - "Database provisioning has prior executions but no completion marker. Inspect the database and exact job execution; do not rerun fresh-database provisioning blindly.", - ) + const complete = await secrets.provisioned() + const learningComplete = await secrets.learningProvisioned() + const freshState = await freshModule.state() + const learningState = await learningModule.state() + if (learningState.length && (!complete || freshState.length)) { + throw new Error( + "Learning provisioning state conflicts with the database marker or fresh provisioning state. Inspect both states and database ownership before recovery.", + ) + } + const cleanup = async (module: ReturnType) => { + await module.apply(variables, { + destroy: true, + allowedDeletions: [ + "azurerm_container_app_job.provision", + "azurerm_user_assigned_identity.provision", + "azurerm_role_assignment.image[0]", + 'azurerm_role_assignment.secrets["DATABASE_URL"]', + 'azurerm_role_assignment.secrets["HUB_MIGRATION_PASSWORD"]', + 'azurerm_role_assignment.secrets["HUB_RUNTIME_PASSWORD"]', + 'azurerm_role_assignment.secrets["HUB_LEARNING_PASSWORD"]', + ], + }) + } + const provision = async ( + module: ReturnType, + mode: "provision" | "provision-learning", + done: boolean, + ) => { + const state = await module.state() + if (done && !state.length) return + if (!done && state.includes("azurerm_container_app_job.provision")) { + const job = await module.output("job_name") + const executions = JSON.parse( + await azure( + "containerapp", + "job", + "execution", + "list", + "--name", + job, + "--resource-group", + installation.resource_group, + ), + ) as { name: string }[] + if (executions.length) { + throw new Error( + "Database provisioning has prior executions but no completion marker. Inspect the database and exact job execution; do not rerun provisioning blindly.", + ) + } } - const execution = JSON.parse( - await azure( - "containerapp", - "job", - "start", - "--name", - job, - "--resource-group", - installation.resource_group, - ), - ) as { name: string } - const deadline = performance.now() + 720_000 - let success = false - while (performance.now() < deadline) { - const result = JSON.parse( + await writePrivateFile( + variables, + JSON.stringify({ + subscription_id: config.azure.subscriptionId, + name: config.name, + location: config.azure.location, + resource_group: installation.resource_group, + environment_id: installation.environment_id, + registry_id: foundation.registry_id, + image, + vault_id: foundation.vault_id, + mode, + secret_urls: mode === "provision" ? secrets.provisioning : secrets.learningProvisioning, + }), + ) + if (done) { + const job = await module.output("job_name") + const executions = JSON.parse( await azure( "containerapp", "job", "execution", - "show", + "list", "--name", job, "--resource-group", installation.resource_group, - "--job-execution-name", - execution.name, ), - ) as { properties: { status: string } } - if (result.properties.status === "Succeeded") { - success = true - break + ) as { properties: { status: string } }[] + if (executions.some(({ properties }) => !terminal.includes(properties.status))) { + throw new Error( + "A provisioning execution is still running. Temporary access cannot be removed yet.", + ) } - if (["Failed", "Stopped", "Canceled"].includes(result.properties.status)) { + } else { + await module.apply(variables) + const job = await module.output("job_name") + const executions = JSON.parse( + await azure( + "containerapp", + "job", + "execution", + "list", + "--name", + job, + "--resource-group", + installation.resource_group, + ), + ) as { name: string; properties: { status: string } }[] + if (executions.length) { throw new Error( - "Fresh-database provisioning failed. Inspect the named provisioning job and database ownership; the release lock is retained.", + "Database provisioning has prior executions but no completion marker. Inspect the database and exact job execution; do not rerun provisioning blindly.", ) } - await timers.setTimeout(5_000) + await lease.verify() + const execution = JSON.parse( + await azure( + "containerapp", + "job", + "start", + "--name", + job, + "--resource-group", + installation.resource_group, + ), + ) as { name: string } + const deadline = performance.now() + 720_000 + let success = false + while (performance.now() < deadline) { + const result = JSON.parse( + await azure( + "containerapp", + "job", + "execution", + "show", + "--name", + job, + "--resource-group", + installation.resource_group, + "--job-execution-name", + execution.name, + ), + ) as { properties: { status: string } } + if (result.properties.status === "Succeeded") { + success = true + break + } + if (["Failed", "Stopped", "Canceled"].includes(result.properties.status)) { + throw new Error( + "Database provisioning failed. Inspect the named provisioning job and database ownership; the release lock is retained.", + ) + } + await timers.setTimeout(5_000) + } + if (!success) + throw new Error("Provisioning timed out. Check the execution before releasing any lock.") + await lease.verify() + if (mode === "provision") { + await secrets.markLearningProvisioned() + await secrets.markProvisioned() + } else { + await secrets.markLearningProvisioned() + } } - if (!success) - throw new Error("Provisioning timed out. Check the execution before releasing any lock.") - await secrets.markProvisioned() + await cleanup(module) } - await module.apply(variables, { - destroy: true, - allowedDeletions: [ - "azurerm_container_app_job.provision", - "azurerm_user_assigned_identity.provision", - "azurerm_role_assignment.image[0]", - 'azurerm_role_assignment.secrets["DATABASE_URL"]', - 'azurerm_role_assignment.secrets["HUB_MIGRATION_PASSWORD"]', - 'azurerm_role_assignment.secrets["HUB_RUNTIME_PASSWORD"]', - ], - }) + await provision(freshModule, "provision", complete) + await provision(learningModule, "provision-learning", learningComplete || !complete) await lease.release() } finally { lease.reportRetained() diff --git a/infrastructure/azure/install/secrets/index.ts b/infrastructure/azure/install/secrets/index.ts index 1816433e1..b7d92e769 100644 --- a/infrastructure/azure/install/secrets/index.ts +++ b/infrastructure/azure/install/secrets/index.ts @@ -62,6 +62,7 @@ export async function installationSecrets(context: AzureInstallation, foundation const admin = await ensure("postgres-admin-password", password) const migration = await ensure("postgres-migration-password", password) const runtime = await ensure("postgres-runtime-password", password) + const learning = await ensure("postgres-learning-password", password) const host = `${config.name}-postgres.postgres.database.azure.com` const url = (role: string, password: string) => `postgresql://${role}:${encodeURIComponent(password)}@${host}:5432/replica?sslmode=verify-full` @@ -72,14 +73,23 @@ export async function installationSecrets(context: AzureInstallation, foundation const runtimeUrl = await ensure("postgres-runtime-url", () => url("replica_runtime", runtime.value), ) + const learningUrl = await ensure("postgres-learning-url", () => + url("replica_learning_runtime", learning.value), + ) return { adminPassword: admin.value, migrationUrl: migrationUrl.id, runtimeUrl: runtimeUrl.id, + learningUrl: learningUrl.id, provisioning: { DATABASE_URL: adminUrl.id, HUB_MIGRATION_PASSWORD: migration.id, HUB_RUNTIME_PASSWORD: runtime.id, + HUB_LEARNING_PASSWORD: learning.id, + }, + learningProvisioning: { + DATABASE_URL: adminUrl.id, + HUB_LEARNING_PASSWORD: learning.id, }, async provisioned() { return ( @@ -95,5 +105,16 @@ export async function installationSecrets(context: AzureInstallation, foundation async markProvisioned() { await put("database-provisioned", config.azure.resourceGroup) }, + async learningProvisioned() { + if (!names.has("learning-database-provisioned")) return false + if ((await read("learning-database-provisioned")).value !== config.azure.resourceGroup) + throw new Error( + "The learning database provisioning marker belongs to another installation.", + ) + return true + }, + async markLearningProvisioned() { + await put("learning-database-provisioned", config.azure.resourceGroup) + }, } } diff --git a/infrastructure/azure/installation.tfvars.example b/infrastructure/azure/installation.tfvars.example index 11151738a..86f2d4e13 100644 --- a/infrastructure/azure/installation.tfvars.example +++ b/infrastructure/azure/installation.tfvars.example @@ -12,6 +12,12 @@ setup_database_secret = { key_vault_id = "/subscriptions/YOUR_SUBSCRIPTION/resourceGroups/YOUR_SECRETS_GROUP/providers/Microsoft.KeyVault/vaults/YOUR_VAULT" secret_id = "https://YOUR-VAULT.vault.azure.net/secrets/hub-migration-database" } +# Enable on a new installation, or only after an existing installation's SQLite +# history and mappings have been imported and verified. Leave unset otherwise. +# learning_database_secret = { +# key_vault_id = "/subscriptions/YOUR_SUBSCRIPTION/resourceGroups/YOUR_SECRETS_GROUP/providers/Microsoft.KeyVault/vaults/YOUR_VAULT" +# secret_id = "https://YOUR-VAULT.vault.azure.net/secrets/postgres-learning-url" +# } # Supply postgres_admin_password through a secret manager as TF_VAR_postgres_admin_password. # Application secrets stay in Key Vault. Optional references, never values: diff --git a/infrastructure/azure/post/configure/index.ts b/infrastructure/azure/post/configure/index.ts index a3771929c..0ea79165e 100644 --- a/infrastructure/azure/post/configure/index.ts +++ b/infrastructure/azure/post/configure/index.ts @@ -374,9 +374,10 @@ export async function configurePostSetup( action === "sign-in" ? Object.keys(shared) : ["GITHUB_CLIENT_SECRET", "GITHUB_APP_PRIVATE_KEY_BASE64", "GITHUB_WEBHOOK_SECRET"] - if (new Set([...Object.keys(references), ...requiredReferences]).size > 63) + const maximumReferences = next.learning_database_secret ? 62 : 63 + if (new Set([...Object.keys(references), ...requiredReferences]).size > maximumReferences) throw new Error( - "This configuration would exceed the runtime limit of 63 additional secret references. Review unused references separately before creating secrets.", + `This configuration would exceed the runtime limit of ${maximumReferences} additional secret references. Review unused references separately before creating secrets.`, ) if (action === "sign-in") { if ( @@ -751,8 +752,7 @@ export async function configurePostSetup( next.github_app_installation_id !== deployment.environment.GITHUB_APP_INSTALLATION_ID || credentials.some( ({ key }) => - references[key]?.secret_id !== - (liveSecretReferences as Record)[key], + references[key]?.secret_id !== (liveSecretReferences as Record)[key], ) const storedRevision = await verifiedGitHubRevision() const savedRevision = @@ -809,8 +809,7 @@ export async function configurePostSetup( ]) delete next.runtime_environment_variables[name] replacements.sort( - (left, right) => - Number(right.key === progress.pending) - Number(left.key === progress.pending), + (left, right) => Number(right.key === progress.pending) - Number(left.key === progress.pending), ) for (const credential of replacements) references[credential.key] = await put(credential.key, credential.name, credential.value) diff --git a/infrastructure/azure/post/index.test.ts b/infrastructure/azure/post/index.test.ts index 1c0e7004f..a08f7e682 100644 --- a/infrastructure/azure/post/index.test.ts +++ b/infrastructure/azure/post/index.test.ts @@ -118,6 +118,9 @@ async function scenario() { }), AZURE_KEY_VAULT_SECRET_REFERENCES: JSON.stringify({ DATABASE_URL: reference("database-runtime").secret_id, + ...(value.learning_database_secret && { + REPLICA_LEARNING_DATABASE_URL: value.learning_database_secret.secret_id, + }), ...Object.fromEntries( Object.entries(value.runtime_secret_references ?? {}).map(([key, value]) => [ key, @@ -602,6 +605,12 @@ it("retains leases and resumes when the completion marker cannot be saved", asyn it("uses the deployed digest despite stale deploy_hub=false and preserves settings across verification and configuration reruns", async () => { const test = await scenario() + test.inputs.learning_database_secret = test.reference("learning-runtime") + await writeFile(test.inputsPath, JSON.stringify(test.inputs), { mode: 0o600 }) + test.state.environment.AZURE_KEY_VAULT_SECRET_REFERENCES = JSON.stringify({ + ...JSON.parse(test.state.environment.AZURE_KEY_VAULT_SECRET_REFERENCES!), + REPLICA_LEARNING_DATABASE_URL: test.inputs.learning_database_secret.secret_id, + }) expect(test.state.environment.HUB_TRUSTED_PROXY_HOPS).toBe("1") test.state.verifyFailures = 1 test.state.recovery = "verify" @@ -1021,9 +1030,9 @@ it("blocks an origin change with Entra configured before creating shared secrets expect(test.uploads).toEqual([]) expect(test.plans).toEqual([]) expect(test.applies).toBe(0) - expect((await readdir(test.directory)).filter((name) => name.startsWith("post-bootstrap-"))).toEqual( - [], - ) + expect( + (await readdir(test.directory)).filter((name) => name.startsWith("post-bootstrap-")), + ).toEqual([]) }) it.each(["plain", "secret-backed"] as const)( @@ -1063,7 +1072,9 @@ it.each(["plain", "secret-backed"] as const)( .privateKey.export({ type: "pkcs8", format: "pem" }) .toString() const values = ["synthetic-client-secret", pem, "synthetic-webhook-secret-for-tests-only"] - const paths = values.map((_, index) => join(test.directory, `custom-origin-credential-${index}`)) + const paths = values.map((_, index) => + join(test.directory, `custom-origin-credential-${index}`), + ) await Promise.all(paths.map((path, index) => writeFile(path, values[index]!, { mode: 0o600 }))) vi.mocked(test.ui.text) .mockReset() @@ -1474,9 +1485,7 @@ it.each([ args.slice(0, 3).join(" ") === "keyvault secret set" && args[args.indexOf("--name") + 1] === "hub-bootstrap-secret" ) { - expect(test.uploads.map(({ name }) => name)).toEqual([ - "hub-authentication-encryption-key", - ]) + expect(test.uploads.map(({ name }) => name)).toEqual(["hub-authentication-encryption-key"]) throw new command.CommandExecutionError("Synthetic secret write failure", false, 1) } return execute(executable, args, options) @@ -1792,7 +1801,9 @@ it.each([ principalId, roleDefinitionId: lookup === "filtered duplicate" ? roleId.toUpperCase() : roleId, roleDefinitionName: - lookup === "conflicting retry" ? "Key Vault Administrator" : "Key Vault Secrets User", + lookup === "conflicting retry" + ? "Key Vault Administrator" + : "Key Vault Secrets User", }, ] return JSON.stringify( @@ -1873,9 +1884,7 @@ it.each([ test.run.mock.calls.some( ([executable, args]) => (executable === "terraform" && ["import", "state"].includes(args[1]!)) || - (executable === "az" && - args[0] === "role" && - ["create", "delete"].includes(args[2]!)), + (executable === "az" && args[0] === "role" && ["create", "delete"].includes(args[2]!)), ), ).toBe(false) }, diff --git a/infrastructure/azure/post/index.ts b/infrastructure/azure/post/index.ts index e769376dc..55cc588b5 100644 --- a/infrastructure/azure/post/index.ts +++ b/infrastructure/azure/post/index.ts @@ -155,6 +155,9 @@ export async function postSetupAzure( throw new Error("The deployed startup secret references are missing or unsupported.") const savedReferences = { DATABASE_URL: runtimeDatabase.secret_id, + ...(saved.learning_database_secret + ? { REPLICA_LEARNING_DATABASE_URL: saved.learning_database_secret.secret_id } + : {}), ...Object.fromEntries( Object.entries(saved.runtime_secret_references ?? {}).map(([key, reference]) => [ key, diff --git a/infrastructure/azure/post/types.ts b/infrastructure/azure/post/types.ts index dfa8f54b5..54bd652eb 100644 --- a/infrastructure/azure/post/types.ts +++ b/infrastructure/azure/post/types.ts @@ -23,6 +23,7 @@ export interface PostInputs extends Record { deploy_hub: boolean runtime_environment_variables?: Record runtime_secret_references?: Record + learning_database_secret?: { key_vault_id: string; secret_id: string } hub_application_origin?: string github_app_id?: string github_client_id?: string diff --git a/infrastructure/azure/provision/main.tf b/infrastructure/azure/provision/main.tf index 15d57eadd..b197b01d8 100644 --- a/infrastructure/azure/provision/main.tf +++ b/infrastructure/azure/provision/main.tf @@ -39,16 +39,24 @@ variable "vault_id" { error_message = "Supply the Key Vault resource ID that owns the provisioning secrets." } } +variable "mode" { + type = string + default = "provision" + validation { + condition = contains(["provision", "provision-learning"], var.mode) + error_message = "Choose provision for a fresh database or provision-learning for an existing installation." + } +} variable "secret_urls" { type = map(string) validation { condition = ( - toset(keys(var.secret_urls)) == toset(["DATABASE_URL", "HUB_MIGRATION_PASSWORD", "HUB_RUNTIME_PASSWORD"]) && + toset(keys(var.secret_urls)) == toset(var.mode == "provision" ? ["DATABASE_URL", "HUB_MIGRATION_PASSWORD", "HUB_RUNTIME_PASSWORD", "HUB_LEARNING_PASSWORD"] : ["DATABASE_URL", "HUB_LEARNING_PASSWORD"]) && alltrue([for secret in values(var.secret_urls) : can(regex("^https://[a-zA-Z0-9-]{1,24}\\.vault\\.azure\\.net/secrets/[a-zA-Z0-9-]{1,127}/[a-fA-F0-9]{32}$", secret)) ]) ) - error_message = "Provide exactly three versioned Key Vault references for the administrator URL and two role passwords, never raw values." + error_message = "Provide the exact versioned Key Vault references required by the provisioning mode, never raw values." } validation { condition = ( @@ -111,7 +119,7 @@ resource "azurerm_container_app_job" "provision" { image = var.image cpu = 0.5 memory = "1Gi" - command = ["node", "dist/server/scripts/azure-entrypoint/index.js", "provision"] + command = ["node", "dist/server/scripts/azure-entrypoint/index.js", var.mode] env { name = "NODE_ENV" value = "production" diff --git a/infrastructure/azure/provision/tests/provision.tftest.hcl b/infrastructure/azure/provision/tests/provision.tftest.hcl index 04ccd20fa..565b56f93 100644 --- a/infrastructure/azure/provision/tests/provision.tftest.hcl +++ b/infrastructure/azure/provision/tests/provision.tftest.hcl @@ -21,6 +21,7 @@ variables { DATABASE_URL = "https://testvault.vault.azure.net/secrets/postgres-admin-url/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-runtime-password/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" } } @@ -39,7 +40,7 @@ run "fresh_database_job_is_explicit_and_has_separate_access" { azurerm_container_app_job.provision.manual_trigger_config[0].replica_completion_count == 1 && azurerm_container_app_job.provision.template[0].container[0].command == tolist(["node", "dist/server/scripts/azure-entrypoint/index.js", "provision"]) && length(azurerm_container_app_job.provision.secret) == 0 && - length(azurerm_role_assignment.secrets) == 3 && + length(azurerm_role_assignment.secrets) == 4 && alltrue([for env in azurerm_container_app_job.provision.template[0].container[0].env : env.secret_name == null || env.secret_name == "" ]) @@ -68,6 +69,7 @@ run "fresh_database_job_is_explicit_and_has_separate_access" { "${var.vault_id}/secrets/postgres-admin-url", "${var.vault_id}/secrets/postgres-migration-password", "${var.vault_id}/secrets/postgres-runtime-password", + "${var.vault_id}/secrets/postgres-learning-password", ]) && alltrue([for grant in azurerm_role_assignment.secrets : grant.principal_id == azurerm_user_assigned_identity.provision.principal_id && @@ -80,7 +82,7 @@ run "fresh_database_job_is_explicit_and_has_separate_access" { one([for env in azurerm_container_app_job.provision.template[0].container[0].env : env.value if env.name == "AZURE_CLIENT_ID"]) == azurerm_user_assigned_identity.provision.client_id && tomap(jsondecode(one([for env in azurerm_container_app_job.provision.template[0].container[0].env : env.value if env.name == "AZURE_KEY_VAULT_SECRET_REFERENCES"]))) == var.secret_urls ) - error_message = "Only the isolated provisioning identity may receive three secret-scoped grants; its container must contain only production mode, its explicit client ID, and the exact URI-only administrator/password map." + error_message = "Only the isolated provisioning identity may receive the required secret-scoped grants and exact URI-only administrator/password map." } } @@ -98,6 +100,30 @@ run "public_digest_needs_no_registry_or_pull_grant" { } } +run "existing_installation_receives_only_learning_provisioning_secrets" { + command = plan + + variables { + mode = "provision-learning" + secret_urls = { + DATABASE_URL = "https://testvault.vault.azure.net/secrets/postgres-admin-url/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" + } + } + + assert { + condition = ( + azurerm_container_app_job.provision.template[0].container[0].command == tolist(["node", "dist/server/scripts/azure-entrypoint/index.js", "provision-learning"]) && + toset([for grant in azurerm_role_assignment.secrets : grant.scope]) == toset([ + "${var.vault_id}/secrets/postgres-admin-url", + "${var.vault_id}/secrets/postgres-learning-password", + ]) && + tomap(jsondecode(one([for env in azurerm_container_app_job.provision.template[0].container[0].env : env.value if env.name == "AZURE_KEY_VAULT_SECRET_REFERENCES"]))) == var.secret_urls + ) + error_message = "Existing installations must grant the job only the admin URL and learning password." + } +} + run "matching_vault_names_are_case_insensitive" { command = plan @@ -107,12 +133,13 @@ run "matching_vault_names_are_case_insensitive" { DATABASE_URL = "https://TestVault.vault.azure.net/secrets/postgres-admin-url/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://TESTVAULT.vault.azure.net/secrets/postgres-runtime-password/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" } } assert { condition = ( - length(azurerm_role_assignment.secrets) == 3 && + length(azurerm_role_assignment.secrets) == 4 && alltrue([for grant in azurerm_role_assignment.secrets : startswith(grant.scope, "${var.vault_id}/secrets/")]) && tomap(jsondecode(one([for env in azurerm_container_app_job.provision.template[0].container[0].env : env.value if env.name == "AZURE_KEY_VAULT_SECRET_REFERENCES"]))) == var.secret_urls ) @@ -130,13 +157,14 @@ run "mutable_image_is_rejected" { expect_failures = [var.image] } -run "all_three_provisioning_secrets_are_required" { +run "all_provisioning_secrets_are_required" { command = plan variables { secret_urls = { HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-runtime-password/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" } } @@ -151,6 +179,7 @@ run "additional_secret_access_is_rejected" { DATABASE_URL = "https://testvault.vault.azure.net/secrets/postgres-admin-url/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-runtime-password/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" EXTRA_SECRET = "https://testvault.vault.azure.net/secrets/extra/dddddddddddddddddddddddddddddddd" } } @@ -166,6 +195,7 @@ run "unversioned_secret_is_rejected" { DATABASE_URL = "https://testvault.vault.azure.net/secrets/postgres-admin-url" HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-runtime-password/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" } } @@ -200,6 +230,7 @@ run "secret_hosts_must_match_the_granted_vault" { DATABASE_URL = "https://another-vault.vault.azure.net/secrets/postgres-admin-url/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-migration-password/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-runtime-password/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/postgres-learning-password/dddddddddddddddddddddddddddddddd" } } @@ -215,6 +246,7 @@ run "maximum_length_secret_urls_are_accepted" { DATABASE_URL = "https://vvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/${join("", [for i in range(127) : "a"])}/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://vvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/${join("", [for i in range(127) : "b"])}/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://vvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/${join("", [for i in range(127) : "c"])}/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://vvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/${join("", [for i in range(127) : "d"])}/dddddddddddddddddddddddddddddddd" } } @@ -236,6 +268,7 @@ run "secret_urls_reject_oversized_vault" { DATABASE_URL = "https://vvvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/admin/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://vvvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/migration/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://vvvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/runtime/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://vvvvvvvvvvvvvvvvvvvvvvvvv.vault.azure.net/secrets/learning/dddddddddddddddddddddddddddddddd" } } @@ -250,6 +283,7 @@ run "secret_urls_reject_oversized_secret" { DATABASE_URL = "https://testvault.vault.azure.net/secrets/${join("", [for i in range(128) : "a"])}/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" HUB_MIGRATION_PASSWORD = "https://testvault.vault.azure.net/secrets/migration/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" HUB_RUNTIME_PASSWORD = "https://testvault.vault.azure.net/secrets/runtime/cccccccccccccccccccccccccccccccc" + HUB_LEARNING_PASSWORD = "https://testvault.vault.azure.net/secrets/learning/dddddddddddddddddddddddddddddddd" } } diff --git a/infrastructure/azure/roles.tf b/infrastructure/azure/roles.tf index 8d610f1fc..26853a4f3 100644 --- a/infrastructure/azure/roles.tf +++ b/infrastructure/azure/roles.tf @@ -1,6 +1,6 @@ locals { runtime_secret_scopes = toset([ - for secret in concat([var.runtime_database_secret], values(var.runtime_secret_references)) : + for secret in concat([var.runtime_database_secret], var.learning_database_secret == null ? [] : [var.learning_database_secret], values(var.runtime_secret_references)) : "${secret.key_vault_id}/secrets/${split("/", secret.secret_id)[4]}" ]) } diff --git a/infrastructure/azure/setup.tf b/infrastructure/azure/setup.tf index 6dfaf0ef7..c389cbfd7 100644 --- a/infrastructure/azure/setup.tf +++ b/infrastructure/azure/setup.tf @@ -35,15 +35,18 @@ resource "azurerm_container_app_job" "setup" { command = ["node", "dist/server/scripts/azure-entrypoint/index.js", "setup"] dynamic "env" { - for_each = { + for_each = merge({ NODE_ENV = "production" RUNTIME_MODE = "setup" DATABASE_RUNTIME_ROLE = "replica_runtime" AZURE_CLIENT_ID = azurerm_user_assigned_identity.setup.client_id AZURE_KEY_VAULT_SECRET_REFERENCES = jsonencode({ - DATABASE_URL = var.setup_database_secret.secret_id + DATABASE_URL = var.setup_database_secret.secret_id + REPLICA_LEARNING_MIGRATION_DATABASE_URL = var.setup_database_secret.secret_id }) - } + }, var.learning_database_secret == null ? {} : { + REPLICA_LEARNING_RUNTIME_ROLE = "replica_learning_runtime" + }) content { name = env.key value = env.value diff --git a/infrastructure/azure/tests/deployment.tftest.hcl b/infrastructure/azure/tests/deployment.tftest.hcl index 05abee56f..54993b33b 100644 --- a/infrastructure/azure/tests/deployment.tftest.hcl +++ b/infrastructure/azure/tests/deployment.tftest.hcl @@ -347,7 +347,8 @@ run "setup_and_runtime_have_separate_secret_access" { SERVICE_API_KEY = var.runtime_secret_references.SERVICE_API_KEY.secret_id }) && tomap(jsondecode(one([for env in azurerm_container_app_job.setup.template[0].container[0].env : env.value if env.name == "AZURE_KEY_VAULT_SECRET_REFERENCES"]))) == tomap({ - DATABASE_URL = var.setup_database_secret.secret_id + DATABASE_URL = var.setup_database_secret.secret_id + REPLICA_LEARNING_MIGRATION_DATABASE_URL = var.setup_database_secret.secret_id }) ) error_message = "Each container must receive only its explicit identity and URI-only startup metadata, without platform secrets, secret-name bindings, or resolved secret values." @@ -364,7 +365,7 @@ run "setup_and_runtime_have_separate_secret_access" { } : one([for env in azurerm_container_app_job.setup.template[0].container[0].env : env.value if env.name == name]) == value ]) ) - error_message = "Setup must receive only production/setup mode, its identity and migration URI metadata, and the fixed runtime grant target." + error_message = "SQLite setup must not grant an unprovisioned learning runtime role." } assert { condition = ( @@ -386,6 +387,28 @@ run "setup_and_runtime_have_separate_secret_access" { } } +run "learning_postgresql_uses_runtime_secret_and_setup_migration_identity" { + command = plan + + variables { + deploy_hub = true + learning_database_secret = { + key_vault_id = "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/secrets/providers/Microsoft.KeyVault/vaults/database" + secret_id = "https://database.vault.azure.net/secrets/learning-runtime/dddddddddddddddddddddddddddddddd" + } + } + + assert { + condition = ( + jsondecode(one([for env in azurerm_container_app.hub[0].template[0].container[0].env : env.value if env.name == "AZURE_KEY_VAULT_SECRET_REFERENCES"])).REPLICA_LEARNING_DATABASE_URL == var.learning_database_secret.secret_id && + contains([for grant in azurerm_role_assignment.runtime_secrets : grant.scope], "${var.learning_database_secret.key_vault_id}/secrets/learning-runtime") && + jsondecode(one([for env in azurerm_container_app_job.setup.template[0].container[0].env : env.value if env.name == "AZURE_KEY_VAULT_SECRET_REFERENCES"])).REPLICA_LEARNING_MIGRATION_DATABASE_URL == var.setup_database_secret.secret_id && + one([for env in azurerm_container_app_job.setup.template[0].container[0].env : env.value if env.name == "REPLICA_LEARNING_RUNTIME_ROLE"]) == "replica_learning_runtime" + ) + error_message = "Learning must use its own runtime secret and setup's migration identity." + } +} + run "runtime_environment_rejects_reserved_names" { command = plan variables { diff --git a/infrastructure/azure/variables.tf b/infrastructure/azure/variables.tf index 873a625a7..c927ddc7c 100644 --- a/infrastructure/azure/variables.tf +++ b/infrastructure/azure/variables.tf @@ -144,9 +144,31 @@ variable "setup_database_secret" { } } +variable "learning_database_secret" { + type = object({ + key_vault_id = string + secret_id = string + }) + default = null + description = "Optional Key Vault reference containing the replica_learning_runtime database URL. Set only after existing SQLite history is reconciled." + + validation { + condition = var.learning_database_secret == null ? true : ( + can(regex("^/subscriptions/[^/]+/resourceGroups/[^/]+/providers/Microsoft.KeyVault/vaults/[^/]+$", var.learning_database_secret.key_vault_id)) && + can(regex("^https://[a-zA-Z0-9-]{1,24}\\.vault\\.azure\\.net/secrets/[a-zA-Z0-9-]{1,127}(/[a-fA-F0-9]{32})?$", var.learning_database_secret.secret_id)) && + lower(try(split("/", var.learning_database_secret.secret_id)[2], "")) == "${lower(try(split("/", var.learning_database_secret.key_vault_id)[8], ""))}.vault.azure.net" && + alltrue([for secret in [var.runtime_database_secret, var.setup_database_secret] : + lower("${secret.key_vault_id}/secrets/${try(split("/", secret.secret_id)[4], "")}") != lower("${var.learning_database_secret.key_vault_id}/secrets/${try(split("/", var.learning_database_secret.secret_id)[4], "")}") + ]) + ) + error_message = "Supply a separate learning runtime secret URL and its Key Vault resource ID." + } +} + locals { runtime_reserved_environment_names = [ "DATABASE_URL", "DATABASE_RUNTIME_ROLE", "NODE_ENV", "RUNTIME_MODE", "HOST", "PORT", + "REPLICA_LEARNING_DATABASE_URL", "REPLICA_LEARNING_MIGRATION_DATABASE_URL", "REPLICA_LEARNING_RUNTIME_ROLE", "CLIENT_DIRECTORY", "SHUTDOWN_TIMEOUT_MS", "ARTIFACT_STORAGE_PROVIDER", "ARTIFACT_STORAGE_DIRECTORY", "AZURE_STORAGE_ACCOUNT", "AZURE_STORAGE_CONTAINER", "AZURE_CLIENT_ID", "AZURE_KEY_VAULT_SECRET_REFERENCES", @@ -266,12 +288,12 @@ variable "runtime_secret_references" { description = "Existing RBAC Key Vault secret references keyed by uppercase runtime environment name. Values remain outside Terraform." validation { - condition = length(keys(var.runtime_secret_references)) <= 63 && alltrue([ + condition = length(keys(var.runtime_secret_references)) <= (var.learning_database_secret == null ? 63 : 62) && alltrue([ for name in keys(var.runtime_secret_references) : can(regex("^[A-Z][A-Z0-9_]{0,40}$", name)) && !contains(concat(local.runtime_reserved_environment_names, ["GITHUB_APP_ID", "GITHUB_CLIENT_ID", "GITHUB_APP_INSTALLATION_ID", "GITHUB_PROVIDER_REVISION"]), name) ]) - error_message = "Supply at most 63 additional secret references, using uppercase environment names of at most 41 characters; deployment-owned settings cannot be overridden." + error_message = "Supply at most 63 additional secret references (62 with a learning database), using uppercase environment names of at most 41 characters; deployment-owned settings cannot be overridden." } validation { diff --git a/scripts/check-ci-workflows/index.test.ts b/scripts/check-ci-workflows/index.test.ts index 0b2bbba10..6db6e1a91 100644 --- a/scripts/check-ci-workflows/index.test.ts +++ b/scripts/check-ci-workflows/index.test.ts @@ -39,6 +39,19 @@ describe("checkWorkflows()", () => { expect(() => checkWorkflows(root)).not.toThrow() }) + it("rejects Hub checks without the learning runtime", () => { + const directory = fixture() + const path = join(directory, ".github/workflows/hub-ci.yml") + const workflow = parse(readFileSync(path, "utf8")) as Workflow + assert(workflow.jobs.check.steps) + workflow.jobs.check.steps = workflow.jobs.check.steps.filter( + (step) => + step.run !== "npm ci --prefix ../packages/learning --ignore-scripts --engine-strict", + ) + writeFileSync(path, stringify(workflow)) + expect(() => checkWorkflows(directory)).toThrow(/learning runtime/) + }) + it("rejects an aggregate result gate", () => { const directory = fixture() const path = join(directory, ".github/workflows/hub-ci.yml") diff --git a/scripts/check-ci-workflows/index.ts b/scripts/check-ci-workflows/index.ts index c5c150354..754c55dbb 100644 --- a/scripts/check-ci-workflows/index.ts +++ b/scripts/check-ci-workflows/index.ts @@ -78,6 +78,13 @@ export function checkWorkflows(root: string): void { "test:database", ]) assert(hub.check.steps?.some((step) => step.run === "npm run ${{ matrix.command }}")) + assert( + hub.check.steps?.some( + (step) => + step.run === "npm ci --prefix ../packages/learning --ignore-scripts --engine-strict", + ), + "Hub checks must install the learning runtime", + ) for (const command of [ "controls:test", "extension:test", From 4439c425073228fb31c85360a7781c4db1f6c7d8 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sun, 29 Nov 2026 11:29:04 -0800 Subject: [PATCH 02/23] fix(hub): give the learning login every privilege the package needs A new repository scope writes through triggers that maintain the decision tables, and deleting learnings needs DELETE. The grant script missed those, so the restricted login could not open a fresh scope. It now matches the package's documented runtime privileges, and a database test runs real commands as that login. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../index.db.test.ts | 80 +++++++++++++++++++ .../grant-learning-database-access/index.ts | 29 +++---- 2 files changed, 93 insertions(+), 16 deletions(-) create mode 100644 hub/server/scripts/grant-learning-database-access/index.db.test.ts diff --git a/hub/server/scripts/grant-learning-database-access/index.db.test.ts b/hub/server/scripts/grant-learning-database-access/index.db.test.ts new file mode 100644 index 000000000..bfe322151 --- /dev/null +++ b/hub/server/scripts/grant-learning-database-access/index.db.test.ts @@ -0,0 +1,80 @@ +import { execFile } from "node:child_process" +import { randomBytes, randomUUID } from "node:crypto" +import { mkdtemp, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { fileURLToPath } from "node:url" +import { promisify } from "node:util" +import pg from "pg" +import { describe, expect, it } from "vitest" + +import { runLearningCommand } from "../../integrations/learning/run-learning-command/index.ts" +import { learningStoreArguments } from "../../domains/learning/learning-store-arguments/index.ts" +import { grantLearningDatabaseAccess } from "./index.ts" + +const cliPath = fileURLToPath( + new URL("../../../../packages/learning/bin/replica-learning.mjs", import.meta.url), +) + +describe("grantLearningDatabaseAccess()", () => { + it("lets the learning login open a new repository and delete its learnings", async () => { + const adminUrl = process.env.TEST_DATABASE_URL + if (!adminUrl) throw new Error("TEST_DATABASE_URL is required.") + const name = `replica_learning_grants_${randomBytes(8).toString("hex")}` + const password = randomBytes(16).toString("hex") + const admin = new pg.Client({ connectionString: adminUrl }) + await admin.connect() + const directory = await mkdtemp(join(tmpdir(), "replica-learning-grants-")) + try { + await admin.query(`CREATE DATABASE ${pg.escapeIdentifier(name)}`) + await admin.query( + `DO $$ BEGIN + CREATE ROLE replica_learning_runtime LOGIN; + EXCEPTION WHEN duplicate_object THEN NULL; + END $$`, + ) + await admin.query( + `ALTER ROLE replica_learning_runtime LOGIN PASSWORD ${pg.escapeLiteral(password)}`, + ) + await admin.query( + `GRANT CONNECT ON DATABASE ${pg.escapeIdentifier(name)} TO replica_learning_runtime`, + ) + const migrationUrl = new URL(adminUrl) + migrationUrl.pathname = name + await promisify(execFile)(process.execPath, [cliPath, "migrate"], { + env: { ...process.env, REPLICA_LEARNING_MIGRATION_DATABASE_URL: migrationUrl.toString() }, + timeout: 60_000, + }) + await grantLearningDatabaseAccess(migrationUrl.toString()) + const runtimeUrl = new URL(migrationUrl) + runtimeUrl.username = "replica_learning_runtime" + runtimeUrl.password = password + const store = learningStoreArguments({ + directory, + repositoryId: randomUUID(), + repositoryScope: "github.com/repositories/1", + }) + const options = { cliPath, learningDatabaseUrl: runtimeUrl.toString() } + + await expect(runLearningCommand(["memories", ...store], options)).resolves.toEqual([]) + await expect( + runLearningCommand( + [ + "delete-repository", + "--by", + "github:admin", + "--confirm", + "repositories/1", + ...store, + ], + options, + ), + ).resolves.toBeDefined() + } finally { + await rm(directory, { force: true, recursive: true }) + await admin.query(`DROP DATABASE IF EXISTS ${pg.escapeIdentifier(name)} WITH (FORCE)`) + await admin.query("DROP ROLE IF EXISTS replica_learning_runtime") + await admin.end() + } + }, 120_000) +}) diff --git a/hub/server/scripts/grant-learning-database-access/index.ts b/hub/server/scripts/grant-learning-database-access/index.ts index 5ad49fc29..7d79a27f0 100644 --- a/hub/server/scripts/grant-learning-database-access/index.ts +++ b/hub/server/scripts/grant-learning-database-access/index.ts @@ -12,25 +12,22 @@ export async function grantLearningDatabaseAccess(databaseUrl: string) { await client.connect() await client.query("BEGIN") await client.query("REVOKE ALL ON SCHEMA replica_learning FROM PUBLIC") - await client.query("GRANT USAGE ON SCHEMA replica_learning TO replica_learning_runtime") - await client.query( - "GRANT SELECT, INSERT, UPDATE ON replica_learning.records TO replica_learning_runtime", - ) await client.query( "REVOKE UPDATE ON replica_learning.memory_versions FROM replica_learning_runtime", ) - await client.query( - "GRANT SELECT, INSERT ON replica_learning.memory_versions TO replica_learning_runtime", - ) - await client.query( - "GRANT SELECT, INSERT ON replica_learning.scope_migrations, replica_learning.sqlite_imports TO replica_learning_runtime", - ) - await client.query( - "GRANT USAGE ON ALL SEQUENCES IN SCHEMA replica_learning TO replica_learning_runtime", - ) - await client.query( - "GRANT SELECT ON replica_learning.schema_migrations TO replica_learning_runtime", - ) + // Match the runtime privileges in packages/learning/README.md#postgresql-storage. + // Writes fire triggers that maintain the decision tables, so those need grants too. + for (const statement of [ + "GRANT USAGE ON SCHEMA replica_learning", + "GRANT SELECT ON replica_learning.schema_migrations", + "GRANT SELECT, INSERT, UPDATE, DELETE ON replica_learning.records", + "GRANT SELECT, INSERT, UPDATE ON replica_learning.decision_generations", + "GRANT SELECT, INSERT, DELETE ON replica_learning.memory_versions, replica_learning.decision_memory_targets, replica_learning.decision_grant_sources", + "GRANT SELECT, INSERT ON replica_learning.decision_withdrawal_targets, replica_learning.decision_migration_origins, replica_learning.scope_migrations, replica_learning.sqlite_imports", + "GRANT USAGE ON ALL SEQUENCES IN SCHEMA replica_learning", + ]) { + await client.query(`${statement} TO replica_learning_runtime`) + } await client.query("COMMIT") } finally { await client.end() From c050cff88bab4674bf3a26877e1a0cbebf500567 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sun, 29 Nov 2026 11:30:18 -0800 Subject: [PATCH 03/23] fix(hub): keep pre-upgrade review snapshots when reviews are unchanged Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../index.db.test.ts | 37 +++++++++++++++++++ .../index.ts | 27 ++++++++++++-- 2 files changed, 61 insertions(+), 3 deletions(-) diff --git a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.db.test.ts b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.db.test.ts index 450b2f3cc..c8ebd0312 100644 --- a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.db.test.ts +++ b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.db.test.ts @@ -451,6 +451,43 @@ describe("createHubDecisionTasksetSource() training exports", () => { await expect(access(directory)).rejects.toMatchObject({ code: "ENOENT" }) }, 60_000) + it("keeps a pre-upgrade checkpoint's snapshot when its reviews are unchanged", async () => { + const root = await workspace() + const databaseUrl = await learningDatabase(root) + const { repository } = await reviewedRepository() + await addGrant(root, repository.id, ["review", "training"]) + const request = { repositoryId: repository.id, actorMembershipId: randomUUID() } + const path = join( + root, + ".replica", + "learning", + "repositories", + repository.id, + "decision-review-snapshot.json", + ) + const original = await source(root).exportTrainingEvidence(request) + const snapshot = await captureRepositoryReviewSnapshot(prisma, repository.id) + const { legacyDigest } = createHubReviewCollection( + snapshot, + "https://hub.example.test", + repositoryScope, + ) + const checkpoint = readableLegacySnapshot(await readFile(path, "utf8")) + if (!checkpoint) throw new Error("Expected the initial SQLite checkpoint.") + await writeFile(path, `${JSON.stringify({ ...checkpoint, digest: legacyDigest })}\n`) + await importSqlite(root, repository.id, databaseUrl) + + const upgraded = await source(root, databaseUrl).exportTrainingEvidence(request) + + expect(exported(upgraded.bytes).collections).toEqual(exported(original.bytes).collections) + await expect( + prisma.decisionReviewSnapshot.findUniqueOrThrow({ where: { repositoryId: repository.id } }), + ).resolves.toMatchObject({ + digest: original.repeatableReviewSnapshotDigest, + snapshotId: checkpoint.snapshotId, + }) + }, 60_000) + it("preserves a no-consent snapshot from the SQLite file during cutover", async () => { const root = await workspace() const databaseUrl = await learningDatabase(root) diff --git a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts index cbed8e8ec..f901272b6 100644 --- a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts +++ b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts @@ -271,16 +271,35 @@ async function readLegacyReviewSnapshot(directory: string) { } } +/** + * Picks the checkpoint to save for the current reviews. Files written before reviews + * were tied to a repository ID hold a review-only digest. When the reviews still match + * it, the old snapshot ID and capture time carry over, so the first run after an + * upgrade doesn't import the same reviews again. + */ +function nextReviewSnapshot( + previous: { digest: string; snapshotId: string; capturedAt: Date } | null, + digest: string, + legacyDigest: string, + capturedAt: Date, +) { + if (previous?.digest === digest || previous?.digest === legacyDigest) { + return { digest, snapshotId: previous.snapshotId, capturedAt: previous.capturedAt } + } + return { digest, snapshotId: randomUUID(), capturedAt } +} + async function stabilizeLocalReviewSnapshot( directory: string, digest: string, + legacyDigest: string, capturedAt: Date, signal: AbortSignal, ): Promise<{ snapshotId: string; capturedAt: Date }> { const previous = await readLegacyReviewSnapshot(directory) signal.throwIfAborted() if (previous?.digest === digest) return previous - const next = { digest, snapshotId: randomUUID(), capturedAt } + const next = nextReviewSnapshot(previous, digest, legacyDigest, capturedAt) const temporary = join(directory, `.decision-review-snapshot-${randomUUID()}`) const handle = await open( temporary, @@ -308,6 +327,7 @@ async function stabilizeReviewSnapshot( repositoryId: string, directory: string, digest: string, + legacyDigest: string, capturedAt: Date, signal: AbortSignal, ): Promise<{ snapshotId: string; capturedAt: Date }> { @@ -316,8 +336,7 @@ async function stabilizeReviewSnapshot( const previous = stored ?? (await readLegacyReviewSnapshot(directory)) signal.throwIfAborted() if (stored?.digest === digest) return stored - const next = - previous?.digest === digest ? previous : { digest, snapshotId: randomUUID(), capturedAt } + const next = nextReviewSnapshot(previous, digest, legacyDigest, capturedAt) if (!(await saveDecisionReviewSnapshot(lockClient, repositoryId, next, stored))) { throw new DecisionModelError( 409, @@ -1096,12 +1115,14 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource repositoryId, store.directory, initialReview.digest, + initialReview.legacyDigest, snapshot.capturedAt, signal, ) : await stabilizeLocalReviewSnapshot( store.directory, initialReview.digest, + initialReview.legacyDigest, snapshot.capturedAt, signal, ) From 7a86ebd2c0bb676eb4462e8d624e103688741545 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sun, 29 Nov 2026 11:32:37 -0800 Subject: [PATCH 04/23] feat(learning): list redaction follow-ups without re-checking every record Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- packages/learning/README.md | 2 +- packages/learning/src/cli.mjs | 14 +++++++ packages/learning/src/store.mjs | 40 ++++++++++++------- .../learning/test/scope-migration.test.mjs | 4 ++ 4 files changed, 44 insertions(+), 16 deletions(-) diff --git a/packages/learning/README.md b/packages/learning/README.md index 6d45566b3..1b0c1dc47 100644 --- a/packages/learning/README.md +++ b/packages/learning/README.md @@ -179,7 +179,7 @@ Hosts such as Hub can serve the same tools by importing `createLearningMcpServer - In a checkout, `origin` names a GitHub repository. The command looks up its numeric ID with the person's GitHub CLI sign-in and saves it in the local config, so later commands use `github.com/repositories/` without a network request. If the remote changes, the command looks up the new repository; if it cannot look up an uncached ID, it stops instead of guessing. A host such as Hub names the same scope with `--repository github.com/repositories/` and the store with `--dir`; if that directory is inside a checkout, Git must ignore it. The scope is asserted by whoever runs the command, not checked repository access, so a host checks access before it runs one. Every record carries its scope, and a store reads and writes only records in the caller's scope. Output never shows a user name or password from the remote URL. - To migrate an existing checkout, stop all clients using the store, confirm the old repository name belongs to the current GitHub repository, and run `replica-learning migrate-scope --offline`. If the repository was renamed before the upgrade, add `--legacy-repository github.com/old-owner/old-name`. Repeat the command with each confirmed historical name if the same store contains more than one. A custom provider that cannot enumerate old scopes requires the old name explicitly. For a new empty custom store, run `replica-learning migrate-scope --offline --empty` instead; it keeps the configured provider. SQLite moves each history in one transaction and refuses old-scope writes. For JSON Lines and custom providers, the command verifies and copies this repository's history into a new SQLite file, then selects it in the local config. It leaves the original store untouched; verify the new store before removing any old data, which may still contain private or later-redacted text. If the original provider held other repositories, their data remains there: restore `memory.provider` from `memory.migration.sourceProvider` and remove `memory.migration` before migrating another repository. Do not run older clients against the original store after copying it; their writes would not appear in the new store. - Histories of the same Hub review thread retain their records and share redaction, retraction, and consent checks. Matching snapshots retain both original collection records. Migration refuses conflicting comment versions or different contents under the same snapshot ID without changing either history. -- When merging histories reveals a redaction, the command reports affected exports and accepted learnings on migration and retry. Other local store commands also warn on standard error after automatic migration. Follow up on each export and rebuild the affected learnings. `replica-learning status` retains this information for later review. +- When merging histories reveals a redaction, the command reports affected exports and accepted learnings on migration and retry. Other local store commands also warn on standard error after automatic migration. Follow up on each export and rebuild the affected learnings. `replica-learning status` retains this information for later review. `replica-learning status --follow-ups` lists only these follow-ups and skips re-checking every record, so it stays fast on large stores. - The purposes are review, instruction, evaluation, analytics, training, and publication. Permission for one never implies another. A grant names its purposes and sources, and optionally the range of evidence times it covers. It covers a comment when it names the comment's source and its range contains the time the comment was written. A label counts only while the comment it judges does. - Withdrawing a purpose takes effect at once. Evidence stops serving that purpose, learnings built on it stop being recalled, and the command lists earlier exports that already copied it so their owners can be asked to delete it. A learning depends on its counterevidence too: it is used only while both the evidence and the contradictions a reviewer saw permit the purpose. - Evidence is append-only. An edited comment adds a version that supersedes the old one. A thread that someone resolves or reopens adds a status change, and so does a thread resolved again since the last import. A deleted comment adds a retraction that removes the earlier versions, and labels on them, from every purpose. Nothing is rewritten, with one exception the contract allows: a provider may remove an event's payload and record why in `redaction`. The event's digest still verifies, and a redacted event is never evidence. Labels and retractions name the event they apply to in `parentEventId`, which must match the payload and which the digest covers, so redacting one never loses its target and a redacted retraction still retracts. diff --git a/packages/learning/src/cli.mjs b/packages/learning/src/cli.mjs index 33d2d3112..f1f38fb04 100644 --- a/packages/learning/src/cli.mjs +++ b/packages/learning/src/cli.mjs @@ -63,6 +63,8 @@ Set up Inspect status Counts and anything that needs attention + [--follow-ups] Only exports and learnings to revisit after merged + histories removed comment text; skips record checks doctor Which provider, consolidator, scope, and directory are in use, and why observations [--purpose

] [--event ]... Evidence a purpose may use now; select up to @@ -250,6 +252,7 @@ const OPTIONS = { comment: { type: "string" }, budget: { type: "string" }, preview: { type: "boolean" }, + "follow-ups": { type: "boolean" }, out: { type: "string" }, "learnings-only": { type: "boolean" }, export: { type: "string" }, @@ -881,6 +884,7 @@ async function setup(session) { async function status(session) { const { store, providerSource } = await open(session) + if (session.values["follow-ups"]) return statusFollowUps(session, store) const result = await store.status(context(session, actor(session))) const { counts } = result const memories = counts?.memories @@ -913,6 +917,16 @@ async function status(session) { return counts ? 0 : 1 } +async function statusFollowUps(session, store) { + const followUps = await store.redactionFollowUps(context(session, actor(session))) + const pending = followUps.memoriesNeedingRebuild.length || followUps.exportsToFollowUp.length + session.out( + pending ? { migrationRedactionFollowUps: followUps } : {}, + pending ? redactionFollowUpLines(followUps).join("\n") : "Nothing needs follow-up.", + ) + return 0 +} + async function doctor(session) { const { environment } = session const report = { diff --git a/packages/learning/src/store.mjs b/packages/learning/src/store.mjs index 722018a70..65c0636ff 100644 --- a/packages/learning/src/store.mjs +++ b/packages/learning/src/store.mjs @@ -5316,6 +5316,30 @@ class LearningStore { * Counts and anything that needs a person's attention. When stored records fail their * checks, every other operation is blocked, so status reports only that. */ + /** + * List the exports to check and the learnings to rebuild because merging histories + * removed comment text. It reads only migration records, so a page can show these + * without waiting for status to re-check every record. + */ + async redactionFollowUps(context) { + assertContext(context) + const migrations = (await this.#provider.scopeMigrations?.(context.scope)) ?? [] + return { + memoriesNeedingRebuild: unique( + migrations.flatMap( + (migration) => migration.redactionFollowUps?.memoriesNeedingRebuild ?? [], + ), + ), + exportsToFollowUp: [ + ...new Map( + migrations + .flatMap((migration) => migration.redactionFollowUps?.exportsToFollowUp ?? []) + .map((item) => [item.id, item]), + ).values(), + ], + } + } + async status(context) { assertContext(context) const integrity = await this.verify(context) @@ -5345,21 +5369,7 @@ class LearningStore { } } const [{ eligibility, grants }, observations, { items }, collections] = read - const migrations = (await this.#provider.scopeMigrations?.(context.scope)) ?? [] - const followUps = { - memoriesNeedingRebuild: unique( - migrations.flatMap( - (migration) => migration.redactionFollowUps?.memoriesNeedingRebuild ?? [], - ), - ), - exportsToFollowUp: [ - ...new Map( - migrations - .flatMap((migration) => migration.redactionFollowUps?.exportsToFollowUp ?? []) - .map((item) => [item.id, item]), - ).values(), - ], - } + const followUps = await this.redactionFollowUps(context) const states = { proposed: 0, accepted: 0, rejected: 0, retired: 0 } for (const item of items) states[item.record.state]++ const attention = [ diff --git a/packages/learning/test/scope-migration.test.mjs b/packages/learning/test/scope-migration.test.mjs index a29591cc5..9a30f7231 100644 --- a/packages/learning/test/scope-migration.test.mjs +++ b/packages/learning/test/scope-migration.test.mjs @@ -1201,6 +1201,10 @@ it("reports redaction follow-ups on migration and retry", async () => { item.destination === "private/exports/other.json", ), ) + assert.deepEqual( + ok(repo, ["status", "--follow-ups"], { failLookup: true }).migrationRedactionFollowUps, + followUps, + ) const retry = ok(repo, migrate, { failLookup: true }) assert.deepEqual(retry.redactionFollowUps, followUps) const retryText = cli(repo, migrate, { failLookup: true, json: false }) From 46b5473edc146a9f7fe185493f72eb9b1577bc1a Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sun, 29 Nov 2026 11:32:37 -0800 Subject: [PATCH 05/23] perf(hub): load learning follow-ups without a full store check Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../domains/learning/get-learning-overview/index.test.ts | 1 + hub/server/domains/learning/get-learning-overview/index.ts | 5 ++++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/hub/server/domains/learning/get-learning-overview/index.test.ts b/hub/server/domains/learning/get-learning-overview/index.test.ts index 297baa0e2..a3ae53c72 100644 --- a/hub/server/domains/learning/get-learning-overview/index.test.ts +++ b/hub/server/domains/learning/get-learning-overview/index.test.ts @@ -260,6 +260,7 @@ describe("getLearningOverview()", () => { for (const [arguments_] of statusCalls) expect(arguments_).toEqual( expect.arrayContaining([ + "--follow-ups", "--repository", "github.com/repositories/123", "--legacy-repository", diff --git a/hub/server/domains/learning/get-learning-overview/index.ts b/hub/server/domains/learning/get-learning-overview/index.ts index 6067e4858..cece391f7 100644 --- a/hub/server/domains/learning/get-learning-overview/index.ts +++ b/hub/server/domains/learning/get-learning-overview/index.ts @@ -162,7 +162,10 @@ export async function getLearningOverview(input: { repositoryScope: input.repositoryScope, }) const rawMemories = await runLearningCommand(["memories", ...commonArguments], commandOptions) - const rawStatus = await runLearningCommand(["status", ...commonArguments], commandOptions) + const rawStatus = await runLearningCommand( + ["status", "--follow-ups", ...commonArguments], + commandOptions, + ) const rawRecall = await runLearningCommand( ["recall", "--preview", "--by", input.viewer, ...commonArguments], commandOptions, From c90d4adac8d216bae0b85fdb433ff78a9e5c9715 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sun, 29 Nov 2026 11:36:08 -0800 Subject: [PATCH 06/23] fix(hub): let the local developer administer the decision walkthrough Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../index.db.test.ts | 19 +++++++------- .../index.ts | 7 +++--- .../index.db.test.ts | 25 ++++++++++++------- .../index.ts | 11 +++----- 4 files changed, 34 insertions(+), 28 deletions(-) diff --git a/hub/server/repositories/repository-access/lock-repository-administrator-authority/index.db.test.ts b/hub/server/repositories/repository-access/lock-repository-administrator-authority/index.db.test.ts index f1d36e4de..1f4acd97a 100644 --- a/hub/server/repositories/repository-access/lock-repository-administrator-authority/index.db.test.ts +++ b/hub/server/repositories/repository-access/lock-repository-administrator-authority/index.db.test.ts @@ -101,6 +101,16 @@ describe("lockRepositoryAdministratorAuthority()", () => { await expect(authorize(membership.id, repository.id)).resolves.toBe(true) }) + it("authorizes the local developer for a local repository with a GitHub ID", async () => { + const { membership, repository } = await createLocalAuthority() + await prisma.repository.update({ + data: { githubRepositoryId: 17n }, + where: { id: repository.id }, + }) + + await expect(authorize(membership.id, repository.id)).resolves.toBe(true) + }) + it("does not substitute an ordinary identity for fixed local authority", async () => { const { membership, repository } = await createLocalAuthority({ issuer: "https://github.com", @@ -121,15 +131,6 @@ describe("lockRepositoryAdministratorAuthority()", () => { }) }, ], - [ - "GitHub-linked repository", - async ({ repository }: Awaited>) => { - await prisma.repository.update({ - data: { githubRepositoryId: 17n }, - where: { id: repository.id }, - }) - }, - ], [ "repository without a local path", async ({ repository }: Awaited>) => { diff --git a/hub/server/repositories/repository-access/lock-repository-administrator-authority/index.ts b/hub/server/repositories/repository-access/lock-repository-administrator-authority/index.ts index 4191b46f1..2c9e00b1e 100644 --- a/hub/server/repositories/repository-access/lock-repository-administrator-authority/index.ts +++ b/hub/server/repositories/repository-access/lock-repository-administrator-authority/index.ts @@ -62,11 +62,12 @@ export async function lockRepositoryAdministratorAuthority( FOR SHARE ` if (grant?.accessLevel !== "ADMIN") return false + // A local path wins over a GitHub ID: the decision model walkthrough keeps a + // verified GitHub ID for learning on a local repository. Local sign-in only runs in + // development, and GitHub-connected repositories never get a local path. if (repository.localPath !== null) { return ( - repository.githubRepositoryId === null && - Boolean(localIdentity) && - Boolean(localProvider?.enabled && localProvider.selectedRevisionId) + Boolean(localIdentity) && Boolean(localProvider?.enabled && localProvider.selectedRevisionId) ) } return ( diff --git a/hub/server/repositories/repository-access/lock-repository-administrator-session/index.db.test.ts b/hub/server/repositories/repository-access/lock-repository-administrator-session/index.db.test.ts index 3b3ac26c3..a336d97d2 100644 --- a/hub/server/repositories/repository-access/lock-repository-administrator-session/index.db.test.ts +++ b/hub/server/repositories/repository-access/lock-repository-administrator-session/index.db.test.ts @@ -150,6 +150,22 @@ describe("lockRepositoryAdministratorSession()", () => { ).resolves.toBe(true) }) + it("authorizes the local session for a local repository with a GitHub ID", async () => { + const { membership, repository, sessionDigest } = await createLocalSessionAuthority() + await prisma.repository.update({ + data: { githubRepositoryId: 17n }, + where: { id: repository.id }, + }) + + await expect( + authorize({ + membershipId: membership.id, + repositoryId: repository.id, + sessionDigest, + }), + ).resolves.toBe(true) + }) + it("does not substitute an ordinary identity for the fixed local session", async () => { const { membership, repository, sessionDigest } = await createLocalSessionAuthority({ issuer: "local", @@ -176,15 +192,6 @@ describe("lockRepositoryAdministratorSession()", () => { }) }, ], - [ - "GitHub-linked repository", - async ({ repository }: Awaited>) => { - await prisma.repository.update({ - data: { githubRepositoryId: 17n }, - where: { id: repository.id }, - }) - }, - ], [ "repository without a local path", async ({ repository }: Awaited>) => { diff --git a/hub/server/repositories/repository-access/lock-repository-administrator-session/index.ts b/hub/server/repositories/repository-access/lock-repository-administrator-session/index.ts index c9b6a177c..c7c2106f9 100644 --- a/hub/server/repositories/repository-access/lock-repository-administrator-session/index.ts +++ b/hub/server/repositories/repository-access/lock-repository-administrator-session/index.ts @@ -124,14 +124,11 @@ export async function lockRepositoryAdministratorSession( FOR SHARE ` if (!repository || repository.removedAt !== null) return false + // A local path wins over a GitHub ID: the decision model walkthrough keeps a + // verified GitHub ID for learning on a local repository. Local sign-in only runs in + // development, and GitHub-connected repositories never get a local path. if (repository.localPath !== null) { - if ( - candidate.providerKey !== "local" || - repository.githubRepositoryId !== null || - !localIdentity - ) { - return false - } + if (candidate.providerKey !== "local" || !localIdentity) return false } else { const githubProvider = providers.find(({ key }) => key === "github") if ( From 4799e32cae0efcd6ee82a7b5bc9736536a93cccd Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sun, 29 Nov 2026 11:46:00 -0800 Subject: [PATCH 07/23] fix(infrastructure): skip the release lease when provisioning has no work left Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- infrastructure/azure/install/provision/index.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/infrastructure/azure/install/provision/index.ts b/infrastructure/azure/install/provision/index.ts index 9b6f15faf..58d62901a 100644 --- a/infrastructure/azure/install/provision/index.ts +++ b/infrastructure/azure/install/provision/index.ts @@ -35,6 +35,13 @@ export async function provisionDatabase( const learningModule = moduleFor("learning-provision") await freshModule.init(backend) await learningModule.init(learningBackend) + if ( + (await secrets.provisioned()) && + (await secrets.learningProvisioned()) && + !(await freshModule.state()).length && + !(await learningModule.state()).length + ) + return const lease = await acquireLease( context, installation.storage_account, From 90702fcb9e0a9e7d07a5b88c577b826865eaacef Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sun, 29 Nov 2026 11:50:13 -0800 Subject: [PATCH 08/23] style(infrastructure): restore original formatting Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- infrastructure/azure/post/configure/index.ts | 6 ++++-- infrastructure/azure/post/index.test.ts | 22 ++++++++++---------- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/infrastructure/azure/post/configure/index.ts b/infrastructure/azure/post/configure/index.ts index 0ea79165e..0a79a430e 100644 --- a/infrastructure/azure/post/configure/index.ts +++ b/infrastructure/azure/post/configure/index.ts @@ -752,7 +752,8 @@ export async function configurePostSetup( next.github_app_installation_id !== deployment.environment.GITHUB_APP_INSTALLATION_ID || credentials.some( ({ key }) => - references[key]?.secret_id !== (liveSecretReferences as Record)[key], + references[key]?.secret_id !== + (liveSecretReferences as Record)[key], ) const storedRevision = await verifiedGitHubRevision() const savedRevision = @@ -809,7 +810,8 @@ export async function configurePostSetup( ]) delete next.runtime_environment_variables[name] replacements.sort( - (left, right) => Number(right.key === progress.pending) - Number(left.key === progress.pending), + (left, right) => + Number(right.key === progress.pending) - Number(left.key === progress.pending), ) for (const credential of replacements) references[credential.key] = await put(credential.key, credential.name, credential.value) diff --git a/infrastructure/azure/post/index.test.ts b/infrastructure/azure/post/index.test.ts index a08f7e682..5e7a91c96 100644 --- a/infrastructure/azure/post/index.test.ts +++ b/infrastructure/azure/post/index.test.ts @@ -1030,9 +1030,9 @@ it("blocks an origin change with Entra configured before creating shared secrets expect(test.uploads).toEqual([]) expect(test.plans).toEqual([]) expect(test.applies).toBe(0) - expect( - (await readdir(test.directory)).filter((name) => name.startsWith("post-bootstrap-")), - ).toEqual([]) + expect((await readdir(test.directory)).filter((name) => name.startsWith("post-bootstrap-"))).toEqual( + [], + ) }) it.each(["plain", "secret-backed"] as const)( @@ -1072,9 +1072,7 @@ it.each(["plain", "secret-backed"] as const)( .privateKey.export({ type: "pkcs8", format: "pem" }) .toString() const values = ["synthetic-client-secret", pem, "synthetic-webhook-secret-for-tests-only"] - const paths = values.map((_, index) => - join(test.directory, `custom-origin-credential-${index}`), - ) + const paths = values.map((_, index) => join(test.directory, `custom-origin-credential-${index}`)) await Promise.all(paths.map((path, index) => writeFile(path, values[index]!, { mode: 0o600 }))) vi.mocked(test.ui.text) .mockReset() @@ -1485,7 +1483,9 @@ it.each([ args.slice(0, 3).join(" ") === "keyvault secret set" && args[args.indexOf("--name") + 1] === "hub-bootstrap-secret" ) { - expect(test.uploads.map(({ name }) => name)).toEqual(["hub-authentication-encryption-key"]) + expect(test.uploads.map(({ name }) => name)).toEqual([ + "hub-authentication-encryption-key", + ]) throw new command.CommandExecutionError("Synthetic secret write failure", false, 1) } return execute(executable, args, options) @@ -1801,9 +1801,7 @@ it.each([ principalId, roleDefinitionId: lookup === "filtered duplicate" ? roleId.toUpperCase() : roleId, roleDefinitionName: - lookup === "conflicting retry" - ? "Key Vault Administrator" - : "Key Vault Secrets User", + lookup === "conflicting retry" ? "Key Vault Administrator" : "Key Vault Secrets User", }, ] return JSON.stringify( @@ -1884,7 +1882,9 @@ it.each([ test.run.mock.calls.some( ([executable, args]) => (executable === "terraform" && ["import", "state"].includes(args[1]!)) || - (executable === "az" && args[0] === "role" && ["create", "delete"].includes(args[2]!)), + (executable === "az" && + args[0] === "role" && + ["create", "delete"].includes(args[2]!)), ), ).toBe(false) }, From 9d45773b2ed5738d267263ed82ec53060d1eb323 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Sun, 29 Nov 2026 18:46:55 -0800 Subject: [PATCH 09/23] style(hub): format learning database test Keep the focused database test aligned with the Hub formatter. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../grant-learning-database-access/index.db.test.ts | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/hub/server/scripts/grant-learning-database-access/index.db.test.ts b/hub/server/scripts/grant-learning-database-access/index.db.test.ts index bfe322151..ec0cdd6ec 100644 --- a/hub/server/scripts/grant-learning-database-access/index.db.test.ts +++ b/hub/server/scripts/grant-learning-database-access/index.db.test.ts @@ -59,14 +59,7 @@ describe("grantLearningDatabaseAccess()", () => { await expect(runLearningCommand(["memories", ...store], options)).resolves.toEqual([]) await expect( runLearningCommand( - [ - "delete-repository", - "--by", - "github:admin", - "--confirm", - "repositories/1", - ...store, - ], + ["delete-repository", "--by", "github:admin", "--confirm", "repositories/1", ...store], options, ), ).resolves.toBeDefined() From 3b6a5fd68c5c64d3db932aa2f65d2f3a8a1f6f5f Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 01:01:51 -0800 Subject: [PATCH 10/23] refactor(hub): keep migration notice rendering in the UI layer Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../hub/routes/learnings-flow.test.tsx | 22 ------------------- .../view-models/settings-learnings/index.ts | 4 +++- 2 files changed, 3 insertions(+), 23 deletions(-) diff --git a/hub/client/application/hub/routes/learnings-flow.test.tsx b/hub/client/application/hub/routes/learnings-flow.test.tsx index db77c3a29..663499f0a 100644 --- a/hub/client/application/hub/routes/learnings-flow.test.tsx +++ b/hub/client/application/hub/routes/learnings-flow.test.tsx @@ -315,28 +315,6 @@ describe("Learnings frontend integration", () => { ).toBeVisible() }) - it("shows migration redaction follow-ups to the repository administrator after reload", async () => { - const server = stubHubFetch(...learningsWorkspace()) - const notice = - "Rebuild learning mem_111111111111111111111111. Follow up on export exp_222222222222222222222222 at private/exports/team.json." - let loads = 0 - server.use( - http.get("/api/repositories/2001/learnings", () => { - loads++ - return Response.json({ - ...learningsResponse(), - loadError: notice, - }) - }), - ) - const router = await renderHubFlow(server, "/repositories/2001/learnings") - - expect(await screen.findByText(notice)).toBeVisible() - await router.settle(() => router.revalidate()) - expect(loads).toBe(2) - expect(screen.getByText(notice)).toBeVisible() - }) - it("posts a run only to the dedicated repository endpoint", async () => { const server = stubHubFetch(...learningsWorkspace()) const runRequests = vi.fn() diff --git a/hub/client/application/hub/view-models/settings-learnings/index.ts b/hub/client/application/hub/view-models/settings-learnings/index.ts index 7753f42bd..cb51aa0ef 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.ts @@ -350,7 +350,9 @@ export function settingsLearnings( path: `/repositories/${repositoryId}/learnings/runs`, available: state.permissions.requestRun && state.runAvailable, }, - loadError: state.loadError, + loadError: state.loadError + ? `Hub could not read this repository's learnings: ${state.loadError}` + : null, identityNotice: state.identityReviewCount > 0 ? "Earlier suggestions or accepted learnings need identity revalidation. Hub keeps their history, but agents cannot use those versions. Find learnings again, then review any rebuilt suggestions." From 27d7b2aacd5b036889ffd746d8b81c849cf00249 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 02:31:36 -0800 Subject: [PATCH 11/23] test(infrastructure): cover private-preview lease recovery Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- infrastructure/azure/install/index.test.ts | 48 ++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/infrastructure/azure/install/index.test.ts b/infrastructure/azure/install/index.test.ts index 0772cb2ea..6692baa97 100644 --- a/infrastructure/azure/install/index.test.ts +++ b/infrastructure/azure/install/index.test.ts @@ -15,6 +15,7 @@ import { join } from "node:path" import { afterEach, expect, it, vi } from "vitest" import { CommandExecutionError } from "../../installer/command/index.ts" +import { parseConfig } from "../../installer/config/index.ts" import { installationWorkspace } from "../../installer/workspace/index.ts" import type { DeploymentConfig, InstallerUI, RunCommand } from "../../installer/types.ts" import { installAzure } from "./index.ts" @@ -1829,3 +1830,50 @@ it.each([ expect(beforePreview).toHaveLength(recoversFirst ? 1 : 0) expect(releaseRecoveries.length).toBe(beforePreview.length + 1) }) + +it("resumes an owned preview lease before recovering completed provisioning", async () => { + const s = await scenario({ existing: true }) + await withSignIn(s) + const lease = randomUUID() + await (await leaseOwnership( + { config: parseConfig(s.config), directory: installationWorkspace(s.config, s.directory) }, + "artifactstore", + "releases", + "deployment.lock", + "private-preview", + )).save(lease) + const order: string[] = [] + previewStep(order) + const recover = vi + .spyOn(recovery, "recoverLease") + .mockImplementation(async (_context, account, container, blob) => { + if (account === "artifactstore" && container === "releases" && blob === "deployment.lock") + order.push("recover") + }) + const run = vi.fn(async (executable, args, options) => { + if ( + executable === "az" && + args.slice(0, 3).join(" ") === "storage blob show" && + args[args.indexOf("--name") + 1] === "deployment.lock" + ) + return JSON.stringify({ state: "leased", status: "locked", duration: "infinite" }) + if ( + executable === "az" && + args.slice(0, 4).join(" ") === "storage blob lease renew" && + args.includes(lease) + ) + return "" + if (executable === process.execPath) order.push("release") + return s.run(executable, args, options) + }) + + await installAzure(s.config, { ...s, run }) + + expect(order).toEqual(["prepare", "recover", "release", "finish"]) + expect( + recover.mock.calls.filter( + ([, account, container, blob]) => + account === "artifactstore" && container === "releases" && blob === "deployment.lock", + ), + ).toHaveLength(1) +}) From d6a90c81b54f87a4aea68c4311199cc98aebe575 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 04:30:23 -0800 Subject: [PATCH 12/23] fix(hub): redact learning fixture credentials Keep fixture reports to an explicit non-sensitive environment allowlist. Report credential presence without logging values. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../run-learning-command/index.test.ts | 32 ++++++++++++++----- hub/test/fixtures/learning/report-runtime.mjs | 19 ++++++++++- 2 files changed, 42 insertions(+), 9 deletions(-) diff --git a/hub/server/integrations/learning/run-learning-command/index.test.ts b/hub/server/integrations/learning/run-learning-command/index.test.ts index a63023102..5de375dc6 100644 --- a/hub/server/integrations/learning/run-learning-command/index.test.ts +++ b/hub/server/integrations/learning/run-learning-command/index.test.ts @@ -61,14 +61,18 @@ describe("runLearningCommand()", () => { }, })) as { arguments: string[] + credentialPresence: { copilotGithubToken: boolean; learningDatabaseUrl: boolean } environment: NodeJS.ProcessEnv temporaryDirectory: string temporaryDirectoryMode: number } expect(result.arguments).toEqual(["copilot", "status", "--json"]) + expect(result.credentialPresence).toEqual({ + copilotGithubToken: true, + learningDatabaseUrl: false, + }) expect(result.environment).toEqual({ - COPILOT_GITHUB_TOKEN: "explicit-token", HOME: "/private/home", LANG: "en_US.UTF-8", LC_ALL: "C", @@ -90,9 +94,9 @@ describe("runLearningCommand()", () => { COPILOT_GITHUB_TOKEN: "ambient-token-must-not-leak", PATH: process.env.PATH, }, - })) as { environment: NodeJS.ProcessEnv } + })) as { credentialPresence: { copilotGithubToken: boolean } } - expect(result.environment.COPILOT_GITHUB_TOKEN).toBeUndefined() + expect(result.credentialPresence.copilotGithubToken).toBe(false) }) it("uses a private Postgres config and passes only explicitly supplied credentials", async () => { @@ -118,6 +122,7 @@ describe("runLearningCommand()", () => { )) as { arguments: string[] config: string + credentialPresence: { copilotGithubToken: boolean; learningDatabaseUrl: boolean } environment: NodeJS.ProcessEnv temporaryDirectory: string temporaryDirectoryMode: number @@ -137,11 +142,13 @@ describe("runLearningCommand()", () => { "github.com/repositories/123", "--json", ]) + expect(result.credentialPresence).toEqual({ + copilotGithubToken: true, + learningDatabaseUrl: true, + }) expect(result.environment).toEqual({ PATH: process.env.PATH, TMPDIR: result.temporaryDirectory, - COPILOT_GITHUB_TOKEN: "explicit-token", - REPLICA_LEARNING_DATABASE_URL: databaseUrl, REPLICA_LEARNING_HUB_POSTGRES: "1", }) expect(JSON.parse(result.config)).toMatchObject({ @@ -163,6 +170,9 @@ describe("runLearningCommand()", () => { expect(result.config).not.toContain(secret) expect(result.arguments.join(" ")).not.toContain(secret) } + expect(JSON.stringify(result)).not.toContain(databaseUrl) + expect(JSON.stringify(result)).not.toContain("learning-password") + expect(JSON.stringify(result)).not.toContain("explicit-token") expect(result.temporaryDirectoryMode).toBe(0o700) await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) }) @@ -417,13 +427,19 @@ describe("runLearningCommand()", () => { COPILOT_GITHUB_TOKEN: "ambient-token-must-not-leak", REPLICA_LEARNING_MIGRATION_DATABASE_URL: "migration-url-must-not-leak", }, - })) as { arguments: string[]; environment: NodeJS.ProcessEnv; temporaryDirectory: string } + })) as { + arguments: string[] + credentialPresence: { learningDatabaseUrl: boolean } + environment: NodeJS.ProcessEnv + temporaryDirectory: string + } expect(result.arguments).toEqual(["copilot", "status", "--json"]) expect(result.environment).toEqual({ PATH: process.env.PATH, TMPDIR: result.temporaryDirectory, }) + expect(result.credentialPresence.learningDatabaseUrl).toBe(false) await expect(stat(result.temporaryDirectory)).rejects.toMatchObject({ code: "ENOENT" }) }) @@ -434,7 +450,7 @@ describe("runLearningCommand()", () => { cliPath: resolve(fixtures, "report-runtime.mjs"), environment: { PATH: process.env.PATH, REPLICA_LEARNING_DATABASE_URL: "ambient-url" }, }, - )) as { arguments: string[]; environment: NodeJS.ProcessEnv } + )) as { arguments: string[]; credentialPresence: { learningDatabaseUrl: boolean } } expect(result.arguments).toEqual([ "consolidate", @@ -444,7 +460,7 @@ describe("runLearningCommand()", () => { "github.com/repositories/123", "--json", ]) - expect(result.environment.REPLICA_LEARNING_DATABASE_URL).toBeUndefined() + expect(result.credentialPresence.learningDatabaseUrl).toBe(false) }) it("removes the private Postgres config after a failed command", async () => { diff --git a/hub/test/fixtures/learning/report-runtime.mjs b/hub/test/fixtures/learning/report-runtime.mjs index 7a5f7d7e5..40312be41 100644 --- a/hub/test/fixtures/learning/report-runtime.mjs +++ b/hub/test/fixtures/learning/report-runtime.mjs @@ -20,7 +20,24 @@ if (directory !== undefined) { const report = JSON.stringify({ arguments: arguments_, config, - environment: process.env, + credentialPresence: { + copilotGithubToken: process.env.COPILOT_GITHUB_TOKEN !== undefined, + learningDatabaseUrl: process.env.REPLICA_LEARNING_DATABASE_URL !== undefined, + }, + environment: Object.fromEntries( + [ + "HOME", + "LANG", + "LC_ALL", + "PATH", + "REPLICA_LEARNING_HUB_POSTGRES", + "REPLICA_LEARNING_HUB_REQUIRE_IMPORT", + "TMPDIR", + "TZ", + ] + .filter((name) => process.env[name] !== undefined) + .map((name) => [name, process.env[name]]), + ), temporaryDirectory, temporaryDirectoryMode: status.mode & 0o777, }) From 514b5865c0d3afd0183d5a3cdc17e0e9b47f2927 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 05:20:40 -0800 Subject: [PATCH 13/23] fix(learning): display migration follow-ups accurately Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../settings-learnings/index.test.ts | 12 +++++ .../view-models/settings-learnings/index.ts | 4 +- hub/client/pages/learnings-page/stories.tsx | 3 +- packages/learning/src/store.mjs | 4 +- .../learning/test/scope-migration.test.mjs | 44 +++++++++++++++++++ 5 files changed, 61 insertions(+), 6 deletions(-) diff --git a/hub/client/application/hub/view-models/settings-learnings/index.test.ts b/hub/client/application/hub/view-models/settings-learnings/index.test.ts index bbd1eb556..4d34aba7d 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.test.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.test.ts @@ -206,6 +206,18 @@ function mockState(administerHub: boolean) { } describe("settingsLearnings()", () => { + it("preserves successful follow-up messages without describing them as read failures", () => { + const administrator = mockState(true) + const message = "Rebuild the learning because its review evidence was removed." + const state = { ...administrator.learnings, loadError: message } + + const result = settingsLearnings(administrator.workspace, state, null) + + expect(result.accessDenied).toBe(false) + if (result.accessDenied) throw new Error("The administrator must receive Learnings.") + expect(result.loadError).toBe(message) + }) + it("uses repository permissions for learning actions and Hub administration for navigation", () => { const state: LearningsResponse = { accessDenied: false, diff --git a/hub/client/application/hub/view-models/settings-learnings/index.ts b/hub/client/application/hub/view-models/settings-learnings/index.ts index cb51aa0ef..7753f42bd 100644 --- a/hub/client/application/hub/view-models/settings-learnings/index.ts +++ b/hub/client/application/hub/view-models/settings-learnings/index.ts @@ -350,9 +350,7 @@ export function settingsLearnings( path: `/repositories/${repositoryId}/learnings/runs`, available: state.permissions.requestRun && state.runAvailable, }, - loadError: state.loadError - ? `Hub could not read this repository's learnings: ${state.loadError}` - : null, + loadError: state.loadError, identityNotice: state.identityReviewCount > 0 ? "Earlier suggestions or accepted learnings need identity revalidation. Hub keeps their history, but agents cannot use those versions. Find learnings again, then review any rebuilt suggestions." diff --git a/hub/client/pages/learnings-page/stories.tsx b/hub/client/pages/learnings-page/stories.tsx index 461ea8dc3..e23d11fff 100644 --- a/hub/client/pages/learnings-page/stories.tsx +++ b/hub/client/pages/learnings-page/stories.tsx @@ -852,8 +852,7 @@ export const LoadError: Story = { suggestions: [], learnings: [], recall: { text: "", count: 0 }, - loadError: - "Hub could not read this repository's learnings: The learning store failed its integrity checks; run verify.", + loadError: "The learning store failed its integrity checks; run verify.", }, }, } diff --git a/packages/learning/src/store.mjs b/packages/learning/src/store.mjs index 65c0636ff..9ea74be9a 100644 --- a/packages/learning/src/store.mjs +++ b/packages/learning/src/store.mjs @@ -5323,7 +5323,9 @@ class LearningStore { */ async redactionFollowUps(context) { assertContext(context) - const migrations = (await this.#provider.scopeMigrations?.(context.scope)) ?? [] + const migrations = + (await (this.#provider.scopeMigrationSummaries?.(context.scope) ?? + this.#provider.scopeMigrations?.(context.scope))) ?? [] return { memoriesNeedingRebuild: unique( migrations.flatMap( diff --git a/packages/learning/test/scope-migration.test.mjs b/packages/learning/test/scope-migration.test.mjs index 9a30f7231..7a45d0ea1 100644 --- a/packages/learning/test/scope-migration.test.mjs +++ b/packages/learning/test/scope-migration.test.mjs @@ -90,6 +90,50 @@ function ok(repo, args, options) { return JSON.parse(result.stdout) } +it("reads redaction follow-ups from provider summaries when available", async () => { + const provider = createInMemoryProvider() + const followUps = { + memoriesNeedingRebuild: ["memory-1"], + exportsToFollowUp: [{ id: "export-1", destination: "private/export.json" }], + } + let summaryCalls = 0 + provider.scopeMigrationSummaries = async () => { + summaryCalls += 1 + return [{ oldScope: scope, redactionFollowUps: followUps }] + } + provider.scopeMigrations = async () => { + throw new Error("Full migration metadata should not be read.") + } + const store = await createLearningStore({ provider }) + + assert.deepEqual( + await store.redactionFollowUps({ + scope, + principal: { kind: "human", id: "github:ana-designer" }, + }), + followUps, + ) + assert.equal(summaryCalls, 1) +}) + +it("falls back to full migration records for providers without summaries", async () => { + const provider = createInMemoryProvider() + const followUps = { + memoriesNeedingRebuild: ["memory-2"], + exportsToFollowUp: [{ id: "export-2", destination: "private/another-export.json" }], + } + provider.scopeMigrations = async () => [{ redactionFollowUps: followUps }] + const store = await createLearningStore({ provider }) + + assert.deepEqual( + await store.redactionFollowUps({ + scope, + principal: { kind: "human", id: "github:ana-designer" }, + }), + followUps, + ) +}) + // These databases were created with the previous scope rules, before the new resolver ran. function installLegacyStore(repo, fixture) { const directory = path.join(repo, ".replica", "learning") From 741d0c2454f18b2dcfc7541b1924988c39749e59 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 05:20:40 -0800 Subject: [PATCH 14/23] fix(hub): parameterize learning database grants Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/.env.example | 2 +- hub/docs/testing-and-operations.md | 2 +- .../index.db.test.ts | 25 +++++++++---------- .../grant-learning-database-access/index.ts | 12 +++++---- 4 files changed, 21 insertions(+), 20 deletions(-) diff --git a/hub/.env.example b/hub/.env.example index 96a42ecbd..a74e6e2e4 100644 --- a/hub/.env.example +++ b/hub/.env.example @@ -71,7 +71,7 @@ SCHEDULED_JOB_CONCURRENCY=1 # Run `npm run setup` before starting a database-backed API. DATABASE_URL=postgresql://replica:replica@127.0.0.1:5432/replica -# Only database-enabled tests require this URL and CREATEDB permission. +# Database tests need CREATEDB; the learning grant test also needs CREATEROLE. TEST_DATABASE_URL=postgresql://replica:replica@127.0.0.1:5432/postgres # --- Required shared settings --- diff --git a/hub/docs/testing-and-operations.md b/hub/docs/testing-and-operations.md index da1d1b688..4daf7e445 100644 --- a/hub/docs/testing-and-operations.md +++ b/hub/docs/testing-and-operations.md @@ -53,7 +53,7 @@ Use `.test.ts` or `.test.tsx` for ordinary cases. Use `.db.test.ts` or `.db.test `npm test` selects `node` and `browser` without requiring PostgreSQL. `npm run test:database` selects both database-enabled projects. To select one project, run `npx vitest run --project=node-database --passWithNoTests` or use `--project=browser-database` instead. -Start the PostgreSQL service as described in [Development](development.md) and set `TEST_DATABASE_URL` using `.env.example`. The devcontainer supplies this variable. Use a local database user with permission to create and drop databases, never a production connection. +Start the PostgreSQL service as described in [Development](development.md) and set `TEST_DATABASE_URL` using `.env.example`. The devcontainer supplies this variable. Use a local database user with permission to create and drop databases, never a production connection. The learning database grant test also creates a temporary login role, so its user needs `CREATEROLE`. The database command uses `--passWithNoTests` so an empty selection exits successfully. It still fails when tests fail. The job integration cases exercise real PostgreSQL queues, schedules, and database resets. diff --git a/hub/server/scripts/grant-learning-database-access/index.db.test.ts b/hub/server/scripts/grant-learning-database-access/index.db.test.ts index ec0cdd6ec..9c96a0fc0 100644 --- a/hub/server/scripts/grant-learning-database-access/index.db.test.ts +++ b/hub/server/scripts/grant-learning-database-access/index.db.test.ts @@ -21,33 +21,32 @@ describe("grantLearningDatabaseAccess()", () => { const adminUrl = process.env.TEST_DATABASE_URL if (!adminUrl) throw new Error("TEST_DATABASE_URL is required.") const name = `replica_learning_grants_${randomBytes(8).toString("hex")}` + const runtimeRole = `replica_learning_test_${randomBytes(8).toString("hex")}` const password = randomBytes(16).toString("hex") - const admin = new pg.Client({ connectionString: adminUrl }) + const connectionUrl = new URL(adminUrl) + if (process.env.REPLICA_DEVCONTAINER === "true") { + connectionUrl.searchParams.set("host", "/var/run/postgresql") + } + const admin = new pg.Client({ connectionString: connectionUrl.toString() }) await admin.connect() const directory = await mkdtemp(join(tmpdir(), "replica-learning-grants-")) try { await admin.query(`CREATE DATABASE ${pg.escapeIdentifier(name)}`) await admin.query( - `DO $$ BEGIN - CREATE ROLE replica_learning_runtime LOGIN; - EXCEPTION WHEN duplicate_object THEN NULL; - END $$`, - ) - await admin.query( - `ALTER ROLE replica_learning_runtime LOGIN PASSWORD ${pg.escapeLiteral(password)}`, + `CREATE ROLE ${pg.escapeIdentifier(runtimeRole)} LOGIN PASSWORD ${pg.escapeLiteral(password)}`, ) await admin.query( - `GRANT CONNECT ON DATABASE ${pg.escapeIdentifier(name)} TO replica_learning_runtime`, + `GRANT CONNECT ON DATABASE ${pg.escapeIdentifier(name)} TO ${pg.escapeIdentifier(runtimeRole)}`, ) - const migrationUrl = new URL(adminUrl) + const migrationUrl = new URL(connectionUrl) migrationUrl.pathname = name await promisify(execFile)(process.execPath, [cliPath, "migrate"], { env: { ...process.env, REPLICA_LEARNING_MIGRATION_DATABASE_URL: migrationUrl.toString() }, timeout: 60_000, }) - await grantLearningDatabaseAccess(migrationUrl.toString()) + await grantLearningDatabaseAccess(migrationUrl.toString(), runtimeRole) const runtimeUrl = new URL(migrationUrl) - runtimeUrl.username = "replica_learning_runtime" + runtimeUrl.username = runtimeRole runtimeUrl.password = password const store = learningStoreArguments({ directory, @@ -66,7 +65,7 @@ describe("grantLearningDatabaseAccess()", () => { } finally { await rm(directory, { force: true, recursive: true }) await admin.query(`DROP DATABASE IF EXISTS ${pg.escapeIdentifier(name)} WITH (FORCE)`) - await admin.query("DROP ROLE IF EXISTS replica_learning_runtime") + await admin.query(`DROP ROLE IF EXISTS ${pg.escapeIdentifier(runtimeRole)}`) await admin.end() } }, 120_000) diff --git a/hub/server/scripts/grant-learning-database-access/index.ts b/hub/server/scripts/grant-learning-database-access/index.ts index 7d79a27f0..10ef7446c 100644 --- a/hub/server/scripts/grant-learning-database-access/index.ts +++ b/hub/server/scripts/grant-learning-database-access/index.ts @@ -5,16 +5,18 @@ import pg from "pg" import { logger } from "../../integrations/pino/index.ts" -export async function grantLearningDatabaseAccess(databaseUrl: string) { +export async function grantLearningDatabaseAccess( + databaseUrl: string, + runtimeRoleName = "replica_learning_runtime", +) { if (!databaseUrl) throw new Error("Learning grants require a migration database URL.") const client = new pg.Client({ connectionString: databaseUrl, connectionTimeoutMillis: 5_000 }) + const runtimeRole = pg.escapeIdentifier(runtimeRoleName) try { await client.connect() await client.query("BEGIN") await client.query("REVOKE ALL ON SCHEMA replica_learning FROM PUBLIC") - await client.query( - "REVOKE UPDATE ON replica_learning.memory_versions FROM replica_learning_runtime", - ) + await client.query(`REVOKE UPDATE ON replica_learning.memory_versions FROM ${runtimeRole}`) // Match the runtime privileges in packages/learning/README.md#postgresql-storage. // Writes fire triggers that maintain the decision tables, so those need grants too. for (const statement of [ @@ -26,7 +28,7 @@ export async function grantLearningDatabaseAccess(databaseUrl: string) { "GRANT SELECT, INSERT ON replica_learning.decision_withdrawal_targets, replica_learning.decision_migration_origins, replica_learning.scope_migrations, replica_learning.sqlite_imports", "GRANT USAGE ON ALL SEQUENCES IN SCHEMA replica_learning", ]) { - await client.query(`${statement} TO replica_learning_runtime`) + await client.query(`${statement} TO ${runtimeRole}`) } await client.query("COMMIT") } finally { From f3b52fdc387b3464b8b991c4e2eb72b5bc425956 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 05:20:40 -0800 Subject: [PATCH 15/23] fix(hub): isolate local repositories from GitHub sync Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/docs/development.md | 2 ++ .../index.db.test.ts | 32 +++++++++++++++++++ .../index.ts | 2 +- .../index.db.test.ts | 21 ++++++++++++ .../upsert-connected-repositories/index.ts | 6 ++++ 5 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 hub/server/repositories/repository-access/list-connected-github-repositories/index.db.test.ts diff --git a/hub/docs/development.md b/hub/docs/development.md index 1c5d50ce2..2202942bd 100644 --- a/hub/docs/development.md +++ b/hub/docs/development.md @@ -226,6 +226,8 @@ docker compose -f hub/.devcontainer/compose.yaml exec -T \ The seed resets only the dedicated local walkthrough repository. It refuses to run while a walkthrough job is active or after the dedicated fixture runtime has a promotion generation. To restart from the beginning, stop the worker and services, remove only `$REPLICA_RUNTIME_STATE_DIR`, recreate it with mode `0700`, and start the Compose bundle again before reseeding. The seed creates four reviewed prototypes with breaking and fixed Builds distributed across training, development, and test splits; 32 valid screenshots; two reviewer identities; one accepted learning; training consent; and local repository administrator authority. It uses the learning CLI to grant consent, import the real Hub review snapshot, label and consolidate the evidence, and accept the learning. +The fixture remains local even though it stores the dedicated GitHub ID to scope Learnings. Keep that repository out of the Hub GitHub App installation. GitHub sync omits local repositories and rejects attempts to connect one. + Start the on-demand worker in a third terminal: ```sh diff --git a/hub/server/repositories/repository-access/list-connected-github-repositories/index.db.test.ts b/hub/server/repositories/repository-access/list-connected-github-repositories/index.db.test.ts new file mode 100644 index 000000000..86ba40b18 --- /dev/null +++ b/hub/server/repositories/repository-access/list-connected-github-repositories/index.db.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest" + +import { prisma } from "../../../integrations/prisma" +import { listConnectedGitHubRepositories } from "." + +describe("listConnectedGitHubRepositories", () => { + it("omits a local repository even when it has a GitHub ID", async () => { + await prisma.repository.create({ + data: { + defaultBranch: "trunk", + githubRepositoryId: 8n, + localPath: "/workspace/local", + nameWithOwner: "local/project", + }, + }) + await prisma.repository.create({ + data: { + defaultBranch: "main", + githubRepositoryId: 9n, + nameWithOwner: "octo/connected", + }, + }) + + await expect(listConnectedGitHubRepositories(prisma)).resolves.toEqual([ + { + defaultBranch: "main", + githubRepositoryId: 9n, + nameWithOwner: "octo/connected", + }, + ]) + }) +}) diff --git a/hub/server/repositories/repository-access/list-connected-github-repositories/index.ts b/hub/server/repositories/repository-access/list-connected-github-repositories/index.ts index 1b8bf6847..636a4cae2 100644 --- a/hub/server/repositories/repository-access/list-connected-github-repositories/index.ts +++ b/hub/server/repositories/repository-access/list-connected-github-repositories/index.ts @@ -5,6 +5,6 @@ export async function listConnectedGitHubRepositories( ) { return database.repository.findMany({ select: { defaultBranch: true, githubRepositoryId: true, nameWithOwner: true }, - where: { githubRepositoryId: { not: null }, removedAt: null }, + where: { githubRepositoryId: { not: null }, localPath: null, removedAt: null }, }) } diff --git a/hub/server/repositories/repository-access/upsert-connected-repositories/index.db.test.ts b/hub/server/repositories/repository-access/upsert-connected-repositories/index.db.test.ts index cf0c836b3..b45f18363 100644 --- a/hub/server/repositories/repository-access/upsert-connected-repositories/index.db.test.ts +++ b/hub/server/repositories/repository-access/upsert-connected-repositories/index.db.test.ts @@ -139,4 +139,25 @@ describe("upsertConnectedRepositories", () => { removedAt: null, }) }) + + it("rejects GitHub evidence for a local repository without changing it", async () => { + const localRepository = await prisma.repository.create({ + data: { + defaultBranch: "trunk", + githubRepositoryId: 8n, + localPath: "/workspace/local", + nameWithOwner: "local/project", + }, + }) + + await expect( + upsertConnectedRepositories(prisma, [evidence(8, "octo/project")], { + allowReconnect: false, + }), + ).rejects.toThrow("GitHub synchronization cannot adopt a locally registered repository.") + + await expect( + prisma.repository.findUniqueOrThrow({ where: { id: localRepository.id } }), + ).resolves.toEqual(localRepository) + }) }) diff --git a/hub/server/repositories/repository-access/upsert-connected-repositories/index.ts b/hub/server/repositories/repository-access/upsert-connected-repositories/index.ts index ebf57d71a..7bd380ce2 100644 --- a/hub/server/repositories/repository-access/upsert-connected-repositories/index.ts +++ b/hub/server/repositories/repository-access/upsert-connected-repositories/index.ts @@ -5,6 +5,7 @@ interface StoredRepository { defaultBranch: string githubRepositoryId: bigint | null id: string + localPath: string | null nameWithOwner: string removedAt: Date | null } @@ -18,12 +19,14 @@ const storedFields = { defaultBranch: true, githubRepositoryId: true, id: true, + localPath: true, nameWithOwner: true, removedAt: true, } as const /** * Records repositories the GitHub App can read, matching only immutable GitHub IDs. + * A local repository is never adopted as a connected repository. * Returns Hub IDs in order using bounded queries for the supported installation size. */ export async function upsertConnectedRepositories( @@ -55,6 +58,9 @@ export async function upsertConnectedRepositories( continue } const existing = byGitHubId.get(githubRepositoryId) + if (existing && existing.localPath !== null) { + throw new Error("GitHub synchronization cannot adopt a locally registered repository.") + } if (existing?.removedAt && !options.allowReconnect) { throw new Error("User evidence cannot reconnect a disconnected GitHub repository.") } From b297a12aab2c95bbec32d7664b9a8919d843b657 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 05:20:40 -0800 Subject: [PATCH 16/23] test(azure): cover learning reference limits Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../azure/install/inputs/index.test.ts | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/infrastructure/azure/install/inputs/index.test.ts b/infrastructure/azure/install/inputs/index.test.ts index eb1303baf..504dbe1d5 100644 --- a/infrastructure/azure/install/inputs/index.test.ts +++ b/infrastructure/azure/install/inputs/index.test.ts @@ -921,6 +921,69 @@ describe("readInstallationInputs()", () => { expect(failure).toBeInstanceOf(Error) }) + it("rejects a learning database secret that reuses the setup database secret", async () => { + const { config, inputs } = boundaryInputs() + inputs.learning_database_secret = inputs.setup_database_secret + vi.mocked(readPrivateFile).mockResolvedValue(JSON.stringify(inputs)) + + const failure = await readInstallationInputs("synthetic-installation", config).catch( + (error: unknown) => error, + ) + + expect(failure).toBeInstanceOf(Error) + }) + + it("rejects a case-insensitive match with the runtime database secret", async () => { + const { config, inputs } = boundaryInputs() + inputs.learning_database_secret = { + key_vault_id: inputs.runtime_database_secret.key_vault_id.toUpperCase(), + secret_id: inputs.runtime_database_secret.secret_id + .replace("database.vault.azure.net", "DATABASE.VAULT.AZURE.NET") + .replace("runtime-database", "RUNTIME-DATABASE"), + } + vi.mocked(readPrivateFile).mockResolvedValue(JSON.stringify(inputs)) + + const failure = await readInstallationInputs("synthetic-installation", config).catch( + (error: unknown) => error, + ) + + expect(failure).toBeInstanceOf(Error) + }) + + it("accepts 62 additional references when the learning database secret is configured", async () => { + const { config, inputs, reference } = boundaryInputs() + inputs.learning_database_secret = reference(24, 127, "learning") + inputs.runtime_secret_references = Object.fromEntries( + Array.from({ length: 62 }, (_, index) => [ + `SERVICE_${index}`, + reference(24, 127, `service${index}`), + ]), + ) + vi.mocked(readPrivateFile).mockResolvedValue(JSON.stringify(inputs)) + + await expect(readInstallationInputs("synthetic-installation", config)).resolves.toMatchObject({ + runtime_secret_references: inputs.runtime_secret_references, + }) + }) + + it("rejects 63 additional references when the learning database secret is configured", async () => { + const { config, inputs, reference } = boundaryInputs() + inputs.learning_database_secret = reference(24, 127, "learning") + inputs.runtime_secret_references = Object.fromEntries( + Array.from({ length: 63 }, (_, index) => [ + `SERVICE_${index}`, + reference(24, 127, `service${index}`), + ]), + ) + vi.mocked(readPrivateFile).mockResolvedValue(JSON.stringify(inputs)) + + const failure = await readInstallationInputs("synthetic-installation", config).catch( + (error: unknown) => error, + ) + + expect(failure).toBeInstanceOf(Error) + }) + it("accepts a full runtime map with maximum-length versioned Azure references", async () => { const { config, inputs, reference } = boundaryInputs() const secret = reference(24, 127) @@ -1000,6 +1063,7 @@ function boundaryInputs() { resource_group_name: config.azure.resourceGroup, runtime_database_secret: reference(24, 127), setup_database_secret: reference(24, 127, "setup"), + learning_database_secret: undefined as ReturnType | undefined, runtime_secret_references: {} as Record>, } return { config, inputs, reference } From 896a0062df4b0617056c38189c1b31acbbc72a4e Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 07:41:41 -0800 Subject: [PATCH 17/23] fix(hub): process training withdrawals after repository access changes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../index.test.ts | 46 +++++----- .../index.ts | 9 +- .../index.test.ts | 88 ++++++++++++++++++- .../index.ts | 11 ++- hub/server/domains/decision-model/types.ts | 1 + 5 files changed, 126 insertions(+), 29 deletions(-) diff --git a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts index 76688cc18..50cec05f6 100644 --- a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts +++ b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.test.ts @@ -368,29 +368,32 @@ describe("createHubDecisionTasksetSource()", () => { expect(runLearningCommand).not.toHaveBeenCalled() }) - it("retries a training withdrawal after a repository administrator returns", async () => { + it("uses persisted training-job context to process withdrawals after repository access is gone", async () => { const trainingJob = { consentGrantId: "grant-training", trainingExportId: "export-1", evidenceDigest: `sha256:${"e".repeat(64)}`, tasksetDigest: `sha256:${"d".repeat(64)}`, + requestedByMembershipId: "44444444-4444-4444-8444-444444444444", + requestedByMembership: { + user: { profile: { login: "mona" } }, + }, } - vi.mocked(listDecisionWithdrawalSources) - .mockResolvedValueOnce([ - { id: repositoryId, decisionTrainingJobs: [trainingJob], accessGrants: [] }, - ] as never) - .mockResolvedValueOnce([ - { - id: repositoryId, - decisionTrainingJobs: [trainingJob], - accessGrants: [ - { - membershipId: "99999999-9999-4999-8999-999999999999", - membership: { user: { profile: { login: "active-admin" } } }, - }, - ], - }, - ] as never) + vi.mocked(listDecisionWithdrawalSources).mockResolvedValue([ + { + id: repositoryId, + decisionTrainingJobs: [ + trainingJob, + { + consentGrantId: "unrelated-grant", + trainingExportId: "unrelated-export", + evidenceDigest: `sha256:${"u".repeat(64)}`, + tasksetDigest: `sha256:${"v".repeat(64)}`, + }, + ], + accessGrants: [], + }, + ] as never) vi.mocked(prepareLearningStore).mockResolvedValue({ directory: "/private/learning/repository", repositoryScope: "github.com/repositories/123", @@ -406,16 +409,13 @@ describe("createHubDecisionTasksetSource()", () => { ]) const taskset = source(storage({})) - await expect(taskset.listTrainingWithdrawals()).resolves.toEqual({ - withdrawals: [], - failedRepositoryIds: [repositoryId], - }) await expect(taskset.listTrainingWithdrawals()).resolves.toEqual({ withdrawals: [ { repositoryId, - actorMembershipId: "99999999-9999-4999-8999-999999999999", + actorMembershipId: trainingJob.requestedByMembershipId, actorLogin: "mona", + authorization: "recorded_training_withdrawal", selectors: { exportId: trainingJob.trainingExportId, grantId: trainingJob.consentGrantId, @@ -428,6 +428,7 @@ describe("createHubDecisionTasksetSource()", () => { ], failedRepositoryIds: [], }) + expect(listDecisionWithdrawalSources).toHaveBeenCalledOnce() }) it("maps training grant withdrawals to idempotent runtime deletion selectors", async () => { @@ -475,6 +476,7 @@ describe("createHubDecisionTasksetSource()", () => { repositoryId, actorMembershipId: "99999999-9999-4999-8999-999999999999", actorLogin: "mona", + authorization: "recorded_training_withdrawal", selectors: { grantId: "grant-secondary" }, reason: "The repository administrator withdrew training consent.", idempotencyKey: "withdrawal:withdrawal-1:grant", diff --git a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts index f901272b6..97803160c 100644 --- a/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts +++ b/hub/server/domains/decision-model/create-hub-decision-taskset-source/index.ts @@ -912,17 +912,20 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource const matchingJobs = repository.decisionTrainingJobs.filter( (candidate) => candidate.consentGrantId === withdrawal.grantId, ) + const fallbackJob = matchingJobs[0] ?? repository.decisionTrainingJobs[0] const matchingActorGrant = repository.accessGrants.find( (grant) => grant.membership.user.profile?.login === login, ) const actorMembershipId = - matchingActorGrant?.membershipId ?? repository.accessGrants[0]?.membershipId + matchingActorGrant?.membershipId ?? + repository.accessGrants[0]?.membershipId ?? + fallbackJob?.requestedByMembershipId if (!actorMembershipId) { if (!failedRepositoryIds.includes(repository.id)) failedRepositoryIds.push(repository.id) options.logger?.warn( { repositoryId: repository.id }, - "Decision training withdrawal needs an active repository administrator", + "Decision training withdrawal has no saved job actor for its deletion record", ) continue } @@ -931,6 +934,7 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource repositoryId: repository.id, actorMembershipId, actorLogin: login, + authorization: "recorded_training_withdrawal" as const, selectors: { grantId: withdrawal.grantId }, reason: withdrawal.reason ?? "Training consent was withdrawn.", idempotencyKey: `withdrawal:${withdrawal.id}:grant`, @@ -942,6 +946,7 @@ export function createHubDecisionTasksetSource(options: HubDecisionTasksetSource repositoryId: repository.id, actorMembershipId, actorLogin: login, + authorization: "recorded_training_withdrawal" as const, selectors: { exportId: job.trainingExportId, grantId: withdrawal.grantId, diff --git a/hub/server/domains/decision-model/process-decision-runtime-deletion/index.test.ts b/hub/server/domains/decision-model/process-decision-runtime-deletion/index.test.ts index 57d6979ce..e79db8ead 100644 --- a/hub/server/domains/decision-model/process-decision-runtime-deletion/index.test.ts +++ b/hub/server/domains/decision-model/process-decision-runtime-deletion/index.test.ts @@ -7,8 +7,9 @@ describe("processDecisionRuntimeDeletion()", () => { it("persists disclosed copy references and the durable pending receipt", async () => { const saveRuntimeCopies = vi.fn() const updateDeletionReceipt = vi.fn() + const requireRepositoryAdministrator = vi.fn() const dependencies = { - authorization: { requireRepositoryAdministrator: vi.fn() }, + authorization: { requireRepositoryAdministrator }, runtime: { listRuntimeCopies: vi.fn().mockResolvedValue({ items: [ @@ -82,5 +83,90 @@ describe("processDecisionRuntimeDeletion()", () => { "11111111-1111-4111-8111-111111111111", expect.objectContaining({ id: "deletion-1", state: "pending" }), ) + expect(requireRepositoryAdministrator).toHaveBeenCalledWith({ + membershipId: "33333333-3333-4333-8333-333333333333", + repositoryId: "22222222-2222-4222-8222-222222222222", + }) + }) + + it("allows a recorded training withdrawal without current repository access", async () => { + const selectors = { grantId: "withdrawn-training-grant" } + const requireRepositoryAdministrator = vi.fn() + const createOrGetDeletion = vi.fn().mockResolvedValue({ + id: "deletion-1", + runtimeDeletionId: null, + state: "PENDING", + }) + const requestDeletion = vi.fn().mockResolvedValue({ + id: "runtime-deletion-1", + state: "complete", + selectors, + items: [], + pendingItems: [], + failures: [], + revokedAt: "2026-11-19T18:00:00.000Z", + updatedAt: "2026-11-19T18:00:00.000Z", + completedAt: "2026-11-19T18:00:00.000Z", + }) + const dependencies = { + authorization: { requireRepositoryAdministrator }, + runtime: { + listRuntimeCopies: vi.fn().mockResolvedValue({ items: [], nextCursor: null }), + requestDeletion, + getDeletion: vi.fn(), + }, + store: { + createOrGetDeletion, + saveRuntimeCopies: vi.fn(), + updateDeletionReceipt: vi.fn(), + }, + } as unknown as DecisionModelDependencies + + await expect( + processDecisionRuntimeDeletion( + { + repositoryId: "22222222-2222-4222-8222-222222222222", + actorMembershipId: "33333333-3333-4333-8333-333333333333", + actorLogin: "former-member", + authorization: "recorded_training_withdrawal", + selectors, + reason: "training consent withdrawn", + idempotencyKey: "withdrawal:withdrawal-1:grant", + }, + dependencies, + ), + ).resolves.toMatchObject({ state: "complete", pending: 0 }) + + expect(requireRepositoryAdministrator).not.toHaveBeenCalled() + expect(createOrGetDeletion).toHaveBeenCalledWith(expect.objectContaining({ selectors })) + expect(requestDeletion).toHaveBeenCalledWith(expect.objectContaining({ selectors })) + }) + + it("does not record an ordinary deletion when repository-admin authorization fails", async () => { + const requireRepositoryAdministrator = vi + .fn() + .mockRejectedValue(new Error("repository administrator required")) + const createOrGetDeletion = vi.fn() + const dependencies = { + authorization: { requireRepositoryAdministrator }, + store: { createOrGetDeletion }, + } as unknown as DecisionModelDependencies + + await expect( + processDecisionRuntimeDeletion( + { + repositoryId: "22222222-2222-4222-8222-222222222222", + actorMembershipId: "33333333-3333-4333-8333-333333333333", + actorLogin: "mona", + selectors: { grantId: "ordinary-grant" }, + reason: "requested deletion", + idempotencyKey: "ordinary-delete", + }, + dependencies, + ), + ).rejects.toThrow("repository administrator required") + + expect(requireRepositoryAdministrator).toHaveBeenCalledOnce() + expect(createOrGetDeletion).not.toHaveBeenCalled() }) }) diff --git a/hub/server/domains/decision-model/process-decision-runtime-deletion/index.ts b/hub/server/domains/decision-model/process-decision-runtime-deletion/index.ts index 596da2605..7be71f75a 100644 --- a/hub/server/domains/decision-model/process-decision-runtime-deletion/index.ts +++ b/hub/server/domains/decision-model/process-decision-runtime-deletion/index.ts @@ -7,16 +7,19 @@ export async function processDecisionRuntimeDeletion( repositoryId: string actorMembershipId: string actorLogin: string + authorization?: "recorded_training_withdrawal" selectors: DecisionRuntimeDeletionSelectors reason: string idempotencyKey: string }, dependencies: DecisionModelDependencies, ) { - await dependencies.authorization.requireRepositoryAdministrator({ - membershipId: input.actorMembershipId, - repositoryId: input.repositoryId, - }) + if (input.authorization !== "recorded_training_withdrawal") { + await dependencies.authorization.requireRepositoryAdministrator({ + membershipId: input.actorMembershipId, + repositoryId: input.repositoryId, + }) + } if (!dependencies.store.createOrGetDeletion) { throw new Error("Decision runtime deletion support is required.") } diff --git a/hub/server/domains/decision-model/types.ts b/hub/server/domains/decision-model/types.ts index a92d3c00b..a75cc77ea 100644 --- a/hub/server/domains/decision-model/types.ts +++ b/hub/server/domains/decision-model/types.ts @@ -290,6 +290,7 @@ export interface DecisionTrainingWithdrawalDiscovery { repositoryId: string actorMembershipId: string actorLogin: string + authorization: "recorded_training_withdrawal" selectors: DecisionRuntimeDeletionSelectors reason: string idempotencyKey: string From 2175de3d2af5c8705ede96d7da6517b93f2a3fb1 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 07:41:41 -0800 Subject: [PATCH 18/23] fix(infrastructure): require durable learning storage for existing installs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- infrastructure/azure/install/index.test.ts | 82 ++++++++++++++++++- infrastructure/azure/install/index.ts | 8 ++ .../azure/installation.tfvars.example | 12 +-- 3 files changed, 93 insertions(+), 9 deletions(-) diff --git a/infrastructure/azure/install/index.test.ts b/infrastructure/azure/install/index.test.ts index 6692baa97..94d3189d9 100644 --- a/infrastructure/azure/install/index.test.ts +++ b/infrastructure/azure/install/index.test.ts @@ -63,12 +63,24 @@ afterEach(async () => { async function scenario({ existing = false, + databaseProvisioned = existing, + learningDatabaseConfigured = true, learningProvisioned = true, releaseFails = false, priorProvisioning = false, provisioningFails = false, retainedRelease = false, imageFailsOnce = false, +}: { + existing?: boolean + databaseProvisioned?: boolean + learningDatabaseConfigured?: boolean + learningProvisioned?: boolean + releaseFails?: boolean + priorProvisioning?: boolean + provisioningFails?: boolean + retainedRelease?: boolean + imageFailsOnce?: boolean } = {}) { const directory = await mkdtemp(join(process.cwd(), ".replica-install-")) directories.push(directory) @@ -86,10 +98,11 @@ async function scenario({ }, } const image = `registry.azurecr.io/replica-hub@sha256:${"a".repeat(64)}` + const hasLearningDatabase = learningDatabaseConfigured const events: { command: string[]; env?: NodeJS.ProcessEnv }[] = [] const messages: string[] = [] const secretValues = new Map([ - ...(existing ? [["database-provisioned", config.azure.resourceGroup]] : []), + ...(databaseProvisioned ? [["database-provisioned", config.azure.resourceGroup]] : []), ...(existing && learningProvisioned ? [["learning-database-provisioned", config.azure.resourceGroup]] : []), @@ -101,6 +114,32 @@ async function scenario({ registry_id: `/subscriptions/${config.azure.subscriptionId}/resourceGroups/foundation/providers/Microsoft.ContainerRegistry/registries/registry`, registry_url: "registry.azurecr.io", } + if (existing) { + const workspace = installationWorkspace(config, directory) + await mkdir(workspace, { recursive: true, mode: 0o700 }) + const reference = (name: string) => ({ + key_vault_id: vaultId, + secret_id: `https://testvault.vault.azure.net/secrets/${name}/${"a".repeat(32)}`, + }) + await writeFile( + join(workspace, "installation.tfvars.json"), + JSON.stringify({ + subscription_id: config.azure.subscriptionId, + name: config.name, + owner: config.owner, + location: config.azure.location, + resource_group_name: config.azure.resourceGroup, + grant_deployment_storage_access: true, + image, + deploy_hub: true, + acr_id: foundation.registry_id, + runtime_database_secret: reference("runtime-database"), + setup_database_secret: reference("setup-database"), + ...(hasLearningDatabase ? { learning_database_secret: reference("learning-database") } : {}), + }), + { mode: 0o600 }, + ) + } let released = false let imageAttempts = 0 let releaseLocked = retainedRelease @@ -1095,7 +1134,7 @@ it("updates an installed app only through the release orchestrator and never rer ).toBe(false) }) -it("provisions only the learning role on a SQLite installation without activating PostgreSQL", async () => { +it("provisions only the learning role when durable learning storage is configured", async () => { const s = await scenario({ existing: true, learningProvisioned: false }) await installAzure(s.config, s) @@ -1108,7 +1147,7 @@ it("provisions only the learning role on a SQLite installation without activatin "HUB_LEARNING_PASSWORD", ]) const inputs = JSON.parse(await readFile(join(workspace, "installation.tfvars.json"), "utf8")) - expect(inputs).not.toHaveProperty("learning_database_secret") + expect(inputs.learning_database_secret.secret_id).toContain("/secrets/learning-database/") expect(s.secretValues.get("learning-database-provisioned")).toBe(s.config.azure.resourceGroup) expect( s.events.filter(({ command }) => command.slice(0, 4).join(" ") === "az containerapp job start"), @@ -1116,6 +1155,43 @@ it("provisions only the learning role on a SQLite installation without activatin expect(s.released()).toBe(true) }) +it("blocks an existing SQLite installation until durable learning storage is configured", async () => { + const s = await scenario({ + existing: true, + databaseProvisioned: false, + learningDatabaseConfigured: false, + }) + + await expect(installAzure(s.config, s)).rejects.toThrow(/durable learning storage/) + + expect(s.released()).toBe(false) + expect( + s.events.some( + ({ command }) => + command[0] === process.execPath && + command.includes("release"), + ), + ).toBe(false) +}) + +it("blocks a provisioned database without an app until durable learning storage is configured", async () => { + const s = await scenario({ + databaseProvisioned: true, + learningDatabaseConfigured: false, + }) + + await expect(installAzure(s.config, s)).rejects.toThrow(/durable learning storage/) + + expect(s.released()).toBe(false) + expect( + s.events.some( + ({ command }) => + command[0] === process.execPath && + command.includes("release"), + ), + ).toBe(false) +}) + it("cleans up a completed learning provisioning job without rerunning it", async () => { const s = await scenario({ existing: true }) const run: RunCommand = async (executable, args, options) => { diff --git a/infrastructure/azure/install/index.ts b/infrastructure/azure/install/index.ts index 91e22fe16..54448ef99 100644 --- a/infrastructure/azure/install/index.ts +++ b/infrastructure/azure/install/index.ts @@ -248,6 +248,14 @@ async function install( } const appCreated = appState.includes("azurerm_container_app.hub[0]") const databaseProvisioned = await secrets.provisioned() + if ( + (appCreated || databaseProvisioned) && + !operatorInputs.learning_database_secret + ) { + throw new Error( + "An existing installation cannot be released without durable learning storage. Import and verify any SQLite learning history, configure learning_database_secret, then retry.", + ) + } const variables = join(directory, "installation.tfvars.json") const inputs = { ...postgres, diff --git a/infrastructure/azure/installation.tfvars.example b/infrastructure/azure/installation.tfvars.example index 86f2d4e13..083ccb610 100644 --- a/infrastructure/azure/installation.tfvars.example +++ b/infrastructure/azure/installation.tfvars.example @@ -12,12 +12,12 @@ setup_database_secret = { key_vault_id = "/subscriptions/YOUR_SUBSCRIPTION/resourceGroups/YOUR_SECRETS_GROUP/providers/Microsoft.KeyVault/vaults/YOUR_VAULT" secret_id = "https://YOUR-VAULT.vault.azure.net/secrets/hub-migration-database" } -# Enable on a new installation, or only after an existing installation's SQLite -# history and mappings have been imported and verified. Leave unset otherwise. -# learning_database_secret = { -# key_vault_id = "/subscriptions/YOUR_SUBSCRIPTION/resourceGroups/YOUR_SECRETS_GROUP/providers/Microsoft.KeyVault/vaults/YOUR_VAULT" -# secret_id = "https://YOUR-VAULT.vault.azure.net/secrets/postgres-learning-url" -# } +# Learning history uses durable storage. For an existing installation, first import and verify +# its SQLite history and mappings, then configure the database secret before releasing an update. +learning_database_secret = { + key_vault_id = "/subscriptions/YOUR_SUBSCRIPTION/resourceGroups/YOUR_SECRETS_GROUP/providers/Microsoft.KeyVault/vaults/YOUR_VAULT" + secret_id = "https://YOUR-VAULT.vault.azure.net/secrets/postgres-learning-url" +} # Supply postgres_admin_password through a secret manager as TF_VAR_postgres_admin_password. # Application secrets stay in Key Vault. Optional references, never values: From 2b06803b354c9a6bca282559645f503314d761f0 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 07:41:41 -0800 Subject: [PATCH 19/23] fix(learning): expose redaction follow-ups in the public types Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- packages/learning/index.d.mts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/learning/index.d.mts b/packages/learning/index.d.mts index 3e0097496..89ee5bc12 100644 --- a/packages/learning/index.d.mts +++ b/packages/learning/index.d.mts @@ -996,6 +996,10 @@ export interface LearningStore { readonly manifest: ProviderManifest health(): Promise<{ ok: boolean; detail: string }> close(): Promise + redactionFollowUps(context: LearningContext): Promise<{ + memoriesNeedingRebuild: string[] + exportsToFollowUp: Array<{ id: string; purpose: Purpose; destination: string }> + }> addGrant( context: LearningContext, input: { From a041c21542b5148a1a67a7ddd7ff2908bf07c100 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 15:10:22 -0800 Subject: [PATCH 20/23] fix(hub): separate withdrawal authority from deletion input Only the reconciliation worker passes the authority from a persisted training withdrawal. The ordinary deletion path always requires a current repository administrator. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../create-decision-model-job-processors/index.ts | 4 ++-- .../process-decision-runtime-deletion/index.test.ts | 2 +- .../process-decision-runtime-deletion/index.ts | 5 +++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/hub/server/domains/decision-model/create-decision-model-job-processors/index.ts b/hub/server/domains/decision-model/create-decision-model-job-processors/index.ts index b06e23d5d..8fbfafc49 100644 --- a/hub/server/domains/decision-model/create-decision-model-job-processors/index.ts +++ b/hub/server/domains/decision-model/create-decision-model-job-processors/index.ts @@ -144,9 +144,9 @@ export function createDecisionModelJobProcessors(input: { const reconcileDeletions = createJobProcessor(reconcileRuntimeDeletionsJob, async () => { const discovery = await (input.dependencies.listTrainingWithdrawals?.() ?? Promise.resolve({ withdrawals: [], failedRepositoryIds: [] })) - for (const withdrawal of discovery.withdrawals) { + for (const { authorization, ...withdrawal } of discovery.withdrawals) { try { - await processDecisionRuntimeDeletion(withdrawal, input.dependencies) + await processDecisionRuntimeDeletion(withdrawal, input.dependencies, authorization) } catch (error) { input.logger.warn( { diff --git a/hub/server/domains/decision-model/process-decision-runtime-deletion/index.test.ts b/hub/server/domains/decision-model/process-decision-runtime-deletion/index.test.ts index e79db8ead..ea9a8b6f8 100644 --- a/hub/server/domains/decision-model/process-decision-runtime-deletion/index.test.ts +++ b/hub/server/domains/decision-model/process-decision-runtime-deletion/index.test.ts @@ -128,12 +128,12 @@ describe("processDecisionRuntimeDeletion()", () => { repositoryId: "22222222-2222-4222-8222-222222222222", actorMembershipId: "33333333-3333-4333-8333-333333333333", actorLogin: "former-member", - authorization: "recorded_training_withdrawal", selectors, reason: "training consent withdrawn", idempotencyKey: "withdrawal:withdrawal-1:grant", }, dependencies, + "recorded_training_withdrawal", ), ).resolves.toMatchObject({ state: "complete", pending: 0 }) diff --git a/hub/server/domains/decision-model/process-decision-runtime-deletion/index.ts b/hub/server/domains/decision-model/process-decision-runtime-deletion/index.ts index 7be71f75a..e6c119beb 100644 --- a/hub/server/domains/decision-model/process-decision-runtime-deletion/index.ts +++ b/hub/server/domains/decision-model/process-decision-runtime-deletion/index.ts @@ -7,14 +7,15 @@ export async function processDecisionRuntimeDeletion( repositoryId: string actorMembershipId: string actorLogin: string - authorization?: "recorded_training_withdrawal" selectors: DecisionRuntimeDeletionSelectors reason: string idempotencyKey: string }, dependencies: DecisionModelDependencies, + authority?: "recorded_training_withdrawal", ) { - if (input.authorization !== "recorded_training_withdrawal") { + // Only the reconciliation worker supplies authority from a persisted withdrawal. + if (authority !== "recorded_training_withdrawal") { await dependencies.authorization.requireRepositoryAdministrator({ membershipId: input.actorMembershipId, repositoryId: input.repositoryId, From 80a612ba5d6ff9d205d4e1bfc27438eae8d91a64 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 15:15:40 -0800 Subject: [PATCH 21/23] fix(hub): refuse credential-bearing Learning command results Check parsed JSON values and property names before returning a successful command result. Fail closed instead of silently rewriting signed evidence or returning private diagnostics. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../run-learning-command/index.test.ts | 19 ++++++++++++++++++ .../learning/run-learning-command/index.ts | 20 ++++++++++++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/hub/server/integrations/learning/run-learning-command/index.test.ts b/hub/server/integrations/learning/run-learning-command/index.test.ts index 5de375dc6..11f11b6e4 100644 --- a/hub/server/integrations/learning/run-learning-command/index.test.ts +++ b/hub/server/integrations/learning/run-learning-command/index.test.ts @@ -591,6 +591,25 @@ describe("runLearningCommand()", () => { } }) + it("refuses a successful report containing a database credential without returning its text", async () => { + const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) + await mkdir(directory) + onTestFinished(() => rm(directory, { force: true, recursive: true })) + const cliPath = resolve(directory, "report.mjs") + await writeFile( + cliPath, + `console.log(JSON.stringify({ diagnostic: new URL(process.env.REPLICA_LEARNING_DATABASE_URL).password }))`, + ) + const result = runLearningCommand(["doctor", "--dir", resolve(directory, "store")], { + cliPath, + learningDatabaseUrl: "postgresql://test:fixture-secret@localhost/example", + }) + await expect(result).rejects.toMatchObject({ + code: "unreadable_output", + message: "replica-learning returned output Hub could not read.", + }) + }) + it("does not expose malformed successful output through the error or its cause", async () => { const directory = resolve(`server/integrations/learning/.process-test-${randomUUID()}`) await mkdir(directory) diff --git a/hub/server/integrations/learning/run-learning-command/index.ts b/hub/server/integrations/learning/run-learning-command/index.ts index c3683b8aa..4cc44c63a 100644 --- a/hub/server/integrations/learning/run-learning-command/index.ts +++ b/hub/server/integrations/learning/run-learning-command/index.ts @@ -392,7 +392,25 @@ export async function runLearningCommand( return } try { - resolve(JSON.parse(stdout)) + if (hideDiagnostics && hasDirectory) throw new Error() + // A successful result can carry signed evidence. Refuse it rather than changing it. + const result: unknown = JSON.parse( + stdout, + secrets.length + ? (key, value: unknown) => { + if ( + secrets.some( + (secret) => + key.includes(secret) || + (typeof value === "string" && value.includes(secret)), + ) + ) + throw new Error() + return value + } + : undefined, + ) + resolve(result) } catch { reject( new LearningCommandError( From 5f0ece001eb5b73276ba7f90eb7b669a2e7f0535 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 15:18:57 -0800 Subject: [PATCH 22/23] fix(hub): wait for timed-out learning subprocesses to exit The direct child may close before the kernel reaps its descendants. Use the same bounded process-group wait on failure as on successful completion. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- hub/server/integrations/learning/run-learning-command/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hub/server/integrations/learning/run-learning-command/index.ts b/hub/server/integrations/learning/run-learning-command/index.ts index 4cc44c63a..c37a4e0da 100644 --- a/hub/server/integrations/learning/run-learning-command/index.ts +++ b/hub/server/integrations/learning/run-learning-command/index.ts @@ -275,7 +275,7 @@ export async function runLearningCommand( clearTimeout(timer) signal?.removeEventListener("abort", abort) try { - stopProcessTree(child.pid) + await stopRemainingProcessGroup(child.pid) } catch (stopError) { error = new AggregateError( [error, stopError], From c1939f08a7d95511c5e5686c3b9760cecd318b08 Mon Sep 17 00:00:00 2001 From: Nishiki Liu Date: Mon, 30 Nov 2026 15:31:50 -0800 Subject: [PATCH 23/23] fix(hub): preserve public identifiers when checking command results Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 459b160c-a7ab-4c14-8a06-098ca9096352 --- .../run-learning-command/index.test.ts | 7 ++++++ .../learning/run-learning-command/index.ts | 23 +++++++++++++++---- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/hub/server/integrations/learning/run-learning-command/index.test.ts b/hub/server/integrations/learning/run-learning-command/index.test.ts index 11f11b6e4..9430da673 100644 --- a/hub/server/integrations/learning/run-learning-command/index.test.ts +++ b/hub/server/integrations/learning/run-learning-command/index.test.ts @@ -608,6 +608,13 @@ describe("runLearningCommand()", () => { code: "unreadable_output", message: "replica-learning returned output Hub could not read.", }) + await writeFile(cliPath, `console.log(JSON.stringify({ kind: "replica.learning-config/v1" }))`) + await expect( + runLearningCommand(["doctor", "--dir", resolve(directory, "store")], { + cliPath, + learningDatabaseUrl: "postgresql://test:replica@localhost/example", + }), + ).resolves.toEqual({ kind: "replica.learning-config/v1" }) }) it("does not expose malformed successful output through the error or its cause", async () => { diff --git a/hub/server/integrations/learning/run-learning-command/index.ts b/hub/server/integrations/learning/run-learning-command/index.ts index c37a4e0da..895481c7c 100644 --- a/hub/server/integrations/learning/run-learning-command/index.ts +++ b/hub/server/integrations/learning/run-learning-command/index.ts @@ -232,6 +232,22 @@ export async function runLearningCommand( } } secrets.sort((first, second) => second.length - first.length) + const passwords = secrets.filter( + (value) => value !== githubToken && value !== learningDatabaseUrl, + ) + const passwordPattern = passwords.length + ? new RegExp( + `(? value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})(?![\\w./-])`, + "u", + ) + : null + function containsCredential(text: string) { + if (githubToken && text.includes(githubToken)) return true + if (learningDatabaseUrl && text.includes(learningDatabaseUrl)) return true + // Local installs can use "replica" as their password. A public schema name like + // "replica.learning-config/v1" is not a credential echoed in a diagnostic. + return passwordPattern?.test(text) ?? false + } function redact(value: string) { return secrets.reduce((text, secret) => text.replaceAll(secret, "[redacted]"), value) } @@ -399,11 +415,8 @@ export async function runLearningCommand( secrets.length ? (key, value: unknown) => { if ( - secrets.some( - (secret) => - key.includes(secret) || - (typeof value === "string" && value.includes(secret)), - ) + containsCredential(key) || + (typeof value === "string" && containsCredential(value)) ) throw new Error() return value