Skip to content
Closed
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ More detail: [How the engine works](docs/guides/how-it-works.md).
| `npm run push -- <org>` | Preflight the write plan, then push without pulling first (prefer `apply`); `--strict` also blocks validation errors outside the plan and `variable-undefined` warnings. 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). |
| `npm run rollback -- <org>` | Restore a pre-deploy snapshot |
| `npm run cleanup -- <org>` | Find, and optionally delete, platform resources with no file |
| `npm run audit -- <org>` | Report drift between files, state and the platform |
| `npm run audit -- <org>` | Report drift between files, state and the platform; ignore version-only changes for assistants, tools and squads |
| `npm run call -- <org>` | Talk to an assistant or squad from your terminal |
| `npm run sim -- <org>` | Run a simulation suite against deployed resources |
| `npm run check` | Run PR simulation checks against local files |
Expand Down
5 changes: 5 additions & 0 deletions docs/guides/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ same-name candidates without linking them. Existing mappings, including
legacy entries without provenance, remain linked. New pull mappings record
`origin: pulled`; push-created resources record `origin: pushed`.

Pull, drift checks, and normal create/update requests ignore the top-level
`latestVersion` of assistants, tools and squads. If an old baseline can't
prove a side is unchanged, use the
[normal conflict-resolution flow](../learnings/sync-behavior.md#publishing-or-rolling-back-a-version-can-leave-the-config-unchanged).

Dry-run push/apply ends with **Name collisions**, listing same-name state and
live dashboard resources for every planned POST, including dependency creates.
Read-only GETs run in dry-run. No matches prints `Name collisions: none`;
Expand Down
18 changes: 17 additions & 1 deletion docs/learnings/sync-behavior.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,23 @@ UUIDs → names):
| ≠ | = | `local-ahead` | You edited locally; dashboard untouched → **your change is the natural next step UP** |
| = | ≠ | `dashboard-ahead` | Someone edited the dashboard; you didn't → **their change is the natural next step DOWN** |
| ≠ | ≠ (but L = D) | treated as `clean` | Both sides already agree; the baseline is just stale → self-heals, never blocks, never prompts |
| ≠ | ≠ (and L ≠ D) | `both-diverged` | True 3-way conflict — the only case a human is ever asked about |
| ≠ | ≠ (and L ≠ D) | `both-diverged` | Neither side is known to match the last sync; resolve the difference before overwriting |

### Publishing or rolling back a version can leave the config unchanged

For assistants, tools and squads, the API's top-level `latestVersion` isn't
config. Pull omits it when writing files, and drift checks and normal
create/update requests ignore it even if an existing local file still has it.
Nested keys with that name are unaffected. Pull still leaves files using blocks
as written, and promotion can still copy source text verbatim. Snapshot capture
and replay are unchanged.

An existing baseline may include the version in its hash. GitOps can still
recognize an unchanged side if the whole old hash matches that side's config
with a version value still visible in the file or the API response. If neither
side can be proven unchanged and their configs differ, use the normal conflict
resolution flow. A push that automatically refreshes mappings preserves these
existing baselines so the refresh can't hide a conflict.

> **The core principle:** a question is only ever asked **per resource**, and
> only for `both-diverged`-class situations at push time. Everything else has
Expand Down
24 changes: 20 additions & 4 deletions improvements.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ you which stack PR closes the row.**
| 40 | Nothing checked a `credentialIds` list against the keys an org has saved | A list that hides the org's own key runs the call on Vapi's key, silently | None | RESOLVED 2026-11-17 (#96) |
| 41 | Shared prompt text and config had no home, and pull would erase any include marker | Repeated paragraphs drift apart across assistants and orgs | None | RESOLVED 2026-11-16 (#94) |
| 42 | An org with no credentials is re-bootstrapped on every push, which disables the drift check | A dashboard edit is overwritten without a warning in such an org | None | Open |
| 45 | A version pointer looked like a config edit | Version-only publishes and rollbacks report false drift | None | Implemented |

**Active backlog after cleanup:** `#2`, `#6`, `#8`, `#12`, `#20`, `#24–#26`, `#31`, and the open remainder of `#27` (wiring the listing-completeness verdict into push/delete/audit, and moving `cleanup.ts` onto the shared pager). Resolved entries stay in this file as historical incident notes per the maintenance directive; stale superseded backlog rows are not duplicated.

Expand Down Expand Up @@ -2318,7 +2319,7 @@ The push drift check refuses to overwrite a resource that was edited in the
dashboard since the last pull. In an org that has no credentials stored in
Vapi, it never refuses.

### Current behavior (Verified)
### Original behavior (Verified)

`maybeBootstrapState` in `src/push.ts` treats a state file with an empty
`credentials` section as uninitialized and runs a bootstrap pull before
Expand All @@ -2338,8 +2339,8 @@ credentials.

### Current mitigation

None. `npm run pull -- <org>` first still shows a dashboard edit before it is
overwritten, for anyone who reads the output.
Automatic push bootstrap now keeps existing baselines for assistants, tools
and squads (#45). Other resource types still have the original behavior.

### Possible fix

Expand All @@ -2349,7 +2350,7 @@ have a bootstrap pull leave existing baselines alone.

### Status

**Open.**
**Partially mitigated.**

---

Expand Down Expand Up @@ -2389,6 +2390,21 @@ per-practice numbers in inline squad overrides; see `examples/nhs-shared-squads`

---

## 45. Version pointers looked like resource config edits

An assistant, tool or squad's top-level `latestVersion` could land in a pulled
file, so publishing or rolling back to identical settings could report false
drift or block a legitimate local edit. Normal sync now strips that field
from config and write requests. An old drift baseline can identify an unchanged
side only when its full hash can be reproduced; otherwise differing configs
still go through conflict resolution. Automatic push bootstrap preserves these
existing baselines, closing that path to the overwrite risk in #42 for these
three types.

**Implemented.** Covered by local API stubs in `tests/latest-version.test.ts`.

---

## Out of scope (intentionally not improvements)

- **State file is identity-only and not git-ignored.** It's intentionally
Expand Down
19 changes: 12 additions & 7 deletions src/adopt-alias-files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { confirm } from "@inquirer/prompts";
import { rm } from "fs/promises";
import { relative } from "path";
import type { AdoptionAlias } from "./adopt.ts";
import { withoutLatestVersion } from "./canonical.ts";
import { BASE_DIR, DRY_RUN, RESOURCES_DIR, VAPI_ENV } from "./config.ts";
import { deleteBaseline, readBaseline } from "./hash-store.ts";
import { parseResourceDataFromFile } from "./resource-parse.ts";
Expand All @@ -24,14 +25,18 @@ export async function prepareAliasCleanup(
}[] = [];
for (const { file, uuid, adoptedAs, type } of files) {
const path = relative(BASE_DIR, file.filePath);
let hash: string | undefined;
try {
hash = hashPayload(
parseResourceDataFromFile(file.filePath, RESOURCES_DIR),
);
} catch {}
const baseline = readBaseline(VAPI_ENV, uuid);
if (!baseline || hash !== baseline) {
let matches = false;
if (baseline) {
try {
const raw = parseResourceDataFromFile(file.filePath, RESOURCES_DIR);
const config = withoutLatestVersion(raw, type);
matches =
hashPayload(config) === baseline ||
(config !== raw && hashPayload(raw) === baseline);
} catch {}
}
if (!matches) {
const message = `${path}: local edits or no baseline. Delete it by hand (or merge its edits into ${adoptedAs}) and rerun.`;
if (
DRY_RUN ||
Expand Down
28 changes: 13 additions & 15 deletions src/audit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@

import { readFile } from "fs/promises";
import { join } from "path";
import { canonicalizeForHash, type VapiResource } from "./canonical.ts";
import type { VapiResource } from "./canonical.ts";
import { matchesIgnore, RESOURCES_DIR, VAPI_ENV } from "./config.ts";
import { credentialReverseMap } from "./credentials.ts";
import { classifyDrift } from "./drift.ts";
import { compareResourceDrift } from "./drift.ts";
import { readBaseline } from "./hash-store.ts";
import { findOrphanResourceIds } from "./new-file-gate.ts";
import { fetchAllResources, listExistingResourceIds } from "./pull.ts";
import { FOLDER_MAP, hashLocalResource } from "./resources.ts";
import { FOLDER_MAP, readLocalResourceContent } from "./resources.ts";
import { extractBaseSlug, slugify } from "./slug-utils.ts";
import { hashPayload, loadState } from "./state.ts";
import { loadState } from "./state.ts";
import type { ResourceType, StateFile } from "./types.ts";
import { VALID_RESOURCE_TYPES } from "./types.ts";

Expand Down Expand Up @@ -384,21 +384,19 @@ function checkContentDrift(
const entry = state[type][resourceId];
if (!entry) continue;

const localHash = hashLocalResource(type, resourceId);
if (!localHash) continue;
const local = readLocalResourceContent(type, resourceId);
if (!local) continue;

const remoteResource = remoteByUuid.get(entry.uuid);
if (!remoteResource) continue;

// canonicalizeForHash centralizes the 3-step pipeline + _platformDefault
// mutation so the hash agrees with the pull-write baseline basis.
const platformHash = hashPayload(
canonicalizeForHash(remoteResource, state, credReverse, type),
);
const direction = classifyDrift({
localHash,
lastPulledHash: baselineReader(entry.uuid),
platformHash,
const { direction } = compareResourceDrift({
local,
remote: remoteResource,
state,
credReverse,
resourceType: type,
baseline: baselineReader(entry.uuid),
});
if (direction === "clean") continue;

Expand Down
15 changes: 14 additions & 1 deletion src/canonical.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,19 @@ export interface VapiResource {
[key: string]: unknown;
}

export function isVersionedResource(type?: ResourceType): boolean {
return type === "assistants" || type === "tools" || type === "squads";
}

export function withoutLatestVersion(
data: Record<string, unknown>,
type?: ResourceType,
): Record<string, unknown> {
if (!isVersionedResource(type) || !("latestVersion" in data)) return data;
const { latestVersion: _version, ...config } = data;
return config;
}

// Fields to remove before hashing/writing (server-managed or computed).
// Single source of truth — drift's old private `SERVER_FIELDS` was an exact
// duplicate of this and drifted out of sync risk-free only by luck.
Expand Down Expand Up @@ -213,7 +226,7 @@ export function canonicalizeForHash(
credReverse: Map<string, string>,
resourceType?: ResourceType,
): Record<string, unknown> {
const cleaned = cleanResource(resource);
const cleaned = withoutLatestVersion(cleanResource(resource), resourceType);
const content =
resourceType === "assistants" ? withoutAssistantFolder(cleaned) : cleaned;
const resolved = resolveReferencesToResourceIds(content, state);
Expand Down
126 changes: 87 additions & 39 deletions src/drift.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,18 @@
// ─────────────────────────────────────────────────────────────────────────────

import { VapiApiError, vapiGet } from "./api.ts";
import { canonicalizeForHash, type VapiResource } from "./canonical.ts";
import {
canonicalizeForHash,
isVersionedResource,
type VapiResource,
} from "./canonical.ts";
import { credentialReverseMap } from "./credentials.ts";
import { readBaseline } from "./hash-store.ts";
import { hashLocalResource } from "./resources.ts";
import {
type LocalResourceContent,
localResourceContent,
readLocalResourceContent,
} from "./resources.ts";
import { hashPayload } from "./state-serialize.ts";
import type { ResourceType, StateFile } from "./types.ts";

Expand Down Expand Up @@ -56,6 +64,71 @@ export function classifyDrift(input: ClassifyDriftInput): DriftDirection {
return "both-diverged";
}

export function compareResourceDrift({
local,
remote,
state,
credReverse,
resourceType,
baseline,
}: {
local: LocalResourceContent | null;
remote: VapiResource;
state: StateFile;
credReverse: Map<string, string>;
resourceType: ResourceType;
baseline?: string;
}): { localHash: string; platformHash: string; direction: DriftDirection } {
const platform = canonicalizeForHash(
remote,
state,
credReverse,
resourceType,
);
const platformHash = hashPayload(platform);
let lastPulledHash = baseline;
if (
baseline &&
platformHash !== baseline &&
local?.hash !== baseline &&
local?.hash !== platformHash &&
isVersionedResource(resourceType)
) {
for (const latestVersion of new Set([
local?.latestVersion,
remote.latestVersion,
])) {
if (
latestVersion !== null &&
typeof latestVersion !== "string" &&
typeof latestVersion !== "number"
)
continue;
if (hashPayload({ ...platform, latestVersion }) === baseline) {
lastPulledHash = platformHash;
break;
}
if (
local &&
hashPayload({ ...local.config, latestVersion }) === baseline
) {
lastPulledHash = local.hash;
break;
}
}
}
const localHash = local?.hash ?? lastPulledHash ?? "";
return {
localHash,
platformHash,
direction: classifyDrift({
localHash,
lastPulledHash,
platformHash,
}),
};
}

export function formatDriftLabel(direction: DriftDirection): string {
switch (direction) {
case "dashboard-ahead":
Expand Down Expand Up @@ -103,6 +176,7 @@ export async function checkDriftForUpdate(options: {
resourceType: ResourceType;
resourceId: string; // local resource id
state: StateFile;
loadedTypeScriptData?: Record<string, unknown>;
env: string; // org slug — keys the hash store
overwrite: boolean;
}): Promise<DriftCheckResult> {
Expand Down Expand Up @@ -137,46 +211,20 @@ export async function checkDriftForUpdate(options: {
return { ok: true, reason: "no-baseline" };
}

// Hash all three points (platform, local, baseline) in ONE basis — the
// canonical form defined in canonical.ts that pull also uses to write
// `lastPulledHash`. Drift previously carried its own field-strip copy that
// omitted reference/credential resolution, so any tool- or credential-bearing
// resource hashed differently here than at pull time → phantom both-diverged.
const credReverse = credentialReverseMap(state);
const platformHash = hashPayload(
canonicalizeForHash(
remote as VapiResource,
state,
credReverse,
resourceType,
),
);
if (platformHash === baseline) {
return { ok: true, reason: "match", platformHash, platformPayload: remote };
}

// On-disk hash in the same basis as the baseline. Absent a local file
// (rare on an update path), fall back to the baseline so the direction is
// dashboard-ahead rather than a phantom both-diverged.
const localHash = hashLocalResource(resourceType, resourceId) ?? baseline;

// Local and platform are byte-identical → there is nothing to reconcile and
// the PATCH is a no-op. NEVER block here, even if the baseline disagrees
// with both (a stale or older-basis baseline must not manufacture a conflict
// when the two LIVE sides already agree). `classifyDrift` encodes the same
// invariant, but this early return also short-circuits before the direction
// bookkeeping. This is the fix for the phantom-drift class: a freshly
// upgraded customer repo carries baselines written in an older hash basis,
// so every untouched resource hit `both-diverged` on its first push.
if (localHash === platformHash) {
const { direction, platformHash } = compareResourceDrift({
local: options.loadedTypeScriptData
? localResourceContent(resourceType, options.loadedTypeScriptData)
: readLocalResourceContent(resourceType, resourceId),
remote: remote as VapiResource,
state,
credReverse: credentialReverseMap(state),
resourceType,
baseline,
});
if (direction === "clean" || direction === "local-ahead") {
return { ok: true, reason: "match", platformHash, platformPayload: remote };
}

const direction = classifyDrift({
localHash,
lastPulledHash: baseline,
platformHash,
});
const directionTag = `[${direction}]`;

if (overwrite) {
Expand Down
Loading
Loading