Skip to content

Commit 53cf972

Browse files
feat(blocks): sync a block edit to every resource that uses it
A block edit changes what many resources send to Vapi without changing their files, so nothing in git said which resources still ran old text. Push now records the block content each resource went up with in resources/<org>/.vapi-blocks.json. "npm run sync-blocks" lists, across every org, the resources whose blocks changed since they were last pushed, and with --apply deploys them through apply, so the drift check still refuses a resource that was edited in the dashboard. Promotion plans those resources as "sync" entries for the destination org, the promotion workflow runs on templates/**, and a shared block edit selects every PR check. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
1 parent 69fb622 commit 53cf972

9 files changed

Lines changed: 781 additions & 3 deletions

File tree

‎.github/workflows/promotion.yml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ on:
66
paths:
77
- promotion.yml
88
- resources/**
9+
# Shared blocks: an edit changes resources without changing their files.
10+
- templates/**
911
workflow_dispatch:
1012
inputs:
1113
pipeline:

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
"check": "tsx src/check-cmd.ts",
2323
"rollback": "tsx src/rollback-cmd.ts",
2424
"promote": "tsx src/promote-cmd.ts",
25+
"sync-blocks": "tsx src/sync-blocks-cmd.ts",
2526
"build": "tsc --noEmit",
2627
"test": "node --import tsx --import ./tests/no-vapi-api.ts --test tests/*.test.ts"
2728
},

‎src/check-select.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ const ENGINE_PATTERNS = [
1212
CHECKS_CONFIG_FILE,
1313
"promotion.yml",
1414
"src/**",
15+
// Shared blocks are expanded into any org's resources. An org's own blocks
16+
// sit under resources/<org>/, which each check already watches.
17+
"templates/**",
1518
"package.json",
1619
"package-lock.json",
1720
];

‎src/promote-cmd.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,9 @@ async function transitionRun(
271271
`\n${transition.pipeline}: ${transition.source} → ${transition.target}`,
272272
);
273273
for (const change of plan.changes)
274-
console.log(` ${change.kind.padEnd(6)} ${change.path}`);
274+
console.log(
275+
` ${change.kind.padEnd(6)} ${change.path}${change.blocks ? ` (block changed: ${change.blocks.join(", ")})` : ""}`,
276+
);
275277
for (const warning of plan.warnings) console.warn(` ⚠️ ${warning}`);
276278
if (plan.changes.length === 0) console.log(" no changes");
277279
if (plan.changes.length === 0) return false;

‎src/promotion.ts‎

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,18 @@ import { dirname, extname, join, relative } from "node:path";
1111
import { pathToFileURL } from "node:url";
1212
import { isDeepStrictEqual } from "node:util";
1313
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
14-
import { FOLDER_MAP, VALID_EXTENSIONS } from "./resource-parse.ts";
14+
import {
15+
type BlockUsage,
16+
blockLayers,
17+
blocksChanged,
18+
blocksExpand,
19+
blocksRecordRead,
20+
} from "./blocks.ts";
21+
import {
22+
FOLDER_MAP,
23+
markdownResourceParse,
24+
VALID_EXTENSIONS,
25+
} from "./resource-parse.ts";
1526
import type { ResourceType, StateFile } from "./types.ts";
1627

1728
type BindingPolicy = "bind" | "omit";
@@ -46,9 +57,13 @@ export interface PromotionConfig {
4657
}
4758

4859
export interface PromotionChange {
49-
kind: "create" | "update" | "delete";
60+
// "sync": the target's file is already identical, but a block it uses has
61+
// changed since the target was last pushed, so it needs pushing again.
62+
kind: "create" | "update" | "delete" | "sync";
5063
path: string;
5164
content?: string;
65+
// For "sync": the block files that changed.
66+
blocks?: string[];
5267
}
5368

5469
export interface PromotionPlan {
@@ -606,6 +621,9 @@ export async function promotionPlanBuild(
606621
options.sourceState,
607622
);
608623
const targetByPath = new Map(target.map((file) => [file.path, file]));
624+
const targetDir = join(options.rootDir, "resources", options.target);
625+
const targetLayers = blockLayers(targetDir);
626+
const targetRecord = blocksRecordRead(targetDir);
609627
const sourcePaths = new Set([...wanted.values()].map((file) => file.path));
610628
const changes: PromotionChange[] = [];
611629
const warnings: string[] = [];
@@ -645,7 +663,32 @@ export async function promotionPlanBuild(
645663
warnings.push(
646664
`${file.path}: credentialIds entry "${alias}" is left out in ${options.target} (binding policy "omit"). Calls there can use only the keys still on the list, so that provider would run on Vapi's own key.`,
647665
);
666+
continue;
648667
}
668+
// Same file text in both orgs. The target still needs a push when a
669+
// block the file uses has changed since the target last received it:
670+
// blocks are expanded with the target's own folder first, at push time.
671+
let usage: BlockUsage;
672+
try {
673+
usage = blocksExpand(
674+
extname(file.path) === ".ts"
675+
? parsed.data
676+
: extname(file.path) === ".md"
677+
? markdownResourceParse(content)
678+
: parseYaml(content),
679+
targetLayers,
680+
).usage;
681+
} catch (error) {
682+
throw new Error(
683+
`${file.path} can't be expanded for ${options.target}: ${error instanceof Error ? error.message : error}`,
684+
);
685+
}
686+
const blocks = blocksChanged(
687+
usage,
688+
targetRecord[`${FOLDER_MAP[file.type]}/${file.id}`],
689+
);
690+
if (Object.keys(usage).length > 0 && blocks.length > 0)
691+
changes.push({ kind: "sync", path: file.path, blocks });
649692
}
650693
for (const file of target)
651694
if (
@@ -671,6 +714,7 @@ export async function promotionPlanApply(plan: PromotionPlan): Promise<void> {
671714
await rm(path, { force: true });
672715
continue;
673716
}
717+
if (change.kind === "sync") continue;
674718
await mkdir(dirname(path), { recursive: true });
675719
await writeFile(path, change.content ?? "");
676720
}

‎src/push.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { select } from "@inquirer/prompts";
22
import { relative, resolve } from "path";
33
import { fileURLToPath } from "url";
44
import { getDryRunCounts, VapiApiError, vapiRequest } from "./api.ts";
5+
import { type BlockUsage, blocksRecordUpdate } from "./blocks.ts";
56
import { canonicalizeForHash, type VapiResource } from "./canonical.ts";
67
import {
78
ALLOW_NEW_FILES,
@@ -223,6 +224,15 @@ async function writeAssistantVersionMetadata(options: {
223224
}
224225
}
225226

227+
// Every resource this run created or updated on the platform, as
228+
// "<type folder>/<id>". The blocks record marks a resource as in sync with
229+
// its blocks only when it is in here: a skipped or refused push is not.
230+
const pushedResources = new Set<string>();
231+
232+
function pushedRecord(type: ResourceType | undefined, resourceId: string) {
233+
if (type) pushedResources.add(`${FOLDER_MAP[type]}/${resourceId}`);
234+
}
235+
226236
async function upsertResourceWithStateRecovery(options: {
227237
resourceLabel: string;
228238
resourceId: string;
@@ -262,6 +272,7 @@ async function upsertResourceWithStateRecovery(options: {
262272
after: result,
263273
});
264274
}
275+
pushedRecord(RESOURCE_LABEL_TO_TYPE[resourceLabel], resourceId);
265276
return result.id;
266277
}
267278

@@ -416,6 +427,7 @@ async function upsertResourceWithStateRecovery(options: {
416427
after: result,
417428
});
418429
}
430+
pushedRecord(RESOURCE_LABEL_TO_TYPE[resourceLabel], resourceId);
419431
return existingUuid;
420432
} catch (error) {
421433
if (!(error instanceof VapiApiError) || error.statusCode !== 404) {
@@ -1033,11 +1045,13 @@ export async function applyEval(
10331045
updatePayload,
10341046
);
10351047
await writeBaselineFromResponse(existingUuid, result, state);
1048+
pushedRecord("evals", resourceId);
10361049
return existingUuid;
10371050
} else {
10381051
console.log(` ✨ Creating eval: ${resourceId}`);
10391052
const result = await vapiRequest("POST", "/eval", payload);
10401053
await writeBaselineFromResponse(result.id, result, state);
1054+
pushedRecord("evals", resourceId);
10411055
return result.id;
10421056
}
10431057
}
@@ -1630,6 +1644,11 @@ async function main(): Promise<void> {
16301644
// merge into existing on-disk state instead of rewriting wholesale.
16311645
const touched: TouchedSets = emptyTouchedSets();
16321646

1647+
// The blocks every local resource uses, keyed "<type folder>/<id>". Set
1648+
// once the files have loaded, so a run that fails before then leaves the
1649+
// blocks record alone.
1650+
let blocksUsed: Map<string, BlockUsage> | undefined;
1651+
16331652
// Track what was applied for summary
16341653
const applied: Record<ResourceType, number> = {
16351654
tools: 0,
@@ -1715,6 +1734,14 @@ async function main(): Promise<void> {
17151734
simulationSuites: allSimulationSuitesRaw,
17161735
evals: allEvalsRaw,
17171736
};
1737+
blocksUsed = new Map(
1738+
(Object.keys(loadedResources) as ResourceType[]).flatMap((type) =>
1739+
loadedResources[type].map((file) => [
1740+
`${FOLDER_MAP[type]}/${file.resourceId}`,
1741+
file.blocks ?? {},
1742+
]),
1743+
),
1744+
);
17181745

17191746
state = await maybeBootstrapState(loadedResources, state);
17201747

@@ -2313,6 +2340,18 @@ async function main(): Promise<void> {
23132340
` Local state may be out of sync with platform. Run \`npm run pull -- ${VAPI_ENV} --bootstrap\` to recover.`,
23142341
);
23152342
}
2343+
// Record the block content each pushed resource went up with, so
2344+
// sync-blocks and promotion can tell which resources a later block
2345+
// edit has not reached yet.
2346+
try {
2347+
if (blocksUsed)
2348+
blocksRecordUpdate(RESOURCES_DIR, blocksUsed, pushedResources);
2349+
} catch (recordError) {
2350+
console.error(
2351+
"\n⚠️ Failed to update the blocks record after apply:",
2352+
recordError instanceof Error ? recordError.message : recordError,
2353+
);
2354+
}
23162355
}
23172356
}
23182357
}

0 commit comments

Comments
 (0)