retakes-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,387 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { BRAND } from "../brand.js";
4
+ import { openRepo } from "../store.js";
5
+ import { getAdapter } from "../adapters/index.js";
6
+ import { hasFfmpeg, makePoster, makePreview, makeMarkedFrame } from "../media.js";
7
+ import { api, remoteFor, tokenFor, needToken, readCreds, writeCreds, uploadBlob, download } from "../remote.js";
8
+ import { c, fail, fmtTime, ago, openBrowser, parseTarget, humanBytes, sha256File } from "../util.js";
9
+ import { init, save } from "./local.js";
10
+
11
+ const MIME = {
12
+ ".html": "text/html; charset=utf-8", ".htm": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8",
13
+ ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".ts": "text/plain; charset=utf-8",
14
+ ".tsx": "text/plain; charset=utf-8", ".jsx": "text/plain; charset=utf-8", ".json": "application/json",
15
+ ".md": "text/markdown; charset=utf-8", ".txt": "text/plain; charset=utf-8", ".svg": "image/svg+xml",
16
+ ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif",
17
+ ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime", ".mp3": "audio/mpeg", ".wav": "audio/wav",
18
+ ".m4a": "audio/mp4", ".ogg": "audio/ogg", ".woff2": "font/woff2", ".woff": "font/woff", ".ttf": "font/ttf", ".otf": "font/otf",
19
+ };
20
+ const mimeOf = (p) => MIME[path.extname(p).toLowerCase()] || "application/octet-stream";
21
+
22
+ // ── login ────────────────────────────────────────────────────────────────────
23
+ export async function login(args) {
24
+ const remote = remoteFor(null, args.values.remote);
25
+ const creds = readCreds();
26
+ if (args.values.token) {
27
+ const me = await api(remote, "GET", "/api/me", { token: args.values.token });
28
+ creds.remotes[remote] = { token: args.values.token, handle: me.user.handle };
29
+ creds.defaultRemote = remote;
30
+ writeCreds(creds);
31
+ return console.log(`${c.green("✓")} Logged in to ${remote} as @${me.user.handle}`);
32
+ }
33
+ const start = await api(remote, "POST", "/api/cli/device", { json: { label: `${BRAND.bin} CLI on ${process.platform}` } });
34
+ console.log(`Open ${c.cyan(start.verifyUrl)}`);
35
+ console.log(`and confirm the code ${c.bold(start.userCode)}`);
36
+ if (!args.values["no-browser"]) openBrowser(start.verifyUrl);
37
+ const deadline = Date.now() + start.expiresIn * 1000;
38
+ while (Date.now() < deadline) {
39
+ await new Promise((r) => setTimeout(r, (start.interval || 2) * 1000));
40
+ const poll = await api(remote, "GET", `/api/cli/device/${start.deviceCode}`);
41
+ if (poll.status === "approved") {
42
+ creds.remotes[remote] = { token: poll.token, handle: poll.user.handle };
43
+ creds.defaultRemote = remote;
44
+ writeCreds(creds);
45
+ return console.log(`${c.green("✓")} Logged in to ${remote} as @${poll.user.handle}`);
46
+ }
47
+ if (poll.status === "expired") break;
48
+ }
49
+ fail("The login code expired. Run login again.");
50
+ }
51
+
52
+ export async function logout(args) {
53
+ const remote = remoteFor(null, args.values.remote);
54
+ const creds = readCreds();
55
+ delete creds.remotes[remote];
56
+ writeCreds(creds);
57
+ console.log(`Logged out of ${remote}.`);
58
+ }
59
+
60
+ export async function whoami(args) {
61
+ const remote = remoteFor(null, args.values.remote);
62
+ const me = await api(remote, "GET", "/api/me", { token: needToken(remote) });
63
+ const u = me.usage;
64
+ console.log(`@${me.user.handle} on ${remote} · ${me.plan.label} plan`);
65
+ if (u) console.log(c.dim(` storage ${humanBytes(u.bytes)} of ${u.limit ? humanBytes(u.limit) : "unlimited"}`));
66
+ }
67
+
68
+ // ── push ─────────────────────────────────────────────────────────────────────
69
+ async function derive(repo, v) {
70
+ if (!v.render || !hasFfmpeg() || !repo.hasObj(v.render.h)) return false;
71
+ let changed = false;
72
+ const src = repo.objPath(v.render.h);
73
+ if (!v.poster) {
74
+ const out = repo.p("derived", `${v.render.h}-poster.jpg`);
75
+ if (!fs.existsSync(out)) makePoster(src, out, (v.render.duration || 1) * 0.3);
76
+ const h = await sha256File(out);
77
+ await repo.putFile(out, h);
78
+ v.poster = { h, s: fs.statSync(out).size };
79
+ changed = true;
80
+ }
81
+ if (!v.preview) {
82
+ const out = repo.p("derived", `${v.render.h}-preview.mp4`);
83
+ if (!fs.existsSync(out)) {
84
+ process.stdout.write(c.dim(` making a 540p preview of v${v.n}…\n`));
85
+ makePreview(src, out);
86
+ }
87
+ const h = await sha256File(out);
88
+ await repo.putFile(out, h);
89
+ v.preview = { h, s: fs.statSync(out).size };
90
+ changed = true;
91
+ }
92
+ return changed;
93
+ }
94
+
95
+ export async function ensureProject(repo, remote, token, visibility, link = false) {
96
+ const cfg = repo.config;
97
+ if (cfg.project && cfg.project.remote === remote) return cfg.project;
98
+ const res = await api(remote, "POST", "/api/projects", {
99
+ token,
100
+ json: { slug: cfg.slug, title: cfg.title, engine: cfg.engine, visibility: visibility || cfg.visibility || "private", forkedFrom: cfg.forkedFrom, link },
101
+ });
102
+ cfg.project = { id: res.project.id, handle: res.project.handle, slug: res.project.slug, remote };
103
+ cfg.remote = remote;
104
+ repo.saveConfig();
105
+ if (res.created === false) console.log(c.dim(` linked to your existing project ${res.project.handle}/${res.project.slug}`));
106
+ return cfg.project;
107
+ }
108
+
109
+ export async function push(args) {
110
+ const repo = openRepo();
111
+ const remote = remoteFor(repo, args.values.remote);
112
+ const token = needToken(remote);
113
+ const visibility = args.values.private ? "private" : args.values.public ? "public" : null;
114
+ const project = await ensureProject(repo, remote, token, visibility, Boolean(args.values.link));
115
+ if (visibility) {
116
+ await api(remote, "PATCH", `/api/projects/${project.id}`, { token, json: { visibility } });
117
+ repo.config.visibility = visibility;
118
+ repo.saveConfig();
119
+ }
120
+ const pending = repo.versions().filter((v) => v.remote?.projectId !== project.id);
121
+ const url = `${remote}/${project.handle}/${project.slug}`;
122
+ if (!pending.length) {
123
+ console.log(`Everything is pushed. ${c.cyan(url)}`);
124
+ return visibilityNote(remote, token, project);
125
+ }
126
+
127
+ for (const v of pending) {
128
+ if (await derive(repo, v)) repo.writeVersion(v);
129
+ const blobs = new Map();
130
+ for (const [rel, f] of Object.entries(v.files)) if (!blobs.has(f.h)) blobs.set(f.h, { size: f.s, type: mimeOf(rel), label: rel });
131
+ if (v.render) blobs.set(v.render.h, { size: v.render.s, type: mimeOf(v.render.path), label: `render ${path.basename(v.render.path)}` });
132
+ if (v.poster) blobs.set(v.poster.h, { size: v.poster.s, type: "image/jpeg", label: "poster" });
133
+ if (v.preview) blobs.set(v.preview.h, { size: v.preview.s, type: "video/mp4", label: "preview" });
134
+
135
+ const { missing } = await api(remote, "POST", `/api/projects/${project.id}/blobs/missing`, { token, json: { hashes: [...blobs.keys()] } });
136
+ const total = missing.reduce((n, h) => n + blobs.get(h).size, 0);
137
+ console.log(`${c.bold("v" + v.n)} ${v.message} ${c.dim(`· uploading ${missing.length} of ${blobs.size} objects (${humanBytes(total)})`)}`);
138
+ for (const h of missing) {
139
+ const b = blobs.get(h);
140
+ if (!repo.hasObj(h)) fail(`Object ${h.slice(0, 12)} (${b.label}) is missing locally.`);
141
+ await uploadBlob(remote, token, { hash: h, size: b.size, file: repo.objPath(h), contentType: b.type, label: b.label });
142
+ }
143
+ const res = await api(remote, "POST", `/api/projects/${project.id}/versions`, {
144
+ token,
145
+ json: {
146
+ number: v.n,
147
+ parent: v.parent,
148
+ message: v.message,
149
+ prompt: v.prompt,
150
+ agent: v.agent,
151
+ engine: v.engine,
152
+ createdAt: v.createdAt,
153
+ files: v.files,
154
+ render: v.render,
155
+ poster: v.poster,
156
+ preview: v.preview,
157
+ timeline: v.timeline,
158
+ resolves: v.resolves,
159
+ starred: v.starred,
160
+ },
161
+ });
162
+ v.remote = { projectId: project.id, versionId: res.version.id, pushedAt: new Date().toISOString() };
163
+ repo.writeVersion(v);
164
+ if (res.pruned?.length) console.log(c.dim(` free plan: kept previews only for ${res.pruned.map((n) => "v" + n).join(", ")}`));
165
+ if (res.resolved?.length) console.log(c.dim(` resolved ${res.resolved.length} comment${res.resolved.length === 1 ? "" : "s"}`));
166
+ }
167
+ console.log(`${c.green("✓")} Pushed. ${c.cyan(url)}`);
168
+ await visibilityNote(remote, token, project);
169
+ }
170
+
171
+ // Say who can see the project, since everything starts private.
172
+ async function visibilityNote(remote, token, project) {
173
+ try {
174
+ const { project: p } = await api(remote, "GET", `/api/p/${project.handle}/${project.slug}`, { token });
175
+ if (p.visibility === "private") console.log(c.dim(` private: only you can see it. To share it: ${BRAND.bin} push --public (or the Make public button on the page)`));
176
+ else console.log(c.dim(` public: anyone with the link can watch, fork and remix it. ${BRAND.bin} push --private hides it again`));
177
+ } catch {}
178
+ }
179
+
180
+ // ── feedback ─────────────────────────────────────────────────────────────────
181
+ async function renderFileFor(repo, remote, token, cm) {
182
+ const local = repo.versions().find((v) => v.remote?.versionId === cm.versionId);
183
+ if (local?.render && repo.hasObj(local.render.h)) return repo.objPath(local.render.h);
184
+ const cached = repo.p("feedback", `${cm.versionId}.mp4`);
185
+ if (fs.existsSync(cached)) return cached;
186
+ try {
187
+ await download(remote, token, `/media/${cm.versionId}/best`, cached);
188
+ return cached;
189
+ } catch {
190
+ return null;
191
+ }
192
+ }
193
+
194
+ export async function feedback(args) {
195
+ const repo = openRepo();
196
+ const remote = remoteFor(repo, args.values.remote);
197
+ const token = needToken(remote);
198
+ const project = repo.config.project;
199
+ if (!project) fail(`Push first (\`${BRAND.bin} push\`), then reviewers can comment on the web page.`);
200
+ const status = args.values.all ? "all" : "open";
201
+ const data = await api(remote, "GET", `/api/projects/${project.id}/feedback?status=${status}`, { token });
202
+ const adapter = getAdapter(repo.config.engine);
203
+ const comments = data.comments;
204
+
205
+ const frames = !args.values["no-frames"] && hasFfmpeg();
206
+ for (const cm of comments) {
207
+ if (!cm.where) {
208
+ const local = repo.versions().find((v) => v.remote?.versionId === cm.versionId);
209
+ cm.where = adapter.locate?.(local?.timeline ?? cm.timeline ?? [], cm.t, local?.render?.fps ?? cm.fps) ?? null;
210
+ }
211
+ delete cm.timeline;
212
+ if (frames) {
213
+ const file = await renderFileFor(repo, remote, token, cm);
214
+ if (file) {
215
+ const out = repo.p("feedback", `${cm.id}.jpg`);
216
+ try {
217
+ makeMarkedFrame(file, out, cm.t, cm.x, cm.y);
218
+ cm.frame = path.relative(process.cwd(), out).split(path.sep).join("/");
219
+ } catch {
220
+ /* still useful without the still */
221
+ }
222
+ }
223
+ }
224
+ }
225
+
226
+ if (args.values.json) return console.log(JSON.stringify({ project: data.project, comments }, null, 2));
227
+ const url = `${remote}/${project.handle}/${project.slug}`;
228
+ if (!comments.length) return console.log(`No ${status === "open" ? "open " : ""}feedback on ${url}.`);
229
+ console.log(`# ${status === "open" ? "Open feedback" : "Feedback"} on ${project.handle}/${project.slug} (${comments.length})\n`);
230
+ for (const cm of comments) {
231
+ const w = cm.where;
232
+ const where = w?.file ? ` — ${w.file} @ ${w.local.toFixed(2)}s (scene ${w.scene})` : w?.frame != null ? ` — frame ${w.frame}` : "";
233
+ const region = cm.x != null ? ` — region x ${cm.x.toFixed(2)} y ${cm.y.toFixed(2)}` : "";
234
+ console.log(`- [${cm.id}] v${cm.versionNumber} @ ${fmtTime(cm.t)}${where}${region}${cm.status === "resolved" ? " (resolved)" : ""}`);
235
+ console.log(` "${cm.body.replace(/\n/g, "\n ")}"`);
236
+ console.log(c.dim(` — @${cm.author.handle}, ${ago(cm.createdAt)}${cm.frame ? ` · frame: ${cm.frame}` : ""}`));
237
+ }
238
+ const ids = comments.filter((x) => x.status === "open").map((x) => x.id);
239
+ if (ids.length)
240
+ console.log(`\nFix these, render, then:\n ${BRAND.bin} save -m "..." --resolves ${ids.join(",")} && ${BRAND.bin} push`);
241
+ }
242
+
243
+ export async function resolve(args) {
244
+ const repo = openRepo();
245
+ const remote = remoteFor(repo, args.values.remote);
246
+ const token = needToken(remote);
247
+ const ids = args.positionals.join(",").split(",").map((s) => s.trim()).filter(Boolean);
248
+ if (!ids.length) fail(`Name the comment ids: ${BRAND.bin} resolve c_abc,c_def`);
249
+ for (const id of ids) await api(remote, "PATCH", `/api/comments/${id}`, { token, json: { status: args.values.reopen ? "open" : "resolved" } });
250
+ console.log(`${c.green("✓")} ${args.values.reopen ? "Reopened" : "Resolved"} ${ids.join(", ")}`);
251
+ }
252
+
253
+ // ── fork / remix ─────────────────────────────────────────────────────────────
254
+ async function fetchVersion(remote, token, target) {
255
+ const p = await api(remote, "GET", `/api/p/${target.handle}/${target.slug}`, { token });
256
+ const n = target.number ?? p.project.headNumber;
257
+ if (n == null) fail(`${target.handle}/${target.slug} has no versions yet.`);
258
+ const v = await api(remote, "GET", `/api/p/${target.handle}/${target.slug}/versions/${n}`, { token });
259
+ return { project: p.project, version: v.version, files: v.files };
260
+ }
261
+
262
+ async function downloadTree(remote, token, versionId, files, destRoot) {
263
+ const byHash = new Map();
264
+ const entries = Object.entries(files);
265
+ let i = 0;
266
+ for (const [rel, f] of entries) {
267
+ i++;
268
+ const dest = path.join(destRoot, ...rel.split("/"));
269
+ if (byHash.has(f.h)) {
270
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
271
+ fs.copyFileSync(byHash.get(f.h), dest);
272
+ continue;
273
+ }
274
+ if (process.stdout.isTTY) process.stdout.write(`\r downloading ${i}/${entries.length} files `);
275
+ await download(remote, token, `/api/v/${versionId}/blob/${f.h}`, dest);
276
+ byHash.set(f.h, dest);
277
+ }
278
+ if (process.stdout.isTTY) process.stdout.write("\n");
279
+ }
280
+
281
+ function emptyDir(dir) {
282
+ if (fs.existsSync(dir) && fs.readdirSync(dir).length) fail(`${dir} already exists and isn't empty.`);
283
+ fs.mkdirSync(dir, { recursive: true });
284
+ }
285
+
286
+ export async function fork(args) {
287
+ const target = parseTarget(args.positionals[0]);
288
+ const remote = remoteFor(null, args.values.remote || target.host);
289
+ const token = tokenFor(remote);
290
+ const { project, version, files } = await fetchVersion(remote, token, target);
291
+ const dir = path.resolve(args.positionals[1] || project.slug);
292
+ emptyDir(dir);
293
+ console.log(`Forking ${c.bold(`${project.handle}/${project.slug}`)} v${version.number} into ${dir}`);
294
+ await downloadTree(remote, token, version.id, files, dir);
295
+ if (args.values["with-render"] && version.render) {
296
+ const p = version.render.path || `renders/${project.slug}.mp4`;
297
+ await download(remote, token, `/media/${version.id}/render`, path.join(dir, ...p.split("/")));
298
+ }
299
+ await init({ positionals: [dir], values: { engine: version.engine, title: project.title, slug: project.slug, remote } });
300
+ const rel = path.relative(process.cwd(), dir) || ".";
301
+ process.chdir(dir);
302
+ const repo = openRepo();
303
+ repo.config.forkedFrom = { handle: project.handle, slug: project.slug, number: version.number, kind: "fork" };
304
+ repo.saveConfig();
305
+ const v1 = await save({ positionals: [], values: { message: `Forked from @${project.handle}/${project.slug} v${version.number}`, "no-render": !args.values["with-render"], prompt: version.prompt || undefined } });
306
+ // Without --with-render, point at the original's render, poster and preview by hash: the server
307
+ // already has them for the forked-from version, so nothing is downloaded or uploaded.
308
+ if (v1 && !v1.render && version.render?.hash) {
309
+ const r = version.render;
310
+ v1.render = { h: r.hash, s: r.bytes ?? 0, path: r.path ?? `renders/${project.slug}.mp4`, duration: r.duration, width: r.width, height: r.height, fps: r.fps, remoteOnly: true };
311
+ if (version.posterHash) v1.poster = { h: version.posterHash, s: 0 };
312
+ if (version.previewHash) v1.preview = { h: version.previewHash, s: 0 };
313
+ repo.writeVersion(v1);
314
+ }
315
+ console.log(`\n cd ${rel} and keep going. \`${BRAND.bin} push\` publishes your fork.`);
316
+ }
317
+
318
+ export async function remix(args) {
319
+ const target = parseTarget(args.positionals[0]);
320
+ const remote = remoteFor(null, args.values.remote || target.host);
321
+ const token = tokenFor(remote);
322
+ const { project, version, files } = await fetchVersion(remote, token, target);
323
+ const dir = path.resolve(args.positionals[1] || `${project.slug}-remix`);
324
+ emptyDir(dir);
325
+ const ref = path.join(dir, "reference");
326
+ console.log(`Remixing the style of ${c.bold(`${project.handle}/${project.slug}`)} v${version.number}`);
327
+ const kind = version.render && !version.renderPruned ? "render" : "preview";
328
+ const refVideo = path.join(ref, `${project.slug}.mp4`);
329
+ try {
330
+ await download(remote, token, `/media/${version.id}/${kind}`, refVideo);
331
+ } catch {
332
+ console.log(c.yellow(" no video to download for that version"));
333
+ }
334
+ await downloadTree(remote, token, version.id, files, path.join(ref, "source"));
335
+ const engine = args.values.engine || version.engine;
336
+ await init({ positionals: [dir], values: { engine, title: args.values.title || `${project.title} remix`, remote } });
337
+ fs.appendFileSync(path.join(dir, BRAND.ignoreFile), "reference/\n");
338
+ process.chdir(dir);
339
+ const repo = openRepo();
340
+ repo.config.forkedFrom = { handle: project.handle, slug: project.slug, number: version.number, kind: "remix" };
341
+ repo.saveConfig();
342
+ const pageUrl = `${remote}/${project.handle}/${project.slug}/v/${version.number}`;
343
+ const timeline = (version.timeline || []).map((s) => `| ${fmtTime(s.start)} | ${s.duration.toFixed(2)}s | ${s.id} | ${s.file ?? ""} |`).join("\n");
344
+ fs.writeFileSync(
345
+ path.join(dir, "REMIX.md"),
346
+ `# Remix brief
347
+
348
+ Make a new video in the style of **${project.title}** (${pageUrl}), about your own subject.
349
+
350
+ - Reference video: \`reference/${project.slug}.mp4\`${version.render?.duration ? ` (${version.render.duration.toFixed(1)} s, ${version.render.width}×${version.render.height})` : ""}
351
+ - Reference source (${version.engine}): \`reference/source/\` — read it for timing, eases, type and palette; don't copy brand assets.
352
+ - The prompt behind the reference: ${version.prompt ? `“${version.prompt}”` : "not recorded"}
353
+
354
+ ## Scene map of the reference
355
+ ${timeline ? `| at | length | scene | file |\n| --- | --- | --- | --- |\n${timeline}` : "No scene map recorded; watch the reference and write a cue sheet first."}
356
+
357
+ ## Workflow (the retakes-recreate skill runs this)
358
+ 1. Ask the person for direction: what to keep (pacing, transitions, type, palette, music feel), what to swap (subject, brand, copy, footage), length, aspect and sound.
359
+ 2. Study the reference: \`reference/watch/WATCH.md\`, \`timeline.png\` and \`overview.jpg\` first, then the shot strips and bursts you need. Fill \`reference/watch/cuesheet.md\`.
360
+ 3. Show the person the cue sheet for their version and wait for a yes.
361
+ 4. Build to the measured timings, render, then \`${BRAND.bin} save -m "first pass" --prompt "<their request>"\`.
362
+ 5. \`${BRAND.bin} match reference/${project.slug}.mp4\`: fix only the shots it flags, re-render, run it again (unchanged shots are skipped).
363
+ 6. \`${BRAND.bin} push\` and share the link.
364
+ `
365
+ );
366
+ const { buildWatchPack } = await import("../video/pack.js");
367
+ const { hasFfmpeg } = await import("../media.js");
368
+ if (fs.existsSync(refVideo) && hasFfmpeg()) {
369
+ try {
370
+ await buildWatchPack({ file: refVideo, label: project.slug }, repo, { out: path.join(ref, "watch") });
371
+ console.log(c.dim(" built a watch pack of the reference in reference/watch/"));
372
+ } catch (e) {
373
+ console.log(c.yellow(` couldn't build the watch pack (${e.message}); run \`${BRAND.bin} watch ${path.relative(dir, refVideo)}\` later`));
374
+ }
375
+ }
376
+ console.log(`${c.green("✓")} Remix project ready in ${dir}`);
377
+ console.log(` Read ${c.cyan("REMIX.md")}, build, then \`${BRAND.bin} save\` and \`${BRAND.bin} push\`.`);
378
+ }
379
+
380
+ export async function open(args) {
381
+ const repo = openRepo();
382
+ const p = repo.config.project;
383
+ if (!p) fail(`Not pushed yet. Run \`${BRAND.bin} push\`.`);
384
+ const url = `${p.remote}/${p.handle}/${p.slug}${args.positionals[0] ? `/v/${String(args.positionals[0]).replace(/^v/i, "")}` : ""}`;
385
+ console.log(url);
386
+ openBrowser(url);
387
+ }
@@ -0,0 +1,53 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { BRAND } from "../brand.js";
6
+ import { c } from "../util.js";
7
+
8
+ const SKILLS_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "skills");
9
+ const SKILL_SRC = path.join(SKILLS_DIR, BRAND.skillName);
10
+ const allSkills = () => fs.readdirSync(SKILLS_DIR, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
11
+
12
+ export const AGENTS_SNIPPET = `## Video versions (${BRAND.name})
13
+ This project is versioned with \`${BRAND.bin}\`. After every render:
14
+ \`${BRAND.bin} save -m "<what changed>" --prompt "<what the user asked for>"\`, then \`${BRAND.bin} push\` (private by default; add \`--public\` only when the user asks to share it).
15
+ Before changing anything after a review, run \`${BRAND.bin} feedback\`: it lists open frame comments with the
16
+ scene file and local time each one points at, plus a marked still per comment. Fix them, render, then
17
+ \`${BRAND.bin} save -m "..." --resolves <ids>\` and \`${BRAND.bin} push\`. Never edit ${BRAND.dir}/ by hand.
18
+ You can't play video: to understand one (a reference or your render), run \`${BRAND.bin} watch <video>\` and read its
19
+ WATCH.md, timeline.png and overview.jpg first. After a change, \`${BRAND.bin} vdiff\` shows only the shots that changed;
20
+ \`${BRAND.bin} match <reference>\` scores your render against a reference shot by shot.
21
+ `;
22
+
23
+ function copyDir(src, dest) {
24
+ fs.mkdirSync(dest, { recursive: true });
25
+ for (const e of fs.readdirSync(src, { withFileTypes: true })) {
26
+ const s = path.join(src, e.name);
27
+ const d = path.join(dest, e.name);
28
+ if (e.isDirectory()) copyDir(s, d);
29
+ else fs.copyFileSync(s, d);
30
+ }
31
+ }
32
+
33
+ export async function skill(args) {
34
+ const sub = args.positionals[0] || "install";
35
+ if (sub === "print") return console.log(fs.readFileSync(path.join(args.positionals[1] ? path.join(SKILLS_DIR, args.positionals[1]) : SKILL_SRC, "SKILL.md"), "utf8"));
36
+ if (sub === "list") return console.log(allSkills().join("\n"));
37
+ if (sub === "agents-md") return console.log(AGENTS_SNIPPET);
38
+ if (sub !== "install") return console.log(`Usage: ${BRAND.bin} skill install [--claude] [--codex] [--dir <path>] | print | agents-md`);
39
+ const home = os.homedir();
40
+ const roots = [];
41
+ if (args.values.dir) roots.push(path.resolve(args.values.dir));
42
+ const pickClaude = args.values.claude || (!args.values.codex && !args.values.dir);
43
+ const pickCodex = args.values.codex || (!args.values.claude && !args.values.dir);
44
+ if (pickClaude) roots.push(path.join(home, ".claude", "skills"));
45
+ if (pickCodex) roots.push(path.join(process.env.CODEX_HOME || path.join(home, ".codex"), "skills"));
46
+ const names = allSkills();
47
+ for (const root of roots) {
48
+ for (const name of names) copyDir(path.join(SKILLS_DIR, name), path.join(root, name));
49
+ console.log(`${c.green("✓")} ${names.join(", ")} → ${root}`);
50
+ }
51
+ console.log(c.dim(`\nFor repos that use AGENTS.md, add this block (\`${BRAND.bin} skill agents-md\` prints it):\n`));
52
+ console.log(AGENTS_SNIPPET);
53
+ }
@@ -0,0 +1,120 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { BRAND } from "../brand.js";
4
+ import { getAdapter, findRender } from "../adapters/index.js";
5
+ import { locateGeneric } from "../adapters/locate.js";
6
+ import { analyzeVideo, buildWatchPack, repoOrNull, resolveVideo } from "../video/pack.js";
7
+ import { compare } from "../video/match.js";
8
+ import { rel } from "../video/ff.js";
9
+ import { c, fail, fmtTime, sha256File } from "../util.js";
10
+
11
+ // retake watch <video>: turn a video into things an image-reading agent can study.
12
+ export async function watch(args) {
13
+ const repo = repoOrNull();
14
+ const src = await resolveVideo(args.positionals[0], repo, { remote: args.values.remote });
15
+ const t0 = Date.now();
16
+ const { dir, cached, a } = await buildWatchPack(src, repo, {
17
+ out: args.values.out ? path.resolve(args.values.out) : undefined,
18
+ force: Boolean(args.values.force),
19
+ bursts: args.values.bursts ? Number(args.values.bursts) : 8,
20
+ });
21
+ const w = JSON.parse(fs.readFileSync(path.join(dir, "watch.json"), "utf8"));
22
+ if (args.values.json) return console.log(JSON.stringify(w, null, 2));
23
+ console.log(`${c.green("✓")} Watch pack ${cached ? "(cached)" : `built in ${((Date.now() - t0) / 1000).toFixed(1)}s`}: ${c.cyan(rel(dir))}`);
24
+ console.log(c.dim(` ${w.duration.toFixed(2)}s · ${w.width}×${w.height} · ${w.scenes.length} shots · ${w.bursts.length} bursts${w.audio ? ` · ${w.audio.bpm ? `~${w.audio.bpm} BPM` : "no steady beat"} · ${w.audio.loudness?.integratedLufs ?? "?"} LUFS` : " · no audio"}`));
25
+ console.log(` Start with ${c.cyan(rel(path.join(dir, "WATCH.md")))}, then timeline.png and overview.jpg.`);
26
+ void a;
27
+ }
28
+
29
+ function workingRender(repo) {
30
+ const adapter = getAdapter(repo.config.engine);
31
+ return findRender(repo.root, adapter)?.path ?? null;
32
+ }
33
+
34
+ // retake match <reference> [yours]: score your render against a reference, shot by shot.
35
+ export async function match(args) {
36
+ const repo = repoOrNull();
37
+ const [refIn, candIn] = args.positionals;
38
+ if (!refIn) fail(`Usage: ${BRAND.bin} match <reference> [your video]`);
39
+ const ref = await resolveVideo(refIn, repo, { remote: args.values.remote });
40
+ let cand;
41
+ if (candIn) cand = await resolveVideo(candIn, repo, { remote: args.values.remote });
42
+ else {
43
+ const f = repo && workingRender(repo);
44
+ if (!f) fail("Name your video too, or run this inside a project that has a render.");
45
+ cand = { file: f, label: path.basename(f, path.extname(f)) };
46
+ }
47
+ const A = await analyzeVideo(ref.file, repo, { withAudio: false });
48
+ const B = await analyzeVideo(cand.file, repo, { withAudio: false });
49
+ const outDir = args.values.out ? path.resolve(args.values.out) : repo ? repo.p("match", `${ref.label}-${A.key.slice(0, 8)}`) : path.resolve(`match-${ref.label}`);
50
+ const { rows, overall } = await compare(A, B, {
51
+ mode: "match",
52
+ outDir,
53
+ stateFile: path.join(outDir, "state.json"),
54
+ threshold: args.values.threshold ? Number(args.values.threshold) : 0.75,
55
+ all: Boolean(args.values.all),
56
+ labels: [ref.label, cand.label],
57
+ });
58
+ if (args.values.json) return console.log(fs.readFileSync(path.join(outDir, "match.json"), "utf8"));
59
+ const look = rows.filter((r) => r.status === "check").sort((x, y) => x.score - y.score);
60
+ const unchanged = rows.filter((r) => r.status === "unchanged").length;
61
+ console.log(`${c.bold(`Match ${overall}`)} ${c.dim(`(${cand.label} vs ${ref.label}; ${A.scenes.length} → ${B.scenes.length} shots)`)}`);
62
+ for (const r of look.slice(0, 8)) console.log(` ${c.yellow("check")} shot ${r.ref.index} @ ${fmtTime(r.ref.start)} score ${r.score} layout ${r.layout} motion ${r.motion} color ${r.color} timing ${r.timing}${r.image ? c.dim(` ${r.image}`) : ""}`);
63
+ const miss = rows.filter((r) => r.status === "missing").length;
64
+ const extra = rows.filter((r) => r.status === "extra").length;
65
+ if (miss || extra) console.log(c.dim(` ${miss} shot${miss === 1 ? "" : "s"} missing, ${extra} extra`));
66
+ if (unchanged) console.log(c.dim(` ${unchanged} shot${unchanged === 1 ? "" : "s"} unchanged since the last check (no new images)`));
67
+ console.log(` Report: ${c.cyan(rel(path.join(outDir, "MATCH.md")))}`);
68
+ }
69
+
70
+ // retake vdiff [a] [b]: what visibly changed between two takes, with images only for those shots.
71
+ export async function vdiff(args) {
72
+ const repo = repoOrNull();
73
+ if (!repo) fail(`Run this inside a ${BRAND.name} project.`);
74
+ const versions = repo.versions().filter((v) => v.render);
75
+ const [aIn, bIn] = args.positionals;
76
+ let b;
77
+ let bVersion = null;
78
+ if (bIn) {
79
+ b = await resolveVideo(bIn, repo);
80
+ bVersion = b.version ?? null;
81
+ } else {
82
+ const f = workingRender(repo);
83
+ const headRender = versions.find((v) => v.n === repo.config.head)?.render;
84
+ if (f && (!headRender || (await sha256File(f)) !== headRender.h)) b = { file: f, label: "working" };
85
+ else {
86
+ bVersion = versions.filter((v) => v.n <= (repo.config.head ?? Infinity)).pop();
87
+ if (!bVersion) fail("No renders to compare yet.");
88
+ b = await resolveVideo(`v${bVersion.n}`, repo);
89
+ }
90
+ }
91
+ let a;
92
+ if (aIn) a = await resolveVideo(aIn, repo);
93
+ else {
94
+ const before = bVersion ? versions.filter((v) => v.n < bVersion.n).pop() : versions.filter((v) => v.n <= (repo.config.head ?? Infinity)).pop();
95
+ if (!before) fail("Nothing earlier to compare with.");
96
+ a = await resolveVideo(`v${before.n}`, repo);
97
+ }
98
+ const A = await analyzeVideo(a.file, repo, { withAudio: false });
99
+ const B = await analyzeVideo(b.file, repo, { withAudio: false });
100
+ const timeline = bVersion?.timeline?.length ? bVersion.timeline : getAdapter(repo.config.engine).timeline?.((r) => {
101
+ try {
102
+ return fs.readFileSync(path.join(repo.root, ...r.split("/")), "utf8");
103
+ } catch {
104
+ return null;
105
+ }
106
+ }) ?? [];
107
+ const sceneName = (t) => {
108
+ const w = locateGeneric(timeline, t);
109
+ return w ? `${w.file ?? w.scene}` : null;
110
+ };
111
+ const outDir = repo.p("vdiff", `${a.label}-${b.label}`);
112
+ const { rows } = await compare(A, B, { mode: "takes", outDir, labels: [a.label, b.label], sceneName });
113
+ const changed = rows.filter((r) => !["same", "shifted"].includes(r.status));
114
+ console.log(`${c.bold(`${a.label} → ${b.label}`)}: ${changed.length} of ${rows.length} shots changed`);
115
+ for (const r of changed) {
116
+ const s = r.cand ?? r.ref;
117
+ console.log(` ${c.yellow(r.status.padEnd(17))} ${fmtTime(s.start)} (${s.duration.toFixed(2)}s)${sceneName(s.start + s.duration / 2) ? c.dim(` ${sceneName(s.start + s.duration / 2)}`) : ""}${r.image ? c.dim(` ${r.image}`) : ""}`);
118
+ }
119
+ console.log(` Report: ${c.cyan(rel(path.join(outDir, "VDIFF.md")))}`);
120
+ }
package/src/diff.js ADDED
@@ -0,0 +1,92 @@
1
+ // Line diff (LCS after trimming the shared head and tail), printed as unified hunks.
2
+ export function lineDiff(aText, bText, maxCells = 4_000_000) {
3
+ const A = aText.split(/\r?\n/);
4
+ const B = bText.split(/\r?\n/);
5
+ let start = 0;
6
+ while (start < A.length && start < B.length && A[start] === B[start]) start++;
7
+ let endA = A.length;
8
+ let endB = B.length;
9
+ while (endA > start && endB > start && A[endA - 1] === B[endB - 1]) {
10
+ endA--;
11
+ endB--;
12
+ }
13
+ const a = A.slice(start, endA);
14
+ const b = B.slice(start, endB);
15
+ const n = a.length;
16
+ const m = b.length;
17
+ if (n * m > maxCells) return null;
18
+ const W = m + 1;
19
+ const L = new Uint32Array((n + 1) * W);
20
+ for (let i = n - 1; i >= 0; i--)
21
+ for (let j = m - 1; j >= 0; j--)
22
+ L[i * W + j] = a[i] === b[j] ? L[(i + 1) * W + j + 1] + 1 : Math.max(L[(i + 1) * W + j], L[i * W + j + 1]);
23
+ const ops = [];
24
+ for (let k = 0; k < start; k++) ops.push([" ", A[k]]);
25
+ let i = 0;
26
+ let j = 0;
27
+ while (i < n && j < m) {
28
+ if (a[i] === b[j]) {
29
+ ops.push([" ", a[i++]]);
30
+ j++;
31
+ } else if (L[(i + 1) * W + j] >= L[i * W + j + 1]) ops.push(["-", a[i++]]);
32
+ else ops.push(["+", b[j++]]);
33
+ }
34
+ while (i < n) ops.push(["-", a[i++]]);
35
+ while (j < m) ops.push(["+", b[j++]]);
36
+ for (let k = endA; k < A.length; k++) ops.push([" ", A[k]]);
37
+ return ops;
38
+ }
39
+
40
+ export function countOps(ops) {
41
+ let add = 0;
42
+ let del = 0;
43
+ for (const [t] of ops) {
44
+ if (t === "+") add++;
45
+ else if (t === "-") del++;
46
+ }
47
+ return { add, del };
48
+ }
49
+
50
+ export function hunks(ops, context = 3) {
51
+ const out = [];
52
+ let ai = 1;
53
+ let bi = 1;
54
+ const pos = ops.map(([t]) => {
55
+ const p = [ai, bi];
56
+ if (t !== "+") ai++;
57
+ if (t !== "-") bi++;
58
+ return p;
59
+ });
60
+ const changes = [];
61
+ ops.forEach(([t], i) => {
62
+ if (t !== " ") changes.push(i);
63
+ });
64
+ if (!changes.length) return out;
65
+ const groups = [];
66
+ let gs = changes[0];
67
+ let ge = changes[0];
68
+ for (const i of changes.slice(1)) {
69
+ if (i - ge <= context * 2 + 1) ge = i;
70
+ else {
71
+ groups.push([gs, ge]);
72
+ gs = ge = i;
73
+ }
74
+ }
75
+ groups.push([gs, ge]);
76
+ for (const [s0, e0] of groups) {
77
+ const s = Math.max(0, s0 - context);
78
+ const e = Math.min(ops.length, e0 + context + 1);
79
+ const slice = ops.slice(s, e);
80
+ const aLen = slice.filter(([t]) => t !== "+").length;
81
+ const bLen = slice.filter(([t]) => t !== "-").length;
82
+ out.push(`@@ -${pos[s][0]},${aLen} +${pos[s][1]},${bLen} @@`);
83
+ for (const [t, line] of slice) out.push(`${t}${line}`);
84
+ }
85
+ return out;
86
+ }
87
+
88
+ export function looksText(buf) {
89
+ const n = Math.min(buf.length, 8000);
90
+ for (let i = 0; i < n; i++) if (buf[i] === 0) return false;
91
+ return true;
92
+ }