diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 845831a6..db60aa4b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,6 +42,8 @@ jobs: run: | npm run generate git diff --exit-code -- packages/docs/openapi.yaml packages/api-client/src/schema.d.ts + - name: Validate hosted docs, MCP inventory and generated exports + run: npm run validate --workspace=factorize-docs - name: Install browser for static application checks run: npx playwright install --with-deps chromium - run: npm run check diff --git a/README.md b/README.md index d9cf65cc..20bcbf18 100644 --- a/README.md +++ b/README.md @@ -1,243 +1,35 @@ # Factorize [![CI](https://github.com/GenerationSoftware/factorize/actions/workflows/ci.yml/badge.svg)](https://github.com/GenerationSoftware/factorize/actions/workflows/ci.yml) -[![Deploy to Cloudflare](https://img.shields.io/badge/Deploy_to-Cloudflare-F38020?style=flat&logo=cloudflare&logoColor=white)](https://deploy.workers.cloudflare.com/?url=https://github.com/GenerationSoftware/factorize&path=packages/api) -**A no-code software factory for Linear teams.** Factorize turns selected Linear issue changes into coding-agent jobs on isolated, ephemeral exe.dev VMs. +Factorize hosts jobs for your coding agents. **Connect your agent → create a job → run it → inspect the result → automate it.** -```text -Linear webhook → Cloudflare Worker → Durable Object → exe.dev /exec → isolated agent VM - ↑ polls status ↓ - concurrency control Linear comments -``` - -## Why Factorize? - -- Keep control: agents run on your own exe.dev VM, not a shared runner. -- Automate deliberately: match Linear issues by owner, creator, status, label, or assignee. -- Isolate work: every agent run gets a fresh VM that is deleted as soon as the run ends. -- Stay isolated: each Linear workspace has its own Cloudflare Durable Object. -- Avoid duplicate work: a claimed issue stays claimed until its agent job completes. - -## Deploy to Cloudflare - -Click the **Deploy to Cloudflare** button above to create a copy of the app Worker in your own Cloudflare account. The button selects `packages/api` as the Worker root; Cloudflare provisions the bindings for the copied repository. Configure Workers Builds to run `npm run build --workspace=factorize-app` before deploying; static output lives beside the backend package. Follow the API-first bootstrap in the rollout guide. - -> The Deploy to Cloudflare button works for public GitHub or GitLab repositories. If you are using a private fork, deploy with Wrangler instead. - -### Deploy with Wrangler - -1. Clone the repository and install dependencies. -2. Set `APP_ORIGIN` in `packages/api/wrangler.jsonc` to your final HTTPS Worker URL or custom domain. -3. Create a dedicated OAuth KV namespace with `npm exec --workspace=factorize -- wrangler kv namespace create OAUTH_KV`, then set its ID in `packages/api/wrangler.jsonc`. -4. Configure the Linear OAuth callback as `https://your-domain.example/auth/linear/callback`. -5. Bootstrap the additive API stage and verify its marker as described in [the rollout guide](docs/package-migration.md), then build assets, add secrets, and deploy: - -```bash -npm ci -npm run build:app +Start at [app.factorize.sh](https://app.factorize.sh). Sign up with email and password, verify email, and connect an execution account in **Settings → Integrations**. You supply execution, repository/model access and any provider accounts; Factorize hosts job configuration, triggers, queues and run history. -npm exec --workspace=factorize -- wrangler secret put LINEAR_CLIENT_ID -npm exec --workspace=factorize -- wrangler secret put LINEAR_CLIENT_SECRET -npm exec --workspace=factorize -- wrangler secret put LINEAR_WEBHOOK_SIGNING_SECRET -npm exec --workspace=factorize -- wrangler secret put CREDENTIAL_ENCRYPTION_KEY -npm exec --workspace=factorize -- wrangler secret put SESSION_SIGNING_SECRET - -npm run deploy:app -``` - -For a headless machine, authenticate first with `npx wrangler login --device --browser=false`, then open the displayed URL and approve the device code from your browser. - -## Quick start - -### Prerequisites - -- A Cloudflare account with Workers enabled. -- A Linear OAuth application with webhooks enabled. -- Optional: a ClickUp OAuth application for ClickUp task triggers. -- An exe.dev account. Fresh VMs include supported coding agents such as Codex and Claude. -- An exe.dev HTTPS API token allowed to run `ls`, `new`, `ssh`, and `rm`. - -### Develop locally - -```bash -npm install -cp packages/api/.dev.vars.example packages/api/.dev.vars -npm run dev -``` - -Set the Linear OAuth callback URL to: - -```text -http://localhost:8787/auth/linear/callback -``` - -Fill `.dev.vars` with the Linear OAuth credentials, webhook signing secret, and two independent application secrets. Generate the encryption key with: - -```bash -openssl rand -base64 32 -``` - -## Account authentication - -Factorize owns authentication in PostgreSQL. Create a native account at `/auth/signup` with an email address and a password of 12–200 characters. Emails are case-insensitive. Verify the email before signing in at `/auth/login`; email plus password are accepted. Linear is connected after sign-in from **Settings → Integrations**, only for Linear-backed jobs. - -Postmark sends one-hour, single-use verification and password-reset links. `/auth/verify/request` resends verification; `/auth/password-reset` handles recovery. Links never appear in application responses or logs. Passwords use salted PBKDF2-SHA-256. **Change password** in the account menu requires the current password. Password reset, password change and sign-out invalidate existing sessions via membership session versions, including delegated API credentials. - -Before deploying, configure `POSTMARK_SERVER_TOKEN` as a **production GitHub environment secret**. The deployment copies it to a Worker secret; the verified sender and transactional message stream are non-secret Worker vars in `packages/api/wrangler.jsonc`. For a manual Postmark preflight, set the following environment variables along with `APP_ORIGIN`: - -| Setting | Required value | -| --- | --- | -| `POSTMARK_SERVER_TOKEN` | Postmark **server** API token for the sending server; never an account token or a committed value | -| `POSTMARK_FROM_EMAIL` | Plain email address on a verified Postmark sender signature or verified domain | -| `POSTMARK_MESSAGE_STREAM` | Active **transactional** stream ID, commonly `outbound` | - -`APP_ORIGIN` must be the canonical HTTPS origin, without a trailing slash. Run `npm run auth:validate-email --workspace=factorize` manually when needed: it checks the server token/stream with Postmark and sends one preflight email from/to the configured sender, rejecting unverified senders or sending failures. It prints no credentials. Missing configuration fails the manual check. The deploy workflow does not run this check or send a preflight email. Runtime signup and recovery also fail closed if configuration or delivery fails; users can resend verification after a delivery failure. Local mail testing needs an HTTPS origin and a separate Postmark test server/sender; automated tests mock Postmark and never send mail. - -### Existing account migration - -Apply `0008_native_accounts.sql` and `0009_remove_auth_usernames.sql` before deploying this code. They reject ambiguous legacy emails that differ only in case (reconcile those identities before retrying migration), preserve tenant IDs, memberships, jobs and encrypted Linear connections, and backfill explicit Linear organization-to-workspace mappings. Existing Linear-only users choose **Forgot password or previously signed in with Linear?**, receive a reset email at their existing address, and set a password. Email possession is required; signup cannot replace an existing account's credentials. Existing native users keep their passwords and may sign in by email; unverified accounts must verify first. A reset never promotes a member to owner. An account with multiple existing owner memberships currently opens the oldest workspace; no new workspace-switching UI is introduced. - -Linear OAuth requires an authenticated owner, binds state to that user/workspace, stores the connection there, and never creates a Factorize session. A Linear organization already bound to another workspace cannot be claimed. Existing webhook routes resolve the explicit mapping. Do not delete that binding to work around an account-recovery problem. - -### Authentication verification - -`npm run check` runs unit/contract tests and Postmark preflight tests. CI also runs the real PostgreSQL authentication suite against a disposable service. To run it locally, set `AUTH_TEST_DATABASE_URL` to an isolated PostgreSQL server whose user can create/drop test databases, then run `npm test --workspace=factorize -- --run test/native-auth.postgres.test.ts`. The suite creates and removes its own database and applies every migration, including a legacy connection fixture before the auth migration. - -## Configure Linear - -Use authorization-code OAuth and enable **Webhooks** on the OAuth application. Configure: - -| Setting | Value | -| --- | --- | -| Callback URL | `https://your-domain.example/auth/linear/callback` | -| Webhook URL | `https://your-domain.example/webhooks/linear` | -| Webhook events | **Issues** and **Issue labels** | -| Webhook secret | Store as `LINEAR_WEBHOOK_SIGNING_SECRET` | - -After changing the webhook settings, re-authorize existing workspaces so Linear creates a fresh workspace subscription. - -## Configure ClickUp - -Create a ClickUp OAuth application with the callback URL `https://your-domain.example/auth/clickup/callback`, then store its client ID and secret in `CLICKUP_CLIENT_ID` and `CLICKUP_CLIENT_SECRET`. Connecting ClickUp from Settings registers the signed task webhook automatically. ClickUp triggers can filter a list by status, tag, assignee, or creator; all configured rules must match. - -## Create a Job - -1. Sign in with Linear. -2. Connect exe.dev using an account-level HTTPS API token and the VM tags needed to attach integrations. -3. Create a Job, choose its execution target, and add authenticated provider triggers. Every Linear matching rule must match. - -Matching provider events queue work up to the Job’s configured concurrency. Each run creates a tagged VM, clones the configured repository, runs the agent directly, captures its output, and deletes the VM on every terminal outcome. - -Cloudflare Worker failures can also start Jobs through the separately deployable Tail relay. See [Cloudflare Tail job trigger](docs/cloudflare-tail.md). - -## Configuration reference - -| Variable | Purpose | -| --- | --- | -| `LINEAR_CLIENT_ID` | Linear OAuth client ID | -| `LINEAR_CLIENT_SECRET` | Linear OAuth client secret | -| `LINEAR_WEBHOOK_SIGNING_SECRET` | Verifies Linear webhook signatures | -| `CLICKUP_CLIENT_ID` | ClickUp OAuth client ID | -| `CLICKUP_CLIENT_SECRET` | ClickUp OAuth client secret; ClickUp also uses a per-installation webhook secret stored encrypted by Factorize | -| `CREDENTIAL_ENCRYPTION_KEY` | Base64-encoded 32-byte key for encrypted credentials | -| `SESSION_SIGNING_SECRET` | Independent secret for signed browser sessions | -| `APP_ORIGIN` | Public Worker origin, configured in `packages/api/wrangler.jsonc` | -| `OAUTH_KV` | KV binding containing OAuth clients, grants, refresh tokens, and revocation state | - -Never commit `.dev.vars` or production secret values. The included `.dev.vars.example` is a safe template. - -## Development commands - -| Command | What it does | -| --- | --- | -| `npm run dev` | Build the static frontend and start HTTPS Vite + local API development | -| `npm run build:app` | Build static React/Tailwind assets in `packages/app/dist` | -| `npm test` | Run the unit test suite | -| `npm run check` | Check package boundaries/contracts, React/API tests, local routing and Worker dry runs | -| `npm run deploy:app` | Verify the API stage, build static assets and deploy the existing `factorize` Worker | -| `npm run deploy:tail-relay` | Deploy only the `factorize-tail-relay` Worker | -| `npm run deploy` | Deploy the app, then the Tail relay; stop on the first failure | - -GitHub Actions installs the single root lockfile and runs `npm run check` on every push and pull request. The two packages are independently deployable Cloudflare Workers; the root scripts only provide a unified developer workflow. - -## REST API and OAuth - -Read the complete, implementation-accurate API and MCP documentation at [docs.factorize.sh](https://docs.factorize.sh), including the checked-in [OpenAPI definition](packages/docs/openapi.yaml). - -API clients use OAuth 2.1 authorization code flow with PKCE S256 or the OAuth 2.0 Device Authorization Grant for headless environments. Factorize publishes authorization-server and protected-resource discovery metadata, supports Client ID Metadata Documents, and retains dynamic client registration at `/oauth/register` for older clients. Access tokens last one hour and may be refreshed for up to 30 days; RFC 7009 revocation is advertised by discovery metadata. - -Available scopes are `flows:read`, `flows:write`, `runs:read`, and `runs:write`. The resource owner must sign in through the native Factorize session and explicitly approve the requested scopes. Factorize rechecks owner membership and session version on every service call. - -The versioned API is rooted at `/api/v1`: - -```bash -curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ - https://app.factorize.sh/api/v1/jobs - -curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ - 'https://app.factorize.sh/api/v1/runs?jobId=JOB_ID&state=running&contextQuery=customer%20impact&limit=25' - -curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ - https://app.factorize.sh/api/v1/runs/RUN_ID - -curl -X POST -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ - https://app.factorize.sh/api/v1/runs/RUN_ID/stop -``` - -Connected GitHub App installation metadata, including the installation IDs used by GitHub Job triggers, is available without exposing credentials: - -```bash -curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" \ - https://app.factorize.sh/api/v1/github-installations -``` - -Job CRUD is available at `/jobs` and `/jobs/:id`; job metadata includes `currentRuns` and `maxConcurrency`. Run collections return `{ "items": [...], "nextCursor": "..." }`; pass `nextCursor` back as the `cursor` query parameter. Runs can be filtered by `jobId`, `state`, and `contextQuery`; context queries use case-insensitive literal substring matching and matching items contain a bounded `context_excerpt`, never the full context. `GET /runs/:runId` returns the rendered `prompt`, complete structured trigger `context`, and invocation metadata, including the firing `trigger_id`. The canonical Job prompt contract is documented in [docs/job-trigger-context.md](docs/job-trigger-context.md). Errors consistently use `{ "error": { "code": "...", "message": "..." } }`. - -Production diagnostics are authenticated and tenant-scoped. `GET /api/v1/runs/:runId/diagnostics` reports generic run lifecycle checks without returning credentials or internal command payloads. `POST /api/v1/integrations/exe/:connectionId/diagnostics` checks saved exe.dev permissions and creates then deletes a disposable tagged VM to verify the configured agent and managed model integration. - -The Wrangler-backed E2E suite loads the complete Worker and Durable Objects from `wrangler.jsonc`. Its exe.dev lifecycle tests disable external networking and use a stateful command-API stub to cover successful completion, masked shell-launch failures, run diagnostics, integration diagnostics, output capture, and VM cleanup without creating a real VM or calling an LLM. - -## MCP clients - -Configure a compatible remote MCP client with this single URL: +Connect a supported remote MCP client to: ```text https://app.factorize.sh/mcp ``` -The client discovers OAuth automatically, opens Factorize in a browser, completes native Factorize sign-in if necessary, requests consent, and returns to the client after PKCE authorization. No Linear or exe.dev credential is copied into the MCP client. The server is stateless Streamable HTTP and exposes Job CRUD, run inspection/filtering, provider webhook activity, and active-run stopping tools. +Follow [Connect your agent](https://docs.factorize.sh/mcp/overview) for Codex/Claude Code configuration and browser consent. Then ask: -Factorize also supports the OAuth 2.0 Device Authorization Grant (RFC 8628) for headless clients. Discovery advertises `device_authorization_endpoint`; clients obtain a code from `POST /oauth/device_authorization`, direct the user to `/device`, and poll `/oauth/token` with grant type `urn:ietf:params:oauth:grant-type:device_code`. Device codes expire after ten minutes, polling is rate-limited, and approved grants use the same scoped access and refresh tokens, tenant checks, and revocation behavior as browser PKCE authorization. +> Show me my available execution targets. Create a manual job called ‘Review recent changes’ using my repository’s target. Have it clone REPOSITORY_URL, review the latest commit and summarize any problems. Run it once and report the result. -## Security +The conversational agent calls `list_execution_targets`, checks existing jobs, creates a job, invokes it with a stable idempotency key, and reads `get_run` until completion. Current exe.dev targets select an account/agent, not a repository: put the repository URL in the prompt. Browser-only signup, integration credentials, resource selection and consent are separate from MCP job management. -- Linear and exe.dev credentials, issue prompts, and agent results are AES-GCM encrypted at rest in the Durable Object. -- Linear webhooks require a valid HMAC-SHA256 signature and fresh timestamp before workspace routing. -- Session cookies are signed, expire after seven days, and are checked against workspace membership. -- OAuth access is tenant-bound, scope-checked, revocable, and revalidates current owner membership at the shared service boundary. -- Public REST and MCP responses omit connection tokens, credential records, and internal execution requests/responses. Authorized run inspection includes the rendered prompt sent to the agent. -- Agent output is retained in Factorize run inspection and is not copied into Linear. -- The dashboard uses a restrictive content-security policy and locally built Tailwind CSS. +Read [Your first job](https://docs.factorize.sh/quickstart), [safe editing and configuration replacement](https://docs.factorize.sh/work/jobs), and [stop/retry behavior](https://docs.factorize.sh/work/stop-retry). Add [schedules](https://docs.factorize.sh/recipes/scheduled-review), [Linear](https://docs.factorize.sh/recipes/linear-job), [GitHub](https://docs.factorize.sh/integrations/github), [ClickUp](https://docs.factorize.sh/integrations/clickup), or [job chaining](https://docs.factorize.sh/recipes/chaining) after a successful manual run. -## License +MCP provides selected scoped operations, not every REST capability. REST contracts remain available in [OpenAPI](packages/docs/openapi.yaml) and [authentication reference](https://docs.factorize.sh/api/authentication). Credential management and trace replay require an interactive owner session. Agents can use the generated [llms.txt](packages/docs/llms.txt) and [llms-full.txt](packages/docs/llms-full.txt). -[Apache License 2.0](LICENSE) -Test line for the Factorize PR-check and merge-queue flow. +## Development and documentation -### Static application migration +Use Node 24, `npm ci`, `npm run dev`, and `npm run check`. The Worker lives in `packages/api`, React frontend in `packages/app`, and generated public contract in `packages/api-client`. Frontend calls documented `/api/v1` routes. Keep local secrets in ignored `packages/api/.dev.vars`. -The Worker lives in `packages/api`, the static React frontend in `packages/app`, and the OpenAPI-generated public client in `packages/api-client`. The frontend consumes only documented `/api/v1` operations. Same-origin routing preserves the existing Worker and state identities. See [the required API-first rollout and rollback procedure](docs/package-migration.md). +Run `npm run generate --workspace=factorize-docs` after guide edits and `npm run validate --workspace=factorize-docs` before publishing. See [docs publishing](docs/mintlify.md) and [package migration](docs/package-migration.md) for development and release gates. -| Command | Purpose | -| --- | --- | -| `npm run dev:api` | Run the local HTTPS API Worker | -| `npm run dev:app` | Run the static frontend development server | -| `npm run generate` | Generate OpenAPI and browser client types | -| `npm run build:app` | Build static frontend assets | -| `npm run check:boundaries` | Reject frontend/backend implementation imports | -| `npm run check` | Validate packages, generated client, tests and builds | +## Optional self-hosting -Use Node 24. Keep local secrets in `packages/api/.dev.vars`; the static frontend does not expose environment variables. +Hosted users do not deploy Factorize. To operate your own instance, follow [deployment](https://docs.factorize.sh/self-hosting/deployment), [configuration](https://docs.factorize.sh/self-hosting/configuration), and [operations](https://docs.factorize.sh/self-hosting/operations). These contain Cloudflare/Worker, Postmark, provider OAuth registration, webhook infrastructure and secret setup. -The static app includes native auth, consent/device, jobs/editor/provider, run/history/trace, integration and credential-management screens. Install Chromium with `npx playwright install --with-deps chromium` before checking. Local development uses HTTPS at `https://localhost:5173`; `npm run dev` creates an ignored local Vite certificate. See [the migration guide](docs/package-migration.md) for local database setup, production gates, asset retention and rollback. No production deployment is implied by this source migration. +[Apache License 2.0](LICENSE) diff --git a/docs/job-trigger-context.md b/docs/job-trigger-context.md index b01a58db..8dc63e19 100644 --- a/docs/job-trigger-context.md +++ b/docs/job-trigger-context.md @@ -15,15 +15,15 @@ The available value beneath a slug is: | Trigger | Fields | | --- | --- | | Manual | `prompt`, `data` | -| Schedule | `scheduled_at`, `cron`, `timezone` | +| Schedule | `occurredAt`, `externalId`, `metadata.timezone` | | Linear webhook | Complete Linear delivery, plus `provider`, `event`, `delivery_id` | | GitHub webhook | Complete GitHub delivery, plus `provider`, `event`, `delivery_id` | | Cloudflare Tail | Complete sanitized Tail delivery, plus `provider`, `event`, `delivery_id` | -| Job lifecycle | `source_job_id`, `source_run_id`, `final_state`, `transitioned_at`, `observation_destination` | +| Job lifecycle | Terminal: `sourceJobId`, `sourceRunId`, `state`, `completedAt`; edited: `source_job_id`, `event`, `edited_at` | -Every trigger returned by `GET /api/v1/jobs` and `GET /api/v1/jobs/:id` (and the corresponding MCP `list_jobs` and `get_job` tools) includes a `reflection` object. It contains the stable `slug`, trigger kind/provider, whether the result is dynamic, and a flat `paths` list with nested path, basic value type, description, and occasional example. The Job editor consumes this same canonical contract for Mustache autocomplete. Webhook conditions preserve normal provider context reflection. +Every trigger returned by `GET /api/v1/jobs` and `GET /api/v1/jobs/:id` (and the corresponding MCP `list_jobs` and `get_job` tools) includes a `reflection` object. It contains the stable `slug`, trigger kind/provider, whether the result is dynamic, and a flat `paths` list with nested path, basic value type, description, and occasional example. The Job editor consumes this contract for Mustache autocomplete. Current terminal lifecycle reflection still advertises older snake_case fields; the scheduler emits the camelCase fields above, so inspect persisted context when verifying templates. Webhook conditions preserve normal provider context reflection. -Manual invocation accepts an optional display `name`, `prompt`, JSON object `data`, and `idempotencyKey`. The display name is used as the run name, while prompt and data are exposed beneath the manual trigger slug. `idempotencyKey` is the client-facing value and must not include the reserved internal `manual:` prefix. Reusing the same value returns the original invocation. Run inspection exposes that reusable value as `invocation.idempotency_key`, while `invocation.claim_key` is the internal prefixed claim and must not be passed back to the invocation API. Parameter defaults and invocation, schedule, or webhook parameter overrides are not accepted. +Manual invocation accepts an optional display `name`, `prompt`, JSON object `data`, and `idempotencyKey`. The display name is used as the run name, while prompt and data are exposed beneath the manual trigger slug. `idempotencyKey` is the client-facing value and must not include the reserved internal `manual:` prefix. Reusing the same value returns the original invocation. Retain the submitted key. Current run inspection does not expose `invocation.idempotency_key`; `invocation.claim_key` is the internal prefixed claim and must not be passed back to the invocation API. Parameter defaults and invocation, schedule, or webhook parameter overrides are not accepted. Run inspection returns `context` as the complete persisted object and `invocation.trigger_id` as the trigger that fired. Parameter-era stored Jobs are migrated: old context and parameters are retained beneath `legacy_context` and `legacy_parameters` in the corresponding trigger context. They are not used as global template variables. diff --git a/packages/api/test/api-contract.test.ts b/packages/api/test/api-contract.test.ts index 839e28dd..9e0080b3 100644 --- a/packages/api/test/api-contract.test.ts +++ b/packages/api/test/api-contract.test.ts @@ -105,14 +105,15 @@ describe("versioned API contract", () => { } }); - it("configures Mintlify to render the exact committed artifact", () => { + it("keeps the exact committed REST artifact available in the Reference group", () => { const docs = JSON.parse( readFileSync(new URL("../../docs/docs.json", import.meta.url), "utf8"), ); - expect( - docs.navigation.tabs.find((tab: any) => tab.tab === "API Reference") - .openapi, - ).toBe("/openapi.yaml"); + const pages = docs.navigation.groups.find((group: any) => group.group === "Reference").pages; + expect(pages).toContain("api/reference"); + expect(pages.find((page: any) => page.openapi)?.openapi).toBe("/openapi.yaml"); + expect(readFileSync(new URL("../../docs/api/reference.mdx", import.meta.url), "utf8")).toContain("](/openapi.yaml)"); + const reference = readFileSync( new URL("../../docs/api/reference.mdx", import.meta.url), "utf8", diff --git a/packages/api/test/docs-workflows.test.ts b/packages/api/test/docs-workflows.test.ts new file mode 100644 index 00000000..0b57143d --- /dev/null +++ b/packages/api/test/docs-workflows.test.ts @@ -0,0 +1,79 @@ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; +import { jobInputSchema, manualInvocationSchema, triggerSchema } from "../src/flow-schemas"; +import { jobUpdateInput } from "../src/job-contracts"; +import { executionTargetResponse } from "../src/editor-contracts"; +import { ApiService } from "../src/flow-service"; +import { InvocationService, type Invocation, type Job, type JobRun } from "../src/job-domain"; +import { validateScheduleConfig, nextOccurrence } from "../src/schedule"; +import { evaluateWebhookConditions } from "../src/webhook-conditions"; + +const guide = (path: string) => readFileSync(new URL(`../../docs/${path}.mdx`, import.meta.url), "utf8"); +const examples = (path: string) => [...guide(path).matchAll(/```json\n([\s\S]*?)\n```/g)].map(match => JSON.parse(match[1]!)); + +describe("maintained hosted documentation examples", () => { + it("first-job discovery/create/invoke renders the actual prompt and deduplicates a lost response", async () => { + const [create, invocation] = examples("quickstart"); + const target = executionTargetResponse.parse({ id: "TARGET_ID", kind: "exe-vm", name: "Ephemeral exe.dev VMs", workspace: "ephemeral", cwd: "/home/exedev/workspace", agentKind: "codex", capabilities: ["stop"] }); + const input = jobInputSchema.parse(create); + expect(input.executionTargetId).toBe(target.id); + const service = new ApiService({} as any, {} as any); + const triggers = (service as any).normalizedTriggers(input.triggers); + expect(triggers[0].slug).toBe("trigger-1"); + const job: Job = { ...input, id: "JOB_ID", model: "", enabled: true, triggers, executionTarget: { connectionId: target.id, agentKind: target.agentKind, workspace: target.workspace, cwd: target.cwd }, createdAt: "now", updatedAt: "now" }; + const stored = new Map(); + const repository = { + getJob: async () => job, + findInvocation: async (_jobId: string, key: string) => stored.get(key) ?? null, + insertInvocationAndRun: async (value: Invocation, run: JobRun) => { stored.set(value.claimKey, { invocation: value, run }); return true; }, + countActiveRuns: async () => 0, + markRunRunning: async () => { throw new Error("not used"); }, + }; + const { jobId, ...request } = invocation; + const parsed = manualInvocationSchema.parse(request); + const invoker = new InvocationService(repository, async text => text); + const call = { source: "manual" as const, triggerId: triggers[0].id, claimKey: `manual:${parsed.idempotencyKey}`, context: { [triggers[0].slug]: { prompt: parsed.prompt, data: parsed.data ?? {} } } }; + const first = await invoker.invoke(jobId, call); + const retry = await invoker.invoke(jobId, call); + expect(first.run.encryptedPrompt).toContain("https://github.com/YOUR_ORG/YOUR_REPO.git"); + expect(first.run.encryptedPrompt).toContain("Review now"); + expect(retry.duplicate).toBe(true); + expect(retry.run.id).toBe(first.run.id); + expect(stored.size).toBe(1); + }); + + it("scheduled, Linear, GitHub, ClickUp and lifecycle recipe configurations satisfy current schemas", () => { + for (const path of ["recipes/scheduled-review", "recipes/linear-job", "recipes/chaining", "integrations/github", "integrations/clickup"]) { + for (const example of examples(path)) triggerSchema.parse(example); + } + const schedule = examples("recipes/scheduled-review")[0].config; + validateScheduleConfig(schedule); + expect(nextOccurrence(schedule, new Date("2026-10-09T09:01:00Z")).toISOString()).toBe("2026-10-12T09:00:00.000Z"); + }); + + it("reference create/replacement/invocation and conditions examples are actionable", async () => { + const blocks = examples("mcp/tools"); + const create = blocks.find(value => value.promptTemplate && !value.jobId && !value.id); + jobInputSchema.parse(create); + jobUpdateInput.extend({ jobId: jobInputSchema.shape.executionTargetId }).parse(blocks.find(value => value.expectedUpdatedAt)); + const invoke = blocks.find(value => value.idempotencyKey); + const { jobId, ...request } = invoke; + expect(jobId).toBe("JOB_ID"); + manualInvocationSchema.parse(request); + expect(manualInvocationSchema.safeParse({ idempotencyKey: "manual:internal" }).success).toBe(false); + const condition = blocks.find(value => value.conditions); + expect((await evaluateWebhookConditions(condition.conditions, condition.webhook)).decision).toBe("match"); + }); + + it("documented current limitations match implementation rather than stale tool descriptions", () => { + const service = readFileSync(new URL("../src/flow-service.ts", import.meta.url), "utf8"); + const scheduler = readFileSync(new URL("../src/postgres/automation-scheduler.ts", import.meta.url), "utf8"); + expect(service).toContain("killRun(runId: string) { return this.stopRun(runId); }"); + for (const key of ["sourceRunId", "sourceJobId", "completedAt", "occurredAt"]) { + expect(scheduler).toContain(key); + expect(guide("work/prompts")).toContain(key); + } + expect(guide("mcp/tools")).toContain("does not include `output`"); + expect(guide("work/stop-retry")).toContain("does not return `invocation.idempotency_key`"); + }); +}); diff --git a/packages/docs/README.md b/packages/docs/README.md index 6162b0c8..cb714b40 100644 --- a/packages/docs/README.md +++ b/packages/docs/README.md @@ -2,6 +2,6 @@ This is an independently previewable and publishable [Mintlify](https://mintlify.com) package. Install the Mintlify CLI, run `npm run dev --workspace=factorize-docs`, and open the local URL. Publish with `npm run deploy --workspace=factorize-docs` from a configured Mintlify project. See [the publishing runbook](../../docs/mintlify.md) for repository, custom-domain, DNS, and verification configuration. -The API Reference tab renders `openapi.yaml` directly. This is the generated API artifact consumed by the docs, clients, and CI. Update the executable catalog in `packages/api/src/api-contract.ts`, run `npm run generate:openapi` from the repository root, and commit the resulting YAML. Shared schemas and general metadata live beside the catalog. +The REST reference links to `openapi.yaml` directly. This is the generated API artifact consumed by the docs, clients, and CI. Update the executable catalog in `packages/api/src/api-contract.ts`, run `npm run generate:openapi` from the repository root, and commit the resulting YAML. Shared schemas and general metadata live beside the catalog. -Run `npm run validate --workspace=factorize-docs` to check artifact freshness, parsed method/path equality, Mintlify configuration, and LLM exports. CI also regenerates the artifact and rejects any diff. `llms.txt` and `llms-full.txt` provide documentation summaries and point to the generated contract for operation details. +Run `npm run validate --workspace=factorize-docs` to check artifact freshness, parsed method/path equality, Mintlify configuration, and LLM exports. CI also regenerates the artifact and rejects any diff. Run `npm run generate --workspace=factorize-docs` after editing guides/navigation. Both LLM exports are generated from every maintained navigation guide; validation rejects stale exports, missing/invented MCP tools, broken local links and onboarding drift. JSON examples in the first-job and recipes are parsed against implementation schemas by the API docs-workflows tests. diff --git a/packages/docs/api/authentication.mdx b/packages/docs/api/authentication.mdx index dbbfee67..0963a78a 100644 --- a/packages/docs/api/authentication.mdx +++ b/packages/docs/api/authentication.mdx @@ -7,7 +7,7 @@ Protected API and MCP requests use `Authorization: Bearer `. Browser user ## Browser accounts -Create a username/password account at `/auth/signup` and verify the email delivered by Postmark before signing in at `/auth/login`. Recovery is at `/auth/password-reset`; legacy Linear-only users use that flow to choose a username/password while retaining their workspace. Change your password from the account menu. Resetting/changing passwords or signing out invalidates existing sessions and delegated credentials. +Create an email/password account at `/auth/signup` and verify the email delivered by Postmark before signing in at `/auth/login`. Recovery is at `/auth/password-reset`; legacy Linear-only users use that flow to choose a password while retaining their workspace. Change your password from the account menu. Resetting/changing passwords or signing out invalidates existing sessions and delegated credentials. Linear OAuth is an integration connection available only after native sign-in. Workspace membership, not the connected Linear identity, controls authorization. diff --git a/packages/docs/api/discovery.mdx b/packages/docs/api/discovery.mdx index 00212c2e..0ffe530a 100644 --- a/packages/docs/api/discovery.mdx +++ b/packages/docs/api/discovery.mdx @@ -3,9 +3,9 @@ title: OAuth discovery description: Endpoints and metadata for OAuth-aware clients. --- -At the deployment origin, clients can retrieve: +At `https://app.factorize.sh`, clients can retrieve: * `/.well-known/oauth-authorization-server` — issuer, authorization, token, registration, revocation, and device endpoints plus supported grants/scopes. -* `/.well-known/oauth-protected-resource` — resource `APP_ORIGIN/mcp`, authorization server, header bearer authentication, and supported scopes. +* `/.well-known/oauth-protected-resource` — resource `https://app.factorize.sh/mcp`, authorization server, header bearer authentication, and supported scopes. -The authorization endpoint is `/authorize`, token endpoint `/oauth/token`, dynamic registration endpoint `/oauth/register`, and device endpoint `/oauth/device_authorization`. Client ID Metadata Documents are enabled. MCP clients should use `APP_ORIGIN/mcp`; they can discover OAuth automatically and complete browser PKCE consent. +The authorization endpoint is `/authorize`, token endpoint `/oauth/token`, dynamic registration endpoint `/oauth/register`, and device endpoint `/oauth/device_authorization`. Client ID Metadata Documents are enabled. MCP clients should use `https://app.factorize.sh/mcp`; they can discover OAuth automatically and complete browser PKCE consent. diff --git a/packages/docs/api/openapi.mdx b/packages/docs/api/openapi.mdx index 00a98e0a..db06b5e4 100644 --- a/packages/docs/api/openapi.mdx +++ b/packages/docs/api/openapi.mdx @@ -3,7 +3,7 @@ title: OpenAPI definition description: Download the verified Factorize REST contract. --- -[Download openapi.yaml](/openapi.yaml). The API Reference tab renders this exact file, and clients can use it to generate SDKs or inspect request and response schemas. +[Download openapi.yaml](/openapi.yaml). Clients can use this exact file to generate SDKs or inspect request and response schemas. The definition is generated from the executable route catalog in `packages/api/src/api-contract.ts`, which the Worker dispatches in `protected-api.ts`. To change an API operation, update its catalog entry (method, path, scope, validation, handler, and documentation), then run: diff --git a/packages/docs/api/reference.mdx b/packages/docs/api/reference.mdx index 20da9add..bf4d19df 100644 --- a/packages/docs/api/reference.mdx +++ b/packages/docs/api/reference.mdx @@ -3,7 +3,7 @@ title: REST API reference description: How to use the generated API reference. --- -The **API Reference** tab renders every application operation directly from [openapi.yaml](/openapi.yaml), including request validation, required scopes, owner-session restrictions, and JSON response schemas. This is the same generated artifact verified by CI and available to API clients. +The **REST operations** group under Reference renders every application operation directly from [openapi.yaml](/openapi.yaml), including request validation, required scopes, owner-session restrictions, and JSON response schemas. This is the same generated artifact verified by CI and available to API clients. All application endpoints use `/api/v1`. Authenticate with a scoped bearer token or an interactive owner session; credential management and trace replay require an interactive owner session. Errors use `{ "error": { "code": "...", "message": "..." } }`. diff --git a/packages/docs/concepts.mdx b/packages/docs/concepts.mdx index 5a274a42..545590e7 100644 --- a/packages/docs/concepts.mdx +++ b/packages/docs/concepts.mdx @@ -1,27 +1,18 @@ --- -title: Jobs, triggers, and runs -description: The durable execution model and prompt contract. +title: Jobs, triggers, runs, and targets +description: Understand the workflow before configuring automation. --- -A Job contains a prompt template, execution target, model/effort options, concurrency limit (1–50), and up to 50 triggers. Every job has a server-generated manual trigger. A Run is a queued or executing instance. Automatic webhook, schedule, and lifecycle signals coalesce; manual invocations never coalesce. Each job admits at most one queued run in addition to its active runs. When a run is already queued, new automatic occurrences are skipped and manual requests return `409 queue_full`. Retrying an accepted idempotency key still returns its original run. Queued runs retain their original prompt and context. Any backlog accepted before this policy was deployed drains normally. +A **job** is a saved instruction: what to do, where to execute it, and when it may run. A **trigger** is a reason to run it: a manual request, schedule, provider event, or another job's lifecycle event. A **run** is one execution of the job, with its own state, prompt, context and output. An **execution target** is a saved execution account/agent configuration discovered with `list_execution_targets`. -Templates are Mustache and render only against the firing trigger's stable slug, such as `{{trigger-1.issue.title}}`. Missing paths become empty strings. Run inspection returns the complete persisted `context`, rendered `prompt`, `invocation.trigger_id`, execution metadata, output, and activity. +The **conversational agent** you talk to uses MCP to control Factorize. The **execution agent** receives the job's rendered prompt and does the work on the execution account. Giving the conversational agent MCP permission does not give the execution agent repository, provider or model access. Your saved connection, VM tags and prompt must supply those. -Trigger kinds are `manual`, `schedule`, `webhook`, and `jobLifecycle`. Webhooks support Linear, ClickUp, GitHub, and Cloudflare Tail. Optional declarative JSON conditions filter the prepared webhook context without replacing it. See [trigger conditions](/integrations/triggers). +Every job gets a manual trigger. Additional triggers have immutable server-generated slugs such as `trigger-2`. Each run receives only the firing trigger's context; [prompt templates](/work/prompts) use that slug. -See the repository's [trigger context contract](https://github.com/GenerationSoftware/factorize/blob/main/docs/job-trigger-context.md) for the reflection paths exposed with every trigger. +## Concurrency and the queue -Prompt and run-name templates render plain text: double-brace substitutions preserve URLs, quotes, Markdown, and code without HTML entity escaping. Triple-brace substitutions remain supported. Literal entity text in job context is preserved, not decoded. The web UI escapes rendered values when displaying them. This applies to new runs; existing persisted prompts are unchanged. +With concurrency 1, a review already running occupies the only active slot. One more run may wait in the queue. A further manual request returns `queue_full`; wait for capacity instead of repeatedly changing retry keys. Automatic schedule/webhook/lifecycle signals arriving while a run is queued are skipped/coalesced, so they are not a complete event log. An accepted idempotency key still returns its original run even when the queue is full. +Concurrency can be 1–50. With concurrency 2, two reviews may execute and one may wait. Queued runs keep the prompt/context they were submitted with; editing a job does not rewrite those runs. Query runs and the provider for authoritative work when automatic events coalesce. -## Run traces and recovery - -Codex and Claude can show tool calls live from an execution stream; Pi uses its native session. The run page identifies the source and artifact state, and labels native fallback after rollback. A trace may be partial when collection fails. - -`GET /api/v1/runs/{runId}/diagnostics` reports the declared source and versions, actual projection source and artifact checksum, live generation and byte cursor, terminal reconciliation state, parse warnings, unknown-event rate, retained artifacts, and fallback use. `matched` verifies the projected live prefix against the terminal artifact. Missing reconciliation evidence does not establish completeness. - -An interactive tenant owner with `runs:write` can use `POST /api/v1/runs/{runId}/trace/replay` to reproject retained primary bytes or restore a retained native session. Supply a UUID `requestId` and `source` (`primary` or `native_session`). Preserve the request ID when retrying an interrupted operation. Replay is limited to 10 requests per tenant per minute. Results distinguish projected, already projected, skipped, and unrecoverable runs. Historical Codex tool calls can be recovered only if the native session artifact still exists. Replay preserves stored artifacts; expired or deleted bytes cannot be recovered. - -See the [trace rollout and debugging runbook](https://github.com/GenerationSoftware/factorize/blob/main/docs/trace-rollout-runbook.md) for canary gates, retention, resumption, and rollback. - -Object and array substitutions insert compact JSON, including nested values: `{{trigger-1}}` inserts the complete trigger context and `{{trigger-1.data}}` inserts the complete manual data object. Object keys are sorted recursively (integer keys follow JSON's numeric ordering); array order is preserved. Nested nulls render as JSON `null`; a directly interpolated null or missing value remains empty, as in Mustache. Primitive values remain raw text. Sections still use the original context for truthiness, object scopes, and array iteration. +Inspect output before treating a terminal state as a useful result. Trace collection can be incomplete even when execution completed; advanced trace recovery belongs in [operations](/self-hosting/operations). diff --git a/packages/docs/docs.json b/packages/docs/docs.json index b5358bfd..c8eae4f3 100644 --- a/packages/docs/docs.json +++ b/packages/docs/docs.json @@ -7,52 +7,72 @@ "light": "#fff8e1", "dark": "#17130a" }, - "favicon": "/favicon.ico", + "favicon": "/logo-light.svg", "logo": { "light": "/logo-light.svg", "dark": "/logo-dark.svg" }, "navigation": { - "tabs": [ + "groups": [ { - "tab": "Guides", - "groups": [ - { - "group": "Start", - "pages": [ - "index", - "quickstart", - "concepts" - ] - }, - { - "group": "REST API", - "pages": [ - "api/authentication", - "api/discovery", - "api/openapi", - "api/reference" - ] - }, - { - "group": "MCP", - "pages": [ - "mcp/overview", - "mcp/tools" - ] - }, + "group": "Get started", + "pages": [ + "index", + "mcp/overview", + "quickstart" + ] + }, + { + "group": "Work with your agent", + "pages": [ + "work/jobs", + "work/prompts", + "work/results", + "work/stop-retry" + ] + }, + { + "group": "Automate jobs", + "pages": [ + "recipes/scheduled-review", + "recipes/linear-job", + "integrations/github", + "integrations/clickup", + "recipes/chaining", + "integrations/oauth", + "integrations/triggers" + ] + }, + { + "group": "Troubleshooting", + "pages": [ + "troubleshooting/connection", + "troubleshooting/events", + "troubleshooting/runs" + ] + }, + { + "group": "Reference", + "pages": [ + "mcp/tools", + "concepts", + "api/reference", + "api/authentication", + "api/discovery", + "api/openapi", { - "group": "Integrations", - "pages": [ - "integrations/triggers", - "integrations/oauth" - ] + "group": "REST operations", + "openapi": "/openapi.yaml" } ] }, { - "tab": "API Reference", - "openapi": "/openapi.yaml" + "group": "Self-hosting", + "pages": [ + "self-hosting/deployment", + "self-hosting/configuration", + "self-hosting/operations" + ] } ] } diff --git a/packages/docs/index.mdx b/packages/docs/index.mdx index 2fdfdcc3..e9668da5 100644 --- a/packages/docs/index.mdx +++ b/packages/docs/index.mdx @@ -1,13 +1,15 @@ --- -title: Factorize documentation -description: Automate coding-agent jobs from Linear, GitHub, ClickUp, schedules, and MCP. +title: Factorize with your agent +description: Connect your agent, create a job, run it, inspect the result, and automate it. --- -Factorize turns authenticated provider events into jobs on your own exe.dev VM. Jobs have explicit triggers, concurrency limits, durable run history, and a scoped REST/MCP API. +Factorize hosts your job configuration, trigger routing, queue, run history, and MCP endpoint. Your conversational agent controls Factorize through MCP; the execution agent runs each job using an execution account you connect. + +Start at [app.factorize.sh](https://app.factorize.sh). Connect your agent to `https://app.factorize.sh/mcp`, create a manual job, inspect its result, then add a schedule or provider trigger. - Create and invoke your first job - Every public REST operation + Authorize a remote MCP client + Review a repository and inspect the result -The public documentation origin is `https://docs.factorize.sh`; replace `https://app.factorize.sh` in examples with your deployment origin when self-hosting. +You supply an execution account (exe.dev or Amp), repository access, model access, and any Linear, GitHub or ClickUp accounts needed by the job. Factorize hosts the application; it does not grant your execution agent access to those accounts. Add execution integrations in the browser before asking your agent to create a job. [Self-hosting](/self-hosting/deployment) is optional. diff --git a/packages/docs/integrations/clickup.mdx b/packages/docs/integrations/clickup.mdx new file mode 100644 index 00000000..317cd56e --- /dev/null +++ b/packages/docs/integrations/clickup.mdx @@ -0,0 +1,16 @@ +--- +title: Automate from ClickUp +description: Connect a workspace and select matching tasks. +--- + +[Connect ClickUp](/integrations/oauth) in Settings and approve access to the intended team/list. Factorize registers the task webhook on connection. Use the browser job editor to select a list and rule target IDs; MCP does not discover ClickUp lists/statuses. + +Add this trigger to the complete job configuration: + +```json +{"kind":"webhook","config":{"provider":"clickup","listId":"LIST_ID","matchRules":[{"type":"status","targetId":"STATUS_ID"}]}} +``` + +Replace IDs with browser-selected values. All configured rules must match. Read the returned stable slug/reflection before using `{{trigger-2.task}}` in the prompt. Ensure the execution agent separately has any ClickUp access required to work on the task. + +Change one test task to the selected status. Verify delivery with `list_webhook_deliveries({"provider":"clickup"})`, inspect its timeline, job activity and resulting run. Reconnect in Settings if provider authorization expires; use [event troubleshooting](/troubleshooting/events) for rejected or absent deliveries. diff --git a/packages/docs/integrations/github.mdx b/packages/docs/integrations/github.mdx new file mode 100644 index 00000000..b4208410 --- /dev/null +++ b/packages/docs/integrations/github.mdx @@ -0,0 +1,16 @@ +--- +title: Automate from GitHub +description: Select an installation, repository, and event. +--- + +[Connect the Factorize GitHub App](/integrations/oauth) in the browser and approve the selected repositories. Ask `list_github_installations({})` for safe installation IDs. Select the repository in the browser job editor to obtain its numeric repository ID; MCP does not provide a repository picker. + +Append this trigger to a successful manual job, preserving the complete configuration: + +```json +{"kind":"webhook","config":{"provider":"github","installationId":12345,"repositoryId":67890,"event":"pull_request","action":"opened"}} +``` + +Replace illustrative IDs with the selected installation/repository IDs. GitHub requires either non-empty issue match rules or both event and action. Read the saved trigger's slug/reflection before using fields such as `{{trigger-2.pull_request.number}}`. Give the execution agent its own repository access. + +Open one test PR on the selected repository. Verify delivery timeline, job activity and run context, then output in the browser trace. Missing events often mean wrong repository selection, a suspended installation or event/action mismatch. Use [event troubleshooting](/troubleshooting/events). Delayed conflict workflows also verify live PR state; conditions previews do not perform that verification. diff --git a/packages/docs/integrations/oauth.mdx b/packages/docs/integrations/oauth.mdx index 697e5e4c..fb61dfb3 100644 --- a/packages/docs/integrations/oauth.mdx +++ b/packages/docs/integrations/oauth.mdx @@ -1,8 +1,20 @@ --- -title: Provider OAuth and boundaries -description: Configure Linear and optional ClickUp connections. +title: Connect your accounts +description: Browser setup, resource access, and delivery verification. --- -Factorize accounts own dashboard identity. Sign up with a username, email and password, verify your email, then connect Linear from Settings → Integrations when using Linear-backed jobs. Linear OAuth only connects the workspace; it never signs you in. Register `/auth/linear/callback`, configure issue and issue-label webhooks at `/webhooks/linear`, and store the client credentials and signing secret as Worker secrets. ClickUp is optional: register `/auth/clickup/callback`; connecting it automatically registers its task webhook. GitHub uses an installed GitHub App, while exe.dev and Cloudflare Tail connections are configured in Settings. +Sign up with email/password, verify email, then open [Settings → Integrations](https://app.factorize.sh/settings). Linear OAuth connects a workspace; it does not sign you in to Factorize. -Provider credentials are encrypted at rest in the tenant Durable Object. Public REST/MCP APIs expose only safe metadata. Owner membership and session version are enforced at the shared service boundary. +| Account | Browser action and required access | Verification | +| --- | --- | --- | +| exe.dev | Add an account-level token, test credentials, choose Codex/Claude/Pi and VM tags, save. Needs VM listing/creation/SSH/deletion and tagged repository/model integrations. | Test connection, then `list_execution_targets`; optionally diagnose the saved connection. | +| Amp | Add access token and project; ensure project/model/repository access. | Test and save, then discover the `amp:` target. | +| Linear | Connect Linear and approve the workspace. Your account must access the selected project and issues; organization policies may require an administrator. | Select project/rules in the browser editor, send one matching event, inspect delivery/run. | +| ClickUp | Connect ClickUp and approve the intended workspace/team with access to the list/tasks. | Select list/rules, change one matching task and inspect delivery/run. | +| GitHub | Connect GitHub to install/authorize the Factorize App on the intended account/repositories; organization approval may be required. | Confirm active installation and repository selection, then send a matching event. | + +The provider consent/installation screen is the authority for granted permissions. Grant access to the selected resources; changing those resources can require provider reauthorization. Job-trigger access and execution-agent access are separate: installing the Factorize GitHub App does not supply git credentials to an exe.dev VM. + +MCP exposes safe connection/installation/target metadata, not tokens. Account connections, resource pickers and credential management require browser setup. Reconnect Linear/ClickUp from Settings; use GitHub's Configure installation link for repository access and verify the installation is active. Do not disconnect integrations while jobs still reference them; update those jobs first. + +After changing access, create one controlled event and use `list_webhook_deliveries`, `get_webhook_delivery`, `list_job_webhook_activity`, and `list_runs` to verify delivery and execution. See [jobs not firing](/troubleshooting/events). Hosted Factorize manages OAuth application registration, callbacks and webhook infrastructure. Operators of their own deployment use [configuration](/self-hosting/configuration). diff --git a/packages/docs/integrations/triggers.mdx b/packages/docs/integrations/triggers.mdx index 48a1c9d3..6392dcd3 100644 --- a/packages/docs/integrations/triggers.mdx +++ b/packages/docs/integrations/triggers.mdx @@ -7,7 +7,7 @@ Schedule config is `{cron, timezone}`. Webhook config supports `linear` (`projec Lifecycle config is `{sourceJobIds, states}`, where states are `succeeded`, `failed`, `stopped`, or `edited`. Triggers have stable server-generated slugs (`trigger-1`, `trigger-2`, …); use them in Mustache templates. Disabled triggers do not fire. -Linear webhooks require a fresh HMAC timestamp/signature and configured OAuth subscription. ClickUp uses its OAuth connection and signed webhook. GitHub uses the connected App installation. Cloudflare Tail sends sanitized, signed delivery data to the generated destination. +For hosted jobs, connect the provider in [Settings](/integrations/oauth), select accessible resources in the browser editor, and verify a matching event with delivery tools. Factorize verifies provider signatures and manages OAuth subscriptions. Optional Cloudflare Tail triggers require your own source/relay integration; infrastructure setup belongs in [operations](/self-hosting/operations). Choose **Job lifecycle → Edited** and one or more source jobs to run a job when another job is saved (including enable/disable saves). Creation and run status changes do not produce edit events. Each successful save is an event, even if the submitted values are unchanged. Only enabled subscribers in the same tenant are matched; a job cannot subscribe to its own edits. diff --git a/packages/docs/llms-full.txt b/packages/docs/llms-full.txt index 74ad93c2..ee6bf20b 100644 --- a/packages/docs/llms-full.txt +++ b/packages/docs/llms-full.txt @@ -1,24 +1,727 @@ -# Factorize full documentation +# Factorize -Factorize creates durable coding-agent Jobs on a user's exe.dev VM. A Job has a prompt template, execution target, concurrency limit, and stable-slugged manual, schedule, webhook, or lifecycle triggers. Runs are queued, scoped to a tenant, and inspectable through REST or MCP. +Hosted workflow: connect your agent → create a job → run it → inspect the result → automate it. -## Authentication +Application: https://app.factorize.sh +MCP (Streamable HTTP + OAuth): https://app.factorize.sh/mcp -Use OAuth 2.1 authorization code with PKCE S256 or RFC 8628 device authorization. Scopes are flows:read, flows:write, runs:read, and runs:write. Access tokens last one hour; refresh tokens last up to 30 days. Owner membership, session version, tenant binding, and revocation are checked on service calls. +Browser: email/password signup, verification, execution/provider connections and consent. +MCP: discover targets, manage jobs, invoke with retained idempotency keys, inspect state/context/diagnostics. +Current MCP does not return execution output; inspect browser traces or REST trace pages. REST is not full MCP parity. -## REST +Generated from maintained guides in navigation order. Do not edit this file directly. -The API is rooted at `/api/v1`. The verified operation inventory, request validation, scopes, and response schemas are in [openapi.yaml](/openapi.yaml). Mintlify renders the API Reference directly from this generated contract. CI rejects stale artifacts or any method/path mismatch with the executable Worker route catalog. +## Factorize with your agent +Source: https://docs.factorize.sh/ -## MCP +Factorize hosts your job configuration, trigger routing, queue, run history, and MCP endpoint. Your conversational agent controls Factorize through MCP; the execution agent runs each job using an execution account you connect. -Connect to `APP_ORIGIN/mcp` using Streamable HTTP. Tools mirror the REST surface: connection/target discovery, job CRUD and enablement, manual invocation, run inspection/filtering/stopping, webhook activity, and prepared webhook conditions testing. Tool output is structured JSON plus text; secrets are omitted. +Start at [app.factorize.sh](https://app.factorize.sh). Connect your agent to `https://app.factorize.sh/mcp`, create a manual job, inspect its result, then add a schedule or provider trigger. -## Triggers -Webhooks support Linear, ClickUp, GitHub, and Cloudflare Tail. Schedule config is `{cron,timezone}`. Lifecycle config is `{sourceJobIds,states}` with succeeded, failed, or stopped. Templates address the firing trigger by slug, for example `{{trigger-1.issue.title}}`. Manual idempotency keys are client values and must not begin with `manual:`. + [Connect your agent](https://docs.factorize.sh/mcp/overview): Authorize a remote MCP client + [First job](https://docs.factorize.sh/quickstart): Review a repository and inspect the result -## Trace provenance and recovery +You supply an execution account (exe.dev or Amp), repository access, model access, and any Linear, GitHub or ClickUp accounts needed by the job. Factorize hosts the application; it does not grant your execution agent access to those accounts. Add execution integrations in the browser before asking your agent to create a job. [Self-hosting](https://docs.factorize.sh/self-hosting/deployment) is optional. -Codex and Claude use execution-stream primary sources when admitted by rollout gates; Pi uses its version-pinned native session. Run diagnostics expose source/CLI/harness versions, retained artifact receipts, projection checksum/parser version, live generation/offset, reconciliation, warning and unknown counts, and native fallback use. See the trace replay operation in [openapi.yaml](/openapi.yaml) for owner-session requirements, request validation, replay restrictions, rate limits, and documented outcomes. Neither replay nor rollback deletes artifacts. +## Connect your agent +Source: https://docs.factorize.sh/mcp/overview + +Use the remote **Streamable HTTP** endpoint: + +```text +https://app.factorize.sh/mcp +``` + +Complete [browser account and execution setup](https://docs.factorize.sh/quickstart) first. Factorize requires OAuth authorization, owner membership and tenant-bound scopes. A JSON configuration from one client is not a universal MCP configuration. + +## Codex + +Current Codex supports Streamable HTTP and OAuth. Add this client-specific TOML to `~/.codex/config.toml`: + +```toml +[mcp_servers.factorize] +url = "https://app.factorize.sh/mcp" +``` + +Run `codex mcp login factorize`, then use `/mcp` in Codex to verify the connection. See the [official Codex MCP documentation](https://developers.openai.com/codex/mcp) for configuration and OAuth support. + +## Claude Code + +Add the remote server: + +```bash +claude mcp add --transport http factorize https://app.factorize.sh/mcp +``` + +Start Claude Code, enter `/mcp`, choose Factorize and authenticate when prompted. See the [official Claude Code MCP documentation](https://code.claude.com/docs/en/mcp) for HTTP transport, OAuth and configuration scope. + +## Authorize in the browser + +The client opens Factorize authorization in your browser. Sign in with your verified Factorize email/password and approve the requested scopes. For the full workflow, grant `flows:read`, `flows:write`, `runs:read`, and `runs:write`. Read-only access cannot create or invoke jobs. Return to your client after consent. + +If you need to create an account or verify your email, finish those steps and restart client authorization; do not assume the signup screen will automatically resume the original request. No Linear or execution token belongs in the MCP client. + +Ask **“List my Factorize jobs.”** The agent should call `list_jobs({})`. An empty `items` list is a successful connection to a workspace with no jobs. Next ask it to list execution targets and follow the [first-job walkthrough](https://docs.factorize.sh/quickstart). + +Other clients must support remote Streamable HTTP and Factorize's OAuth discovery/PKCE flow. Their UI and plan availability vary; consult their own documentation rather than pasting either configuration above. + +## Connection problems + +For rejected consent, expired authorization, missing targets, scope errors and reconnection steps, see [connection troubleshooting](https://docs.factorize.sh/troubleshooting/connection). Protocol implementers should use [authentication](https://docs.factorize.sh/api/authentication) and [discovery](https://docs.factorize.sh/api/discovery). + +## Your first job +Source: https://docs.factorize.sh/quickstart + +## Set up in the browser + +1. Open [app.factorize.sh/auth/signup](https://app.factorize.sh/auth/signup). Sign up with **email and password** (12–200 characters), verify the email, then sign in. Use [resend verification](https://app.factorize.sh/auth/verify/request) if needed. +2. Open [Settings → Integrations](https://app.factorize.sh/settings). Add an exe.dev account token, test credentials, select the execution agent and VM tags, then save. Saving validates the agent/models on a temporary VM. Alternatively connect an Amp project and its access token. +3. Ensure the execution account can access your repository and the required model/integrations. For exe.dev, the account token must permit VM listing, creation, SSH and deletion (`ls`, `new`, `ssh`, `rm`). VM tags attach your execution integrations. Current exe.dev targets do **not** store a repository URL or checkout ref: put the repository URL and checkout instructions in the job prompt. +4. [Connect your MCP client](https://docs.factorize.sh/mcp/overview), approve the four workflow scopes, and ask “List my Factorize jobs.” + +These account, credential and consent steps happen in the browser. MCP can discover saved targets, manage jobs and invoke/inspect runs; it cannot sign you up, verify email, connect execution credentials or select provider resources. + +## Ask your agent + +Copy this request and replace the repository URL: + +> Show me my available execution targets. Create a manual job called ‘Review recent changes’ using my repository’s target. Have it clone https://github.com/YOUR_ORG/YOUR_REPO.git, review the latest commit and summarize any problems. Run it once and report the result. + +If several targets are available, choose one by its agent/account metadata. Target discovery does not imply a repository binding. + +Expected tools: + +1. `list_execution_targets({})`: choose a returned `id`; never invent one. Empty results mean browser execution setup is incomplete. +2. `list_jobs({})`: check whether this job already exists before creating it. +3. `create_job` with the input below. Save its returned `id` as `JOB_ID`. +4. `invoke_job` with `JOB_ID` and a stable key. Save `runId`. +5. `get_run({runId: RUN_ID})`: check periodically until terminal; inspect prompt, context and activity. Current MCP does not expose execution output: open the returned run in the browser trace view to read the review, or use authorized REST trace pagination. The agent should report the observed state and result link rather than invent findings. + +```json +{ + "name": "Review recent changes", + "slug": "review-recent-changes", + "executionTargetId": "TARGET_ID", + "promptTemplate": "Clone https://github.com/YOUR_ORG/YOUR_REPO.git into the workspace. Review the latest commit on the default branch, run relevant checks, and summarize any problems. {{trigger-1.prompt}}", + "concurrencyLimit": 1, + "triggers": [{"kind": "manual", "config": {}}] +} +``` + +Invoke input: + +```json +{"jobId":"JOB_ID","prompt":"Review now","idempotencyKey":"review-recent-changes-first-run"} +``` + +Example invocation result (identifiers are illustrative): + +```json +{"invocationId":"INVOCATION_ID","runId":"RUN_ID","state":"queued","duplicate":false} +``` + +Success means target discovery returned a usable target, the created job returned an `id` and manual trigger with a stable slug, invocation returned `runId`, and `get_run` reports `succeeded` with the rendered repository prompt. Open its browser trace and confirm the review output; state alone does not prove the review findings. Submission alone is not completion. You can also open `https://app.factorize.sh/job-runs/RUN_ID` to inspect it. + +If the request times out, repeat **the invocation with the same key**, not job creation; it returns the original run with `duplicate: true`. A failed run is still the original run for that key. Follow [failed-run troubleshooting](https://docs.factorize.sh/troubleshooting/runs) before requesting a new run with a new key. After a successful manual review, add a [schedule](https://docs.factorize.sh/recipes/scheduled-review). + +## Create and edit jobs +Source: https://docs.factorize.sh/work/jobs + +Ask: “List execution targets and jobs, then create a review job for this repository.” Use [the first-job input](https://docs.factorize.sh/quickstart) and [MCP tool contract](https://docs.factorize.sh/mcp/tools). Reuse an existing job when its slug/purpose matches; job creation has no idempotency key. + +`update_job` **replaces configuration**, rather than patching one field. Always call `get_job` first. Build a write object containing `jobId`, `name`, `slug`, `promptTemplate`, `executionTargetId`, `runNameTemplate`, `concurrencyLimit`, `model`, optional `effort`, and the full intended `triggers` array. Preserve each existing trigger's `id`, `slug`, `kind`, `enabled`, and writable `config`. Strip read-only response fields (`jobId` inside triggers, timestamps, reflection, secretConfigured and destination). Do not pass the entire read response unchanged. + +Supply `expectedUpdatedAt` from the fetched job's `updatedAt` to protect against concurrent edits. On `stale_job`, fetch again and reapply the desired changes. Omitting it retains last-writer-wins behavior. Omitted optional configuration resets to defaults; omitted triggers remove the configured automatic triggers. Preserve all triggers you want to keep. + +After saving, call `get_job` and compare prompt, target and triggers. `enable_job` and `disable_job` change enabled state without rebuilding configuration. Disabling automation does not stop an existing run. Job saves can trigger `edited` lifecycle subscribers. Deleting a job removes its execution history/artifacts; inspect and retain anything needed first. + +## Write job prompts +Source: https://docs.factorize.sh/work/prompts + +Write the repository URL, checkout branch/ref, task, validation and reporting requirements explicitly. Execution targets select an account/agent, not a repository. Example: + +```text +Clone https://github.com/YOUR_ORG/YOUR_REPO.git. Review the latest commit, +run relevant tests, and report problems with file paths and evidence. +Additional request: {{trigger-1.prompt}} +Manual data: {{trigger-1.data}} +``` + +Use `get_job` to discover each trigger's stable `slug` and `reflection.paths`. Never assume an automatic trigger is `trigger-1`. Mustache renders only the firing trigger's context: manual has `prompt` and `data`; schedule currently has `occurredAt`, `externalId` and `metadata.timezone`; provider context contains prepared delivery fields (Linear `issue`, ClickUp `task`); terminal lifecycle currently has `sourceJobId`, `sourceRunId`, `state`, `completedAt`; edited has `source_job_id`, `event`, `edited_at`. Current reflection still describes older snake_case terminal fields: use the persisted run context as the authority. + +Missing/null scalar paths become empty text. Objects and arrays interpolate as compact JSON; array order is preserved and object keys sorted. Double braces preserve plain-text URLs, quotes, Markdown and code; triple braces are also supported. Sections use original context truthiness and array iteration. There are no global parameter defaults/overrides. + +After creating an automatic trigger, read its returned slug, then safely replace the full configuration to reference that slug. For example `{{trigger-2.issue.title}}` only works if that is the actual Linear trigger. Verify the rendered `prompt` and complete `context` with `get_run`. See the [full context contract](https://github.com/GenerationSoftware/factorize/blob/main/docs/job-trigger-context.md). + +## Inspect results +Source: https://docs.factorize.sh/work/results + +Ask: “Show the latest runs for this job and summarize the completed review.” Use `list_runs({"jobId":"JOB_ID","limit":10})`, then `get_run({"runId":"RUN_ID"})`. Current MCP does not return an `output` field or trace messages. Open the browser run page to read the trace, or retrieve REST trace pages with an authorized client. Report the state/link through MCP and only summarize findings after actually reading them. + +Run pages return `items` and `nextCursor`; send that cursor for the next page. Optional `state` and `contextQuery` filter runs. Context search is a case-insensitive substring, not a query language. Current list rows contain no context excerpt; `get_run` returns full `context`, rendered `prompt`, `invocation.trigger_id`, execution metadata and activity. + +Check that the intended trigger fired, the repository/task appears in the rendered prompt, and the browser/REST trace supports the reported result. A queued submission is not a successful execution. Browser run pages are at `https://app.factorize.sh/job-runs/RUN_ID`. Agent output stays in Factorize and is not automatically copied into Linear. + +For missing output or execution failures, call `get_run_diagnostics` and follow [failed-run troubleshooting](https://docs.factorize.sh/troubleshooting/runs). + +## Stop and retry runs +Source: https://docs.factorize.sh/work/stop-retry + +Ask: “Inspect this run, stop it if it is still active, and verify its final state.” Fetch `get_run`, then use `stop_run({"runId":"RUN_ID"})` for a starting, running or blocked run. The response requests `stopping`; poll until terminal and inspect diagnostics for cleanup. + +**Current behavior:** `kill_run` calls the same stop operation as `stop_run`. It does not force a queued run to terminate or release its slot immediately. Both return `operation_failed` when the run is not active. Do not treat kill as stronger recovery; contact the hosted operator if a run remains stuck. + +For a timed-out manual submission, repeat `invoke_job` with the **same** `idempotencyKey`. The response contains the original `invocationId`, `runId`, and `duplicate: true`. Retain the key you submitted: current `get_run` does not return `invocation.idempotency_key`. Never send its internal `invocation.claim_key` or a `manual:` prefix back as the key. If the key was lost, inspect existing runs before requesting another. + +An intentional new run after failure needs a new key. First verify that the prior run is terminal, inspect whether it made external changes, and fix the cause. A retry may repeat those external effects: invocation deduplication is not transactional rollback of the agent's work. For `queue_full`, wait for capacity and reuse the key for the intended request. See [failed runs](https://docs.factorize.sh/troubleshooting/runs). + +## Schedule a repository review +Source: https://docs.factorize.sh/recipes/scheduled-review + +User request: + +> Review the latest commit in https://github.com/YOUR_ORG/YOUR_REPO.git every weekday at 09:00 UTC. Keep a manual trigger and report findings in Factorize. + +First complete a [manual run](https://docs.factorize.sh/quickstart). Fetch the job, preserve its writable configuration and manual trigger identity, and append: + +```json +{"kind":"schedule","enabled":true,"config":{"cron":"0 9 * * 1-5","timezone":"UTC"}} +``` + +Save with `update_job` and `expectedUpdatedAt`. Fetch again to discover the schedule's stable slug. Use a repository review prompt that works without manual context; optionally add `Scheduled at {{trigger-2.occurredAt}}` using the actual slug. Preserve the entire trigger list when saving this prompt. + +Expected result: an enabled weekday schedule and one queued/executing run at the next matching occurrence (subject to queue coalescing). Verify cron/timezone and next occurrence in the browser editor, then `list_runs({"jobId":"JOB_ID"})` and `get_run`: the invocation's trigger ID and context must match the schedule, and the browser trace output must contain the review. Do not claim automation verified until a scheduled occurrence has actually run. + +## Run a job from Linear +Source: https://docs.factorize.sh/recipes/linear-job + +User request: + +> When an issue in my selected Linear project moves to my selected Ready status, run the repository agent to investigate it and report the result. + +In browser [Settings → Integrations](https://app.factorize.sh/settings), connect Linear, approve workspace access, and select an accessible project/status in the job editor. The execution account separately needs repository and Linear access if the prompt asks it to read/update Linear. MCP does not list Linear projects/statuses or connect accounts; use browser resource selection to obtain the IDs. + +Create a job with the required [job fields](https://docs.factorize.sh/mcp/tools), repository instructions, and this trigger (replace both IDs): + +```json +{"kind":"webhook","enabled":true,"config":{"provider":"linear","projectId":"PROJECT_ID","matchRules":[{"type":"status","targetId":"STATUS_ID"}]}} +``` + +Factorize adds the manual trigger. Fetch the saved job to obtain the webhook slug/reflection. Safely replace configuration with a prompt such as `Clone REPOSITORY_URL. Investigate this Linear issue: {{trigger-2.issue.title}}. Issue context: {{trigger-2}}. Run relevant checks and report evidence.` Use the actual webhook slug, preserving all other configuration. + +Expected result: a matching issue change delivers an event and starts a run; all configured rules must match. Move one test issue into the selected status. Verify `list_webhook_deliveries({"provider":"linear","jobId":"JOB_ID"})`, inspect the delivery timeline and `list_job_webhook_activity`, then check the run's firing trigger, issue context, then inspect output in the browser trace. Factorize does not automatically post execution output to Linear. For absent/rejected events follow [jobs not firing](https://docs.factorize.sh/troubleshooting/events). + +## Automate from GitHub +Source: https://docs.factorize.sh/integrations/github + +[Connect the Factorize GitHub App](https://docs.factorize.sh/integrations/oauth) in the browser and approve the selected repositories. Ask `list_github_installations({})` for safe installation IDs. Select the repository in the browser job editor to obtain its numeric repository ID; MCP does not provide a repository picker. + +Append this trigger to a successful manual job, preserving the complete configuration: + +```json +{"kind":"webhook","config":{"provider":"github","installationId":12345,"repositoryId":67890,"event":"pull_request","action":"opened"}} +``` + +Replace illustrative IDs with the selected installation/repository IDs. GitHub requires either non-empty issue match rules or both event and action. Read the saved trigger's slug/reflection before using fields such as `{{trigger-2.pull_request.number}}`. Give the execution agent its own repository access. + +Open one test PR on the selected repository. Verify delivery timeline, job activity and run context, then output in the browser trace. Missing events often mean wrong repository selection, a suspended installation or event/action mismatch. Use [event troubleshooting](https://docs.factorize.sh/troubleshooting/events). Delayed conflict workflows also verify live PR state; conditions previews do not perform that verification. + +## Automate from ClickUp +Source: https://docs.factorize.sh/integrations/clickup + +[Connect ClickUp](https://docs.factorize.sh/integrations/oauth) in Settings and approve access to the intended team/list. Factorize registers the task webhook on connection. Use the browser job editor to select a list and rule target IDs; MCP does not discover ClickUp lists/statuses. + +Add this trigger to the complete job configuration: + +```json +{"kind":"webhook","config":{"provider":"clickup","listId":"LIST_ID","matchRules":[{"type":"status","targetId":"STATUS_ID"}]}} +``` + +Replace IDs with browser-selected values. All configured rules must match. Read the returned stable slug/reflection before using `{{trigger-2.task}}` in the prompt. Ensure the execution agent separately has any ClickUp access required to work on the task. + +Change one test task to the selected status. Verify delivery with `list_webhook_deliveries({"provider":"clickup"})`, inspect its timeline, job activity and resulting run. Reconnect in Settings if provider authorization expires; use [event troubleshooting](https://docs.factorize.sh/troubleshooting/events) for rejected or absent deliveries. + +## Chain jobs +Source: https://docs.factorize.sh/recipes/chaining + +User request: + +> After my review job succeeds, run a second job to inspect its findings. Keep the follow-up manually runnable. + +Discover source job ID with `list_jobs`, and choose a target with `list_execution_targets`. Create the destination with required job fields and: + +```json +{"kind":"jobLifecycle","enabled":true,"config":{"sourceJobIds":["SOURCE_JOB_ID"],"states":["succeeded"]}} +``` + +Read the destination's returned trigger slug, then preserve all writable fields/triggers while setting its prompt to `Inspect source job {{trigger-2.sourceJobId}} and run {{trigger-2.sourceRunId}}. Summarize its findings.` Use the actual slug. Context includes identifiers, `state` and `completedAt`, not the source output. The execution agent must have its own authorized way to retrieve source results (for example its own Factorize MCP access); the conversational client's authorization is not forwarded. If unavailable, have the conversational agent inspect the source output in the browser or via REST trace pages and manually invoke the destination with output in `data` instead of claiming automatic output transfer. + +Expected result: a successful source run produces a destination run. Invoke the source with a stable key, wait for success, then inspect destination runs and full context to verify source job/run IDs, then inspect output in the browser. Avoid cycles and make prompts safe for repeated events; automatic signals may coalesce. + +Available states are `succeeded`, `failed`, `stopped`, and `edited`. **Edited** fires on successful saves (including enable/disable), even unchanged saves, not creation or run-state changes. Edited context has `source_job_id`, `event: "edited"`, and `edited_at`; it has no source run ID. Only same-tenant enabled subscribers match, and a job cannot subscribe to its own edits. Pending edit events wait while disabled/unmatched; deleting the source or removing the trigger discards them. Verify an edited recipe by saving the source and inspecting the destination context. + +## Connect your accounts +Source: https://docs.factorize.sh/integrations/oauth + +Sign up with email/password, verify email, then open [Settings → Integrations](https://app.factorize.sh/settings). Linear OAuth connects a workspace; it does not sign you in to Factorize. + +| Account | Browser action and required access | Verification | +| --- | --- | --- | +| exe.dev | Add an account-level token, test credentials, choose Codex/Claude/Pi and VM tags, save. Needs VM listing/creation/SSH/deletion and tagged repository/model integrations. | Test connection, then `list_execution_targets`; optionally diagnose the saved connection. | +| Amp | Add access token and project; ensure project/model/repository access. | Test and save, then discover the `amp:` target. | +| Linear | Connect Linear and approve the workspace. Your account must access the selected project and issues; organization policies may require an administrator. | Select project/rules in the browser editor, send one matching event, inspect delivery/run. | +| ClickUp | Connect ClickUp and approve the intended workspace/team with access to the list/tasks. | Select list/rules, change one matching task and inspect delivery/run. | +| GitHub | Connect GitHub to install/authorize the Factorize App on the intended account/repositories; organization approval may be required. | Confirm active installation and repository selection, then send a matching event. | + +The provider consent/installation screen is the authority for granted permissions. Grant access to the selected resources; changing those resources can require provider reauthorization. Job-trigger access and execution-agent access are separate: installing the Factorize GitHub App does not supply git credentials to an exe.dev VM. + +MCP exposes safe connection/installation/target metadata, not tokens. Account connections, resource pickers and credential management require browser setup. Reconnect Linear/ClickUp from Settings; use GitHub's Configure installation link for repository access and verify the installation is active. Do not disconnect integrations while jobs still reference them; update those jobs first. + +After changing access, create one controlled event and use `list_webhook_deliveries`, `get_webhook_delivery`, `list_job_webhook_activity`, and `list_runs` to verify delivery and execution. See [jobs not firing](https://docs.factorize.sh/troubleshooting/events). Hosted Factorize manages OAuth application registration, callbacks and webhook infrastructure. Operators of their own deployment use [configuration](https://docs.factorize.sh/self-hosting/configuration). + +## Trigger configuration +Source: https://docs.factorize.sh/integrations/triggers + +Schedule config is `{cron, timezone}`. Webhook config supports `linear` (`projectId`, non-empty `matchRules`), `clickup` (`listId`, rules), `github` (`installationId`, `repositoryId`, and rules or event/action), and `cloudflareTail` (`integrationId`). Match rule types are `owner`, `creator`, `status`, `label`, and `assignee`, each with a `targetId`. + +Lifecycle config is `{sourceJobIds, states}`, where states are `succeeded`, `failed`, `stopped`, or `edited`. Triggers have stable server-generated slugs (`trigger-1`, `trigger-2`, …); use them in Mustache templates. Disabled triggers do not fire. + +For hosted jobs, connect the provider in [Settings](https://docs.factorize.sh/integrations/oauth), select accessible resources in the browser editor, and verify a matching event with delivery tools. Factorize verifies provider signatures and manages OAuth subscriptions. Optional Cloudflare Tail triggers require your own source/relay integration; infrastructure setup belongs in [operations](https://docs.factorize.sh/self-hosting/operations). + +Choose **Job lifecycle → Edited** and one or more source jobs to run a job when another job is saved (including enable/disable saves). Creation and run status changes do not produce edit events. Each successful save is an event, even if the submitted values are unchanged. Only enabled subscribers in the same tenant are matched; a job cannot subscribe to its own edits. + +Edited events expose `{{trigger-1.source_job_id}}`, `{{trigger-1.event}}` (`edited`), and `{{trigger-1.edited_at}}`. Events are recorded in the save transaction and delivered by the scheduler with retry deduplication. Subscribers added later do not receive earlier edits. Pending events wait while the destination is disabled or no longer matches; removing a trigger or deleting its source job discards them. + + +Webhook trigger configuration accepts optional `conditions`, a json-rules-engine +condition tree, not a full rule/engine configuration. No conditions means no +additional filtering. `all`, `any`, and `not` compose leaf conditions; empty groups +are invalid. Invalid configuration or evaluation failures never create a run. +Provider authentication, scope/event/action selection and matchRules still apply. + +```json +{"all":[{"fact":"webhook","path":"$.check_suite.conclusion","operator":"equal","value":"success"},{"fact":"webhook","path":"$.check_suite.head_branch","operator":"startsWith","value":"feature/"}]} +``` + +`webhook` is the only fact. It contains the prepared context the job receives: +original provider fields, provider/event/delivery_id metadata, and existing +Linear `issue`/ClickUp `task` aliases. Tail context has already been sanitized. +Delayed GitHub dequeue verification still checks an open PR targeting main, +retries unresolved mergeability, and only proceeds on confirmed conflict. Its +prepared pull_request includes verified mergeable=false and mergeable_state. +Conditions use the latest trigger configuration and never transform context. + +JSONPath supports `$`, ordinary `.property` and quoted bracket properties, +array indexes `[0]`, and wildcards `[*]`/`.*`. No recursive descent, slices, +unions, filters, scripts or executable expressions are accepted; expression +evaluation is disabled. A scalar path returns its selected value (including an +array when selecting an array field). A wildcard path always returns an array +of matches, even for zero or one match. Missing scalar paths yield undefined. +`notEqual` may match missing fields; null and missing are distinct. Malformed +paths are configuration errors, not non-matches. + +| Operator | Configured value | Semantics | +| --- | --- | --- | +| equal / notEqual | string, number, boolean or null | Strict scalar equality/inequality; string IDs differ from numeric IDs | +| lessThan / lessThanInclusive / greaterThan / greaterThanInclusive | finite number | Both operands must be finite numbers; strings/null/missing do not match | +| in / notIn | array of scalar values | Strict membership/non-membership of the selected value in the configured array | +| contains / doesNotContain | scalar | Strict array membership/non-membership; a non-array selected value does not match | +| startsWith | string | String prefix; missing/null/non-string selected values do not match | + +Boolean negation follows the library semantics: `not` negates a valid result, +including a non-match due to a wrong operand type. No existence operator is +introduced. Conditions are limited to 16,384 serialized UTF-8 bytes, depth 16 +(root counts as 1), 128 nodes, and 512 characters per path. User priorities, +fact references in values, callbacks and network facts are rejected. + +The editor provides conditions JSON and prepared-example JSON textareas. +POST `/api/v1/job-conditions/test` and MCP `test_job_webhook_conditions` accept +`{conditions?, webhook}` with flows:write authorization. The context is limited +to 262,144 serialized bytes; the HTTP request is limited to 300,000 bytes. +They return `decision: match | no-match | error` plus plain JSON result details. +Configuration/request validation errors return a validation error. Details with +no `result` were not evaluated, and must not be displayed as failed. The preview +does not authenticate the example, route events, verify live GitHub state, or +invoke jobs. Runtime activity stores only concise decisions, never these values. + +## Connection problems +Source: https://docs.factorize.sh/troubleshooting/connection + +| Symptom | Action | +| --- | --- | +| Browser consent fails or is cancelled | Sign in to the correct verified Factorize owner account, restart authorization from the client, and approve the requested scopes. Finish signup/email verification separately before restarting. | +| Client never connects | Confirm the exact URL `https://app.factorize.sh/mcp`, remote Streamable HTTP and OAuth support. Open the client's MCP status view and authenticate; use [client-specific instructions](https://docs.factorize.sh/mcp/overview). | +| `invalid_token` or access disappears | Reauthorize the client. Password resets/changes and sign-out invalidate delegated credentials. An expired access token needs client refresh or renewed login. | +| `insufficient_scope` | Reconnect and grant `flows:read` for discovery, `flows:write` for job edits/diagnosis, `runs:read` for inspection and `runs:write` for invocation/stop. | +| `list_execution_targets` returns no items | In browser Settings, test and save an exe.dev or Amp integration in the same workspace. MCP cannot create credential-bearing connections. | +| Target exists but repository/model access fails | Test the saved execution integration and check execution-account repository/model access and VM tags. For exe.dev, `diagnose_exe_integration` uses the saved connection ID and creates/deletes a temporary VM. | + +To reconnect access, open [Settings → Authorized clients](https://app.factorize.sh/settings/authorized-clients), revoke the old client if necessary, remove/reconnect its authorization in the MCP client, then authorize again. Verify with “List my Factorize jobs” followed by “List my execution targets.” Revocation affects access, not stored jobs. Provider reconnection is separate: use [Settings → Integrations](https://app.factorize.sh/settings). + +## Jobs not firing +Source: https://docs.factorize.sh/troubleshooting/events + +1. Fetch `get_job`; confirm the job and intended trigger are enabled. Check schedule timezone/cron, selected provider resources, and all matching rules. +2. Make one controlled matching provider event. Ask for `list_webhook_deliveries` filtered by `provider` and `jobId`; if nothing is found, search by provider alone since unmatched deliveries may not link the job. +3. Use the returned delivery's identifier with `get_webhook_delivery` to inspect its safe timeline. Use `list_job_webhook_activity` for matching, rejected, duplicate and accepted activity. No raw payloads or secrets are returned. +4. If no delivery appears, reconnect the provider in Settings, check resource access/app installation and provider delivery status. Ask the hosted operator to investigate transport/subscription failures; hosted users do not configure Factorize's webhook signing secrets. +5. If delivery appears but no run does, check event/action selection, match rules and conditions. `test_job_webhook_conditions` previews prepared example context only; it does not authenticate or deliver an event. +6. Check `list_runs`: automatic occurrences coalesce while a run is queued. An accepted run may be waiting for an active slot. Query the provider itself for authoritative work. + +For schedules, verify the next occurrence in the browser editor, timezone and enabled state, then inspect runs after that time. For lifecycle triggers, verify source IDs/state selection and same-tenant source jobs. A destination cannot subscribe to its own edits. See [trigger configuration](https://docs.factorize.sh/integrations/triggers). + +## Failed or stuck runs +Source: https://docs.factorize.sh/troubleshooting/runs + +Ask: + +> Investigate run RUN_ID. Show its prompt and lifecycle diagnostics, and link to its browser trace for output. Identify the failure and whether it changed anything externally. Do not create a duplicate run; recommend a safe recovery. + +Call `get_run({"runId":"RUN_ID"})` then `get_run_diagnostics({"runId":"RUN_ID"})`. Expected evidence includes `state`, `execution`, `trace`, `artifact`, `harnessLog` and `activity`. Check launch, prompt delivery, output capture, claim release and cleanup rather than treating a missing trace as proof the agent never ran. + +| Evidence | Recovery | +| --- | --- | +| Queued | Inspect active runs/concurrency with `get_job`; wait for a slot. | +| Launch or permission failure | Browser-test the execution connection; check repository/model access and tags. Use `list_exe_connections` then `diagnose_exe_integration({"connectionId":"CONNECTION_ID"})` if appropriate. This probe uses a disposable VM. | +| Wrong/empty prompt values | Read actual trigger slug/reflection and persisted context; safely replace the full job configuration. | +| Failed with useful output | Fix the reported cause, inspect the browser trace and check external changes, then request a new manual run with a new idempotency key. | +| Starting/running/blocked but stuck | Request `stop_run`, poll, and inspect cleanup. `kill_run` currently has identical semantics. Escalate persistently stuck runs to the hosted operator with run ID and safe diagnostics. | +| Missing/partial trace | Inspect output and artifact state; ask the owner/operator about REST-only retained-artifact replay. See [advanced operations](https://docs.factorize.sh/self-hosting/operations). | + +Worked recovery configuration: use the original job ID and `invoke_job({"jobId":"JOB_ID","prompt":"Retry after correcting repository access","idempotencyKey":"investigation-RUN_ID-retry-1"})` only after fixing the cause and confirming the old run is terminal. Expected result is a **new** run ID. Verify its rendered prompt/state with `get_run` and successful output in the browser trace; a diagnostic probe passing does not itself prove the job succeeds. + +## MCP tool reference +Source: https://docs.factorize.sh/mcp/tools + +Connect to `https://app.factorize.sh/mcp` using [client authorization](https://docs.factorize.sh/mcp/overview). Tools return text containing JSON and the same JSON in `structuredContent`. Array service results are wrapped as `{"items":[...]}`; object results retain their fields. Examples below show structured content, sometimes with selected fields only. Identifiers such as `JOB_ID` are placeholders: use returned identifiers, never invented values. + +## Inventory + +| Tool | Required scope | Input contract | +| --- | --- | --- | +| `list_exe_connections` | flows:read | `{}` | +| `list_github_installations` | flows:read | `{}` | +| `list_execution_targets` | flows:read | `{}` | +| `list_cloudflare_tail_integrations` | flows:read | `{}` | +| `list_jobs` | flows:read | `{}` | +| `get_job` | flows:read | Required string `jobId` | +| `create_job` | flows:write | Required `name`, `slug`, `promptTemplate`, `executionTargetId`; job fields below | +| `update_job` | flows:write | Same required job fields plus `jobId`; optional `expectedUpdatedAt` | +| `delete_job` | flows:write | Required string `jobId` | +| `enable_job` | flows:write | Required string `jobId` | +| `disable_job` | flows:write | Required string `jobId` | +| `list_runs` | runs:read | Optional `jobId`, `state`, `contextQuery`, `limit`, `cursor` | +| `get_run` | runs:read | Required string `runId` | +| `get_run_diagnostics` | runs:read | Required string `runId` | +| `invoke_job` | runs:write | Required string `jobId`; optional `name`, `prompt`, `data`, `idempotencyKey` | +| `stop_run` | runs:write | Required string `runId` | +| `kill_run` | runs:write | Required string `runId`; currently the same stop operation | +| `list_job_webhook_activity` | runs:read | Required `jobId`; optional integer `limit` (1–100, default 50) | +| `list_webhook_deliveries` | runs:read | Optional strings `provider`, `deliveryId`, `event`, `action`, `outcome`, `jobId`, `q`, `from`, `to`, `cursor`; integer `limit` (1–100, default 50) | +| `get_webhook_delivery` | runs:read | Required string `deliveryId` | +| `test_job_webhook_conditions` | flows:write | Required prepared JSON object `webhook`; optional `conditions` tree | +| `diagnose_exe_integration` | flows:write | Required string `connectionId` | + +The inventory is validated against every registered implementation tool. All required IDs are non-empty strings except numeric GitHub installation/repository IDs in trigger configuration. + +## Discovery inputs and outputs + +- `list_execution_targets({})` → `{"items":[{"id":"TARGET_ID","kind":"exe-vm","name":"Ephemeral exe.dev VMs","workspace":"ephemeral","cwd":"/home/exedev/workspace","agentKind":"codex","models":[],"efforts":["minimal","low","medium","high","xhigh"],"capabilities":["recovery","stop"]}]}`. Copy `id` into `executionTargetId`. Amp IDs have an `amp:` prefix and kind `amp`. Empty results require browser integration setup. Targets do not contain repository URLs. +- `list_exe_connections({})` → `{"items":[{"connectionId":"CONNECTION_ID","agentKind":"codex","tags":[]}]}` (selected fields). Use `connectionId` for integration diagnosis. +- `list_github_installations({})` → `{"items":[{"installationId":12345,"accountLogin":"YOUR_ORG","state":"active"}]}` (selected fields). Use numeric `installationId` in GitHub triggers; choose repository IDs in the browser. +- `list_cloudflare_tail_integrations({})` → `{"items":[{"integrationId":"INTEGRATION_ID","name":"Worker errors","referencedJobCount":0}]}` (selected fields). Use `integrationId` in Tail trigger configuration. +- `diagnose_exe_integration({"connectionId":"CONNECTION_ID"})` probes permissions and a disposable tagged VM's agent/model access, deleting that VM before returning. Example selected result: `{"ok":true,"connectionId":"CONNECTION_ID","agentKind":"codex","permissions":{"ok":true,"missing":[],"tags":[]},"agent":{"ok":true}}`. Inspect both permissions and agent results rather than assuming a successful tool response means all checks passed. Missing connections return `not_found`. + +## Job fields and creation + +| Field | Contract | +| --- | --- | +| `name` | Required trimmed string, 1–120 characters | +| `slug` | Required string matching `^[a-z][a-z0-9_-]{0,29}$`; unique within workspace | +| `promptTemplate` | Required string, 1–50,000 characters | +| `executionTargetId` | Required non-empty ID from target discovery | +| `runNameTemplate` | Optional string, max 500; defaults to empty | +| `concurrencyLimit` | Optional integer 1–50; defaults to 1 | +| `model` | Optional trimmed string, max 120; defaults to empty/provider default | +| `effort` | Optional trimmed string, max 40; choose target-supported values | +| `triggers` | Optional array, max 50; defaults to empty and server supplies a manual trigger | + +Do not submit credentials, unknown top-level fields, parameters or parameter overrides. Trigger objects contain `kind`, `config`, optional `enabled` (default true), and optional `id`/`slug` for preservation during edits. Kinds/configuration: + +- `manual`: `{}`. +- `schedule`: `{"cron":"0 9 * * 1-5","timezone":"UTC"}`. +- `webhook`: provider-specific configuration below, optional `conditions`. +- `jobLifecycle`: `{"sourceJobIds":["SOURCE_JOB_ID"],"states":["succeeded"]}`. States: `succeeded`, `failed`, `stopped`, `edited`. + +Webhook configurations: + +```json +[ + {"provider":"linear","projectId":"PROJECT_ID","matchRules":[{"type":"status","targetId":"STATUS_ID"}]}, + {"provider":"clickup","listId":"LIST_ID","matchRules":[{"type":"assignee","targetId":"USER_ID"}]}, + {"provider":"github","installationId":12345,"repositoryId":67890,"event":"pull_request","action":"opened"}, + {"provider":"cloudflareTail","integrationId":"INTEGRATION_ID"} +] +``` + +Match rule types: `owner`, `creator`, `status`, `label`, `assignee`, with non-empty string `targetId`. Linear/ClickUp require at least one rule; GitHub requires at least one rule or both event/action. Select actual resource IDs in the browser editor. This array illustrates alternative configurations, not a tool input. + +`create_job` input: + +```json +{"name":"Review recent changes","slug":"review-recent-changes","promptTemplate":"Clone REPOSITORY_URL and review the latest commit. {{trigger-1.prompt}}","executionTargetId":"TARGET_ID","concurrencyLimit":1,"triggers":[{"kind":"manual","config":{}}]} +``` + +Result includes (selected fields): + +```json +{"id":"JOB_ID","name":"Review recent changes","slug":"review-recent-changes","enabled":true,"executionTargetId":"TARGET_ID","concurrencyLimit":1,"currentRuns":0,"maxConcurrency":1,"updatedAt":"2026-10-10T09:00:00.000Z","triggers":[{"id":"TRIGGER_ID","slug":"trigger-1","kind":"manual","enabled":true,"config":{}}]} +``` + +Save `id`, trigger IDs/slugs and `updatedAt`. Full job results include prompt/configuration, timestamps, agent metadata and trigger reflection. `list_jobs({})` returns `{"items":[...jobs]}`; `get_job({"jobId":"JOB_ID"})` returns a single job. Creation errors include `conflict` for duplicate slug and `invalid_request` for invalid/unknown target or invalid fields. If creation's response is lost, list/find the job before recreating it. + +## Safe replacement and enable/delete + +`update_job` replaces configuration. Fetch first; preserve all intended fields and triggers; strip read-only fields. Example for a manual-only job: + +```json +{"jobId":"JOB_ID","expectedUpdatedAt":"2026-10-10T09:00:00.000Z","name":"Review recent changes","slug":"review-recent-changes","promptTemplate":"Clone REPOSITORY_URL and review the latest commit. Run relevant checks. {{trigger-1.prompt}}","executionTargetId":"TARGET_ID","runNameTemplate":"","concurrencyLimit":1,"model":"","triggers":[{"id":"TRIGGER_ID","slug":"trigger-1","kind":"manual","enabled":true,"config":{}}]} +``` + +Result is the saved job with new `updatedAt`. Preserve any automatic triggers too. Omission can reset optional settings or remove automatic triggers. On `stale_job`, fetch/reapply; omitting `expectedUpdatedAt` is last-writer-wins. Stable slugs survive edits when trigger identity/kind is retained; changing kind creates a new trigger identity. Inspect returned slugs rather than assuming numbering. + +`enable_job({"jobId":"JOB_ID"})` → `{"id":"JOB_ID","enabled":true}`; `disable_job({"jobId":"JOB_ID"})` → `{"id":"JOB_ID","enabled":false}`. `delete_job({"jobId":"JOB_ID"})` → `{"id":"JOB_ID","deleted":true}`; deletion also removes execution history/artifacts. Missing jobs return `not_found`. Saves can emit `edited` events; see [chaining](https://docs.factorize.sh/recipes/chaining). + +## Invocation, run inspection, and retries + +`invoke_job` input: + +```json +{"jobId":"JOB_ID","name":"First review","prompt":"Focus on regressions","data":{"branch":"main"},"idempotencyKey":"review-first-1"} +``` + +Result: + +```json +{"invocationId":"INVOCATION_ID","runId":"RUN_ID","state":"queued","duplicate":false} +``` + +Optional `name`: trimmed 1–120 characters; `prompt`: max 50,000, default empty; `data`: JSON object; `idempotencyKey`: trimmed 1–200 characters and must not begin `manual:`. Retrying the same key for the same job returns the original IDs with `duplicate:true`, even if that run failed. Without a key, each call is a new invocation. Intentional reruns require a new key. Manual requests never coalesce; `queue_full` means capacity is exhausted. Disabled manual triggers return `operation_failed`. + +`list_runs({"jobId":"JOB_ID","state":"failed","contextQuery":"regression","limit":10})` → `{"items":[{"id":"RUN_ID","job_id":"JOB_ID","state":"failed"}],"nextCursor":null}` (selected fields). Pass a returned cursor for later pages. `limit` is 1–100, default 50; `contextQuery` is 1–50,000 characters and case-insensitive substring matching. The current repository uses SQL ILIKE: percent and underscore behave as wildcards; use get_run for full context. Current results do not include excerpts. + +Allowed state filters: `queued`, `starting`, `running`, `done`, `blocked`, `failed`, `ignored`, `succeeded`, `stopping`, `stopped`. + +`get_run({"runId":"RUN_ID"})` → a full run including `id`, `job_id`, `state`, rendered `prompt`, full `context`, `activity`, execution metadata and `invocation`. Example selected fields: + +```json +{"id":"RUN_ID","job_id":"JOB_ID","state":"succeeded","prompt":"Clone REPOSITORY_URL and review the latest commit. Focus on regressions","context":{"trigger-1":{"prompt":"Focus on regressions","data":{"branch":"main"}}},"invocation":{"trigger_id":"TRIGGER_ID"}} +``` + +Retain the submitted key for retries. Current `get_run` returns only internal `invocation.claim_key`, not `invocation.idempotency_key`; never pass that internal field back. `get_run_diagnostics({"runId":"RUN_ID"})` returns a diagnostic object with `runId`, `jobId`, `state`, `execution`, `trace`, `artifact`, `harnessLog`, `activity` and timestamps. These cover launch/prompt/output/cleanup and trace evidence, not credentials. Missing runs return `not_found`. + +`stop_run({"runId":"RUN_ID"})` → `{"id":"RUN_ID","state":"stopping"}`. Current `kill_run({"runId":"RUN_ID"})` returns the same result and uses the same operation. Both accept starting/running/blocked runs; queued or terminal runs return `operation_failed`. Neither guarantees immediate termination/slot release. Poll `get_run` and inspect cleanup. See [stop/retry](https://docs.factorize.sh/work/stop-retry). + +## Webhook investigation and conditions + +`list_job_webhook_activity({"jobId":"JOB_ID","limit":10})` → `{"items":[{"id":"ACTIVITY_ID","provider":"linear","deliveryId":"PROVIDER_DELIVERY_ID","outcome":"accepted","detail":"...","receivedAt":"2026-10-10T09:00:00.000Z"}]}`. Use it for matching/rejected/duplicate/accepted evidence; it is not a full provider event history. + +`list_webhook_deliveries({"provider":"linear","jobId":"JOB_ID","limit":10})` → `{"items":[{"id":"DELIVERY_RECORD_ID","provider":"linear","deliveryId":"PROVIDER_DELIVERY_ID","event":"Issue","outcome":"accepted"}],"nextCursor":null}` (selected fields). Results are newest-first and cursor paginated. Provider/delivery/event/action/outcome filters are exact matches; `q` searches safe diagnostic text. **Current limitation:** `from` and `to` are accepted by the tool schema but the repository does not apply time-range filters; do not rely on them to bound results. + +`get_webhook_delivery({"deliveryId":"DELIVERY_RECORD_ID"})` accepts the internal record ID or provider delivery ID and returns delivery metadata plus `timeline` entries with `jobId`, `outcome`, `detail`, `createdAt`. Prefer the record ID to disambiguate deliveries. Secrets/raw payloads are never returned. Missing records return `not_found`. + +`test_job_webhook_conditions` input: + +```json +{"conditions":{"all":[{"fact":"webhook","path":"$.issue.title","operator":"startsWith","value":"Review"}]},"webhook":{"provider":"linear","issue":{"title":"Review latest changes"}}} +``` + +Result contains `decision: "match" | "no-match" | "error"` and plain JSON evaluation details. An invalid request/configuration yields `invalid_request`; evaluation failure yields an error decision. This preview does not authenticate the example, route an event, verify live GitHub state or invoke a job. See [condition operators and limits](https://docs.factorize.sh/integrations/triggers). + +Current `get_run` does not include `output`, trace message contents or a client-facing retry key. To inspect findings, open `https://app.factorize.sh/job-runs/RUN_ID` or use REST trace pagination. `harness_log` is artifact metadata, not log bytes. Retain your submitted idempotency key. + +## Common errors and capability boundaries + +Tool errors are `code: message`. `invalid_token` needs reauthorization; `insufficient_scope` needs the listed scope; `invalid_request` needs corrected input; `not_found` means the ID is absent from the authorized workspace; `stale_job` needs refetch/reapply; `conflict` needs an unused job slug; `queue_full` needs capacity; `operation_failed` needs state/diagnostic inspection. Do not repeatedly retry a write with new identifiers after a lost response. + +MCP is a selected tool surface, **not full REST parity**. Signup, verification, integration credential management, authorized-client management, provider resource selection, schedule preview, specialized run status/trace pagination and retained-artifact replay have no corresponding tools in this inventory. Some REST operations require an interactive owner session rather than delegated tokens. Use the browser for setup/resource selection and [REST reference](https://docs.factorize.sh/api/reference) for exact routes, restrictions and schemas. MCP cannot pass your conversational client's credentials to the execution agent. + +## Jobs, triggers, runs, and targets +Source: https://docs.factorize.sh/concepts + +A **job** is a saved instruction: what to do, where to execute it, and when it may run. A **trigger** is a reason to run it: a manual request, schedule, provider event, or another job's lifecycle event. A **run** is one execution of the job, with its own state, prompt, context and output. An **execution target** is a saved execution account/agent configuration discovered with `list_execution_targets`. + +The **conversational agent** you talk to uses MCP to control Factorize. The **execution agent** receives the job's rendered prompt and does the work on the execution account. Giving the conversational agent MCP permission does not give the execution agent repository, provider or model access. Your saved connection, VM tags and prompt must supply those. + +Every job gets a manual trigger. Additional triggers have immutable server-generated slugs such as `trigger-2`. Each run receives only the firing trigger's context; [prompt templates](https://docs.factorize.sh/work/prompts) use that slug. + +## Concurrency and the queue + +With concurrency 1, a review already running occupies the only active slot. One more run may wait in the queue. A further manual request returns `queue_full`; wait for capacity instead of repeatedly changing retry keys. Automatic schedule/webhook/lifecycle signals arriving while a run is queued are skipped/coalesced, so they are not a complete event log. An accepted idempotency key still returns its original run even when the queue is full. + +Concurrency can be 1–50. With concurrency 2, two reviews may execute and one may wait. Queued runs keep the prompt/context they were submitted with; editing a job does not rewrite those runs. Query runs and the provider for authoritative work when automatic events coalesce. + +Inspect output before treating a terminal state as a useful result. Trace collection can be incomplete even when execution completed; advanced trace recovery belongs in [operations](https://docs.factorize.sh/self-hosting/operations). + +## REST API reference +Source: https://docs.factorize.sh/api/reference + +The **REST operations** group under Reference renders every application operation directly from [openapi.yaml](https://docs.factorize.sh/openapi.yaml), including request validation, required scopes, owner-session restrictions, and JSON response schemas. This is the same generated artifact verified by CI and available to API clients. + +All application endpoints use `/api/v1`. Authenticate with a scoped bearer token or an interactive owner session; credential management and trace replay require an interactive owner session. Errors use `{ "error": { "code": "...", "message": "..." } }`. + +`GET /healthz` is the unauthenticated infrastructure liveness probe and returns `{ "ok": true }`. It is outside the application API contract. + +See [authentication](https://docs.factorize.sh/api/authentication) for access setup and [OpenAPI definition](https://docs.factorize.sh/api/openapi) for downloading or regenerating the contract. + +## Authentication and scopes +Source: https://docs.factorize.sh/api/authentication + +Protected API and MCP requests use `Authorization: Bearer `. Browser users may also use their signed Factorize session cookie. Access is tenant-bound; owner membership and session version are rechecked on every service call. + +## Browser accounts + +Create an email/password account at `/auth/signup` and verify the email delivered by Postmark before signing in at `/auth/login`. Recovery is at `/auth/password-reset`; legacy Linear-only users use that flow to choose a password while retaining their workspace. Change your password from the account menu. Resetting/changing passwords or signing out invalidates existing sessions and delegated credentials. + +Linear OAuth is an integration connection available only after native sign-in. Workspace membership, not the connected Linear identity, controls authorization. + +## Scopes + +| Scope | Allows | +| --- | --- | +| `flows:read` | Jobs, targets, connections, integrations, trigger availability | +| `flows:write` | Create/update/delete/enable/disable jobs; test conditions | +| `runs:read` | List/get runs and webhook activity | +| `runs:write` | Invoke and stop runs | + +Authorization-code clients must use PKCE S256. Implicit and plain PKCE are disabled. Access tokens last 1 hour; refresh tokens can last 30 days. RFC 7009 revocation is advertised by discovery. + +## Device flow + +1. Register a public client at `POST /oauth/register` with `grant_types` containing `urn:ietf:params:oauth:grant-type:device_code` and `token_endpoint_auth_method: none`. +2. POST form data to `/oauth/device_authorization` with `client_id`, `scope`, and optional `resource`. +3. Send the user to `/device?user_code=...` and poll `/oauth/token` with the device code. + +Device codes expire after 10 minutes and polling is rate limited. The token endpoint returns `authorization_pending`, `slow_down`, `access_denied`, or `expired_token` as appropriate. + +Never send Linear, exe.dev, or connection credentials to an API client. Tokens are revocable and responses omit stored secrets. + +## OAuth discovery +Source: https://docs.factorize.sh/api/discovery + +At `https://app.factorize.sh`, clients can retrieve: + +* `/.well-known/oauth-authorization-server` — issuer, authorization, token, registration, revocation, and device endpoints plus supported grants/scopes. +* `/.well-known/oauth-protected-resource` — resource `https://app.factorize.sh/mcp`, authorization server, header bearer authentication, and supported scopes. + +The authorization endpoint is `/authorize`, token endpoint `/oauth/token`, dynamic registration endpoint `/oauth/register`, and device endpoint `/oauth/device_authorization`. Client ID Metadata Documents are enabled. MCP clients should use `https://app.factorize.sh/mcp`; they can discover OAuth automatically and complete browser PKCE consent. + +## OpenAPI definition +Source: https://docs.factorize.sh/api/openapi + +[Download openapi.yaml](https://docs.factorize.sh/openapi.yaml). Clients can use this exact file to generate SDKs or inspect request and response schemas. + +The definition is generated from the executable route catalog in `packages/api/src/api-contract.ts`, which the Worker dispatches in `protected-api.ts`. To change an API operation, update its catalog entry (method, path, scope, validation, handler, and documentation), then run: + +```bash +npm run generate:openapi +``` + +Commit `packages/docs/openapi.yaml` with the change. CI regenerates it and rejects a diff; parsed contract tests also require exact method/path equality with the executable catalog. Shared schemas and general API metadata live beside the catalog in `flow-schemas.ts`, `trace-replay-schemas.ts`, and `api-document.json`. + +Run `npm run validate --workspace=factorize-docs` to verify the generated artifact, parsed operation contract, and Mintlify configuration before publishing. + +## REST operations +Contract: https://docs.factorize.sh/openapi.yaml +The site renders this exact generated contract under Reference → REST operations. + +## Optional self-hosting +Source: https://docs.factorize.sh/self-hosting/deployment + +Hosted users can start at [app.factorize.sh](https://app.factorize.sh) without deploying anything. Self-hosting is for operators who want to own the application infrastructure. + +The Worker lives in `packages/api`, React frontend in `packages/app`, and generated public client in `packages/api-client`. Use Node 24 and the root lockfile. Follow the [API-first deployment and rollback gates](https://github.com/GenerationSoftware/factorize/blob/main/docs/package-migration.md) before deploying static assets. Preserve Worker identity, bindings, migrations, and old hashed assets. + +Install dependencies with `npm ci`. Configure `packages/api/wrangler.jsonc`, PostgreSQL, OAuth KV and artifact storage, set the final HTTPS `APP_ORIGIN`, then build with `npm run build:app` and deploy with `npm run deploy:app`. See [configuration](https://docs.factorize.sh/self-hosting/configuration) before deployment. + +For local development, copy `packages/api/.dev.vars.example` to `packages/api/.dev.vars`, supply local configuration, and use `npm run dev`. Development uses HTTPS at `https://localhost:5173`; use that origin for local callbacks. The migration guide covers local database setup. Never commit secrets. + +## Operator configuration +Source: https://docs.factorize.sh/self-hosting/configuration + +These steps apply only to your own deployment. Hosted Factorize users connect existing accounts in [Settings](https://app.factorize.sh/settings); they do not register Factorize OAuth applications or set Worker secrets. + +Register provider applications for your deployment origin. Linear requires Issues and Issue labels webhooks and fresh workspace authorization after subscription changes; ClickUp registers its task webhook on connection. Configure the GitHub App credentials and webhook settings for your deployment using the template in `packages/api/.dev.vars.example` and the executable callbacks/webhook routes in `packages/api/src/worker.ts`. + +## Account authentication + +Factorize owns authentication in PostgreSQL. Create a native account at `/auth/signup` with an email address and a password of 12–200 characters. Emails are case-insensitive. Verify the email before signing in at `/auth/login`; email plus password are accepted. Linear is connected after sign-in from **Settings → Integrations**, only for Linear-backed jobs. + +Postmark sends one-hour, single-use verification and password-reset links. `/auth/verify/request` resends verification; `/auth/password-reset` handles recovery. Links never appear in application responses or logs. Passwords use salted PBKDF2-SHA-256. **Change password** in the account menu requires the current password. Password reset, password change and sign-out invalidate existing sessions via membership session versions, including delegated API credentials. + +Before deploying, configure `POSTMARK_SERVER_TOKEN` as a **production GitHub environment secret**. The deployment copies it to a Worker secret; the verified sender and transactional message stream are non-secret Worker vars in `packages/api/wrangler.jsonc`. For a manual Postmark preflight, set the following environment variables along with `APP_ORIGIN`: + +| Setting | Required value | +| --- | --- | +| `POSTMARK_SERVER_TOKEN` | Postmark **server** API token for the sending server; never an account token or a committed value | +| `POSTMARK_FROM_EMAIL` | Plain email address on a verified Postmark sender signature or verified domain | +| `POSTMARK_MESSAGE_STREAM` | Active **transactional** stream ID, commonly `outbound` | + +`APP_ORIGIN` must be the canonical HTTPS origin, without a trailing slash. Run `npm run auth:validate-email --workspace=factorize` manually when needed: it checks the server token/stream with Postmark and sends one preflight email from/to the configured sender, rejecting unverified senders or sending failures. It prints no credentials. Missing configuration fails the manual check. The deploy workflow does not run this check or send a preflight email. Runtime signup and recovery also fail closed if configuration or delivery fails; users can resend verification after a delivery failure. Local mail testing needs an HTTPS origin and a separate Postmark test server/sender; automated tests mock Postmark and never send mail. + +### Existing account migration + +Apply `0008_native_accounts.sql` and `0009_remove_auth_usernames.sql` before deploying this code. They reject ambiguous legacy emails that differ only in case (reconcile those identities before retrying migration), preserve tenant IDs, memberships, jobs and encrypted Linear connections, and backfill explicit Linear organization-to-workspace mappings. Existing Linear-only users choose **Forgot password or previously signed in with Linear?**, receive a reset email at their existing address, and set a password. Email possession is required; signup cannot replace an existing account's credentials. Existing native users keep their passwords and may sign in by email; unverified accounts must verify first. A reset never promotes a member to owner. An account with multiple existing owner memberships currently opens the oldest workspace; no new workspace-switching UI is introduced. + +Linear OAuth requires an authenticated owner, binds state to that user/workspace, stores the connection there, and never creates a Factorize session. A Linear organization already bound to another workspace cannot be claimed. Existing webhook routes resolve the explicit mapping. Do not delete that binding to work around an account-recovery problem. + +### Authentication verification + +`npm run check` runs unit/contract tests and Postmark preflight tests. CI also runs the real PostgreSQL authentication suite against a disposable service. To run it locally, set `AUTH_TEST_DATABASE_URL` to an isolated PostgreSQL server whose user can create/drop test databases, then run `npm test --workspace=factorize -- --run test/native-auth.postgres.test.ts`. The suite creates and removes its own database and applies every migration, including a legacy connection fixture before the auth migration. + +## Configure Linear + +Use authorization-code OAuth and enable **Webhooks** on the OAuth application. Configure: + +| Setting | Value | +| --- | --- | +| Callback URL | `https://your-domain.example/auth/linear/callback` | +| Webhook URL | `https://your-domain.example/webhooks/linear` | +| Webhook events | **Issues** and **Issue labels** | +| Webhook secret | Store as `LINEAR_WEBHOOK_SIGNING_SECRET` | + +After changing the webhook settings, re-authorize existing workspaces so Linear creates a fresh workspace subscription. + +## Configure ClickUp + +Create a ClickUp OAuth application with the callback URL `https://your-domain.example/auth/clickup/callback`, then store its client ID and secret in `CLICKUP_CLIENT_ID` and `CLICKUP_CLIENT_SECRET`. Connecting ClickUp from Settings registers the signed task webhook automatically. ClickUp triggers can filter a list by status, tag, assignee, or creator; all configured rules must match. + + +## Configuration reference + +| Variable | Purpose | +| --- | --- | +| `LINEAR_CLIENT_ID` | Linear OAuth client ID | +| `LINEAR_CLIENT_SECRET` | Linear OAuth client secret | +| `LINEAR_WEBHOOK_SIGNING_SECRET` | Verifies Linear webhook signatures | +| `CLICKUP_CLIENT_ID` | ClickUp OAuth client ID | +| `CLICKUP_CLIENT_SECRET` | ClickUp OAuth client secret; ClickUp also uses a per-installation webhook secret stored encrypted by Factorize | +| `CREDENTIAL_ENCRYPTION_KEY` | Base64-encoded 32-byte key for encrypted credentials | +| `SESSION_SIGNING_SECRET` | Independent secret for signed browser sessions | +| `APP_ORIGIN` | Public Worker origin, configured in `packages/api/wrangler.jsonc` | +| `OAUTH_KV` | KV binding containing OAuth clients, grants, refresh tokens, and revocation state | + +Never commit `.dev.vars` or production secret values. The included `.dev.vars.example` is a safe template. + +## Operations and advanced trace recovery +Source: https://docs.factorize.sh/self-hosting/operations + +Use the [deployment runbook](https://github.com/GenerationSoftware/factorize/blob/main/docs/package-migration.md) and [trace rollout runbook](https://github.com/GenerationSoftware/factorize/blob/main/docs/trace-rollout-runbook.md) for retention, canary gates and rollback. `npm run check` checks package boundaries, generated contracts, runtime tests and builds. The PostgreSQL auth suite uses an isolated database; see configuration for migration verification. + +`get_run_diagnostics` exposes declared trace sources, projection evidence, artifacts and fallback use. A trace may be partial when collection fails. A `matched` reconciliation result verifies the live prefix against the terminal artifact; missing evidence does not prove completeness. + +Trace replay is REST-only and requires an interactive owner session with `runs:write`: `POST /api/v1/runs/{runId}/trace/replay` with a UUID `requestId` and `source` (`primary` or `native_session`). Reuse the request ID after interruption. Limit: ten requests per tenant per minute. Results distinguish projected, already projected, skipped and unrecoverable. Replay preserves artifacts; expired/deleted bytes cannot be recovered. Historical Codex tool calls require retained native session bytes. + +Cloudflare Tail infrastructure is optional: use the [Tail relay deployment guide](https://github.com/GenerationSoftware/factorize/blob/main/docs/cloudflare-tail.md). Hosted users still supply their own source Worker/relay integration. diff --git a/packages/docs/llms.txt b/packages/docs/llms.txt index 0e1fdbc8..633d4c9e 100644 --- a/packages/docs/llms.txt +++ b/packages/docs/llms.txt @@ -1,11 +1,60 @@ # Factorize -> Automate coding-agent jobs from provider events on your own exe.dev VM. - -- [Quickstart](/quickstart): Configure Factorize and create a first job. -- [Concepts](/concepts): Jobs, triggers, runs, and the Mustache prompt contract. -- [REST authentication](/api/authentication): OAuth, scopes, and device authorization. -- [REST reference](/api/reference): Using the generated API reference. -- [OpenAPI contract](/openapi.yaml): Verified operation inventory, validation, scopes, and response schemas. -- [MCP](/mcp/overview): Connect a remote MCP client. -- [MCP tools](/mcp/tools): Complete tool catalog. +Hosted workflow: connect your agent → create a job → run it → inspect the result → automate it. + +Application: https://app.factorize.sh +MCP (Streamable HTTP + OAuth): https://app.factorize.sh/mcp + +Browser: email/password signup, verification, execution/provider connections and consent. +MCP: discover targets, manage jobs, invoke with retained idempotency keys, inspect state/context/diagnostics. +Current MCP does not return execution output; inspect browser traces or REST trace pages. REST is not full MCP parity. + +## Get started + +- [Factorize with your agent](https://docs.factorize.sh/): Connect your agent, create a job, run it, inspect the result, and automate it. +- [Connect your agent](https://docs.factorize.sh/mcp/overview): Authorize Codex or Claude Code for hosted Factorize. +- [Your first job](https://docs.factorize.sh/quickstart): Run a hosted repository review through MCP. + +## Work with your agent + +- [Create and edit jobs](https://docs.factorize.sh/work/jobs): Discover a target and replace configuration safely. +- [Write job prompts](https://docs.factorize.sh/work/prompts): Use stable trigger context and explicit execution instructions. +- [Inspect results](https://docs.factorize.sh/work/results): Read run state, output, prompt, and trigger context. +- [Stop and retry runs](https://docs.factorize.sh/work/stop-retry): Avoid duplicate work and understand current stop behavior. + +## Automate jobs + +- [Schedule a repository review](https://docs.factorize.sh/recipes/scheduled-review): Turn a successful manual review into daily automation. +- [Run a job from Linear](https://docs.factorize.sh/recipes/linear-job): Connect a workspace, select a project and match issues. +- [Automate from GitHub](https://docs.factorize.sh/integrations/github): Select an installation, repository, and event. +- [Automate from ClickUp](https://docs.factorize.sh/integrations/clickup): Connect a workspace and select matching tasks. +- [Chain jobs](https://docs.factorize.sh/recipes/chaining): Start a follow-up after another job finishes or is edited. +- [Connect your accounts](https://docs.factorize.sh/integrations/oauth): Browser setup, resource access, and delivery verification. +- [Trigger configuration](https://docs.factorize.sh/integrations/triggers): Configure schedules, provider webhooks, and lifecycle triggers. + +## Troubleshooting + +- [Connection problems](https://docs.factorize.sh/troubleshooting/connection): Recover authorization, scopes, and execution targets. +- [Jobs not firing](https://docs.factorize.sh/troubleshooting/events): Verify automation from provider event to accepted run. +- [Failed or stuck runs](https://docs.factorize.sh/troubleshooting/runs): Investigate evidence, fix the cause, and verify recovery. + +## Reference + +- [MCP tool reference](https://docs.factorize.sh/mcp/tools): Complete hosted MCP inventory, inputs, results, and common errors. +- [Jobs, triggers, runs, and targets](https://docs.factorize.sh/concepts): Understand the workflow before configuring automation. +- [REST API reference](https://docs.factorize.sh/api/reference): How to use the generated API reference. +- [Authentication and scopes](https://docs.factorize.sh/api/authentication): OAuth 2.1, device authorization, and access-token rules. +- [OAuth discovery](https://docs.factorize.sh/api/discovery): Endpoints and metadata for OAuth-aware clients. +- [OpenAPI definition](https://docs.factorize.sh/api/openapi): Download the verified Factorize REST contract. +- [REST operations](https://docs.factorize.sh/openapi.yaml): Complete generated REST schemas and operations + +## Self-hosting + +- [Optional self-hosting](https://docs.factorize.sh/self-hosting/deployment): Deploy your own Factorize instance. +- [Operator configuration](https://docs.factorize.sh/self-hosting/configuration): Email, OAuth applications, webhooks, and Worker secrets. +- [Operations and advanced trace recovery](https://docs.factorize.sh/self-hosting/operations): Operator checks, retained artifacts, and rollout evidence. + +## Machine-readable REST reference + +- https://docs.factorize.sh/openapi.yaml +- https://docs.factorize.sh/llms-full.txt diff --git a/packages/docs/mcp/overview.mdx b/packages/docs/mcp/overview.mdx index a3f8b997..52fae945 100644 --- a/packages/docs/mcp/overview.mdx +++ b/packages/docs/mcp/overview.mdx @@ -1,12 +1,47 @@ --- -title: Remote MCP -description: Connect an MCP client to Factorize. +title: Connect your agent +description: Authorize Codex or Claude Code for hosted Factorize. --- -Use the single Streamable HTTP URL `APP_ORIGIN/mcp`. The endpoint is OAuth-protected and advertises protected-resource metadata. Compatible clients discover authorization, use PKCE S256, and request only the scopes they need. The server is stateless; each request is tenant-isolated. +Use the remote **Streamable HTTP** endpoint: -```json -{ "mcpServers": { "factorize": { "url": "https://app.factorize.sh/mcp" } } } +```text +https://app.factorize.sh/mcp ``` -Tool results contain MCP text plus structured JSON. Errors are reported as `code: message`. Credentials and signing secrets are never accepted or returned. +Complete [browser account and execution setup](/quickstart) first. Factorize requires OAuth authorization, owner membership and tenant-bound scopes. A JSON configuration from one client is not a universal MCP configuration. + +## Codex + +Current Codex supports Streamable HTTP and OAuth. Add this client-specific TOML to `~/.codex/config.toml`: + +```toml +[mcp_servers.factorize] +url = "https://app.factorize.sh/mcp" +``` + +Run `codex mcp login factorize`, then use `/mcp` in Codex to verify the connection. See the [official Codex MCP documentation](https://developers.openai.com/codex/mcp) for configuration and OAuth support. + +## Claude Code + +Add the remote server: + +```bash +claude mcp add --transport http factorize https://app.factorize.sh/mcp +``` + +Start Claude Code, enter `/mcp`, choose Factorize and authenticate when prompted. See the [official Claude Code MCP documentation](https://code.claude.com/docs/en/mcp) for HTTP transport, OAuth and configuration scope. + +## Authorize in the browser + +The client opens Factorize authorization in your browser. Sign in with your verified Factorize email/password and approve the requested scopes. For the full workflow, grant `flows:read`, `flows:write`, `runs:read`, and `runs:write`. Read-only access cannot create or invoke jobs. Return to your client after consent. + +If you need to create an account or verify your email, finish those steps and restart client authorization; do not assume the signup screen will automatically resume the original request. No Linear or execution token belongs in the MCP client. + +Ask **“List my Factorize jobs.”** The agent should call `list_jobs({})`. An empty `items` list is a successful connection to a workspace with no jobs. Next ask it to list execution targets and follow the [first-job walkthrough](/quickstart). + +Other clients must support remote Streamable HTTP and Factorize's OAuth discovery/PKCE flow. Their UI and plan availability vary; consult their own documentation rather than pasting either configuration above. + +## Connection problems + +For rejected consent, expired authorization, missing targets, scope errors and reconnection steps, see [connection troubleshooting](/troubleshooting/connection). Protocol implementers should use [authentication](/api/authentication) and [discovery](/api/discovery). diff --git a/packages/docs/mcp/tools.mdx b/packages/docs/mcp/tools.mdx index 97a54cf0..48b8a825 100644 --- a/packages/docs/mcp/tools.mdx +++ b/packages/docs/mcp/tools.mdx @@ -1,26 +1,157 @@ --- -title: MCP tools -description: Every tool exposed at /mcp. +title: MCP tool reference +description: Complete hosted MCP inventory, inputs, results, and common errors. --- -| Tool | Scope | Input | +Connect to `https://app.factorize.sh/mcp` using [client authorization](/mcp/overview). Tools return text containing JSON and the same JSON in `structuredContent`. Array service results are wrapped as `{"items":[...]}`; object results retain their fields. Examples below show structured content, sometimes with selected fields only. Identifiers such as `JOB_ID` are placeholders: use returned identifiers, never invented values. + +## Inventory + +| Tool | Required scope | Input contract | | --- | --- | --- | | `list_exe_connections` | flows:read | `{}` | | `list_github_installations` | flows:read | `{}` | | `list_execution_targets` | flows:read | `{}` | | `list_cloudflare_tail_integrations` | flows:read | `{}` | | `list_jobs` | flows:read | `{}` | -| `get_job` | flows:read | `{jobId}` | -| `list_runs` | runs:read | `jobId?`, `state?`, `contextQuery?`, `limit?`, `cursor?` | -| `get_run` | runs:read | `{runId}` | -| `list_job_webhook_activity` | runs:read | `{jobId, limit?}` | -| `create_job` | flows:write | Job create object | -| `update_job` | flows:write | Job object plus `jobId` | -| `delete_job` | flows:write | `{jobId}` | -| `enable_job` / `disable_job` | flows:write | `{jobId}` | -| `test_job_webhook_conditions` | flows:write | `{conditions?,webhook}` | -| `invoke_job` | runs:write | `{jobId,name?,prompt?,data?,idempotencyKey?}` | -| `stop_run` | runs:write | `{runId}` | -| `kill_run` | runs:write | `{runId}` | - -`list_runs` uses case-insensitive literal substring matching for `contextQuery`; matching rows contain only a bounded excerpt. `get_run` contains the complete context and the reusable `invocation.idempotency_key`, while its internal `claim_key` must not be reused. +| `get_job` | flows:read | Required string `jobId` | +| `create_job` | flows:write | Required `name`, `slug`, `promptTemplate`, `executionTargetId`; job fields below | +| `update_job` | flows:write | Same required job fields plus `jobId`; optional `expectedUpdatedAt` | +| `delete_job` | flows:write | Required string `jobId` | +| `enable_job` | flows:write | Required string `jobId` | +| `disable_job` | flows:write | Required string `jobId` | +| `list_runs` | runs:read | Optional `jobId`, `state`, `contextQuery`, `limit`, `cursor` | +| `get_run` | runs:read | Required string `runId` | +| `get_run_diagnostics` | runs:read | Required string `runId` | +| `invoke_job` | runs:write | Required string `jobId`; optional `name`, `prompt`, `data`, `idempotencyKey` | +| `stop_run` | runs:write | Required string `runId` | +| `kill_run` | runs:write | Required string `runId`; currently the same stop operation | +| `list_job_webhook_activity` | runs:read | Required `jobId`; optional integer `limit` (1–100, default 50) | +| `list_webhook_deliveries` | runs:read | Optional strings `provider`, `deliveryId`, `event`, `action`, `outcome`, `jobId`, `q`, `from`, `to`, `cursor`; integer `limit` (1–100, default 50) | +| `get_webhook_delivery` | runs:read | Required string `deliveryId` | +| `test_job_webhook_conditions` | flows:write | Required prepared JSON object `webhook`; optional `conditions` tree | +| `diagnose_exe_integration` | flows:write | Required string `connectionId` | + +The inventory is validated against every registered implementation tool. All required IDs are non-empty strings except numeric GitHub installation/repository IDs in trigger configuration. + +## Discovery inputs and outputs + +- `list_execution_targets({})` → `{"items":[{"id":"TARGET_ID","kind":"exe-vm","name":"Ephemeral exe.dev VMs","workspace":"ephemeral","cwd":"/home/exedev/workspace","agentKind":"codex","models":[],"efforts":["minimal","low","medium","high","xhigh"],"capabilities":["recovery","stop"]}]}`. Copy `id` into `executionTargetId`. Amp IDs have an `amp:` prefix and kind `amp`. Empty results require browser integration setup. Targets do not contain repository URLs. +- `list_exe_connections({})` → `{"items":[{"connectionId":"CONNECTION_ID","agentKind":"codex","tags":[]}]}` (selected fields). Use `connectionId` for integration diagnosis. +- `list_github_installations({})` → `{"items":[{"installationId":12345,"accountLogin":"YOUR_ORG","state":"active"}]}` (selected fields). Use numeric `installationId` in GitHub triggers; choose repository IDs in the browser. +- `list_cloudflare_tail_integrations({})` → `{"items":[{"integrationId":"INTEGRATION_ID","name":"Worker errors","referencedJobCount":0}]}` (selected fields). Use `integrationId` in Tail trigger configuration. +- `diagnose_exe_integration({"connectionId":"CONNECTION_ID"})` probes permissions and a disposable tagged VM's agent/model access, deleting that VM before returning. Example selected result: `{"ok":true,"connectionId":"CONNECTION_ID","agentKind":"codex","permissions":{"ok":true,"missing":[],"tags":[]},"agent":{"ok":true}}`. Inspect both permissions and agent results rather than assuming a successful tool response means all checks passed. Missing connections return `not_found`. + +## Job fields and creation + +| Field | Contract | +| --- | --- | +| `name` | Required trimmed string, 1–120 characters | +| `slug` | Required string matching `^[a-z][a-z0-9_-]{0,29}$`; unique within workspace | +| `promptTemplate` | Required string, 1–50,000 characters | +| `executionTargetId` | Required non-empty ID from target discovery | +| `runNameTemplate` | Optional string, max 500; defaults to empty | +| `concurrencyLimit` | Optional integer 1–50; defaults to 1 | +| `model` | Optional trimmed string, max 120; defaults to empty/provider default | +| `effort` | Optional trimmed string, max 40; choose target-supported values | +| `triggers` | Optional array, max 50; defaults to empty and server supplies a manual trigger | + +Do not submit credentials, unknown top-level fields, parameters or parameter overrides. Trigger objects contain `kind`, `config`, optional `enabled` (default true), and optional `id`/`slug` for preservation during edits. Kinds/configuration: + +- `manual`: `{}`. +- `schedule`: `{"cron":"0 9 * * 1-5","timezone":"UTC"}`. +- `webhook`: provider-specific configuration below, optional `conditions`. +- `jobLifecycle`: `{"sourceJobIds":["SOURCE_JOB_ID"],"states":["succeeded"]}`. States: `succeeded`, `failed`, `stopped`, `edited`. + +Webhook configurations: + +```json +[ + {"provider":"linear","projectId":"PROJECT_ID","matchRules":[{"type":"status","targetId":"STATUS_ID"}]}, + {"provider":"clickup","listId":"LIST_ID","matchRules":[{"type":"assignee","targetId":"USER_ID"}]}, + {"provider":"github","installationId":12345,"repositoryId":67890,"event":"pull_request","action":"opened"}, + {"provider":"cloudflareTail","integrationId":"INTEGRATION_ID"} +] +``` + +Match rule types: `owner`, `creator`, `status`, `label`, `assignee`, with non-empty string `targetId`. Linear/ClickUp require at least one rule; GitHub requires at least one rule or both event/action. Select actual resource IDs in the browser editor. This array illustrates alternative configurations, not a tool input. + +`create_job` input: + +```json +{"name":"Review recent changes","slug":"review-recent-changes","promptTemplate":"Clone REPOSITORY_URL and review the latest commit. {{trigger-1.prompt}}","executionTargetId":"TARGET_ID","concurrencyLimit":1,"triggers":[{"kind":"manual","config":{}}]} +``` + +Result includes (selected fields): + +```json +{"id":"JOB_ID","name":"Review recent changes","slug":"review-recent-changes","enabled":true,"executionTargetId":"TARGET_ID","concurrencyLimit":1,"currentRuns":0,"maxConcurrency":1,"updatedAt":"2026-10-10T09:00:00.000Z","triggers":[{"id":"TRIGGER_ID","slug":"trigger-1","kind":"manual","enabled":true,"config":{}}]} +``` + +Save `id`, trigger IDs/slugs and `updatedAt`. Full job results include prompt/configuration, timestamps, agent metadata and trigger reflection. `list_jobs({})` returns `{"items":[...jobs]}`; `get_job({"jobId":"JOB_ID"})` returns a single job. Creation errors include `conflict` for duplicate slug and `invalid_request` for invalid/unknown target or invalid fields. If creation's response is lost, list/find the job before recreating it. + +## Safe replacement and enable/delete + +`update_job` replaces configuration. Fetch first; preserve all intended fields and triggers; strip read-only fields. Example for a manual-only job: + +```json +{"jobId":"JOB_ID","expectedUpdatedAt":"2026-10-10T09:00:00.000Z","name":"Review recent changes","slug":"review-recent-changes","promptTemplate":"Clone REPOSITORY_URL and review the latest commit. Run relevant checks. {{trigger-1.prompt}}","executionTargetId":"TARGET_ID","runNameTemplate":"","concurrencyLimit":1,"model":"","triggers":[{"id":"TRIGGER_ID","slug":"trigger-1","kind":"manual","enabled":true,"config":{}}]} +``` + +Result is the saved job with new `updatedAt`. Preserve any automatic triggers too. Omission can reset optional settings or remove automatic triggers. On `stale_job`, fetch/reapply; omitting `expectedUpdatedAt` is last-writer-wins. Stable slugs survive edits when trigger identity/kind is retained; changing kind creates a new trigger identity. Inspect returned slugs rather than assuming numbering. + +`enable_job({"jobId":"JOB_ID"})` → `{"id":"JOB_ID","enabled":true}`; `disable_job({"jobId":"JOB_ID"})` → `{"id":"JOB_ID","enabled":false}`. `delete_job({"jobId":"JOB_ID"})` → `{"id":"JOB_ID","deleted":true}`; deletion also removes execution history/artifacts. Missing jobs return `not_found`. Saves can emit `edited` events; see [chaining](/recipes/chaining). + +## Invocation, run inspection, and retries + +`invoke_job` input: + +```json +{"jobId":"JOB_ID","name":"First review","prompt":"Focus on regressions","data":{"branch":"main"},"idempotencyKey":"review-first-1"} +``` + +Result: + +```json +{"invocationId":"INVOCATION_ID","runId":"RUN_ID","state":"queued","duplicate":false} +``` + +Optional `name`: trimmed 1–120 characters; `prompt`: max 50,000, default empty; `data`: JSON object; `idempotencyKey`: trimmed 1–200 characters and must not begin `manual:`. Retrying the same key for the same job returns the original IDs with `duplicate:true`, even if that run failed. Without a key, each call is a new invocation. Intentional reruns require a new key. Manual requests never coalesce; `queue_full` means capacity is exhausted. Disabled manual triggers return `operation_failed`. + +`list_runs({"jobId":"JOB_ID","state":"failed","contextQuery":"regression","limit":10})` → `{"items":[{"id":"RUN_ID","job_id":"JOB_ID","state":"failed"}],"nextCursor":null}` (selected fields). Pass a returned cursor for later pages. `limit` is 1–100, default 50; `contextQuery` is 1–50,000 characters and case-insensitive substring matching. The current repository uses SQL ILIKE: percent and underscore behave as wildcards; use get_run for full context. Current results do not include excerpts. + +Allowed state filters: `queued`, `starting`, `running`, `done`, `blocked`, `failed`, `ignored`, `succeeded`, `stopping`, `stopped`. + +`get_run({"runId":"RUN_ID"})` → a full run including `id`, `job_id`, `state`, rendered `prompt`, full `context`, `activity`, execution metadata and `invocation`. Example selected fields: + +```json +{"id":"RUN_ID","job_id":"JOB_ID","state":"succeeded","prompt":"Clone REPOSITORY_URL and review the latest commit. Focus on regressions","context":{"trigger-1":{"prompt":"Focus on regressions","data":{"branch":"main"}}},"invocation":{"trigger_id":"TRIGGER_ID"}} +``` + +Retain the submitted key for retries. Current `get_run` returns only internal `invocation.claim_key`, not `invocation.idempotency_key`; never pass that internal field back. `get_run_diagnostics({"runId":"RUN_ID"})` returns a diagnostic object with `runId`, `jobId`, `state`, `execution`, `trace`, `artifact`, `harnessLog`, `activity` and timestamps. These cover launch/prompt/output/cleanup and trace evidence, not credentials. Missing runs return `not_found`. + +`stop_run({"runId":"RUN_ID"})` → `{"id":"RUN_ID","state":"stopping"}`. Current `kill_run({"runId":"RUN_ID"})` returns the same result and uses the same operation. Both accept starting/running/blocked runs; queued or terminal runs return `operation_failed`. Neither guarantees immediate termination/slot release. Poll `get_run` and inspect cleanup. See [stop/retry](/work/stop-retry). + +## Webhook investigation and conditions + +`list_job_webhook_activity({"jobId":"JOB_ID","limit":10})` → `{"items":[{"id":"ACTIVITY_ID","provider":"linear","deliveryId":"PROVIDER_DELIVERY_ID","outcome":"accepted","detail":"...","receivedAt":"2026-10-10T09:00:00.000Z"}]}`. Use it for matching/rejected/duplicate/accepted evidence; it is not a full provider event history. + +`list_webhook_deliveries({"provider":"linear","jobId":"JOB_ID","limit":10})` → `{"items":[{"id":"DELIVERY_RECORD_ID","provider":"linear","deliveryId":"PROVIDER_DELIVERY_ID","event":"Issue","outcome":"accepted"}],"nextCursor":null}` (selected fields). Results are newest-first and cursor paginated. Provider/delivery/event/action/outcome filters are exact matches; `q` searches safe diagnostic text. **Current limitation:** `from` and `to` are accepted by the tool schema but the repository does not apply time-range filters; do not rely on them to bound results. + +`get_webhook_delivery({"deliveryId":"DELIVERY_RECORD_ID"})` accepts the internal record ID or provider delivery ID and returns delivery metadata plus `timeline` entries with `jobId`, `outcome`, `detail`, `createdAt`. Prefer the record ID to disambiguate deliveries. Secrets/raw payloads are never returned. Missing records return `not_found`. + +`test_job_webhook_conditions` input: + +```json +{"conditions":{"all":[{"fact":"webhook","path":"$.issue.title","operator":"startsWith","value":"Review"}]},"webhook":{"provider":"linear","issue":{"title":"Review latest changes"}}} +``` + +Result contains `decision: "match" | "no-match" | "error"` and plain JSON evaluation details. An invalid request/configuration yields `invalid_request`; evaluation failure yields an error decision. This preview does not authenticate the example, route an event, verify live GitHub state or invoke a job. See [condition operators and limits](/integrations/triggers). + +Current `get_run` does not include `output`, trace message contents or a client-facing retry key. To inspect findings, open `https://app.factorize.sh/job-runs/RUN_ID` or use REST trace pagination. `harness_log` is artifact metadata, not log bytes. Retain your submitted idempotency key. + +## Common errors and capability boundaries + +Tool errors are `code: message`. `invalid_token` needs reauthorization; `insufficient_scope` needs the listed scope; `invalid_request` needs corrected input; `not_found` means the ID is absent from the authorized workspace; `stale_job` needs refetch/reapply; `conflict` needs an unused job slug; `queue_full` needs capacity; `operation_failed` needs state/diagnostic inspection. Do not repeatedly retry a write with new identifiers after a lost response. + +MCP is a selected tool surface, **not full REST parity**. Signup, verification, integration credential management, authorized-client management, provider resource selection, schedule preview, specialized run status/trace pagination and retained-artifact replay have no corresponding tools in this inventory. Some REST operations require an interactive owner session rather than delegated tokens. Use the browser for setup/resource selection and [REST reference](/api/reference) for exact routes, restrictions and schemas. MCP cannot pass your conversational client's credentials to the execution agent. diff --git a/packages/docs/package.json b/packages/docs/package.json index c16dbf35..b62f72ea 100644 --- a/packages/docs/package.json +++ b/packages/docs/package.json @@ -5,6 +5,8 @@ "scripts": { "dev": "mint dev", "validate": "node scripts/validate.mjs", - "deploy": "mint deploy" + "deploy": "mint deploy", + "generate": "node scripts/exports.mjs", + "check:exports": "node scripts/exports.mjs --check" } } diff --git a/packages/docs/quickstart.mdx b/packages/docs/quickstart.mdx index 872d9b19..f85c16e4 100644 --- a/packages/docs/quickstart.mdx +++ b/packages/docs/quickstart.mdx @@ -1,34 +1,56 @@ --- -title: Quickstart -description: Configure authentication and create a job end to end. +title: Your first job +description: Run a hosted repository review through MCP. --- -## Prerequisites +## Set up in the browser -You need a Cloudflare Worker deployment, a Postmark server with a verified sender and transactional message stream, and an exe.dev account-level HTTPS API token allowed to run `ls`, `new`, `ssh`, and `rm`. Agents are installed on each newly-created VM. For Linear-driven jobs, also configure a Linear OAuth application. Set `POSTMARK_SERVER_TOKEN`, `POSTMARK_FROM_EMAIL`, `POSTMARK_MESSAGE_STREAM`, `APP_ORIGIN`, OAuth credentials, `LINEAR_WEBHOOK_SIGNING_SECRET`, `CREDENTIAL_ENCRYPTION_KEY`, and `SESSION_SIGNING_SECRET`. +1. Open [app.factorize.sh/auth/signup](https://app.factorize.sh/auth/signup). Sign up with **email and password** (12–200 characters), verify the email, then sign in. Use [resend verification](https://app.factorize.sh/auth/verify/request) if needed. +2. Open [Settings → Integrations](https://app.factorize.sh/settings). Add an exe.dev account token, test credentials, select the execution agent and VM tags, then save. Saving validates the agent/models on a temporary VM. Alternatively connect an Amp project and its access token. +3. Ensure the execution account can access your repository and the required model/integrations. For exe.dev, the account token must permit VM listing, creation, SSH and deletion (`ls`, `new`, `ssh`, `rm`). VM tags attach your execution integrations. Current exe.dev targets do **not** store a repository URL or checkout ref: put the repository URL and checkout instructions in the job prompt. +4. [Connect your MCP client](/mcp/overview), approve the four workflow scopes, and ask “List my Factorize jobs.” -Create a native Factorize account with a username, email and password. Verify your email, sign in, connect Linear if needed in Settings → Integrations, and configure an exe.dev execution target with its token, repository URL, optional checkout ref, agent, and VM tags. Tags attach the integrations required by the repository and agent. Use `list_execution_targets` or `GET /api/v1/execution-targets` before submitting `executionTargetId`. +These account, credential and consent steps happen in the browser. MCP can discover saved targets, manage jobs and invoke/inspect runs; it cannot sign you up, verify email, connect execution credentials or select provider resources. -## First API call +## Ask your agent -```bash -curl -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" "$APP_ORIGIN/api/v1/jobs" +Copy this request and replace the repository URL: + +> Show me my available execution targets. Create a manual job called ‘Review recent changes’ using my repository’s target. Have it clone https://github.com/YOUR_ORG/YOUR_REPO.git, review the latest commit and summarize any problems. Run it once and report the result. + +If several targets are available, choose one by its agent/account metadata. Target discovery does not imply a repository binding. + +Expected tools: + +1. `list_execution_targets({})`: choose a returned `id`; never invent one. Empty results mean browser execution setup is incomplete. +2. `list_jobs({})`: check whether this job already exists before creating it. +3. `create_job` with the input below. Save its returned `id` as `JOB_ID`. +4. `invoke_job` with `JOB_ID` and a stable key. Save `runId`. +5. `get_run({runId: RUN_ID})`: check periodically until terminal; inspect prompt, context and activity. Current MCP does not expose execution output: open the returned run in the browser trace view to read the review, or use authorized REST trace pagination. The agent should report the observed state and result link rather than invent findings. + +```json +{ + "name": "Review recent changes", + "slug": "review-recent-changes", + "executionTargetId": "TARGET_ID", + "promptTemplate": "Clone https://github.com/YOUR_ORG/YOUR_REPO.git into the workspace. Review the latest commit on the default branch, run relevant checks, and summarize any problems. {{trigger-1.prompt}}", + "concurrencyLimit": 1, + "triggers": [{"kind": "manual", "config": {}}] +} ``` -Create a manual job: +Invoke input: -```bash -curl -X POST "$APP_ORIGIN/api/v1/jobs" \ - -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" -H 'content-type: application/json' \ - -d '{"name":"Review changes","slug":"review-changes","promptTemplate":"Review: {{trigger-1.prompt}}","executionTargetId":"TARGET_ID","triggers":[{"kind":"manual","config":{}}]}' +```json +{"jobId":"JOB_ID","prompt":"Review now","idempotencyKey":"review-recent-changes-first-run"} ``` -Invoke it with a reusable idempotency key: +Example invocation result (identifiers are illustrative): -```bash -curl -X POST "$APP_ORIGIN/api/v1/jobs/JOB_ID/invocations" \ - -H "Authorization: Bearer $FACTORIZE_ACCESS_TOKEN" -H 'content-type: application/json' \ - -d '{"prompt":"Review the latest commit","idempotencyKey":"review-2026-09-17"}' +```json +{"invocationId":"INVOCATION_ID","runId":"RUN_ID","state":"queued","duplicate":false} ``` -The response is `202`. Query `/runs` and then `/runs/RUN_ID`; stop an active run with `/runs/RUN_ID/stop`, or force any non-terminal run to release its slot with `/runs/RUN_ID/kill`. +Success means target discovery returned a usable target, the created job returned an `id` and manual trigger with a stable slug, invocation returned `runId`, and `get_run` reports `succeeded` with the rendered repository prompt. Open its browser trace and confirm the review output; state alone does not prove the review findings. Submission alone is not completion. You can also open `https://app.factorize.sh/job-runs/RUN_ID` to inspect it. + +If the request times out, repeat **the invocation with the same key**, not job creation; it returns the original run with `duplicate: true`. A failed run is still the original run for that key. Follow [failed-run troubleshooting](/troubleshooting/runs) before requesting a new run with a new key. After a successful manual review, add a [schedule](/recipes/scheduled-review). diff --git a/packages/docs/recipes/chaining.mdx b/packages/docs/recipes/chaining.mdx new file mode 100644 index 00000000..e64ccc7c --- /dev/null +++ b/packages/docs/recipes/chaining.mdx @@ -0,0 +1,20 @@ +--- +title: Chain jobs +description: Start a follow-up after another job finishes or is edited. +--- + +User request: + +> After my review job succeeds, run a second job to inspect its findings. Keep the follow-up manually runnable. + +Discover source job ID with `list_jobs`, and choose a target with `list_execution_targets`. Create the destination with required job fields and: + +```json +{"kind":"jobLifecycle","enabled":true,"config":{"sourceJobIds":["SOURCE_JOB_ID"],"states":["succeeded"]}} +``` + +Read the destination's returned trigger slug, then preserve all writable fields/triggers while setting its prompt to `Inspect source job {{trigger-2.sourceJobId}} and run {{trigger-2.sourceRunId}}. Summarize its findings.` Use the actual slug. Context includes identifiers, `state` and `completedAt`, not the source output. The execution agent must have its own authorized way to retrieve source results (for example its own Factorize MCP access); the conversational client's authorization is not forwarded. If unavailable, have the conversational agent inspect the source output in the browser or via REST trace pages and manually invoke the destination with output in `data` instead of claiming automatic output transfer. + +Expected result: a successful source run produces a destination run. Invoke the source with a stable key, wait for success, then inspect destination runs and full context to verify source job/run IDs, then inspect output in the browser. Avoid cycles and make prompts safe for repeated events; automatic signals may coalesce. + +Available states are `succeeded`, `failed`, `stopped`, and `edited`. **Edited** fires on successful saves (including enable/disable), even unchanged saves, not creation or run-state changes. Edited context has `source_job_id`, `event: "edited"`, and `edited_at`; it has no source run ID. Only same-tenant enabled subscribers match, and a job cannot subscribe to its own edits. Pending edit events wait while disabled/unmatched; deleting the source or removing the trigger discards them. Verify an edited recipe by saving the source and inspecting the destination context. diff --git a/packages/docs/recipes/linear-job.mdx b/packages/docs/recipes/linear-job.mdx new file mode 100644 index 00000000..c1604ced --- /dev/null +++ b/packages/docs/recipes/linear-job.mdx @@ -0,0 +1,20 @@ +--- +title: Run a job from Linear +description: Connect a workspace, select a project and match issues. +--- + +User request: + +> When an issue in my selected Linear project moves to my selected Ready status, run the repository agent to investigate it and report the result. + +In browser [Settings → Integrations](https://app.factorize.sh/settings), connect Linear, approve workspace access, and select an accessible project/status in the job editor. The execution account separately needs repository and Linear access if the prompt asks it to read/update Linear. MCP does not list Linear projects/statuses or connect accounts; use browser resource selection to obtain the IDs. + +Create a job with the required [job fields](/mcp/tools), repository instructions, and this trigger (replace both IDs): + +```json +{"kind":"webhook","enabled":true,"config":{"provider":"linear","projectId":"PROJECT_ID","matchRules":[{"type":"status","targetId":"STATUS_ID"}]}} +``` + +Factorize adds the manual trigger. Fetch the saved job to obtain the webhook slug/reflection. Safely replace configuration with a prompt such as `Clone REPOSITORY_URL. Investigate this Linear issue: {{trigger-2.issue.title}}. Issue context: {{trigger-2}}. Run relevant checks and report evidence.` Use the actual webhook slug, preserving all other configuration. + +Expected result: a matching issue change delivers an event and starts a run; all configured rules must match. Move one test issue into the selected status. Verify `list_webhook_deliveries({"provider":"linear","jobId":"JOB_ID"})`, inspect the delivery timeline and `list_job_webhook_activity`, then check the run's firing trigger, issue context, then inspect output in the browser trace. Factorize does not automatically post execution output to Linear. For absent/rejected events follow [jobs not firing](/troubleshooting/events). diff --git a/packages/docs/recipes/scheduled-review.mdx b/packages/docs/recipes/scheduled-review.mdx new file mode 100644 index 00000000..92123cc3 --- /dev/null +++ b/packages/docs/recipes/scheduled-review.mdx @@ -0,0 +1,18 @@ +--- +title: Schedule a repository review +description: Turn a successful manual review into daily automation. +--- + +User request: + +> Review the latest commit in https://github.com/YOUR_ORG/YOUR_REPO.git every weekday at 09:00 UTC. Keep a manual trigger and report findings in Factorize. + +First complete a [manual run](/quickstart). Fetch the job, preserve its writable configuration and manual trigger identity, and append: + +```json +{"kind":"schedule","enabled":true,"config":{"cron":"0 9 * * 1-5","timezone":"UTC"}} +``` + +Save with `update_job` and `expectedUpdatedAt`. Fetch again to discover the schedule's stable slug. Use a repository review prompt that works without manual context; optionally add `Scheduled at {{trigger-2.occurredAt}}` using the actual slug. Preserve the entire trigger list when saving this prompt. + +Expected result: an enabled weekday schedule and one queued/executing run at the next matching occurrence (subject to queue coalescing). Verify cron/timezone and next occurrence in the browser editor, then `list_runs({"jobId":"JOB_ID"})` and `get_run`: the invocation's trigger ID and context must match the schedule, and the browser trace output must contain the review. Do not claim automation verified until a scheduled occurrence has actually run. diff --git a/packages/docs/scripts/content.mjs b/packages/docs/scripts/content.mjs new file mode 100644 index 00000000..4fd03a28 --- /dev/null +++ b/packages/docs/scripts/content.mjs @@ -0,0 +1,39 @@ +import { readFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { root } from "./exports.mjs"; + +export function checkInventory(implementation, reference) { + const actual = [...implementation.matchAll(/\btool\("([^"]+)"/g)].map(match => match[1]).sort(); + const documented = [...reference.matchAll(/^\| `([^\`]+)` \|/gm)].map(match => match[1]).filter(name => name.includes("_")).sort(); + if (!actual.length || JSON.stringify(actual) !== JSON.stringify(documented)) throw new Error("MCP inventory differs from registered tools"); +} + +export async function checkContent() { + const config = JSON.parse(await readFile(resolve(root, "docs.json"), "utf8")); + const groups = config.navigation.groups; + const expected = ["Get started", "Work with your agent", "Automate jobs", "Troubleshooting", "Reference", "Self-hosting"]; + if (JSON.stringify(groups.map(g => g.group)) !== JSON.stringify(expected)) throw new Error("Task navigation order changed"); + const pages = groups.flatMap(g => g.pages).filter(page => typeof page === "string"); + const rest = groups.find(group => group.group === "Reference").pages.find(page => page.openapi); + if (rest?.openapi !== "/openapi.yaml") throw new Error("Missing rendered REST contract"); + if (new Set(pages).size !== pages.length) throw new Error("Duplicate navigation page"); + const guides = new Map(await Promise.all(pages.map(async name => [name, await readFile(resolve(root, name + ".mdx"), "utf8")]))); + for (const [name, body] of guides) { + if (!/^---\ntitle: .+\ndescription: .+\n---\n/.test(body)) throw new Error(`Invalid frontmatter: ${name}`); + for (const match of body.matchAll(/(?:\]\(|href=")(\/[^)"#]+)(?:#[^)" ]*)?/g)) { + const link = match[1].slice(1); + if (!pages.includes(link)) await readFile(resolve(root, link)); + } + } + const main = ["index", "quickstart", "mcp/overview"].map(name => guides.get(name)).join("\n"); + for (const url of ["https://app.factorize.sh", "https://app.factorize.sh/mcp"]) if (!main.includes(url)) throw new Error("Missing hosted URL"); + for (const phrase of ["list_execution_targets", "create_job", "invoke_job", "get_run", "idempotencyKey", "browser", "output"]) if (!guides.get("quickstart").includes(phrase)) throw new Error(`Incomplete first-job guide: ${phrase}`); + if (/Worker secrets|POSTMARK_SERVER_TOKEN|LINEAR_CLIENT_SECRET|Cloudflare account/.test(main)) throw new Error("Operator prerequisite in main onboarding"); + for (const body of guides.values()) if (/username\/password|username, email|Job create object|mirrors REST/.test(body)) throw new Error("Stale auth or capability claim"); + const reference = guides.get("mcp/tools"); + checkInventory(await readFile(resolve(root, "../api/src/protected-api.ts"), "utf8"), reference); + for (const term of ["expectedUpdatedAt", "replaces configuration", "duplicate", "manual:", "edited", "Current", "not full REST parity"]) if (!reference.includes(term)) throw new Error(`Missing contract detail: ${term}`); + const readme = await readFile(resolve(root, "../../README.md"), "utf8"); + if (!readme.includes("https://app.factorize.sh/mcp") || readme.indexOf("Optional self-hosting") < readme.indexOf("Connect a supported")) throw new Error("README positioning drift"); + console.log(`Validated ${pages.length} navigation pages, local links, hosted workflow and complete MCP inventory.`); +} diff --git a/packages/docs/scripts/content.test.mjs b/packages/docs/scripts/content.test.mjs new file mode 100644 index 00000000..9be46aa9 --- /dev/null +++ b/packages/docs/scripts/content.test.mjs @@ -0,0 +1,25 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { checkInventory, checkContent } from "./content.mjs"; +import { root, renderExports, syncExports } from "./exports.mjs"; + +test("all navigation pages and local links resolve and hosted contracts remain complete", checkContent); +test("inventory rejects a missing, invented, or duplicated tool", async () => { + const implementation = await readFile(resolve(root, "../api/src/protected-api.ts"), "utf8"); + const reference = await readFile(resolve(root, "mcp/tools.mdx"), "utf8"); + for (const changed of [ + reference.replace(/^\| `get_run_diagnostics`.*\n/m, ""), + reference + "\n| `invented_tool` | flows:read | {} |", + reference + "\n| `get_run` | runs:read | {} |", + ]) assert.throws(() => checkInventory(implementation, changed), /inventory differs/); +}); +test("exports include every maintained guide, lifecycle edited and actionable MCP contracts", async () => { + const exports = await renderExports(); + const full = exports["llms-full.txt"]; + for (const token of ["https://app.factorize.sh/mcp", "expectedUpdatedAt", "idempotencyKey", "get_run_diagnostics", "diagnose_exe_integration", "list_webhook_deliveries", "get_webhook_delivery", "edited"]) assert.ok(full.includes(token), token); + assert.ok(full.indexOf("## Connect your agent") < full.indexOf("## REST API reference")); + assert.ok(full.length > 40000); + await syncExports(true); +}); diff --git a/packages/docs/scripts/exports.mjs b/packages/docs/scripts/exports.mjs new file mode 100644 index 00000000..3fed002f --- /dev/null +++ b/packages/docs/scripts/exports.mjs @@ -0,0 +1,45 @@ +import { readFile, writeFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; + +export const root = resolve(import.meta.dirname, ".."); + +export async function renderExports() { + const config = JSON.parse(await readFile(resolve(root, "docs.json"), "utf8")); + const summary = ["# Factorize", "", "Hosted workflow: connect your agent → create a job → run it → inspect the result → automate it.", "", "Application: https://app.factorize.sh", "MCP (Streamable HTTP + OAuth): https://app.factorize.sh/mcp", "", "Browser: email/password signup, verification, execution/provider connections and consent.", "MCP: discover targets, manage jobs, invoke with retained idempotency keys, inspect state/context/diagnostics.", "Current MCP does not return execution output; inspect browser traces or REST trace pages. REST is not full MCP parity.", ""]; + const full = [...summary, "Generated from maintained guides in navigation order. Do not edit this file directly.", ""]; + for (const group of config.navigation.groups) { + summary.push(`## ${group.group}`, ""); + for (const entry of group.pages) { + if (typeof entry !== "string") { + summary.push(`- [${entry.group}](https://docs.factorize.sh/openapi.yaml): Complete generated REST schemas and operations`); + full.push("## REST operations", "Contract: https://docs.factorize.sh/openapi.yaml", "The site renders this exact generated contract under Reference → REST operations.", ""); + continue; + } + const name = entry; + const source = await readFile(resolve(root, `${name}.mdx`), "utf8"); + const match = source.match(/^---\n([\s\S]*?)\n---\n/); + if (!match) throw new Error(`Missing frontmatter: ${name}`); + const title = match[1].match(/^title: (.+)$/m)?.[1]; + const description = match[1].match(/^description: (.+)$/m)?.[1]; + summary.push(`- [${title}](https://docs.factorize.sh/${name === "index" ? "" : name}): ${description}`); + const body = source.slice(match[0].length) + .replace(/]*>|<\/CardGroup>/g, "") + .replace(/]*title="([^"]+)"[^>]*href="([^"]+)"[^>]*>([\s\S]*?)<\/Card>/g, "[$1]($2): $3") + .replace(/\]\(\/(?!\/)([^)]+)\)/g, "](https://docs.factorize.sh/$1)"); + full.push(`## ${title}`, `Source: https://docs.factorize.sh/${name === "index" ? "" : name}`, "", body.trim(), ""); + } + summary.push(""); + } + summary.push("## Machine-readable REST reference", "", "- https://docs.factorize.sh/openapi.yaml", "- https://docs.factorize.sh/llms-full.txt", ""); + return { "llms.txt": summary.join("\n"), "llms-full.txt": full.join("\n") }; +} + +export async function syncExports(check = false) { + for (const [name, content] of Object.entries(await renderExports())) { + if (check) { + if (await readFile(resolve(root, name), "utf8") !== content) throw new Error(`${name} is stale; run npm run generate --workspace=factorize-docs`); + } else await writeFile(resolve(root, name), content); + } +} +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) await syncExports(process.argv.includes("--check")); diff --git a/packages/docs/scripts/validate.mjs b/packages/docs/scripts/validate.mjs index 4d5765fa..f7282c2e 100644 --- a/packages/docs/scripts/validate.mjs +++ b/packages/docs/scripts/validate.mjs @@ -1,9 +1,11 @@ -import { readFile } from "node:fs/promises"; import { resolve } from "node:path"; import { execFileSync } from "node:child_process"; +import { checkContent } from "./content.mjs"; +import { syncExports } from "./exports.mjs"; -const root = resolve(import.meta.dirname, ".."); -for (const file of ["docs.json", "llms.txt", "llms-full.txt"]) await readFile(resolve(root, file)); -execFileSync("npm", ["run", "check:openapi"], { cwd: resolve(root, "../.."), stdio: "inherit" }); -execFileSync("npm", ["test", "--workspace=factorize", "--", "test/api-contract.test.ts"], { cwd: resolve(root, "../.."), stdio: "inherit" }); -console.log("Validated generated OpenAPI, executable operation equality, Mintlify configuration, and LLM exports."); +await checkContent(); +await syncExports(true); +execFileSync(process.execPath, ["--test", "scripts/content.test.mjs"], { cwd: resolve(import.meta.dirname, ".."), stdio: "inherit" }); +execFileSync("npm", ["run", "check:openapi"], { cwd: resolve(import.meta.dirname, "../../.."), stdio: "inherit" }); +execFileSync("npm", ["test", "--workspace=factorize", "--", "test/api-contract.test.ts", "test/docs-workflows.test.ts"], { cwd: resolve(import.meta.dirname, "../../.."), stdio: "inherit" }); +console.log("Validated OpenAPI, documentation example contracts, navigation/links, MCP inventory and generated exports."); diff --git a/packages/docs/self-hosting/configuration.mdx b/packages/docs/self-hosting/configuration.mdx new file mode 100644 index 00000000..23464a3d --- /dev/null +++ b/packages/docs/self-hosting/configuration.mdx @@ -0,0 +1,68 @@ +--- +title: Operator configuration +description: Email, OAuth applications, webhooks, and Worker secrets. +--- + +These steps apply only to your own deployment. Hosted Factorize users connect existing accounts in [Settings](https://app.factorize.sh/settings); they do not register Factorize OAuth applications or set Worker secrets. + +Register provider applications for your deployment origin. Linear requires Issues and Issue labels webhooks and fresh workspace authorization after subscription changes; ClickUp registers its task webhook on connection. Configure the GitHub App credentials and webhook settings for your deployment using the template in `packages/api/.dev.vars.example` and the executable callbacks/webhook routes in `packages/api/src/worker.ts`. + +## Account authentication + +Factorize owns authentication in PostgreSQL. Create a native account at `/auth/signup` with an email address and a password of 12–200 characters. Emails are case-insensitive. Verify the email before signing in at `/auth/login`; email plus password are accepted. Linear is connected after sign-in from **Settings → Integrations**, only for Linear-backed jobs. + +Postmark sends one-hour, single-use verification and password-reset links. `/auth/verify/request` resends verification; `/auth/password-reset` handles recovery. Links never appear in application responses or logs. Passwords use salted PBKDF2-SHA-256. **Change password** in the account menu requires the current password. Password reset, password change and sign-out invalidate existing sessions via membership session versions, including delegated API credentials. + +Before deploying, configure `POSTMARK_SERVER_TOKEN` as a **production GitHub environment secret**. The deployment copies it to a Worker secret; the verified sender and transactional message stream are non-secret Worker vars in `packages/api/wrangler.jsonc`. For a manual Postmark preflight, set the following environment variables along with `APP_ORIGIN`: + +| Setting | Required value | +| --- | --- | +| `POSTMARK_SERVER_TOKEN` | Postmark **server** API token for the sending server; never an account token or a committed value | +| `POSTMARK_FROM_EMAIL` | Plain email address on a verified Postmark sender signature or verified domain | +| `POSTMARK_MESSAGE_STREAM` | Active **transactional** stream ID, commonly `outbound` | + +`APP_ORIGIN` must be the canonical HTTPS origin, without a trailing slash. Run `npm run auth:validate-email --workspace=factorize` manually when needed: it checks the server token/stream with Postmark and sends one preflight email from/to the configured sender, rejecting unverified senders or sending failures. It prints no credentials. Missing configuration fails the manual check. The deploy workflow does not run this check or send a preflight email. Runtime signup and recovery also fail closed if configuration or delivery fails; users can resend verification after a delivery failure. Local mail testing needs an HTTPS origin and a separate Postmark test server/sender; automated tests mock Postmark and never send mail. + +### Existing account migration + +Apply `0008_native_accounts.sql` and `0009_remove_auth_usernames.sql` before deploying this code. They reject ambiguous legacy emails that differ only in case (reconcile those identities before retrying migration), preserve tenant IDs, memberships, jobs and encrypted Linear connections, and backfill explicit Linear organization-to-workspace mappings. Existing Linear-only users choose **Forgot password or previously signed in with Linear?**, receive a reset email at their existing address, and set a password. Email possession is required; signup cannot replace an existing account's credentials. Existing native users keep their passwords and may sign in by email; unverified accounts must verify first. A reset never promotes a member to owner. An account with multiple existing owner memberships currently opens the oldest workspace; no new workspace-switching UI is introduced. + +Linear OAuth requires an authenticated owner, binds state to that user/workspace, stores the connection there, and never creates a Factorize session. A Linear organization already bound to another workspace cannot be claimed. Existing webhook routes resolve the explicit mapping. Do not delete that binding to work around an account-recovery problem. + +### Authentication verification + +`npm run check` runs unit/contract tests and Postmark preflight tests. CI also runs the real PostgreSQL authentication suite against a disposable service. To run it locally, set `AUTH_TEST_DATABASE_URL` to an isolated PostgreSQL server whose user can create/drop test databases, then run `npm test --workspace=factorize -- --run test/native-auth.postgres.test.ts`. The suite creates and removes its own database and applies every migration, including a legacy connection fixture before the auth migration. + +## Configure Linear + +Use authorization-code OAuth and enable **Webhooks** on the OAuth application. Configure: + +| Setting | Value | +| --- | --- | +| Callback URL | `https://your-domain.example/auth/linear/callback` | +| Webhook URL | `https://your-domain.example/webhooks/linear` | +| Webhook events | **Issues** and **Issue labels** | +| Webhook secret | Store as `LINEAR_WEBHOOK_SIGNING_SECRET` | + +After changing the webhook settings, re-authorize existing workspaces so Linear creates a fresh workspace subscription. + +## Configure ClickUp + +Create a ClickUp OAuth application with the callback URL `https://your-domain.example/auth/clickup/callback`, then store its client ID and secret in `CLICKUP_CLIENT_ID` and `CLICKUP_CLIENT_SECRET`. Connecting ClickUp from Settings registers the signed task webhook automatically. ClickUp triggers can filter a list by status, tag, assignee, or creator; all configured rules must match. + + +## Configuration reference + +| Variable | Purpose | +| --- | --- | +| `LINEAR_CLIENT_ID` | Linear OAuth client ID | +| `LINEAR_CLIENT_SECRET` | Linear OAuth client secret | +| `LINEAR_WEBHOOK_SIGNING_SECRET` | Verifies Linear webhook signatures | +| `CLICKUP_CLIENT_ID` | ClickUp OAuth client ID | +| `CLICKUP_CLIENT_SECRET` | ClickUp OAuth client secret; ClickUp also uses a per-installation webhook secret stored encrypted by Factorize | +| `CREDENTIAL_ENCRYPTION_KEY` | Base64-encoded 32-byte key for encrypted credentials | +| `SESSION_SIGNING_SECRET` | Independent secret for signed browser sessions | +| `APP_ORIGIN` | Public Worker origin, configured in `packages/api/wrangler.jsonc` | +| `OAUTH_KV` | KV binding containing OAuth clients, grants, refresh tokens, and revocation state | + +Never commit `.dev.vars` or production secret values. The included `.dev.vars.example` is a safe template. diff --git a/packages/docs/self-hosting/deployment.mdx b/packages/docs/self-hosting/deployment.mdx new file mode 100644 index 00000000..2a4a3bee --- /dev/null +++ b/packages/docs/self-hosting/deployment.mdx @@ -0,0 +1,12 @@ +--- +title: Optional self-hosting +description: Deploy your own Factorize instance. +--- + +Hosted users can start at [app.factorize.sh](https://app.factorize.sh) without deploying anything. Self-hosting is for operators who want to own the application infrastructure. + +The Worker lives in `packages/api`, React frontend in `packages/app`, and generated public client in `packages/api-client`. Use Node 24 and the root lockfile. Follow the [API-first deployment and rollback gates](https://github.com/GenerationSoftware/factorize/blob/main/docs/package-migration.md) before deploying static assets. Preserve Worker identity, bindings, migrations, and old hashed assets. + +Install dependencies with `npm ci`. Configure `packages/api/wrangler.jsonc`, PostgreSQL, OAuth KV and artifact storage, set the final HTTPS `APP_ORIGIN`, then build with `npm run build:app` and deploy with `npm run deploy:app`. See [configuration](/self-hosting/configuration) before deployment. + +For local development, copy `packages/api/.dev.vars.example` to `packages/api/.dev.vars`, supply local configuration, and use `npm run dev`. Development uses HTTPS at `https://localhost:5173`; use that origin for local callbacks. The migration guide covers local database setup. Never commit secrets. diff --git a/packages/docs/self-hosting/operations.mdx b/packages/docs/self-hosting/operations.mdx new file mode 100644 index 00000000..70c1ef7a --- /dev/null +++ b/packages/docs/self-hosting/operations.mdx @@ -0,0 +1,12 @@ +--- +title: Operations and advanced trace recovery +description: Operator checks, retained artifacts, and rollout evidence. +--- + +Use the [deployment runbook](https://github.com/GenerationSoftware/factorize/blob/main/docs/package-migration.md) and [trace rollout runbook](https://github.com/GenerationSoftware/factorize/blob/main/docs/trace-rollout-runbook.md) for retention, canary gates and rollback. `npm run check` checks package boundaries, generated contracts, runtime tests and builds. The PostgreSQL auth suite uses an isolated database; see configuration for migration verification. + +`get_run_diagnostics` exposes declared trace sources, projection evidence, artifacts and fallback use. A trace may be partial when collection fails. A `matched` reconciliation result verifies the live prefix against the terminal artifact; missing evidence does not prove completeness. + +Trace replay is REST-only and requires an interactive owner session with `runs:write`: `POST /api/v1/runs/{runId}/trace/replay` with a UUID `requestId` and `source` (`primary` or `native_session`). Reuse the request ID after interruption. Limit: ten requests per tenant per minute. Results distinguish projected, already projected, skipped and unrecoverable. Replay preserves artifacts; expired/deleted bytes cannot be recovered. Historical Codex tool calls require retained native session bytes. + +Cloudflare Tail infrastructure is optional: use the [Tail relay deployment guide](https://github.com/GenerationSoftware/factorize/blob/main/docs/cloudflare-tail.md). Hosted users still supply their own source Worker/relay integration. diff --git a/packages/docs/troubleshooting/connection.mdx b/packages/docs/troubleshooting/connection.mdx new file mode 100644 index 00000000..eed30c04 --- /dev/null +++ b/packages/docs/troubleshooting/connection.mdx @@ -0,0 +1,15 @@ +--- +title: Connection problems +description: Recover authorization, scopes, and execution targets. +--- + +| Symptom | Action | +| --- | --- | +| Browser consent fails or is cancelled | Sign in to the correct verified Factorize owner account, restart authorization from the client, and approve the requested scopes. Finish signup/email verification separately before restarting. | +| Client never connects | Confirm the exact URL `https://app.factorize.sh/mcp`, remote Streamable HTTP and OAuth support. Open the client's MCP status view and authenticate; use [client-specific instructions](/mcp/overview). | +| `invalid_token` or access disappears | Reauthorize the client. Password resets/changes and sign-out invalidate delegated credentials. An expired access token needs client refresh or renewed login. | +| `insufficient_scope` | Reconnect and grant `flows:read` for discovery, `flows:write` for job edits/diagnosis, `runs:read` for inspection and `runs:write` for invocation/stop. | +| `list_execution_targets` returns no items | In browser Settings, test and save an exe.dev or Amp integration in the same workspace. MCP cannot create credential-bearing connections. | +| Target exists but repository/model access fails | Test the saved execution integration and check execution-account repository/model access and VM tags. For exe.dev, `diagnose_exe_integration` uses the saved connection ID and creates/deletes a temporary VM. | + +To reconnect access, open [Settings → Authorized clients](https://app.factorize.sh/settings/authorized-clients), revoke the old client if necessary, remove/reconnect its authorization in the MCP client, then authorize again. Verify with “List my Factorize jobs” followed by “List my execution targets.” Revocation affects access, not stored jobs. Provider reconnection is separate: use [Settings → Integrations](https://app.factorize.sh/settings). diff --git a/packages/docs/troubleshooting/events.mdx b/packages/docs/troubleshooting/events.mdx new file mode 100644 index 00000000..49216e14 --- /dev/null +++ b/packages/docs/troubleshooting/events.mdx @@ -0,0 +1,13 @@ +--- +title: Jobs not firing +description: Verify automation from provider event to accepted run. +--- + +1. Fetch `get_job`; confirm the job and intended trigger are enabled. Check schedule timezone/cron, selected provider resources, and all matching rules. +2. Make one controlled matching provider event. Ask for `list_webhook_deliveries` filtered by `provider` and `jobId`; if nothing is found, search by provider alone since unmatched deliveries may not link the job. +3. Use the returned delivery's identifier with `get_webhook_delivery` to inspect its safe timeline. Use `list_job_webhook_activity` for matching, rejected, duplicate and accepted activity. No raw payloads or secrets are returned. +4. If no delivery appears, reconnect the provider in Settings, check resource access/app installation and provider delivery status. Ask the hosted operator to investigate transport/subscription failures; hosted users do not configure Factorize's webhook signing secrets. +5. If delivery appears but no run does, check event/action selection, match rules and conditions. `test_job_webhook_conditions` previews prepared example context only; it does not authenticate or deliver an event. +6. Check `list_runs`: automatic occurrences coalesce while a run is queued. An accepted run may be waiting for an active slot. Query the provider itself for authoritative work. + +For schedules, verify the next occurrence in the browser editor, timezone and enabled state, then inspect runs after that time. For lifecycle triggers, verify source IDs/state selection and same-tenant source jobs. A destination cannot subscribe to its own edits. See [trigger configuration](/integrations/triggers). diff --git a/packages/docs/troubleshooting/runs.mdx b/packages/docs/troubleshooting/runs.mdx new file mode 100644 index 00000000..dbf79c3a --- /dev/null +++ b/packages/docs/troubleshooting/runs.mdx @@ -0,0 +1,21 @@ +--- +title: Failed or stuck runs +description: Investigate evidence, fix the cause, and verify recovery. +--- + +Ask: + +> Investigate run RUN_ID. Show its prompt and lifecycle diagnostics, and link to its browser trace for output. Identify the failure and whether it changed anything externally. Do not create a duplicate run; recommend a safe recovery. + +Call `get_run({"runId":"RUN_ID"})` then `get_run_diagnostics({"runId":"RUN_ID"})`. Expected evidence includes `state`, `execution`, `trace`, `artifact`, `harnessLog` and `activity`. Check launch, prompt delivery, output capture, claim release and cleanup rather than treating a missing trace as proof the agent never ran. + +| Evidence | Recovery | +| --- | --- | +| Queued | Inspect active runs/concurrency with `get_job`; wait for a slot. | +| Launch or permission failure | Browser-test the execution connection; check repository/model access and tags. Use `list_exe_connections` then `diagnose_exe_integration({"connectionId":"CONNECTION_ID"})` if appropriate. This probe uses a disposable VM. | +| Wrong/empty prompt values | Read actual trigger slug/reflection and persisted context; safely replace the full job configuration. | +| Failed with useful output | Fix the reported cause, inspect the browser trace and check external changes, then request a new manual run with a new idempotency key. | +| Starting/running/blocked but stuck | Request `stop_run`, poll, and inspect cleanup. `kill_run` currently has identical semantics. Escalate persistently stuck runs to the hosted operator with run ID and safe diagnostics. | +| Missing/partial trace | Inspect output and artifact state; ask the owner/operator about REST-only retained-artifact replay. See [advanced operations](/self-hosting/operations). | + +Worked recovery configuration: use the original job ID and `invoke_job({"jobId":"JOB_ID","prompt":"Retry after correcting repository access","idempotencyKey":"investigation-RUN_ID-retry-1"})` only after fixing the cause and confirming the old run is terminal. Expected result is a **new** run ID. Verify its rendered prompt/state with `get_run` and successful output in the browser trace; a diagnostic probe passing does not itself prove the job succeeds. diff --git a/packages/docs/work/jobs.mdx b/packages/docs/work/jobs.mdx new file mode 100644 index 00000000..642d9555 --- /dev/null +++ b/packages/docs/work/jobs.mdx @@ -0,0 +1,12 @@ +--- +title: Create and edit jobs +description: Discover a target and replace configuration safely. +--- + +Ask: “List execution targets and jobs, then create a review job for this repository.” Use [the first-job input](/quickstart) and [MCP tool contract](/mcp/tools). Reuse an existing job when its slug/purpose matches; job creation has no idempotency key. + +`update_job` **replaces configuration**, rather than patching one field. Always call `get_job` first. Build a write object containing `jobId`, `name`, `slug`, `promptTemplate`, `executionTargetId`, `runNameTemplate`, `concurrencyLimit`, `model`, optional `effort`, and the full intended `triggers` array. Preserve each existing trigger's `id`, `slug`, `kind`, `enabled`, and writable `config`. Strip read-only response fields (`jobId` inside triggers, timestamps, reflection, secretConfigured and destination). Do not pass the entire read response unchanged. + +Supply `expectedUpdatedAt` from the fetched job's `updatedAt` to protect against concurrent edits. On `stale_job`, fetch again and reapply the desired changes. Omitting it retains last-writer-wins behavior. Omitted optional configuration resets to defaults; omitted triggers remove the configured automatic triggers. Preserve all triggers you want to keep. + +After saving, call `get_job` and compare prompt, target and triggers. `enable_job` and `disable_job` change enabled state without rebuilding configuration. Disabling automation does not stop an existing run. Job saves can trigger `edited` lifecycle subscribers. Deleting a job removes its execution history/artifacts; inspect and retain anything needed first. diff --git a/packages/docs/work/prompts.mdx b/packages/docs/work/prompts.mdx new file mode 100644 index 00000000..de20fb16 --- /dev/null +++ b/packages/docs/work/prompts.mdx @@ -0,0 +1,19 @@ +--- +title: Write job prompts +description: Use stable trigger context and explicit execution instructions. +--- + +Write the repository URL, checkout branch/ref, task, validation and reporting requirements explicitly. Execution targets select an account/agent, not a repository. Example: + +```text +Clone https://github.com/YOUR_ORG/YOUR_REPO.git. Review the latest commit, +run relevant tests, and report problems with file paths and evidence. +Additional request: {{trigger-1.prompt}} +Manual data: {{trigger-1.data}} +``` + +Use `get_job` to discover each trigger's stable `slug` and `reflection.paths`. Never assume an automatic trigger is `trigger-1`. Mustache renders only the firing trigger's context: manual has `prompt` and `data`; schedule currently has `occurredAt`, `externalId` and `metadata.timezone`; provider context contains prepared delivery fields (Linear `issue`, ClickUp `task`); terminal lifecycle currently has `sourceJobId`, `sourceRunId`, `state`, `completedAt`; edited has `source_job_id`, `event`, `edited_at`. Current reflection still describes older snake_case terminal fields: use the persisted run context as the authority. + +Missing/null scalar paths become empty text. Objects and arrays interpolate as compact JSON; array order is preserved and object keys sorted. Double braces preserve plain-text URLs, quotes, Markdown and code; triple braces are also supported. Sections use original context truthiness and array iteration. There are no global parameter defaults/overrides. + +After creating an automatic trigger, read its returned slug, then safely replace the full configuration to reference that slug. For example `{{trigger-2.issue.title}}` only works if that is the actual Linear trigger. Verify the rendered `prompt` and complete `context` with `get_run`. See the [full context contract](https://github.com/GenerationSoftware/factorize/blob/main/docs/job-trigger-context.md). diff --git a/packages/docs/work/results.mdx b/packages/docs/work/results.mdx new file mode 100644 index 00000000..c70c721e --- /dev/null +++ b/packages/docs/work/results.mdx @@ -0,0 +1,12 @@ +--- +title: Inspect results +description: Read run state, output, prompt, and trigger context. +--- + +Ask: “Show the latest runs for this job and summarize the completed review.” Use `list_runs({"jobId":"JOB_ID","limit":10})`, then `get_run({"runId":"RUN_ID"})`. Current MCP does not return an `output` field or trace messages. Open the browser run page to read the trace, or retrieve REST trace pages with an authorized client. Report the state/link through MCP and only summarize findings after actually reading them. + +Run pages return `items` and `nextCursor`; send that cursor for the next page. Optional `state` and `contextQuery` filter runs. Context search is a case-insensitive substring, not a query language. Current list rows contain no context excerpt; `get_run` returns full `context`, rendered `prompt`, `invocation.trigger_id`, execution metadata and activity. + +Check that the intended trigger fired, the repository/task appears in the rendered prompt, and the browser/REST trace supports the reported result. A queued submission is not a successful execution. Browser run pages are at `https://app.factorize.sh/job-runs/RUN_ID`. Agent output stays in Factorize and is not automatically copied into Linear. + +For missing output or execution failures, call `get_run_diagnostics` and follow [failed-run troubleshooting](/troubleshooting/runs). diff --git a/packages/docs/work/stop-retry.mdx b/packages/docs/work/stop-retry.mdx new file mode 100644 index 00000000..ea99f0a0 --- /dev/null +++ b/packages/docs/work/stop-retry.mdx @@ -0,0 +1,12 @@ +--- +title: Stop and retry runs +description: Avoid duplicate work and understand current stop behavior. +--- + +Ask: “Inspect this run, stop it if it is still active, and verify its final state.” Fetch `get_run`, then use `stop_run({"runId":"RUN_ID"})` for a starting, running or blocked run. The response requests `stopping`; poll until terminal and inspect diagnostics for cleanup. + +**Current behavior:** `kill_run` calls the same stop operation as `stop_run`. It does not force a queued run to terminate or release its slot immediately. Both return `operation_failed` when the run is not active. Do not treat kill as stronger recovery; contact the hosted operator if a run remains stuck. + +For a timed-out manual submission, repeat `invoke_job` with the **same** `idempotencyKey`. The response contains the original `invocationId`, `runId`, and `duplicate: true`. Retain the key you submitted: current `get_run` does not return `invocation.idempotency_key`. Never send its internal `invocation.claim_key` or a `manual:` prefix back as the key. If the key was lost, inspect existing runs before requesting another. + +An intentional new run after failure needs a new key. First verify that the prior run is terminal, inspect whether it made external changes, and fix the cause. A retry may repeat those external effects: invocation deduplication is not transactional rollback of the agent's work. For `queue_full`, wait for capacity and reuse the key for the intended request. See [failed runs](/troubleshooting/runs).