diff --git a/package-lock.json b/package-lock.json index b353f702..4a1ffde3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3606,6 +3606,18 @@ "undici-types": "~8.9.0" } }, + "node_modules/@types/pg": { + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz", + "integrity": "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "pg-protocol": "*", + "pg-types": "^2.2.0" + } + }, "node_modules/@types/whatwg-mimetype": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz", @@ -4697,6 +4709,95 @@ "node": ">= 14.16" } }, + "node_modules/pg": { + "version": "8.16.3", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.16.3.tgz", + "integrity": "sha512-enxc1h0jA/aq5oSDMvqyW3q89ra6XIIDZgCX9vkMrnz5DFTw/Ny3Li2lFQ+pt3L6MCgm/5o2o8HW9hiJji+xvw==", + "license": "MIT", + "dependencies": { + "pg-connection-string": "^2.9.1", + "pg-pool": "^3.10.1", + "pg-protocol": "^1.10.3", + "pg-types": "2.2.0", + "pgpass": "1.0.5" + }, + "engines": { + "node": ">= 16.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.2.7" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.0.tgz", + "integrity": "sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==", + "license": "MIT", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.0.tgz", + "integrity": "sha512-XwWDGcLRGCXAR8F/AM5bG7Q+A3Wm2s6QeEjlOKZLlH3UYcguiqCWKyWXVag5TLTIjR7oOJUY8kcADaZgWPyLeg==", + "license": "MIT" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "license": "ISC", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz", + "integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==", + "license": "MIT", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.0.tgz", + "integrity": "sha512-sILXutLVjCLjcDuOmvhX5e2Z4cS5qG/6Bu3VkpFwdf/633ElGLpEh9bgmuI5I4sqKqkifQiGyiCcx1HdtrK7tg==", + "license": "MIT" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "license": "MIT", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "license": "MIT", + "dependencies": { + "split2": "^4.1.0" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -4746,6 +4847,45 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", + "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/rollup": { "version": "4.63.1", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.63.1.tgz", @@ -4882,6 +5022,15 @@ "node": ">=0.10.0" } }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -5838,6 +5987,15 @@ } } }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, "node_modules/youch": { "version": "4.1.0-beta.10", "resolved": "https://registry.npmjs.org/youch/-/youch-4.1.0-beta.10.tgz", @@ -5882,6 +6040,7 @@ "cron-parser": "^5.10.1", "hono": "^4.11.4", "mustache": "^4.2.0", + "pg": "8.16.3", "zod": "^4.6.2" }, "devDependencies": { @@ -5890,6 +6049,7 @@ "@tailwindcss/cli": "^4.1.14", "@types/mustache": "^4.2.6", "@types/node": "^26.5.1", + "@types/pg": "^8.15.5", "happy-dom": "^20.14.5", "tailwindcss": "^4.1.14", "typescript": "^5.9.3", diff --git a/packages/app/migrations/0001_app_schema.sql b/packages/app/migrations/0001_app_schema.sql new file mode 100644 index 00000000..f80b819e --- /dev/null +++ b/packages/app/migrations/0001_app_schema.sql @@ -0,0 +1,61 @@ +CREATE EXTENSION IF NOT EXISTS pg_trgm; +CREATE SCHEMA IF NOT EXISTS app; + +CREATE TABLE IF NOT EXISTS app.schema_migrations (version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now()); +CREATE TABLE app.tenants (id uuid PRIMARY KEY, name text, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now()); +CREATE TABLE app.auth_users (id uuid PRIMARY KEY, email text NOT NULL UNIQUE, email_verified boolean NOT NULL DEFAULT false, created_at timestamptz NOT NULL DEFAULT now()); +CREATE TABLE app.auth_accounts (id uuid PRIMARY KEY, user_id uuid NOT NULL REFERENCES app.auth_users(id) ON DELETE CASCADE, provider text NOT NULL, provider_account_id text NOT NULL, password_hash text, UNIQUE(provider, provider_account_id)); +CREATE TABLE app.auth_reset_tokens (digest text PRIMARY KEY, user_id uuid NOT NULL REFERENCES app.auth_users(id) ON DELETE CASCADE, expires_at timestamptz NOT NULL, used_at timestamptz); +CREATE TABLE app.auth_sessions (id uuid PRIMARY KEY, user_id uuid NOT NULL REFERENCES app.auth_users(id) ON DELETE CASCADE, expires_at timestamptz NOT NULL, revoked_at timestamptz); +CREATE TABLE app.members (tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, user_id uuid NOT NULL REFERENCES app.auth_users(id) ON DELETE CASCADE, email text NOT NULL, role text NOT NULL CHECK (role IN ('owner','member')), session_version integer NOT NULL DEFAULT 1 CHECK (session_version > 0), created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,user_id)); +CREATE TABLE app.access_tokens (tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, id uuid NOT NULL, name text NOT NULL, digest text NOT NULL UNIQUE, user_id uuid NOT NULL, session_version integer NOT NULL, scopes jsonb NOT NULL DEFAULT '[]', created_at timestamptz NOT NULL DEFAULT now(), expires_at timestamptz NOT NULL, last_used_at timestamptz, revoked_at timestamptz, PRIMARY KEY (tenant_id,id), FOREIGN KEY (tenant_id,user_id) REFERENCES app.members(tenant_id,user_id) ON DELETE CASCADE); + +CREATE TABLE app.connections (tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, kind text NOT NULL, encrypted_value text NOT NULL, updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,kind)); +CREATE TABLE app.github_installations (installation_id bigint PRIMARY KEY, tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, account_login text NOT NULL, account_type text NOT NULL, state text NOT NULL CHECK (state IN ('active','suspended')), updated_at timestamptz NOT NULL DEFAULT now(), UNIQUE (tenant_id,installation_id)); +CREATE TABLE app.github_setup_states (tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, nonce text NOT NULL, expires_at timestamptz NOT NULL, used_at timestamptz, PRIMARY KEY (tenant_id,nonce)); + +CREATE TABLE app.jobs (tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, id uuid NOT NULL, name text NOT NULL, slug text NOT NULL, encrypted_prompt_template text NOT NULL, encrypted_run_name_template text NOT NULL DEFAULT '', execution_target jsonb NOT NULL, concurrency_limit integer NOT NULL CHECK (concurrency_limit >= 1), enabled boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,slug)); +CREATE TABLE app.triggers (tenant_id uuid NOT NULL, id uuid NOT NULL, job_id uuid NOT NULL, kind text NOT NULL CHECK (kind IN ('manual','schedule','webhook','jobLifecycle')), slug text NOT NULL, enabled boolean NOT NULL DEFAULT true, config jsonb NOT NULL DEFAULT '{}', position integer NOT NULL DEFAULT 0, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,job_id,slug), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE); +CREATE TABLE app.invocations (tenant_id uuid NOT NULL, id uuid NOT NULL, job_id uuid NOT NULL, source text NOT NULL CHECK (source IN ('manual','schedule','webhook','jobLifecycle')), claim_key text NOT NULL, trigger_id uuid NOT NULL, context jsonb NOT NULL, occurrence jsonb, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,job_id,claim_key), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE, FOREIGN KEY (tenant_id,trigger_id) REFERENCES app.triggers(tenant_id,id)); +CREATE TABLE app.job_runs (tenant_id uuid NOT NULL, id uuid NOT NULL, job_id uuid NOT NULL, invocation_id uuid NOT NULL, state text NOT NULL CHECK (state IN ('queued','starting','running','blocked','stopping','succeeded','failed','stopped')), encrypted_prompt text NOT NULL, run_name text NOT NULL DEFAULT '', launch_lease_expires_at timestamptz, next_poll_at timestamptz, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), started_at timestamptz, PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,invocation_id), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE, FOREIGN KEY (tenant_id,invocation_id) REFERENCES app.invocations(tenant_id,id) ON DELETE CASCADE); +CREATE INDEX job_runs_queue ON app.job_runs (state,created_at) WHERE state='queued'; +CREATE INDEX job_runs_poll_due ON app.job_runs (next_poll_at) WHERE state IN ('running','blocked','stopping'); +CREATE INDEX job_runs_launch_lease ON app.job_runs (launch_lease_expires_at) WHERE state='starting'; + +CREATE TABLE app.runs (tenant_id uuid NOT NULL, id uuid NOT NULL, job_id uuid NOT NULL, invocation_id uuid NOT NULL, provider text NOT NULL, issue_id text NOT NULL, issue_url text, issue_title text NOT NULL DEFAULT '', run_name text NOT NULL DEFAULT '', agent_name text NOT NULL, workspace_name text NOT NULL DEFAULT '', agent_kind text NOT NULL DEFAULT '', state text NOT NULL, execution_backend_kind text NOT NULL DEFAULT '', execution_handle jsonb, execution_capabilities jsonb NOT NULL DEFAULT '[]', destination_url text, result text, output_captured boolean NOT NULL DEFAULT false, claim_released boolean NOT NULL DEFAULT false, vm_cleanup_attempt integer NOT NULL DEFAULT 0, cleanup_next_at timestamptz, vm_cleanup_complete boolean NOT NULL DEFAULT false, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,invocation_id), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE, FOREIGN KEY (tenant_id,invocation_id) REFERENCES app.invocations(tenant_id,id) ON DELETE CASCADE); +CREATE INDEX runs_order ON app.runs (tenant_id,created_at DESC,id DESC); +CREATE INDEX runs_state_order ON app.runs (tenant_id,state,created_at DESC,id DESC); +CREATE INDEX runs_cleanup_due ON app.runs (cleanup_next_at) WHERE NOT vm_cleanup_complete; +CREATE INDEX runs_issue_trgm ON app.runs USING gin (issue_id gin_trgm_ops); +CREATE INDEX runs_name_trgm ON app.runs USING gin (run_name gin_trgm_ops); +CREATE TABLE app.run_transcripts (tenant_id uuid NOT NULL, run_id uuid NOT NULL, transcript text NOT NULL, byte_size integer NOT NULL CHECK (byte_size >= 0), search_vector tsvector GENERATED ALWAYS AS (to_tsvector('english',transcript)) STORED, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,run_id), FOREIGN KEY (tenant_id,run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE); +CREATE INDEX run_transcripts_search ON app.run_transcripts USING gin (search_vector); +CREATE TABLE app.run_activity (tenant_id uuid NOT NULL, id uuid NOT NULL, run_id uuid NOT NULL, action text NOT NULL, detail text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), FOREIGN KEY (tenant_id,run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE); +CREATE TABLE app.active_claims (tenant_id uuid NOT NULL, job_id uuid NOT NULL, claim_key text NOT NULL, run_id uuid NOT NULL, expires_at timestamptz, PRIMARY KEY (tenant_id,job_id,claim_key), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE, FOREIGN KEY (tenant_id,run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE); + +CREATE TABLE app.schedule_state (tenant_id uuid NOT NULL, trigger_id uuid NOT NULL, job_id uuid NOT NULL, next_run_at timestamptz, last_triggered_at timestamptz, PRIMARY KEY (tenant_id,trigger_id), FOREIGN KEY (tenant_id,trigger_id) REFERENCES app.triggers(tenant_id,id) ON DELETE CASCADE, FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE); +CREATE INDEX schedules_due ON app.schedule_state (next_run_at) WHERE next_run_at IS NOT NULL; +CREATE TABLE app.automatic_wakes (tenant_id uuid NOT NULL, job_id uuid NOT NULL, trailing_pending boolean NOT NULL DEFAULT false, summary jsonb NOT NULL DEFAULT '{}', updated_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,job_id), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE); +CREATE TABLE app.lifecycle_deliveries (tenant_id uuid NOT NULL, trigger_id uuid NOT NULL, source_run_id uuid NOT NULL, terminal_state text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,trigger_id,source_run_id,terminal_state), FOREIGN KEY (tenant_id,trigger_id) REFERENCES app.triggers(tenant_id,id) ON DELETE CASCADE, FOREIGN KEY (tenant_id,source_run_id) REFERENCES app.runs(tenant_id,id) ON DELETE CASCADE); +CREATE TABLE app.job_events (tenant_id uuid NOT NULL, id uuid NOT NULL, job_id uuid NOT NULL, provider text NOT NULL, delivery_id text NOT NULL, outcome text NOT NULL, detail text NOT NULL, received_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE); +CREATE INDEX job_events_by_job ON app.job_events (tenant_id,job_id,received_at DESC); + +CREATE TABLE app.webhook_deliveries (tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, id uuid NOT NULL, provider text NOT NULL, delivery_id text NOT NULL, event_type text NOT NULL DEFAULT 'unknown', event_action text NOT NULL DEFAULT 'unknown', outcome text NOT NULL, detail text NOT NULL, received_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), UNIQUE (tenant_id,provider,delivery_id)); +CREATE TABLE app.webhook_delivery_events (tenant_id uuid NOT NULL, id uuid NOT NULL, delivery_id uuid NOT NULL, job_id uuid, outcome text NOT NULL, detail text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id,id), FOREIGN KEY (tenant_id,delivery_id) REFERENCES app.webhook_deliveries(tenant_id,id) ON DELETE CASCADE, FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE SET NULL); +CREATE TABLE app.pending_verifications (tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, id uuid NOT NULL, job_id uuid, delivery_id text NOT NULL, installation_id bigint NOT NULL, repository_id bigint NOT NULL, repository_owner text NOT NULL, repository_name text NOT NULL, pull_number integer NOT NULL, attempt integer NOT NULL DEFAULT 0, next_attempt_at timestamptz NOT NULL, payload jsonb NOT NULL, PRIMARY KEY (tenant_id,id), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE); +CREATE INDEX pending_verifications_due ON app.pending_verifications (next_attempt_at); +CREATE TABLE app.tail_fingerprints (tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE, job_id uuid NOT NULL, fingerprint text NOT NULL, window_started_at timestamptz NOT NULL, count integer NOT NULL CHECK (count >= 0), PRIMARY KEY (tenant_id,job_id,fingerprint), FOREIGN KEY (tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE CASCADE); +CREATE TABLE app.wake_hints (key text PRIMARY KEY DEFAULT 'global' CHECK (key='global'), not_before timestamptz NOT NULL, updated_at timestamptz NOT NULL DEFAULT now()); + +CREATE OR REPLACE FUNCTION app.next_wake_at() RETURNS timestamptz LANGUAGE sql STABLE AS $$ + SELECT min(candidate) FROM ( + SELECT min(not_before) candidate FROM app.wake_hints + UNION ALL SELECT min(next_run_at) FROM app.schedule_state + UNION ALL SELECT min(next_attempt_at) FROM app.pending_verifications + UNION ALL SELECT min(launch_lease_expires_at) FROM app.job_runs WHERE state='starting' + UNION ALL SELECT min(next_poll_at) FROM app.job_runs WHERE state IN ('running','blocked','stopping') + UNION ALL SELECT min(cleanup_next_at) FROM app.runs WHERE NOT vm_cleanup_complete + ) wakes +$$; + +INSERT INTO app.schema_migrations(version) VALUES ('0001_app_schema') ON CONFLICT DO NOTHING; diff --git a/packages/app/migrations/README.md b/packages/app/migrations/README.md new file mode 100644 index 00000000..2b8c8c23 --- /dev/null +++ b/packages/app/migrations/README.md @@ -0,0 +1,21 @@ +# PostgreSQL migrations + +These reviewed SQL migrations run outside Worker request handling. Apply them +with a schema-owner connection: + +```bash +DATABASE_URL=postgresql://... npm run db:migrate --workspace=factorize +DATABASE_URL=postgresql://... npm run db:verify --workspace=factorize +``` + +The runner serializes concurrent deploys with a PostgreSQL advisory lock and +records each applied filename in `app.schema_migrations`. Verify migrations on +an isolated Neon branch before applying them to production. The application +must connect through Hyperdrive with a least-privilege role; do not commit its +connection string or expose it as a Worker variable. + +The initial schema deliberately excludes the inert legacy `pipes`, +`deliveries`, and `flow_events` tables. Every application-owned relationship +uses a tenant-qualified key so a child row cannot reference another tenant's +record. `run_transcripts` stores only scrubbed plaintext and provides the GIN +full-text index used by PostgreSQL search. diff --git a/packages/app/package.json b/packages/app/package.json index 3fe3827b..ab9aaa81 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -9,7 +9,9 @@ "check": "tsc --noEmit && vitest run && npm run test:e2e && wrangler deploy --dry-run", "test": "vitest run", "test:e2e": "vitest run --config vitest.e2e.config.ts", - "deploy": "wrangler deploy" + "deploy": "wrangler deploy", + "db:migrate": "node scripts/migrate.mjs", + "db:verify": "node scripts/verify-schema.mjs" }, "dependencies": { "@cloudflare/workers-oauth-provider": "^0.10.3", @@ -18,6 +20,7 @@ "cron-parser": "^5.10.1", "hono": "^4.11.4", "mustache": "^4.2.0", + "pg": "8.16.3", "zod": "^4.6.2" }, "devDependencies": { @@ -26,6 +29,7 @@ "@tailwindcss/cli": "^4.1.14", "@types/mustache": "^4.2.6", "@types/node": "^26.5.1", + "@types/pg": "^8.15.5", "happy-dom": "^20.14.5", "tailwindcss": "^4.1.14", "typescript": "^5.9.3", diff --git a/packages/app/scripts/migrate.mjs b/packages/app/scripts/migrate.mjs new file mode 100644 index 00000000..166a36b4 --- /dev/null +++ b/packages/app/scripts/migrate.mjs @@ -0,0 +1,37 @@ +import { readFile, readdir } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import pg from "pg"; + +const databaseUrl = process.env.DATABASE_URL; +if (!databaseUrl) throw new Error("DATABASE_URL is required"); + +const migrationsDirectory = join(dirname(fileURLToPath(import.meta.url)), "..", "migrations"); +const files = (await readdir(migrationsDirectory)).filter((file) => /^\d+.*\.sql$/.test(file)).sort(); +const client = new pg.Client({ connectionString: databaseUrl, ssl: databaseUrl.includes("localhost") ? undefined : { rejectUnauthorized: false } }); + +await client.connect(); +try { + await client.query("SELECT pg_advisory_lock(hashtext('factorize:migrations'))"); + await client.query("CREATE SCHEMA IF NOT EXISTS app"); + await client.query("CREATE TABLE IF NOT EXISTS app.schema_migrations (version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())"); + const applied = new Set((await client.query("SELECT version FROM app.schema_migrations")).rows.map(({ version }) => version)); + for (const file of files) { + const version = file.replace(/\.sql$/, ""); + if (applied.has(version)) continue; + const sql = await readFile(join(migrationsDirectory, file), "utf8"); + await client.query("BEGIN"); + try { + await client.query(sql); + await client.query("INSERT INTO app.schema_migrations(version) VALUES ($1) ON CONFLICT DO NOTHING", [version]); + await client.query("COMMIT"); + console.log(`applied ${version}`); + } catch (error) { + await client.query("ROLLBACK"); + throw error; + } + } +} finally { + await client.query("SELECT pg_advisory_unlock(hashtext('factorize:migrations'))").catch(() => undefined); + await client.end(); +} diff --git a/packages/app/scripts/verify-schema.mjs b/packages/app/scripts/verify-schema.mjs new file mode 100644 index 00000000..ab8f461d --- /dev/null +++ b/packages/app/scripts/verify-schema.mjs @@ -0,0 +1,43 @@ +import pg from "pg"; + +const databaseUrl = process.env.DATABASE_URL; +if (!databaseUrl) throw new Error("DATABASE_URL is required"); +const client = new pg.Client({ connectionString: databaseUrl, ssl: databaseUrl.includes("localhost") ? undefined : { rejectUnauthorized: false } }); +const ids = { + tenantA: "10000000-0000-4000-8000-000000000001", tenantB: "10000000-0000-4000-8000-000000000002", + jobA: "20000000-0000-4000-8000-000000000001", jobB: "20000000-0000-4000-8000-000000000002", + triggerA: "30000000-0000-4000-8000-000000000001", invocationA: "40000000-0000-4000-8000-000000000001", + runA: "50000000-0000-4000-8000-000000000001", executionA: "60000000-0000-4000-8000-000000000001", +}; + +await client.connect(); +try { + await client.query("BEGIN"); + await client.query("INSERT INTO app.tenants(id) VALUES ($1),($2)", [ids.tenantA, ids.tenantB]); + await client.query("INSERT INTO app.jobs(tenant_id,id,name,slug,encrypted_prompt_template,execution_target,concurrency_limit) VALUES ($1,$2,'A','same-slug','cipher','{}',1),($3,$4,'B','same-slug','cipher','{}',1)", [ids.tenantA, ids.jobA, ids.tenantB, ids.jobB]); + await client.query("INSERT INTO app.triggers(tenant_id,id,job_id,kind,slug) VALUES ($1,$2,$3,'manual','manual')", [ids.tenantA, ids.triggerA, ids.jobA]); + await client.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context) VALUES ($1,$2,$3,'manual','claim:one',$4,'{}')", [ids.tenantA, ids.invocationA, ids.jobA, ids.triggerA]); + const duplicate = await client.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context) VALUES ($1,gen_random_uuid(),$2,'manual','claim:one',$3,'{}') ON CONFLICT (tenant_id,job_id,claim_key) DO NOTHING", [ids.tenantA, ids.jobA, ids.triggerA]); + if (duplicate.rowCount !== 0) throw new Error("invocation deduplication constraint failed"); + await client.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt) VALUES ($1,$2,$3,$4,'queued','cipher')", [ids.tenantA, ids.runA, ids.jobA, ids.invocationA]); + await client.query("INSERT INTO app.runs(tenant_id,id,job_id,invocation_id,provider,issue_id,agent_name,state) VALUES ($1,$2,$3,$4,'linear','GEN-2113','codex','running')", [ids.tenantA, ids.executionA, ids.jobA, ids.invocationA]); + await client.query("INSERT INTO app.run_transcripts(tenant_id,run_id,transcript,byte_size) VALUES ($1,$2,'postgres durable orchestration',30)", [ids.tenantA, ids.executionA]); + const search = await client.query("SELECT run_id FROM app.run_transcripts WHERE tenant_id=$1 AND search_vector @@ plainto_tsquery('english',$2)", [ids.tenantA, "orchestration"]); + if (search.rowCount !== 1) throw new Error("tenant-scoped full-text search failed"); + let isolated = false; + await client.query("SAVEPOINT cross_tenant"); + try { + await client.query("INSERT INTO app.triggers(tenant_id,id,job_id,kind,slug) VALUES ($1,gen_random_uuid(),$2,'manual','invalid')", [ids.tenantA, ids.jobB]); + } catch (error) { + if (error.code !== "23503") throw error; + isolated = true; + await client.query("ROLLBACK TO SAVEPOINT cross_tenant"); + } + if (!isolated) throw new Error("cross-tenant foreign key was accepted"); + await client.query("INSERT INTO app.wake_hints(not_before) VALUES (now()) ON CONFLICT (key) DO UPDATE SET not_before=excluded.not_before"); + if (!(await client.query("SELECT app.next_wake_at() wake")).rows[0]?.wake) throw new Error("next wake calculation failed"); + console.log("schema verification passed"); +} finally { + await client.query("ROLLBACK").catch(() => undefined); + await client.end(); +} diff --git a/packages/app/src/postgres/database.ts b/packages/app/src/postgres/database.ts new file mode 100644 index 00000000..31bcc4c3 --- /dev/null +++ b/packages/app/src/postgres/database.ts @@ -0,0 +1,30 @@ +import { Pool, type PoolClient, type PoolConfig, type QueryResultRow } from "pg"; + +export interface DatabaseClient { + query(text: string, values?: readonly unknown[]): Promise<{ rows: Row[]; rowCount: number | null }>; +} + +export class Database { + readonly pool: Pool; + + constructor(config: PoolConfig) { + this.pool = new Pool({ max: 5, connectionTimeoutMillis: 10_000, idleTimeoutMillis: 30_000, ...config }); + } + + async transaction(work: (client: PoolClient) => Promise): Promise { + const client = await this.pool.connect(); + try { + await client.query("BEGIN"); + const result = await work(client); + await client.query("COMMIT"); + return result; + } catch (error) { + await client.query("ROLLBACK"); + throw error; + } finally { + client.release(); + } + } + + async close(): Promise { await this.pool.end(); } +} diff --git a/packages/app/src/postgres/invocation-repository.ts b/packages/app/src/postgres/invocation-repository.ts new file mode 100644 index 00000000..a7f339c1 --- /dev/null +++ b/packages/app/src/postgres/invocation-repository.ts @@ -0,0 +1,82 @@ +import type { Invocation, JobRun } from "../job-domain"; +import type { Database, DatabaseClient } from "./database"; + +export interface PersistedInvocation { invocation: Invocation; run: JobRun } + +interface InvocationRow { + invocation_id: string; + job_id: string; + source: Invocation["source"]; + claim_key: string; + trigger_id: string; + context: Record; + occurrence: Invocation["occurrence"] | null; + invocation_created_at: Date; + run_id: string; + run_state: JobRun["state"]; + encrypted_prompt: string; + run_name: string; + run_created_at: Date; + run_updated_at: Date; + started_at: Date | null; +} + +const SELECT_INVOCATION = ` + SELECT i.id invocation_id,i.job_id,i.source,i.claim_key,i.trigger_id,i.context,i.occurrence, + i.created_at invocation_created_at,r.id run_id,r.state run_state,r.encrypted_prompt, + r.run_name,r.created_at run_created_at,r.updated_at run_updated_at,r.started_at + FROM app.invocations i + JOIN app.job_runs r ON r.tenant_id=i.tenant_id AND r.invocation_id=i.id + WHERE i.tenant_id=$1 AND i.job_id=$2 AND i.claim_key=$3`; + +function mapped(row: InvocationRow): PersistedInvocation { + return { + invocation: { + id: row.invocation_id, jobId: row.job_id, source: row.source, claimKey: row.claim_key, + triggerId: row.trigger_id, context: row.context, ...(row.occurrence ? { occurrence: row.occurrence } : {}), + createdAt: row.invocation_created_at.toISOString(), + }, + run: { + id: row.run_id, jobId: row.job_id, invocationId: row.invocation_id, state: row.run_state, + encryptedPrompt: row.encrypted_prompt, ...(row.run_name ? { runName: row.run_name } : {}), + createdAt: row.run_created_at.toISOString(), updatedAt: row.run_updated_at.toISOString(), + ...(row.started_at ? { startedAt: row.started_at.toISOString() } : {}), + } as JobRun, + }; +} + +/** All methods require tenant identity; no query in this repository is tenant-global. */ +export class InvocationRepository { + constructor(private database: Database, private tenantId: string) { + if (!tenantId) throw new Error("tenantId is required"); + } + + async find(jobId: string, claimKey: string, client: DatabaseClient = this.database.pool): Promise { + const result = await client.query(SELECT_INVOCATION, [this.tenantId, jobId, claimKey]); + return result.rows[0] ? mapped(result.rows[0]) : null; + } + + async create(invocation: Invocation, run: JobRun, wakeAt = new Date()): Promise { + return this.database.transaction(async (client) => { + const inserted = await client.query<{ id: string }>(` + INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context,occurrence,created_at) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) + ON CONFLICT (tenant_id,job_id,claim_key) DO NOTHING RETURNING id`, + [this.tenantId, invocation.id, invocation.jobId, invocation.source, invocation.claimKey, invocation.triggerId, invocation.context, invocation.occurrence ?? null, invocation.createdAt]); + + if (inserted.rowCount) { + await client.query(` + INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt,run_name,created_at,updated_at,started_at) + VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, + [this.tenantId, run.id, run.jobId, run.invocationId, run.state, run.encryptedPrompt, (run as JobRun & { runName?: string }).runName ?? "", run.createdAt, run.updatedAt, run.startedAt ?? null]); + await client.query(` + INSERT INTO app.wake_hints(key,not_before,updated_at) VALUES ('global',$1,now()) + ON CONFLICT (key) DO UPDATE SET not_before=least(app.wake_hints.not_before,excluded.not_before),updated_at=now()`, [wakeAt]); + } + + const persisted = await this.find(invocation.jobId, invocation.claimKey, client); + if (!persisted) throw new Error("Invocation transaction completed without a canonical record"); + return { ...persisted, duplicate: !inserted.rowCount }; + }); + } +} diff --git a/packages/app/test/postgres-invocation-repository.test.ts b/packages/app/test/postgres-invocation-repository.test.ts new file mode 100644 index 00000000..f7d390b8 --- /dev/null +++ b/packages/app/test/postgres-invocation-repository.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it, vi } from "vitest"; +import { InvocationRepository } from "../src/postgres/invocation-repository"; +import type { Database } from "../src/postgres/database"; +import type { Invocation, JobRun } from "../src/job-domain"; + +const tenantId = "10000000-0000-4000-8000-000000000001"; +const invocation: Invocation = { id: "20000000-0000-4000-8000-000000000001", jobId: "30000000-0000-4000-8000-000000000001", source: "manual", claimKey: "manual:one", triggerId: "40000000-0000-4000-8000-000000000001", context: { value: 1 }, createdAt: "2026-09-18T00:00:00.000Z" }; +const run: JobRun = { id: "50000000-0000-4000-8000-000000000001", jobId: invocation.jobId, invocationId: invocation.id, state: "queued", encryptedPrompt: "ciphertext", createdAt: invocation.createdAt, updatedAt: invocation.createdAt }; +const row = { invocation_id: invocation.id, job_id: invocation.jobId, source: invocation.source, claim_key: invocation.claimKey, trigger_id: invocation.triggerId, context: invocation.context, occurrence: null, invocation_created_at: new Date(invocation.createdAt), run_id: run.id, run_state: run.state, encrypted_prompt: run.encryptedPrompt, run_name: "", run_created_at: new Date(run.createdAt), run_updated_at: new Date(run.updatedAt), started_at: null }; + +describe("InvocationRepository", () => { + it("creates invocation, run, and wake hint in one transaction", async () => { + const query = vi.fn().mockResolvedValueOnce({ rows: [{ id: invocation.id }], rowCount: 1 }).mockResolvedValueOnce({ rows: [], rowCount: 1 }).mockResolvedValueOnce({ rows: [], rowCount: 1 }).mockResolvedValueOnce({ rows: [row], rowCount: 1 }); + const database = { pool: {}, transaction: (work: (client: { query: typeof query }) => unknown) => work({ query }) } as unknown as Database; + const result = await new InvocationRepository(database, tenantId).create(invocation, run); + expect(result.duplicate).toBe(false); + expect(query).toHaveBeenCalledTimes(4); + expect(query.mock.calls[0][1][0]).toBe(tenantId); + expect(query.mock.calls[2][0]).toContain("app.wake_hints"); + expect(query.mock.calls[3][1]).toEqual([tenantId, invocation.jobId, invocation.claimKey]); + }); + + it("returns the canonical winner without creating a second run", async () => { + const query = vi.fn().mockResolvedValueOnce({ rows: [], rowCount: 0 }).mockResolvedValueOnce({ rows: [row], rowCount: 1 }); + const database = { pool: {}, transaction: (work: (client: { query: typeof query }) => unknown) => work({ query }) } as unknown as Database; + const result = await new InvocationRepository(database, tenantId).create(invocation, run); + expect(result.duplicate).toBe(true); + expect(query).toHaveBeenCalledTimes(2); + }); + + it("rejects construction without tenant scope", () => { + expect(() => new InvocationRepository({} as Database, "")).toThrow("tenantId is required"); + }); +});