Skip to content

Commit 311fb97

Browse files
fix(push): validate the whole plan before the first write (#107)
* fix(push): validate the whole plan before the first write Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * docs(agents): explain the push preflight stop Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: dhruva <dhruva@vapi.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent d528997 commit 311fb97

8 files changed

Lines changed: 394 additions & 23 deletions

File tree

‎AGENTS.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,14 @@ are needed to remove a verified unchanged leftover of an already-adopted
194194
resource. The engine never auto-adopts, auto-allows new files or deletes edited
195195
files without approval.
196196

197+
**When a deploy stops at the push preflight** ("Push preflight failed …
198+
Nothing was written to the remote API"), a resource the push would write (one
199+
you selected, or a dependency it would create) has a validation error or an
200+
unresolved credential. Fix the listed findings and rerun; nothing was applied,
201+
so there is nothing to roll back. Errors in files outside the push only warn
202+
(`--strict` blocks those too). The preflight only catches what `validate`
203+
knows about, so an API rejection can still leave a push partly applied.
204+
197205
If something goes wrong: `npm run rollback -- <org> --list`, then (with a yes)
198206
`--to <timestamp>`. Details for every workflow:
199207
[Everyday workflows](docs/guides/workflows.md);

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,9 +207,9 @@ More detail: [How the engine works](docs/guides/how-it-works.md).
207207
| --- | --- |
208208
| `npm run setup` | Connect an org: create `.env.<org>` and `resources/<org>/` |
209209
| `npm run validate -- <org>` | Check resource files offline before deploying |
210-
| `npm run apply -- <org>` | Deploy: pull, merge, then push (the default) |
210+
| `npm run apply -- <org>` | Deploy: pull, merge, then preflight and push (the default) |
211211
| `npm run pull -- <org>` | Sync platform changes down without overwriting local edits; unknown UUIDs get separate files, never name-linked |
212-
| `npm run push -- <org>` | Push without pulling first (prefer `apply`); review `--dry-run` Name collisions, and use `--adopt <id>[=<uuid>]` only with explicit approval to take over a resource; unchanged alias files are removed, edited/unbaselined copies need review. Push/apply support `--json` for one grouped link-preflight report (exit 1 on blockers); see [Running in CI](docs/guides/commands.md#running-in-ci). |
212+
| `npm run push -- <org>` | Preflight the write plan, then push without pulling first (prefer `apply`); `--strict` also blocks validation errors outside the plan. Review `--dry-run` Name collisions, and use `--adopt <id>[=<uuid>]` only with explicit approval to take over a resource; unchanged alias files are removed, edited/unbaselined copies need review. Push/apply support `--json` for one grouped link-preflight report (exit 1 on blockers); see [Running in CI](docs/guides/commands.md#running-in-ci). |
213213
| `npm run rollback -- <org>` | Restore a pre-deploy snapshot |
214214
| `npm run cleanup -- <org>` | Find, and optionally delete, platform resources with no file |
215215
| `npm run audit -- <org>` | Report drift between files, state and the platform |

‎docs/guides/commands.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ The other commands are direct only.
1111
| --- | --- | --- |
1212
| `npm run setup` | `npm run setup [-- <org>]` | Connect an org: creates `.env.<org>` and `resources/<org>/`. |
1313
| `npm run validate` | `npm run validate -- <org>` | Check resource files offline: API shape rules, and that every reference names a file or a state entry. `apply` runs it first. On GitHub Actions, findings are also shown on the files in the pull request. |
14-
| `npm run apply` | `npm run apply -- <org> [types or paths] [--adopt <id>[=<uuid>]]` | **The default deploy:** pull, merge, then push. See [workflows](workflows.md). |
14+
| `npm run apply` | `npm run apply -- <org> [types or paths] [--adopt <id>[=<uuid>]]` | **The default deploy:** pull, merge, then push. The push preflight below runs before remote writes. See [workflows](workflows.md). |
1515
| `npm run pull` | `npm run pull -- <org> [--force] [--bootstrap]` | Sync platform changes down; never overwrites local edits unless `--force`. |
16-
| `npm run push` | `npm run push -- <org> [--dry-run] [--json] [--strict] [--adopt <id>[=<uuid>]]` | Push without pulling first. Prefer `apply`. `--strict` aborts before any API call if validation finds an error. |
16+
| `npm run push` | `npm run push -- <org> [--dry-run] [--json] [--strict] [--adopt <id>[=<uuid>]]` | Push without pulling first. Prefer `apply`. Preflight blocks validation errors and unresolved credential names in the write plan (selected resources plus auto-applied dependencies) before any remote mutation, including deletions. `--dry-run` uses the same gate. `--strict` additionally blocks error-severity findings outside the plan; warnings remain advisory. Bootstrap reads may run before preflight. |
1717
| `npm run rollback` | `npm run rollback -- <org> --list` or `--to <ISO>` | Restore a pre-deploy snapshot from `.vapi-state.<org>.snapshots/`. |
1818
| `npm run cleanup` | `npm run cleanup -- <org> [--force --confirm <org>]` | List platform resources with no file; delete them only with both flags. |
1919
| `npm run audit` | `npm run audit -- <org> [--type <type>]` | Report drift between files, state and the platform. Exits 1 on any finding, so it can run in CI. |

‎improvements.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,25 @@
3131
3232
---
3333

34+
## Push write-plan preflight [RESOLVED 2026-11-20]
35+
36+
- **Problem:** Push is not atomic: a 400 on a later payload can leave earlier
37+
resources applied and the org partially updated.
38+
- **Current behavior:** Verified in `src/push.ts`: validation now gates all
39+
selected writes and local auto-applied dependencies before orphan deletion
40+
or POST/PATCH. `src/push-plan.ts` computes this plan without API calls.
41+
- **Risk:** Previously, known error-severity findings only warned unless
42+
`--strict` was set. Unknown API-side errors can still leave partial writes;
43+
this is preflight validation, not a remote transaction.
44+
- **Current mitigation:** Default preflight (also in dry-run) blocks planned
45+
errors and unresolved credential names. `--strict` also blocks errors in
46+
unrelated local resources. Bootstrap pulls before the gate only read remote
47+
state.
48+
- **Possible fix:** Extend offline validators as new API rejection cases are
49+
discovered; true atomicity would require platform transaction support.
50+
- **Status:** Resolved for known validation findings; covered by local HTTP
51+
stub tests in `tests/push-preflight.test.ts` asserting zero remote mutations.
52+
3453
## How to read this file
3554

3655
Sections are ordered by **severity / blast radius**, not by date discovered.

‎src/push-plan.ts‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import { extractReferencedIds } from "./resolver.ts";
2+
import type {
3+
LoadedResources,
4+
ResourceFile,
5+
ResourceType,
6+
StateFile,
7+
} from "./types.ts";
8+
import { VALID_RESOURCE_TYPES } from "./types.ts";
9+
import type { ValidationFinding } from "./validate.ts";
10+
11+
const UUID_RE =
12+
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13+
14+
// Mirror ensure*Exists without fetching inventories or adopting remote IDs.
15+
export function computePushPlan(
16+
selected: LoadedResources,
17+
local: LoadedResources,
18+
state: StateFile,
19+
): Set<string> {
20+
const plan = new Set<string>();
21+
const available = new Map<ResourceType, Set<string>>();
22+
for (const type of VALID_RESOURCE_TYPES) {
23+
available.set(type, new Set(Object.keys(state[type])));
24+
for (const resource of selected[type]) {
25+
plan.add(`${type}:${resource.resourceId}`);
26+
available.get(type)!.add(resource.resourceId);
27+
}
28+
}
29+
const ensure = (type: "tools" | "structuredOutputs", id: string): boolean => {
30+
if (UUID_RE.test(id) || available.get(type)!.has(id)) return false;
31+
if (!local[type].some((r) => r.resourceId === id)) return false;
32+
plan.add(`${type}:${id}`);
33+
available.get(type)!.add(id);
34+
return true;
35+
};
36+
const assistantDeps = (assistant: ResourceFile<Record<string, unknown>>) => {
37+
const refs = extractReferencedIds(assistant.data);
38+
let created = false;
39+
for (const id of refs.tools) created = ensure("tools", id) || created;
40+
for (const id of refs.structuredOutputs)
41+
created = ensure("structuredOutputs", id) || created;
42+
return created;
43+
};
44+
for (const assistant of selected.assistants) assistantDeps(assistant);
45+
for (const squad of selected.squads) {
46+
for (const id of extractReferencedIds(squad.data).assistants) {
47+
if (UUID_RE.test(id)) continue;
48+
const assistant = local.assistants.find((r) => r.resourceId === id);
49+
if (!assistant) continue;
50+
const depsCreated = assistantDeps(assistant);
51+
if (depsCreated || !available.get("assistants")!.has(id)) {
52+
plan.add(`assistants:${id}`);
53+
available.get("assistants")!.add(id);
54+
}
55+
}
56+
}
57+
return plan;
58+
}
59+
60+
export function pushBlockingFindings(
61+
findings: ValidationFinding[],
62+
plan: Set<string>,
63+
strict: boolean,
64+
): ValidationFinding[] {
65+
return findings
66+
.filter(
67+
(finding) =>
68+
(finding.severity === "error" && strict) ||
69+
(plan.has(`${finding.type}:${finding.resourceId}`) &&
70+
(finding.severity === "error" ||
71+
finding.rule === "unresolved-credential")),
72+
)
73+
.map((finding) => ({ ...finding, severity: "error" }));
74+
}

‎src/push.ts‎

Lines changed: 42 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { deleteBaseline, writeBaseline } from "./hash-store.ts";
2727
import { prepareResourceLinks } from "./link-preflight.ts";
2828
import { assertStateMigrated } from "./migrate-hash-store.ts";
2929
import { NameCollisionReport } from "./name-collisions.ts";
30+
import { computePushPlan, pushBlockingFindings } from "./push-plan.ts";
3031
import { reconcileStateKeyForResource } from "./reconcile-state-key.ts";
3132
import { writeSnapshot } from "./snapshot.ts";
3233
import { mergeScoped } from "./state-merge.ts";
@@ -1756,10 +1757,7 @@ async function main(): Promise<void> {
17561757
}
17571758
}
17581759
preflightComplete = true;
1759-
// Run client-side validators against the loaded resource set. In default
1760-
// mode, errors are surfaced as warnings so a single bad spec doesn't block
1761-
// an otherwise-good push. With --strict, any error-severity finding aborts
1762-
// before any API call.
1760+
// Validate the full local set; gate errors against the write plan below.
17631761
console.log("\n🔎 Running validators...");
17641762
const findings = [
17651763
...validateResources(loadedResources),
@@ -1780,18 +1778,6 @@ async function main(): Promise<void> {
17801778
} else {
17811779
console.log(" ✅ No validation issues.");
17821780
}
1783-
const errorCount = findings.filter((f) => f.severity === "error").length;
1784-
if (errorCount > 0) {
1785-
if (STRICT_VALIDATION) {
1786-
console.error(
1787-
`\n❌ Validation failed (${errorCount} error(s)). --strict refuses to push. Fix the issues above or drop --strict.`,
1788-
);
1789-
process.exit(1);
1790-
}
1791-
console.warn(
1792-
` ⚠️ ${errorCount} validation error(s) detected — push will continue (use --strict to abort on errors).`,
1793-
);
1794-
}
17951781

17961782
// Resolve credential names → UUIDs in all resource data before applying
17971783
const credMap = credentialForwardMap(state);
@@ -1879,6 +1865,46 @@ async function main(): Promise<void> {
18791865
? filterResourcesByPaths(allEvals, "evals")
18801866
: [];
18811867

1868+
const plan = computePushPlan(
1869+
{
1870+
tools,
1871+
structuredOutputs,
1872+
assistants,
1873+
squads,
1874+
personalities,
1875+
scenarios,
1876+
simulations,
1877+
simulationSuites,
1878+
evals,
1879+
},
1880+
{
1881+
tools: allTools,
1882+
structuredOutputs: allStructuredOutputs,
1883+
assistants: allAssistants,
1884+
squads: allSquads,
1885+
personalities: allPersonalities,
1886+
scenarios: allScenarios,
1887+
simulations: allSimulations,
1888+
simulationSuites: allSimulationSuites,
1889+
evals: allEvals,
1890+
},
1891+
state,
1892+
);
1893+
const blocking = pushBlockingFindings(findings, plan, STRICT_VALIDATION);
1894+
if (blocking.length > 0) {
1895+
console.error(summarizeFindings(blocking));
1896+
console.error(
1897+
`\n❌ Push preflight failed (${blocking.length} blocking finding(s))${STRICT_VALIDATION ? " (--strict)" : ""}. Nothing was written to the remote API.`,
1898+
);
1899+
process.exit(1);
1900+
}
1901+
const outsideErrors = findings.filter((f) => f.severity === "error").length;
1902+
if (outsideErrors > 0) {
1903+
console.warn(
1904+
` ⚠️ ${outsideErrors} validation error(s) outside the push plan — push will continue (use --strict to abort on all errors).`,
1905+
);
1906+
}
1907+
18821908
// Scoped run: print exactly what's in scope (the load above was quiet).
18831909
if (partial) {
18841910
const scoped: Array<[string, ResourceFile<Record<string, unknown>>[]]> = [

‎src/validate.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22
// Client-side validators — fail-fast schema / lockstep / shape checks
33
//
44
// Designed to catch the classes of errors that would otherwise only surface
5-
// when the Vapi API returns a 400 mid-push. The push pipeline runs these in
6-
// warning-only mode by default; `--strict` promotes warnings to blocking
7-
// errors that abort before any API call.
5+
// when the Vapi API returns a 400 mid-push. Push blocks error-severity findings
6+
// in its write plan (including auto-applied dependencies) before any remote
7+
// mutation, also in dry-run. `--strict` additionally blocks errors outside
8+
// the plan; warning-severity findings remain advisory.
89
//
910
// Sources for each check are documented in `improvements.md`:
1011
// - Name length cap (40 chars) → improvements #18

0 commit comments

Comments
 (0)