Skip to content

Commit 20c8877

Browse files
authored
feat(push): label assistant versions with the pusher, commit and changed fields
A push that publishes an assistant version now sets its versionName and versionDescription to the pusher, the commit, and the dotted paths of the fields that changed. API-key writes record no author on the version, so this is the only trace of who published it.
1 parent fbbf64c commit 20c8877

5 files changed

Lines changed: 367 additions & 4 deletions

File tree

‎docs/learnings/sync-behavior.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,26 @@ Do not delete the source state mapping or refresh it away before step 2. With
247247
no source files and no tombstone, promotion refuses the empty-source mirror
248248
instead of guessing that a full destination wipe was intended.
249249

250+
## Assistant version labels
251+
252+
On an org with assistant versioning, every assistant create or PATCH that
253+
changes content publishes a new version (`v8`, `v9`, …). The platform records
254+
no author on a version written with a private API key, so push labels it:
255+
256+
- `versionName`: `gitops <commit>[+dirty] by <actor>`
257+
- `versionDescription`: the actor, the commit, and the dotted paths of the
258+
fields that changed (`model.messages, voice.voiceId`), computed from the
259+
dashboard payload before the PATCH and the PATCH response.
260+
261+
The actor is `VAPI_GITOPS_ACTOR` if set, else `github:$GITHUB_ACTOR` in CI,
262+
else `git config user.email`. It is self-reported, so treat it as an audit
263+
trail, not proof. `+dirty` means `resources/<org>/` had uncommitted edits, so
264+
the commit alone does not reproduce the push.
265+
266+
Push skips the label when nothing new was published (identical content is
267+
deduplicated) and in `--dry-run`. A failed label is a warning, never a failed
268+
push: the content is already live.
269+
250270
---
251271

252272
## Flag cheat sheet

‎src/push.ts‎

Lines changed: 65 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
loadIgnorePatterns,
1414
OVERWRITE_DRIFT,
1515
removeExcludedKeys,
16+
RESOURCES_DIR,
1617
STATE_FILE_PATH,
1718
STRICT_VALIDATION,
1819
VAPI_BASE_URL,
@@ -39,6 +40,11 @@ import {
3940
validateNoIgnoredReferences,
4041
validateResources,
4142
} from "./validate.ts";
43+
import {
44+
changedFieldPaths,
45+
versionActorResolve,
46+
versionMetadataBuild,
47+
} from "./version-metadata.ts";
4248

4349
// Map a resource label to its state-file key. Used for snapshotting —
4450
// snapshot directories are keyed by the same names the state file uses.
@@ -165,6 +171,45 @@ async function writeBaselineFromResponse(
165171
}
166172
}
167173

174+
// Label the version an assistant push just published with who pushed it,
175+
// from which commit, and which fields changed. Only assistants: they are the
176+
// only resource whose versions accept metadata. Skips when the push published
177+
// nothing new (the platform dedups identical content), and never blocks the
178+
// push: the content is already live, the label is an audit trail.
179+
async function writeAssistantVersionMetadata(options: {
180+
uuid: string;
181+
before: unknown;
182+
after: unknown;
183+
}): Promise<void> {
184+
const { uuid, before, after } = options;
185+
if (DRY_RUN) return;
186+
const latestVersionRead = (value: unknown): string | null =>
187+
value &&
188+
typeof value === "object" &&
189+
"latestVersion" in value &&
190+
typeof value.latestVersion === "string"
191+
? value.latestVersion
192+
: null;
193+
const published = latestVersionRead(after);
194+
if (!published || published === latestVersionRead(before)) return;
195+
const metadata = versionMetadataBuild({
196+
actor: versionActorResolve(RESOURCES_DIR),
197+
changedPaths: before === undefined ? [] : changedFieldPaths(before, after),
198+
created: before === undefined,
199+
});
200+
try {
201+
await vapiRequest("PATCH", `/assistant/${uuid}/versions/${published}`, {
202+
...metadata,
203+
});
204+
console.log(` 🏷️ ${published}: ${metadata.versionName}`);
205+
} catch (err) {
206+
console.warn(
207+
` ⚠️ failed to label ${published} of assistant ${uuid}: ` +
208+
(err instanceof Error ? err.message : String(err)),
209+
);
210+
}
211+
}
212+
168213
async function upsertResourceWithStateRecovery(options: {
169214
resourceLabel: string;
170215
resourceId: string;
@@ -197,6 +242,13 @@ async function upsertResourceWithStateRecovery(options: {
197242
console.log(` ✨ Creating ${resourceLabel}: ${resourceId}`);
198243
const result = await vapiRequest("POST", createEndpoint, createPayload);
199244
await writeBaselineFromResponse(result.id, result, fullState);
245+
if (resourceLabel === "assistant") {
246+
await writeAssistantVersionMetadata({
247+
uuid: result.id,
248+
before: undefined,
249+
after: result,
250+
});
251+
}
200252
return result.id;
201253
}
202254

@@ -210,13 +262,14 @@ async function upsertResourceWithStateRecovery(options: {
210262
// what would happen, and skipped if no baseline hash.
211263
// When we successfully fetch the platform payload, snapshot it (and our
212264
// outgoing payload) so `npm run rollback` has a target.
265+
// Platform payload fetched by the drift check, reused for the rollback
266+
// snapshot below so we don't fire a second GET at the same endpoint, and
267+
// as the "before" side of the version-metadata field diff.
268+
let platformPayloadForSnapshot: unknown;
213269
if (!DRY_RUN) {
214270
const stateEntry = stateSection[resourceId];
215271
if (stateEntry) {
216272
const driftResourceType = RESOURCE_LABEL_TO_TYPE[resourceLabel];
217-
// Platform payload fetched by the drift check, reused for the rollback
218-
// snapshot below so we don't fire a second GET at the same endpoint.
219-
let platformPayloadForSnapshot: unknown;
220273
// The drift check now owns the full hash computation (platform, local,
221274
// and baseline all canonicalized via canonical.ts). Push just hands it
222275
// the full state + resource type — no hash plumbing at the call site.
@@ -341,6 +394,13 @@ async function upsertResourceWithStateRecovery(options: {
341394
// the freshest possible "last known platform state." Hash it as the new
342395
// drift baseline so the next push of a further local edit is clean.
343396
await writeBaselineFromResponse(existingUuid, result, fullState);
397+
if (resourceLabel === "assistant" && platformPayloadForSnapshot) {
398+
await writeAssistantVersionMetadata({
399+
uuid: existingUuid,
400+
before: platformPayloadForSnapshot,
401+
after: result,
402+
});
403+
}
344404
return existingUuid;
345405
} catch (error) {
346406
if (!(error instanceof VapiApiError) || error.statusCode !== 404) {
@@ -745,7 +805,8 @@ export function cleanDestinationAssistantIds(destinations: unknown): unknown {
745805
function countAuthoredAssistantRefs(assistantIds: unknown): number {
746806
if (!Array.isArray(assistantIds)) return 0;
747807
return assistantIds.filter(
748-
(ref) => typeof ref === "string" && (ref.split("##")[0]?.trim() ?? "") !== "",
808+
(ref) =>
809+
typeof ref === "string" && (ref.split("##")[0]?.trim() ?? "") !== "",
749810
).length;
750811
}
751812

‎src/types.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,20 @@ export interface OrphanedResource {
9494
resourceId: string;
9595
uuid: string;
9696
}
97+
98+
// Who pushed an assistant version, recorded in its version metadata.
99+
export interface VersionActor {
100+
// Who pushed: the CI actor when set, else the local git identity.
101+
name: string;
102+
// Short commit SHA of HEAD, or null outside a git checkout.
103+
commit: string | null;
104+
// True when the pushed files had uncommitted edits, so the commit alone
105+
// does not reproduce what was pushed.
106+
dirty: boolean;
107+
}
108+
109+
// Body of PATCH /assistant/:id/versions/:version.
110+
export interface VersionMetadata {
111+
versionName: string;
112+
versionDescription: string;
113+
}

‎src/version-metadata.ts‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
// Labels the assistant version a push publishes with who pushed it, from
2+
// which commit, and which fields changed. The platform records no author on
3+
// versions written with a private API key (createdBy is null), so without
4+
// this a version published by gitops cannot be traced back to a person.
5+
//
6+
// Config-free on purpose (like user-agent.ts): importing config.ts would
7+
// parse argv and exit, which breaks importing this from tests.
8+
9+
import { execFileSync } from "node:child_process";
10+
import type { VersionActor, VersionMetadata } from "./types.ts";
11+
12+
// Limits enforced by PATCH /assistant/:id/versions/:version. Longer values
13+
// are rejected with a 400, so the builder truncates instead.
14+
const VERSION_NAME_MAX = 80;
15+
const VERSION_DESCRIPTION_MAX = 500;
16+
17+
// Server-managed keys that differ between any two reads of the same
18+
// resource. Comparing them would list a change on every push.
19+
const IGNORED_KEYS = new Set([
20+
"id",
21+
"orgId",
22+
"createdAt",
23+
"updatedAt",
24+
"latestVersion",
25+
"modelDeprecations",
26+
]);
27+
28+
function isPlainObject(value: unknown): value is Record<string, unknown> {
29+
return value !== null && typeof value === "object" && !Array.isArray(value);
30+
}
31+
32+
function sameValue(a: unknown, b: unknown): boolean {
33+
return JSON.stringify(a) === JSON.stringify(b);
34+
}
35+
36+
// Dotted paths of the fields that differ between two reads of a resource,
37+
// descending into nested objects up to `maxDepth` levels (so a prompt edit
38+
// reads `model.messages`, not just `model`). Arrays compare whole.
39+
export function changedFieldPaths(
40+
before: unknown,
41+
after: unknown,
42+
maxDepth = 2,
43+
prefix = "",
44+
): string[] {
45+
if (!isPlainObject(before) || !isPlainObject(after)) {
46+
return sameValue(before, after) ? [] : [prefix || "(root)"];
47+
}
48+
49+
const keys = new Set([...Object.keys(before), ...Object.keys(after)]);
50+
const paths: string[] = [];
51+
for (const key of keys) {
52+
if (!prefix && IGNORED_KEYS.has(key)) continue;
53+
const path = prefix ? `${prefix}.${key}` : key;
54+
const a = before[key];
55+
const b = after[key];
56+
if (sameValue(a, b)) continue;
57+
const depth = path.split(".").length;
58+
if (depth < maxDepth && isPlainObject(a) && isPlainObject(b)) {
59+
paths.push(...changedFieldPaths(a, b, maxDepth, path));
60+
} else {
61+
paths.push(path);
62+
}
63+
}
64+
return paths.sort();
65+
}
66+
67+
function gitRead(args: string[]): string | null {
68+
try {
69+
const out = execFileSync("git", args, {
70+
encoding: "utf-8",
71+
stdio: ["ignore", "pipe", "ignore"],
72+
}).trim();
73+
return out || null;
74+
} catch {
75+
return null;
76+
}
77+
}
78+
79+
// Self-reported identity: git config and GITHUB_ACTOR are whatever the
80+
// pusher's environment says. Good for an audit trail between colleagues,
81+
// not proof against a pusher who sets them deliberately.
82+
export function versionActorResolve(
83+
resourcesDir: string,
84+
env: NodeJS.ProcessEnv = process.env,
85+
): VersionActor {
86+
const name =
87+
env.VAPI_GITOPS_ACTOR ||
88+
(env.GITHUB_ACTOR ? `github:${env.GITHUB_ACTOR}` : null) ||
89+
gitRead(["config", "user.email"]) ||
90+
gitRead(["config", "user.name"]) ||
91+
"unknown";
92+
const commit = gitRead(["rev-parse", "--short", "HEAD"]);
93+
const dirty =
94+
commit !== null &&
95+
gitRead(["status", "--porcelain", "--", resourcesDir]) !== null;
96+
return { name, commit, dirty };
97+
}
98+
99+
function truncate(value: string, max: number): string {
100+
return value.length <= max ? value : `${value.slice(0, max - 1)}…`;
101+
}
102+
103+
// Lists as many changed paths as fit in the description limit, then
104+
// "+N more" so a large change never pushes the actor line out.
105+
function changedFieldsLine(paths: string[], budget: number): string {
106+
if (paths.length === 0) return "Changed: (no field-level change detected)";
107+
const head = "Changed: ";
108+
let line = head;
109+
for (let i = 0; i < paths.length; i++) {
110+
const remaining = paths.length - i - 1;
111+
const sep = i === 0 ? "" : ", ";
112+
const tail = remaining > 0 ? ` (+${remaining} more)` : "";
113+
const candidate = `${line}${sep}${paths[i]}`;
114+
if (candidate.length + tail.length > budget) {
115+
return `${line} (+${paths.length - i} more)`;
116+
}
117+
line = candidate;
118+
}
119+
return line;
120+
}
121+
122+
export function versionMetadataBuild(args: {
123+
actor: VersionActor;
124+
changedPaths: string[];
125+
created: boolean;
126+
}): VersionMetadata {
127+
const { actor, changedPaths, created } = args;
128+
const commit = actor.commit
129+
? `${actor.commit}${actor.dirty ? "+dirty" : ""}`
130+
: "no-commit";
131+
const versionName = truncate(
132+
`gitops ${commit} by ${actor.name}`,
133+
VERSION_NAME_MAX,
134+
);
135+
const header = `Pushed by ${actor.name} from commit ${commit} via vapi-gitops.`;
136+
const body = created
137+
? "Created by gitops."
138+
: changedFieldsLine(
139+
changedPaths,
140+
VERSION_DESCRIPTION_MAX - header.length - 1,
141+
);
142+
return {
143+
versionName,
144+
versionDescription: truncate(`${header}\n${body}`, VERSION_DESCRIPTION_MAX),
145+
};
146+
}

0 commit comments

Comments
 (0)