Skip to content

Commit e7a6cc0

Browse files
committed
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 a67a4b1 commit e7a6cc0

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
@@ -12,6 +12,7 @@ import {
1212
FORCE_DELETE,
1313
loadIgnorePatterns,
1414
OVERWRITE_DRIFT,
15+
RESOURCES_DIR,
1516
removeExcludedKeys,
1617
STATE_FILE_PATH,
1718
STRICT_VALIDATION,
@@ -41,6 +42,11 @@ import {
4142
validateResources,
4243
} from "./validate.ts";
4344
import { validateReferences } from "./validate-refs.ts";
45+
import {
46+
changedFieldPaths,
47+
versionActorResolve,
48+
versionMetadataBuild,
49+
} from "./version-metadata.ts";
4450

4551
// Map a resource label to its state-file key. Used for snapshotting —
4652
// snapshot directories are keyed by the same names the state file uses.
@@ -167,6 +173,45 @@ async function writeBaselineFromResponse(
167173
}
168174
}
169175

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

@@ -212,13 +264,14 @@ async function upsertResourceWithStateRecovery(options: {
212264
// what would happen, and skipped if no baseline hash.
213265
// When we successfully fetch the platform payload, snapshot it (and our
214266
// outgoing payload) so `npm run rollback` has a target.
267+
// Platform payload fetched by the drift check, reused for the rollback
268+
// snapshot below so we don't fire a second GET at the same endpoint, and
269+
// as the "before" side of the version-metadata field diff.
270+
let platformPayloadForSnapshot: unknown;
215271
if (!DRY_RUN) {
216272
const stateEntry = stateSection[resourceId];
217273
if (stateEntry) {
218274
const driftResourceType = RESOURCE_LABEL_TO_TYPE[resourceLabel];
219-
// Platform payload fetched by the drift check, reused for the rollback
220-
// snapshot below so we don't fire a second GET at the same endpoint.
221-
let platformPayloadForSnapshot: unknown;
222275
// The drift check now owns the full hash computation (platform, local,
223276
// and baseline all canonicalized via canonical.ts). Push just hands it
224277
// the full state + resource type — no hash plumbing at the call site.
@@ -344,6 +397,13 @@ async function upsertResourceWithStateRecovery(options: {
344397
// the freshest possible "last known platform state." Hash it as the new
345398
// drift baseline so the next push of a further local edit is clean.
346399
await writeBaselineFromResponse(existingUuid, result, fullState);
400+
if (resourceLabel === "assistant" && platformPayloadForSnapshot) {
401+
await writeAssistantVersionMetadata({
402+
uuid: existingUuid,
403+
before: platformPayloadForSnapshot,
404+
after: result,
405+
});
406+
}
347407
return existingUuid;
348408
} catch (error) {
349409
if (!(error instanceof VapiApiError) || error.statusCode !== 404) {
@@ -748,7 +808,8 @@ export function cleanDestinationAssistantIds(destinations: unknown): unknown {
748808
function countAuthoredAssistantRefs(assistantIds: unknown): number {
749809
if (!Array.isArray(assistantIds)) return 0;
750810
return assistantIds.filter(
751-
(ref) => typeof ref === "string" && (ref.split("##")[0]?.trim() ?? "") !== "",
811+
(ref) =>
812+
typeof ref === "string" && (ref.split("##")[0]?.trim() ?? "") !== "",
752813
).length;
753814
}
754815

‎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)