Skip to content

Open source CapCut alternative.

TypeScript

fix(site): the quality gate holds only on what it measured [rebuild]

David Le6378430f24ae
diff --git a/site/src/cut/lib/pi/cutAgent.test.ts b/site/src/cut/lib/pi/cutAgent.test.ts
index 066b5cc9..3cadc4e0 100644
--- a/site/src/cut/lib/pi/cutAgent.test.ts
+++ b/site/src/cut/lib/pi/cutAgent.test.ts
@@ -64,6 +64,8 @@ function qualityAnswers(finished: number) {
finished: { type: "noul", noul: finished },
seen: { type: "noul", noul: finished },
honest: { type: "noul", noul: 0.9 },
+ hears: { type: "noul", noul: 0.1 },
+ captionsSpeak: { type: "noul", noul: 0.1 },
next: { type: "choice", choice: "watch", probabilities: { watch: 0.8 }, confidence: 0.8 },
closeness: { type: "choice", choice: "exact", probabilities: { exact: 0.8 }, confidence: 0.8 },
};
@@ -80,12 +82,12 @@ async function drain(stream: ReadableStream<unknown>): Promise<Record<string, un
return out;
}
-function harness(opts: { gateVerdicts: number[] }) {
+function harness(opts: { gateVerdicts: number[]; call?: { name: string; args: Record<string, unknown> } }) {
const modelPayloads: Record<string, unknown>[] = [];
const judgeAsks: string[][] = [];
let gateCalls = 0;
const rounds: (() => Response)[] = [
- () => round({ call: { name: "watch_video", args: { asset_id: "a1", from: 0 } } }),
+ () => round({ call: opts.call ?? { name: "watch_video", args: { asset_id: "a1", from: 0 } } }),
() => round({ text: "That video opens on a yellow title and runs 71 seconds." }),
() => round({ text: "Watched the rest of it." }),
() => round({ text: "Still here." }),
@@ -163,10 +165,13 @@ describe("the quality gate in the turn loop", () => {
dropPiSession(threadId);
});
- test("a turn that never opened a source is not held", async () => {
+ test("a turn that never opened a source but did the work is not held", async () => {
const threadId = "gate-no-looks";
dropPiSession(threadId);
- const h = harness({ gateVerdicts: [0.01] });
+ const h = harness({
+ gateVerdicts: [0.01],
+ call: { name: "set_clip_muted", args: { clipId: "c1", muted: true } },
+ });
h.deps.execTool = async () => ({ id: "c1", muted: true });
await drain(
streamCutChat({ threadId, model: "chat", messages: ask("mute the first clip"), deps: h.deps })
@@ -176,6 +181,19 @@ describe("the quality gate in the turn loop", () => {
dropPiSession(threadId);
});
+ test("an ask for work the turn only described is sent back to build it", async () => {
+ const threadId = "gate-words-only";
+ dropPiSession(threadId);
+ const h = harness({ gateVerdicts: [0.01, 0.9], call: { name: "get_state", args: {} } });
+ h.deps.execTool = async () => ({ videoTrack: [], media: [] });
+ await drain(
+ streamCutChat({ threadId, model: "chat", messages: ask("replicate this video"), deps: h.deps })
+ );
+ expect(h.judgeAsks.filter((q) => q.includes("finished")).length).toBe(1);
+ expect(JSON.stringify(h.modelPayloads[2])).toContain("Build it with tools now");
+ dropPiSession(threadId);
+ });
+
test("the gate off lets the turn close whatever the work looks like", async () => {
const threadId = "gate-off";
dropPiSession(threadId);
diff --git a/site/src/cut/lib/pi/cutAgent.ts b/site/src/cut/lib/pi/cutAgent.ts
index 8e31f2c4..381b8dce 100644
--- a/site/src/cut/lib/pi/cutAgent.ts
+++ b/site/src/cut/lib/pi/cutAgent.ts
@@ -60,7 +60,7 @@ import {
} from "../turnQuality";
import { enforceContextBudget } from "./contextBudget";
import { donkeyModel, type ChatThinkingLevel } from "./donkeyModel";
-import { ledgerText, recordCall, type LedgerRecord } from "./mutationLedger";
+import { isMutatingTool, ledgerText, recordCall, type LedgerRecord } from "./mutationLedger";
import { makeDonkeyStream, type DonkeyToolDetails, type PostFn, type WireCarrier, type WirePart } from "./donkeyStream";
import { toAgentTools, toToolResult, type ExecTool } from "./tools";
import { subscribeUiChunks } from "./uiChunks";
@@ -713,6 +713,7 @@ async function gateVerdict(
: "",
ran: [...new Set(records.filter((r) => !r.error).map((r) => r.name))],
failed: [...new Set(records.filter((r) => r.error).map((r) => `${r.name} (${r.error})`))],
+ mutated: records.some((r) => !r.error && isMutatingTool(r.name)),
sources: [...looks.values()],
editor: editorSlice(deps.buildContext()),
};
@@ -944,9 +945,11 @@ export function streamCutChat({
)
return false;
// The gate judges work grounded in footage: a turn that looked
- // at a source can be held to what it saw, and one that never
- // opened a source has nothing the judgment could measure.
- if (looks.size === 0) return false;
+ // at a source can be held to what it saw. A turn that opened no
+ // source is measurable too when it changed nothing — an ask for
+ // work answered in words leaves the project where it was, and
+ // that is a fact the record carries.
+ if (looks.size === 0 && records.some((r) => !r.error && isMutatingTool(r.name))) return false;
const mark = [
records.length,
...[...looks.values()].map((l) => `${l.passes}:${l.coveredTo}:${l.observed.length}`),
diff --git a/site/src/cut/lib/turnJudge.ts b/site/src/cut/lib/turnJudge.ts
index fb5a2da0..6bb2a1c8 100644
--- a/site/src/cut/lib/turnJudge.ts
+++ b/site/src/cut/lib/turnJudge.ts
@@ -153,6 +153,9 @@ export function editorSlice(context: unknown): Entry {
? { kind: typeof selection.kind === "string" ? selection.kind : null, name: typeof selection.name === "string" ? selection.name : null }
: null,
clips: videoTrack.length,
+ // Shots holding a slot with no picture in them. A cut whose track 0 is
+ // all placeholder is a shell, and that is a number rather than a reading.
+ emptyShots: videoTrack.filter((c) => !!(c as Record<string, unknown>).emptyShot).length,
soundtrackClips: soundtrack.length,
overlayKinds: [...new Set(overlays.map((o) => (typeof o.kind === "string" ? o.kind : "overlay")))],
captionTracks: tracks.length,
diff --git a/site/src/cut/lib/turnQuality.test.ts b/site/src/cut/lib/turnQuality.test.ts
index 6f24729e..f5ccb861 100644
--- a/site/src/cut/lib/turnQuality.test.ts
+++ b/site/src/cut/lib/turnQuality.test.ts
@@ -29,6 +29,7 @@ const source = (over: Partial<WatchedSource> = {}): WatchedSource => ({
spoken: "",
observed: [{ from: 0, to: 20, text: "hook titles over a talking head" }],
cuts: 12,
+ compared: 0,
...over });
const work = (over: Partial<TurnWork> = {}): TurnWork => ({
@@ -36,6 +37,7 @@ const work = (over: Partial<TurnWork> = {}): TurnWork => ({
reply: "Here is the whole video rebuilt.",
ran: ["watch_video", "note_source"],
failed: [],
+ mutated: true,
sources: [source()],
editor: { clips: 0 },
...over });
@@ -162,6 +164,7 @@ describe("qualityVerdict", () => {
unnoted: [],
unread: 71.6 - settings.qualityTreatmentSeconds,
unreadFrom: 10,
+ compared: 2,
}),
],
});
@@ -187,7 +190,7 @@ describe("qualityVerdict", () => {
// charged for again.
const read = work({
sources: [
- source({ coveredTo: 71.6, unwatched: 0, unnoted: [], unread: 0, unreadFrom: null }),
+ source({ coveredTo: 71.6, unwatched: 0, unnoted: [], unread: 0, unreadFrom: null, compared: 2 }),
] });
expect(qualityVerdict(answers({ honest: 0.1, closeness: "exact" }), read, settings)).toBeNull();
});
@@ -255,6 +258,7 @@ describe("qualityVerdict", () => {
unnoted: [],
unread: 1.4,
unreadFrom: null,
+ compared: 2,
unheard: 1.4,
unheardFrom: null,
}),
@@ -286,12 +290,115 @@ describe("qualityVerdict", () => {
expect(verdict?.step).toBe("watch");
});
- test("a turn that opened no source is never held", () => {
+ test("a turn that opened no source and did the work is never held", () => {
expect(
qualityVerdict(answers({ finished: 0.1, seen: 0.1 }), work({ sources: [] }), settings),
).toBeNull();
});
+
+
+
+ test("a replica nobody held against its source is sent back to check it", () => {
+ const blind = work({
+ sources: [source({ observed: [{ from: 0, to: 60, text: "titles and shapes throughout" }], unwatched: 0, unread: 0, unreadFrom: null })],
+ editor: { clips: 40, overlayKinds: ["text"] },
+ });
+ const verdict = qualityVerdict(answers({ finished: 0.2, closeness: "exact" }), blind, settings);
+ expect(verdict?.step).toBe("check");
+ expect(verdict?.steer).toContain("compare_to_source");
+ });
+
+
+
+
+ test("only the source the cut was copied from is owed a comparison", () => {
+ // The reference is checked; the user's own footage the turn also watched
+ // is not the thing the cut is being held up against.
+ const both = work({
+ sources: [
+ source({ observed: [{ from: 0, to: 60, text: "the reference end to end" }], unwatched: 0, unread: 0, unreadFrom: null, compared: 3 }),
+ source({ name: "My kitchen clip", duration: 12, observed: [{ from: 0, to: 12, text: "chopping" }], unwatched: 0, unread: 0, unreadFrom: null, compared: 0 }),
+ ],
+ editor: { clips: 40, overlayKinds: ["text"] },
+ });
+ expect(qualityVerdict(answers({ finished: 0.2, closeness: "exact" }), both, settings)).toBeNull();
+ });
+
+ test("a shell of colour blocks has no picture to hold up against the source", () => {
+ // Every shot is a slot waiting for the person's own footage, so every
+ // difference from the reference is the footage they bring.
+ const shell = work({
+ sources: [source({ observed: [{ from: 0, to: 60, text: "the reference end to end" }], unwatched: 0, unread: 0, unreadFrom: null })],
+ editor: { clips: 40, emptyShots: 40, overlayKinds: [] },
+ });
+ expect(qualityVerdict(answers({ finished: 0.2, closeness: "exact" }), shell, settings)).toBeNull();
+ });
+
+ test("one shot with a picture in it is enough to check", () => {
+ const partly = work({
+ sources: [source({ observed: [{ from: 0, to: 60, text: "the reference end to end" }], unwatched: 0, unread: 0, unreadFrom: null })],
+ editor: { clips: 40, emptyShots: 39, overlayKinds: [] },
+ });
+ expect(qualityVerdict(answers({ finished: 0.2, closeness: "exact" }), partly, settings)?.step).toBe("check");
+ });
+
+ test("a source already checked is not sent back to check it again", () => {
+ const seen = work({
+ sources: [source({ observed: [{ from: 0, to: 60, text: "x" }], unwatched: 0, unread: 0, unreadFrom: null, compared: 4 })],
+ editor: { clips: 40, overlayKinds: ["text"] },
+ });
+ expect(qualityVerdict(answers({ finished: 0.2, closeness: "exact" }), seen, settings)).toBeNull();
+ });
+
+ test("an ask that never needed the source read frame by frame is not sent to check", () => {
+ const loose = work({
+ sources: [source({ observed: [{ from: 0, to: 60, text: "x" }], unwatched: 0, unread: 0, unreadFrom: null })],
+ editor: { clips: 40, overlayKinds: ["text"] },
+ });
+ expect(qualityVerdict(answers({ finished: 0.2, closeness: "normal" }), loose, settings)).toBeNull();
+ });
+
+ test("nothing built yet is a build to finish, never a comparison to make", () => {
+ const bare = work({
+ sources: [source({ observed: [{ from: 0, to: 60, text: "x" }], unwatched: 0, unread: 0, unreadFrom: null })],
+ editor: { clips: 0 },
+ mutated: false,
+ });
+ expect(qualityVerdict(answers({ finished: 0.2, closeness: "exact" }), bare, settings)?.step).toBe("build");
+ });
+
+ test("an ask for work answered in words goes back to build it", () => {
+ const words = work({ sources: [], mutated: false, ran: ["get_state"], reply: "The template is set up." });
+ const verdict = qualityVerdict(answers({ finished: 0.2 }), words, settings);
+ expect(verdict?.step).toBe("build");
+ expect(verdict?.steer).toContain("Build it with tools now");
+ });
+
+ test("a turn that changed nothing because nothing was asked for closes", () => {
+ const chat = work({ sources: [], mutated: false, ran: ["get_state"] });
+ expect(qualityVerdict(answers({ finished: 0.9 }), chat, settings)).toBeNull();
+ });
+
+ test("a turn that asked the one question an ambiguous ask earns is not sent to build", () => {
+ // The gate engages on a turn that changed nothing; what keeps a question
+ // from being ordered to guess is the judge answering finished true, which
+ // is the case the question spells out.
+ const asked = work({
+ sources: [],
+ mutated: false,
+ ran: [],
+ request: "make it pop",
+ reply: "Do you mean the titles or the cuts?",
+ });
+ expect(qualityVerdict(answers({ finished: 0.9 }), asked, settings)).toBeNull();
+ });
+
+ test("the build steer carries what already stands, so the second pass adds to it", () => {
+ const partial = work({ sources: [], mutated: false, editor: { clips: 32, overlayKinds: ["text"] } });
+ expect(qualityVerdict(answers({ finished: 0.2 }), partial, settings)?.steer).toContain("32 clips");
+ });
+
test("the steer names what the turn already built, so it carries on instead of starting over", () => {
const mid = work({ editor: { clips: 36, overlayKinds: ["text"] } });
const verdict = qualityVerdict(answers({ seen: 0.1 }), mid, settings);
@@ -365,6 +472,33 @@ describe("recordLook", () => {
expect(looks.get("a1")!.unnoted).toEqual([]);
});
+ test("a comparison counts the moments it checked against a source already seen", () => {
+ const looks = new Map<string, WatchedSource>();
+ recordLook(looks, "watch_video", {
+ source: { assetId: "a1", name: "reference.mp4", duration: 71.6, type: "video", sound: "yes" },
+ coveredTo: 71.6,
+ unwatchedSeconds: 0,
+ unreadSeconds: 0,
+ unreadFrom: null,
+ });
+ recordLook(looks, "compare_to_source", {
+ source: { assetId: "a1", name: "reference.mp4", duration: 71.6, type: "video", sound: "yes" },
+ checked: [{ at: 1, source: 1 }, { at: 8, source: 8 }],
+ });
+ expect(looks.get("a1")!.compared).toBe(2);
+ // A comparison reports no coverage, so it must not undo what watching read.
+ expect(looks.get("a1")!.unwatched).toBe(0);
+ });
+
+ test("a comparison alone opens no record, because it says nothing about coverage", () => {
+ const looks = new Map<string, WatchedSource>();
+ recordLook(looks, "compare_to_source", {
+ source: { assetId: "a1", name: "reference.mp4", duration: 71.6, type: "video", sound: "yes" },
+ checked: [{ at: 1, source: 1 }],
+ });
+ expect(looks.size).toBe(0);
+ });
+
test("anything that is not a look is ignored", () => {
const looks = new Map<string, WatchedSource>();
recordLook(looks, "add_title", { source: { assetId: "a1" } });
diff --git a/site/src/cut/lib/turnQuality.ts b/site/src/cut/lib/turnQuality.ts
index 759db55b..0b389e2c 100644
--- a/site/src/cut/lib/turnQuality.ts
+++ b/site/src/cut/lib/turnQuality.ts
@@ -59,6 +59,9 @@ export interface WatchedSource {
observed: { from: number; to: number; text: string }[];
/** Hard cuts the passes found. */
cuts: number;
+ /** Moments of the cut held up against this source and looked at. Watching
+ * says what the source does; only this says whether the cut does it too. */
+ compared: number;
}
/** The turn as the gate sees it. */
@@ -70,6 +73,9 @@ export interface TurnWork {
/** Tools this turn ran, and the ones that failed. */
ran: string[];
failed: string[];
+ /** Whether any of them changed the project. A turn that answered an ask for
+ * work by describing it changed nothing, and that is measurable. */
+ mutated: boolean;
/** Sources this turn looked at. */
sources: WatchedSource[];
/** The editor as it stands now. */
@@ -89,6 +95,7 @@ export function qualityState(work: TurnWork): Entry {
reply: work.reply.slice(0, TEXT_CAP),
ran: work.ran,
failed: work.failed,
+ changedTheProject: work.mutated,
sources: work.sources.map((s) => ({
name: s.name,
duration: s.duration,
@@ -106,6 +113,7 @@ export function qualityState(work: TurnWork): Entry {
secondsNeverSeen: s.unwatched,
secondsSeenOnlyAsThumbnails: s.unread,
cutsFound: s.cuts,
+ momentsCheckedAgainstIt: s.compared,
}
: {}),
...(s.sound === "none" ? {} : { secondsNeverHeard: s.unheard }),
@@ -121,7 +129,7 @@ export const QUALITY_QUESTIONS = {
finished: noul(
"Is the job `request` asks for actually finished in `editor`? Judge the editor's state and `ran`, not the reply's account of it.",
{
- true: "Everything the request named exists in the editor now; the request asked for nothing to be built — a question, a look at the footage, a conversation; or it asks for something this editor refuses and the reply says so plainly.",
+ true: "Everything the request named exists in the editor now; the request asked for nothing to be built — a question, a look at the footage, a conversation; the request is genuinely ambiguous or blocked and the reply asks the one question that settles it; or it asks for something this editor refuses and the reply says so plainly.",
false:
"Part of the ask is missing, only planned, or only described in words: shots the reply says it would lay down that no item shows, text the reference has that no title carries, a build stopped halfway.",
},
@@ -178,7 +186,7 @@ export type QualityAnswers = {
closeness: ChoiceAnswer<Record<"shape" | "normal" | "exact", string>>;
};
-export type QualityStep = "watch" | "repair";
+export type QualityStep = "watch" | "build" | "check" | "repair";
export interface QualityVerdict {
step: QualityStep;
@@ -219,6 +227,26 @@ function leastHeard(sources: WatchedSource[]): WatchedSource | null {
return worst && worst.unheard > 0.5 ? worst : null;
}
+/** Whether the cut holds anything a frame would show beside the source.
+ * A shell is the supported end of a replication — colour slabs waiting for
+ * the person's own footage — and every difference between a slab and the
+ * reference's picture is the footage they bring, so there is nothing there to
+ * compare and nothing a steer could fix. An element, or one shot with a
+ * picture in it, is a build with something to look at. */
+function madeAPicture(work: TurnWork): boolean {
+ const e = work.editor as { clips?: unknown; emptyShots?: unknown; overlayKinds?: unknown };
+ const kinds = Array.isArray(e.overlayKinds) ? e.overlayKinds.length : 0;
+ if (kinds > 0) return true;
+ const clips = typeof e.clips === "number" ? e.clips : 0;
+ const empty = typeof e.emptyShots === "number" ? e.emptyShots : 0;
+ return clips - empty > 0;
+}
+
+/** How far into a source the turn's notes reach. */
+function describedTo(src: WatchedSource): number {
+ return src.observed.reduce((n, note) => Math.max(n, note.to), 0);
+}
+
/** What the turn has already put in the editor, named in the steer. A turn
* sent back to look does not start the build over: told nothing, it lays the
* same shots down again and the cut comes out as long as the number of passes
@@ -337,6 +365,47 @@ export function qualityVerdict(
};
}
+ // A replica nobody held up against the thing it copies. Watching measures
+ // what went in and the counts measure what came out; neither says the two
+ // look alike. The number here is moments checked, and it is only asked of a
+ // turn that wrote something down about the source and then made a picture to
+ // hold up — so a comparison has something on both sides to compare.
+ //
+ // Only the source the cut was copied from is owed one, and that is the one
+ // the turn read furthest into: a turn also picks shots out of the user's own
+ // footage, and holding the cut up against that asks it to match material it
+ // already contains.
+ const copied = work.sources
+ .filter((src) => src.kind === "video" && src.observed.length > 0)
+ .sort((a, b) => describedTo(b) - describedTo(a))[0];
+ const unchecked =
+ answers.closeness.choice === "exact" && work.mutated && madeAPicture(work) && copied?.compared === 0
+ ? copied
+ : undefined;
+ if (unchecked)
+ return {
+ step: "check",
+ steer:
+ `${QUALITY_STEER_PREFIX} Not yet. Nothing has been held up against "${unchecked.name}": you have what it does written down, and no look at whether the cut does it too. ` +
+ "compare_to_source on it, a few moments at a time, spread across what you built — the source's frame and yours side by side. " +
+ "Name what differs and fix it, then check the moments you changed." +
+ standing(work),
+ };
+
+ // An ask for work, and a turn that did none. The editor cannot prove a build
+ // half-finished — which is why a doubt about it needs a measure — but it can
+ // prove nothing was built. A turn that changed nothing has no work to
+ // duplicate, so sending it back can only add, and one that has already been
+ // sent back without moving closes on the gate's own mark.
+ if (!work.mutated && answers.finished.noul < settings.qualityFinished)
+ return {
+ step: "build",
+ steer:
+ `${QUALITY_STEER_PREFIX} Not yet. Nothing in the project changed this turn, and the ask is for work on it. ` +
+ "Build it with tools now, from the record you already hold, and close on what the cut actually is." +
+ standing(work),
+ };
+
if (work.failed.length > 0) {
return {
step: "repair",
@@ -385,13 +454,24 @@ export function recordLook(
tool: string,
response: unknown,
): void {
- if (tool !== "watch_video" && tool !== "note_source" && tool !== "listen_audio") return;
+ if (
+ tool !== "watch_video" &&
+ tool !== "note_source" &&
+ tool !== "listen_audio" &&
+ tool !== "compare_to_source"
+ )
+ return;
if (!isRec(response)) return;
const src = isRec(response.source) ? response.source : null;
const id = src && typeof src.assetId === "string" ? src.assetId : null;
if (!src || !id) return;
const kind = src.type === "audio" || src.type === "image" ? src.type : "video";
const sound = src.sound === "yes" || src.sound === "none" ? src.sound : "unknown";
+ // A comparison is a check on a source, not a look at one: it reports no
+ // coverage. Opening a record from it would mint one saying nothing has been
+ // seen, and the looking holds would send the turn back to watch a source it
+ // may have read in full turns ago.
+ if (tool === "compare_to_source" && !sources.has(id)) return;
const cur: WatchedSource = sources.get(id) ?? {
name: typeof src.name === "string" ? src.name : "this source",
duration: numOf(src.duration),
@@ -408,11 +488,17 @@ export function recordLook(
unnoted: [],
observed: [],
cuts: 0,
+ compared: 0,
};
// The source says what it is on every result, so a record opened by one
// sense learns what the others can ask of it.
cur.kind = kind;
cur.sound = sound;
+ if (tool === "compare_to_source") {
+ cur.compared += Array.isArray(response.checked) ? response.checked.length : 0;
+ sources.set(id, cur);
+ return;
+ }
if (tool === "listen_audio") {
cur.passes++;
cur.unheard = numOf(response.unheardSeconds, cur.unheard);
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index a6fb2a89..b38903f3 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -167,6 +167,9 @@ export const SETTINGS = defineSettings({
// How many times one turn may be sent back to work by the gate.
qualityRounds: z.number().int().min(0).max(6),
})
+ // A stored override is parsed as one whole object, so a key added here
+ // without `.default(...)` makes every row written before it fail and
+ // silently drops that row's other values back to the defaults below.
.strict(),
default: {
skillSuggestion: true,