Skip to content

Commit 4f41c23

Browse files
Write assistant folder to metadata.gitops.folderPath on push (#106)
* feat(push): sync assistant subfolders as derived metadata Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * feat(push): namespace one-level assistant folder metadata Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix(push): preserve full assistant subfolder paths Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: dhruva <dhruva@vapi.ai> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent 311fb97 commit 4f41c23

11 files changed

Lines changed: 364 additions & 16 deletions

File tree

‎AGENTS.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,17 @@ default-exports the object (safety rule 5).
258258

259259
The engine resolves IDs and credential names to each org's UUIDs on push.
260260

261+
Assistant subfolders are pushed as derived `metadata.gitops.folderPath` (for example
262+
`assistants/support/intake.yml` → `support`). Other metadata and sibling `gitops`
263+
keys are preserved; top-level `metadata.folderPath` is a user key, left untouched.
264+
The full subfolder path is preserved:
265+
`assistants/support/intake/b.yml` → `support/intake`.
266+
Root assistants send `metadata.gitops.folderPath: null`, clearing stale grouping.
267+
Pull and drift exclude this key; don't author it locally. File moves still require the normal
268+
filename/state mapping safeguards below. Other resource types are unchanged.
269+
If authored, `metadata.gitops` must be a plain object. Pull removes only the
270+
derived key, dropping `gitops` and `metadata` only if they become empty.
271+
261272
### Naming and renaming
262273

263274
- **Files you create keep their names.** Resources pulled from the platform
@@ -272,7 +283,7 @@ The engine resolves IDs and credential names to each org's UUIDs on push.
272283
| To rename… | Do this |
273284
| --- | --- |
274285
| The display name | Change `name` in the file (or in the dashboard, then pull). The filename stays. |
275-
| The file itself | A renamed file has no state entry, so the next deploy stops at the new-file check. Either keep the old filename, or (with the human's agreement) deploy it as new with `--allow-new-files` and delete the old platform resource with `npm run cleanup -- <org> --force --confirm <org>`. |
286+
| The file itself | A renamed or moved file has no state entry. With the human's agreement, use `--adopt <new-resourceId>=<uuid>` to keep managing the same platform resource under the new path. Without adoption, an unlinked file is created as a new resource, not matched by name. |
276287

277288
### Excluding resources (`.vapi-ignore`)
278289

‎README.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,17 @@ To test every pull request automatically, set up [PR checks](docs/guides/pr-chec
182182
- **Secrets stay out of git.** API keys live in `.env.<org>` (gitignored) or
183183
CI secrets. Credentials are referenced by name and bound to each org's own
184184
credentials.
185+
- **Assistant subfolders group the dashboard.** Pushing
186+
`assistants/support/intake.yml` sets `metadata.gitops.folderPath` to
187+
`support`, preserving other authored metadata and sibling `gitops` keys.
188+
A top-level `metadata.folderPath` remains a user-authored key. The full
189+
subfolder path is preserved: `assistants/support/intake/b.yml` sets
190+
`metadata.gitops.folderPath` to `support/intake`. Root assistants send
191+
`metadata.gitops.folderPath: null` to clear any previous folder. This derived key is omitted
192+
on pull and ignored for drift; do not author it in YAML. Moving files still
193+
requires explicit `--adopt <new-resourceId>=<uuid>` to retain the same platform
194+
resource; an unlinked file otherwise creates a new one. `apply` uses the same
195+
folder behavior in its push phase.
185196
- **Each folder is pinned to its org.** The first command that can see which
186197
org a key belongs to records it in `resources/<org>/.vapi-org.json`. After
187198
that, every command checks the key against it before any request, and stops

‎docs/guides/commands.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,19 @@ adoption before dependency resolution to take one over instead.
9797

9898
## Interactive Mode
9999

100+
Assistant pushes (including the push phase of `apply`) derive
101+
`metadata.gitops.folderPath` from the full subfolder path under `assistants/`, preserving
102+
other authored metadata and sibling `gitops` keys:
103+
`assistants/support/intake.yml` groups under `support`.
104+
Nested paths are preserved: `assistants/support/intake/b.yml` groups under
105+
`support/intake`. Root files send
106+
`metadata.gitops.folderPath: null` to clear grouping.
107+
Pull omits this derived key, dropping empty `gitops`/`metadata` objects, and drift
108+
comparisons ignore it. Top-level `metadata.folderPath` is a user key, left
109+
untouched. Authored `metadata.gitops` must be a plain object. To move a file
110+
while retaining its platform UUID, explicitly adopt it with
111+
`--adopt <new-resourceId>=<uuid>`; the subsequent push updates its folder path.
112+
100113
When you run a command without arguments, you get a fully interactive experience:
101114

102115
```bash

‎src/assistant-folder.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
function isPlainObject(value: unknown): value is Record<string, unknown> {
2+
return (
3+
value !== null &&
4+
typeof value === "object" &&
5+
(Object.getPrototypeOf(value) === Object.prototype ||
6+
Object.getPrototypeOf(value) === null)
7+
);
8+
}
9+
10+
export function withoutAssistantFolder(
11+
data: Record<string, unknown>,
12+
): Record<string, unknown> {
13+
const metadata = data.metadata;
14+
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) {
15+
return data;
16+
}
17+
const gitops = (metadata as Record<string, unknown>).gitops;
18+
if (!isPlainObject(gitops)) return data;
19+
const { folderPath: _, ...rest } = gitops;
20+
const remainingMetadata = { ...(metadata as Record<string, unknown>) };
21+
if (Object.keys(rest).length > 0) remainingMetadata.gitops = rest;
22+
else delete remainingMetadata.gitops;
23+
const result = { ...data };
24+
if (Object.keys(remainingMetadata).length > 0)
25+
result.metadata = remainingMetadata;
26+
else delete result.metadata;
27+
return result;
28+
}
29+
30+
export function withAssistantFolder(
31+
data: Record<string, unknown>,
32+
resourceId: string,
33+
): Record<string, unknown> {
34+
const normalized = resourceId.replace(/\\/g, "/");
35+
const slash = normalized.lastIndexOf("/");
36+
const metadata = data.metadata;
37+
if (
38+
metadata != null &&
39+
(typeof metadata !== "object" || Array.isArray(metadata))
40+
) {
41+
throw new Error("Assistant metadata must be an object");
42+
}
43+
const gitops = (metadata as Record<string, unknown> | null | undefined)
44+
?.gitops;
45+
if (metadata && Object.hasOwn(metadata, "gitops") && !isPlainObject(gitops)) {
46+
throw new Error("Assistant metadata.gitops must be a plain object");
47+
}
48+
return {
49+
...data,
50+
metadata: {
51+
...(metadata as Record<string, unknown> | undefined),
52+
gitops: {
53+
...(gitops as Record<string, unknown> | undefined),
54+
folderPath: slash < 0 ? null : normalized.slice(0, slash),
55+
},
56+
},
57+
};
58+
}

‎src/audit.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,12 @@
2121

2222
import { readFile } from "fs/promises";
2323
import { join } from "path";
24+
import { canonicalizeForHash, type VapiResource } from "./canonical.ts";
2425
import { matchesIgnore, RESOURCES_DIR, VAPI_ENV } from "./config.ts";
2526
import { credentialReverseMap } from "./credentials.ts";
2627
import { classifyDrift } from "./drift.ts";
2728
import { readBaseline } from "./hash-store.ts";
2829
import { findOrphanResourceIds } from "./new-file-gate.ts";
29-
import { canonicalizeForHash, type VapiResource } from "./canonical.ts";
3030
import { fetchAllResources, listExistingResourceIds } from "./pull.ts";
3131
import { FOLDER_MAP, hashLocalResource } from "./resources.ts";
3232
import { extractBaseSlug, slugify } from "./slug-utils.ts";
@@ -393,7 +393,7 @@ function checkContentDrift(
393393
// canonicalizeForHash centralizes the 3-step pipeline + _platformDefault
394394
// mutation so the hash agrees with the pull-write baseline basis.
395395
const platformHash = hashPayload(
396-
canonicalizeForHash(remoteResource, state, credReverse),
396+
canonicalizeForHash(remoteResource, state, credReverse, type),
397397
);
398398
const direction = classifyDrift({
399399
localHash,

‎src/canonical.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
// drift, so drift could not import back — it grew a divergent copy instead).
1313
// ─────────────────────────────────────────────────────────────────────────────
1414

15+
import { withoutAssistantFolder } from "./assistant-folder.ts";
1516
import { replaceCredentialRefs } from "./credentials.ts";
1617
import type { ResourceType, StateFile } from "./types.ts";
1718

@@ -210,9 +211,12 @@ export function canonicalizeForHash(
210211
resource: VapiResource,
211212
state: StateFile,
212213
credReverse: Map<string, string>,
214+
resourceType?: ResourceType,
213215
): Record<string, unknown> {
214216
const cleaned = cleanResource(resource);
215-
const resolved = resolveReferencesToResourceIds(cleaned, state);
217+
const content =
218+
resourceType === "assistants" ? withoutAssistantFolder(cleaned) : cleaned;
219+
const resolved = resolveReferencesToResourceIds(content, state);
216220
const withCredNames = replaceCredentialRefs(resolved, credReverse);
217221
const isPlatformDefault =
218222
resource.orgId === null || resource.orgId === undefined;

‎src/drift.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
// has nothing to compare against — only PATCH (update) is drift-sensitive.
1919
// ─────────────────────────────────────────────────────────────────────────────
2020

21-
import { vapiGet, VapiApiError } from "./api.ts";
21+
import { VapiApiError, vapiGet } from "./api.ts";
2222
import { canonicalizeForHash, type VapiResource } from "./canonical.ts";
2323
import { credentialReverseMap } from "./credentials.ts";
2424
import { readBaseline } from "./hash-store.ts";
@@ -144,7 +144,12 @@ export async function checkDriftForUpdate(options: {
144144
// resource hashed differently here than at pull time → phantom both-diverged.
145145
const credReverse = credentialReverseMap(state);
146146
const platformHash = hashPayload(
147-
canonicalizeForHash(remote as VapiResource, state, credReverse),
147+
canonicalizeForHash(
148+
remote as VapiResource,
149+
state,
150+
credReverse,
151+
resourceType,
152+
),
148153
);
149154
if (platformHash === baseline) {
150155
return { ok: true, reason: "match", platformHash, platformPayload: remote };
@@ -153,8 +158,7 @@ export async function checkDriftForUpdate(options: {
153158
// On-disk hash in the same basis as the baseline. Absent a local file
154159
// (rare on an update path), fall back to the baseline so the direction is
155160
// dashboard-ahead rather than a phantom both-diverged.
156-
const localHash =
157-
hashLocalResource(resourceType, resourceId) ?? baseline;
161+
const localHash = hashLocalResource(resourceType, resourceId) ?? baseline;
158162

159163
// Local and platform are byte-identical → there is nothing to reconcile and
160164
// the PATCH is a no-op. NEVER block here, even if the baseline disagrees

‎src/pull.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,7 @@ export async function writeDashboardBackup(
538538
platformPayload,
539539
state,
540540
credReverse,
541+
resourceType,
541542
);
542543
// Filesystem-safe ISO timestamp: 2026-06-04T19-22-33 (no colons, no ms).
543544
const timestamp = new Date()
@@ -844,7 +845,7 @@ export async function pullResourceType(
844845
// classifier, audit, and resolveBothDiverged sites. Any asymmetry here
845846
// makes every drifted file look `both-diverged` even when content matches.
846847
const platformHash = hashPayload(
847-
canonicalizeForHash(resource, state, credReverse),
848+
canonicalizeForHash(resource, state, credReverse, resourceType),
848849
);
849850
// Note: classifyDrift treats live local + platform agreement as
850851
// `clean` whatever the (possibly stale) baseline says — the clean
@@ -1015,7 +1016,12 @@ export async function pullResourceType(
10151016
// Single canonicalization for both the file write AND the lastPulledHash
10161017
// fallback. Encodes the 3-step pipeline (cleanResource → resolve refs →
10171018
// replace credential UUIDs) plus the _platformDefault marker.
1018-
const withCredNames = canonicalizeForHash(resource, state, credReverse);
1019+
const withCredNames = canonicalizeForHash(
1020+
resource,
1021+
state,
1022+
credReverse,
1023+
resourceType,
1024+
);
10191025

10201026
if (bootstrap) {
10211027
const icon = isPlatformDefault ? "🔒" : isNew ? "✨" : "📝";
@@ -1175,6 +1181,7 @@ async function resolveBothDivergedResources(options: {
11751181
entry.resource,
11761182
state,
11771183
credReverse,
1184+
entry.resourceType,
11781185
);
11791186

11801187
await writeResourceFile(

‎src/push.ts‎

Lines changed: 24 additions & 4 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 { withAssistantFolder } from "./assistant-folder.ts";
56
import { canonicalizeForHash, type VapiResource } from "./canonical.ts";
67
import {
78
APPLY_FILTER,
@@ -153,13 +154,19 @@ async function writeBaselineFromResponse(
153154
uuid: string,
154155
response: unknown,
155156
state: StateFile,
157+
resourceType?: ResourceType,
156158
): Promise<void> {
157159
if (DRY_RUN) return;
158160
if (!response || typeof response !== "object") return;
159161
try {
160162
const credReverse = credentialReverseMap(state);
161163
const hash = hashPayload(
162-
canonicalizeForHash(response as VapiResource, state, credReverse),
164+
canonicalizeForHash(
165+
response as VapiResource,
166+
state,
167+
credReverse,
168+
resourceType,
169+
),
163170
);
164171
await writeBaseline(VAPI_ENV, uuid, hash);
165172
} catch (err) {
@@ -254,7 +261,12 @@ async function upsertResourceWithStateRecovery(options: {
254261
uuid: result.id,
255262
origin: "pushed",
256263
});
257-
await writeBaselineFromResponse(result.id, result, fullState);
264+
await writeBaselineFromResponse(
265+
result.id,
266+
result,
267+
fullState,
268+
RESOURCE_LABEL_TO_TYPE[resourceLabel],
269+
);
258270
if (resourceLabel === "assistant") {
259271
await writeAssistantVersionMetadata({
260272
uuid: result.id,
@@ -408,7 +420,12 @@ async function upsertResourceWithStateRecovery(options: {
408420
// The PATCH response is the full resource as the platform now stores it —
409421
// the freshest possible "last known platform state." Hash it as the new
410422
// drift baseline so the next push of a further local edit is clean.
411-
await writeBaselineFromResponse(existingUuid, result, fullState);
423+
await writeBaselineFromResponse(
424+
existingUuid,
425+
result,
426+
fullState,
427+
RESOURCE_LABEL_TO_TYPE[resourceLabel],
428+
);
412429
if (resourceLabel === "assistant" && platformPayloadForSnapshot) {
413430
await writeAssistantVersionMetadata({
414431
uuid: existingUuid,
@@ -885,7 +902,10 @@ export async function applyAssistant(
885902
const existingUuid = state.assistants[resourceId]?.uuid;
886903

887904
// Resolve tool and structured output references
888-
const payload = resolveReferences(data as Record<string, unknown>, state);
905+
const payload = withAssistantFolder(
906+
resolveReferences(data as Record<string, unknown>, state),
907+
resourceId,
908+
);
889909

890910
return upsertResourceWithStateRecovery({
891911
resourceLabel: "assistant",

‎src/resources.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { existsSync } from "fs";
22
import { readFile } from "fs/promises";
33
import { basename, extname, join, relative, resolve } from "path";
44
import { parse as parseYaml } from "yaml";
5+
import { withoutAssistantFolder } from "./assistant-folder.ts";
56
import { BASE_DIR, matchesIgnore, RESOURCES_DIR } from "./config.ts";
67
import {
78
FOLDER_MAP,
@@ -16,10 +17,10 @@ import { stateUuid } from "./state.ts";
1617
import { hashPayload } from "./state-serialize.ts";
1718
import type { ResourceFile, ResourceType, StateFile } from "./types.ts";
1819

20+
export type { LoadOptions };
1921
// The file-reading half lives in resource-parse.ts (config-free). These are
2022
// re-exported so existing importers keep working.
2123
export { FOLDER_MAP, VALID_EXTENSIONS };
22-
export type { LoadOptions };
2324

2425
function findLocalResourceFile(
2526
type: ResourceType,
@@ -42,7 +43,10 @@ export function hashLocalResource(
4243
const filePath = findLocalResourceFile(type, resourceId);
4344
if (!filePath) return null;
4445
try {
45-
return hashPayload(parseResourceDataFromFile(filePath));
46+
const data = parseResourceDataFromFile(filePath);
47+
return hashPayload(
48+
type === "assistants" ? withoutAssistantFolder(data) : data,
49+
);
4650
} catch {
4751
return null;
4852
}

0 commit comments

Comments
 (0)