Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions docs/factorize-validation-runner.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,31 @@ PostgreSQL admin URL, so missing image prerequisites fail before migrations
or the full suite. A failure requires correcting the image or bootstrap and
publishing a new digest, followed by repeating this sequence.

## Background run acceptance

`npm run test:local` includes the background run acceptance scenario. It starts
the Worker and PostgreSQL locally. A deterministic VM backend receives the
scheduler's launch requests and supplies success and failure responses. The
test dispatches through MCP, listens for a resource update, and delivers each
terminal outcome to a durable conversation inbox. It also exercises vendor
identity, duplicate submissions, capacity, cancellation, replay, and run
history after template deletion. Chromium covers the launch form and skill
filter in the browser lane.

For a focused rerun after `npm ci`, run `npm run bootstrap:test`, export the
local database variables it prints, then run:

```sh
npm run build --workspace=factorize-app
node --test scripts/agent-api-runtime.test.mjs
node --test --test-name-pattern='filter direct runs' packages/app/test/runs.browser.test.mjs
```

The [host adapter](../scripts/watch-run.mjs) accepts an authenticated MCP
request function, a conversation ID, and an idempotent delivery callback.
The [acceptance test](../scripts/background-run-acceptance.mjs) supplies a
PostgreSQL inbox and verifies delivery after reconnecting.

## Validated image record

| Field | Value |
Expand Down
274 changes: 254 additions & 20 deletions packages/api-client/src/schema.d.ts

Large diffs are not rendered by default.

52 changes: 52 additions & 0 deletions packages/api/migrations/0061_project_runs.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
ALTER TABLE app.job_skills ADD COLUMN context_skill boolean NOT NULL DEFAULT true;
ALTER TABLE app.projects ADD COLUMN run_defaults jsonb;
ALTER TABLE app.invocations ALTER COLUMN job_id DROP NOT NULL, ALTER COLUMN trigger_id DROP NOT NULL,
ADD FOREIGN KEY (tenant_id) REFERENCES app.tenants(id) ON DELETE CASCADE,
ADD COLUMN caller text, ADD COLUMN request_hash text,
DROP CONSTRAINT invocations_source_check,
ADD CONSTRAINT invocations_source_check CHECK(source IN ('manual','schedule','webhook','jobLifecycle','jobIdle','direct'));
ALTER TABLE app.job_runs ALTER COLUMN job_id DROP NOT NULL;
ALTER TABLE app.runs ALTER COLUMN job_id DROP NOT NULL, ADD COLUMN project_id uuid,
ADD COLUMN launch_skill_id uuid, ADD COLUMN launch_skill_key text, ADD COLUMN launch_skill_revision integer,
ADD COLUMN source_job_name text;
UPDATE app.runs r SET project_id=j.project_id,source_job_name=j.name FROM app.jobs j WHERE j.tenant_id=r.tenant_id AND j.id=r.job_id;
ALTER TABLE app.runs ALTER COLUMN project_id SET NOT NULL,
ADD FOREIGN KEY(tenant_id,project_id) REFERENCES app.projects(tenant_id,id) DEFERRABLE INITIALLY DEFERRED;
ALTER TABLE app.invocations ADD COLUMN template_job_id uuid, ADD COLUMN origin_trigger_id uuid;
UPDATE app.invocations SET template_job_id=job_id,origin_trigger_id=trigger_id;
CREATE FUNCTION app.snapshot_invocation_origin() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
NEW.template_job_id := NEW.job_id;
NEW.origin_trigger_id := NEW.trigger_id;
RETURN NEW;
END $$;
CREATE TRIGGER snapshot_invocation_origin BEFORE INSERT ON app.invocations FOR EACH ROW EXECUTE FUNCTION app.snapshot_invocation_origin();
-- Allow the previous application writer to continue inserting job launches during rollout.
CREATE FUNCTION app.capture_run_project() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.job_id IS NOT NULL THEN
SELECT project_id,name INTO NEW.project_id,NEW.source_job_name FROM app.jobs WHERE tenant_id=NEW.tenant_id AND id=NEW.job_id;
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER capture_run_project BEFORE INSERT ON app.runs FOR EACH ROW EXECUTE FUNCTION app.capture_run_project();
ALTER TABLE app.runs DROP CONSTRAINT runs_tenant_id_job_id_fkey, ADD FOREIGN KEY(tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE SET NULL (job_id);
ALTER TABLE app.job_runs DROP CONSTRAINT job_runs_tenant_id_job_id_fkey, ADD FOREIGN KEY(tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE SET NULL (job_id);
ALTER TABLE app.invocations DROP CONSTRAINT invocations_tenant_id_job_id_fkey, ADD FOREIGN KEY(tenant_id,job_id) REFERENCES app.jobs(tenant_id,id) ON DELETE SET NULL (job_id),
DROP CONSTRAINT invocations_tenant_id_trigger_id_fkey, ADD FOREIGN KEY(tenant_id,trigger_id) REFERENCES app.triggers(tenant_id,id) ON DELETE SET NULL (trigger_id);
CREATE UNIQUE INDEX direct_run_claim ON app.invocations(tenant_id,caller,claim_key) WHERE source='direct';
CREATE INDEX runs_project_skill ON app.runs(tenant_id,project_id,launch_skill_id,created_at DESC,id DESC);
CREATE INDEX runs_skill ON app.runs(tenant_id,launch_skill_id,created_at DESC,id DESC);

-- A terminal run has one outcome for its lifetime. Recording it on the row
-- covers queued cancellations as well as the scheduler's terminal transaction.
ALTER TABLE app.runs ADD COLUMN outcome_id uuid;
UPDATE app.runs SET outcome_id=id WHERE state IN ('succeeded','failed','stopped');
CREATE FUNCTION app.capture_run_outcome() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NEW.state IN ('succeeded','failed','stopped') THEN NEW.outcome_id := NEW.id; END IF;
RETURN NEW;
END $$;
CREATE TRIGGER capture_run_outcome BEFORE INSERT OR UPDATE OF state ON app.runs FOR EACH ROW EXECUTE FUNCTION app.capture_run_outcome();

INSERT INTO app.schema_migrations(version) VALUES ('0061_project_runs') ON CONFLICT DO NOTHING;
2 changes: 1 addition & 1 deletion packages/api/src/access-tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Env, OAuthProps } from "./types";
import { databaseFor } from "./postgres/database";
import { AccessTokenRepository } from "./postgres/access-token-repository";

export const ACCESS_SCOPES = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "runs:write", "integrations:read", "integrations:write", "skills:read", "skills:write"] as const;
export const ACCESS_SCOPES = ["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:start", "runs:cancel", "runs:write", "integrations:read", "integrations:write", "skills:read", "skills:write"] as const;
export const AGENT_SCOPES: readonly string[] = [...ACCESS_SCOPES, "proxy:use", "vm:grant"];
export type AccessScope = typeof ACCESS_SCOPES[number];
export type LegacyScope = "flows:read" | "flows:write";
Expand Down
10 changes: 9 additions & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { z } from "zod";
import type { ApiService } from "./flow-service";
import {
jobInputSchema,
manualInvocationSchema,
startRunInput, startRunReceipt, projectRunDefaults, storedRunDefaults, manualInvocationSchema,
renameRunSchema,
reportRunErrorSchema,
invocationPermissionsInput,
Expand Down Expand Up @@ -978,6 +978,14 @@ export const API_ROUTES: RouteContract[] = [
{ summary: "Delete job", responses: { "200": { description: "Deleted" } } },
(service, { params }) => service.deleteJob(params.jobId),
),
route("POST","/api/v1/runs","runs:start",{
summary:"Start a project VM run with a literal prompt and optional launch skill",
responses:{"202":{description:"Accepted run",content:{"application/json":{schema:jsonSchema(startRunReceipt,"output")}}}},
},(service,{body})=>service.startRun(body),{body:startRunInput,maxBodyBytes:256_000}),
route("PUT","/api/v1/projects/{projectId}/run-defaults","projects:write",{
summary:"Set the VM configuration, permissions and capacity for direct launches",
responses:{"200":{description:"Project run defaults",content:{"application/json":{schema:jsonSchema(storedRunDefaults,"output")}}}},
},(service,{params,body})=>service.setRunDefaults(params.projectId,body),{body:projectRunDefaults,parameters:z.object({projectId:z.guid()}),ownerSession:true}),
route(
"GET",
"/api/v1/runs",
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/api-document.json
Original file line number Diff line number Diff line change
Expand Up @@ -767,7 +767,7 @@
"type": "string"
},
"jobId": {
"type": "string"
"type": ["string", "null"]
},
"state": {
"type": "string"
Expand Down
24 changes: 23 additions & 1 deletion packages/api/src/flow-schemas.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { z } from "zod";
import { conditionsSchema, preparedWebhookSchema } from "./webhook-conditions";

export const scopeSchema = z.enum(["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:cancel", "runs:write", "integrations:read", "integrations:write", "skills:read", "skills:write"]);
export const scopeSchema = z.enum(["projects:read", "projects:write", "jobs:read", "jobs:write", "runs:read", "runs:invoke", "runs:start", "runs:cancel", "runs:write", "integrations:read", "integrations:write", "skills:read", "skills:write"]);
export const runStateSchema = z.enum(["queued", "reserved", "starting", "running", "done", "blocked", "failed", "ignored", "succeeded", "stopping", "stopped"]);
export const matchRuleSchema = z.object({
type: z.enum(["owner", "creator", "status", "label", "assignee"]),
targetId: z.string().min(1),
});
export const listRunsSchema = z.object({
projectId: z.union([z.guid(), z.array(z.guid()).min(1).max(100)]).optional(), jobId: z.union([z.guid(), z.array(z.guid()).min(1).max(100)]).optional(), state: z.union([runStateSchema, z.array(runStateSchema).min(1).max(10)]).optional(),
launchSkillId: z.union([z.guid(), z.literal("none")]).optional(),
contextQuery: z.string().min(1).max(50_000).optional(),
sort: z.enum(["job", "run", "status", "created", "agent"]).optional(),
direction: z.enum(["asc", "desc"]).optional(),
Expand Down Expand Up @@ -75,6 +76,7 @@ export const jobInputSchema = z.object({
model: z.string().trim().max(120).optional(),
effort: z.string().trim().max(40).optional(),
triggers: z.array(triggerSchema).max(50).default([]),
launchSkillId: z.guid().nullable().optional(),
skillIds: z.array(z.guid()).max(50).optional(),
portableIntegrationIds: z.array(z.guid()).max(100).refine(ids => new Set(ids).size === ids.length, "Portable integrations must be unique").optional(),
modelAccess: z.enum(["native", "portable"]).optional(),
Expand Down Expand Up @@ -112,3 +114,23 @@ export const jobConditionsTestSchema = z.object({

export type JobInput = z.infer<typeof jobInputSchema>;
export type ManualInvocationInput = z.infer<typeof manualInvocationSchema>;

export const startRunInput = z.object({
projectId: z.guid().optional(),
prompt: z.string().min(1).max(50_000).refine(value => !!value.trim()),
skill: z.string().min(1).max(64).optional(),
name: z.string().trim().min(1).max(120).optional(),
inputs: z.record(z.string(), z.unknown()).refine(value => new TextEncoder().encode(JSON.stringify(value)).length <= 200_000, "Inputs exceed 200,000 bytes").optional(),
idempotencyKey: z.string().trim().min(1).max(200).optional(),
}).strict();
export const startRunReceipt = z.object({runId:z.guid(), url:z.url(), outcomeUri:z.string(), duplicate:z.boolean()});
export const projectRunDefaults = z.object({
executionConfigId: jobInputSchema.shape.executionConfigId,
model: jobInputSchema.shape.model, effort: jobInputSchema.shape.effort, vmImage: jobInputSchema.shape.vmImage,
tags: jobInputSchema.shape.tags, modelAccountId: jobInputSchema.shape.modelAccountId,
portableIntegrationIds: jobInputSchema.shape.portableIntegrationIds, githubInstallationIds: jobInputSchema.shape.githubInstallationIds,
linearConnectionId: jobInputSchema.shape.linearConnectionId, xConnectionIds: jobInputSchema.shape.xConnectionIds,
runScopes: jobInputSchema.shape.runScopes, capacity: z.number().int().min(1).max(50).default(4),
}).strict();

export const storedRunDefaults = projectRunDefaults.extend({vmImage:z.string().optional()});
Loading