Skip to content

Commit 4e9059a

Browse files
feat(cli): add agent timeline workflows (#4241)
* feat(cli): add timeline agent mutation commands * fix(cli): type timeline a2 mutations * style(cli): format timeline a2 commands * test(cli): cover timeline a2 verbs * test(cli): assert ids keep named refs * refactor: centralize timeline duplicate mutation * fix(cli): narrow set assignment field * style(cli): format timeline mutation exports * refactor(cli): split apply plan decisions * fix(cli): tag apply plan refusals * refactor(cli): move A2 runners beside timeline helpers * fix(cli): remove stale A2 imports * style(cli): format A2 command module * fix(cli): avoid A2 command import cycle * refactor(cli): isolate shared timeline mutation logic * fix(cli): restore timeline mutation command factory * fix(cli): remove stale command-surface remnants * fix(cli): complete shared timeline support extraction * fix(cli): close shared conflict helper * fix(cli): import shared timeline formatter * style(cli): format shared mutation runner * refactor(cli): split mutation command orchestration * fix(cli): keep shared mutation primitives in support module * fix(cli): use shared mutation support helpers * refactor(cli): centralize A2 refusals * style(cli): format A2 refusal helpers * fix(cli): clean shared A2 imports * fix(cli): make A2 runner imports explicit * refactor(cli): isolate apply plan target validation * fix(cli): tag prepared plan edits * style(cli): format plan target helper * fix(cli): validate sequential plans and duplicate ids * test(cli): account for stamped composition id * fix(studio): stamp ids on patched html * fix(studio): preserve no-op patch bytes * test(studio): expect stamped patch markup * fix(studio-server): duplicate elements in nested templates * refactor(cli): share timeline mutation receipts * fix(studio-server): harden duplicate and no-op mutations * fix(studio-server): reduce duplicate helper complexity
1 parent 9742073 commit 4e9059a

12 files changed

Lines changed: 1355 additions & 600 deletions

File tree

‎packages/cli/src/commands/timeline.ts‎

Lines changed: 40 additions & 579 deletions
Large diffs are not rendered by default.
Lines changed: 291 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,291 @@
1+
import { applyFileMutations, fileContentVersion } from "@hyperframes/studio-server";
2+
import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
3+
import { readFileSync } from "node:fs";
4+
import { join } from "node:path";
5+
import { describeProject, type ProjectTimeline, type TimelineRow } from "./describeProject.js";
6+
import { resolveRef } from "./resolveRef.js";
7+
import { parseTimeExpression } from "./timeExpr.js";
8+
import { ensureDOMParser } from "../utils/dom.js";
9+
import { resolveProject } from "../utils/project.js";
10+
import { withMeta } from "../utils/updateCheck.js";
11+
import {
12+
allRows,
13+
decideMutation,
14+
diff,
15+
fpsFor,
16+
isRecord,
17+
mutationConflict,
18+
positional,
19+
publicReceipt,
20+
refuse,
21+
rowAt,
22+
type MutationContext,
23+
type MutationVerb,
24+
} from "./a2Shared.js";
25+
26+
export async function runIds(args: Record<string, unknown>): Promise<void> {
27+
const project = resolveProject(typeof args.dir === "string" ? args.dir : undefined);
28+
const json = args.json === true;
29+
ensureDOMParser();
30+
const beforeTimeline = await describeProject(project.indexPath);
31+
const files = [...new Set(["index.html", ...allRows(beforeTimeline).map((row) => row.file)])];
32+
const inputs = files.flatMap((file) => {
33+
const before = readFileSync(join(project.dir, file), "utf-8");
34+
const after = ensureHfIds(before);
35+
return after === before
36+
? []
37+
: [{ sourceFile: file, absPath: join(project.dir, file), before, after }];
38+
});
39+
const receipts = inputs.length > 0 ? applyFileMutations(project.dir, inputs) : [];
40+
const afterTimeline = await describeProject(project.indexPath);
41+
const result = {
42+
ok: true,
43+
receipt: receipts.map((receipt) => publicReceipt(receipt)),
44+
file: files,
45+
before: allRows(beforeTimeline),
46+
after: allRows(afterTimeline),
47+
diff: "",
48+
warnings: [],
49+
};
50+
if (json) console.log(JSON.stringify(withMeta(result), null, 2));
51+
else console.log(`ids: stamped ${receipts.length} file${receipts.length === 1 ? "" : "s"}`);
52+
}
53+
type ApplyEditResult =
54+
| { ok: true; file: string; after: string }
55+
| { ok: false; reason: string; fix: string };
56+
57+
const PLAN_VERBS = new Set<MutationVerb>(["move", "trim", "split", "delete", "set", "duplicate"]);
58+
59+
type PreparedPlanEdit = {
60+
ok: true;
61+
edit: Record<string, unknown>;
62+
row: TimelineRow;
63+
before: string;
64+
resolved: Extract<ReturnType<typeof resolveRef>, { ok: true }>;
65+
};
66+
67+
function preparePlanEdit(
68+
edit: unknown,
69+
timeline: ProjectTimeline,
70+
sourceByFile: Map<string, string>,
71+
): PreparedPlanEdit | { ok: false; reason: string; fix: string } {
72+
if (!isRecord(edit) || typeof edit.verb !== "string" || typeof edit.ref !== "string") {
73+
return {
74+
ok: false,
75+
reason: "each edit needs a verb and ref",
76+
fix: "pass {verb, ref, ...} objects",
77+
};
78+
}
79+
if (!PLAN_VERBS.has(edit.verb as MutationVerb)) {
80+
return {
81+
ok: false,
82+
reason: `unsupported edit verb ${edit.verb}`,
83+
fix: "use move, trim, split, delete, set, or duplicate",
84+
};
85+
}
86+
const resolved = resolveRef(timeline, edit.ref);
87+
if (!resolved.ok) return resolved;
88+
const before = sourceByFile.get(resolved.row.file);
89+
return before === undefined
90+
? { ok: false, reason: `${resolved.row.file} was not found`, fix: "choose an existing clip" }
91+
: { ok: true, edit, row: resolved.row, before, resolved };
92+
}
93+
94+
function applyPlanEdit(
95+
edit: unknown,
96+
timeline: ProjectTimeline,
97+
project: ReturnType<typeof resolveProject>,
98+
sourceByFile: Map<string, string>,
99+
): ApplyEditResult {
100+
const prepared = preparePlanEdit(edit, timeline, sourceByFile);
101+
if (!prepared.ok) return prepared;
102+
const { edit: planEdit, row, before, resolved } = prepared;
103+
const verb = planEdit.verb as MutationVerb;
104+
const context: MutationContext = {
105+
ref: planEdit.ref as string,
106+
row,
107+
before,
108+
resolved,
109+
parseTime: (expression) =>
110+
parseTimeExpression(expression, {
111+
row,
112+
duration: timeline.duration,
113+
fps: fpsFor(project.indexPath),
114+
resolveAnchor: (anchorRef) => {
115+
const anchor = resolveRef(timeline, anchorRef);
116+
return anchor.ok ? anchor.row : undefined;
117+
},
118+
}),
119+
duration: row.nested && row.hostRow ? rowAt(timeline, row.hostRow).duration : timeline.duration,
120+
};
121+
const decision = decideMutation(verb, context, { ...planEdit, _: [planEdit.ref] });
122+
if (!decision.ok) return { ok: false, reason: decision.reason, fix: decision.fix };
123+
const conflict = mutationConflict(
124+
verb as MutationVerb,
125+
planEdit.overwrite === true,
126+
row,
127+
timeline,
128+
decision.nextStart,
129+
decision.nextDuration,
130+
);
131+
if (conflict) return { ok: false, reason: conflict.reason, fix: conflict.fix };
132+
return { ok: true, file: row.file, after: decision.after };
133+
}
134+
135+
type EditPlan = { ok: true; edits: unknown[] } | { ok: false; reason: string; fix: string };
136+
137+
function readEditPlan(file: string): EditPlan {
138+
const raw = file === "-" ? readFileSync(0, "utf-8") : readFileSync(file, "utf-8");
139+
try {
140+
const edits: unknown = JSON.parse(raw);
141+
return Array.isArray(edits)
142+
? { ok: true, edits }
143+
: { ok: false, reason: "edit plan must be a JSON array", fix: "pass a JSON array of edits" };
144+
} catch {
145+
return { ok: false, reason: "edit plan is not valid JSON", fix: "pass a JSON array of edits" };
146+
}
147+
}
148+
149+
function readPlanSources(
150+
timeline: ProjectTimeline,
151+
project: ReturnType<typeof resolveProject>,
152+
): { sourceByFile: Map<string, string>; beforeByFile: Map<string, string> } {
153+
const sourceByFile = new Map<string, string>();
154+
const beforeByFile = new Map<string, string>();
155+
for (const fileName of new Set(allRows(timeline).map((row) => row.file))) {
156+
const source = readFileSync(join(project.dir, fileName), "utf-8");
157+
sourceByFile.set(fileName, source);
158+
beforeByFile.set(fileName, source);
159+
}
160+
return { sourceByFile, beforeByFile };
161+
}
162+
163+
async function applyPlanEdits(
164+
edits: unknown[],
165+
timeline: ProjectTimeline,
166+
project: ReturnType<typeof resolveProject>,
167+
sourceByFile: Map<string, string>,
168+
): Promise<{ ok: true } | { ok: false; reason: string; fix: string }> {
169+
for (const edit of edits) {
170+
const result = applyPlanEdit(edit, timeline, project, sourceByFile);
171+
if (!result.ok) return result;
172+
sourceByFile.set(result.file, result.after);
173+
timeline = await describeProject(project.indexPath, undefined, sourceByFile);
174+
}
175+
return { ok: true };
176+
}
177+
178+
export async function runApply(args: Record<string, unknown>): Promise<void> {
179+
const project = resolveProject(typeof args.dir === "string" ? args.dir : undefined);
180+
const json = args.json === true;
181+
const plan = args.plan === true;
182+
const file = typeof args.file === "string" ? args.file : positional(args)[1];
183+
if (!file)
184+
return refuse(
185+
"timeline apply",
186+
{ reason: "an edit plan is required", fix: "pass an edits.json path or -" },
187+
json,
188+
);
189+
const planInput = readEditPlan(file);
190+
if (!planInput.ok) return refuse("timeline apply", planInput, json);
191+
ensureDOMParser();
192+
const timeline = await describeProject(project.indexPath);
193+
const { sourceByFile, beforeByFile } = readPlanSources(timeline, project);
194+
const editsResult = await applyPlanEdits(planInput.edits, timeline, project, sourceByFile);
195+
if (!editsResult.ok) return refuse("timeline apply", editsResult, json);
196+
const inputs = [...sourceByFile].flatMap(([fileName, after]) => {
197+
const before = beforeByFile.get(fileName)!;
198+
return after === before
199+
? []
200+
: [
201+
{
202+
sourceFile: fileName,
203+
absPath: join(project.dir, fileName),
204+
before,
205+
after,
206+
expectedVersion: fileContentVersion(before),
207+
},
208+
];
209+
});
210+
const afterTimeline = await describeProject(project.indexPath, undefined, sourceByFile);
211+
const result = {
212+
ok: true,
213+
planned: plan,
214+
receipt: null as unknown,
215+
file: inputs.map((input) => input.sourceFile),
216+
before: allRows(timeline),
217+
after: allRows(afterTimeline),
218+
diff: inputs
219+
.map((input) => diff(input.before, input.after))
220+
.filter(Boolean)
221+
.join("\n"),
222+
warnings: [],
223+
};
224+
if (!plan) {
225+
const receipts = inputs.length > 0 ? applyFileMutations(project.dir, inputs) : [];
226+
result.receipt = receipts.map((receipt) => publicReceipt(receipt));
227+
}
228+
if (json) console.log(JSON.stringify(withMeta(result), null, 2));
229+
else
230+
console.log(
231+
`${plan ? "planned" : "applied"} ${inputs.length} file${inputs.length === 1 ? "" : "s"}`,
232+
);
233+
}
234+
235+
export async function runUndo(args: Record<string, unknown>): Promise<void> {
236+
const project = resolveProject(typeof args.dir === "string" ? args.dir : undefined);
237+
const json = args.json === true;
238+
const input = typeof args.receipt === "string" ? args.receipt : positional(args)[1];
239+
if (!input)
240+
return refuse(
241+
"timeline undo",
242+
{ reason: "an undo receipt is required", fix: "pass the receipt JSON or its file" },
243+
json,
244+
);
245+
let raw: string;
246+
try {
247+
raw = readFileSync(input, "utf-8");
248+
} catch {
249+
raw = input;
250+
}
251+
let parsed: unknown;
252+
try {
253+
parsed = JSON.parse(raw);
254+
} catch {
255+
return refuse(
256+
"timeline undo",
257+
{ reason: "undo receipt is not valid JSON", fix: "pass the applied JSON receipt" },
258+
json,
259+
);
260+
}
261+
const value = isRecord(parsed) && isRecord(parsed.receipt) ? parsed.receipt : parsed;
262+
if (
263+
!isRecord(value) ||
264+
typeof value.file !== "string" ||
265+
typeof value.version !== "string" ||
266+
typeof value.backupPath !== "string"
267+
) {
268+
return refuse(
269+
"timeline undo",
270+
{
271+
reason: "undo receipt is missing file, version, or backupPath",
272+
fix: "pass an applied timeline receipt",
273+
},
274+
json,
275+
);
276+
}
277+
const backup = join(project.dir, value.backupPath);
278+
const target = join(project.dir, value.file);
279+
const before = readFileSync(target, "utf-8");
280+
const after = readFileSync(backup, "utf-8");
281+
const receipts = applyFileMutations(project.dir, [
282+
{ sourceFile: value.file, absPath: target, before, after, expectedVersion: value.version },
283+
]);
284+
const result = {
285+
ok: true,
286+
receipt: receipts.map((receipt) => publicReceipt(receipt)),
287+
file: value.file,
288+
};
289+
if (json) console.log(JSON.stringify(withMeta(result), null, 2));
290+
else console.log(`undid ${value.file}`);
291+
}

0 commit comments

Comments
 (0)