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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ on:
branches:
- main
workflow_dispatch:
inputs:
validate_conditions_only:
description: Validate GEN-2158 on its isolated Neon clone without deploying
type: boolean
default: false

permissions:
contents: read
Expand All @@ -15,7 +20,23 @@ concurrency:
cancel-in-progress: false

jobs:
validate-conditions:
if: github.event_name == 'workflow_dispatch' && inputs.validate_conditions_only
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: 24
cache: npm
- run: npm ci
- name: Validate explicit cutover on isolated Neon branch
run: npx tsx packages/api/scripts/validate-webhook-conditions-cutover.ts --neon
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
deploy:
if: github.event_name != 'workflow_dispatch' || !inputs.validate_conditions_only
name: Deploy app and marketing site
runs-on: ubuntu-latest
timeout-minutes: 15
Expand Down Expand Up @@ -84,5 +105,9 @@ jobs:
path: ${{ runner.temp }}/factorize-app-release
retention-days: 35
if-no-files-found: error
- name: Restore explicitly migrated webhook triggers after conditions deployment
run: node packages/api/scripts/restore-webhook-conditions.mjs https://app.factorize.sh
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
- name: Verify public production routing after deployment
run: node scripts/verify-public-routing.mjs https://app.factorize.sh --wait
2 changes: 1 addition & 1 deletion docs/cloudflare-tail.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,4 @@ For caught internal failures, log a structured event:
console.error(JSON.stringify({ event: "factorize_unexpected_failure", component: "billing", message: error.message }));
```

Do not include request bodies, headers, credentials, or prompts in the structured log. Expected 4xx/domain failures remain ordinary Tail events unless the Job handler explicitly accepts them.
Do not include request bodies, headers, credentials, or prompts in the structured log. Expected 4xx/domain failures remain ordinary Tail events unless the Job conditions explicitly accept them.
4 changes: 2 additions & 2 deletions docs/job-trigger-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ The available value beneath a slug is:
| 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` |

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. A webhook with a replacing handler reports `dynamic: true` and an explicit `*`/`unknown` fallback because arbitrary handler output cannot be inferred safely.
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.

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.

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.

Every webhook trigger may also define `handlerCode` containing one synchronous `function handler(webhook)` declaration. Factorize runs it only after provider authentication and trigger scoping, inside an isolated Worker with no bindings or outbound network access. Returning `false` rejects the delivery, `true` retains the default value above, and a JSON-compatible object replaces that value beneath the stable trigger slug. Timeouts, exceptions, and invalid return values are recorded in webhook activity and never create a run. REST `POST /api/v1/job-handlers/test` and MCP `test_job_webhook_handler` exercise the same isolation boundary without creating an invocation.
Webhook triggers may define optional declarative `conditions`; they filter without replacing context. See [webhook conditions](webhook-conditions.md) for operators, JSONPath, limits and preview behavior.

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.

Expand Down
80 changes: 80 additions & 0 deletions docs/webhook-conditions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Webhook conditions

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.

## Explicit GEN-2158 cutover

Migration 0013 inventories **every stored trigger**, including disabled and
removed triggers. It recognizes only the exact reviewed Build Manager source,
job ID and trigger slug/event/action. Any additional or changed handler aborts
the transaction for explicit review; no arbitrary JavaScript is translated.
It records prior enabled state, disables affected triggers, removes the legacy
property and installs the three exclusion groups in
`packages/api/migrations/build-manager-conditions.json`. Absent check_suite
matches, preserving the old early return for selected completed events.
Trigger identity, routing and prompt context stay intact. A database constraint
rejects future writes of the removed property.

Before production, validate on an isolated Neon branch and inventory again.
Land the conditions replacement on main before production cutover so later
main deployments (including concurrent frontend work) cannot restore the old
backend over converted data. The production workflow migrates before deploying the conditions Worker, then
runs `restore-webhook-conditions.mjs` only after deployment. The public session
response's `X-Factorize-Webhook-Conditions: v1` marker gates restoration. On any
migration/deployment/verification failure, affected triggers remain disabled.
Restoration rejects changed conditions or prematurely enabled triggers and
restores the recorded prior enabled state transactionally. After deployment,
verify the canonical authenticated preview on exclusion/accepted examples,
trigger identity/configuration/enabled state, and no stored legacy property.
Do not deploy the old runtime over the converted data: disable migrated triggers
first if a backend rollback becomes necessary. A frontend-only rollback must
retain the conditions API/runtime.
Loading
Loading