Skip to content

Commit d87f6d1

Browse files
fix: integrate blocks with adoption folder hashes and strict preflight
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent ae0a482 commit d87f6d1

14 files changed

Lines changed: 381 additions & 64 deletions

‎AGENTS.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,8 @@ Nothing was written to the remote API"), a resource the push would write (one
209209
you selected, or a dependency it would create) has a validation error or an
210210
unresolved credential. Fix the listed findings and rerun; nothing was applied,
211211
so there is nothing to roll back. Errors in files outside the push only warn
212-
(`--strict` blocks those too). The preflight only catches what `validate`
212+
(`--strict` blocks those too, as well as `variable-undefined` warnings).
213+
The preflight only catches what `validate`
213214
knows about, so an API rejection can still leave a push partly applied.
214215

215216
If something goes wrong: `npm run rollback -- <org> --list`, then (with a yes)

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ More detail: [How the engine works](docs/guides/how-it-works.md).
224224
| `npm run validate -- <org> [--strict]` | Check resource files offline, including undefined squad variables (`variable-undefined`); `--strict` blocks on that warning. `transfer-number-liquid` always errors on Liquid in transfer destination numbers; use per-practice literal numbers (see `examples/nhs-shared-squads`). |
225225
| `npm run apply -- <org>` | Deploy: pull, merge, then preflight and push (the default) |
226226
| `npm run pull -- <org>` | Sync platform changes down without overwriting local edits; unknown UUIDs get separate files, never name-linked |
227-
| `npm run push -- <org>` | Preflight the write plan, then push without pulling first (prefer `apply`); `--strict` also blocks validation errors outside the plan. 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). |
227+
| `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). |
228228
| `npm run rollback -- <org>` | Restore a pre-deploy snapshot |
229229
| `npm run cleanup -- <org>` | Find, and optionally delete, platform resources with no file |
230230
| `npm run audit -- <org>` | Report drift between files, state and the platform |

‎docs/guides/commands.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ The other commands are direct only.
1313
| `npm run validate` | `npm run validate -- <org> [--strict]` | Check resource files offline: API shape rules, references, and undefined squad variables. `variable-undefined` warns once per squad member, listing missing root names and where to define them; `--strict` makes this warning blocking in validate and push. `transfer-number-liquid` is always an error: the API rejects Liquid in transfer destination numbers, even with `numberE164CheckEnabled:false`; use per-practice literal numbers, e.g. inline in squad `membersOverrides['tools:append']` (see `examples/nhs-shared-squads`). Covers standalone tools, inline model tools and member/squad appended tools. `apply` runs validation first. On GitHub Actions, findings are also shown on the files in the pull request. |
1414
| `npm run apply` | `npm run apply -- <org> [types or paths] [--adopt <id>[=<uuid>]]` | **The default deploy:** pull, merge, then push. The push preflight below runs before remote writes. See [workflows](workflows.md). |
1515
| `npm run pull` | `npm run pull -- <org> [--force] [--bootstrap]` | Sync platform changes down; never overwrites local edits unless `--force`. |
16-
| `npm run push` | `npm run push -- <org> [--dry-run] [--json] [--strict] [--adopt <id>[=<uuid>]]` | Push without pulling first. Prefer `apply`. Preflight blocks validation errors and unresolved credential names in the write plan (selected resources plus auto-applied dependencies) before any remote mutation, including deletions. `--dry-run` uses the same gate. `--strict` additionally blocks error-severity findings outside the plan; warnings remain advisory. Bootstrap reads may run before preflight. |
16+
| `npm run push` | `npm run push -- <org> [--dry-run] [--json] [--strict] [--adopt <id>[=<uuid>]]` | Push without pulling first. Prefer `apply`. Preflight blocks validation errors and unresolved credential names in the write plan (selected resources plus auto-applied dependencies) before any remote mutation, including deletions. `--dry-run` uses the same gate. `--strict` additionally blocks error-severity findings outside the plan; `variable-undefined` warnings also block under `--strict`; other warnings remain advisory. Bootstrap reads may run before preflight. |
1717
| `npm run rollback` | `npm run rollback -- <org> --list` or `--to <ISO>` | Restore a pre-deploy snapshot from `state/<org>/local/snapshots/`. |
1818
| `npm run cleanup` | `npm run cleanup -- <org> [--force --confirm <org>]` | List platform resources with no file; delete them only with both flags. |
1919
| `npm run audit` | `npm run audit -- <org> [--type <type>]` | Report drift between files, state and the platform. Exits 1 on any finding, so it can run in CI. |

‎src/adopt-alias-files.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { confirm } from "@inquirer/prompts";
22
import { rm } from "fs/promises";
33
import { relative } from "path";
44
import type { AdoptionAlias } from "./adopt.ts";
5-
import { BASE_DIR, DRY_RUN, VAPI_ENV } from "./config.ts";
5+
import { BASE_DIR, DRY_RUN, RESOURCES_DIR, VAPI_ENV } from "./config.ts";
66
import { deleteBaseline, readBaseline } from "./hash-store.ts";
77
import { parseResourceDataFromFile } from "./resource-parse.ts";
88
import { hashPayload } from "./state-serialize.ts";
@@ -26,7 +26,9 @@ export async function prepareAliasCleanup(
2626
const path = relative(BASE_DIR, file.filePath);
2727
let hash: string | undefined;
2828
try {
29-
hash = hashPayload(parseResourceDataFromFile(file.filePath));
29+
hash = hashPayload(
30+
parseResourceDataFromFile(file.filePath, RESOURCES_DIR),
31+
);
3032
} catch {}
3133
const baseline = readBaseline(VAPI_ENV, uuid);
3234
if (!baseline || hash !== baseline) {

‎src/pull.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -637,7 +637,7 @@ async function blocksFilePull(options: {
637637
return;
638638
}
639639
const platformHash = hashPayload(
640-
canonicalizeForHash(resource, state, options.credReverse),
640+
canonicalizeForHash(resource, state, options.credReverse, resourceType),
641641
);
642642
const baseline = readBaseline(VAPI_ENV, resource.id);
643643
const direction = classifyDrift({

‎src/push-plan.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,9 @@ export function pushBlockingFindings(
6565
return findings
6666
.filter(
6767
(finding) =>
68-
(finding.severity === "error" && strict) ||
68+
(strict &&
69+
(finding.severity === "error" ||
70+
finding.rule === "variable-undefined")) ||
6971
(plan.has(`${finding.type}:${finding.resourceId}`) &&
7072
(finding.severity === "error" ||
7173
finding.rule === "unresolved-credential")),

‎src/resource-parse.ts‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,7 @@ export const FOLDER_MAP: Record<ResourceType, string> = {
4646
evals: "evals",
4747
};
4848

49-
// Single source of truth for resource file extensions. Imported by
50-
// `recanonicalize.ts` so the precondition-5 "both files exist" check
51-
// stays in lockstep with the loader — without this, a `.ts`-authored
52-
// resource paired with a UUID-suffixed `.ts` twin would be invisible to
53-
// the safety check and silently allow the data-loss shape the
54-
// recanonicalize header explicitly refuses.
49+
// Single source of truth for resource file extensions.
5550
export const VALID_EXTENSIONS: readonly string[] = [
5651
".yml",
5752
".yaml",

‎src/slug-utils.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,15 @@
66
// - `slugify(name)` — 4 byte-identical copies
77
// - `extractBaseSlug(resourceId)` — 2 byte-identical copies
88
//
9-
// It also exposes the strict `isEngineSuffixedSlug` form used by
10-
// `recanonicalize.ts` to prove a state key was engine-generated (i.e. the
9+
// It also exposes the strict `isEngineSuffixedSlug` form to check whether
10+
// a state key has an engine-generated shape (i.e. the
1111
// captured 8-hex matches the entry's UUID prefix), and the canonical
1212
// `UUID_SUFFIX_RE` constant.
1313
//
1414
// Config-free is load-bearing: `config.ts` asserts `argv[2]` / `VAPI_TOKEN`
1515
// at module load. Any test that imports a slug helper without going through
1616
// this module would otherwise have to prime `process.argv` and
17-
// `process.env.VAPI_TOKEN` (see `tests/recanonicalize.test.ts:7-8`). This
17+
// `process.env.VAPI_TOKEN`. This
1818
// module has zero such side effects so it's safely importable from any test.
1919
// ─────────────────────────────────────────────────────────────────────────────
2020

@@ -55,8 +55,7 @@ export function extractBaseSlug(resourceId: string): string {
5555
// the resourceId doesn't match the engine shape at all.
5656
//
5757
// Use this when you have BOTH a state key AND its entry's UUID and need to
58-
// prove the key was engine-generated (the precondition-2 check in
59-
// `recanonicalize.ts`). A user-given name that coincidentally ends in
58+
// check the key against the engine-generated shape. A user-given name that coincidentally ends in
6059
// `-abcd1234` will NOT match because its UUID prefix is different.
6160
//
6261
// Mirrors `generateResourceId` in `src/pull.ts:265-273` — UUIDs have the

‎src/sync-blocks-cmd.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,8 @@ function orgsRead(rootDir: string): string[] {
4141
return readdirSync(resources)
4242
.filter(
4343
(entry) =>
44-
!entry.startsWith(".") && statSync(join(resources, entry)).isDirectory(),
44+
!entry.startsWith(".") &&
45+
statSync(join(resources, entry)).isDirectory(),
4546
)
4647
.sort();
4748
}
@@ -96,8 +97,7 @@ export async function syncBlocksRun(
9697
overrides: Partial<SyncBlocksDeps> = {},
9798
): Promise<number> {
9899
const rootDir =
99-
overrides.rootDir ??
100-
resolve(process.env.VAPI_GITOPS_ROOT ?? baseDir());
100+
overrides.rootDir ?? resolve(process.env.VAPI_GITOPS_ROOT ?? baseDir());
101101
const deploy =
102102
overrides.applyRun ??
103103
((org: string, paths: string[]) => applyRun(rootDir, org, paths));

‎tests/blocks-integration.test.ts‎

Lines changed: 259 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,259 @@
1+
import "./engine-sandbox.ts";
2+
import assert from "node:assert/strict";
3+
import { spawnSync } from "node:child_process";
4+
import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
5+
import { join } from "node:path";
6+
import test from "node:test";
7+
import { fileURLToPath } from "node:url";
8+
import {
9+
assistantFile,
10+
assistantPayload,
11+
cliRun,
12+
engineRepoCreate,
13+
stateFile,
14+
stubStart,
15+
} from "./blocks-helpers.ts";
16+
17+
const ORG = "block-integration";
18+
const UUID = "aaaaaaaa-1111-4111-8111-111111111111";
19+
20+
function scriptRun(root: string, script: string): void {
21+
const result = spawnSync(
22+
process.execPath,
23+
[
24+
"--import",
25+
"tsx",
26+
"--input-type=module",
27+
"-e",
28+
`
29+
import assert from "node:assert/strict";
30+
process.argv = ["node", "test", "${ORG}"];
31+
process.env.VAPI_TOKEN = "fake";
32+
${script}
33+
`,
34+
],
35+
{
36+
cwd: root,
37+
env: { ...process.env },
38+
encoding: "utf8",
39+
timeout: 20000,
40+
},
41+
);
42+
assert.equal(result.status, 0, result.stdout + result.stderr);
43+
}
44+
45+
test("adoption expands block aliases before comparing baselines and refuses unsafe aliases", () => {
46+
const root = engineRepoCreate({
47+
"templates/blocks/greeting.md": "Hello.",
48+
[`resources/${ORG}/assistants/alias.md`]: assistantFile(
49+
"Triage",
50+
"@include greeting",
51+
),
52+
});
53+
try {
54+
scriptRun(
55+
root,
56+
`
57+
const { existsSync, writeFileSync, unlinkSync } = await import("node:fs");
58+
const { prepareAliasCleanup } = await import("./src/adopt-alias-files.ts");
59+
const { writeBaseline, readBaseline } = await import("./src/hash-store.ts");
60+
const { canonicalizeForHash } = await import("./src/canonical.ts");
61+
const { hashPayload } = await import("./src/state-serialize.ts");
62+
const { createEmptyState } = await import("./src/state.ts");
63+
const { RESOURCES_DIR } = await import("./src/config.ts");
64+
const path = RESOURCES_DIR + "/assistants/alias.md";
65+
const resources = Object.fromEntries(Object.keys(createEmptyState()).filter(k => k !== "credentials").map(k => [k, []]));
66+
resources.assistants.push({ resourceId: "alias", filePath: path, data: {} });
67+
const aliases = [{ type: "assistants", resourceId: "alias", uuid: "${UUID}", adoptedAs: "triage" }];
68+
const hash = hashPayload(canonicalizeForHash(${JSON.stringify(assistantPayload(UUID, "Triage", "Hello."))}, createEmptyState(), new Map(), "assistants"));
69+
assert.deepEqual((await prepareAliasCleanup([], resources)).problems, []);
70+
assert.equal((await prepareAliasCleanup(aliases, resources)).problems.length, 1);
71+
await writeBaseline("${ORG}", "${UUID}", hash);
72+
writeFileSync("templates/blocks/greeting.md", "Edited locally.");
73+
assert.equal((await prepareAliasCleanup(aliases, resources)).problems.length, 1);
74+
assert.ok(existsSync(path));
75+
unlinkSync("templates/blocks/greeting.md");
76+
assert.equal((await prepareAliasCleanup(aliases, resources)).problems.length, 1);
77+
assert.ok(existsSync(path));
78+
writeFileSync("templates/blocks/greeting.md", "Hello.");
79+
const cleanup = await prepareAliasCleanup(aliases, resources);
80+
assert.deepEqual(cleanup.problems, []);
81+
await cleanup.run();
82+
assert.equal(existsSync(path), false);
83+
assert.deepEqual(resources.assistants, []);
84+
assert.equal(readBaseline("${ORG}", "${UUID}"), undefined);
85+
`,
86+
);
87+
} finally {
88+
rmSync(root, { recursive: true, force: true });
89+
}
90+
});
91+
92+
test("local hashes expand blocks and ignore folder metadata only for assistants", () => {
93+
const data = {
94+
name: "Triage",
95+
model: { messages: [{ role: "system", content: "@include greeting" }] },
96+
metadata: {
97+
folderPath: "user",
98+
gitops: { owner: "repo", folderPath: "old" },
99+
},
100+
};
101+
const root = engineRepoCreate({
102+
"templates/blocks/greeting.md": "Hello.",
103+
[`resources/${ORG}/assistants/support/triage.yml`]: JSON.stringify(data),
104+
[`resources/${ORG}/squads/triage.yml`]: JSON.stringify(data),
105+
[`resources/${ORG}/assistants/empty.yml`]: "{}",
106+
[`resources/${ORG}/assistants/broken.md`]: assistantFile(
107+
"Broken",
108+
"@include missing",
109+
),
110+
});
111+
try {
112+
scriptRun(
113+
root,
114+
`
115+
const { hashLocalResource } = await import("./src/resources.ts");
116+
const { hashPayload } = await import("./src/state-serialize.ts");
117+
const expanded = ${JSON.stringify({ ...data, model: { messages: [{ role: "system", content: "Hello." }] } })};
118+
assert.equal(hashLocalResource("squads", "triage"), hashPayload(expanded));
119+
delete expanded.metadata.gitops.folderPath;
120+
assert.equal(hashLocalResource("assistants", "support/triage"), hashPayload(expanded));
121+
assert.equal(hashLocalResource("assistants", "empty"), hashPayload({}));
122+
assert.equal(hashLocalResource("assistants", "missing"), null);
123+
assert.equal(hashLocalResource("assistants", "broken"), null);
124+
`,
125+
);
126+
} finally {
127+
rmSync(root, { recursive: true, force: true });
128+
}
129+
});
130+
131+
test("repeated pull of a subfolder block assistant ignores derived folder metadata", async () => {
132+
const path = `resources/${ORG}/assistants/support/triage.md`;
133+
const authored = assistantFile("Triage", "@include greeting");
134+
const root = engineRepoCreate({
135+
"templates/blocks/greeting.md": "Hello.",
136+
[path]: authored,
137+
[`state/${ORG}/state.json`]: stateFile({ "support/triage": UUID }),
138+
});
139+
const stub = await stubStart([
140+
{
141+
method: "GET",
142+
pathStartsWith: "/assistant",
143+
body: [
144+
{
145+
...assistantPayload(UUID, "Triage", "Hello."),
146+
metadata: { gitops: { folderPath: "support" } },
147+
},
148+
],
149+
},
150+
]);
151+
try {
152+
for (let i = 0; i < 2; i++) {
153+
const result = cliRun(root, "src/pull.ts", [ORG], stub.port);
154+
assert.equal(result.code, 0, result.output);
155+
assert.match(
156+
result.output,
157+
/support\/triage \(uses blocks, matches the dashboard/,
158+
);
159+
assert.doesNotMatch(
160+
result.output,
161+
/support\/triage:|support\/triage \(local ahead/,
162+
);
163+
assert.equal(readFileSync(join(root, path), "utf8"), authored);
164+
assert.deepEqual(
165+
readdirSync(join(root, `resources/${ORG}/assistants/support`)),
166+
["triage.md"],
167+
);
168+
}
169+
} finally {
170+
await stub.stop();
171+
rmSync(root, { recursive: true, force: true });
172+
}
173+
});
174+
175+
test("block-expanded undefined variables block strict validate and push before mutations", async () => {
176+
const tracked = JSON.parse(stateFile({ triage: UUID }));
177+
tracked.squads.team = { uuid: "bbbbbbbb-2222-4222-8222-222222222222" };
178+
const root = engineRepoCreate({
179+
"templates/blocks/greeting.md": "Welcome to {{practice}}.",
180+
[`resources/${ORG}/assistants/triage.md`]: assistantFile(
181+
"Triage",
182+
"@include greeting",
183+
),
184+
[`resources/${ORG}/squads/team.yml`]:
185+
"name: Team\nmembers:\n - assistantId: triage\n",
186+
[`state/${ORG}/state.json`]: JSON.stringify(tracked),
187+
});
188+
const assistant = assistantPayload(
189+
UUID,
190+
"Triage",
191+
"Welcome to {{practice}}.",
192+
);
193+
const squad = {
194+
id: tracked.squads.team.uuid,
195+
name: "Team",
196+
members: [{ assistantId: UUID }],
197+
};
198+
const stub = await stubStart([
199+
{ method: "GET", pathStartsWith: `/assistant/${UUID}`, body: assistant },
200+
{ method: "GET", pathStartsWith: "/assistant", body: [assistant] },
201+
{ method: "GET", pathStartsWith: `/squad/${squad.id}`, body: squad },
202+
{ method: "GET", pathStartsWith: "/squad", body: [squad] },
203+
]);
204+
try {
205+
for (const strict of [false, true]) {
206+
const result = cliRun(
207+
root,
208+
"src/validate-cmd.ts",
209+
[ORG, ...(strict ? ["--strict"] : [])],
210+
stub.port,
211+
);
212+
assert.equal(result.code, strict ? 1 : 0, result.output);
213+
assert.match(result.output, /variable-undefined/);
214+
}
215+
const advisory = cliRun(root, "src/push.ts", [ORG, "--dry-run"], stub.port);
216+
assert.equal(advisory.code, 0, advisory.output);
217+
assert.match(advisory.output, /variable-undefined/);
218+
for (const flags of [
219+
[],
220+
["--dry-run"],
221+
[`resources/${ORG}/assistants/triage.md`],
222+
]) {
223+
const result = cliRun(
224+
root,
225+
"src/push.ts",
226+
[ORG, "--strict", ...flags],
227+
stub.port,
228+
);
229+
assert.equal(result.code, 1, result.output);
230+
assert.match(result.output, /variable-undefined/);
231+
assert.match(result.output, /Nothing was written to the remote API/);
232+
}
233+
assert.deepEqual(
234+
(await stub.requests()).filter((request) =>
235+
/^(POST|PATCH|DELETE) /.test(request),
236+
),
237+
[],
238+
);
239+
} finally {
240+
await stub.stop();
241+
rmSync(root, { recursive: true, force: true });
242+
}
243+
});
244+
245+
test("block integrations do not restore the removed recanonicalize module", () => {
246+
const src = fileURLToPath(new URL("../src", import.meta.url));
247+
assert.equal(existsSync(join(src, "recanonicalize.ts")), false);
248+
for (const file of readdirSync(src).filter((file) => file.endsWith(".ts"))) {
249+
const code = readFileSync(join(src, file), "utf8")
250+
.split("\n")
251+
.filter((line) => !line.trimStart().startsWith("//"))
252+
.join("\n");
253+
assert.doesNotMatch(
254+
code,
255+
/recanonicalizeStateKeys|formatRecanonicalizeReport|["\x27].*recanonicalize\.ts["\x27]/,
256+
file,
257+
);
258+
}
259+
});

0 commit comments

Comments
 (0)