diff --git a/README.md b/README.md index 5fce042..071eb5b 100644 --- a/README.md +++ b/README.md @@ -227,7 +227,7 @@ More detail: [How the engine works](docs/guides/how-it-works.md). | `npm run push -- ` | 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 [=]` 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 -- ` | Restore a pre-deploy snapshot | | `npm run cleanup -- ` | Find, and optionally delete, platform resources with no file | -| `npm run audit -- ` | Report drift between files, state and the platform | +| `npm run audit -- ` | Report drift between files, state and the platform; ignore version-only changes for assistants, tools and squads | | `npm run call -- ` | Talk to an assistant or squad from your terminal | | `npm run sim -- ` | Run a simulation suite against deployed resources | | `npm run check` | Run PR simulation checks against local files | diff --git a/docs/guides/commands.md b/docs/guides/commands.md index eaf32d7..4b82213 100644 --- a/docs/guides/commands.md +++ b/docs/guides/commands.md @@ -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`; diff --git a/docs/learnings/sync-behavior.md b/docs/learnings/sync-behavior.md index ff44862..7f28bdd 100644 --- a/docs/learnings/sync-behavior.md +++ b/docs/learnings/sync-behavior.md @@ -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 diff --git a/improvements.md b/improvements.md index 20fdec6..8414628 100644 --- a/improvements.md +++ b/improvements.md @@ -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. @@ -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 @@ -2338,8 +2339,8 @@ credentials. ### Current mitigation -None. `npm run pull -- ` 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 @@ -2349,7 +2350,7 @@ have a bootstrap pull leave existing baselines alone. ### Status -**Open.** +**Partially mitigated.** --- @@ -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 diff --git a/src/adopt-alias-files.ts b/src/adopt-alias-files.ts index 6d447fd..172f86d 100644 --- a/src/adopt-alias-files.ts +++ b/src/adopt-alias-files.ts @@ -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"; @@ -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 || diff --git a/src/audit.ts b/src/audit.ts index a623056..0b78343 100644 --- a/src/audit.ts +++ b/src/audit.ts @@ -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"; @@ -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; diff --git a/src/canonical.ts b/src/canonical.ts index cde5306..a201c27 100644 --- a/src/canonical.ts +++ b/src/canonical.ts @@ -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, + type?: ResourceType, +): Record { + 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. @@ -213,7 +226,7 @@ export function canonicalizeForHash( credReverse: Map, resourceType?: ResourceType, ): Record { - const cleaned = cleanResource(resource); + const cleaned = withoutLatestVersion(cleanResource(resource), resourceType); const content = resourceType === "assistants" ? withoutAssistantFolder(cleaned) : cleaned; const resolved = resolveReferencesToResourceIds(content, state); diff --git a/src/drift.ts b/src/drift.ts index d7bb365..8bd3b8b 100644 --- a/src/drift.ts +++ b/src/drift.ts @@ -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"; @@ -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; + 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": @@ -103,6 +176,7 @@ export async function checkDriftForUpdate(options: { resourceType: ResourceType; resourceId: string; // local resource id state: StateFile; + loadedTypeScriptData?: Record; env: string; // org slug — keys the hash store overwrite: boolean; }): Promise { @@ -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) { diff --git a/src/pull.ts b/src/pull.ts index 49f96b8..175848f 100644 --- a/src/pull.ts +++ b/src/pull.ts @@ -13,6 +13,7 @@ import { import { buildReverseMap, canonicalizeForHash, + isVersionedResource, type VapiResource, } from "./canonical.ts"; import { @@ -33,7 +34,7 @@ import { } from "./credential-kinds.ts"; import { credentialReverseMap } from "./credentials.ts"; import { - classifyDrift, + compareResourceDrift, type DriftDirection, formatDriftLabel, } from "./drift.ts"; @@ -43,6 +44,7 @@ import { FOLDER_MAP, hashLocalResource, parseResourceFilePath, + readLocalResourceContent, resolvePullScopeFromFilePaths, } from "./resources.ts"; import { extractBaseSlug, isBackupCopyFile, slugify } from "./slug-utils.ts"; @@ -631,21 +633,21 @@ async function blocksFilePull(options: { bothDiverged?: BothDivergedResource[]; }): Promise { const { resourceType, resourceId, resource, state, localFile } = options; - const localHash = hashLocalResource(resourceType, resourceId); - if (localHash === null) { + const local = readLocalResourceContent(resourceType, resourceId); + if (local === null) { console.warn( ` ⚠️ ${resourceId}: uses blocks that could not be expanded, file left as written (run npm run validate -- ${VAPI_ENV})`, ); return; } - const platformHash = hashPayload( - canonicalizeForHash(resource, state, options.credReverse, resourceType), - ); const baseline = readBaseline(VAPI_ENV, resource.id); - const direction = classifyDrift({ - localHash, - lastPulledHash: baseline, - platformHash, + const { direction, localHash, platformHash } = compareResourceDrift({ + local, + remote: resource, + state, + credReverse: options.credReverse, + resourceType, + baseline, }); if (!options.force && options.driftCounts) options.driftCounts[direction]++; @@ -844,6 +846,7 @@ function timingLine(entry: BothDivergedResource): string { export interface PullOptions { force?: boolean; bootstrap?: boolean; + preserveVersionedBaselines?: boolean; bindingsOnly?: boolean; skipBindings?: boolean; typeFilter?: ResourceType[]; @@ -865,6 +868,7 @@ export async function pullResourceType( changedFiles?: Set; force?: boolean; bootstrap?: boolean; + preserveVersionedBaselines?: boolean; resourceIds?: string[]; driftCounts?: DriftDirectionCounts; bothDiverged?: BothDivergedResource[]; @@ -988,23 +992,15 @@ export async function pullResourceType( const localFile = findLocalResourcePath(folderPath, resourceId); if (localFile && baseline) { - const localHash = hashLocalResource(resourceType, resourceId); - if (localHash) { - // Use canonicalizeForHash so platform-default mutation (_platformDefault) - // and the 3-step pipeline are applied identically across pull-write, - // classifier, audit, and resolveBothDiverged sites. Any asymmetry here - // makes every drifted file look `both-diverged` even when content matches. - const platformHash = hashPayload( - canonicalizeForHash(resource, state, credReverse, resourceType), - ); - // Note: classifyDrift treats live local + platform agreement as - // `clean` whatever the (possibly stale) baseline says — the clean - // fall-through to the write path re-seeds the baseline from the - // disk form, self-healing the stale pointer. - const direction = classifyDrift({ - localHash, - lastPulledHash: baseline, - platformHash, + const local = readLocalResourceContent(resourceType, resourceId); + if (local) { + const { direction, localHash, platformHash } = compareResourceDrift({ + local, + remote: resource, + state, + credReverse, + resourceType, + baseline, }); if (driftCounts) driftCounts[direction]++; @@ -1227,6 +1223,14 @@ export async function pullResourceType( uuid: resource.id, origin: "pulled", }); + if ( + bootstrap && + options.preserveVersionedBaselines && + isVersionedResource(resourceType) && + readBaseline(VAPI_ENV, resource.id) + ) { + continue; + } await writeBaseline( VAPI_ENV, resource.id, @@ -1622,6 +1626,7 @@ export async function runPull(options: PullOptions = {}): Promise { changedFiles, force, bootstrap, + preserveVersionedBaselines: options.preserveVersionedBaselines, resourceIds: idsByType?.get(type) ?? resourceIds, driftCounts, bothDiverged: bothDivergedResources, diff --git a/src/push.ts b/src/push.ts index f2f1f2a..a665e03 100644 --- a/src/push.ts +++ b/src/push.ts @@ -4,7 +4,11 @@ import { fileURLToPath } from "url"; import { getDryRunCounts, VapiApiError, vapiRequest } from "./api.ts"; import { withAssistantFolder } from "./assistant-folder.ts"; import { type BlockUsage, blocksRecordUpdate } from "./blocks.ts"; -import { canonicalizeForHash, type VapiResource } from "./canonical.ts"; +import { + canonicalizeForHash, + type VapiResource, + withoutLatestVersion, +} from "./canonical.ts"; import { APPLY_FILTER, BASE_DIR, @@ -247,6 +251,7 @@ async function upsertResourceWithStateRecovery(options: { updatePayload: Record; createEndpoint: string; createPayload: Record; + loadedTypeScriptData?: Record; // Full state file — needed so drift detection can canonicalize the platform // payload into the same basis as `lastPulledHash` (resolves UUID refs back // to resourceId slugs + credential names). Without it the drift check @@ -328,6 +333,7 @@ async function upsertResourceWithStateRecovery(options: { resourceType: driftResourceType, resourceId, state: fullState, + loadedTypeScriptData: options.loadedTypeScriptData, env: VAPI_ENV, overwrite: OVERWRITE_DRIFT, }); @@ -665,7 +671,11 @@ async function maybeBootstrapState( ); } - const result = await runPull({ bootstrap: true, typeFilter: [] }); + const result = await runPull({ + bootstrap: true, + preserveVersionedBaselines: true, + typeFilter: [], + }); return result.state; } @@ -702,7 +712,7 @@ export async function applyTool( const existingUuid = state.tools[resourceId]?.uuid; // Resolve references (but assistants may not exist yet on first pass) - const payload = resolveReferences(data as Record, state); + const payload = resolveReferences(withoutLatestVersion(data, "tools"), state); // For handoff tools with assistant destinations, strip unresolved assistantIds for initial creation // They will be linked after assistants are created @@ -724,6 +734,7 @@ export async function applyTool( ), createEndpoint: "/tool", createPayload: payloadForCreate, + loadedTypeScriptData: resource.filePath?.endsWith(".ts") ? data : undefined, }); } @@ -925,7 +936,7 @@ export async function applyAssistant( // Resolve tool and structured output references const payload = withAssistantFolder( - resolveReferences(data as Record, state), + resolveReferences(withoutLatestVersion(data, "assistants"), state), resourceId, ); @@ -939,6 +950,7 @@ export async function applyAssistant( updatePayload: removeExcludedKeys(payload, "assistants"), createEndpoint: "/assistant", createPayload: payload, + loadedTypeScriptData: resource.filePath?.endsWith(".ts") ? data : undefined, }); } @@ -950,7 +962,10 @@ export async function applySquad( const existingUuid = state.squads[resourceId]?.uuid; // Resolve assistant references in members - const payload = resolveReferences(data as Record, state); + const payload = resolveReferences( + withoutLatestVersion(data, "squads"), + state, + ); return upsertResourceWithStateRecovery({ resourceLabel: "squad", @@ -962,6 +977,7 @@ export async function applySquad( updatePayload: removeExcludedKeys(payload, "squads"), createEndpoint: "/squad", createPayload: payload, + loadedTypeScriptData: resource.filePath?.endsWith(".ts") ? data : undefined, }); } @@ -1138,7 +1154,7 @@ export async function updateToolAssistantRefs( // This PATCH mutates the platform AFTER the main upsert wrote its // baseline — refresh it from the linking response, or the next push would // see drift we caused ourselves. - await writeBaselineFromResponse(uuid, result, state); + await writeBaselineFromResponse(uuid, result, state, "tools"); } } @@ -2068,6 +2084,7 @@ async function main(): Promise { // 6. Simulation suites (references simulations) // 7. Evals + const appliedTools: ResourceFile[] = []; if (tools.length > 0) { console.log("\n🔧 Applying tools...\n"); for (const tool of tools) { @@ -2079,6 +2096,7 @@ async function main(): Promise { }); touched.tools.add(tool.resourceId); applied.tools++; + appliedTools.push(tool); } catch (error) { console.error(formatApiError(tool.resourceId, error)); throw error; @@ -2252,7 +2270,7 @@ async function main(): Promise { } // Second pass: Link resources to assistants (include auto-applied deps) - const allAppliedTools = [...tools, ...autoAppliedTools]; + const allAppliedTools = [...appliedTools, ...autoAppliedTools]; if (allAppliedTools.length > 0) { console.log("\n🔗 Linking tools to assistant destinations...\n"); await updateToolAssistantRefs(allAppliedTools, state); diff --git a/src/resources.ts b/src/resources.ts index 78cd631..414e974 100644 --- a/src/resources.ts +++ b/src/resources.ts @@ -4,6 +4,7 @@ import { basename, extname, join, relative, resolve } from "path"; import { parse as parseYaml } from "yaml"; import { withoutAssistantFolder } from "./assistant-folder.ts"; import { blockLayers, blocksExpand } from "./blocks.ts"; +import { withoutLatestVersion } from "./canonical.ts"; import { BASE_DIR, matchesIgnore, RESOURCES_DIR } from "./config.ts"; import { FOLDER_MAP, @@ -36,23 +37,51 @@ function findLocalResourceFile( return undefined; } -/** Stable content hash of a local resource file (same basis as lastPulledHash). */ -export function hashLocalResource( +export interface LocalResourceContent { + config: Record; + hash: string; + latestVersion: unknown; +} + +export function localResourceContent( + type: ResourceType, + data: Record, +): LocalResourceContent { + const config = withoutLatestVersion( + type === "assistants" ? withoutAssistantFolder(data) : data, + type, + ); + return { + config, + hash: hashPayload(config), + latestVersion: data.latestVersion, + }; +} + +export function readLocalResourceContent( type: ResourceType, resourceId: string, -): string | null { +): LocalResourceContent | null { const filePath = findLocalResourceFile(type, resourceId); if (!filePath) return null; try { - const data = parseResourceDataFromFile(filePath, RESOURCES_DIR); - return hashPayload( - type === "assistants" ? withoutAssistantFolder(data) : data, + return localResourceContent( + type, + parseResourceDataFromFile(filePath, RESOURCES_DIR), ); } catch { return null; } } +/** Stable content hash of a local resource file (same basis as lastPulledHash). */ +export function hashLocalResource( + type: ResourceType, + resourceId: string, +): string | null { + return readLocalResourceContent(type, resourceId)?.hash ?? null; +} + export async function loadResources( type: ResourceType, options: LoadOptions = {}, diff --git a/tests/latest-version.test.ts b/tests/latest-version.test.ts new file mode 100644 index 0000000..1995b77 --- /dev/null +++ b/tests/latest-version.test.ts @@ -0,0 +1,617 @@ +import "./engine-sandbox.ts"; +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { existsSync, readFileSync, rmSync } from "node:fs"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { join } from "node:path"; +import test, { type TestContext } from "node:test"; +import { pathToFileURL } from "node:url"; +import { promisify } from "node:util"; +import { parse, stringify } from "yaml"; +import { hashPayload } from "../src/state-serialize.ts"; +import { + assistantFile, + assistantPayload, + engineRepoCreate, + filesWrite, + stateFile, +} from "./blocks-helpers.ts"; + +const exec = promisify(execFile); + +type Payload = Record; +type Stored = Payload & { id: string; orgId: string }; + +async function fixture( + t: TestContext, + files: Record, + resources: Record, +) { + const root = engineRepoCreate({ + ...files, + "loopback-only.mjs": ` + const fetch = globalThis.fetch; + globalThis.fetch = (input, init) => { + if (new URL(input instanceof Request ? input.url : input).origin !== process.env.FIXTURE_API_ORIGIN) + throw new Error("GitOps fixture tried to reach a non-stub URL"); + return fetch(input, { ...init, redirect: "error" }); + }; + `, + }); + t.after(() => rmSync(root, { recursive: true, force: true })); + const writes: Array<{ method: string; path: string; data: Payload }> = []; + const server = createServer(async (req, res) => { + const method = req.method!; + const path = new URL(req.url!, "http://localhost").pathname; + const [, type, id, subresource] = path.split("/"); + const records = resources[type!] ?? []; + const existing = records.find((record) => record.id === id); + res.setHeader("content-type", "application/json"); + if (method === "GET") { + if (!resources[type!]) { + res.end("[]"); + return; + } + if (id && !existing) res.statusCode = 404; + res.end(JSON.stringify(id ? (existing ?? {}) : records)); + return; + } + let body = ""; + for await (const chunk of req) body += String(chunk); + const data = JSON.parse(body) as Payload; + writes.push({ method, path, data }); + if (subresource === "versions") { + res.end("{}"); + return; + } + const record = { + ...existing, + ...data, + id: id ?? `created-${type}`, + orgId: "org-test", + latestVersion: "v-published", + }; + if (existing) Object.assign(existing, record); + else records.push(record); + res.end(JSON.stringify(record)); + }); + await new Promise((done) => server.listen(0, "127.0.0.1", done)); + t.after(() => new Promise((done) => server.close(() => done()))); + const port = (server.address() as AddressInfo).port; + const baseUrl = `http://127.0.0.1:${port}`; + const cli = async (script: string, ...args: string[]) => { + const options = { + cwd: root, + env: { + ...process.env, + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ""} --import=${pathToFileURL(join(root, "loopback-only.mjs"))}`, + FIXTURE_API_ORIGIN: baseUrl, + VAPI_PRIVATE_API_KEY: "test-key", + VAPI_BASE_URL: baseUrl, + VAPI_GITOPS_ORG_PIN: "off", + VAPI_GITOPS_ACTOR: "fixture-actor", + VAPI_PROMOTION_TOKENS: JSON.stringify({ + dev: "test-key", + prod: "test-key", + }), + }, + timeout: 30_000, + }; + try { + const { stdout, stderr } = await exec( + process.execPath, + ["--import", "tsx", `src/${script}-cmd.ts`, ...args], + options, + ); + return { code: 0, output: stdout + stderr }; + } catch (error) { + const { code, stdout, stderr } = error as { + code: number; + stdout: string; + stderr: string; + }; + return { code, output: stdout + stderr }; + } + }; + return { + root, + baseUrl, + cli, + writes, + read: (path: string) => readFileSync(join(root, path), "utf8"), + }; +} + +for (const extension of ["yml", "ts"]) { + test(`handoff linking respects drift and stores a stripped baseline (${extension})`, async (t) => { + const intakeId = "00000000-0000-4000-8000-000000000001"; + const otherId = "00000000-0000-4000-8000-000000000002"; + const tool = { + type: "handoff", + function: { name: "handoff", description: "Base description." }, + destinations: [{ type: "assistant", assistantId: "intake" }], + }; + const state = { + ...JSON.parse(stateFile({ intake: intakeId, other: otherId })), + tools: { handoff: { uuid: "tool-id" } }, + }; + const baselinePath = "state/dev/local/baselines/tool-id"; + const baseline = hashPayload({ ...tool, latestVersion: "v1" }); + const local = { + ...tool, + destinations: [{ type: "assistant", assistantId: "other" }], + }; + const dashboard = { + ...tool, + id: "tool-id", + orgId: "org-test", + latestVersion: "v2", + function: { ...tool.function, description: "Dashboard edit." }, + destinations: [{ type: "assistant", assistantId: intakeId }], + }; + const path = `resources/dev/tools/handoff.${extension}`; + const config = { ...local, latestVersion: "v1" }; + const loadMarker = "handoff-loaded"; + const f = await fixture( + t, + { + "state/dev/state.json": JSON.stringify(state), + [baselinePath]: baseline, + [path]: + extension === "ts" + ? `import { appendFileSync } from "node:fs";\nappendFileSync(${JSON.stringify(loadMarker)}, "loaded\\n");\nexport default ${JSON.stringify(config)};\n` + : stringify(config), + }, + { tool: [dashboard] }, + ); + if (extension === "ts") { + await f.cli("audit", "dev", "--type", "tools"); + assert.equal(existsSync(join(f.root, loadMarker)), false); + } + const { code, output } = await f.cli("push", "dev", path); + assert.equal(code, 1, output); + assert.match(output, /drift detected on tool handoff \[both-diverged\]/); + assert.deepEqual(f.writes.slice(), [], output); + assert.equal(f.read(baselinePath).trim(), baseline); + + dashboard.function = tool.function; + const allowed = await f.cli("push", "dev", path); + assert.equal(allowed.code, 0, allowed.output); + assert.equal(f.writes.length, 2, allowed.output); + assert.deepEqual(f.writes.at(-1)?.data, { + destinations: [{ type: "assistant", assistantId: otherId }], + }); + assert.match( + allowed.output, + /Linking tool handoff to assistant destinations/, + ); + assert.equal(f.read(baselinePath).trim(), hashPayload(local)); + if (extension === "ts") { + assert.equal(f.read(loadMarker), "loaded\nloaded\n"); + } + }); +} + +for (const mode of ["legacy", "normalized", "edited"]) { + test(`adoption still checks versioned aliases for real edits (${mode})`, async (t) => { + const uuid = "aaaaaaaa-0000-4000-8000-000000000000"; + const file = "resources/dev/assistants/riley.md"; + const alias = "resources/dev/assistants/riley-aaaaaaaa.md"; + const { + id: _id, + orgId: _orgId, + ...config + } = assistantPayload(uuid, "riley", "Base."); + const content = assistantFile( + "riley", + mode === "edited" ? "Local edit." : "Base.", + ).replace("name:", "latestVersion: v1\nname:"); + const f = await fixture( + t, + { + "state/dev/state.json": stateFile({ "riley-aaaaaaaa": uuid }), + [`state/dev/local/baselines/${uuid}`]: hashPayload( + mode === "legacy" ? { ...config, latestVersion: "v1" } : config, + ), + [file]: assistantFile("riley", "Base."), + [alias]: content, + }, + { + assistant: [ + { ...assistantPayload(uuid, "riley", "Base."), latestVersion: "v2" }, + ], + }, + ); + const { code, output } = await f.cli( + "push", + "dev", + "--dry-run", + "--adopt", + "riley", + file, + ); + assert.equal(code, mode === "edited" ? 1 : 0, output); + assert.match( + output, + mode === "edited" + ? /local edits or no baseline/ + : /would delete .*riley-aaaaaaaa\.md/, + ); + assert.equal(f.read(alias), content); + assert.deepEqual(f.writes, []); + }); +} + +for (const mode of ["apply", "promote"]) { + test(`${mode} strips the pointer on creates and updates but preserves nested config`, async (t) => { + const org = mode === "apply" ? "dev" : "prod"; + const oldTool = { + type: "function", + function: { + name: "existing_tool", + description: "Before.", + parameters: { + type: "object", + properties: { latestVersion: { type: "string" } }, + }, + }, + }; + const oldAssistant = { + name: "Existing Assistant", + model: { provider: "openai", model: "gpt-4o" }, + firstMessage: "Before.", + metadata: { latestVersion: "authored" }, + }; + const oldSquad = { + name: "Existing Squad", + members: [ + { + assistantId: "existing-assistant", + assistantOverrides: { variableValues: { latestVersion: "authored" } }, + }, + ], + }; + const endpoints = [ + [ + "tool", + "tools", + oldTool, + { + ...oldTool, + function: { ...oldTool.function, description: "After." }, + }, + { ...oldTool, function: { ...oldTool.function, name: "new_tool" } }, + ], + [ + "assistant", + "assistants", + oldAssistant, + { ...oldAssistant, firstMessage: "After." }, + { ...oldAssistant, name: "New Assistant" }, + ], + [ + "squad", + "squads", + oldSquad, + { ...oldSquad, name: "Updated Squad" }, + { ...oldSquad, name: "New Squad" }, + ], + ] as const; + const files: Record = {}; + const resources: Record = { + credential: [ + { + id: "cred-uuid-unused", + orgId: "org-test", + name: "unused-credential", + }, + ], + }; + const state = JSON.parse(stateFile({})); + for (const [endpoint, type, before, update, create] of endpoints) { + const id = `existing-${endpoint}`; + state[type] = { [id]: { uuid: id } }; + resources[endpoint] = [ + { ...before, id, orgId: "org-test", latestVersion: "v-live" }, + ]; + const base = `resources/${org}/${type}`; + if (mode === "promote") files[`${base}/${id}.yml`] = stringify(before); + files[`resources/dev/${type}/${id}.yml`] = stringify({ + ...update, + latestVersion: "v-file", + }); + files[`resources/dev/${type}/new-${endpoint}.yml`] = stringify({ + ...create, + latestVersion: "v-file", + }); + } + files[`state/${org}/state.json`] = JSON.stringify(state); + const f = await fixture(t, files, resources); + + let args = ["dev", "--allow-new-files"]; + if (mode === "promote") { + await exec("git", ["init", "--quiet"], { cwd: f.root }); + filesWrite(f.root, { + "state/dev/state.json": "{}", + "promotion.yml": stringify({ + version: 1, + orgs: { dev: { baseUrl: f.baseUrl }, prod: { baseUrl: f.baseUrl } }, + pipelines: { + release: { orgs: ["dev", "prod"], resources: ["**/*"] }, + }, + }), + }); + args = [ + "--pipeline", + "release", + "--from", + "dev", + "--to", + "prod", + "--apply", + ]; + } + const result = await f.cli(mode, ...args); + assert.equal(result.code, 0, result.output); + + for (const [endpoint, , , update, create] of endpoints) { + for (const [method, path, desired] of [ + ["PATCH", `/${endpoint}/existing-${endpoint}`, update], + ["POST", `/${endpoint}`, create], + ] as const) { + const request = f.writes.find( + (w) => w.method === method && w.path === path, + ); + assert.ok(request, result.output); + assert.ok( + !Object.hasOwn(request.data, "latestVersion"), + JSON.stringify(request), + ); + const nestedKey = + endpoint === "tool" + ? "function" + : endpoint === "assistant" + ? "metadata" + : "members"; + const nested = (desired as Payload)[nestedKey]; + if (endpoint === "assistant") { + assert.equal( + (request.data.metadata as Payload).latestVersion, + (nested as Payload).latestVersion, + ); + } else { + assert.deepEqual(request.data[nestedKey], nested); + } + } + } + const labels = f.writes.filter(({ path }) => + path.endsWith("/versions/v-published"), + ); + assert.equal(labels.length, 2, result.output); + assert.ok( + labels.every(({ data }) => + String(data.versionName).includes("fixture-actor"), + ), + ); + assert.doesNotMatch(f.read(`state/${org}/state.json`), /latestVersion/); + const pulled = await f.cli("pull", org); + assert.equal(pulled.code, 0, pulled.output); + for (const [endpoint, type] of endpoints) { + const config = parse( + f.read(`resources/${org}/${type}/existing-${endpoint}.yml`), + ) as Payload; + assert.ok(!Object.hasOwn(config, "latestVersion")); + assert.match(JSON.stringify(config), /"latestVersion"/); + } + }); +} + +for (const layout of ["legacy", "state directory"]) { + test(`version pointers and old baselines across pull, audit and push (${layout})`, async (t) => { + const statePath = + layout === "legacy" ? ".vapi-state.dev.json" : "state/dev/state.json"; + const baselineDir = + layout === "legacy" + ? ".vapi-state-hash/dev" + : "state/dev/local/baselines"; + const cases = [ + { id: "advance", baseline: "v1", local: "v1", remote: "v2" }, + { id: "rollback", baseline: "v2", local: "v2", remote: "v1" }, + { + id: "local", + baseline: "v1", + local: "v1", + remote: "v2", + localBody: "Local.", + }, + { + id: "dashboard", + baseline: "v1", + local: "v1", + remote: "v2", + remoteBody: "Remote.", + }, + { + id: "conflict", + baseline: "v1", + local: "v1", + remote: "v2", + localBody: "Local.", + remoteBody: "Remote.", + }, + { id: "ambiguous", baseline: "v1", remote: "v2", localBody: "Local." }, + { id: "block", baseline: "v1", local: "v1", remote: "v2", block: true }, + { id: "normalized", remote: "v2", localBody: "Local." }, + ]; + const config = (id: string, body: string, version?: string) => { + const { id: _id, orgId: _org, ...data } = assistantPayload(id, id, body); + return version === undefined ? data : { ...data, latestVersion: version }; + }; + const filePath = (id: string) => `resources/dev/assistants/${id}.md`; + const original = Object.fromEntries( + cases.map((c) => [ + c.id, + assistantFile( + c.id, + c.block ? "@include shared" : (c.localBody ?? "Base."), + ).replace( + "name:", + c.local ? `latestVersion: ${c.local}\nname:` : "name:", + ), + ]), + ); + const baselines = Object.fromEntries( + cases.map((c) => [c.id, hashPayload(config(c.id, "Base.", c.baseline))]), + ); + const remote = cases.map((c) => ({ + ...assistantPayload(c.id, c.id, c.remoteBody ?? "Base."), + latestVersion: c.remote, + })); + const f = await fixture( + t, + { + [statePath]: stateFile( + Object.fromEntries(cases.map(({ id }) => [id, id])), + ), + "templates/blocks/shared.md": "Base.", + ...Object.fromEntries( + cases.map(({ id }) => [filePath(id), original[id]!]), + ), + ...Object.fromEntries( + cases.map(({ id }) => [`${baselineDir}/${id}`, `${baselines[id]}\n`]), + ), + }, + { + assistant: remote, + credential: [ + { + id: "cred-uuid-unused", + orgId: "org-test", + name: "unused-credential", + }, + ], + }, + ); + + await t.test( + "audit distinguishes config edits from version movement", + async () => { + const { output } = await f.cli("audit", "dev", "--type", "assistants"); + const directions = Object.fromEntries( + [ + ...output.matchAll( + /\[content-drift\] assistants\/(\S+)\n\s+[^\n]+ \[(local-ahead|dashboard-ahead|both-diverged)\]/g, + ), + ].map(([, id, direction]) => [id, direction]), + ); + assert.deepEqual( + directions, + { + ambiguous: "both-diverged", + conflict: "both-diverged", + dashboard: "dashboard-ahead", + local: "local-ahead", + normalized: "local-ahead", + }, + output, + ); + }, + ); + + await t.test( + "push gates real and ambiguous conflicts and accepts a proven local edit", + async () => { + const { code, output } = await f.cli( + "push", + "dev", + ...["local", "dashboard", "conflict", "ambiguous"].map(filePath), + ); + assert.equal(code, 0, output); + for (const [id, direction] of [ + ["dashboard", "dashboard-ahead"], + ["conflict", "both-diverged"], + ["ambiguous", "both-diverged"], + ]) { + assert.ok( + output.includes(`drift detected on assistant ${id} [${direction}]`), + output, + ); + } + assert.deepEqual( + f.writes.map(({ path }) => path), + ["/assistant/local", "/assistant/local/versions/v-published"], + output, + ); + assert.doesNotMatch(JSON.stringify(f.writes[0]?.data), /latestVersion/); + assert.match( + String(f.writes[1]?.data.versionDescription), + /Changed: [^\n]*\bmodel\.messages\b/, + ); + assert.equal( + f.read(`${baselineDir}/local`).trim(), + hashPayload(config("local", "Local.")), + ); + }, + ); + + await t.test( + "pull accepts real dashboard edits and keeps conflicts and block markers", + async () => { + const { code, output } = await f.cli( + "pull", + "dev", + "--type", + "assistants", + ); + assert.equal(code, 1, output); + assert.match(output, /2 resource\(s\) have 3-way drift/); + assert.doesNotMatch(output, /block.*dashboard version differs/); + for (const id of ["advance", "rollback", "dashboard"]) { + assert.doesNotMatch(f.read(filePath(id)), /^latestVersion:/m, output); + } + assert.match(f.read(filePath("dashboard")), /Remote\./); + for (const id of ["ambiguous", "conflict", "block", "normalized"]) { + assert.equal(f.read(filePath(id)), original[id]); + } + for (const id of ["ambiguous", "conflict"]) { + assert.equal(f.read(`${baselineDir}/${id}`).trim(), baselines[id]); + } + for (const id of ["advance", "rollback", "block"]) { + assert.equal( + f.read(`${baselineDir}/${id}`).trim(), + hashPayload(config(id, "Base.")), + ); + } + assert.doesNotMatch(f.read(statePath), /latestVersion/); + }, + ); + + await t.test( + "automatic push bootstrap keeps unresolved baseline evidence", + async () => { + const state = JSON.parse(f.read(statePath)); + filesWrite(f.root, { + [statePath]: JSON.stringify({ ...state, credentials: {} }), + }); + f.writes.length = 0; + const { code, output } = await f.cli( + "push", + "dev", + filePath("ambiguous"), + ); + assert.match(output, /Bootstrap state sync required/); + assert.equal(code, 1, output); + assert.match( + output, + /drift detected on assistant ambiguous \[both-diverged\]/, + ); + assert.deepEqual(f.writes, []); + assert.equal( + f.read(`${baselineDir}/ambiguous`).trim(), + baselines.ambiguous, + ); + }, + ); + }); +}