Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(agent): le bac à sable de deepagents fabriquait une preuve d'absence
Etienne Lescot0e53709ad01c
diff --git a/electron/ai-edition/agent-tools.test.ts b/electron/ai-edition/agent-tools.test.tsindex 097248fb4..7af6d5660 100644--- a/electron/ai-edition/agent-tools.test.ts+++ b/electron/ai-edition/agent-tools.test.ts@@ -4,7 +4,8 @@ import {createEmptyDocument,documentSchema,} from "../../src/lib/ai-edition/schema";-import { AGENT_TOOL_SPECS, executeAgentTool, isMutatingTool } from "./agent-tools";+import { ZOOM_DEPTH_SCALES } from "../../src/lib/ai-edition/timeline/zoom-scale";+import { executeAgentTool, isMutatingTool, MUTATING_TOOL_NAMES } from "./agent-tools";function fixtureDocument(): AxcutDocument {const base = createEmptyDocument({ title: "Test", projectId: "proj_1" });@@ -71,28 +72,107 @@ function fixtureDocument(): AxcutDocument {});}-describe("agent-tools specs", () => {- it("declares the clip/trim + effect tools with mutation flags", () => {- const names = AGENT_TOOL_SPECS.map((t) => t.name);- expect(names).toEqual([- "getCurrentDocument",- "getTranscript",- "addTrim",- "setTrim",- "setClipRange",- "replaceTimeline",- "addZoom",- "setZoom",- "addSpeed",- "setSpeed",- "addAnnotation",- "setAnnotation",- "addCameraFullscreen",- "setCameraFullscreen",- "removeTrim",- "removeModifier",- "removeClip",- ]);+/** One clip whose end is NOT a round number — the real recording length that+ * made the clamp visible (24.703979 s of source, stored as 24 704 ms). */+function shortSingleClip(): AxcutDocument {+ const base = createEmptyDocument({ title: "Short", projectId: "proj_short" });+ return documentSchema.parse({+ ...base,+ project: { ...base.project, primaryAssetId: "asset_1" },+ assets: [+ {+ id: "asset_1",+ kind: "video",+ label: "Recording",+ originalPath: "C:/videos/rec.mp4",+ durationSec: 24.703979,+ },+ ],+ timeline: {+ ...base.timeline,+ clips: [+ {+ id: "clip_1",+ assetId: "asset_1",+ sourceStartSec: 0,+ sourceEndSec: 24.703979,+ timelineStartSec: 0,+ timelineEndSec: 24.703979,+ wordRefs: [],+ origin: "user",+ reason: "",+ },+ ],+ },+ });+}++/** The same document with a webcam linked to its asset. Two projects that+ * differ ONLY here were indistinguishable to the model before `hasCameraTrack`+ * reached the snapshot. */+function withCameraTrack(document: AxcutDocument): AxcutDocument {+ return documentSchema.parse({+ ...document,+ assets: document.assets.map((a) => ({+ ...a,+ cameraTrack: { sourcePath: "C:/videos/cam.mp4", startMs: 0, offsetMs: 0, visible: true },+ })),+ });+}++/** A zoom carrying BOTH depth and customScale — the state `migrate.ts` leaves a+ * v1.7 project in, where the depth is inert at render. */+function zoomWithCustomScale(document: AxcutDocument, customScale: number): AxcutDocument {+ return documentSchema.parse({+ ...document,+ zoomRanges: [+ {+ id: "zoom_1",+ startMs: 2_000,+ endMs: 6_000,+ clipId: "clip_1",+ sourceStartSec: 2,+ sourceEndSec: 6,+ depth: 3,+ focus: { cx: 0.5, cy: 0.5 },+ focusMode: "manual",+ customScale,+ source: "manual",+ },+ ],+ });+}++describe("the mutating-tool table", () => {+ it("names every write and nothing else", () => {+ // ponytail: this used to read the `name`/`mutating` pairs off+ // AGENT_TOOL_SPECS, ~300 lines of JSON schema whose comment claimed it was+ // "sent verbatim to the provider" and which had not reached a provider in a+ // release. The names are now pinned where they are actually built — see+ // deep-agent/service.test.ts, which ties TOOL_DESCRIPTIONS, buildTools and+ // this executor's switch to one another. What is left here is the one thing+ // the specs carried that production still needs: which tools write.+ expect([...MUTATING_TOOL_NAMES].sort()).toEqual(+ [+ "addAnnotation",+ "addCameraFullscreen",+ "addSpeed",+ "addTrim",+ "addZoom",+ "moveClip",+ "removeClip",+ "removeModifier",+ "removeTrim",+ "replaceTimeline",+ "setAnnotation",+ "setCameraFullscreen",+ "setClipRange",+ "setSpeed",+ "setTrim",+ "setZoom",+ ].sort(),+ );+ expect(isMutatingTool("getCurrentDocument")).toBe(false);expect(isMutatingTool("getTranscript")).toBe(false);expect(isMutatingTool("replaceTimeline")).toBe(true);expect(isMutatingTool("addZoom")).toBe(true);@@ -277,7 +357,7 @@ describe("executeAgentTool", () => {expect(result.summary).toMatch(/2 intervals/);});- it("replaceTimeline refuses when the timeline has user-placed clips", () => {+ it("replaceTimeline refuses to shorten a clip out of existence", () => {const result = executeAgentTool(fixtureDocument(),"replaceTimeline",@@ -287,9 +367,11 @@ describe("executeAgentTool", () => {}),);expect(result.ok).toBe(false);- const payload = JSON.parse(result.resultJson) as { error: string };- expect(payload.error).toMatch(/user-placed clip/);+ const payload = JSON.parse(result.resultJson) as { error: string; lostClipIds: string[] };+ expect(payload.lostClipIds).toEqual(["clip_2"]);+ expect(payload.error).toMatch(/clip_2/);expect(payload.error).toMatch(/addTrim/);+ expect(result.document).toBeUndefined();});it("rejects malformed JSON arguments and unknown tools", () => {@@ -378,7 +460,7 @@ describe("executeAgentTool", () => {it("addCameraFullscreen / setCameraFullscreen write a region the snapshot exposes", () => {const added = executeAgentTool(- fixtureDocument(),+ withCameraTrack(fixtureDocument()),"addCameraFullscreen",JSON.stringify({ startSec: 9, endSec: 5 }),);@@ -412,7 +494,7 @@ describe("executeAgentTool", () => {expect(movedRegion).toMatchObject({ startMs: 1000, endMs: 2000 });expect(executeAgentTool(- fixtureDocument(),+ withCameraTrack(fixtureDocument()),"setCameraFullscreen",JSON.stringify({ cameraFullscreenId: "nope" }),).ok,@@ -473,6 +555,103 @@ describe("executeAgentTool", () => {expect(wrong.resultJson).toMatch(/removeTrim/);});+ it("addZoom reports the CLAMPED span, not the one it was asked for", () => {+ // ponytail: the exact shape of D-HONEST. Ventilation trims the span to the+ // clip; the tool used to echo back 20–40 while the document held 20–24.704+ // and answer ok:true, so the model reported a zoom that does not exist as+ // asked. The oracle `diffMatches` was written for precisely this.+ const doc = shortSingleClip();+ const result = executeAgentTool(doc, "addZoom", JSON.stringify({ startSec: 20, endSec: 40 }));+ expect(result.ok).toBe(true);+ const payload = JSON.parse(result.resultJson);+ expect(payload.startSec).toBe(20);+ expect(payload.endSec).toBeCloseTo(24.704, 3);+ expect(payload.clamped).toBe(true);+ expect(payload.requestedEndSec).toBe(40);+ // And the document agrees with the report, which is the whole point.+ const stored = result.document?.zoomRanges.at(-1);+ expect(stored?.endMs).toBe(24_704);+ expect(payload.ids).toEqual([stored?.id]);+ expect(result.summary).toMatch(/clamped from/);+ });++ it("addZoom refuses a span that covers no clip instead of storing a dead region", () => {+ const result = executeAgentTool(+ shortSingleClip(),+ "addZoom",+ JSON.stringify({ startSec: 90, endSec: 95 }),+ );+ expect(result.ok).toBe(false);+ expect(result.document).toBeUndefined();+ const payload = JSON.parse(result.resultJson) as { error: string };+ // The refusal has to be actionable: without the real extent the model can+ // only retry blindly, and there is no timeout anywhere on this path.+ expect(payload.error).toMatch(/covers no clip/);+ expect(payload.error).toMatch(/0\.0–24\.7 s/);+ });++ it("addZoom reports BOTH ids when the span straddles two clips", () => {+ // `anchorRawRegionsToClips` keeps the region's id for the first fragment+ // and mints a fresh one for each extra clip. The result used to name one+ // id and one span for a write that produced two regions.+ const result = executeAgentTool(+ fixtureDocument(),+ "addZoom",+ JSON.stringify({ startSec: 25, endSec: 35 }),+ );+ expect(result.ok).toBe(true);+ const payload = JSON.parse(result.resultJson);+ expect(payload.ids).toHaveLength(2);+ expect(payload.fragments).toBe(2);+ const stored = new Set((result.document?.zoomRanges ?? []).map((z) => z.id));+ for (const id of payload.ids as string[]) expect(stored.has(id)).toBe(true);+ expect(result.summary).toMatch(/split across 2 clips/);+ });++ it("setClipRange names the modifiers its trim destroyed", () => {+ // Before: "trimmed clip to 0:00.0 – 0:03.0" while a zoom ceased to exist,+ // with nothing in the result to contradict "the zoom is preserved".+ const doc = fixtureDocument();+ const withZoom = executeAgentTool(doc, "addZoom", JSON.stringify({ startSec: 5, endSec: 8 }))+ .document as AxcutDocument;+ const zoomId = withZoom.zoomRanges[0].id;++ const result = executeAgentTool(+ withZoom,+ "setClipRange",+ JSON.stringify({ clipId: "clip_1", sourceStartSec: 0, sourceEndSec: 3 }),+ );+ expect(result.ok).toBe(true);+ const payload = JSON.parse(result.resultJson);+ expect(payload.droppedModifierIds).toEqual([zoomId]);+ expect(result.document?.zoomRanges.map((z) => z.id)).not.toContain(zoomId);+ expect(result.summary).toContain(zoomId);+ });++ it("setClipRange says nothing about casualties when there are none", () => {+ const result = executeAgentTool(+ fixtureDocument(),+ "setClipRange",+ JSON.stringify({ clipId: "clip_1", sourceStartSec: 0, sourceEndSec: 20 }),+ );+ const payload = JSON.parse(result.resultJson);+ expect(payload.droppedModifierIds).toEqual([]);+ expect(payload.droppedTrimIds).toEqual([]);+ expect(result.summary).not.toContain("dropped");+ });++ it("removeClip names the modifiers that went with the clip", () => {+ const doc = fixtureDocument();+ const withZoom = executeAgentTool(doc, "addZoom", JSON.stringify({ startSec: 5, endSec: 8 }))+ .document as AxcutDocument;+ const zoomId = withZoom.zoomRanges[0].id;++ const result = executeAgentTool(withZoom, "removeClip", JSON.stringify({ clipId: "clip_1" }));+ expect(result.ok).toBe(true);+ expect(JSON.parse(result.resultJson).droppedModifierIds).toEqual([zoomId]);+ expect(result.summary).toContain(zoomId);+ });+it("removeClip deletes a clip and reflows the survivor (rejects an unknown id)", () => {const result = executeAgentTool(fixtureDocument(),@@ -492,3 +671,752 @@ describe("executeAgentTool", () => {).toBe(false);});});++// ─── What the snapshot says the project IS ─────────────────────────────────+//+// A projection's omissions are claims. Two of them were being read as facts:+// an absent `cameraTrack` made a project with a webcam and one without+// indistinguishable, and a bare `depth` made an ordinal look like a factor.+describe("documentSnapshotForModel", () => {+ interface Snapshot {+ autoFocusAll: boolean;+ hasAnyCamera: boolean;+ zoomNote: string;+ assets: Array<{ hasCameraTrack: boolean; cameraVisible: boolean }>;+ zoomRanges: Array<{+ depth: number;+ renderedScale: number;+ customScale?: number;+ depthIsOverridden?: boolean;+ focusMode: string;+ source: string;+ }>;+ }++ function snapshotOf(document: AxcutDocument): Snapshot {+ return JSON.parse(executeAgentTool(document, "getCurrentDocument", "").resultJson) as Snapshot;+ }++ it("reports a zoom's rendered scale, not just its ordinal depth", () => {+ const snapshot = snapshotOf(+ documentSchema.parse({+ ...fixtureDocument(),+ zoomRanges: [+ {+ id: "zoom_1",+ startMs: 2_000,+ endMs: 6_000,+ clipId: "clip_1",+ sourceStartSec: 2,+ sourceEndSec: 6,+ depth: 3,+ focus: { cx: 0.5, cy: 0.5 },+ },+ ],+ }),+ );+ // Both assertions on purpose: the literal is what the pill on screen reads,+ // and the table cross-check makes this fail if someone edits the mapping+ // without meaning to. The prompt used to promise ~2.0× for this zoom.+ expect(snapshot.zoomRanges[0].renderedScale).toBe(1.8);+ expect(snapshot.zoomRanges[0].renderedScale).toBe(ZOOM_DEPTH_SCALES[3]);+ expect(snapshot.zoomRanges[0].depth).toBe(3);+ expect(snapshot.zoomRanges[0].depthIsOverridden).toBeUndefined();+ expect(snapshot.zoomRanges[0].focusMode).toBe("manual");+ expect(snapshot.zoomRanges[0].source).toBe("manual");+ expect(snapshot.zoomNote).toMatch(/3=1\.80×/);+ });++ it("flags a customScale that makes the depth inert", () => {+ const snapshot = snapshotOf(zoomWithCustomScale(fixtureDocument(), 1.1));+ expect(snapshot.zoomRanges[0].renderedScale).toBe(1.1);+ expect(snapshot.zoomRanges[0].customScale).toBe(1.1);+ expect(snapshot.zoomRanges[0].depthIsOverridden).toBe(true);+ // depth 6 would render 5.0×; the model must not read it as the strength.+ expect(snapshot.zoomRanges[0].depth).toBe(3);+ });++ it("clamps a customScale the schema accepts but the renderer will not", () => {+ // `zoomRegionSchema` only asks for a positive number, so 12 is a legal+ // document. The preview clamps to 5.0; reporting 12 would be a third scale.+ const snapshot = snapshotOf(zoomWithCustomScale(fixtureDocument(), 12));+ expect(snapshot.zoomRanges[0].renderedScale).toBe(5);+ });++ it("reports the EFFECTIVE focus mode when the global Auto-Focus is on", () => {+ // `autoFocusAll` overrides every region's own mode at render+ // (sceneDescription.ts) and greys out the per-region control. Echoing the+ // stored "manual" would tell the model its focus point is being honoured+ // while the camera follows the cursor.+ const base = zoomWithCustomScale(fixtureDocument(), 1.1);+ const snapshot = snapshotOf(+ documentSchema.parse({ ...base, legacyEditor: { autoFocusAll: true } }),+ );+ expect(snapshot.autoFocusAll).toBe(true);+ expect(snapshot.zoomRanges[0].focusMode).toBe("auto");+ expect(snapshotOf(base).autoFocusAll).toBe(false);+ expect(snapshotOf(base).zoomRanges[0].focusMode).toBe("manual");+ });++ it("says whether each asset carries a webcam, and whether any clip does", () => {+ const bare = snapshotOf(fixtureDocument());+ expect(bare.assets[0].hasCameraTrack).toBe(false);+ expect(bare.assets[0].cameraVisible).toBe(false);+ expect(bare.hasAnyCamera).toBe(false);++ const withCam = snapshotOf(withCameraTrack(fixtureDocument()));+ expect(withCam.assets[0].hasCameraTrack).toBe(true);+ expect(withCam.assets[0].cameraVisible).toBe(true);+ expect(withCam.hasAnyCamera).toBe(true);+ });++ it("hasAnyCamera follows the placed clips, not merely the assets present", () => {+ // An imported-but-unused asset with a webcam does not put a webcam on the+ // timeline, and answering "yes" there is the same false confidence in the+ // other direction.+ const document = withCameraTrack(fixtureDocument());+ const unplaced = documentSchema.parse({+ ...document,+ timeline: { ...document.timeline, clips: [], trimRanges: [] },+ });+ expect(snapshotOf(unplaced).assets[0].hasCameraTrack).toBe(true);+ expect(snapshotOf(unplaced).hasAnyCamera).toBe(false);+ });+});++describe("zoom strength is written, not just stored", () => {+ it("addZoom reports the scale the viewer will see", () => {+ const result = executeAgentTool(+ fixtureDocument(),+ "addZoom",+ JSON.stringify({ startSec: 2, endSec: 6, depth: 3 }),+ );+ expect(result.ok).toBe(true);+ expect(JSON.parse(result.resultJson).renderedScale).toBe(1.8);+ expect(result.summary).toContain("1.80×");+ });++ it("setZoom{depth} on a customScale zoom clears the override instead of no-op'ing", () => {+ // The defect this closes: the write was accepted, the depth was stored, the+ // result echoed it, and the frame stayed at 1.10× — a change every layer+ // believed had happened.+ const result = executeAgentTool(+ zoomWithCustomScale(fixtureDocument(), 1.1),+ "setZoom",+ JSON.stringify({ zoomId: "zoom_1", depth: 6 }),+ );+ expect(result.ok).toBe(true);+ const after = result.document as AxcutDocument;+ expect(after.zoomRanges[0].customScale).toBeUndefined();+ expect(after.zoomRanges[0].depth).toBe(6);+ const payload = JSON.parse(result.resultJson);+ expect(payload.renderedScale).toBe(ZOOM_DEPTH_SCALES[6]);+ expect(payload.clearedCustomScale).toBe(true);+ expect(result.summary).toMatch(/custom scale/i);+ });++ it("leaves customScale alone when the write does not touch the depth", () => {+ // Dropping a fine-tuned value is destructive; it is only justified by an+ // explicit request to change the strength.+ const result = executeAgentTool(+ zoomWithCustomScale(fixtureDocument(), 1.1),+ "setZoom",+ JSON.stringify({ zoomId: "zoom_1", startSec: 3, endSec: 7 }),+ );+ expect(result.ok).toBe(true);+ const after = result.document as AxcutDocument;+ expect(after.zoomRanges[0].customScale).toBe(1.1);+ expect(JSON.parse(result.resultJson).clearedCustomScale).toBeUndefined();+ expect(JSON.parse(result.resultJson).renderedScale).toBe(1.1);+ });+});++describe("a full-camera region needs a camera", () => {+ it("is refused on footage with no linked webcam", () => {+ const result = executeAgentTool(+ fixtureDocument(),+ "addCameraFullscreen",+ JSON.stringify({ startSec: 0, endSec: 5 }),+ );+ expect(result.ok).toBe(false);+ expect(result.document).toBeUndefined();+ const error = JSON.parse(result.resultJson).error as string;+ expect(error).toMatch(/no webcam/i);+ // Actionable, and specific about WHICH kind of nothing: no camera anywhere+ // is a fact about the recording the model should relay, not retry.+ expect(error).toMatch(/hasCameraTrack/);+ expect(error).toMatch(/no asset in this project/i);+ });++ it("is allowed on footage that carries one", () => {+ const result = executeAgentTool(+ withCameraTrack(fixtureDocument()),+ "addCameraFullscreen",+ JSON.stringify({ startSec: 0, endSec: 5 }),+ );+ expect(result.ok).toBe(true);+ const legacy = result.document?.legacyEditor as Record<string, unknown>;+ expect(legacy.cameraFullscreenRegions).toHaveLength(1);+ });++ it("refuses to MOVE a region onto footage with no webcam", () => {+ // clip_2 comes from a second asset with no camera. Placing is guarded and+ // moving was not, which would have re-opened the hole one tool over.+ const document = withCameraTrack(fixtureDocument());+ const mixed = documentSchema.parse({+ ...document,+ assets: [+ document.assets[0],+ {+ id: "asset_2",+ kind: "video",+ label: "Screen only",+ originalPath: "C:/videos/screen.mp4",+ durationSec: 60,+ },+ ],+ timeline: {+ ...document.timeline,+ clips: document.timeline.clips.map((c) =>+ c.id === "clip_2" ? { ...c, assetId: "asset_2" } : c,+ ),+ },+ });+ const added = executeAgentTool(+ mixed,+ "addCameraFullscreen",+ JSON.stringify({ startSec: 0, endSec: 5 }),+ );+ expect(added.ok).toBe(true);+ const regionId = (+ (added.document?.legacyEditor as Record<string, unknown>).cameraFullscreenRegions as Array<{+ id: string;+ }>+ )[0].id;+ const moved = executeAgentTool(+ added.document as AxcutDocument,+ "setCameraFullscreen",+ JSON.stringify({ cameraFullscreenId: regionId, startSec: 40, endSec: 45 }),+ );+ expect(moved.ok).toBe(false);+ // Other clips DO carry a camera here, so the advice differs from the+ // no-camera-anywhere case above.+ expect(JSON.parse(moved.resultJson).error).toMatch(/other clips/i);+ });+});++// ── D-DESTRUCT ──────────────────────────────────────────────────────────────+//+// "Swap the two clips: put the demo first." There was no tool for it — while+// the system prompt promised one — so the model reached for `replaceTimeline`+// with [30-60], [0-30]. That call sorted the intervals (so the swap never+// happened), merged them (so two clips became one), re-minted the ids, deleted+// the user's 12–17 s cut, re-anchored the effects onto whatever had slid under+// them, and returned `ok: true`. The model then reported that the trim was+// preserved. Every layer of that is fixed separately below.+describe("replaceTimeline refuses what it would destroy", () => {+ /** The workbench's `twoClipsWithTrim`: clips placed by the AGENT, which is+ * exactly what the old `origin === "user"` guard could not see. */+ function twoAgentClipsWithTrim(): AxcutDocument {+ const base = createEmptyDocument({ title: "Two clips", projectId: "proj_two" });+ return documentSchema.parse({+ ...base,+ project: { ...base.project, primaryAssetId: "asset_1" },+ assets: [+ {+ id: "asset_1",+ kind: "video",+ label: "Recording",+ originalPath: "C:/videos/rec.mp4",+ durationSec: 60,+ },+ ],+ timeline: {+ ...base.timeline,+ clips: [+ {+ id: "clip_1",+ assetId: "asset_1",+ sourceStartSec: 0,+ sourceEndSec: 30,+ timelineStartSec: 0,+ timelineEndSec: 30,+ wordRefs: [],+ origin: "agent",+ reason: "intro",+ },+ {+ id: "clip_2",+ assetId: "asset_1",+ sourceStartSec: 30,+ sourceEndSec: 60,+ timelineStartSec: 30,+ timelineEndSec: 60,+ wordRefs: [],+ origin: "agent",+ reason: "demo",+ },+ ],+ trimRanges: [+ {+ id: "trim_1",+ assetId: "asset_1",+ startSec: 12,+ endSec: 17,+ reason: "silence",+ origin: "agent",+ },+ ],+ },+ });+ }++ const swapArgs = JSON.stringify({+ intervals: [+ { startSec: 30, endSec: 60 },+ { startSec: 0, endSec: 30 },+ ],+ reason: "swap",+ });++ it("refuses the swap the workbench measured, and says which tool does it", () => {+ const result = executeAgentTool(twoAgentClipsWithTrim(), "replaceTimeline", swapArgs);+ expect(result.ok).toBe(false);+ expect(result.document).toBeUndefined();+ const payload = JSON.parse(result.resultJson) as {+ error: string;+ code: string;+ reorderRequested: boolean;+ lostClipIds: string[];+ };+ expect(payload.code).toBe("would_destroy");+ expect(payload.reorderRequested).toBe(true);+ expect(payload.error).toMatch(/moveClip/);+ // It is refused for the RIGHT reason: nothing would be lost any more (the+ // pure layer preserves both clips and the cut now), but the swap the user+ // asked for still cannot happen, so answering `ok` would be a lie of a+ // different kind — the tool would report success on a no-op.+ expect(payload.lostClipIds).toEqual([]);+ expect(payload.error).toMatch(/ascending order/);+ });++ it("the guard no longer depends on origin, so it cannot disarm itself", () => {+ // `buildTimelineFromIntervals` stamps its own origin on everything it+ // produces, so ONE legitimate agent rebuild used to turn every clip into+ // `origin: "agent"` and switch the old guard off for the rest of the+ // project's life. Here both clips are already `agent` and it still refuses.+ const first = executeAgentTool(twoAgentClipsWithTrim(), "replaceTimeline", swapArgs);+ expect(first.ok).toBe(false);+ const second = executeAgentTool(twoAgentClipsWithTrim(), "replaceTimeline", swapArgs);+ expect(second.ok).toBe(false);+ });++ it("does not refuse a rebuild with nothing to lose", () => {+ const empty = documentSchema.parse({+ ...twoAgentClipsWithTrim(),+ timeline: { ...twoAgentClipsWithTrim().timeline, clips: [], trimRanges: [] },+ });+ const result = executeAgentTool(+ empty,+ "replaceTimeline",+ JSON.stringify({+ intervals: [+ { startSec: 0, endSec: 10 },+ { startSec: 20, endSec: 30 },+ ],+ reason: "rebuild",+ }),+ );+ expect(result.ok).toBe(true);+ expect(result.document?.timeline.clips).toHaveLength(2);+ });++ it("names what survived instead of reporting two bare counts", () => {+ const result = executeAgentTool(+ twoAgentClipsWithTrim(),+ "replaceTimeline",+ JSON.stringify({+ intervals: [+ { startSec: 0, endSec: 30 },+ { startSec: 30, endSec: 60 },+ ],+ reason: "identity",+ }),+ );+ expect(result.ok).toBe(true);+ const payload = JSON.parse(result.resultJson) as { preservedClipIds: string[] };+ expect(payload.preservedClipIds).toEqual(["clip_1", "clip_2"]);+ expect(result.document?.timeline.trimRanges.map((t) => t.id)).toEqual(["trim_1"]);+ });+});++describe("moveClip — the tool the prompt used to promise", () => {+ function twoClips(): AxcutDocument {+ const base = createEmptyDocument({ title: "Two clips", projectId: "proj_move" });+ return documentSchema.parse({+ ...base,+ project: { ...base.project, primaryAssetId: "asset_1" },+ assets: [+ {+ id: "asset_1",+ kind: "video",+ label: "Recording",+ originalPath: "C:/videos/rec.mp4",+ durationSec: 60,+ },+ ],+ timeline: {+ ...base.timeline,+ clips: [+ {+ id: "clip_1",+ assetId: "asset_1",+ sourceStartSec: 0,+ sourceEndSec: 30,+ timelineStartSec: 0,+ timelineEndSec: 30,+ wordRefs: [],+ origin: "user",+ reason: "intro",+ },+ {+ id: "clip_2",+ assetId: "asset_1",+ sourceStartSec: 30,+ sourceEndSec: 60,+ timelineStartSec: 30,+ timelineEndSec: 60,+ wordRefs: [],+ origin: "user",+ reason: "demo",+ },+ ],+ trimRanges: [+ {+ id: "trim_1",+ assetId: "asset_1",+ startSec: 12,+ endSec: 17,+ reason: "silence",+ origin: "user",+ },+ ],+ },+ zoomRanges: [+ {+ id: "zoom_demo",+ startMs: 40_000,+ endMs: 45_000,+ depth: 3,+ focus: { cx: 0.5, cy: 0.5 },+ clipId: "clip_2",+ sourceStartSec: 40,+ sourceEndSec: 45,+ },+ ],+ });+ }++ it("performs the swap, keeping ids, trims and the anchored zoom", () => {+ const result = executeAgentTool(+ twoClips(),+ "moveClip",+ JSON.stringify({ clipId: "clip_2", beforeClipId: "clip_1" }),+ );+ expect(result.ok).toBe(true);+ const after = result.document as AxcutDocument;+ expect(after.timeline.clips.map((c) => c.id)).toEqual(["clip_2", "clip_1"]);+ // Order changed; content did not.+ expect(after.timeline.clips[0]).toMatchObject({ sourceStartSec: 30, sourceEndSec: 60 });+ expect(after.timeline.trimRanges.map((t) => t.id)).toEqual(["trim_1"]);+ expect(after.zoomRanges[0]).toMatchObject({+ id: "zoom_demo",+ clipId: "clip_2",+ sourceStartSec: 40,+ sourceEndSec: 45,+ });+ // clip_2 now starts the timeline, so the zoom's derived ms follow it.+ expect(after.zoomRanges[0]).toMatchObject({ startMs: 10_000, endMs: 15_000 });+ });++ it("keeps the clip's provenance and its label", () => {+ // `moveClip` stamps whatever origin it is handed. Passing "agent" would+ // relabel a user's clip as the agent's — and, before the guard stopped+ // reading `origin`, would have been a way to disarm it.+ const result = executeAgentTool(+ twoClips(),+ "moveClip",+ JSON.stringify({ clipId: "clip_2", beforeClipId: "clip_1" }),+ );+ expect(result.document?.timeline.clips[0]).toMatchObject({+ origin: "user",+ reason: "demo",+ });+ });++ it("moves a clip last when beforeClipId is null, and when it is omitted", () => {+ for (const args of [+ JSON.stringify({ clipId: "clip_1", beforeClipId: null }),+ JSON.stringify({ clipId: "clip_1" }),+ ]) {+ const result = executeAgentTool(twoClips(), "moveClip", args);+ expect(result.ok).toBe(true);+ expect(result.document?.timeline.clips.map((c) => c.id)).toEqual(["clip_2", "clip_1"]);+ }+ });++ it("refuses an unknown id with the roster instead of throwing", () => {+ // `moveClip` in the document layer THROWS on an unknown clip, and the tool+ // loop has no try/catch of its own — an escape would kill the turn.+ const missing = executeAgentTool(+ twoClips(),+ "moveClip",+ JSON.stringify({ clipId: "clip_nope", beforeClipId: "clip_1" }),+ );+ expect(missing.ok).toBe(false);+ expect(JSON.parse(missing.resultJson).error).toMatch(/clip_1 \(intro\)/);++ const badTarget = executeAgentTool(+ twoClips(),+ "moveClip",+ JSON.stringify({ clipId: "clip_1", beforeClipId: "clip_nope" }),+ );+ expect(badTarget.ok).toBe(false);+ expect(badTarget.document).toBeUndefined();++ const itself = executeAgentTool(+ twoClips(),+ "moveClip",+ JSON.stringify({ clipId: "clip_1", beforeClipId: "clip_1" }),+ );+ expect(itself.ok).toBe(false);+ });++ it("gives the model the label and index it needs to aim", () => {+ // Without `reason` in the snapshot, "put the demo first" is unanswerable:+ // both clips are 30 s of the same asset and differ only by a label the+ // projection was not sending.+ const snapshot = JSON.parse(+ executeAgentTool(twoClips(), "getCurrentDocument", "").resultJson,+ ) as { clips: Array<{ id: string; index: number; reason: string; origin: string }> };+ expect(snapshot.clips[1]).toMatchObject({ id: "clip_2", index: 1, reason: "demo" });+ expect(snapshot.clips[0].origin).toBe("user");+ });+});++// ── D-CONSENT ───────────────────────────────────────────────────────────────+//+// Settings offers "Project edits — when off, the agent must ask before changing+// the timeline". `chat-service.ts` computed `editsAllowed` and then did+// `void editsAllowed;`. The flag reached nothing: not the tools, not the prompt.+describe("allowAgentEdits=false refuses every write", () => {+ it("refuses a write with a payload that tells the model what to do instead", () => {+ const result = executeAgentTool(+ fixtureDocument(),+ "addTrim",+ JSON.stringify({ startSec: 5, endSec: 8, reason: "silence" }),+ { editsAllowed: false },+ );+ expect(result.ok).toBe(false);+ expect(result.document).toBeUndefined();+ expect(result.summary).toBeUndefined();+ const payload = JSON.parse(result.resultJson) as {+ code: string;+ tool: string;+ requestedArgs: { startSec: number };+ howToProceed: string;+ };+ expect(payload.code).toBe("consent_required");+ expect(payload.tool).toBe("addTrim");+ // The args come back so the model can quote the edit it is asking for.+ expect(payload.requestedArgs.startSec).toBe(5);+ // And it is told not to loop: there is no timeout on the product path.+ expect(payload.howToProceed).toMatch(/do NOT retry/i);+ expect(payload.howToProceed).toMatch(/ask the user/i);+ });++ it("refuses ALL of them — no write escapes by being added later", () => {+ const document = fixtureDocument();+ for (const name of MUTATING_TOOL_NAMES) {+ const result = executeAgentTool(document, name, "{}", { editsAllowed: false });+ expect(result.ok, `${name} was allowed through`).toBe(false);+ expect(result.document, `${name} mutated`).toBeUndefined();+ expect(JSON.parse(result.resultJson).code, `${name} failed for another reason`).toBe(+ "consent_required",+ );+ }+ });++ it("leaves the read tools alone — the model must be able to describe the edit", () => {+ for (const name of ["getCurrentDocument", "getTranscript"]) {+ const result = executeAgentTool(fixtureDocument(), name, "{}", { editsAllowed: false });+ expect(result.ok, name).toBe(true);+ }+ });++ it("changes nothing when the flag is absent or true", () => {+ const args = JSON.stringify({ startSec: 5, endSec: 8, reason: "silence" });+ expect(executeAgentTool(fixtureDocument(), "addTrim", args).ok).toBe(true);+ expect(executeAgentTool(fixtureDocument(), "addTrim", args, {}).ok).toBe(true);+ expect(executeAgentTool(fixtureDocument(), "addTrim", args, { editsAllowed: true }).ok).toBe(+ true,+ );+ });+});++// ─── D-TELEM: recorded cursor telemetry reaches the model ────────────────────+//+// The app records where the pointer went and the compositor loads the sidecar,+// but nothing carried a sample to the agent: `grep -rniE "cursor|telemetry"+// electron/ai-edition/` returned nothing at all. Asked what pointer data the+// project held, the model answered from an empty sandbox and reported, in good+// faith, that there was none. These tests hold the two halves of the fix: the+// snapshot says whether there IS data, and the tool returns the digest — with+// "we could not look" kept strictly apart from "there is none".++function samplesWithDwell(atSec: number, holdSec: number, cx: number, cy: number) {+ const step = 33;+ const out: Array<{ timeMs: number; cx: number; cy: number; interactionType: "move" | "click" }> =+ [];+ const startMs = (atSec - holdSec / 2) * 1000;+ const stopMs = startMs + holdSec * 1000;+ let drift = 0;+ for (let timeMs = 0; timeMs <= (atSec + holdSec) * 1000 + 2000; timeMs += step) {+ if (timeMs >= startMs && timeMs <= stopMs) {+ out.push({ timeMs, cx, cy, interactionType: timeMs === startMs ? "click" : "move" });+ } else {+ drift = (drift + 0.05) % 1;+ out.push({ timeMs, cx: drift, cy: drift, interactionType: "move" });+ }+ }+ return out;+}++describe("cursor telemetry in the snapshot", () => {+ it("reports null — not false — when nothing checked", () => {+ // THE distinction. `false` is a claim about the user's project; `null` is a+ // claim about us. Collapsing them is precisely how the model came to+ // announce that a recording with 597 samples had no pointer data.+ const snapshot = JSON.parse(+ executeAgentTool(fixtureDocument(), "getCurrentDocument", "{}").resultJson,+ );+ expect(snapshot.assets[0].hasCursorTelemetry).toBeNull();+ expect(snapshot.cursorNote).toMatch(/null/);+ });++ it("reports true / false once the runtime has looked", () => {+ const present = JSON.parse(+ executeAgentTool(fixtureDocument(), "getCurrentDocument", "{}", {+ cursorTelemetry: { availableByAssetId: { asset_1: true } },+ }).resultJson,+ );+ expect(present.assets[0].hasCursorTelemetry).toBe(true);++ const absent = JSON.parse(+ executeAgentTool(fixtureDocument(), "getCurrentDocument", "{}", {+ cursorTelemetry: { availableByAssetId: { asset_1: false } },+ }).resultJson,+ );+ expect(absent.assets[0].hasCursorTelemetry).toBe(false);+ });++ it("reports null for an asset the probe could not answer for", () => {+ // A probe that throws leaves its asset OUT of the map rather than in it as+ // `false` — our failure must not become a statement about their project.+ const snapshot = JSON.parse(+ executeAgentTool(fixtureDocument(), "getCurrentDocument", "{}", {+ cursorTelemetry: { availableByAssetId: {} },+ }).resultJson,+ );+ expect(snapshot.assets[0].hasCursorTelemetry).toBeNull();+ });+});++describe("getCursorTrack", () => {+ it("returns real samples, downsampled — not an interpretation of them", () => {+ const samples = samplesWithDwell(10, 1.4, 0.66, 0.33);+ const result = executeAgentTool(fixtureDocument(), "getCursorTrack", "{}", {+ cursorTelemetry: { load: { status: "ok", assetId: "asset_1", samples } },+ });+ const payload = JSON.parse(result.resultJson);++ expect(result.ok).toBe(true);+ expect(payload.available).toBe(true);+ expect(payload.sampleCount).toBe(samples.length);+ expect(payload.points.length).toBeGreaterThan(0);+ // Downsampling drops rows, it never invents them: every point returned has+ // to exist in the input at the same instant and the same place.+ for (const point of payload.points as Array<{ atSec: number; cx: number; cy: number }>) {+ const origin = samples.find((s) => Math.abs(s.timeMs / 1000 - point.atSec) < 0.01);+ expect(origin).toBeTruthy();+ expect(point.cx).toBeCloseTo(origin?.cx ?? -1, 2);+ expect(point.cy).toBeCloseTo(origin?.cy ?? -1, 2);+ }+ // The stationary stretch is present as points, not as a verdict about it:+ // nothing in the payload names a dwell, a hold or a focus.+ const during = (payload.points as Array<{ atSec: number }>).filter(+ (p) => p.atSec >= 10 && p.atSec <= 11.4,+ );+ expect(during.length).toBeGreaterThan(0);+ expect(result.resultJson).not.toContain("holdSec");+ expect(result.resultJson).not.toContain("moments");++ // clip_1 is source 0–30 at ruler 0–30, so source and virtual coincide here;+ // the field still has to be present, because it is the one addZoom takes.+ const point = payload.points.find((p: { atSec: number }) => Math.abs(p.atSec - 10) < 0.3);+ expect(point.virtualSec).toBeCloseTo(point.atSec, 1);+ });++ it("says 'no-sidecar' when the asset was checked and has none", () => {+ const result = executeAgentTool(fixtureDocument(), "getCursorTrack", "{}", {+ cursorTelemetry: { load: { status: "no-sidecar", assetId: "asset_1" } },+ });+ const payload = JSON.parse(result.resultJson);++ // `ok: true`: the question was answered. Marking it a failure would push a+ // model with no timeout above it into retrying a verdict that cannot change.+ expect(result.ok).toBe(true);+ expect(payload.available).toBe(false);+ expect(payload.reason).toBe("no-sidecar");+ expect(payload.note).toMatch(/fact about the asset/i);+ });++ it("says 'unavailable' — never 'no-sidecar' — when no reader is wired", () => {+ // The regression that would recreate the defect quietly: a runtime with no+ // reader reporting an absence of data instead of an absence of access.+ const result = executeAgentTool(fixtureDocument(), "getCursorTrack", "{}");+ const payload = JSON.parse(result.resultJson);++ expect(payload.available).toBe(false);+ expect(payload.reason).toBe("unavailable");+ expect(payload.reason).not.toBe("no-sidecar");+ expect(payload.note).toMatch(/report the limit as yours|limit as yours/i);+ });++ it("rejects an unknown asset instead of digesting someone else's samples", () => {+ const result = executeAgentTool(+ fixtureDocument(),+ "getCursorTrack",+ JSON.stringify({ assetId: "asset_nope" }),+ { cursorTelemetry: { load: { status: "ok", assetId: "asset_nope", samples: [] } } },+ );+ expect(result.ok).toBe(false);+ expect(result.resultJson).toContain("Unknown asset");+ });++ it("is a read: it survives allowAgentEdits=false and mutates nothing", () => {+ // Consent gates writes. A model that may not edit must still be able to+ // describe the edit it is proposing, which means reading the telemetry it+ // would base that proposal on.+ const result = executeAgentTool(fixtureDocument(), "getCursorTrack", "{}", {+ editsAllowed: false,+ cursorTelemetry: {+ load: { status: "ok", assetId: "asset_1", samples: samplesWithDwell(5, 1, 0.5, 0.5) },+ },+ });+ expect(result.ok).toBe(true);+ expect(result.document).toBeUndefined();+ expect(JSON.parse(result.resultJson).available).toBe(true);+ expect(isMutatingTool("getCursorTrack")).toBe(false);+ });+});diff --git a/electron/ai-edition/agent-tools.ts b/electron/ai-edition/agent-tools.tsindex 648ae946e..a4177efaf 100644--- a/electron/ai-edition/agent-tools.ts+++ b/electron/ai-edition/agent-tools.ts@@ -1,16 +1,25 @@-// Agent tool layer (P1.1/P1.2): the JSON-schema tool definitions fed to the-// LLM as `tools[]`, plus the executor that validates arguments (zod) and-// applies each tool against an AxcutDocument snapshot. Pure — no IPC, no fs.-// The chat-service tool loop owns checkpoints and persistence; this module-// only knows how to turn (document, toolName, argsJson) into a new document.+// Agent tool layer (P1.1/P1.2): the zod argument schemas — the single source of+// truth, shared with the LangChain `tool()`s built in `deep-agent/service.ts` —+// plus the executor that validates arguments and applies each tool against an+// AxcutDocument snapshot. Pure — no IPC, no fs. The chat-service tool loop owns+// checkpoints and persistence; this module only knows how to turn+// (document, toolName, argsJson) into a new document.//// Read tools return JSON the model can reason over; write tools return the// mutated document plus a human-readable summary line for the chat panel// ("applied: added trim 0:02.1 – 0:02.4").+//+// The PROSE the model reads lives in `TOOL_DESCRIPTIONS` (deep-agent/service.ts)+// — not here. This header used to claim the file held "the JSON-schema tool+// definitions fed to the LLM as tools[]", which stopped being true when the+// deep-agent landed and stayed on the page for a whole release; the specs it+// described are gone (see `MUTATING_TOOL_NAMES`).import { z } from "zod";import { createId } from "../../src/lib/ai-edition/document/ids";import {+ moveClip,+ planTimelineReplacement,type RegionKind,removeClip,removeRegion,@@ -18,21 +27,25 @@ import {setClipSourceRange,} from "../../src/lib/ai-edition/document/timeline";import type { AxcutDocument } from "../../src/lib/ai-edition/schema";+import { hasAnyClipWithCamera } from "../../src/lib/ai-edition/timeline/camera";+import {+ buildCursorTrack,+ type CursorTrackSample,+} from "../../src/lib/ai-edition/timeline/cursor-track";import {anchorRegionsWithDerivedMs,coalesceRegionsForRuler,replacePillSpan,resolvePillIds,} from "../../src/lib/ai-edition/timeline/timelineMap";--export interface AgentToolSpec {- name: string;- description: string;- /** JSON schema for the tool arguments, sent verbatim to the provider. */- parameters: Record<string, unknown>;- /** True when the tool mutates the document (gates checkpoint + permission). */- mutating: boolean;-}+// ponytail: relative, and it has to stay that way — `electron/` never resolves+// the `@/` alias (the main-process build does not declare it), which is why the+// scale table was moved out of `components/video-editor/types.ts` to be+// reachable from here at all.+import {+ effectiveZoomScale,+ ZOOM_DEPTH_LEGEND,+} from "../../src/lib/ai-edition/timeline/zoom-scale";export interface AgentToolExecution {ok: boolean;@@ -94,6 +107,228 @@ function anchorForAgent<T extends { id: string; startMs: number; endMs: number }return anchorRegionsWithDerivedMs([region], document.timeline.clips, () => createId(prefix));}+// ─── What the write actually LANDED ────────────────────────────────────────+//+// ponytail: every add*/set* used to echo back the span it was ASKED for. Three+// ways that is a lie, all reproduced against the real fixtures:+// • CLAMP — `addZoom {20,40}` on a 24.70 s clip stores 20–24.704 and reported+// 20–40. Ventilation trims the span to the clip, silently.+// • FRAGMENTATION — `addZoom {25,35}` across two clips stores TWO fragments,+// the second with a brand-new id (`anchorRawRegionsToClips:74`), and the+// result named one id and one span.+// • NOTHING PLACED — `addZoom {90,95}` on a 24.70 s timeline covers no clip.+// `anchorRegionsWithDerivedMs` passes it through UNANCHORED by design+// (timelineMap.ts:360-375, so a v2 project with a zero-extent clip does not+// lose data), and it was stored, reported ok, and can never play.+// The document is the referee; the report is read back off it.++interface Landing {+ /** Every id the write produced — more than one when it straddled a clip. */+ ids: string[];+ startSec: number;+ endSec: number;+ /** False when nothing covered a clip: the region cannot ever play. */+ anchored: boolean;+ fragments: number;+}++function overlapsAClip(+ region: { startMs: number; endMs: number },+ document: AxcutDocument,+): boolean {+ const startSec = region.startMs / 1000;+ const endSec = region.endMs / 1000;+ return document.timeline.clips.some(+ (c) => Math.min(endSec, c.timelineEndSec) - Math.max(startSec, c.timelineStartSec) > 0,+ );+}++/**+ * `anchored` is BOTH structural and positional on purpose. `replacePillSpan`+ * re-anchors from `pill.member`, whose payload still carries the OLD `clipId`+ * even when the new span covers nothing — so a `clipId` alone proves nothing+ * about where the region ended up. The ruler overlap is what decides whether a+ * viewer will ever see it.+ */+function landingOf(+ regions: Array<{ id: string; startMs: number; endMs: number; clipId?: string }>,+ document: AxcutDocument,+): Landing {+ const starts = regions.map((r) => r.startMs);+ const ends = regions.map((r) => r.endMs);+ return {+ ids: regions.map((r) => r.id),+ startSec: regions.length ? Math.min(...starts) / 1000 : 0,+ endSec: regions.length ? Math.max(...ends) / 1000 : 0,+ anchored:+ regions.length > 0 &&+ regions.every((r) => typeof r.clipId === "string" && overlapsAClip(r, document)),+ fragments: regions.length,+ };+}++/** The regions a pill edit produced: everything in `after` that is not an+ * untouched original. `replacePillSpan` re-ventilates the pill, so the count and+ * the ids can both change under a caller that only passed one id. */+function landingAfterPillEdit<T extends { id: string; startMs: number; endMs: number }>(+ before: T[],+ after: T[],+ pillIds: Set<string>,+ document: AxcutDocument,+): Landing {+ const untouched = new Set(before.filter((r) => !pillIds.has(r.id)).map((r) => r.id));+ return landingOf(+ after.filter((r) => !untouched.has(r.id)) as Array<T & { clipId?: string }>,+ document,+ );+}++/**+ * Refuse a full-camera region on footage that carries no webcam.+ *+ * ponytail: `addCameraFullscreen` took a span and nothing else, and answered+ * `ok: true` whether or not any camera existed anywhere in the project — it+ * writes into `legacyEditor.cameraFullscreenRegions`, which the schema does not+ * validate. A pair of scenarios identical but for a linked webcam produced+ * identical turns, because the evidence really was identical. The snapshot now+ * carries `hasCameraTrack`, and this is the other half: a region that can only+ * render nothing is not written, and the refusal names the reason.+ */+function cameraUnderSpan(+ document: AxcutDocument,+ startSec: number,+ endSec: number,+): { clips: number; withCamera: number } {+ const covered = document.timeline.clips.filter(+ (c) => Math.min(endSec, c.timelineEndSec) - Math.max(startSec, c.timelineStartSec) > 0,+ );+ return {+ clips: covered.length,+ withCamera: covered.filter(+ (c) => document.assets.find((a) => a.id === c.assetId)?.cameraTrack != null,+ ).length,+ };+}++function noCameraUnderSpan(+ document: AxcutDocument,+ startSec: number,+ endSec: number,+): AgentToolExecution | null {+ const coverage = cameraUnderSpan(document, startSec, endSec);+ if (coverage.clips === 0 || coverage.withCamera > 0) return null;+ const anywhere = hasAnyClipWithCamera(document.assets, document.timeline.clips);+ return failure(+ `No webcam is linked to the footage under ${startSec.toFixed(1)}–${endSec.toFixed(1)} s, ` ++ "so a full-camera region there would render nothing and none was written. " ++ (anywhere+ ? "Other clips in this project do carry a camera — check assets[].hasCameraTrack in getCurrentDocument and pick a span over one of those."+ : "No asset in this project carries a cameraTrack at all (assets[].hasCameraTrack is false everywhere): this recording has no webcam. Tell the user instead of placing a region."),+ );+}++/** The span the edited timeline actually occupies, for an actionable refusal. */+function editedExtentSec(document: AxcutDocument): { startSec: number; endSec: number } {+ const clips = document.timeline.clips;+ if (clips.length === 0) return { startSec: 0, endSec: 0 };+ return {+ startSec: Math.min(...clips.map((c) => c.timelineStartSec)),+ endSec: Math.max(...clips.map((c) => c.timelineEndSec)),+ };+}++/**+ * Refuse rather than store a region that covers no clip. The message carries the+ * real bounds so the model can retry once with a usable span instead of looping+ * — there is no AbortSignal and no timeout on the product path.+ */+function coversNoClip(+ kind: string,+ requestedStartSec: number,+ requestedEndSec: number,+ document: AxcutDocument,+): AgentToolExecution {+ const extent = editedExtentSec(document);+ return failure(+ `The span ${requestedStartSec.toFixed(1)}–${requestedEndSec.toFixed(1)} s covers no clip, ` ++ `so no ${kind} was placed (it could never play). The edited timeline runs ` ++ `${extent.startSec.toFixed(1)}–${extent.endSec.toFixed(1)} s. ` ++ `Pick a span inside it, or place a clip there first.`,+ );+}++// The landing fields shared by every add / set result, so the model reads the+// same three things everywhere: what it asked for, what it got, and whether the+// two differ. `clamped` and `fragments` are omitted when there is nothing to+// say — an unconditional `clamped: false` on every result trains a reader to+// stop looking at it.+function landingReport(+ landing: Landing,+ requestedStartSec: number,+ requestedEndSec: number,+): Record<string, unknown> {+ const clamped =+ Math.abs(landing.startSec - requestedStartSec) > 0.001 ||+ Math.abs(landing.endSec - requestedEndSec) > 0.001;+ return {+ startSec: landing.startSec,+ endSec: landing.endSec,+ ids: landing.ids,+ ...(clamped ? { clamped: true, requestedStartSec, requestedEndSec } : {}),+ ...(landing.fragments > 1 ? { fragments: landing.fragments } : {}),+ };+}++function landingSuffix(+ landing: Landing,+ requestedStartSec: number,+ requestedEndSec: number,+): string {+ const parts: string[] = [];+ if (+ Math.abs(landing.startSec - requestedStartSec) > 0.001 ||+ Math.abs(landing.endSec - requestedEndSec) > 0.001+ ) {+ parts.push(+ `clamped from ${formatSec(requestedStartSec)} – ${formatSec(requestedEndSec)} to fit the clips`,+ );+ }+ if (landing.fragments > 1) parts.push(`split across ${landing.fragments} clips`);+ return parts.length ? ` (${parts.join(", ")})` : "";+}++/** Ids of every modifier in the document, all four families at once — the basis+ * for naming what a destructive edit took with it. */+function modifierIdsOf(document: AxcutDocument): string[] {+ const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};+ const speedRegions = (legacy.speedRegions as Array<{ id: string }> | undefined) ?? [];+ const cameraFullscreenRegions =+ (legacy.cameraFullscreenRegions as Array<{ id: string }> | undefined) ?? [];+ return [+ ...document.zoomRanges.map((r) => r.id),+ ...document.annotations.map((r) => r.id),+ ...speedRegions.map((r) => r.id),+ ...cameraFullscreenRegions.map((r) => r.id),+ ];+}++/** ponytail: `setClipRange` and `removeClip` both delete anchored modifiers as a+ * side effect (`setClipSourceRange` drops the pills the new window no longer+ * covers; `removeClip` takes everything anchored to the clip). Both used to+ * report only what was asked — "trimmed clip to 0:00.0 – 0:03.0" while a zoom+ * ceased to exist. Nothing in the result NAMED the casualty, which is what made+ * "the zoom is preserved" an easy thing for a model to say. */+function droppedByEdit(before: AxcutDocument, after: AxcutDocument) {+ const survivingModifiers = new Set(modifierIdsOf(after));+ const survivingTrims = new Set(after.timeline.trimRanges.map((t) => t.id));+ return {+ droppedModifierIds: modifierIdsOf(before).filter((id) => !survivingModifiers.has(id)),+ droppedTrimIds: before.timeline.trimRanges+ .map((t) => t.id)+ .filter((id) => !survivingTrims.has(id)),+ };+}+// Zod arg schemas — the SINGLE source of truth for every tool's arguments. The executor// below validates against them, and the deep-agent (LangChain) layer imports the same// objects to build its `tool()`s, so the two can never advertise a different shape than the@@ -125,10 +360,38 @@ export const replaceTimelineArgs = z.object({reason: z.string().default(""),});+/**+ * ponytail: `beforeClipId`, never an index.+ *+ * `moveClip` (document/timeline.ts) takes an `insertIndex` interpreted against+ * the array AFTER the moved clip is removed — V4Timeline does the `-1` by hand+ * at its call site, with a comment about it. That is a fine internal contract+ * and a terrible one to hand a language model: off by one is silent here, and+ * "put the demo first" would land it second. A neighbour's id has no such+ * ambiguity. Null (or omitted) means last, which is the only position no+ * existing clip can name.+ *+ * There is deliberately NO `reason` field: `reason` is the clip's label ("intro",+ * "demo"), the only thing in the snapshot that lets the model tell two clips+ * apart. A reorder must not be able to overwrite it.+ */+export const moveClipArgs = z.object({+ clipId: z.string().min(1),+ beforeClipId: z.string().min(1).nullish(),+});+export const getTranscriptArgs = z.object({assetId: z.string().min(1).optional(),});+// ponytail: an assetId, never a path. The model names a row of the document and+// the runtime resolves it to `asset.originalPath` behind the allow-list; letting+// it name a file instead would turn a read-only reporting tool into an arbitrary+// JSON reader on the user's disk.+export const getCursorTrackArgs = z.object({+ assetId: z.string().min(1).optional(),+});+// Effects (zoom / speed / annotation) are authored in *virtual* (edited-// timeline) seconds — the position on the ruler the user sees — unlike clips// and trims, which are source-time. The executor converts to the stored ms.@@ -201,312 +464,42 @@ export const removeClipArgs = z.object({clipId: z.string().min(1),});-export const AGENT_TOOL_SPECS: AgentToolSpec[] = [- {- name: "getCurrentDocument",- description:- "Read a compact snapshot of the current project: assets (with durations), timeline clips and trim ranges (source-time), and the zoom / speed / annotation effects (virtual, edited-timeline time). Call this before editing if the snapshot in the system prompt may be stale.",- parameters: { type: "object", properties: {}, additionalProperties: false },- mutating: false,- },- {- name: "getTranscript",- description:- "Read the transcript segments (speech and silence, with start/end seconds and text) for an asset. Omit assetId to read the primary asset's transcript.",- parameters: {- type: "object",- properties: {- assetId: { type: "string", description: "Asset id; defaults to the primary asset." },- },- additionalProperties: false,- },- mutating: false,- },- {- name: "addTrim",- description:- "Add a trim range: a cut of a span *inside* a clip that removes it from both playback and export without splitting the clip (a long clip with a big trim is cleaner than two clips). Times are seconds of the asset's source time. For shortening a clip's head/tail use setClipRange instead.",- parameters: {- type: "object",- properties: {- startSec: { type: "number", minimum: 0 },- endSec: { type: "number", minimum: 0 },- assetId: { type: "string", description: "Asset id; defaults to the primary asset." },- reason: { type: "string", description: "Why this range is being cut." },- },- required: ["startSec", "endSec"],- additionalProperties: false,- },- mutating: true,- },- {- name: "setTrim",- description: "Move or resize an existing trim range by id. Times are source-time seconds.",- parameters: {- type: "object",- properties: {- trimRangeId: { type: "string" },- startSec: { type: "number", minimum: 0 },- endSec: { type: "number", minimum: 0 },- },- required: ["trimRangeId", "startSec", "endSec"],- additionalProperties: false,- },- mutating: true,- },- {- name: "setClipRange",- description:- "Trim a clip: set its source in/out points (seconds). All clips are re-laid back-to-back afterwards, so downstream clips shift automatically.",- parameters: {- type: "object",- properties: {- clipId: { type: "string" },- sourceStartSec: { type: "number", minimum: 0 },- sourceEndSec: { type: "number", minimum: 0 },- },- required: ["clipId", "sourceStartSec", "sourceEndSec"],- additionalProperties: false,- },- mutating: true,- },- {- name: "replaceTimeline",- description:- "Replace the whole timeline with the given kept intervals of the primary asset's source time. Everything outside the intervals becomes a trim. Use for bulk edits like 'cut all silences'.",- parameters: {- type: "object",- properties: {- intervals: {- type: "array",- minItems: 1,- items: {- type: "object",- properties: {- startSec: { type: "number", minimum: 0 },- endSec: { type: "number", minimum: 0 },- },- required: ["startSec", "endSec"],- additionalProperties: false,- },- },- reason: { type: "string" },- },- required: ["intervals"],- additionalProperties: false,- },- mutating: true,- },- {- name: "addZoom",- description:- "Add a zoom-in effect over a span of the *edited timeline* (virtual seconds, as seen on the ruler — not source time). depth 1–6 maps to 1.0×–3.5× (default 3 ≈ 2.0×). focus is the zoom centre in 0–1 fractions of the frame (default centre). Use for 'zoom in on …' and the smart-zoom pass.",- parameters: {- type: "object",- properties: {- startSec: { type: "number", minimum: 0, description: "Virtual-timeline start (seconds)." },- endSec: { type: "number", minimum: 0, description: "Virtual-timeline end (seconds)." },- depth: {- type: "integer",- minimum: 1,- maximum: 6,- description: "Zoom level 1–6 (default 3).",- },- focus: {- type: "object",- description: "Zoom centre, fractions of the frame (default {cx:0.5,cy:0.5}).",- properties: {- cx: { type: "number", minimum: 0, maximum: 1 },- cy: { type: "number", minimum: 0, maximum: 1 },- },- required: ["cx", "cy"],- additionalProperties: false,- },- },- required: ["startSec", "endSec"],- additionalProperties: false,- },- mutating: true,- },- {- name: "setZoom",- description:- "Move, resize, or restyle an existing zoom by id. Times are virtual-timeline seconds. Only the fields you pass are changed.",- parameters: {- type: "object",- properties: {- zoomId: { type: "string" },- startSec: { type: "number", minimum: 0 },- endSec: { type: "number", minimum: 0 },- depth: { type: "integer", minimum: 1, maximum: 6 },- focus: {- type: "object",- properties: {- cx: { type: "number", minimum: 0, maximum: 1 },- cy: { type: "number", minimum: 0, maximum: 1 },- },- required: ["cx", "cy"],- additionalProperties: false,- },- },- required: ["zoomId"],- additionalProperties: false,- },- mutating: true,- },- {- name: "addSpeed",- description:- "Add a speed-change region over a span of the *edited timeline* (virtual seconds). speed > 1 fast-forwards, < 1 slows down (default 1.5×). Use to speed through slow stretches without cutting them.",- parameters: {- type: "object",- properties: {- startSec: { type: "number", minimum: 0, description: "Virtual-timeline start (seconds)." },- endSec: { type: "number", minimum: 0, description: "Virtual-timeline end (seconds)." },- speed: {- type: "number",- exclusiveMinimum: 0,- description: "Playback multiplier (default 1.5).",- },- },- required: ["startSec", "endSec"],- additionalProperties: false,- },- mutating: true,- },- {- name: "setSpeed",- description:- "Move, resize, or change the multiplier of an existing speed region by id. Times are virtual-timeline seconds. Only the fields you pass are changed.",- parameters: {- type: "object",- properties: {- speedId: { type: "string" },- startSec: { type: "number", minimum: 0 },- endSec: { type: "number", minimum: 0 },- speed: { type: "number", exclusiveMinimum: 0 },- },- required: ["speedId"],- additionalProperties: false,- },- mutating: true,- },- {- name: "addAnnotation",- description:- "Add a text annotation over a span of the *edited timeline* (virtual seconds). Position x/y are percentages of the frame (0–100, default centre). Use for callouts and labels.",- parameters: {- type: "object",- properties: {- startSec: { type: "number", minimum: 0, description: "Virtual-timeline start (seconds)." },- endSec: { type: "number", minimum: 0, description: "Virtual-timeline end (seconds)." },- text: { type: "string", description: "The annotation text." },- x: {- type: "number",- minimum: 0,- maximum: 100,- description: "Horizontal position % (default 50).",- },- y: {- type: "number",- minimum: 0,- maximum: 100,- description: "Vertical position % (default 50).",- },- },- required: ["startSec", "endSec", "text"],- additionalProperties: false,- },- mutating: true,- },- {- name: "setAnnotation",- description:- "Move, resize, or edit the text of an existing annotation by id. Times are virtual-timeline seconds. Only the fields you pass are changed.",- parameters: {- type: "object",- properties: {- annotationId: { type: "string" },- startSec: { type: "number", minimum: 0 },- endSec: { type: "number", minimum: 0 },- text: { type: "string" },- },- required: ["annotationId"],- additionalProperties: false,- },- mutating: true,- },- {- name: "addCameraFullscreen",- description:- "Add a camera-fullscreen region over a span of the *edited timeline* (virtual seconds): the webcam fills the frame for that span. Use for 'go fullscreen on the webcam here'.",- parameters: {- type: "object",- properties: {- startSec: { type: "number", minimum: 0, description: "Virtual-timeline start (seconds)." },- endSec: { type: "number", minimum: 0, description: "Virtual-timeline end (seconds)." },- },- required: ["startSec", "endSec"],- additionalProperties: false,- },- mutating: true,- },- {- name: "setCameraFullscreen",- description:- "Move or resize an existing camera-fullscreen region by id. Times are virtual-timeline seconds. Only the fields you pass are changed.",- parameters: {- type: "object",- properties: {- cameraFullscreenId: { type: "string" },- startSec: { type: "number", minimum: 0 },- endSec: { type: "number", minimum: 0 },- },- required: ["cameraFullscreenId"],- additionalProperties: false,- },- mutating: true,- },- {- name: "removeTrim",- description:- "Delete a trim range by id (the cut is un-done — that source span plays and exports again). This is the correct way to 'remove a trim' / 'un-cut' — never re-add a trim to undo one.",- parameters: {- type: "object",- properties: { trimRangeId: { type: "string" } },- required: ["trimRangeId"],- additionalProperties: false,- },- mutating: true,- },- {- name: "removeModifier",- description:- "Delete a modifier (zoom / speed / annotation / camera-fullscreen) by id. Resolves the kind from the id. This is the correct way to 'remove'/'delete' one of these — never neutralise it (span 0, speed 1×): that leaves it in the document. For a trim use removeTrim; for a clip use removeClip.",- parameters: {- type: "object",- properties: { id: { type: "string" } },- required: ["id"],- additionalProperties: false,- },- mutating: true,- },- {- name: "removeClip",- description:- "Delete a placed clip by id. The remaining clips are re-laid back-to-back to close the gap, and any zoom/speed/annotation anchored to the removed clip is dropped. Use only when the user explicitly asks to remove a clip (not to shorten one — that is setClipRange).",- parameters: {- type: "object",- properties: { clipId: { type: "string" } },- required: ["clipId"],- additionalProperties: false,- },- mutating: true,- },-];+/**+ * The tools that change the document. A LIST, not an inference: it gates the+ * checkpoint the chat-service takes before a write and the mutating/non-mutating+ * split the workbench scores its DSL axis on, and neither should quietly change+ * because someone edited a switch case.+ *+ * ponytail: this replaces `AGENT_TOOL_SPECS`, ~300 lines of JSON schema whose+ * own comment said "sent verbatim to the provider". It has not been sent+ * anywhere since the deep-agent landed: the model receives the zod schemas+ * built in `deep-agent/service.ts` and the prose in `TOOL_DESCRIPTIONS`. Two+ * descriptions of the same tools, only one of them reaching the model — and it+ * was the other one that humans read and kept up to date. The surviving+ * documentation duty is `TOOL_DESCRIPTIONS`; `service.test.ts` pins the three+ * remaining surfaces (descriptions, built tools, executor cases) to each other.+ */+export const MUTATING_TOOL_NAMES: ReadonlySet<string> = new Set([+ "addTrim",+ "setTrim",+ "setClipRange",+ "moveClip",+ "replaceTimeline",+ "addZoom",+ "setZoom",+ "addSpeed",+ "setSpeed",+ "addAnnotation",+ "setAnnotation",+ "addCameraFullscreen",+ "setCameraFullscreen",+ "removeTrim",+ "removeModifier",+ "removeClip",+]);export function isMutatingTool(name: string): boolean {- return AGENT_TOOL_SPECS.find((t) => t.name === name)?.mutating ?? false;+ return MUTATING_TOOL_NAMES.has(name);}function roundSec(ms: number): number {@@ -522,7 +515,25 @@ function roundSec(ms: number): number {// • trims — source-time cuts inside a clip (do not split the clip).// • effects — zoom / speed / annotation, in *virtual* (edited-timeline)// seconds, i.e. positions on the ruler after clips + trims are applied.-export function documentSnapshotForModel(document: AxcutDocument): Record<string, unknown> {+//+// ponytail: what a projection LEAVES OUT is a claim too, and two omissions here+// were being read by the model as facts about the project.+// • `cameraTrack` — the assets went out as `{id, label, durationSec}`, so two+// projects identical except for a linked webcam were literally+// indistinguishable. `addCameraFullscreen` answered ok either way, and the+// model placed a full-camera region on a project with no camera and+// reported it done. `hasCameraTrack` is the exact parity of `hasTranscript`+// below, which had already solved the same problem for the transcript.+// • the zoom's real strength — `depth` went out bare. It is an ORDINAL, so a+// reader turns "3" into "3×" while the frame renders 1.80×; and when a+// migrated v1.7 project carries `customScale`, `depth` is inert and nothing+// said so. `renderedScale` is `effectiveZoomScale`, the renderer's own+// function, so the number the model reports is the number the viewer sees.+export function documentSnapshotForModel(+ document: AxcutDocument,+ cursorTelemetry?: CursorTelemetryContext,+): Record<string, unknown> {+ const availability = cursorTelemetry?.availableByAssetId;const legacy = document.legacyEditor as Record<string, unknown> | null;const speedRegions =(legacy?.speedRegions as@@ -532,19 +543,56 @@ export function documentSnapshotForModel(document: AxcutDocument): Record<string(legacy?.cameraFullscreenRegions as| Array<{ id: string; startMs: number; endMs: number }>| undefined) ?? [];+ // The global Auto-Focus toggle OVERRIDES each region's own focusMode at+ // render (sceneDescription.ts:703) and the inspector disables the per-region+ // control while it is on. Reporting the stored mode would hand the model a+ // second thing to be confidently wrong about, so the projection reports the+ // EFFECTIVE mode and the flag that decides it.+ const autoFocusAll = legacy?.autoFocusAll === true;return {timeBaseNote:"clips and trims are in source-time seconds; zooms, speedRegions, annotations and cameraFullscreenRegions are in virtual (edited-timeline) seconds.",+ zoomNote:+ `renderedScale is what the viewer sees (depth is an ordinal, not a factor: ${ZOOM_DEPTH_LEGEND}). ` ++ "When a zoom carries customScale it wins over depth and depthIsOverridden is true — " ++ "a setZoom that only changes depth on such a zoom clears customScale so the depth takes effect.",project: { id: document.project.id, title: document.project.title },primaryAssetId: document.project.primaryAssetId ?? document.assets[0]?.id ?? null,+ autoFocusAll,+ hasAnyCamera: hasAnyClipWithCamera(document.assets, document.timeline.clips),+ cursorNote:+ "assets[].hasCursorTelemetry says whether recorded pointer telemetry exists for that " ++ "asset. true — call getCursorTrack to read the recorded pointer track. " ++ "false — this asset was checked and has none (imported footage, or a recording made " ++ "without the cursor recorder). null — it was NOT checked from here; say that, and do " ++ "not report it as the project having no cursor data.",assets: document.assets.map((a) => ({id: a.id,label: a.label,durationSec: a.durationSec ?? null,+ hasCameraTrack: a.cameraTrack != null,+ cameraVisible: a.cameraTrack?.visible ?? false,+ // Three-valued on purpose (see `CursorTelemetryContext`): `null` is+ // "not checked", and it must never render as `false`. The whole defect+ // was a runtime that could not look being read as a project that has+ // nothing — same field, same three states, one honest projection.+ //+ // `?? null`, not `?? false`: an asset MISSING from the map is one whose+ // probe threw. Defaulting that to `false` would put our failure back in+ // the answer as their fact, one layer lower down.+ hasCursorTelemetry: availability?.[a.id] ?? null,})),- clips: document.timeline.clips.map((c) => ({+ // ponytail: `index`, `reason` and `origin` are here because without them a+ // clip cannot be DESIGNATED. "Put the demo first" is unanswerable when the+ // only handles are `clip_1`/`clip_2` and two indistinguishable source+ // windows — the label the user sees lives in `reason`, and it was not being+ // sent. A reorder tool without this is a tool the model cannot aim.+ clips: document.timeline.clips.map((c, index) => ({id: c.id,+ index,assetId: c.assetId,+ reason: c.reason,+ origin: c.origin,sourceStartSec: c.sourceStartSec,sourceEndSec: c.sourceEndSec ?? null,timelineStartSec: c.timelineStartSec,@@ -562,7 +610,15 @@ export function documentSnapshotForModel(document: AxcutDocument): Record<stringstartSec: roundSec(z.startMs),endSec: roundSec(z.endMs),depth: z.depth,+ renderedScale: effectiveZoomScale(z),+ // Emitted only when set: an unconditional `customScale: null` on every+ // zoom of every snapshot is noise the reader learns to skip, which is+ // how the field would go unnoticed again.+ ...(z.customScale != null ? { customScale: z.customScale, depthIsOverridden: true } : {}),+ ...(z.rotationPreset ? { rotationPreset: z.rotationPreset } : {}),focus: z.focus,+ focusMode: autoFocusAll ? "auto" : (z.focusMode ?? "manual"),+ source: z.source ?? "manual",})),speedRegions: coalesceForAgent(speedRegions).map((s) => ({id: s.id,@@ -590,10 +646,108 @@ function failure(message: string): AgentToolExecution {return { ok: false, resultJson: JSON.stringify({ error: message }) };}+/** The clips as the model would have to name them, for an error about an id it+ * got wrong — a bare "Unknown clip: demo" leaves it guessing twice. */+function clipRoster(document: AxcutDocument): string {+ const clips = document.timeline.clips;+ if (clips.length === 0) return "The timeline has no clips.";+ return `The timeline is: ${clips.map((c) => `${c.id}${c.reason ? ` (${c.reason})` : ""}`).join(", ")}.`;+}++/**+ * The refusal the model gets for every write while `allowAgentEdits` is off.+ *+ * ponytail: it has to be ACTIONABLE, not merely negative. There is no+ * AbortSignal and no timeout anywhere on the product path, and the agent runs+ * at recursionLimit 1000: a bare "refused" invites a model to try the next+ * write tool, and the next, for as long as the provider will answer. So the+ * payload says what to do instead (state the edit, ask), that retrying is+ * pointless (every write is refused, not just this one), that claiming the edit+ * happened is forbidden, and where the user turns the setting back on. The+ * arguments are echoed back so the model can quote the exact edit it wanted+ * without a second round trip.+ *+ * The `{error}` envelope is the shape the workbench's wire oracle already+ * recognises as a failed tool result — a new one would read as a success.+ */+function consentRequired(name: string, args: unknown): AgentToolExecution {+ return {+ ok: false,+ resultJson: JSON.stringify({+ error:+ "Project edits are turned off for this project: the user asked to be consulted " ++ "before the timeline changes. Nothing was modified.",+ code: "consent_required",+ tool: name,+ requestedArgs: args,+ howToProceed:+ "Describe the exact edit you would make — the tool, the times, the ids — and ask the " ++ "user to confirm it. Do NOT retry this call and do NOT reach for another write tool: " ++ "every one of them is refused while the setting is off. Never say an edit was applied. " ++ "If they want you to go ahead, they can re-enable 'Project edits' in Settings → AI.",+ }),+ };+}++export interface AgentToolOptions {+ /**+ * `allowAgentEdits` from the LLM config, threaded down as an explicit+ * argument rather than read from a module global so this stays pure and+ * testable. Only `false` refuses; `undefined` is "allowed", which keeps the+ * three-argument call sites (and ~40 test assertions) working unchanged and+ * mirrors `config.allowAgentEdits !== false`.+ */+ editsAllowed?: boolean;+ /** Cursor telemetry resolved for THIS turn — see `CursorTelemetryContext`.+ * Absent means the runtime has no telemetry reader wired at all, which the+ * executor reports as "could not look", never as "there is none". */+ cursorTelemetry?: CursorTelemetryContext;+}++/**+ * What the runtime managed to find out about cursor telemetry this turn.+ *+ * ponytail: the three states are the whole point, and collapsing any two of them+ * is the defect. "There is no telemetry for this asset" is a fact about the+ * project. "I have no way to look" is a fact about me. The measured failure was+ * the model reporting the second as the first — it probed an empty sandbox and+ * concluded the recording had no pointer data — so the payloads keep them apart+ * and the prompt tells the model to keep them apart too.+ */+export interface CursorTelemetryContext {+ /** assetId → whether a sidecar exists. A MISSING key means "not checked",+ * which the snapshot reports as null, never false. */+ availableByAssetId?: Record<string, boolean>;+ /** The samples the async tool wrapper loaded before entering the executor.+ * `executeAgentTool` is synchronous — deliberately, it is the pure gate every+ * mutation passes through — so the IO happens outside and the verdict comes+ * in as data. */+ load?: CursorTelemetryLoad;+}++export type CursorTelemetryLoad =+ | { status: "ok"; assetId: string; samples: CursorTrackSample[]; durationSec?: number }+ /** We looked; this asset has no sidecar. */+ | { status: "no-sidecar"; assetId: string }+ /** We could NOT look: no reader wired, path refused, file unreadable. */+ | { status: "unavailable"; assetId: string | null; note?: string };++/** Resolves the asset a cursor/transcript question is about: the argument if it+ * names one, otherwise the project's primary asset. Shared so the async wrapper+ * in `deep-agent/service.ts` loads telemetry for exactly the asset the executor+ * will then report on. */+export function resolveCursorAssetId(+ document: AxcutDocument,+ assetId?: string | null,+): string | null {+ return assetId ?? document.project.primaryAssetId ?? document.assets[0]?.id ?? null;+}+export function executeAgentTool(document: AxcutDocument,name: string,rawArgs: string,+ options?: AgentToolOptions,): AgentToolExecution {let args: unknown = {};if (rawArgs.trim()) {@@ -604,9 +758,81 @@ export function executeAgentTool(}}+ // ponytail: THE guard for `allowAgentEdits`. It sits here, in front of the+ // switch, because this function is the single gate every document mutation+ // passes through — the two production callers (`documentTool` for the main+ // agent and, through it, any sub-agent) and the workbench alike. A guard in+ // the event sink could not work: the sink is an observer, called from inside+ // the tool body, and by the time it fires the edit has happened.+ //+ // Reads stay open on purpose. A model that cannot call getCurrentDocument or+ // getTranscript cannot describe the edit it is asking permission for, and+ // would answer "I have no tool for that" — false, and worse than silence.+ if (options?.editsAllowed === false && isMutatingTool(name)) {+ return consentRequired(name, args);+ }+switch (name) {case "getCurrentDocument": {- return { ok: true, resultJson: JSON.stringify(documentSnapshotForModel(document)) };+ return {+ ok: true,+ resultJson: JSON.stringify(documentSnapshotForModel(document, options?.cursorTelemetry)),+ };+ }++ case "getCursorTrack": {+ const parsed = getCursorTrackArgs.safeParse(args);+ if (!parsed.success) return failure(parsed.error.message);+ const assetId = resolveCursorAssetId(document, parsed.data.assetId);+ if (!assetId)+ return failure("Project has no assets — there is nothing to read telemetry for.");+ if (!document.assets.some((a) => a.id === assetId)) {+ return failure(`Unknown asset: ${assetId}`);+ }+ const load = options?.cursorTelemetry?.load;+ // ponytail: `ok: true` on all three branches, including the two that+ // return nothing. None of them is a failure of the CALL — the question+ // was answered, and the answer is "none" or "I could not look". Marking+ // them ok:false would push the model to retry a tool whose verdict will+ // not change, and there is no timeout anywhere on this path.+ if (!load || load.status === "unavailable") {+ return {+ ok: true,+ resultJson: JSON.stringify({+ available: false,+ reason: "unavailable",+ assetId,+ note:+ load?.note ??+ "Cursor telemetry cannot be read in this run — no reader is wired to this " ++ "runtime. This says nothing about whether the recording has any: report " ++ "the limit as yours, and do not tell the user the project has no cursor data.",+ }),+ };+ }+ if (load.status === "no-sidecar") {+ return {+ ok: true,+ resultJson: JSON.stringify({+ available: false,+ reason: "no-sidecar",+ assetId: load.assetId,+ note:+ "Checked: this asset has no cursor-telemetry sidecar. That normally means it " ++ "was imported rather than recorded with OpenScreen's cursor recorder. This is " ++ "a fact about the asset, not a limit of yours.",+ }),+ };+ }+ const asset = document.assets.find((a) => a.id === load.assetId);+ const track = buildCursorTrack({+ assetId: load.assetId,+ samples: load.samples,+ durationSec: load.durationSec ?? asset?.durationSec ?? 0,+ clips: document.timeline.clips,+ trimRanges: document.timeline.trimRanges,+ });+ return { ok: true, resultJson: JSON.stringify({ available: true, ...track }) };}case "getTranscript": {@@ -709,29 +935,114 @@ export function executeAgentTool(// trim removed. Hand-rolling it here is exactly what left this façade orphaning// stale pills the other two didn't.const next = setClipSourceRange(document, clipId, sourceStartSec, sourceEndSec);+ const dropped = droppedByEdit(document, next);+ const casualties = dropped.droppedModifierIds.length + dropped.droppedTrimIds.length;return {ok: true,document: next,- resultJson: JSON.stringify({ clipId, sourceStartSec, sourceEndSec }),- summary: `trimmed clip to ${formatSec(sourceStartSec)} – ${formatSec(sourceEndSec)}`,+ resultJson: JSON.stringify({ clipId, sourceStartSec, sourceEndSec, ...dropped }),+ summary:+ `trimmed clip to ${formatSec(sourceStartSec)} – ${formatSec(sourceEndSec)}` ++ (casualties > 0+ ? ` — dropped ${[...dropped.droppedModifierIds, ...dropped.droppedTrimIds].join(", ")}`+ : ""),+ };+ }++ case "moveClip": {+ const parsed = moveClipArgs.safeParse(args);+ if (!parsed.success) return failure(parsed.error.message);+ const { clipId } = parsed.data;+ const beforeClipId = parsed.data.beforeClipId ?? null;+ const clips = document.timeline.clips;+ const moving = clips.find((c) => c.id === clipId);+ if (!moving) return failure(`Unknown clip: ${clipId}. ${clipRoster(document)}`);+ if (beforeClipId === clipId) {+ return failure(+ `beforeClipId must name a different clip than clipId (both were ${clipId}); ` ++ `pass null to move it last.`,+ );+ }+ const remaining = clips.filter((c) => c.id !== clipId);+ let insertIndex = remaining.length;+ if (beforeClipId !== null) {+ insertIndex = remaining.findIndex((c) => c.id === beforeClipId);+ if (insertIndex < 0) {+ return failure(`Unknown clip: ${beforeClipId}. ${clipRoster(document)}`);+ }+ }+ let next: AxcutDocument;+ try {+ // The clip's OWN origin is passed back in: `moveClip` stamps whatever it+ // is given onto the clip, and a reorder is not a change of provenance —+ // a user's clip stays the user's. Empty reason keeps its label.+ next = moveClip(document, clipId, insertIndex, moving.origin, "");+ } catch (err) {+ return failure(err instanceof Error ? err.message : String(err));+ }+ const order = next.timeline.clips.map((c) => c.id);+ return {+ ok: true,+ document: next,+ resultJson: JSON.stringify({+ clipId,+ beforeClipId,+ clipOrder: order,+ // Nothing is destroyed by a reorder — say so, since the alternative+ // tool the model used to reach for destroyed plenty in silence.+ trimCount: next.timeline.trimRanges.length,+ ...droppedByEdit(document, next),+ }),+ summary:+ `moved ${clipId} ${beforeClipId ? `before ${beforeClipId}` : "to the end"} ` ++ `(order: ${order.join(" → ")})`,};}case "replaceTimeline": {const parsed = replaceTimelineArgs.safeParse(args);if (!parsed.success) return failure(parsed.error.message);- const userPlaced = document.timeline.clips.filter((c) => c.origin === "user");- if (userPlaced.length > 0) {+ // ponytail: refuse on the DAMAGE, not on the provenance. The old guard+ // tested `origin === "user"`, which missed every clip the agent itself had+ // placed — and disarmed itself, since a rebuild stamps its own output+ // `origin: "agent"`. `planTimelineReplacement` answers the question that+ // actually matters: what would this call cost?+ const plan = planTimelineReplacement(document, parsed.data.intervals);+ const objections: string[] = [];+ if (plan.reorderRequested) {+ objections.push(+ "- the intervals are not in ascending order, so this reads as a REORDER. " ++ "replaceTimeline sorts and merges its intervals, so the swap could not happen " ++ "at all: use moveClip (it preserves ids, trims and anchored effects).",+ );+ }+ if (plan.lostClipIds.length > 0) {+ objections.push(+ `- these clips would be merged away or dropped: ${plan.lostClipIds.join(", ")}. ` ++ "To shorten one, use setClipRange; to delete one, removeClip; to change the " ++ "order, moveClip; to cut a span inside one, addTrim.",+ );+ }+ if (plan.slidRegionIds.length > 0) {+ objections.push(+ `- these effects are anchored to those clips and would be re-anchored onto ` ++ `whatever footage moved under them: ${plan.slidRegionIds.join(", ")}.`,+ );+ }+ if (objections.length > 0) {return {ok: false,resultJson: JSON.stringify({error:- `Refused: ${userPlaced.length} user-placed clip(s) would be discarded. ` +- `For 'remove silences' / 'cut pauses' use addTrim (one call per silent range), ` +- `which preserves the placed clips and adds the cuts. ` +- `For 'trim this clip' use setClipRange. ` +- `Only call replaceTimeline when the user explicitly asks to rebuild the timeline from scratch ` +- `(after they have already cleared their placed clips).`,+ "Refused: replaceTimeline would destroy work you were not asked to touch. " ++ "Nothing was modified.\n" ++ `${objections.join("\n")}\n` ++ "replaceTimeline rebuilds the whole timeline and is only for an explicit " ++ "'start over with these intervals' on a timeline with nothing to lose.",+ code: "would_destroy",+ reorderRequested: plan.reorderRequested,+ lostClipIds: plan.lostClipIds,+ slidRegionIds: plan.slidRegionIds,}),};}@@ -748,8 +1059,20 @@ export function executeAgentTool(resultJson: JSON.stringify({clipCount: next.timeline.clips.length,trimCount: next.timeline.trimRanges.length,+ // What survived, by name. The old result reported two counts, and a+ // model reading `trimCount: 0` after a rebuild had nothing telling it+ // WHICH cut had ceased to exist — which is what made "the silence trim+ // is preserved" so easy to write.+ preservedClipIds: plan.slots.map((s) => s.keepClipId).filter((id): id is string => !!id),+ ...(plan.absorbedTrimIds.length ? { absorbedTrimIds: plan.absorbedTrimIds } : {}),+ ...(plan.clippedTrimIds.length ? { clippedTrimIds: plan.clippedTrimIds } : {}),}),- summary: `rebuilt timeline from ${kept} interval${kept === 1 ? "" : "s"} (${next.timeline.clips.length} clips, ${next.timeline.trimRanges.length} trims)`,+ summary:+ `rebuilt timeline from ${kept} interval${kept === 1 ? "" : "s"} ` ++ `(${next.timeline.clips.length} clips, ${next.timeline.trimRanges.length} trims)` ++ (plan.absorbedTrimIds.length+ ? ` — ${plan.absorbedTrimIds.join(", ")} now fall outside the kept spans`+ : ""),};}@@ -767,23 +1090,28 @@ export function executeAgentTool(focusMode: "manual" as const,source: "manual" as const,};+ const placed = anchorForAgent(zoom, document, "zoom");+ const landing = landingOf(placed, document);+ if (!landing.anchored) return coversNoClip("zoom", startMs / 1000, endMs / 1000, document);const next: AxcutDocument = {...document,- zoomRanges: [- ...document.zoomRanges,- ...anchorForAgent(zoom, document, "zoom"),- ] as AxcutDocument["zoomRanges"],+ zoomRanges: [...document.zoomRanges, ...placed] as AxcutDocument["zoomRanges"],};return {ok: true,document: next,resultJson: JSON.stringify({- zoomId: zoom.id,- startSec: startMs / 1000,- endSec: endMs / 1000,+ zoomId: landing.ids[0],depth: zoom.depth,+ // The depth alone is an ordinal; reported on its own it is what the+ // model turns into "3×" for a frame that renders 1.80×.+ renderedScale: effectiveZoomScale(zoom),+ ...landingReport(landing, startMs / 1000, endMs / 1000),}),- summary: `added zoom ${formatSec(startMs / 1000)} – ${formatSec(endMs / 1000)}`,+ summary:+ `added zoom ${formatSec(landing.startSec)} – ${formatSec(landing.endSec)} ` ++ `at ${effectiveZoomScale(zoom).toFixed(2)}×` ++ landingSuffix(landing, startMs / 1000, endMs / 1000),};}@@ -795,34 +1123,61 @@ export function executeAgentTool(if (!existing) return failure(`Unknown zoom: ${zoomId}`);const { startMs, endMs } = resolveSpanMs(existing, parsed.data.startSec, parsed.data.endSec);const zoomPill = new Set(resolvePillIds(document.zoomRanges, zoomId));- const next: AxcutDocument = {- ...document,- zoomRanges: replacePillSpan(- // payload edits first, applied to every region under the pill…- document.zoomRanges.map((z) =>- zoomPill.has(z.id)- ? {- ...z,- ...(parsed.data.depth !== undefined- ? { depth: parsed.data.depth as 1 | 2 | 3 | 4 | 5 | 6 }- : {}),- ...(parsed.data.focus ? { focus: parsed.data.focus } : {}),- }- : z,- ),- // …then the span: clamped against different-property pills, then re-ventilated.- zoomId,- startMs,- endMs,- document.timeline.clips,- () => createId("zoom"),- ) as AxcutDocument["zoomRanges"],- };+ // ponytail: a depth write CLEARS customScale, and that is the whole+ // point. `effectiveZoomScale` returns customScale when it is set, so on a+ // migrated v1.7 zoom (`migrate.ts:185` keeps both fields) a `setZoom+ // {depth: 6}` used to store the 6, answer ok, and leave the picture at+ // 1.10× forever — a write that could not do what every layer involved+ // believed it did. Dropping the override is destructive of a fine-tuned+ // value, so it happens only on an explicit depth write (which IS a+ // request to change the strength) and is named in the result and the+ // summary rather than done quietly.+ const clearsCustomScale =+ parsed.data.depth !== undefined &&+ document.zoomRanges.some((z) => zoomPill.has(z.id) && z.customScale != null);+ const rebuiltZooms = replacePillSpan(+ // payload edits first, applied to every region under the pill…+ document.zoomRanges.map((z) => {+ if (!zoomPill.has(z.id)) return z;+ const { customScale, ...rest } = z;+ return {+ ...(clearsCustomScale ? rest : z),+ ...(parsed.data.depth !== undefined+ ? { depth: parsed.data.depth as 1 | 2 | 3 | 4 | 5 | 6 }+ : {}),+ ...(parsed.data.focus ? { focus: parsed.data.focus } : {}),+ };+ }),+ // …then the span: clamped against different-property pills, then re-ventilated.+ zoomId,+ startMs,+ endMs,+ document.timeline.clips,+ () => createId("zoom"),+ ) as AxcutDocument["zoomRanges"];+ const landing = landingAfterPillEdit(document.zoomRanges, rebuiltZooms, zoomPill, document);+ if (!landing.anchored) return coversNoClip("zoom", startMs / 1000, endMs / 1000, document);+ const next: AxcutDocument = { ...document, zoomRanges: rebuiltZooms };+ // Read back off the document, not off the request: the pill may have been+ // re-ventilated, and `renderedScale` is the only number the viewer sees.+ const landed = new Set(landing.ids);+ const strength = rebuiltZooms.find((z) => landed.has(z.id));return {ok: true,document: next,- resultJson: JSON.stringify({ zoomId, startSec: startMs / 1000, endSec: endMs / 1000 }),- summary: `updated zoom ${formatSec(startMs / 1000)} – ${formatSec(endMs / 1000)}`,+ resultJson: JSON.stringify({+ zoomId: landing.ids[0] ?? zoomId,+ ...(strength+ ? { depth: strength.depth, renderedScale: effectiveZoomScale(strength) }+ : {}),+ ...(clearsCustomScale ? { clearedCustomScale: true } : {}),+ ...landingReport(landing, startMs / 1000, endMs / 1000),+ }),+ summary:+ `updated zoom ${formatSec(landing.startSec)} – ${formatSec(landing.endSec)}` ++ (strength ? ` at ${effectiveZoomScale(strength).toFixed(2)}×` : "") ++ (clearsCustomScale ? " (cleared its custom scale so the depth applies)" : "") ++ landingSuffix(landing, startMs / 1000, endMs / 1000),};}@@ -834,23 +1189,26 @@ export function executeAgentTool(const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};const prev = (legacy.speedRegions as unknown[] | undefined) ?? [];const region = { id: createId("speed"), startMs, endMs, speed: parsed.data.speed };+ const placed = anchorForAgent(region, document, "speed");+ const landing = landingOf(placed, document);+ if (!landing.anchored) {+ return coversNoClip("speed region", startMs / 1000, endMs / 1000, document);+ }const next: AxcutDocument = {...document,- legacyEditor: {- ...legacy,- speedRegions: [...prev, ...anchorForAgent(region, document, "speed")],- },+ legacyEditor: { ...legacy, speedRegions: [...prev, ...placed] },};return {ok: true,document: next,resultJson: JSON.stringify({- speedId: region.id,- startSec: startMs / 1000,- endSec: endMs / 1000,+ speedId: landing.ids[0],speed: region.speed,+ ...landingReport(landing, startMs / 1000, endMs / 1000),}),- summary: `added ${parsed.data.speed}× speed ${formatSec(startMs / 1000)} – ${formatSec(endMs / 1000)}`,+ summary:+ `added ${parsed.data.speed}× speed ${formatSec(landing.startSec)} – ${formatSec(landing.endSec)}` ++ landingSuffix(landing, startMs / 1000, endMs / 1000),};}@@ -867,30 +1225,33 @@ export function executeAgentTool(if (!existing) return failure(`Unknown speed region: ${parsed.data.speedId}`);const { startMs, endMs } = resolveSpanMs(existing, parsed.data.startSec, parsed.data.endSec);const speed = parsed.data.speed ?? existing.speed;+ const rebuiltSpeeds = replacePillSpan(+ prev.map((s) => (speedPill.has(s.id) ? { ...s, speed } : s)),+ parsed.data.speedId,+ startMs,+ endMs,+ document.timeline.clips,+ () => createId("speed"),+ );+ const landing = landingAfterPillEdit(prev, rebuiltSpeeds, speedPill, document);+ if (!landing.anchored) {+ return coversNoClip("speed region", startMs / 1000, endMs / 1000, document);+ }const next: AxcutDocument = {...document,- legacyEditor: {- ...legacy,- speedRegions: replacePillSpan(- prev.map((s) => (speedPill.has(s.id) ? { ...s, speed } : s)),- parsed.data.speedId,- startMs,- endMs,- document.timeline.clips,- () => createId("speed"),- ),- },+ legacyEditor: { ...legacy, speedRegions: rebuiltSpeeds },};return {ok: true,document: next,resultJson: JSON.stringify({- speedId: parsed.data.speedId,- startSec: startMs / 1000,- endSec: endMs / 1000,+ speedId: landing.ids[0] ?? parsed.data.speedId,speed,+ ...landingReport(landing, startMs / 1000, endMs / 1000),}),- summary: `updated speed to ${speed}×`,+ summary:+ `updated speed to ${speed}× over ${formatSec(landing.startSec)} – ${formatSec(landing.endSec)}` ++ landingSuffix(landing, startMs / 1000, endMs / 1000),};}@@ -920,22 +1281,25 @@ export function executeAgentTool(},zIndex: document.annotations.length + 1,};+ const placed = anchorForAgent(ann, document, "ann");+ const landing = landingOf(placed, document);+ if (!landing.anchored) {+ return coversNoClip("annotation", startMs / 1000, endMs / 1000, document);+ }const next: AxcutDocument = {...document,- annotations: [- ...document.annotations,- ...anchorForAgent(ann, document, "ann"),- ] as AxcutDocument["annotations"],+ annotations: [...document.annotations, ...placed] as AxcutDocument["annotations"],};return {ok: true,document: next,resultJson: JSON.stringify({- annotationId: ann.id,- startSec: startMs / 1000,- endSec: endMs / 1000,+ annotationId: landing.ids[0],+ ...landingReport(landing, startMs / 1000, endMs / 1000),}),- summary: `added annotation "${parsed.data.text.slice(0, 24)}"`,+ summary:+ `added annotation "${parsed.data.text.slice(0, 24)}" ${formatSec(landing.startSec)} – ${formatSec(landing.endSec)}` ++ landingSuffix(landing, startMs / 1000, endMs / 1000),};}@@ -947,35 +1311,43 @@ export function executeAgentTool(const annPill = new Set(resolvePillIds(document.annotations, annotationId));if (!existing) return failure(`Unknown annotation: ${annotationId}`);const { startMs, endMs } = resolveSpanMs(existing, parsed.data.startSec, parsed.data.endSec);- const next: AxcutDocument = {- ...document,- annotations: replacePillSpan(- document.annotations.map((a) =>- annPill.has(a.id)- ? {- ...a,- ...(parsed.data.text !== undefined- ? { content: parsed.data.text, textContent: parsed.data.text }- : {}),- }- : a,- ),- annotationId,- startMs,- endMs,- document.timeline.clips,- () => createId("ann"),+ const rebuiltAnnotations = replacePillSpan(+ document.annotations.map((a) =>+ annPill.has(a.id)+ ? {+ ...a,+ ...(parsed.data.text !== undefined+ ? { content: parsed.data.text, textContent: parsed.data.text }+ : {}),+ }+ : a,),- };+ annotationId,+ startMs,+ endMs,+ document.timeline.clips,+ () => createId("ann"),+ );+ const landing = landingAfterPillEdit(+ document.annotations,+ rebuiltAnnotations,+ annPill,+ document,+ );+ if (!landing.anchored) {+ return coversNoClip("annotation", startMs / 1000, endMs / 1000, document);+ }+ const next: AxcutDocument = { ...document, annotations: rebuiltAnnotations };return {ok: true,document: next,resultJson: JSON.stringify({- annotationId,- startSec: startMs / 1000,- endSec: endMs / 1000,+ annotationId: landing.ids[0] ?? annotationId,+ ...landingReport(landing, startMs / 1000, endMs / 1000),}),- summary: `updated annotation ${formatSec(startMs / 1000)} – ${formatSec(endMs / 1000)}`,+ summary:+ `updated annotation ${formatSec(landing.startSec)} – ${formatSec(landing.endSec)}` ++ landingSuffix(landing, startMs / 1000, endMs / 1000),};}@@ -987,22 +1359,27 @@ export function executeAgentTool(const legacy = (document.legacyEditor as Record<string, unknown>) ?? {};const prev = (legacy.cameraFullscreenRegions as unknown[] | undefined) ?? [];const region = { id: createId("camfull"), startMs, endMs };+ const placed = anchorForAgent(region, document, "camfull");+ const landing = landingOf(placed, document);+ if (!landing.anchored) {+ return coversNoClip("full-camera region", startMs / 1000, endMs / 1000, document);+ }+ const blind = noCameraUnderSpan(document, landing.startSec, landing.endSec);+ if (blind) return blind;const next: AxcutDocument = {...document,- legacyEditor: {- ...legacy,- cameraFullscreenRegions: [...prev, ...anchorForAgent(region, document, "camfull")],- },+ legacyEditor: { ...legacy, cameraFullscreenRegions: [...prev, ...placed] },};return {ok: true,document: next,resultJson: JSON.stringify({- cameraFullscreenId: region.id,- startSec: startMs / 1000,- endSec: endMs / 1000,+ cameraFullscreenId: landing.ids[0],+ ...landingReport(landing, startMs / 1000, endMs / 1000),}),- summary: `full-camera ${formatSec(startMs / 1000)} – ${formatSec(endMs / 1000)}`,+ summary:+ `full-camera ${formatSec(landing.startSec)} – ${formatSec(landing.endSec)}` ++ landingSuffix(landing, startMs / 1000, endMs / 1000),};}@@ -1018,29 +1395,35 @@ export function executeAgentTool(if (!existing)return failure(`Unknown full-camera region: ${parsed.data.cameraFullscreenId}`);const { startMs, endMs } = resolveSpanMs(existing, parsed.data.startSec, parsed.data.endSec);+ const camPill = new Set(resolvePillIds(prev, parsed.data.cameraFullscreenId));+ const rebuiltCamera = replacePillSpan(+ prev,+ parsed.data.cameraFullscreenId,+ startMs,+ endMs,+ document.timeline.clips,+ () => createId("camfull"),+ );+ const landing = landingAfterPillEdit(prev, rebuiltCamera, camPill, document);+ if (!landing.anchored) {+ return coversNoClip("full-camera region", startMs / 1000, endMs / 1000, document);+ }+ const blindMove = noCameraUnderSpan(document, landing.startSec, landing.endSec);+ if (blindMove) return blindMove;const next: AxcutDocument = {...document,- legacyEditor: {- ...legacy,- cameraFullscreenRegions: replacePillSpan(- prev,- parsed.data.cameraFullscreenId,- startMs,- endMs,- document.timeline.clips,- () => createId("camfull"),- ),- },+ legacyEditor: { ...legacy, cameraFullscreenRegions: rebuiltCamera },};return {ok: true,document: next,resultJson: JSON.stringify({- cameraFullscreenId: parsed.data.cameraFullscreenId,- startSec: startMs / 1000,- endSec: endMs / 1000,+ cameraFullscreenId: landing.ids[0] ?? parsed.data.cameraFullscreenId,+ ...landingReport(landing, startMs / 1000, endMs / 1000),}),- summary: `moved full-camera to ${formatSec(startMs / 1000)} – ${formatSec(endMs / 1000)}`,+ summary:+ `moved full-camera to ${formatSec(landing.startSec)} – ${formatSec(landing.endSec)}` ++ landingSuffix(landing, startMs / 1000, endMs / 1000),};}@@ -1096,11 +1479,21 @@ export function executeAgentTool(return failure(`Unknown clip: ${clipId}`);}const next = removeClip(document, clipId);+ const dropped = droppedByEdit(document, next);+ const casualties = dropped.droppedModifierIds.length + dropped.droppedTrimIds.length;return {ok: true,document: next,- resultJson: JSON.stringify({ removed: clipId, clipCount: next.timeline.clips.length }),- summary: `removed clip ${clipId}`,+ resultJson: JSON.stringify({+ removed: clipId,+ clipCount: next.timeline.clips.length,+ ...dropped,+ }),+ summary:+ `removed clip ${clipId}` ++ (casualties > 0+ ? ` — dropped ${[...dropped.droppedModifierIds, ...dropped.droppedTrimIds].join(", ")}`+ : ""),};}diff --git a/electron/ai-edition/chat-service.toolloop.test.ts b/electron/ai-edition/chat-service.toolloop.test.tsindex 543dadc1f..3982c901e 100644--- a/electron/ai-edition/chat-service.toolloop.test.ts+++ b/electron/ai-edition/chat-service.toolloop.test.ts@@ -78,6 +78,7 @@ interface CapturedInvoke {model: { provider: string; model: string };history: Array<{ role: "user" | "assistant" | "system"; content: string }>;userMessage: string;+ editsAllowed?: boolean;};}@@ -322,3 +323,72 @@ describe("runChat tool loop", () => {void streamAgent;});});++// ── D-CONSENT ───────────────────────────────────────────────────────────────+//+// `allowAgentEdits` is offered in Settings as "Project edits — when off, the+// agent must ask before changing the timeline". `runChat` computed+// `const editsAllowed = config.allowAgentEdits !== false;` and then, twenty+// lines later, `void editsAllowed;`. That was every use of it: it reached+// neither the tools nor the prompt, and `git log -S` shows it never had.+describe("allowAgentEdits reaches the agent", () => {+ it("passes the flag down when the setting is off", async () => {+ const session = createSession("proj_consent_off");+ await runChat(+ "proj_consent_off",+ session.id,+ "cut the silences",+ stubConfig({ allowAgentEdits: false }),+ fixtureDocument(),+ );+ expect(fixture.captured.at(-1)?.args.editsAllowed).toBe(false);+ });++ it("passes it as allowed when the setting is on, or absent", async () => {+ for (const config of [stubConfig(), stubConfig({ allowAgentEdits: true })]) {+ const session = createSession("proj_consent_on");+ await runChat("proj_consent_on", session.id, "cut it", config, fixtureDocument());+ expect(fixture.captured.at(-1)?.args.editsAllowed).toBe(true);+ }+ });++ it("withholds the document even if an agent somehow reports a mutation", async () => {+ // Belt and braces: this returned document is the only path to disk. If the+ // executor's guard were ever bypassed — a tool built outside the factory,+ // a future sub-agent — the setting would still hold here.+ invokeMock.mockReset();+ invokeMock.mockImplementation(async (args) => ({+ text: "I went ahead and cut them.",+ document: args.document,+ mutated: true,+ }));+ const session = createSession("proj_consent_belt");+ const result = await runChat(+ "proj_consent_belt",+ session.id,+ "cut the silences",+ stubConfig({ allowAgentEdits: false }),+ fixtureDocument(),+ );+ expect(result.success).toBe(true);+ expect(result.document).toBeUndefined();+ });++ it("returns the document normally when edits are allowed", async () => {+ invokeMock.mockReset();+ invokeMock.mockImplementation(async (args) => ({+ text: "Cut them.",+ document: args.document,+ mutated: true,+ }));+ const session = createSession("proj_consent_allowed");+ const result = await runChat(+ "proj_consent_allowed",+ session.id,+ "cut the silences",+ stubConfig(),+ fixtureDocument(),+ );+ expect(result.document).toBeDefined();+ });+});diff --git a/electron/ai-edition/chat-service.ts b/electron/ai-edition/chat-service.tsindex 3e9c3e5d7..180f8e0bc 100644--- a/electron/ai-edition/chat-service.ts+++ b/electron/ai-edition/chat-service.ts@@ -29,6 +29,7 @@ import {DEFAULT_BUDGET_TOKENS,shouldCompact,} from "./chat-compaction";+import type { CursorTelemetryReader } from "./deep-agent/service";import type { DocumentService } from "./document-service";import type { LlmConfigStore } from "./llm-config-store";import { PROVIDER_DEFINITIONS } from "./provider-registry";@@ -217,6 +218,12 @@ export interface ChatEventSink {error?: (message: string) => void;}+export interface ChatRunEnv {+ /** Reads recorded cursor telemetry for an asset. Built in `electron/ipc/+ * handlers.ts`, where the path allow-list lives. */+ cursor?: CursorTelemetryReader;+}+// ponytail: zero-config noop for sink callbacks that the caller did not provide.const noop = () => undefined;@@ -236,6 +243,11 @@ export async function runChat(llmConfig: LlmConfigStore,documentInput?: unknown,sink: ChatEventSink = {},+ /** Runtime capabilities the pure chat path cannot build for itself. Optional+ * and last so the three existing call sites are unchanged — but note that a+ * production caller which forgets to pass `cursor` gets an agent that answers+ * "I could not look" every time, which is honest and unhelpful. */+ env: ChatRunEnv = {},): Promise<AiEditionChatResult> {const emit: Required<ChatEventSink> = { ...NOOP_SINK, ...sink };const config = llmConfig.getConfig();@@ -332,7 +344,6 @@ export async function runChat(thinking: (delta: string) => emit.thinking(delta),toolStart: (name: string, args: unknown) => {emit.toolStart(name, args);- void editsAllowed;},toolEnd: (name: string, ok: boolean, summary?: string) => {emit.toolEnd(name, ok, summary);@@ -357,6 +368,8 @@ export async function runChat(history,userMessage: message,sink: agentSink,+ editsAllowed,+ cursor: env.cursor,});if (!result.text) {@@ -383,7 +396,12 @@ export async function runChat(return {success: true,assistantMessage,- document: result.mutated ? result.document : undefined,+ // ponytail: belt and braces on `editsAllowed`. This returned document is+ // the ONLY path to disk (LeftPanel → applyAgentDocument → saveDocument),+ // so it is where a write that somehow escaped the executor's guard would+ // still land. Cheap, and it makes the setting's guarantee structural+ // rather than dependent on one predicate holding everywhere.+ document: result.mutated && editsAllowed ? result.document : undefined,toolCalls: appliedToolCalls.length ? appliedToolCalls : undefined,userMessageCheckpointId: userMessage.checkpointId ?? undefined,};diff --git a/electron/ai-edition/deep-agent/service.test.ts b/electron/ai-edition/deep-agent/service.test.tsnew file mode 100644index 000000000..5753e0e8a--- /dev/null+++ b/electron/ai-edition/deep-agent/service.test.ts@@ -0,0 +1,565 @@+// ponytail: the agent's SURFACE and the honesty of its event sink — the two+// things that were wrong in a way no unit test could see, because both were+// decided by a dependency rather than by this repo.+//+// D-FS: `createDeepAgent` stacked a filesystem middleware, a todo middleware+// and a sub-agent middleware unconditionally, so the model was handed 25 tools+// instead of our 17 and a system message of ~8 700 characters instead of ours,+// promising a filesystem backed by an EMPTY in-memory store. Asked what cursor+// data the project holds, it ran `ls {"path":"/"}`, found nothing, and said so+// about the project. Counting the tools here is the cheapest tripwire for any+// dependency that starts injecting again.+//+// D-HONEST: every write was announced twice — once by the tool body with the+// executor's real verdict, once by the stream loop with `ok` hard-coded true —+// and read tools were announced only by the lying emission.++import { ChatAnthropic } from "@langchain/anthropic";+import { ChatOpenAI } from "@langchain/openai";+import { describe, expect, it } from "vitest";+import {+ type AxcutDocument,+ createEmptyDocument,+ documentSchema,+} from "../../../src/lib/ai-edition/schema";+import {+ ZOOM_DEPTH_LEGEND,+ ZOOM_DEPTH_SCALES,+} from "../../../src/lib/ai-edition/timeline/zoom-scale";+import { executeAgentTool, isMutatingTool } from "../agent-tools";+import {+ anthropicCachingMiddleware,+ buildSystemPrompt,+ buildTools,+ type OpenScreenAgentSink,+ SYSTEM_PROMPT,+ TOOL_DESCRIPTIONS,+} from "./service";++const OPENSCREEN_TOOLS = [+ "getCurrentDocument",+ "getTranscript",+ "getCursorTrack",+ "addTrim",+ "setTrim",+ "setClipRange",+ "moveClip",+ "replaceTimeline",+ "addZoom",+ "setZoom",+ "addSpeed",+ "setSpeed",+ "addAnnotation",+ "setAnnotation",+ "addCameraFullscreen",+ "setCameraFullscreen",+ "removeTrim",+ "removeModifier",+ "removeClip",+];++/** The tools `createDeepAgent` used to add. None of them may ever be built here+ * again: `execute` is in the middleware's list too and only disappeared at+ * runtime because the default backend is not a sandbox, so it is listed as+ * well — a sandbox backend would have made it a 26th tool. */+const PHANTOM_TOOLS = [+ "ls",+ "read_file",+ "write_file",+ "edit_file",+ "glob",+ "grep",+ "execute",+ "write_todos",+ "task",+];++/** Valid arguments for every tool, chosen so the executor's verdict is split+ * across the table: some succeed, some are refused for an unknown id, and+ * `replaceTimeline` is refused for the user-placed clips. A table where every+ * call succeeds would not notice a sink that reports `ok: true` always. */+const ARGS: Record<string, unknown> = {+ getCurrentDocument: {},+ getTranscript: {},+ getCursorTrack: {},+ addTrim: { startSec: 1, endSec: 2 },+ setTrim: { trimRangeId: "trim_1", startSec: 1, endSec: 2 },+ setClipRange: { clipId: "clip_1", sourceStartSec: 0, sourceEndSec: 10 },+ moveClip: { clipId: "clip_1", beforeClipId: null },+ replaceTimeline: { intervals: [{ startSec: 0, endSec: 10 }] },+ addZoom: { startSec: 1, endSec: 2 },+ setZoom: { zoomId: "zoom_nope" },+ addSpeed: { startSec: 1, endSec: 2 },+ setSpeed: { speedId: "speed_nope" },+ addAnnotation: { startSec: 1, endSec: 2, text: "hi" },+ setAnnotation: { annotationId: "ann_nope" },+ addCameraFullscreen: { startSec: 1, endSec: 2 },+ setCameraFullscreen: { cameraFullscreenId: "cam_nope" },+ removeTrim: { trimRangeId: "trim_1" },+ removeModifier: { id: "nope" },+ removeClip: { clipId: "clip_1" },+};++function fixtureDocument(): AxcutDocument {+ const base = createEmptyDocument({ title: "Test", projectId: "proj_1" });+ return documentSchema.parse({+ ...base,+ project: { ...base.project, primaryAssetId: "asset_1" },+ assets: [+ {+ id: "asset_1",+ kind: "video",+ label: "Recording",+ originalPath: "/tmp/rec.mp4",+ durationSec: 30,+ },+ ],+ transcripts: [+ {+ assetId: "asset_1",+ language: "en",+ segments: [+ { id: "seg_1", kind: "speech", startSec: 0, endSec: 5, text: "Hello", wordIds: [] },+ ],+ words: [],+ },+ ],+ timeline: {+ ...base.timeline,+ clips: [+ {+ id: "clip_1",+ assetId: "asset_1",+ sourceStartSec: 0,+ sourceEndSec: 30,+ timelineStartSec: 0,+ timelineEndSec: 30,+ wordRefs: [],+ origin: "user",+ reason: "",+ },+ ],+ trimRanges: [+ { id: "trim_1", assetId: "asset_1", startSec: 10, endSec: 12, reason: "", origin: "user" },+ ],+ },+ });+}++interface SinkEvent {+ kind: "toolStart" | "toolEnd";+ name: string;+ ok?: boolean;+ summary?: string;+}++function recordingSink(): { sink: OpenScreenAgentSink; events: SinkEvent[] } {+ const events: SinkEvent[] = [];+ return {+ events,+ sink: {+ // Only the tool channel is under test here; the text/thinking/error+ // channels are recorded by the L1 harness instead.+ text: () => undefined,+ thinking: () => undefined,+ toolStart: (name) => events.push({ kind: "toolStart", name }),+ toolEnd: (name, ok, summary) => events.push({ kind: "toolEnd", name, ok, summary }),+ error: () => undefined,+ },+ };+}++function toolsFor(document: AxcutDocument) {+ const { sink, events } = recordingSink();+ const holder = { current: document };+ return { tools: buildTools(holder, sink), events, holder };+}++describe("the tool surface handed to the model", () => {+ it("is exactly OpenScreen's 19 tools", () => {+ const { tools } = toolsFor(fixtureDocument());+ expect(tools.map((t) => t.name)).toEqual(OPENSCREEN_TOOLS);+ });++ it("carries none of the tools deepagents used to inject", () => {+ const names = new Set(toolsFor(fixtureDocument()).tools.map((t) => t.name));+ for (const phantom of PHANTOM_TOOLS) expect(names.has(phantom)).toBe(false);+ });++ it("describes every tool it builds, and builds every tool it describes", () => {+ // Two surfaces that must not drift: a tool with no description reaches the+ // model as a bare name, and a description with no tool is dead prose.+ const names = toolsFor(fixtureDocument()).tools.map((t) => t.name);+ expect(Object.keys(TOOL_DESCRIPTIONS).sort()).toEqual([...names].sort());+ for (const tool of toolsFor(fixtureDocument()).tools) {+ expect(tool.description, `${tool.name} has no description`).toBeTruthy();+ }+ });++ it("promises no filesystem in the system prompt", () => {+ // The middleware prompt that came with the phantom tools said "You have+ // access to a filesystem which you can interact with using these tools.+ // All file paths must start with a /". Ours must never say anything of+ // the sort — a prompt promising tools that are gone is worse than the+ // tools were.+ expect(SYSTEM_PROMPT).not.toMatch(/file ?system|file path|write_todos|sub-?agent/i);+ });+});++describe("prompt caching on the Anthropic-wire providers", () => {+ // `createDeepAgent` added this middleware for us. Dropping it with the rest+ // of deepagents would have made every Anthropic and MiniMax turn re-pay for+ // the whole prompt — a cost and latency regression invisible to every+ // offline test, which all run on the OpenAI-compatible path.+ it("is attached for ChatAnthropic", () => {+ const model = new ChatAnthropic({ apiKey: "test-not-a-real-key", model: "claude-sonnet-4-6" });+ expect(anthropicCachingMiddleware(model)).toHaveLength(1);+ });++ it("covers MiniMax, which rides ChatAnthropic because its wire format is Anthropic's", () => {+ const model = new ChatAnthropic({+ apiKey: "test-not-a-real-key",+ model: "MiniMax-M2",+ anthropicApiUrl: "https://api.minimax.io/anthropic",+ });+ expect(anthropicCachingMiddleware(model)).toHaveLength(1);+ });++ it("is absent everywhere else", () => {+ const model = new ChatOpenAI({ apiKey: "test-not-a-real-key", model: "gpt-4o" });+ expect(anthropicCachingMiddleware(model)).toEqual([]);+ });+});++describe("the sink announces each call exactly once, with the real verdict", () => {+ for (const name of OPENSCREEN_TOOLS) {+ it(`${name}: one start, one end, ok from the executor`, async () => {+ const document = fixtureDocument();+ const args = ARGS[name];+ // The reference verdict, computed by the executor the tool wraps.+ const expected = executeAgentTool(document, name, JSON.stringify(args));++ const { tools, events } = toolsFor(document);+ const tool = tools.find((t) => t.name === name);+ if (!tool) throw new Error(`${name} is not built`);+ await tool.invoke(args as never);++ expect(events.map((e) => e.kind)).toEqual(["toolStart", "toolEnd"]);+ expect(events[0].name).toBe(name);+ expect(events[1].name).toBe(name);+ expect(events[1].ok).toBe(expected.ok);+ expect(events[1].summary).toBe(expected.summary);+ });+ }++ it("covers both verdicts, so a sink hard-coding ok:true could not pass", () => {+ const document = fixtureDocument();+ const verdicts = OPENSCREEN_TOOLS.map(+ (name) => executeAgentTool(document, name, JSON.stringify(ARGS[name])).ok,+ );+ expect(verdicts).toContain(true);+ expect(verdicts).toContain(false);+ });++ it("a read tool that fails is reported as a failure", async () => {+ // `getTranscript` on a project with no transcript returns+ // `{"error":"No transcript for asset …"}`. It used to reach the sink as+ // ok:true — read tools had no emission of their own, and the stream loop+ // hard-coded the verdict.+ const document = { ...fixtureDocument(), transcripts: [], transcript: null };+ const { tools, events } = toolsFor(document);+ const tool = tools.find((t) => t.name === "getTranscript");+ if (!tool) throw new Error("getTranscript is not built");+ const result = await tool.invoke({} as never);++ expect(String(result)).toContain("No transcript");+ expect(events).toHaveLength(2);+ expect(events[1]).toMatchObject({ kind: "toolEnd", name: "getTranscript", ok: false });+ });++ it("advances the holder on a write, and leaves it alone on a refusal", async () => {+ const { tools, holder } = toolsFor(fixtureDocument());+ const before = holder.current;++ const refused = tools.find((t) => t.name === "setZoom");+ if (!refused) throw new Error("setZoom is not built");+ await refused.invoke({ zoomId: "zoom_nope" } as never);+ expect(holder.current).toBe(before);++ const write = tools.find((t) => t.name === "addTrim");+ if (!write) throw new Error("addTrim is not built");+ await write.invoke({ startSec: 1, endSec: 2 } as never);+ expect(holder.current).not.toBe(before);+ expect(holder.current.timeline.trimRanges).toHaveLength(2);+ });+});++// ─── The surfaces that describe the tools ──────────────────────────────────+//+// `agent-tools.ts` used to carry AGENT_TOOL_SPECS — a full JSON-schema+// description of all 17 tools, with a comment saying it was "sent verbatim to+// the provider". It was not, and had not been since the deep-agent landed: the+// model gets the zod schemas built here plus TOOL_DESCRIPTIONS. So the surface+// humans read and the surface the model read were two different documents, and+// only one of them had a reader who would notice it drifting. The specs are+// gone; these tests are what keeps the remaining three in step.+describe("one description of the tools, not two", () => {+ it("every described tool is built, and every built tool is executable", () => {+ // The third surface is the executor's own switch, which answers+ // "Unknown tool: …" for a name it does not handle. A tool that is described+ // and built but not executed would reach the model as a promise and come+ // back as an error — exactly the shape of drift the specs were supposed to+ // prevent and could not, being read by nobody.+ const document = fixtureDocument();+ for (const name of Object.keys(TOOL_DESCRIPTIONS)) {+ const result = executeAgentTool(document, name, JSON.stringify(ARGS[name] ?? {}));+ const error = JSON.parse(result.resultJson).error;+ expect(+ typeof error === "string" && error.startsWith("Unknown tool"),+ `${name}: ${error}`,+ ).toBe(false);+ }+ });++ it("the mutating flag production reads matches the tools that return a document", () => {+ const document = fixtureDocument();+ for (const name of OPENSCREEN_TOOLS) {+ const result = executeAgentTool(document, name, JSON.stringify(ARGS[name]));+ // A read must never produce a document; a write that succeeded must.+ if (!isMutatingTool(name)) expect(result.document, `${name} wrote`).toBeUndefined();+ else if (result.ok) expect(result.document, `${name} returned nothing`).toBeDefined();+ }+ expect(OPENSCREEN_TOOLS.filter((n) => !isMutatingTool(n))).toEqual([+ "getCurrentDocument",+ "getTranscript",+ "getCursorTrack",+ ]);+ });+});++describe("what the descriptions say about zoom strength", () => {+ it("carries the real depth table and not the formula that never matched it", () => {+ // "depth 1–6 maps to 1.0×–3.5×" was `depth/2 + 0.5`, wrong at both ends of a+ // table running 1.25×–5.0×, and it told the model depth 3 was ~2.0× while+ // the pill on screen read 1.80×.+ for (const text of [TOOL_DESCRIPTIONS.addZoom, TOOL_DESCRIPTIONS.setZoom, SYSTEM_PROMPT]) {+ expect(text).not.toMatch(/1\.0×–3\.5×|1\.0x-3\.5x/);+ }+ expect(TOOL_DESCRIPTIONS.addZoom).toContain(ZOOM_DEPTH_LEGEND);+ expect(SYSTEM_PROMPT).toContain(ZOOM_DEPTH_LEGEND);+ // Derived, not retyped: editing the table must move the prompt with it.+ expect(ZOOM_DEPTH_LEGEND).toContain(`3=${ZOOM_DEPTH_SCALES[3].toFixed(2)}×`);+ });++ it("tells the model a full-camera region needs a linked webcam", () => {+ expect(TOOL_DESCRIPTIONS.addCameraFullscreen).toMatch(/hasCameraTrack/);+ expect(SYSTEM_PROMPT).toMatch(/hasCameraTrack/);+ });+});++// ── D-CONSENT ───────────────────────────────────────────────────────────────+//+// The executor's guard is the wall; this is the other half. The workbench+// scores `dsl.consent.no-silent-edit` on the tool_calls the model EMITS, not on+// what the executor did with them — a turn that fires three writes and has all+// three refused is still a turn that tried. Only the prompt stops the emission,+// and only the guard makes the promise real. Neither is sufficient alone, so+// both are tested.+describe("the prompt when the user has turned project edits off", () => {+ it("tells the model to ask, and not to pretend", () => {+ const prompt = buildSystemPrompt({ editsAllowed: false });+ expect(prompt).toMatch(/PROJECT EDITS ARE CURRENTLY DISABLED/);+ expect(prompt).toMatch(/ask the user to confirm/i);+ expect(prompt).toMatch(/getCurrentDocument and getTranscript work as usual/);+ expect(prompt).toMatch(/Never state or imply that an edit was applied/i);+ });++ it("says nothing of the sort on a normal turn", () => {+ expect(buildSystemPrompt({ editsAllowed: true })).toBe(SYSTEM_PROMPT);+ expect(SYSTEM_PROMPT).not.toMatch(/PROJECT EDITS ARE CURRENTLY DISABLED/);+ });++ it("keeps the normal prompt as a prefix, so the editing rules still apply", () => {+ // The consent block CONSTRAINS the turn; it does not replace the tool+ // selection rules the model needs to describe the edit it is proposing.+ expect(buildSystemPrompt({ editsAllowed: false }).startsWith(SYSTEM_PROMPT)).toBe(true);+ });+});++describe("the tools when the user has turned project edits off", () => {+ it("still builds all 18 — the model has to be able to NAME the edit", () => {+ const { sink } = recordingSink();+ const tools = buildTools({ current: fixtureDocument() }, sink, false);+ expect(tools.map((t) => t.name)).toEqual(OPENSCREEN_TOOLS);+ });++ it("refuses every write through the tool, and the sink says so", async () => {+ const holder = { current: fixtureDocument() };+ const { sink, events } = recordingSink();+ const tools = buildTools(holder, sink, false);+ const before = holder.current;++ for (const name of OPENSCREEN_TOOLS.filter((n) => isMutatingTool(n))) {+ const tool = tools.find((t) => t.name === name);+ if (!tool) throw new Error(`${name} is not built`);+ const result = await tool.invoke((ARGS[name] ?? {}) as never);+ expect(JSON.parse(String(result)).code, name).toBe("consent_required");+ }+ // Not one of them advanced the document.+ expect(holder.current).toBe(before);+ // And every one was announced as a failure — a hard-coded ok:true here+ // would have shown the user a green chip for an edit that never happened.+ expect(events.filter((e) => e.kind === "toolEnd").every((e) => e.ok === false)).toBe(true);+ });++ it("leaves the reads working", async () => {+ const tools = buildTools({ current: fixtureDocument() }, recordingSink().sink, false);+ const read = tools.find((t) => t.name === "getCurrentDocument");+ if (!read) throw new Error("getCurrentDocument is not built");+ expect(JSON.parse(String(await read.invoke({} as never))).primaryAssetId).toBe("asset_1");+ });+});++// ─── D-TELEM: the reader is injected, and its absence is reported as ours ────+//+// `readCursorTelemetryFile` and friends existed and worked; they were wired+// only to the renderer, so the agent had no door and answered the question from+// nothing. The tool is the door. What these tests pin is the thing that would+// quietly recreate the defect: an agent whose reader is missing, or throws, must+// say "I could not look" — never "there is none".++const SAMPLES = (() => {+ const out: Array<{ timeMs: number; cx: number; cy: number; interactionType: "move" | "click" }> =+ [];+ let drift = 0;+ let clicked = false;+ for (let timeMs = 0; timeMs <= 12_000; timeMs += 33) {+ const parked = timeMs >= 4000 && timeMs <= 5600;+ if (parked) {+ // The click lands on the FIRST parked sample, so it is inside the dwell+ // window the detector reports rather than a step before it.+ const isClick = !clicked;+ clicked = true;+ out.push({ timeMs, cx: 0.8, cy: 0.25, interactionType: isClick ? "click" : "move" });+ } else {+ drift = (drift + 0.05) % 1;+ out.push({ timeMs, cx: drift, cy: drift, interactionType: "move" });+ }+ }+ return out;+})();++async function invokeCursorTool(runtime: Parameters<typeof buildTools>[3]) {+ const { sink, events } = recordingSink();+ const tools = buildTools({ current: fixtureDocument() }, sink, true, runtime);+ const tool = tools.find((t) => t.name === "getCursorTrack");+ if (!tool) throw new Error("getCursorTrack is not built");+ const result = await tool.invoke({} as never);+ return { payload: JSON.parse(String(result)), events };+}++describe("cursor telemetry reaches the model", () => {+ it("passes through what the injected reader returns", async () => {+ const { payload, events } = await invokeCursorTool({+ cursor: {+ read: async ({ assetId }) => ({ status: "ok", assetId, samples: SAMPLES }),+ },+ });++ expect(payload.available).toBe(true);+ expect(payload.sampleCount).toBe(SAMPLES.length);+ expect(payload.points.length).toBeGreaterThan(0);+ // The positions reaching the model are the recorded ones, not a centroid of+ // them: the click sample survives at its own coordinates.+ const click = payload.points.find((p: { kind?: string }) => p.kind === "click");+ expect(click).toBeTruthy();+ expect(click.cx).toBeCloseTo(0.8, 2);+ expect(click.cy).toBeCloseTo(0.25, 2);+ // A read, announced honestly, exactly once.+ expect(events.map((e) => e.kind)).toEqual(["toolStart", "toolEnd"]);+ expect(events[1].ok).toBe(true);+ });++ it("says 'unavailable' when no reader is injected", async () => {+ const { payload } = await invokeCursorTool({});+ expect(payload.available).toBe(false);+ expect(payload.reason).toBe("unavailable");+ });++ it("says 'unavailable', not 'no-sidecar', when the reader throws", async () => {+ // The failure mode that would put the defect back with green tests: a+ // broken reader turning into an absence of data.+ const { payload } = await invokeCursorTool({+ cursor: {+ read: async () => {+ throw new Error("EACCES: permission denied");+ },+ },+ });+ expect(payload.reason).toBe("unavailable");+ expect(payload.note).toContain("EACCES");+ });++ it("passes 'no-sidecar' through as the asset's own fact", async () => {+ const { payload } = await invokeCursorTool({+ cursor: { read: async ({ assetId }) => ({ status: "no-sidecar", assetId }) },+ });+ expect(payload.reason).toBe("no-sidecar");+ });++ it("asks the reader for the asset the call names, resolving the default itself", async () => {+ const asked: string[] = [];+ const runtime = {+ cursor: {+ read: async ({ assetId }: { assetId: string }) => {+ asked.push(assetId);+ return { status: "no-sidecar" as const, assetId };+ },+ },+ };+ const { sink } = recordingSink();+ const tools = buildTools({ current: fixtureDocument() }, sink, true, runtime);+ const tool = tools.find((t) => t.name === "getCursorTrack");+ if (!tool) throw new Error("getCursorTrack is not built");++ await tool.invoke({} as never);+ await tool.invoke({ assetId: "asset_1" } as never);++ // Both resolve to the primary asset — the wrapper and the executor must+ // agree on which asset is being reported, or the answer describes one and+ // the payload names the other.+ expect(asked).toEqual(["asset_1", "asset_1"]);+ });++ it("never hands the reader a path the model chose", async () => {+ // The tool takes an assetId; the path comes from the document. A tool that+ // accepted a path would be an arbitrary JSON reader on the user's disk.+ const seen: Array<{ originalPath: string | null }> = [];+ const runtime = {+ cursor: {+ read: async (input: { assetId: string; originalPath: string | null }) => {+ seen.push({ originalPath: input.originalPath });+ return { status: "no-sidecar" as const, assetId: input.assetId };+ },+ },+ };+ const { sink } = recordingSink();+ const tools = buildTools({ current: fixtureDocument() }, sink, true, runtime);+ const tool = tools.find((t) => t.name === "getCursorTrack");+ if (!tool) throw new Error("getCursorTrack is not built");++ await tool.invoke({ assetId: "asset_1", path: "/etc/passwd" } as never);++ expect(seen).toEqual([{ originalPath: fixtureDocument().assets[0].originalPath }]);+ });++ it("tells the model that blindness is not evidence", () => {+ // The executor's refusal is the mechanism; this sentence is what stops the+ // model converting it into a claim about the project, which is the half of+ // the defect no guard can reach.+ expect(SYSTEM_PROMPT).toMatch(/Blindness is not evidence/);+ expect(SYSTEM_PROMPT).toMatch(/hasCursorTelemetry/);+ expect(TOOL_DESCRIPTIONS.getCursorTrack).toMatch(/no-sidecar/);+ expect(TOOL_DESCRIPTIONS.getCursorTrack).toMatch(/unavailable/);+ });+});diff --git a/electron/ai-edition/deep-agent/service.ts b/electron/ai-edition/deep-agent/service.tsindex 07eb4ded4..b1fc8466a 100644--- a/electron/ai-edition/deep-agent/service.ts+++ b/electron/ai-edition/deep-agent/service.ts@@ -1,26 +1,47 @@// ponytail: port of axcut's AxcutDeepAgentService (apps/server/src/services/-// axcut-deep-agent.ts). Wraps `createDeepAgent` from the `deepagents` package-// (LangGraph stateful thread) with our existing document tools and emits-// agent.text / agent.toolStart / agent.toolEnd / agent.error events into a-// sink the chat-service pipes through `webContents.send`.+// axcut-deep-agent.ts). Wraps LangChain's `createAgent` (LangGraph ReAct graph)+// with our existing document tools and emits agent.text / agent.toolStart /+// agent.toolEnd / agent.error events into a sink the chat-service pipes through+// `webContents.send`.+//+// It used to wrap `createDeepAgent` from the `deepagents` package. That factory+// stacks three middlewares unconditionally — filesystem, todo-list, sub-agents —+// which handed the model EIGHT extra tools (ls / read_file / write_file /+// edit_file / glob / grep / write_todos / task) bound to an EMPTY in-memory+// backend, plus ~5 800 characters of system prompt promising a filesystem this+// app does not have. Nothing here used any of it, and the cost was not+// cosmetic: asked what cursor telemetry the project holds, the model ran+// `ls {"path":"/"}` then `glob {"pattern":"**/*"}` against that empty sandbox+// and reported, in good faith, that the project contains no pointer data. A+// fabricated proof of absence. `createDeepAgent` has no option to drop those+// middlewares (they are in `REQUIRED_MIDDLEWARE_NAMES`), so the fix is to stop+// going through it: `createAgent` is what it wrapped, minus the sandbox.-import { tool } from "langchain";+import { anthropicPromptCachingMiddleware, createAgent, tool } from "langchain";import { z } from "zod";import type { AxcutDocument } from "../../../src/lib/ai-edition/schema";+// ponytail: the legend is DERIVED from the depth→scale table, not retyped. Both+// tool descriptions used to assert "depth 1–6 maps to 1.0×–3.5×" — a formula+// (`depth/2 + 0.5`) that was purged from two rendering sites and survived here,+// wrong at both ends of a table that actually runs 1.25× to 5.0×.+import { ZOOM_DEPTH_LEGEND } from "../../../src/lib/ai-edition/timeline/zoom-scale";import {addAnnotationArgs,addCameraFullscreenArgs,addSpeedArgs,addTrimArgs,addZoomArgs,- documentSnapshotForModel,+ type CursorTelemetryLoad,executeAgentTool,+ getCursorTrackArgs,getTranscriptArgs,isMutatingTool,+ moveClipArgs,removeClipArgs,removeModifierArgs,removeTrimArgs,replaceTimelineArgs,+ resolveCursorAssetId,setAnnotationArgs,setCameraFullscreenArgs,setClipRangeArgs,@@ -51,7 +72,30 @@ export interface OpenScreenAgentSink {// both the executor's validation and the LangChain `tool()`s built here. Only the empty /// inline read-tool schemas below stay local.-const SYSTEM_PROMPT = [+/**+ * The block appended when the user has turned "Project edits" off.+ *+ * ponytail: the executor's refusal is the wall (see `consentRequired` in+ * agent-tools.ts) but a wall alone does not fix the measured defect. The+ * workbench scores `dsl.consent.no-silent-edit` on the tool_calls the model+ * EMITS, not on what the executor did with them, so a turn that fires three+ * writes and has them all refused still reads as a silent-edit attempt — and+ * rightly: the model tried. Only the prompt can stop the emission. Two layers,+ * neither sufficient alone.+ */+const CONSENT_PROMPT_BLOCK = [+ "",+ "PROJECT EDITS ARE CURRENTLY DISABLED by the user, who asked to be consulted before the timeline changes.",+ "- Read freely: getCurrentDocument and getTranscript work as usual.",+ "- Do NOT call any tool that writes (addTrim, setTrim, setClipRange, moveClip, replaceTimeline, add*/set* effects, remove*). Every one of them will be refused, so calling them wastes the turn and tells the user nothing.",+ "- Instead: say precisely what you would change — which tool, which times, which ids — and ask the user to confirm. Be specific enough that they can say yes to it.",+ "- Never state or imply that an edit was applied. If the user confirms and you are still refused, tell them the 'Project edits' setting in Settings → AI has to be re-enabled first.",+].join("\n");++// ponytail: exported so a test can assert that what the model receives is this+// string and NOTHING else — the deepagents regression was invisible precisely+// because the middlewares appended their prompts downstream of this constant.+const BASE_SYSTEM_PROMPT = ["You are an AI video editor working inside OpenScreen. The user is editing a recording.","Help them cut silences, tighten pacing, add captions, and rewrite titles.","Be concise, action-oriented, and reference the timeline or transcript by time when relevant.",@@ -60,33 +104,54 @@ const SYSTEM_PROMPT = ["","Time-bases (do not mix them up): clips and trims are in SOURCE-time seconds of an asset; zooms, speed regions, annotations and camera-fullscreen regions are in VIRTUAL (edited-timeline) seconds — the position on the ruler after clips + trims are applied. getCurrentDocument returns all of them, clearly labelled.","",- "Tool-selection rules (these are non-negotiable):",- "- 'remove silences' / 'cut pauses' / 'cut the silence' / 'kill the silence' / 'tighten pacing': call addTrim ONCE PER SILENT RANGE. Do NOT call setClipRange, do NOT call replaceTimeline. The placed clip is the canonical cut, the silence becomes a trim inside it.",- "- 'trim this clip to 0-30' / 'cut the end of this clip' / 'shorten this clip': call setClipRange with the new sourceStartSec/sourceEndSec (this is the clip's in/out, distinct from a trim).",- "- 'zoom in on …' / smart zooms: call addZoom over the virtual-timeline span (depth 1–6, focus in 0–1 frame fractions). 'speed through …': addSpeed. 'add a caption/label': addAnnotation. 'make the webcam fullscreen here': addCameraFullscreen.",- "- 'replace the timeline' / 'rebuild the timeline' / 'start over with these intervals': call replaceTimeline. Only when the user explicitly asks for a full rebuild.",- "- DELETING is a first-class action, not a workaround. 'remove/delete this trim' → removeTrim; 'remove/delete this zoom/speed/annotation/full-camera' → removeModifier; 'remove/delete this clip' → removeClip. NEVER fake a deletion by re-adding an element or zeroing it out (span 0, speed 1×) — that leaves it in the document and misreports what you did.",- "Anything else (move a clip, resize a trim, restyle a zoom, change a clip's order, etc.) — pick the most specific tool. If the request is ambiguous, prefer the smallest edit that satisfies it.",+ // ponytail: these describe what each tool is FOR, deliberately without quoting+ // user phrasings. A phrase→tool table reads as helpful and is not: it swaps the+ // model's language understanding for a lookup, so it covers the wordings we+ // happened to list and silently misses every paraphrase — and every language+ // other than English. Say what the tool does; let the model do the matching.+ "How the tools map to intent — pick the most specific one, and prefer the smallest edit that satisfies the request:",+ "- Silences, pauses and dead stretches are removed as trims INSIDE the placed clip: one addTrim per range. The placed clip stays the canonical cut; it is not rebuilt to drop them.",+ "- Changing where a clip starts or ends within its source is setClipRange — the clip's in/out, distinct from a trim.",+ `- addZoom takes a virtual-timeline span (depth is an ordinal 1–6 selecting from a fixed table — ${ZOOM_DEPTH_LEGEND} — never a multiplier; focus in 0–1 frame fractions). addSpeed changes pacing over a span. addAnnotation puts text on screen. addCameraFullscreen enlarges the webcam, and only does something where assets[].hasCameraTrack is true.`,+ "- moveClip changes the order of placed clips, one call per clip that moves, preserving ids, source ranges, trims and anchored effects. replaceTimeline rebuilds the timeline from kept intervals and sorts them, so it cannot reorder anything.",+ "- Deleting is a first-class action, not a workaround: removeTrim, removeModifier, removeClip. Never fake a deletion by re-adding an element or zeroing it out (span 0, speed 1×) — that leaves it in the document and misreports what you did.",+ "If nothing in the list does what was asked, say so; do not approximate it with a bigger tool.",+ "",+ "Cursor telemetry: while the screen was captured, OpenScreen recorded where the pointer went. assets[].hasCursorTelemetry in getCurrentDocument says which assets carry it, and getCursorTrack returns the recorded track for one of them — positions over time, and the pointer shape at each moment. What it means is yours to read.",+ "Blindness is not evidence. When a tool reports it could not read something (reason 'unavailable'), that is a limit of your runtime, not a fact about the project. Only an explicit negative — reason 'no-sidecar', or a false flag — supports telling the user the data is not there.","","Honesty rules: if a request has NO matching tool (e.g. deleting an asset/recording, exporting), say so plainly — do not substitute a different edit and report it as the requested one. After your edits, if you are at all unsure the document ended up as intended, call getCurrentDocument and reconcile what you claim with the real state; each tool result already tells you exactly what it did, so never report a change the results don't support.",].join("\n");-const TOOL_DESCRIPTIONS: Record<string, string> = {+/** The system prompt for a turn, which depends on ONE thing: whether the user+ * currently allows the agent to write. Exported so the consent wording can be+ * tested without a provider. */+export function buildSystemPrompt(options: { editsAllowed: boolean }): string {+ return options.editsAllowed ? BASE_SYSTEM_PROMPT : BASE_SYSTEM_PROMPT + CONSENT_PROMPT_BLOCK;+}++/** The prompt of a normal (edits-allowed) turn — the overwhelmingly common+ * case, and the string the surface tests measure the wire against. */+export const SYSTEM_PROMPT = buildSystemPrompt({ editsAllowed: true });++export const TOOL_DESCRIPTIONS: Record<string, string> = {getCurrentDocument:"Read a compact snapshot of the current project: assets (with durations), timeline clips and trim ranges (source-time), and the zoom / speed / annotation effects (virtual, edited-timeline time). Call this before editing if the snapshot in the system prompt may be stale. The AxcutDocument is the single source of truth — your edits should preserve the user's placed clips and any timeline state they have already set up.",getTranscript:"Read the transcript segments (speech and silence, with start/end seconds and text) for an asset. Omit assetId to read the primary asset's transcript.",+ getCursorTrack:+ "Read the recorded pointer track for an asset: where the cursor was over time, downsampled to a readable rate. Each point carries atSec (the asset's own source clock), virtualSec (the same instant on the edited timeline — the coordinate addZoom takes, null when no clip carries it), cx/cy as 0–1 fractions of the frame, and `shape`, an index into the pointer bitmaps the recording used (equal values are the same pointer; a change means the pointer changed, e.g. arrow to text caret). Points that are not plain moves carry `kind`; points a trim cuts out of playback carry `trimmed`. These are real samples, not a summary — reading what the pointer was doing is yours. Omit assetId for the primary asset. It answers `available:false` in two DIFFERENT ways you must not confuse: reason 'no-sidecar' means this asset was checked and genuinely has no telemetry, while reason 'unavailable' means it could not be read from here.",addTrim:"Add a trim range: a cut of a span inside a clip (this source-time span will not be played or exported) that does NOT split the clip. Times are in seconds of the asset's source time. This is the preferred (and for 'remove silences' requests, the only) way to handle silences; it preserves the user's placed clips and only adds a cut. Call this once per silent range.",setTrim: "Move or resize an existing trim range by id. Times are source-time seconds.",setClipRange:"Set a clip's in/out points (source-time seconds) to shorten its head or tail — distinct from a trim (which cuts a span inside the clip). All clips are re-laid back-to-back afterwards, so downstream clips shift automatically. Use this ONLY when the user explicitly asks to shorten or extend a user-placed clip. Do NOT use this for 'remove silences' or 'cut pauses' — for those, use addTrim.",+ moveClip:+ "Reorder a placed clip: move `clipId` so it plays just before `beforeClipId` (pass null, or omit it, to move it last). Ids come from getCurrentDocument, where each clip carries its `index` and its label in `reason`. This preserves every clip id, every source range, every trim, and the zooms / speed regions / annotations anchored to each clip. This is the tool for 'swap these clips', 'put X first' and 'change the clip order' — replaceTimeline cannot reorder anything.",replaceTimeline:- "Replace the whole timeline with the given kept intervals of the primary asset's source time. Everything outside the intervals becomes a trim. DO NOT use this for 'cut silences' or 'remove pauses' — the user has likely placed clips on the timeline that you'd be discarding. Use this ONLY when the user explicitly asks you to rebuild the timeline from scratch (e.g. 'start over with the kept intervals from the transcript' or 'replace everything with these intervals').",- addZoom:- "Add a zoom-in over a span of the edited timeline (virtual seconds). depth 1–6 maps to 1.0×–3.5× (default 3). focus is the zoom centre in 0–1 fractions of the frame (default centre). Use for 'zoom in on …' and the smart-zoom pass.",- setZoom:- "Move, resize, or restyle an existing zoom by id (virtual-timeline seconds). Only the fields you pass are changed.",+ "Replace the whole timeline with the given kept intervals of the primary asset's source time. Everything outside the intervals becomes a trim. The intervals are SORTED, so this can never reorder clips — use moveClip for that. DO NOT use this for 'cut silences' or 'remove pauses' — the user has likely placed clips on the timeline that you'd be discarding. Use this ONLY when the user explicitly asks you to rebuild the timeline from scratch (e.g. 'start over with the kept intervals from the transcript'). It is refused when it would merge away, shorten or drop an existing clip; the refusal names them and the tool to use instead.",+ addZoom: `Add a zoom-in over a span of the edited timeline (virtual seconds). depth is an ORDINAL 1–6, not a factor: it selects a magnification from a fixed table (${ZOOM_DEPTH_LEGEND}), so the default depth 3 renders at 1.80×. The result reports renderedScale — quote that, never the depth, when telling the user how strong the zoom is. focus is the zoom centre in 0–1 fractions of the frame (default centre). Use for 'zoom in on …' and the smart-zoom pass.`,+ setZoom: `Move, resize, or restyle an existing zoom by id (virtual-timeline seconds). Only the fields you pass are changed. depth selects from the same table (${ZOOM_DEPTH_LEGEND}); if the zoom carries a customScale (getCurrentDocument shows it as depthIsOverridden), that custom value is what renders, and passing depth clears it so the depth takes effect — the result says so. The result reports the resulting renderedScale.`,addSpeed:"Add a speed-change region over a span of the edited timeline (virtual seconds). speed > 1 fast-forwards, < 1 slows down (default 1.5×). Use to speed through slow stretches without cutting them.",setSpeed:@@ -96,9 +161,9 @@ const TOOL_DESCRIPTIONS: Record<string, string> = {setAnnotation:"Move, resize, or edit the text of an existing annotation by id (virtual-timeline seconds). Only the fields you pass are changed.",addCameraFullscreen:- "Add a camera-fullscreen region over a span of the edited timeline (virtual seconds): the webcam fills the frame for that span.",+ "Add a camera-fullscreen region over a span of the edited timeline (virtual seconds): the webcam fills the frame for that span. This only does something when the footage under that span comes from an asset with a linked webcam — check assets[].hasCameraTrack (or hasAnyCamera) in getCurrentDocument first. On footage with no camera the call is refused rather than storing a region that would render nothing; say so instead of retrying.",setCameraFullscreen:- "Move or resize an existing camera-fullscreen region by id (virtual-timeline seconds). Only the fields you pass are changed.",+ "Move or resize an existing camera-fullscreen region by id (virtual-timeline seconds). Only the fields you pass are changed. Refused if the new span lands on footage with no linked webcam.",removeTrim:"Delete a trim range by id — the cut is undone and that span plays/exports again. This is how you 'remove a trim'; never re-add a trim to undo one.",removeModifier:@@ -113,20 +178,67 @@ const TOOL_DESCRIPTIONS: Record<string, string> = {// each tool sees the latest mutated snapshot.type DocumentHolder = { current: AxcutDocument };-// One mutating document tool: run it through the shared executor, advance the-// holder so the next tool in the turn sees the edit, and emit start/end chips.-// (All write tools share this exact flow — factored out so adding a tool is one-// line instead of a 20-line copy.)-function mutatingTool<S extends z.ZodType>(+/**+ * The runtime's door onto recorded cursor telemetry.+ *+ * ponytail: an INTERFACE, injected, because everything that can actually read a+ * sidecar lives behind Electron's path allow-list, and `electron/ai-edition/`+ * deliberately imports nothing from `electron`. It takes an assetId plus the+ * path the DOCUMENT already holds — never a path the model chose.+ *+ * When no reader is injected the tool answers "unavailable", which is honest and+ * useless; a reader that is wired everywhere except production would be a+ * quieter version of the bug being fixed, so `handlers.ts` is the one caller+ * that matters and there is a test for the unwired case.+ */+export interface CursorTelemetryReader {+ read(input: { assetId: string; originalPath: string | null }): Promise<CursorTelemetryLoad>;+ /** Cheap "is there a sidecar?" check, run once per turn for every asset so+ * `getCurrentDocument` can report `hasCursorTelemetry` without reading the+ * file. A reader may omit it; the snapshot then reports null (not checked). */+ probe?(input: { assetId: string; originalPath: string | null }): Promise<boolean>;+}++interface ToolRuntime {+ cursor?: CursorTelemetryReader;+ availableByAssetId?: Record<string, boolean>;+}++// One document tool: run it through the shared executor, advance the holder so+// the next tool in the turn sees the edit, and emit exactly ONE start/end pair+// carrying the executor's REAL verdict.+//+// ponytail: reads go through here too, and that is the point. The read tools+// used to emit nothing of their own and be announced only by the `on_tool_end`+// branch of the stream loop, which hard-coded `ok: true` — so a `getTranscript`+// that came back `{"error":"No transcript for asset …"}` was reported as a+// success, and every write was announced twice (once truthfully here, once as+// `ok: true` there). One factory, one pair, one verdict. `executeAgentTool`+// never throws, so `execution.ok` is the only honest signal available.+function documentTool<S extends z.ZodType>(holder: DocumentHolder,sink: OpenScreenAgentSink,name: string,schema: S,+ editsAllowed: boolean,+ runtime: ToolRuntime,) {return tool(async (args: z.infer<S>) => {sink.toolStart(name, args);- const execution = executeAgentTool(holder.current, name, JSON.stringify(args));+ // ponytail: the ONE async step the pure executor cannot take. Reading a+ // sidecar is IO; `executeAgentTool` is synchronous by design (it is the+ // gate every mutation passes through, and it has to stay testable+ // without a filesystem). So the load happens here and its verdict —+ // including "I could not look" — goes in as data.+ const load =+ name === "getCursorTrack"+ ? await loadCursorTelemetry(holder.current, args, runtime)+ : undefined;+ const execution = executeAgentTool(holder.current, name, JSON.stringify(args), {+ editsAllowed,+ cursorTelemetry: { availableByAssetId: runtime.availableByAssetId, load },+ });if (execution.document) holder.current = execution.document;sink.toolEnd(name, execution.ok, execution.summary);return execution.resultJson;@@ -135,39 +247,93 @@ function mutatingTool<S extends z.ZodType>();}-function buildTools(holder: DocumentHolder, sink: OpenScreenAgentSink) {+/** Reads the sidecar for whichever asset the call names, defaulting to the+ * primary one — the same resolution the executor will use to report it. */+async function loadCursorTelemetry(+ document: AxcutDocument,+ args: unknown,+ runtime: ToolRuntime,+): Promise<CursorTelemetryLoad> {+ const requested = (args as { assetId?: unknown } | null)?.assetId;+ const assetId = resolveCursorAssetId(document, typeof requested === "string" ? requested : null);+ if (!assetId) return { status: "unavailable", assetId: null };+ if (!runtime.cursor) {+ return { status: "unavailable", assetId };+ }+ const asset = document.assets.find((a) => a.id === assetId);+ try {+ return await runtime.cursor.read({ assetId, originalPath: asset?.originalPath ?? null });+ } catch (error) {+ // A reader that throws is still "we could not look" — never "there is+ // none". Collapsing the two is the exact failure this tool exists to stop.+ return {+ status: "unavailable",+ assetId,+ note: `Cursor telemetry could not be read: ${error instanceof Error ? error.message : String(error)}`,+ };+ }+}++/**+ * The complete tool surface handed to the model. Exported so a test can assert+ * its exact shape — the count is the cheapest tripwire for a dependency that+ * starts injecting tools of its own again.+ *+ * ponytail: the write tools are built even when `editsAllowed` is false, and+ * that is deliberate. Withholding them would make the model answer "I have no+ * tool for that" — a lie, and one that hides the setting instead of surfacing+ * it. It has to be able to NAME the edit it is asking permission for.+ */+export function buildTools(+ holder: DocumentHolder,+ sink: OpenScreenAgentSink,+ editsAllowed = true,+ runtime: ToolRuntime = {},+) {+ const build = <S extends z.ZodType>(name: string, schema: S) =>+ documentTool(holder, sink, name, schema, editsAllowed, runtime);+ return [+ build("getCurrentDocument", z.object({})),+ build("getTranscript", getTranscriptArgs),+ build("getCursorTrack", getCursorTrackArgs),+ build("addTrim", addTrimArgs),+ build("setTrim", setTrimArgs),+ build("setClipRange", setClipRangeArgs),+ build("moveClip", moveClipArgs),+ build("replaceTimeline", replaceTimelineArgs),+ build("addZoom", addZoomArgs),+ build("setZoom", setZoomArgs),+ build("addSpeed", addSpeedArgs),+ build("setSpeed", setSpeedArgs),+ build("addAnnotation", addAnnotationArgs),+ build("setAnnotation", setAnnotationArgs),+ build("addCameraFullscreen", addCameraFullscreenArgs),+ build("setCameraFullscreen", setCameraFullscreenArgs),+ build("removeTrim", removeTrimArgs),+ build("removeModifier", removeModifierArgs),+ build("removeClip", removeClipArgs),+ ];+}++/**+ * Prompt caching for the Anthropic-wire providers, which `createDeepAgent`+ * used to add for us (`isAnthropicModel` → `anthropicPromptCachingMiddleware`).+ * Dropping it silently would have made every Anthropic and MiniMax turn re-pay+ * for the full prompt — a cost and latency regression invisible to the offline+ * tests, which all run on the OpenAI-compatible path.+ *+ * The class-name probe is deepagents' own test, kept verbatim so MiniMax (which+ * rides `ChatAnthropic` because its wire format is Anthropic's) keeps caching.+ * `unsupportedModelBehavior: "ignore"` means a model that turns out not to+ * support cache breakpoints degrades instead of throwing.+ */+export function anthropicCachingMiddleware(chatModel: { getName?: () => string }) {+ if (chatModel.getName?.() !== "ChatAnthropic") return [];return [- tool(async () => JSON.stringify(documentSnapshotForModel(holder.current)), {- name: "getCurrentDocument",- description: TOOL_DESCRIPTIONS.getCurrentDocument,- schema: z.object({}),+ anthropicPromptCachingMiddleware({+ unsupportedModelBehavior: "ignore",+ minMessagesToCache: 1,}),- tool(- async (args: { assetId?: string }) => {- const execution = executeAgentTool(holder.current, "getTranscript", JSON.stringify(args));- return execution.resultJson;- },- {- name: "getTranscript",- description: TOOL_DESCRIPTIONS.getTranscript,- schema: getTranscriptArgs,- },- ),- mutatingTool(holder, sink, "addTrim", addTrimArgs),- mutatingTool(holder, sink, "setTrim", setTrimArgs),- mutatingTool(holder, sink, "setClipRange", setClipRangeArgs),- mutatingTool(holder, sink, "replaceTimeline", replaceTimelineArgs),- mutatingTool(holder, sink, "addZoom", addZoomArgs),- mutatingTool(holder, sink, "setZoom", setZoomArgs),- mutatingTool(holder, sink, "addSpeed", addSpeedArgs),- mutatingTool(holder, sink, "setSpeed", setSpeedArgs),- mutatingTool(holder, sink, "addAnnotation", addAnnotationArgs),- mutatingTool(holder, sink, "setAnnotation", setAnnotationArgs),- mutatingTool(holder, sink, "addCameraFullscreen", addCameraFullscreenArgs),- mutatingTool(holder, sink, "setCameraFullscreen", setCameraFullscreenArgs),- mutatingTool(holder, sink, "removeTrim", removeTrimArgs),- mutatingTool(holder, sink, "removeModifier", removeModifierArgs),- mutatingTool(holder, sink, "removeClip", removeClipArgs),];}@@ -177,8 +343,60 @@ export interface InvokeArgs {history: Array<{ role: "user" | "assistant" | "system"; content: string }>;userMessage: string;sink: OpenScreenAgentSink;+ /** `config.allowAgentEdits !== false`, resolved by the chat-service. When+ * false the write tools refuse and the prompt tells the model to ask.+ * Defaults to allowed so a caller that predates the flag behaves as before. */+ editsAllowed?: boolean;+ /** Injected by `chat-service` from the Electron layer. Absent in tests and in+ * the workbench unless one is supplied on purpose. */+ cursor?: CursorTelemetryReader;}+/** One cheap probe per asset, run before the tools are built so the very first+ * `getCurrentDocument` can already say whether telemetry exists. */+async function probeCursorTelemetry(+ document: AxcutDocument,+ cursor: CursorTelemetryReader | undefined,+): Promise<Record<string, boolean> | undefined> {+ if (!cursor?.probe) return undefined;+ const entries = await Promise.all(+ document.assets.map(async (asset) => {+ try {+ return [+ asset.id,+ await cursor.probe!({ assetId: asset.id, originalPath: asset.originalPath ?? null }),+ ] as const;+ } catch {+ // A probe that throws leaves the asset OUT of the map, which the+ // snapshot renders as null — "not checked". Recording it as `false`+ // would turn our failure into a claim about the user's project.+ return null;+ }+ }),+ );+ const map: Record<string, boolean> = {};+ for (const entry of entries) {+ if (entry) map[entry[0]] = entry[1];+ }+ return map;+}++/**+ * ponytail: `on_tool_start` / `on_tool_end` are observed and DROPPED, not+ * forwarded to the sink. `documentTool` already announced the call with the+ * real arguments and the executor's real verdict; this branch has no access to+ * the tool's return value, so it could only ever invent `ok: true` — which is+ * exactly how a REFUSED `replaceTimeline` and a `getTranscript` that returned+ * `{"error":"No transcript…"}` both came out green. Every write was announced+ * twice, the second time as a success. A stream branch must never fabricate a+ * verdict: a tool built outside `documentTool` should be silent here (and get+ * caught by the "one pair per call" test) rather than quietly mislabelled.+ *+ * They are excluded from `nonChatEvents` as well, so the empty-response+ * diagnostic keeps listing only genuinely unhandled events.+ */+const SILENT_TOOL_EVENTS: ReadonlySet<string> = new Set(["on_tool_start", "on_tool_end"]);+export interface InvokeResult {text: string;document: AxcutDocument;@@ -192,21 +410,36 @@ export interface InvokeResult {export async function invokeOpenScreenAgent(args: InvokeArgs): Promise<InvokeResult> {const { document, model, history, userMessage, sink } = args;+ const editsAllowed = args.editsAllowed !== false;const holder: DocumentHolder = { current: document };const initialDocumentJSON = JSON.stringify(document);// ponytail: build a fresh agent per turn (same pattern as axcut). The- // runtime side-effects (langgraph thread, sandbox) are tied to the agent- // instance — checkpoint-based stateful threads can land later by passing- // a `checkpointer` to createDeepAgent; for v1 each turn is single-shot.- const { createDeepAgent } = await import("deepagents");+ // runtime side-effects (langgraph thread) are tied to the agent instance —+ // checkpoint-based stateful threads can land later by passing a+ // `checkpointer`; for v1 each turn is single-shot.const chatModel = await createOpenScreenChatModel(model);- const tools = buildTools(holder, sink);- const agent = await createDeepAgent({+ const availableByAssetId = await probeCursorTelemetry(document, args.cursor);+ const tools = buildTools(holder, sink, editsAllowed, {+ cursor: args.cursor,+ availableByAssetId,+ });+ const agent = createAgent({model: chatModel,tools,- systemPrompt: SYSTEM_PROMPT,+ systemPrompt: buildSystemPrompt({ editsAllowed }),+ middleware: anthropicCachingMiddleware(chatModel),+ }).withConfig({+ // ponytail: NOT optional. LangGraph's default is 25 steps, and an+ // auto-enhance turn spends one step per silence — it would die mid-turn+ // with a GraphRecursionError, which this file's catch block relabels+ // "Empty response from model" (the same words a mute provider gets).+ // `createDeepAgent` used 1e4; that is reckless while there is still no+ // AbortSignal and no timeout anywhere on the product path — a looping+ // model would be indistinguishable from a hang. 1000 is far above any+ // real turn and still bounded.+ recursionLimit: 1000,});const messages = [...history, { role: "user" as const, content: userMessage }];@@ -248,14 +481,15 @@ export async function invokeOpenScreenAgent(args: InvokeArgs): Promise<InvokeRessink.text(delta);finalText += delta;}- } else if (eventType === "on_tool_start") {- const input = data?.input;- sink.toolStart(name, input ?? {});- } else if (eventType === "on_tool_end") {- sink.toolEnd(name, true);} else if (eventType === "on_tool_error") {+ // Kept as a safety net rather than as a live path. `executeAgentTool`+ // never throws, and LangChain's ToolNode catches what does (an unknown+ // tool name, arguments the zod binding rejects) and feeds it back as+ // the tool RESULT instead of raising. This branch only fires for a+ // failure that escapes both — and then the stream is the only witness,+ // so it reports `ok: false` from evidence, never a fabricated verdict.sink.toolEnd(name, false, extractError(data));- } else if (eventType) {+ } else if (eventType && !SILENT_TOOL_EVENTS.has(eventType)) {nonChatEvents.push({ event: eventType, name });}}@@ -320,6 +554,9 @@ function extractError(data: Record<string, unknown> | undefined): string | undefreturn undefined;}-// ponytail: keep `isMutatingTool` reachable via this module so future-// importers don't need to cross into agent-tools directly.+// ponytail: re-exported for the agent-facing surface, but be honest about who+// uses it — no production code calls it. Its only real consumers are the+// workbench (`lib/wire.ts`, `lib/oracles.ts`), which import it straight from+// agent-tools anyway, and the tests. It is kept because the mutating/non-mutating+// split is a property of the agent surface, and this module is that surface.export { isMutatingTool };diff --git a/electron/ai-edition/llm-config-store.ts b/electron/ai-edition/llm-config-store.tsindex 4db7822b0..b558774ac 100644--- a/electron/ai-edition/llm-config-store.ts+++ b/electron/ai-edition/llm-config-store.ts@@ -17,8 +17,18 @@ export interface LlmConfig {model: string;baseUrl?: string;reasoningEffort?: string;- /** P2.5 — when false, the agent's write tools are refused and the model is- * told to ask the user for confirmation. Undefined means enabled. */+ /**+ * P2.5 — when false, the agent's write tools are refused and the model is+ * told to ask the user for confirmation. Undefined means enabled.+ *+ * ponytail: this comment described the contract for a whole release while+ * `chat-service.ts` read the flag and dropped it (`void editsAllowed;`).+ * It is now enforced in two places — `buildSystemPrompt` for the model and+ * `executeAgentTool` for the runtime — plus a guard on the document+ * `runChat` hands back. What is still missing is a per-turn "yes, go ahead"+ * channel: the user re-enables the setting, which is what the refusal tells+ * the model to say (see technical-documentation/architecture/ai-agent.md).+ */allowAgentEdits?: boolean;}diff --git a/src/components/video-editor/types.ts b/src/components/video-editor/types.tsindex aaeac5333..10ab528e4 100644--- a/src/components/video-editor/types.ts+++ b/src/components/video-editor/types.ts@@ -1,7 +1,12 @@+import {+ effectiveZoomScale,+ type ZoomDepth,+ type ZoomScaleInput,+} from "@/lib/ai-edition/timeline/zoom-scale";import type { WebcamLayoutPreset } from "@/lib/compositeLayout";import { clamp01 } from "@/utils/math";-export type ZoomDepth = 1 | 2 | 3 | 4 | 5 | 6;+export type { ZoomDepth, ZoomScaleInput };export type ZoomFocusMode = "manual" | "auto";export type { WebcamLayoutPreset };/** Webcam size as a percentage of the canvas reference dimension (10-50). */@@ -422,27 +427,23 @@ export const SPEED_OPTIONS: Array<{ speed: PlaybackSpeed; label: string }> = [export const DEFAULT_PLAYBACK_SPEED: PlaybackSpeed = 1.5;-export const ZOOM_DEPTH_SCALES: Record<ZoomDepth, number> = {- 1: 1.25,- 2: 1.5,- 3: 1.8,- 4: 2.2,- 5: 3.5,- 6: 5.0,-};--export const MIN_ZOOM_SCALE = 1.0;-export const MAX_ZOOM_SCALE = 5.0;--export const DEFAULT_ZOOM_DEPTH: ZoomDepth = 3;+// The table and the clamp moved to `@/lib/ai-edition/timeline/zoom-scale` so+// the Electron main process can import them without the `@/` alias, which its+// build does not resolve. Re-exported here because every renderer importer+// (focusUtils, zoomRegionUtils, sceneDescription, the inspector, the timeline)+// reaches them through this module.+export {+ DEFAULT_ZOOM_DEPTH,+ effectiveZoomScale,+ MAX_ZOOM_SCALE,+ MIN_ZOOM_SCALE,+ ZOOM_DEPTH_LEGEND,+ ZOOM_DEPTH_SCALES,+} from "@/lib/ai-edition/timeline/zoom-scale";/** Returns the effective zoom scale for a region, preferring customScale over the preset. */-export function getZoomScale(region: ZoomRegion): number {- if (region.customScale != null) {- const clamped = Math.max(MIN_ZOOM_SCALE, Math.min(MAX_ZOOM_SCALE, region.customScale));- if (Number.isFinite(clamped)) return clamped;- }- return ZOOM_DEPTH_SCALES[region.depth];+export function getZoomScale(region: ZoomScaleInput): number {+ return effectiveZoomScale(region);}// An unknown focus means "centre", not "top-left" — so this one can't use thediff --git a/src/lib/ai-edition/document/operations.test.ts b/src/lib/ai-edition/document/operations.test.tsindex 1364bc311..044eab4fd 100644--- a/src/lib/ai-edition/document/operations.test.ts+++ b/src/lib/ai-edition/document/operations.test.ts@@ -135,6 +135,31 @@ describe("applyTimelineOperation.drop_range", () => {.reduce((sum, c) => sum + (c.sourceEndSec - c.sourceStartSec), 0);expect(totalKeep).toBe(50);});++ it("keeps the cuts the user had already made", () => {+ // ponytail: `drop_range` rebuilds the timeline, and the rebuild used to+ // replace `trimRanges` in full with the complement of the kept intervals.+ // So every UI drag of a range deleted every trim the user had placed —+ // silently, one storey below the operation that appeared to be about+ // something else entirely.+ const withTrim = applyTimelineOperation(makeDoc(), {+ type: "add_trim_range",+ startSec: 40,+ endSec: 45,+ }).document;+ const trimId = withTrim.timeline.trimRanges[0].id;+ const dropped = applyTimelineOperation(withTrim, {+ type: "drop_range",+ assetId: "asset_1",+ startSec: 10,+ endSec: 20,+ }).document;+ expect(dropped.timeline.trimRanges.map((t) => t.id)).toContain(trimId);+ expect(dropped.timeline.trimRanges.find((t) => t.id === trimId)).toMatchObject({+ startSec: 40,+ endSec: 45,+ });+ });});describe("applyTimelineOperation.replace_timeline", () => {diff --git a/src/lib/ai-edition/document/operations.ts b/src/lib/ai-edition/document/operations.tsindex 8f51b5533..72a0a59e8 100644--- a/src/lib/ai-edition/document/operations.ts+++ b/src/lib/ai-edition/document/operations.ts@@ -254,11 +254,14 @@ export function applyTimelineOperation(case "restore_full_timeline": {const duration = primaryAssetDuration(document);if (duration <= 0) return { document, summary: "no duration yet" };+ // Same semantics as `restoreFullTimeline`: a genuine reset, so it opts+ // out of the id/trim preservation every other caller wants.const next = replaceTimeline(document,[{ startSec: 0, endSec: duration }],op.reason ?? "restored full timeline","user",+ { preserveIds: false, preserveTrims: false },);return { document: next, summary: "restored full timeline" };}diff --git a/src/lib/ai-edition/document/timeline.test.ts b/src/lib/ai-edition/document/timeline.test.tsindex de92ceaff..b87701402 100644--- a/src/lib/ai-edition/document/timeline.test.ts+++ b/src/lib/ai-edition/document/timeline.test.ts@@ -6,6 +6,7 @@ import {invertIntervals,moveClip,normalizeIntervals,+ planTimelineReplacement,primaryAssetDuration,rederiveRegionMs,removeClip,@@ -176,6 +177,423 @@ describe("timeline pure functions", () => {});});+ // ── D-DESTRUCT ────────────────────────────────────────────────────────────+ //+ // `replaceTimeline` was destructive in three separate ways, each invisible+ // from its return value: it re-minted every id, it merged adjacent intervals+ // (so handing it the timeline's OWN intervals collapsed two clips into one),+ // it replaced `trimRanges` wholesale, and it re-anchored every modifier from+ // its ruler position rather than its content. The document stayed+ // schema-valid throughout, which is why nothing caught it.+ describe("replaceTimeline is not destructive by default", () => {+ /** Two adjacent clips over one asset, a user cut inside the first, and a+ * zoom anchored to the second — the shape the workbench measures. */+ function twoClipDoc(): AxcutDocument {+ return makeDoc({+ timeline: {+ clips: [+ makeClip({ id: "clip_1", sourceStartSec: 0, sourceEndSec: 30, timelineEndSec: 30 }),+ makeClip({+ id: "clip_2",+ sourceStartSec: 30,+ sourceEndSec: 60,+ timelineStartSec: 30,+ timelineEndSec: 60,+ reason: "demo",+ }),+ ],+ gaps: [],+ trimRanges: [makeTrim({ id: "trim_1", startSec: 12, endSec: 17 })],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ },+ zoomRanges: [+ {+ id: "zoom_demo",+ startMs: 40_000,+ endMs: 45_000,+ depth: 3,+ focus: { cx: 0.5, cy: 0.5 },+ clipId: "clip_2",+ sourceStartSec: 40,+ sourceEndSec: 45,+ },+ ] as unknown as AxcutDocument["zoomRanges"],+ });+ }++ it("keeps both clips and the user's cut when handed the timeline's own intervals", () => {+ // The identity call. `normalizeIntervals` merges [0,30] and [30,60] into+ // one span, so this used to return a single `clip_1` spanning 0–60 with+ // zero trims: nothing asked for, everything changed.+ const updated = replaceTimeline(+ twoClipDoc(),+ [+ { startSec: 0, endSec: 30 },+ { startSec: 30, endSec: 60 },+ ],+ "identity",+ "agent",+ );+ expect(updated.timeline.clips.map((c) => c.id)).toEqual(["clip_1", "clip_2"]);+ expect(updated.timeline.trimRanges.map((t) => t.id)).toEqual(["trim_1"]);+ expect(updated.timeline.trimRanges[0]).toMatchObject({ startSec: 12, endSec: 17 });+ });++ it("keeps a preserved clip's origin and label instead of stamping its own", () => {+ const updated = replaceTimeline(+ twoClipDoc(),+ [+ { startSec: 0, endSec: 30 },+ { startSec: 30, endSec: 60 },+ ],+ "rebuilt by the agent",+ "agent",+ );+ expect(updated.timeline.clips[1]).toMatchObject({ origin: "user", reason: "demo" });+ });++ it("leaves an anchored zoom on its own footage, not on whatever slid under it", () => {+ // clip_1 shrinks to 0–25, so clip_2 (kept intact) slides from ruler 30 to+ // ruler 25 while its CONTENT is unchanged. Re-anchoring the zoom from its+ // RAW ms — what a rebuild used to do to EVERY modifier — reads the ruler+ // rather than the content: ruler 40 now falls at source 45, so the zoom+ // came back five seconds into footage the user never pointed at, with a+ // schema-valid document and nothing said.+ const updated = replaceTimeline(+ twoClipDoc(),+ [+ { startSec: 0, endSec: 25 },+ { startSec: 30, endSec: 60 },+ ],+ "shrink the intro",+ "agent",+ );+ const clip2 = updated.timeline.clips.find((c) => c.id === "clip_2");+ expect(clip2).toMatchObject({ timelineStartSec: 25, sourceStartSec: 30 });+ expect(updated.zoomRanges[0]).toMatchObject({+ id: "zoom_demo",+ clipId: "clip_2",+ sourceStartSec: 40,+ sourceEndSec: 45,+ });+ // And its derived ms followed its clip: ruler 25 + (40 − 30) = 35 s.+ expect(updated.zoomRanges[0]).toMatchObject({ startMs: 35_000, endMs: 40_000 });+ });++ it("narrows a straddling trim instead of deleting it, and keeps its id", () => {+ const updated = replaceTimeline(twoClipDoc(), [{ startSec: 0, endSec: 15 }], "cut", "agent");+ const kept = updated.timeline.trimRanges.find((t) => t.id === "trim_1");+ expect(kept).toMatchObject({ startSec: 12, endSec: 15 });+ // And the stretch beyond the kept interval is cut by the complement.+ expect(updated.timeline.trimRanges.some((t) => t.startSec === 15 && t.endSec === 60)).toBe(+ true,+ );+ });++ it("never touches another asset's cuts", () => {+ // The same bug `operations.ts` had already had to fix for add_trim_range:+ // `trimRanges` was replaced in full by the complement of the PRIMARY+ // asset's intervals, with no assetId filter anywhere.+ const doc = makeDoc({+ timeline: {+ clips: [],+ gaps: [],+ trimRanges: [makeTrim({ id: "trim_other", assetId: "asset_2", startSec: 1, endSec: 2 })],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ },+ });+ const updated = replaceTimeline(doc, [{ startSec: 0, endSec: 60 }], "rebuild", "agent");+ expect(updated.timeline.trimRanges.map((t) => t.id)).toContain("trim_other");+ });++ it("mints unique ids for the slots that match nothing", () => {+ // Positional `clip_${i+1}` / `trim_${i+1}` are what let an id survive a+ // rebuild while designating something else — and they would collide+ // outright with a preserved id sitting at the same index.+ const updated = replaceTimeline(+ twoClipDoc(),+ [+ { startSec: 0, endSec: 30 },+ { startSec: 40, endSec: 50 },+ ],+ "cut",+ "agent",+ );+ const ids = updated.timeline.clips.map((c) => c.id);+ expect(ids[0]).toBe("clip_1");+ expect(ids[1]).not.toBe("clip_2");+ expect(new Set(ids).size).toBe(ids.length);+ const trimIds = updated.timeline.trimRanges.map((t) => t.id);+ expect(new Set(trimIds).size).toBe(trimIds.length);+ });++ it("still resets everything when the caller opts out — restoreFullTimeline", () => {+ // The one caller whose semantics ARE "throw it all away". If preservation+ // leaked in here, the Restore button would stop restoring.+ const restored = restoreFullTimeline(twoClipDoc());+ expect(restored.timeline.clips.map((c) => c.id)).toEqual(["clip_1"]);+ expect(restored.timeline.clips[0]).toMatchObject({ sourceStartSec: 0, sourceEndSec: 60 });+ expect(restored.timeline.trimRanges).toHaveLength(0);+ });+ });++ // The anchoring contract itself, stated once and checked after each structural+ // edit rather than re-derived per case. `timelineMap` holds that a fragment's+ // `{clipId, sourceStartSec, sourceEndSec}` is the truth and its `startMs`/+ // `endMs` are a CACHE of where that lands on the ruler — so any operation that+ // moves clips must leave the two agreeing. Both halves of D-DESTRUCT were+ // violations of exactly this: the rebuild recomputed the anchor from the+ // cache (backwards), and nothing checked the result.+ describe("the anchor/derived-ms invariant survives a structural edit", () => {+ /** Every anchored region's cached ms equals what its clip's live position+ * says they should be, and no region points at a clip that is gone. */+ function assertAnchorsAgree(document: AxcutDocument): void {+ const clips = document.timeline.clips;+ for (const region of document.zoomRanges as unknown as Array<{+ id: string;+ startMs: number;+ endMs: number;+ clipId?: string;+ sourceStartSec?: number;+ sourceEndSec?: number;+ }>) {+ if (!region.clipId) continue;+ const clip = clips.find((c) => c.id === region.clipId);+ expect(clip, `${region.id} anchored to a clip that no longer exists`).toBeDefined();+ if (!clip || region.sourceStartSec === undefined || region.sourceEndSec === undefined) {+ continue;+ }+ const offset = clip.timelineStartSec - clip.sourceStartSec;+ expect(region.startMs, `${region.id} startMs`).toBe(+ Math.round((region.sourceStartSec + offset) * 1000),+ );+ expect(region.endMs, `${region.id} endMs`).toBe(+ Math.round((region.sourceEndSec + offset) * 1000),+ );+ }+ }++ /** Three clips, and a zoom straddling the boundary between the last two —+ * stored as TWO fragments, which is the case where a reorder can pull the+ * halves of one pill apart. */+ function straddled(): AxcutDocument {+ return makeDoc({+ timeline: {+ clips: [+ makeClip({ id: "clip_1", sourceStartSec: 0, sourceEndSec: 20, timelineEndSec: 20 }),+ makeClip({+ id: "clip_2",+ sourceStartSec: 20,+ sourceEndSec: 40,+ timelineStartSec: 20,+ timelineEndSec: 40,+ }),+ makeClip({+ id: "clip_3",+ sourceStartSec: 40,+ sourceEndSec: 60,+ timelineStartSec: 40,+ timelineEndSec: 60,+ }),+ ],+ gaps: [],+ trimRanges: [],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ },+ zoomRanges: [+ {+ id: "zoom_a",+ startMs: 35_000,+ endMs: 40_000,+ depth: 3,+ focus: { cx: 0.5, cy: 0.5 },+ clipId: "clip_2",+ sourceStartSec: 35,+ sourceEndSec: 40,+ },+ {+ id: "zoom_b",+ startMs: 40_000,+ endMs: 45_000,+ depth: 3,+ focus: { cx: 0.5, cy: 0.5 },+ clipId: "clip_3",+ sourceStartSec: 40,+ sourceEndSec: 45,+ },+ ] as unknown as AxcutDocument["zoomRanges"],+ });+ }++ it("holds after a moveClip", () => {+ const moved = moveClip(straddled(), "clip_3", 0, "user", "");+ expect(moved.timeline.clips.map((c) => c.id)).toEqual(["clip_3", "clip_1", "clip_2"]);+ assertAnchorsAgree(moved);+ // Each half of the straddling pill went with its OWN clip, so they are+ // no longer adjacent on the ruler — which is correct, and is why+ // fragments carry an anchor rather than a shared group marker.+ const byId = new Map(moved.zoomRanges.map((z) => [z.id, z]));+ expect(byId.get("zoom_b")?.startMs).toBe(0);+ expect(byId.get("zoom_a")?.startMs).toBe(55_000);+ });++ it("holds after a rebuild that keeps every clip", () => {+ const rebuilt = replaceTimeline(+ straddled(),+ [+ { startSec: 0, endSec: 20 },+ { startSec: 20, endSec: 40 },+ { startSec: 40, endSec: 60 },+ ],+ "identity",+ "agent",+ );+ assertAnchorsAgree(rebuilt);+ expect(rebuilt.zoomRanges.map((z) => z.id)).toEqual(["zoom_a", "zoom_b"]);+ });++ it("holds after a rebuild that drops the clip a fragment lived on", () => {+ // clip_3 is gone, so `zoom_b` has no content left. It must be DROPPED,+ // not re-pointed at whatever now occupies its old ruler position.+ const rebuilt = replaceTimeline(+ straddled(),+ [+ { startSec: 0, endSec: 20 },+ { startSec: 20, endSec: 40 },+ ],+ "drop the tail",+ "agent",+ );+ assertAnchorsAgree(rebuilt);+ expect(rebuilt.zoomRanges.map((z) => z.id)).toEqual(["zoom_a"]);+ });++ it("keeps a region that was never anchored at all", () => {+ // The other half of the orphan rule: a v2 migration produces regions+ // with RAW ms and no anchor, because anchoring needs a clip with a real+ // extent. Dropping "cannot place it" wholesale would delete those.+ const doc = straddled();+ const unanchored: AxcutDocument = {+ ...doc,+ zoomRanges: [+ {+ id: "zoom_legacy",+ startMs: 55_000,+ endMs: 58_000,+ depth: 3,+ focus: { cx: 0.5, cy: 0.5 },+ },+ ] as unknown as AxcutDocument["zoomRanges"],+ };+ const rebuilt = replaceTimeline(+ unanchored,+ [{ startSec: 0, endSec: 20 }],+ "drop the tail",+ "agent",+ );+ expect(rebuilt.zoomRanges.map((z) => z.id)).toEqual(["zoom_legacy"]);+ });++ it("holds after a setClipRange that narrows a fragment's window", () => {+ const narrowed = setClipSourceRange(straddled(), "clip_2", 20, 37);+ assertAnchorsAgree(narrowed);+ // zoom_a covered 35–40 of a window that now ends at 37: clamped, kept.+ expect(narrowed.zoomRanges.find((z) => z.id === "zoom_a")).toMatchObject({+ sourceStartSec: 35,+ sourceEndSec: 37,+ });+ });+ });++ describe("planTimelineReplacement", () => {+ function twoClipDoc(): AxcutDocument {+ return makeDoc({+ timeline: {+ clips: [+ makeClip({ id: "clip_1", sourceStartSec: 0, sourceEndSec: 30, timelineEndSec: 30 }),+ makeClip({+ id: "clip_2",+ sourceStartSec: 30,+ sourceEndSec: 60,+ timelineStartSec: 30,+ timelineEndSec: 60,+ }),+ ],+ gaps: [],+ trimRanges: [makeTrim({ id: "trim_1", startSec: 12, endSec: 17 })],+ muteRanges: [],+ speedRanges: [],+ captionRanges: [],+ },+ });+ }++ it("reads a swap as a reorder — the intent only survives before the sort", () => {+ const plan = planTimelineReplacement(twoClipDoc(), [+ { startSec: 30, endSec: 60 },+ { startSec: 0, endSec: 30 },+ ]);+ expect(plan.reorderRequested).toBe(true);+ });++ it("does not call an ordinary rebuild a reorder", () => {+ const plan = planTimelineReplacement(twoClipDoc(), [+ { startSec: 0, endSec: 30 },+ { startSec: 30, endSec: 60 },+ ]);+ expect(plan.reorderRequested).toBe(false);+ expect(plan.lostClipIds).toEqual([]);+ expect(plan.slots.map((s) => s.keepClipId)).toEqual(["clip_1", "clip_2"]);+ });++ it("names the clips a narrower rebuild would cost", () => {+ const plan = planTimelineReplacement(twoClipDoc(), [{ startSec: 0, endSec: 20 }]);+ expect(plan.lostClipIds).toEqual(["clip_1", "clip_2"]);+ });++ it("reports a trim that falls outside the kept spans as absorbed, not lost", () => {+ // Its id goes, its CUT does not: that stretch is excluded anyway. Calling+ // it a loss would make the guard refuse a rebuild that costs nothing.+ const plan = planTimelineReplacement(twoClipDoc(), [{ startSec: 0, endSec: 10 }]);+ expect(plan.absorbedTrimIds).toEqual(["trim_1"]);+ expect(plan.clippedTrimIds).toEqual([]);+ });++ it("counts the modifiers that would be re-anchored onto other footage", () => {+ const doc = twoClipDoc();+ const withZoom: AxcutDocument = {+ ...doc,+ zoomRanges: [+ {+ id: "zoom_demo",+ startMs: 40_000,+ endMs: 45_000,+ depth: 3,+ focus: { cx: 0.5, cy: 0.5 },+ clipId: "clip_2",+ sourceStartSec: 40,+ sourceEndSec: 45,+ },+ ] as unknown as AxcutDocument["zoomRanges"],+ };+ expect(+ planTimelineReplacement(withZoom, [{ startSec: 0, endSec: 20 }]).slidRegionIds,+ ).toEqual(["zoom_demo"]);+ expect(+ planTimelineReplacement(withZoom, [+ { startSec: 0, endSec: 30 },+ { startSec: 30, endSec: 60 },+ ]).slidRegionIds,+ ).toEqual([]);+ });+ });+describe("restoreFullTimeline", () => {it("sets a single interval spanning the full duration", () => {const doc = makeDoc({diff --git a/src/lib/ai-edition/document/timeline.ts b/src/lib/ai-edition/document/timeline.tsindex d8f85a7ac..0e80fe523 100644--- a/src/lib/ai-edition/document/timeline.ts+++ b/src/lib/ai-edition/document/timeline.ts@@ -300,48 +300,52 @@ export function rederiveRegionMs(document: AxcutDocument, clips: AxcutClip[]): A}const clip = clipById.get(region.clipId);if (!clip) return [];- let { sourceStartSec, sourceEndSec } = region;- // Only clamp against a real, probed window — an unprobed clip has- // `sourceEndSec` at/below `sourceStartSec` and must not shave its fragments.- if (clip.sourceEndSec !== undefined && clip.sourceEndSec > clip.sourceStartSec) {- sourceStartSec = Math.max(sourceStartSec, clip.sourceStartSec);- sourceEndSec = Math.min(sourceEndSec, clip.sourceEndSec);- if (sourceEndSec - sourceStartSec <= REGION_WINDOW_EPSILON_SEC) return [];- }- const span = anchoredToRawSpanSec(- { clipId: region.clipId, sourceStartSec, sourceEndSec },- clips,- );- if (!span) return [];- return [- {- ...region,- sourceStartSec,- sourceEndSec,- startMs: Math.round(span.startSec * 1000),- endMs: Math.round(span.endSec * 1000),- },- ];+ return rederiveAnchoredRegion(region, clip, clips);}),);}-/**- * Re-anchor every modifier against a REBUILT clip layout. `replaceTimeline` mints- * brand-new clip identities, so existing anchors point at clips that no longer exist;- * we re-ventilate each region from its current RAW ms (which still describe where it- * sits on the ruler) and rebuild the anchor. Fragments of one region need no shared- * marker to keep reading as a single pill: equal properties + adjacency suffice.- */-export function reanchorRegions(document: AxcutDocument, clips: AxcutClip[]): AxcutDocument {- if (clips.length === 0) return document;- return mapAllRegionCollections(- document,- (regions, prefix) =>- anchorRegionsWithDerivedMs(regions, clips, () => createId(prefix)) as StoredRegion[],- );+/** One region's share of {@link rederiveRegionMs}: clamp it to its clip's current+ * source window, drop it when nothing survives, refresh its derived ms. Extracted+ * so `replaceTimeline` can apply it to the regions whose clip SURVIVED while+ * re-anchoring only the orphans — a rebuild used to re-anchor everything, which+ * moved anchored regions onto whatever content had slid under their ruler+ * position. Same body as before, one region at a time. */+function rederiveAnchoredRegion<+ T extends StoredRegion & { clipId: string; sourceStartSec: number; sourceEndSec: number },+>(region: T, clip: AxcutClip, clips: AxcutClip[]): T[] {+ let { sourceStartSec, sourceEndSec } = region;+ // Only clamp against a real, probed window — an unprobed clip has+ // `sourceEndSec` at/below `sourceStartSec` and must not shave its fragments.+ if (clip.sourceEndSec !== undefined && clip.sourceEndSec > clip.sourceStartSec) {+ sourceStartSec = Math.max(sourceStartSec, clip.sourceStartSec);+ sourceEndSec = Math.min(sourceEndSec, clip.sourceEndSec);+ if (sourceEndSec - sourceStartSec <= REGION_WINDOW_EPSILON_SEC) return [];+ }+ const span = anchoredToRawSpanSec({ clipId: region.clipId, sourceStartSec, sourceEndSec }, clips);+ if (!span) return [];+ return [+ {+ ...region,+ sourceStartSec,+ sourceEndSec,+ startMs: Math.round(span.startSec * 1000),+ endMs: Math.round(span.endSec * 1000),+ },+ ];}+// ponytail: `reanchorRegions` used to live here — re-ventilate EVERY modifier+// from its RAW ruler ms after a rebuild, on the premise that `replaceTimeline`+// minted brand-new clip identities so no anchor could survive. It no longer+// does, and the premise was the bug: a region's ruler position is where it is+// DRAWN, its anchor is what it is ABOUT, and re-deriving the second from the+// first moves it onto whatever footage slid underneath (measured: a zoom on+// source 40–45 came back on 45–50). What is left of it is the orphan branch of+// `reconcileRegionsAfterReplace`, which is the only case where the ruler really+// is the last thing we know. Deleted rather than left exported: a dead helper+// that does the wrong thing is an invitation.+/** A clip that does not yet describe a real stretch of media: either it carries no* source extent at all (what `migrateProjectDataToAxcutDocument` produces — the* migration is pure, so it cannot probe the file for a duration), or it still sits at@@ -427,41 +431,308 @@ export function applyProbedDuration();}+/** One interval of a rebuilt timeline, plus the identity it inherits. `keepClipId`+ * is set when the CALLER'S raw interval is (to the epsilon) an existing clip's own+ * source window: the same stretch of media, so the same clip. */+export interface TimelineReplacementSlot {+ interval: Interval;+ keepClipId: string | null;+}++/**+ * What a {@link replaceTimeline} would cost, computed before anything is applied.+ *+ * ponytail: this exists because `replaceTimeline` is the one tool an agent+ * reaches for when it cannot find a better one, and until now it answered+ * `ok: true` to requests it had silently mangled. Three mechanisms, all of them+ * invisible from the outside:+ * • `normalizeIntervals` SORTS, so a reorder request ([30-60], [0-30]) comes+ * back in ascending order and the swap simply does not happen;+ * • it also MERGES adjacent intervals, so handing back the timeline's own+ * intervals collapsed two clips into one — the identity call was destructive;+ * • the complement replaced `trimRanges` wholesale, so a cut the user made+ * inside a kept interval disappeared with no mention anywhere.+ * The plan names each of those so the caller can refuse with something the model+ * can act on. It is computed on the RAW intervals, because that is the last point+ * at which the caller's INTENT (the order they asked for) is still legible.+ */+export interface TimelineReplacementPlan {+ assetId: string;+ /** The intervals the rebuild would produce, in timeline order. */+ slots: TimelineReplacementSlot[];+ /** The raw intervals were not in ascending order: the caller meant to+ * REORDER. This operation cannot — see {@link moveClip}. */+ reorderRequested: boolean;+ /** Clips that would cease to exist: merged with a neighbour, shortened,+ * dropped, or belonging to another asset (a rebuild only lays out the+ * primary one). */+ lostClipIds: string[];+ /** Trims whose id would disappear because the span they cut now falls+ * entirely outside the kept intervals. The CUT survives — that stretch is+ * excluded anyway — only the id and its reason are lost. */+ absorbedTrimIds: string[];+ /** Trims that would be narrowed to their surviving overlap. */+ clippedTrimIds: string[];+ /** Modifiers anchored to a clip in `lostClipIds`. They are re-ventilated from+ * their RULER position, which is not the same as their content: they land on+ * whatever footage moved under them. */+ slidRegionIds: string[];+}++function intervalsIntersect(a: Interval, b: Interval): Interval | null {+ const startSec = Math.max(a.startSec, b.startSec);+ const endSec = Math.min(a.endSec, b.endSec);+ return endSec - startSec > REGION_WINDOW_EPSILON_SEC ? { startSec, endSec } : null;+}++function sameInterval(a: Interval, b: Interval): boolean {+ return (+ Math.abs(a.startSec - b.startSec) <= REGION_WINDOW_EPSILON_SEC &&+ Math.abs(a.endSec - b.endSec) <= REGION_WINDOW_EPSILON_SEC+ );+}++/** Every anchored modifier of the document, all four families, as `{id, clipId}`. */+function anchoredRegionsOf(document: AxcutDocument): Array<{ id: string; clipId: string }> {+ const legacy = document.legacyEditor as Record<string, unknown> | null;+ const collections: StoredRegion[][] = [+ document.zoomRanges as unknown as StoredRegion[],+ document.annotations as unknown as StoredRegion[],+ (legacy?.speedRegions as StoredRegion[] | undefined) ?? [],+ (legacy?.cameraFullscreenRegions as StoredRegion[] | undefined) ?? [],+ ];+ return collections+ .flat()+ .filter(isAnchored)+ .map((region) => ({ id: region.id, clipId: region.clipId }));+}++export function planTimelineReplacement(+ document: AxcutDocument,+ intervals: Interval[],+): TimelineReplacementPlan {+ const assetId = document.project.primaryAssetId ?? document.assets[0]?.id ?? "";+ const duration = primaryAssetDuration(document);+ const bounded = intervals+ .map((item) => ({+ startSec: Math.max(0, Math.min(duration, item.startSec)),+ endSec: Math.max(0, Math.min(duration, item.endSec)),+ }))+ .filter((item) => item.endSec > item.startSec);++ // Read the intent BEFORE sorting: after `byStart` there is nothing left to see.+ const reorderRequested = bounded.some(+ (item, index) => index > 0 && item.startSec < bounded[index - 1].startSec,+ );++ const clips = document.timeline.clips;+ const claimed = new Set<string>();+ const matchClip = (interval: Interval): string | null => {+ const hit = clips.find(+ (clip) =>+ !claimed.has(clip.id) &&+ clip.assetId === assetId &&+ clip.sourceEndSec !== undefined &&+ sameInterval({ startSec: clip.sourceStartSec, endSec: clip.sourceEndSec }, interval),+ );+ if (!hit) return null;+ claimed.add(hit.id);+ return hit.id;+ };++ const slots: TimelineReplacementSlot[] = [];+ for (const interval of [...bounded].sort(byStart)) {+ const keepClipId = matchClip(interval);+ const last = slots.at(-1);+ const overlaps = last+ ? interval.startSec < last.interval.endSec - REGION_WINDOW_EPSILON_SEC+ : false;+ const touches = last+ ? Math.abs(interval.startSec - last.interval.endSec) <= REGION_WINDOW_EPSILON_SEC+ : false;+ // Overlapping intervals MUST merge — clips may not overlap. Merely ADJACENT+ // ones merge only when neither side is a clip we could keep, which is the+ // one place this differs from `normalizeIntervals`: merging [0,30] and+ // [30,60] when both name an existing clip is precisely how the identity+ // rebuild destroyed a two-clip timeline.+ if (last && (overlaps || (touches && !last.keepClipId && !keepClipId))) {+ last.interval = {+ startSec: last.interval.startSec,+ endSec: Math.max(last.interval.endSec, interval.endSec),+ };+ if (overlaps) last.keepClipId = null;+ continue;+ }+ slots.push({ interval: { ...interval }, keepClipId });+ }++ const kept = new Set(slots.map((slot) => slot.keepClipId).filter((id): id is string => !!id));+ const lostClipIds = clips.filter((clip) => !kept.has(clip.id)).map((clip) => clip.id);+ const slidRegionIds = anchoredRegionsOf(document)+ .filter((region) => !kept.has(region.clipId))+ .map((region) => region.id);++ const keptIntervals = slots.map((slot) => slot.interval);+ const absorbedTrimIds: string[] = [];+ const clippedTrimIds: string[] = [];+ for (const trim of document.timeline.trimRanges) {+ if (trim.assetId !== assetId) continue;+ const pieces = keptIntervals+ .map((slot) => intervalsIntersect(slot, { startSec: trim.startSec, endSec: trim.endSec }))+ .filter((piece): piece is Interval => piece !== null);+ if (pieces.length === 0) absorbedTrimIds.push(trim.id);+ else if (pieces.length > 1 || !sameInterval(pieces[0], trim)) clippedTrimIds.push(trim.id);+ }++ return {+ assetId,+ slots,+ reorderRequested,+ lostClipIds,+ absorbedTrimIds,+ clippedTrimIds,+ slidRegionIds,+ };+}++export interface ReplaceTimelineOptions {+ /** Reuse the id / origin / reason / wordRefs of a clip whose source window a+ * kept interval reproduces exactly. Default true — a rebuild that happens to+ * keep a stretch of media keeps the clip that WAS that stretch of media. */+ preserveIds?: boolean;+ /** Carry the primary asset's existing cuts through the rebuild (narrowed to+ * the kept intervals). Default true. `restoreFullTimeline` is the one caller+ * whose whole point is to drop them. */+ preserveTrims?: boolean;+}+export function replaceTimeline(document: AxcutDocument,intervals: Interval[],reason: string,origin: "system" | "agent" | "user" = "user",+ options: ReplaceTimelineOptions = {},): AxcutDocument {const assetId = document.project.primaryAssetId ?? document.assets[0]?.id;if (!assetId) {throw new Error("Cannot update timeline without a primary asset.");}+ const preserveIds = options.preserveIds !== false;+ const preserveTrims = options.preserveTrims !== false;const duration = primaryAssetDuration(document);- const normalized = normalizeIntervals(duration, intervals);- const clips = buildTimelineFromIntervals(assetId, normalized, {- origin,- reason,- transcript: document.transcript,+ const plan = planTimelineReplacement(document, intervals);+ const clipById = new Map(document.timeline.clips.map((clip) => [clip.id, clip]));++ let cursor = 0;+ const clips: AxcutClip[] = plan.slots.map((slot, index) => {+ const length = slot.interval.endSec - slot.interval.startSec;+ const timelineStartSec = cursor;+ cursor += length;+ const existing = preserveIds && slot.keepClipId ? clipById.get(slot.keepClipId) : undefined;+ return {+ // ponytail: a slot with no ancestor gets a MINTED id, not `clip_${i+1}`.+ // Positional ids are what let `trim_1` survive a rebuild while meaning a+ // different cut, and mixing them with preserved ids would collide outright+ // (a preserved `clip_1` sitting at index 1). The legacy positional naming+ // survives only on the `preserveIds: false` path, which rebuilds from nothing.+ id: existing?.id ?? (preserveIds ? createId("clip") : `clip_${index + 1}`),+ assetId,+ sourceStartSec: slot.interval.startSec,+ sourceEndSec: slot.interval.endSec,+ timelineStartSec,+ timelineEndSec: timelineStartSec + length,+ wordRefs:+ existing?.wordRefs ??+ collectWordRefs(document.transcript, slot.interval.startSec, slot.interval.endSec),+ origin: existing?.origin ?? origin,+ reason: existing?.reason ?? reason,+ };});- const trimRanges = invertIntervals(normalized, duration).map((cut, i) => ({- id: `trim_${i + 1}`,++ const keptIntervals = plan.slots.map((slot) => slot.interval);+ const complement = invertIntervals(keptIntervals, duration).map((cut, index) => ({+ id: preserveIds ? createId("trim") : `trim_${index + 1}`,assetId,startSec: cut.startSec,endSec: cut.endSec,origin,reason,}));+ // Other assets' cuts are NEVER this operation's business — the rebuild only+ // lays out the primary asset. Replacing `trimRanges` wholesale wiped them, the+ // same bug `operations.ts` had already had to fix for `add_trim_range`.+ const foreignTrims = document.timeline.trimRanges.filter((trim) => trim.assetId !== assetId);+ const survivingTrims = preserveTrims+ ? document.timeline.trimRanges.flatMap((trim) => {+ if (trim.assetId !== assetId) return [];+ return keptIntervals+ .map((slot) => intervalsIntersect(slot, { startSec: trim.startSec, endSec: trim.endSec }))+ .filter((piece): piece is Interval => piece !== null)+ .map((piece, index) => ({+ ...trim,+ id: index === 0 ? trim.id : createId("trim"),+ startSec: piece.startSec,+ endSec: piece.endSec,+ }));+ })+ : [];+const next: AxcutDocument = {...document,timeline: {...document.timeline,clips,- trimRanges,+ trimRanges: [...foreignTrims, ...survivingTrims, ...complement].sort(byStart),gaps: [],},};- return reanchorRegions(next, clips);+ return reconcileRegionsAfterReplace(next, clips, new Set(clips.map((clip) => clip.id)));+}++/**+ * Regions after a rebuild, by provenance — the fix for the quietest half of+ * D-DESTRUCT.+ *+ * The old code ran `reanchorRegions` over everything, which re-ventilates each+ * region from its RAW ruler ms. That is right for a region whose clip is gone+ * (its ruler position is all that is left of it) and wrong for one whose clip+ * survived: with the intervals [35-60], [0-25], a zoom anchored to clip_2 at+ * source 40-45 came back anchored at source 50-55. Ten seconds into different+ * footage, schema-valid, unreported. Anything whose anchor still resolves is+ * therefore rederived — the anchor IS the content — and only the orphans are+ * re-ventilated.+ *+ * The orphan branch also has to decide what "re-ventilation found nothing"+ * means, and the answer depends on where the region came from.+ * `anchorRegionsWithDerivedMs` passes such a region through UNCHANGED, which is+ * right for a never-anchored one (a v2 migration keeps a region it cannot place+ * rather than losing user data) and wrong for one whose clip was just deleted:+ * that leaves it pointing at an id nothing resolves, invisible to the timeline+ * and revivable by any future clip that happens to take the name. Its content+ * is gone, so it goes with it — the same call `removeClip` and+ * `setClipSourceRange` already make through `rederiveRegionMs`.+ */+function reconcileRegionsAfterReplace(+ document: AxcutDocument,+ clips: AxcutClip[],+ surviving: Set<string>,+): AxcutDocument {+ if (clips.length === 0) return document;+ const clipById = new Map(clips.map((clip) => [clip.id, clip]));+ return mapAllRegionCollections(document, (regions, prefix) =>+ regions.flatMap((region) => {+ if (isAnchored(region) && surviving.has(region.clipId)) {+ const clip = clipById.get(region.clipId);+ if (clip) return rederiveAnchoredRegion(region, clip, clips);+ }+ const reventilated = anchorRegionsWithDerivedMs([region], clips, () =>+ createId(prefix),+ ) as StoredRegion[];+ const placed = reventilated.some((next) => isAnchored(next) && surviving.has(next.clipId));+ if (placed) return reventilated;+ return isAnchored(region) ? [] : reventilated;+ }),+ );}// ponytail: reorder an existing clip by removing it from its current@@ -640,5 +911,18 @@ export function removeClip(document: AxcutDocument, clipId: string): AxcutDocumeexport function restoreFullTimeline(document: AxcutDocument): AxcutDocument {const duration = primaryAssetDuration(document);if (duration <= 0) return document;- return replaceTimeline(document, [{ startSec: 0, endSec: duration }], "Restore full timeline");+ // ponytail: the ONE caller whose semantics are "put it all back": a single+ // clip covering the whole asset and not a single cut left. `replaceTimeline`+ // preserves ids and trims by default now, which would quietly turn "restore"+ // into "keep everything you already had" — the opposite of the button.+ return replaceTimeline(+ document,+ [{ startSec: 0, endSec: duration }],+ "Restore full timeline",+ "user",+ {+ preserveIds: false,+ preserveTrims: false,+ },+ );}diff --git a/src/lib/ai-edition/schema/index.ts b/src/lib/ai-edition/schema/index.tsindex 506b1fb81..03810b907 100644--- a/src/lib/ai-edition/schema/index.ts+++ b/src/lib/ai-edition/schema/index.ts@@ -290,7 +290,13 @@ export const timelineOperationSchema = z.discriminatedUnion("type", [type: z.literal("move_clip"),reason: z.string().default(""),clipId: z.string().min(1),- timelineStartSec: z.number().nonnegative(),+ // ponytail: `insertIndex`, matching the ONE implementation+ // (`AxcutTimelineOperation` in document/operations.ts, applied by+ // `applyTimelineOperation`). This schema declared `timelineStartSec`+ // instead — a second, incompatible contract for the same op name, with no+ // importer anywhere to notice. Whoever wired the two together next would+ // have had a parse that accepted what the dispatcher could not run.+ insertIndex: z.number().int().nonnegative(),}),z.object({type: z.literal("insert_asset_clip"),diff --git a/src/lib/ai-edition/timeline/zoom-scale.test.ts b/src/lib/ai-edition/timeline/zoom-scale.test.tsnew file mode 100644index 000000000..809d44f85--- /dev/null+++ b/src/lib/ai-edition/timeline/zoom-scale.test.ts@@ -0,0 +1,65 @@+// The depth→scale table is now read by three consumers that used to each carry+// their own idea of it: the renderer, the native compositor, and the agent's+// tool descriptions. These tests pin the two properties that made the copies+// disagree — the mapping is NOT linear, and `customScale` wins but is clamped.++import { describe, expect, it } from "vitest";+import { getZoomScale, ZOOM_DEPTH_SCALES } from "@/components/video-editor/types";+import {+ effectiveZoomScale,+ MAX_ZOOM_SCALE,+ MIN_ZOOM_SCALE,+ ZOOM_DEPTH_LEGEND,+} from "./zoom-scale";++describe("effectiveZoomScale", () => {+ it("maps each depth to the table, which is not depth/2 + 0.5", () => {+ expect(effectiveZoomScale({ depth: 1 })).toBe(1.25);+ expect(effectiveZoomScale({ depth: 3 })).toBe(1.8);+ expect(effectiveZoomScale({ depth: 6 })).toBe(5.0);+ // The formula the agent's descriptions advertised for a release. It agrees+ // with the table at depth 2 and nowhere else — which is why "depth 3 ≈ 2.0×"+ // read plausibly while the pill showed 1.80×.+ const claimed = (depth: number) => depth / 2 + 0.5;+ const agreeing = ([1, 2, 3, 4, 5, 6] as const).filter(+ (d) => Math.abs(claimed(d) - ZOOM_DEPTH_SCALES[d]) < 0.001,+ );+ expect(agreeing).toEqual([2]);+ });++ it("prefers customScale over the depth", () => {+ expect(effectiveZoomScale({ depth: 6, customScale: 1.1 })).toBe(1.1);+ });++ it("clamps customScale into the range the renderer can produce", () => {+ // `zoomRegionSchema` accepts any positive number, so both of these are+ // documents that exist.+ expect(effectiveZoomScale({ depth: 3, customScale: 12 })).toBe(MAX_ZOOM_SCALE);+ expect(effectiveZoomScale({ depth: 3, customScale: 0.2 })).toBe(MIN_ZOOM_SCALE);+ });++ it("falls back to the depth when customScale is not a number the renderer can use", () => {+ expect(effectiveZoomScale({ depth: 4, customScale: Number.NaN })).toBe(2.2);+ });++ it("is exactly what the renderer's getZoomScale re-exports", () => {+ // types.ts re-exports rather than redefining: the split exists only because+ // the Electron main process cannot resolve the `@/` alias the renderer file+ // uses, and it must not become a second table.+ for (const depth of [1, 2, 3, 4, 5, 6] as const) {+ expect(getZoomScale({ depth })).toBe(effectiveZoomScale({ depth }));+ }+ expect(getZoomScale({ depth: 1, customScale: 9 })).toBe(+ effectiveZoomScale({ depth: 1, customScale: 9 }),+ );+ });+});++describe("ZOOM_DEPTH_LEGEND", () => {+ it("is derived from the table, in depth order", () => {+ expect(ZOOM_DEPTH_LEGEND).toBe("1=1.25×, 2=1.50×, 3=1.80×, 4=2.20×, 5=3.50×, 6=5.00×");+ for (const depth of [1, 2, 3, 4, 5, 6] as const) {+ expect(ZOOM_DEPTH_LEGEND).toContain(`${depth}=${ZOOM_DEPTH_SCALES[depth].toFixed(2)}×`);+ }+ });+});diff --git a/src/lib/ai-edition/timeline/zoom-scale.ts b/src/lib/ai-edition/timeline/zoom-scale.tsnew file mode 100644index 000000000..fe0bef88a--- /dev/null+++ b/src/lib/ai-edition/timeline/zoom-scale.ts@@ -0,0 +1,75 @@+// The one place that answers "how much bigger will the picture actually be?".+//+// ponytail: this table used to live in `src/components/video-editor/types.ts`,+// which reaches its own imports through the `@/` alias. That alias is declared+// on the ROOT vite config (`vite.config.ts:45`), not on the main-process build+// (`main.vite.build` is `{}`), and nothing under `electron/` uses it — so the+// agent layer physically could not import the renderer's scale table without+// risking a main-process bundle that typechecks and then fails to resolve. The+// table now lives here, on the relative-import side of that fence, and+// `types.ts` re-exports it so every existing renderer importer is unaffected.+//+// Why it matters that there is exactly ONE table: `depth` is an ORDINAL, and+// three separate places had each invented their own factor for it. The agent's+// tool descriptions claimed "depth 1–6 maps to 1.0×–3.5×" (the formula+// `depth/2 + 0.5`), the compositor's scene description carried that same+// formula until it was corrected, and the pill on screen has always read the+// table below. Wrong at both ends: the range is 1.25×–5.0×, it is not linear,+// and the default depth 3 renders at 1.80× — not the "2.0×" the agent was told+// to report, and certainly not the "3×" a model reads off a bare ordinal.++export type ZoomDepth = 1 | 2 | 3 | 4 | 5 | 6;++export const ZOOM_DEPTH_SCALES: Record<ZoomDepth, number> = {+ 1: 1.25,+ 2: 1.5,+ 3: 1.8,+ 4: 2.2,+ 5: 3.5,+ 6: 5.0,+};++export const MIN_ZOOM_SCALE = 1.0;+export const MAX_ZOOM_SCALE = 5.0;++export const DEFAULT_ZOOM_DEPTH: ZoomDepth = 3;++/** Everything `effectiveZoomScale` reads. Deliberately structural, so a stored+ * zoom region, a UI region and a hand-written `{ depth }` all satisfy it. */+export interface ZoomScaleInput {+ depth: ZoomDepth;+ /** Custom scale overriding the preset depth. When set, `depth` is inert. */+ customScale?: number;+}++/**+ * The scale the viewer will actually see: `customScale` when present (clamped+ * to the renderer's range), otherwise the preset for `depth`.+ *+ * The clamp is part of the answer, not decoration: `zoomRegionSchema` only+ * requires `customScale` to be positive, so a document can legally carry+ * `customScale: 12`. Anything that reads the raw field instead of calling this+ * renders a different picture from the preview.+ */+export function effectiveZoomScale(region: ZoomScaleInput): number {+ if (region.customScale != null) {+ const clamped = Math.max(MIN_ZOOM_SCALE, Math.min(MAX_ZOOM_SCALE, region.customScale));+ if (Number.isFinite(clamped)) return clamped;+ }+ return ZOOM_DEPTH_SCALES[region.depth];+}++/**+ * The depth→scale table as one line of prose, for the tool descriptions handed+ * to the model.+ *+ * ponytail: DERIVED, never retyped. The previous copy was a hand-written+ * "1.0×–3.5×" that outlived the mapping it described by an unknown number of+ * releases, and the model dutifully repeated it to users. Anyone changing the+ * table above now changes the prompt in the same edit.+ */+export const ZOOM_DEPTH_LEGEND = (Object.keys(ZOOM_DEPTH_SCALES) as unknown as ZoomDepth[])+ .map((key) => Number(key) as ZoomDepth)+ .sort((a, b) => a - b)+ .map((depth) => `${depth}=${ZOOM_DEPTH_SCALES[depth].toFixed(2)}×`)+ .join(", ");diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.tsindex 7fbb49129..f8206e11e 100644--- a/src/native/sceneDescription.test.ts+++ b/src/native/sceneDescription.test.ts@@ -399,6 +399,25 @@ describe("buildSceneDescription.zoomRegions", () => {expect(zoomRegions[0].scale).toBe(1.25);});+ it("clamps a customScale the schema lets through, exactly like the UI", () => {+ // `zoomRegionSchema` only requires `customScale` to be positive, so+ // `customScale: 12` is a legal document. This line read the raw field and+ // skipped the [1.0, 5.0] clamp `getZoomScale` applies — the web preview+ // rendered 5× and the native compositor 12×, for the same document. Same+ // class of disagreement as the formula above, one storey down.+ const z = makeZoom({+ id: "z",+ startMs: 0,+ endMs: 1000,+ depth: 3,+ focus: { cx: 0.5, cy: 0.5 },+ customScale: 12,+ });+ const { zoomRegions } = buildSceneDescription(makeDoc({ zoomRanges: [z] }));+ expect(zoomRegions[0].scale).toBe(5);+ expect(zoomRegions[0].scale).toBe(getZoomScale({ depth: 3, customScale: 12 }));+ });+it("depth 6 → the table's scale", () => {const z = makeZoom({ id: "z", startMs: 0, endMs: 1000, depth: 6, focus: { cx: 0.5, cy: 0.5 } });const doc = makeDoc({ zoomRanges: [z] });diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.tsindex 93e36a283..4aa13987c 100644--- a/src/native/sceneDescription.ts+++ b/src/native/sceneDescription.ts@@ -16,7 +16,7 @@*/import type { CameraFullscreenRegion, SpeedRegion } from "@/components/video-editor/types";-import { DEFAULT_CROP_REGION, ZOOM_DEPTH_SCALES } from "@/components/video-editor/types";+import { DEFAULT_CROP_REGION, getZoomScale } from "@/components/video-editor/types";import { annotationFontSizeFraction } from "@/lib/ai-edition/annotationScale";import {captionCuesToTextRegions,@@ -693,7 +693,13 @@ export function buildSceneDescription(// bien que la fenêtre source s'arrêtait 2.78 % avant le bord — 53 px sur 1920// définitivement hors d'atteinte, gimbal à fond dans le coin. Le symptôme rapporté :// « le zoom coupe les bords extérieurs ».- scale: region.customScale ?? ZOOM_DEPTH_SCALES[region.depth],+ //+ // ponytail: et c'est `getZoomScale` en entier, pas la table seule. La ligne+ // lisait `region.customScale ?? ZOOM_DEPTH_SCALES[depth]`, donc sans le clamp+ // [1.0, 5.0] que l'UI applique. Or `zoomRegionSchema` n'exige de `customScale`+ // que d'être positif : un document portant `customScale: 12` est valide, rendait+ // 5× dans l'aperçu web et 12× ici. Même désaccord que ci-dessus, un cran plus bas.+ scale: getZoomScale(region),focusX: region.focus.cx,focusY: region.focus.cy,// The global Auto-Focus toggle OVERRIDES each region's own mode rather than merelydiff --git a/technical-documentation/architecture/ai-agent.md b/technical-documentation/architecture/ai-agent.mdindex 7489f8432..47634129d 100644--- a/technical-documentation/architecture/ai-agent.md+++ b/technical-documentation/architecture/ai-agent.md@@ -37,31 +37,33 @@ sequenceDiagramChat-->>User: Streamed answer, tool summaries, and updated document```-OpenScreen does not override `createDeepAgent`'s recursion limit, so the installed deep-agent runtime's default cap is 10 model/tool iterations for a turn.+The agent is built with LangChain's `createAgent`, not `deepagents`' `createDeepAgent`, and pins `recursionLimit: 1000` explicitly. `createAgent` alone would fall back to LangGraph's default of 25 steps, which an auto-enhance pass placing one trim per silence exceeds without difficulty.## Tool schema-The model never free-writes the project document. It can only call the fixed tool set declared in `agent-tools.ts`; the executor parses JSON, validates arguments with Zod, and returns either a new schema-valid snapshot or an error. The tools operate on the same [document model](document-model.md) as manual editing.+The model never free-writes the project document. It can only call the fixed set of 19 tools built by `deep-agent/service.ts#buildTools`, described by `TOOL_DESCRIPTIONS` in the same file and validated against the Zod argument schemas in `agent-tools.ts`; the executor parses JSON, validates arguments, and returns either a new schema-valid snapshot or an error. Those three surfaces (descriptions, built tools, executor cases) are pinned to one another by `deep-agent/service.test.ts` — an earlier fourth surface, `AGENT_TOOL_SPECS`, described the tools in JSON Schema for a provider it had stopped reaching, and drifted. The tools operate on the same [document model](document-model.md) as manual editing.| Tool | What it does | What it mutates ||---|---|---|-| `getCurrentDocument` | Reads a compact project, asset, clip, trim, and modifier snapshot with explicit time bases. | Nothing. |+| `getCurrentDocument` | Reads a compact project, asset, clip, trim, and modifier snapshot with explicit time bases. Each asset reports `hasCameraTrack` / `cameraVisible` / `hasCursorTelemetry` beside `hasTranscript` (`hasCursorTelemetry` is three-valued: `true`, `false` when the asset was checked and has none, `null` when it was not checked — never `false` for something we failed to look at), the document reports `hasAnyCamera` and `autoFocusAll`, and each zoom reports the `renderedScale` the viewer will see plus `customScale` / `depthIsOverridden` when a custom scale makes its `depth` inert. | Nothing. || `getTranscript` | Reads up to 800 transcript segments for an asset or the primary asset. | Nothing. |+| `getCursorTrack` | Reads the recorded pointer telemetry for an asset as a DIGEST: the moments the cursor sat still or clicked, each with its hold, its average position, its click count, its source time and the `virtualSec` that `addZoom` takes — never the raw samples. Answers `available:false` with `reason:"no-sidecar"` (checked, this asset has none) or `reason:"unavailable"` (could not be read from here), and the two are never conflated. | Nothing. || `addTrim` | Adds a source-time cut inside a clip. | `timeline.trimRanges`. || `setTrim` | Moves or resizes an existing source-time trim. | The matching `timeline.trimRanges` entry. || `setClipRange` | Changes a clip's source in/out points and relays clips back-to-back. | The clip range and any anchored regions clamped or removed by the shared timeline mutator. |-| `replaceTimeline` | Rebuilds the primary-asset timeline from kept source-time intervals; refuses to discard user-placed clips. | Timeline clips and trim ranges. |-| `addZoom` | Adds a clip-anchored zoom over virtual timeline time. | `zoomRanges`. |-| `setZoom` | Moves, resizes, or restyles a zoom pill. | The clip-anchored `zoomRanges` fragments represented by that pill. |+| `moveClip` | Reorders a placed clip by naming the clip it should play before (`null` = last). Preserves every clip id, source range, trim and anchored modifier. | Timeline clip order; anchored modifiers' derived ms follow their clip. |+| `replaceTimeline` | Rebuilds the primary-asset timeline from kept source-time intervals. Preserves the id, origin and label of every clip an interval reproduces exactly, carries existing trims through, and never touches another asset's trims. Refused when it would merge away, shorten or drop a clip, or when the intervals are not ascending (a reorder it cannot perform — the refusal points at `moveClip`). | Timeline clips and trim ranges. |+| `addZoom` | Adds a clip-anchored zoom over virtual timeline time. `depth` is an ordinal selecting from `ZOOM_DEPTH_SCALES` (1.25×–5.0×, non-linear); the result reports the resulting `renderedScale`. | `zoomRanges`. |+| `setZoom` | Moves, resizes, or restyles a zoom pill. Changing `depth` clears any `customScale` on that pill — otherwise the write is a no-op at render — and says so in the result. | The clip-anchored `zoomRanges` fragments represented by that pill. || `addSpeed` | Adds a clip-anchored speed region over virtual timeline time. | `legacyEditor.speedRegions`. || `setSpeed` | Moves, resizes, or changes an existing speed pill. | The corresponding `legacyEditor.speedRegions` fragments. || `addAnnotation` | Adds a positioned text annotation over virtual timeline time. | `annotations`. || `setAnnotation` | Moves, resizes, or changes an annotation's text. | The corresponding clip-anchored `annotations` fragments. |-| `addCameraFullscreen` | Adds a camera-fullscreen region over virtual timeline time. | `legacyEditor.cameraFullscreenRegions`. |-| `setCameraFullscreen` | Moves or resizes a camera-fullscreen pill. | The corresponding `legacyEditor.cameraFullscreenRegions` fragments. |+| `addCameraFullscreen` | Adds a camera-fullscreen region over virtual timeline time; refused when no clip under the span comes from an asset with a linked `cameraTrack`, since such a region can only render nothing. | `legacyEditor.cameraFullscreenRegions`. |+| `setCameraFullscreen` | Moves or resizes a camera-fullscreen pill, under the same camera requirement as `addCameraFullscreen`. | The corresponding `legacyEditor.cameraFullscreenRegions` fragments. || `removeTrim` | Deletes a trim so its source span plays and exports again. | `timeline.trimRanges`. || `removeModifier` | Resolves and deletes a zoom, speed, annotation, or camera-fullscreen modifier by ID. | The matching modifier collection. |-| `removeClip` | Deletes a placed clip, closes the gap, and drops effects anchored only to it. | Timeline clips and affected anchored modifiers. |+| `removeClip` | Deletes a placed clip, closes the gap, and drops effects anchored only to it. The result names the modifiers and trims it took with it. | Timeline clips and affected anchored modifiers. |Clips and trims use source time. Zoom, speed, annotation, and camera-fullscreen tools use virtual edited-timeline time; the executor converts these spans to the clip-anchored millisecond representation used by the document.@@ -84,5 +86,7 @@ Chat sessions and checkpoints live only in nested process-memory `Map` objects i## Known gaps- Chat sessions and message checkpoints have no durable persistence.-- `allowAgentEdits` is exposed in provider settings, but `chat-service.ts` only reads it; the deep-agent tool list and mutating executor do not enforce it. There is therefore no working confirmation or permission gate before write tools.+- `allowAgentEdits` has no per-turn approval channel. When it is off the agent reads freely, is told by its system prompt to state the edit and ask, and has every write refused by `executeAgentTool` with a `consent_required` payload; the returned document is withheld as well. But there is no way for the user to answer "yes, go ahead" for one turn — they have to re-enable the setting in Settings → AI, which is what the refusal tells the model to say.+- Cursor telemetry is read through an injected `CursorTelemetryReader` (`electron/ipc/handlers.ts` builds the only production one, behind `resolveApprovedVideoPath`). A runtime with no reader wired answers `reason: "unavailable"` on every call and reports `hasCursorTelemetry: null` — honest, and useless. There is no cache: a turn probes each asset's sidecar once and reads it in full only if the model asks.+- The digest reports dwells and click counts, not the raw samples, and `readCursorSidecar`'s normalizer flattens `double-click` / `right-click` / `middle-click` to `move` before the digest sees them, so those clicks are currently invisible. The digest already counts the wide union; the narrowing is upstream, in `CursorRecordingSample`.- The deep-agent instance is rebuilt for every turn without a LangGraph checkpointer, so stateful agent threads do not persist independently of the explicit chat history.