Skip to content

Commit b040184

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 e6707bf commit b040184

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
@@ -266,7 +266,9 @@ async function transitionRun(
266266
`\n${transition.pipeline}: ${transition.source} → ${transition.target}`,
267267
);
268268
for (const change of plan.changes)
269-
console.log(` ${change.kind.padEnd(6)} ${change.path}`);
269+
console.log(
270+
` ${change.kind.padEnd(6)} ${change.path}${change.blocks ? ` (block changed: ${change.blocks.join(", ")})` : ""}`,
271+
);
270272
for (const warning of plan.warnings) console.warn(` ⚠️ ${warning}`);
271273
if (plan.changes.length === 0) console.log(" no changes");
272274
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,
@@ -220,6 +221,15 @@ async function writeAssistantVersionMetadata(options: {
220221
}
221222
}
222223

224+
// Every resource this run created or updated on the platform, as
225+
// "<type folder>/<id>". The blocks record marks a resource as in sync with
226+
// its blocks only when it is in here: a skipped or refused push is not.
227+
const pushedResources = new Set<string>();
228+
229+
function pushedRecord(type: ResourceType | undefined, resourceId: string) {
230+
if (type) pushedResources.add(`${FOLDER_MAP[type]}/${resourceId}`);
231+
}
232+
223233
async function upsertResourceWithStateRecovery(options: {
224234
resourceLabel: string;
225235
resourceId: string;
@@ -259,6 +269,7 @@ async function upsertResourceWithStateRecovery(options: {
259269
after: result,
260270
});
261271
}
272+
pushedRecord(RESOURCE_LABEL_TO_TYPE[resourceLabel], resourceId);
262273
return result.id;
263274
}
264275

@@ -413,6 +424,7 @@ async function upsertResourceWithStateRecovery(options: {
413424
after: result,
414425
});
415426
}
427+
pushedRecord(RESOURCE_LABEL_TO_TYPE[resourceLabel], resourceId);
416428
return existingUuid;
417429
} catch (error) {
418430
if (!(error instanceof VapiApiError) || error.statusCode !== 404) {
@@ -1030,11 +1042,13 @@ export async function applyEval(
10301042
updatePayload,
10311043
);
10321044
await writeBaselineFromResponse(existingUuid, result, state);
1045+
pushedRecord("evals", resourceId);
10331046
return existingUuid;
10341047
} else {
10351048
console.log(` ✨ Creating eval: ${resourceId}`);
10361049
const result = await vapiRequest("POST", "/eval", payload);
10371050
await writeBaselineFromResponse(result.id, result, state);
1051+
pushedRecord("evals", resourceId);
10381052
return result.id;
10391053
}
10401054
}
@@ -1627,6 +1641,11 @@ async function main(): Promise<void> {
16271641
// merge into existing on-disk state instead of rewriting wholesale.
16281642
const touched: TouchedSets = emptyTouchedSets();
16291643

1644+
// The blocks every local resource uses, keyed "<type folder>/<id>". Set
1645+
// once the files have loaded, so a run that fails before then leaves the
1646+
// blocks record alone.
1647+
let blocksUsed: Map<string, BlockUsage> | undefined;
1648+
16301649
// Track what was applied for summary
16311650
const applied: Record<ResourceType, number> = {
16321651
tools: 0,
@@ -1712,6 +1731,14 @@ async function main(): Promise<void> {
17121731
simulationSuites: allSimulationSuitesRaw,
17131732
evals: allEvalsRaw,
17141733
};
1734+
blocksUsed = new Map(
1735+
(Object.keys(loadedResources) as ResourceType[]).flatMap((type) =>
1736+
loadedResources[type].map((file) => [
1737+
`${FOLDER_MAP[type]}/${file.resourceId}`,
1738+
file.blocks ?? {},
1739+
]),
1740+
),
1741+
);
17151742

17161743
state = await maybeBootstrapState(loadedResources, state);
17171744

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

0 commit comments

Comments
 (0)