Skip to content

Commit 55e2a7f

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 9e4fffa commit 55e2a7f

9 files changed

Lines changed: 780 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
"test:repository": "node --import tsx --import ./tests/no-vapi-api.ts --test --test-concurrency=1 tests/repository/*.test.ts"

‎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
@@ -270,7 +270,9 @@ async function transitionRun(
270270
`\n${transition.pipeline}: ${transition.source} → ${transition.target}`,
271271
);
272272
for (const change of plan.changes)
273-
console.log(` ${change.kind.padEnd(6)} ${change.path}`);
273+
console.log(
274+
` ${change.kind.padEnd(6)} ${change.path}${change.blocks ? ` (block changed: ${change.blocks.join(", ")})` : ""}`,
275+
);
274276
for (const warning of plan.warnings) console.warn(` ⚠️ ${warning}`);
275277
if (plan.changes.length === 0) console.log(" no changes");
276278
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: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { relative, resolve } from "path";
33
import { fileURLToPath } from "url";
44
import { getDryRunCounts, VapiApiError, vapiRequest } from "./api.ts";
55
import { withAssistantFolder } from "./assistant-folder.ts";
6+
import { type BlockUsage, blocksRecordUpdate } from "./blocks.ts";
67
import { canonicalizeForHash, type VapiResource } from "./canonical.ts";
78
import {
89
APPLY_FILTER,
@@ -229,6 +230,14 @@ async function writeAssistantVersionMetadata(options: {
229230

230231
let dryRunCollisions: NameCollisionReport | undefined;
231232

233+
// Every resource this run created or updated on the platform, as
234+
// "<type folder>/<id>". The blocks record marks a resource as in sync with
235+
// its blocks only when it is in here: a skipped or refused push is not.
236+
const pushedResources = new Set<string>();
237+
238+
function pushedRecord(type: ResourceType | undefined, resourceId: string) {
239+
if (type) pushedResources.add(`${FOLDER_MAP[type]}/${resourceId}`);
240+
}
232241
async function upsertResourceWithStateRecovery(options: {
233242
resourceLabel: string;
234243
resourceId: string;
@@ -285,6 +294,7 @@ async function upsertResourceWithStateRecovery(options: {
285294
after: result,
286295
});
287296
}
297+
pushedRecord(RESOURCE_LABEL_TO_TYPE[resourceLabel], resourceId);
288298
return result.id;
289299
}
290300

@@ -444,6 +454,7 @@ async function upsertResourceWithStateRecovery(options: {
444454
after: result,
445455
});
446456
}
457+
pushedRecord(RESOURCE_LABEL_TO_TYPE[resourceLabel], resourceId);
447458
return existingUuid;
448459
} catch (error) {
449460
if (!(error instanceof VapiApiError) || error.statusCode !== 404) {
@@ -1064,13 +1075,15 @@ export async function applyEval(
10641075
updatePayload,
10651076
);
10661077
await writeBaselineFromResponse(existingUuid, result, state);
1078+
pushedRecord("evals", resourceId);
10671079
return existingUuid;
10681080
} else {
10691081
dryRunCollisions?.recordPost("evals", resourceId, payload, state.evals);
10701082
console.log(` ✨ Creating eval: ${resourceId}`);
10711083
const result = await vapiRequest("POST", "/eval", payload);
10721084
upsertState(state.evals, resourceId, { uuid: result.id, origin: "pushed" });
10731085
await writeBaselineFromResponse(result.id, result, state);
1086+
pushedRecord("evals", resourceId);
10741087
return result.id;
10751088
}
10761089
}
@@ -1666,6 +1679,11 @@ async function main(): Promise<void> {
16661679
// merge into existing on-disk state instead of rewriting wholesale.
16671680
const touched: TouchedSets = emptyTouchedSets();
16681681

1682+
// The blocks every local resource uses, keyed "<type folder>/<id>". Set
1683+
// once the files have loaded, so a run that fails before then leaves the
1684+
// blocks record alone.
1685+
let blocksUsed: Map<string, BlockUsage> | undefined;
1686+
16691687
// Track what was applied for summary
16701688
const applied: Record<ResourceType, number> = {
16711689
tools: 0,
@@ -1751,6 +1769,14 @@ async function main(): Promise<void> {
17511769
simulationSuites: allSimulationSuitesRaw,
17521770
evals: allEvalsRaw,
17531771
};
1772+
blocksUsed = new Map(
1773+
(Object.keys(loadedResources) as ResourceType[]).flatMap((type) =>
1774+
loadedResources[type].map((file) => [
1775+
`${FOLDER_MAP[type]}/${file.resourceId}`,
1776+
file.blocks ?? {},
1777+
]),
1778+
),
1779+
);
17541780

17551781
const inventories = new Map<ResourceType, Promise<RemoteResource[]>>();
17561782
const links = await prepareResourceLinks({
@@ -2350,6 +2376,18 @@ async function main(): Promise<void> {
23502376
` Local state may be out of sync with platform. Run \`npm run pull -- ${VAPI_ENV} --bootstrap\` to recover.`,
23512377
);
23522378
}
2379+
// Record the block content each pushed resource went up with, so
2380+
// sync-blocks and promotion can tell which resources a later block
2381+
// edit has not reached yet.
2382+
try {
2383+
if (blocksUsed)
2384+
blocksRecordUpdate(RESOURCES_DIR, blocksUsed, pushedResources);
2385+
} catch (recordError) {
2386+
console.error(
2387+
"\n⚠️ Failed to update the blocks record after apply:",
2388+
recordError instanceof Error ? recordError.message : recordError,
2389+
);
2390+
}
23532391
}
23542392
}
23552393
}

0 commit comments

Comments
 (0)