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.
package/src/cli.js ADDED
@@ -0,0 +1,70 @@
1
+ import { parseArgs } from "node:util";
2
+ import { BRAND } from "./brand.js";
3
+ import { CliError, c } from "./util.js";
4
+ import * as local from "./commands/local.js";
5
+ import * as remote from "./commands/remote.js";
6
+ import { skill } from "./commands/skill.js";
7
+ import * as video from "./commands/video.js";
8
+
9
+ const S = { type: "string" };
10
+ const B = { type: "boolean" };
11
+ const remoteOpt = { remote: S };
12
+
13
+ const COMMANDS = {
14
+ init: { run: local.init, opts: { engine: S, title: S, slug: S, public: B, private: B, ...remoteOpt }, usage: "init [dir] [--engine hyperframes|remotion|generic] [--title t] [--public]", about: "Start versioning this folder" },
15
+ save: { run: local.save, opts: { message: { type: "string", short: "m" }, prompt: { type: "string", short: "p" }, "prompt-file": S, render: S, "no-render": B, agent: S, resolves: S, star: B, amend: B }, usage: 'save -m "msg" [--prompt "ask"] [--render file] [--resolves c_1,c_2] [--amend]', about: "Snapshot source + newest render as a version" },
16
+ log: { run: local.log, opts: { json: B }, usage: "log [--json]", about: "List versions" },
17
+ status: { run: local.status, opts: {}, usage: "status", about: "What changed since HEAD" },
18
+ diff: { run: local.diff, opts: { patch: B }, usage: "diff [a] [b] [--patch]", about: "Compare two versions (or HEAD with your files)" },
19
+ checkout: { run: local.checkout, opts: { force: B, render: B }, usage: "checkout <n> [--force] [--render]", about: "Restore a version's source" },
20
+ engines: { run: local.engines, opts: {}, usage: "engines", about: "List supported engines" },
21
+ login: { run: remote.login, opts: { token: S, "no-browser": B, ...remoteOpt }, usage: "login [--remote url] [--token t]", about: "Connect this machine to a server" },
22
+ logout: { run: remote.logout, opts: remoteOpt, usage: "logout", about: "Forget the saved token" },
23
+ whoami: { run: remote.whoami, opts: remoteOpt, usage: "whoami", about: "Show account, plan and storage" },
24
+ push: { run: remote.push, opts: { public: B, private: B, link: B, ...remoteOpt }, usage: "push [--public|--private] [--link]", about: "Upload new versions. Private by default; --public shares it (--link: reattach to your project with this slug)" },
25
+ feedback: { run: remote.feedback, opts: { json: B, all: B, "no-frames": B, ...remoteOpt }, usage: "feedback [--json] [--all] [--no-frames]", about: "Pull frame comments for your agent" },
26
+ resolve: { run: remote.resolve, opts: { reopen: B, ...remoteOpt }, usage: "resolve <c_id,...> [--reopen]", about: "Mark comments done" },
27
+ fork: { run: remote.fork, opts: { "with-render": B, ...remoteOpt }, usage: "fork <handle/slug[@n]> [dir] [--with-render]", about: "Copy a project to build on" },
28
+ remix: { run: remote.remix, opts: { engine: S, title: S, ...remoteOpt }, usage: "remix <handle/slug[@n]> [dir]", about: "Start your own video in another one's style" },
29
+ open: { run: remote.open, opts: {}, usage: "open [n]", about: "Open the project page" },
30
+ watch: { run: video.watch, opts: { out: S, force: B, bursts: S, json: B, ...remoteOpt }, usage: "watch <video|v3|handle/slug[@n]|url> [--out dir] [--force]", about: "Turn a video into sheets, shots, bursts, beats and a cue sheet an agent can read" },
31
+ match: { run: video.match, opts: { out: S, threshold: S, all: B, json: B, ...remoteOpt }, usage: "match <reference> [yours] [--threshold 0.75] [--all]", about: "Score your render against a reference, shot by shot (images only for what fails or changed)" },
32
+ vdiff: { run: video.vdiff, opts: {}, usage: "vdiff [a] [b]", about: "What visibly changed between two takes (default: last render vs the one before)" },
33
+ skill: { run: skill, opts: { claude: B, codex: B, dir: S }, usage: "skill install [--claude] [--codex] | print | agents-md", about: "Teach Claude Code / Codex to use this" },
34
+ };
35
+ COMMANDS["pull-feedback"] = COMMANDS.feedback;
36
+
37
+ function help() {
38
+ console.log(`${c.bold(BRAND.name)} — version control for agent-made video\n`);
39
+ console.log(`Usage: ${BRAND.bin} <command>\n`);
40
+ for (const [name, cmd] of Object.entries(COMMANDS)) {
41
+ if (name === "pull-feedback") continue;
42
+ console.log(` ${c.cyan(cmd.usage)}\n ${c.dim(cmd.about)}`);
43
+ }
44
+ console.log(`\nEnvironment: ${BRAND.remoteEnv} (server URL), ${BRAND.tokenEnv} (token for CI/agents).`);
45
+ }
46
+
47
+ export async function main(argv) {
48
+ const [name, ...rest] = argv;
49
+ if (!name || name === "help" || name === "--help" || name === "-h") return help();
50
+ if (name === "--version" || name === "-v") return console.log("0.1.0");
51
+ const cmd = COMMANDS[name];
52
+ if (!cmd) {
53
+ console.error(`Unknown command "${name}". Run \`${BRAND.bin} help\`.`);
54
+ process.exitCode = 1;
55
+ return;
56
+ }
57
+ try {
58
+ const args = parseArgs({ args: rest, options: { help: { type: "boolean", short: "h" }, ...cmd.opts }, allowPositionals: true, strict: true });
59
+ if (args.values.help) return console.log(`${BRAND.bin} ${cmd.usage}\n ${cmd.about}`);
60
+ await cmd.run(args);
61
+ } catch (e) {
62
+ if (e instanceof CliError || e?.code?.startsWith?.("ERR_PARSE_ARGS")) {
63
+ console.error(`${c.red("✗")} ${e.message}`);
64
+ process.exitCode = 1;
65
+ } else {
66
+ console.error(e);
67
+ process.exitCode = 1;
68
+ }
69
+ }
70
+ }
@@ -0,0 +1,253 @@
1
+ import fs from "node:fs";
2
+ import fsp from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { BRAND } from "../brand.js";
5
+ import { Repo, openRepo, findRoot } from "../store.js";
6
+ import { scan, storeFiles, diffManifests, manifestBytes } from "../snapshot.js";
7
+ import { ADAPTERS, detectAdapter, getAdapter, findRender } from "../adapters/index.js";
8
+ import { probe } from "../media.js";
9
+ import { lineDiff, hunks, countOps, looksText } from "../diff.js";
10
+ import { c, fail, humanBytes, ago, fmtTime, detectAgent, slugify, sha256File } from "../util.js";
11
+
12
+ const IGNORE_TEMPLATE = (adapter) => `# Files ${BRAND.name} should not version, one pattern per line (.gitignore syntax).
13
+ # Already ignored: node_modules/, .git/, ${BRAND.dir}/, .env files, logs${adapter.ignore?.length ? ", " + adapter.ignore.join(", ") : ""}.
14
+ `;
15
+
16
+ export async function init(args) {
17
+ const root = path.resolve(args.positionals[0] || ".");
18
+ fs.mkdirSync(root, { recursive: true });
19
+ const existing = findRoot(root);
20
+ if (existing === root) fail(`Already a ${BRAND.name} project: ${root}`);
21
+ const adapter = args.values.engine ? getAdapter(args.values.engine) : detectAdapter(root);
22
+ const title = args.values.title || path.basename(root);
23
+ const repo = Repo.create(root, {
24
+ format: 1,
25
+ engine: adapter.id,
26
+ title,
27
+ slug: slugify(args.values.slug || title),
28
+ remote: args.values.remote || null,
29
+ visibility: args.values.public ? "public" : "private",
30
+ head: null,
31
+ project: null,
32
+ forkedFrom: null,
33
+ });
34
+ const ig = path.join(root, BRAND.ignoreFile);
35
+ if (!fs.existsSync(ig)) fs.writeFileSync(ig, IGNORE_TEMPLATE(adapter));
36
+ console.log(`${c.green("✓")} ${BRAND.name} project ready in ${repo.root}`);
37
+ console.log(` engine ${c.bold(adapter.label)}${args.values.engine ? "" : c.dim(" (detected)")}`);
38
+ if (adapter.renderHint) console.log(` render ${c.dim(adapter.renderHint)}`);
39
+ console.log(`\n After each render: ${c.cyan(`${BRAND.bin} save -m "what changed" --prompt "what you asked for"`)}`);
40
+ return repo;
41
+ }
42
+
43
+ function readPrompt(values) {
44
+ if (values["prompt-file"]) return fs.readFileSync(values["prompt-file"], "utf8").trim();
45
+ return values.prompt?.trim() || null;
46
+ }
47
+
48
+ export async function save(args) {
49
+ const repo = openRepo();
50
+ const cfg = repo.config;
51
+ const adapter = getAdapter(cfg.engine);
52
+ const parent = cfg.head != null ? repo.version(cfg.head) : null;
53
+ const amend = Boolean(args.values.amend);
54
+ if (amend && !parent) fail("Nothing to amend yet.");
55
+ if (amend && parent.remote) fail(`v${parent.n} is already pushed; save a new version instead.`);
56
+ const base = amend ? (parent.parent != null ? repo.version(parent.parent) : null) : parent;
57
+
58
+ const files = await scan(repo, adapter);
59
+ if (!Object.keys(files).length) fail("No files to version here (everything is ignored or the folder is empty).");
60
+ await storeFiles(repo, files);
61
+
62
+ // The render: explicit path, or the newest video in the engine's render folders.
63
+ let render = null;
64
+ if (!args.values["no-render"]) {
65
+ let file = args.values.render ? path.resolve(args.values.render) : findRender(repo.root, adapter)?.path;
66
+ if (args.values.render && !fs.existsSync(file)) fail(`Render not found: ${args.values.render}`);
67
+ if (file) {
68
+ const h = await sha256File(file);
69
+ const stale = !args.values.render && base?.render?.h === h;
70
+ if (!stale) {
71
+ await repo.putFile(file, h);
72
+ const info = probe(file);
73
+ render = { h, s: fs.statSync(file).size, path: path.relative(repo.root, file).split(path.sep).join("/"), ...info };
74
+ }
75
+ }
76
+ }
77
+
78
+ const d = diffManifests(base?.files, files);
79
+ if (!amend && base && d.total === 0 && !render) {
80
+ console.log(`Nothing changed since v${base.n}. ${c.dim("(Render first, or pass --render <file>.)")}`);
81
+ return null;
82
+ }
83
+
84
+ const timeline = adapter.timeline?.((rel) => {
85
+ try {
86
+ return fs.readFileSync(path.join(repo.root, ...rel.split("/")), "utf8");
87
+ } catch {
88
+ return null;
89
+ }
90
+ }) ?? [];
91
+
92
+ const v = {
93
+ n: amend ? parent.n : repo.nextNumber(),
94
+ parent: base ? base.n : null,
95
+ message: args.values.message || (amend ? parent.message : null) || (base ? `v${repo.nextNumber()}` : "First version"),
96
+ prompt: readPrompt(args.values) ?? (amend ? parent.prompt : null),
97
+ agent: args.values.agent || detectAgent(),
98
+ engine: adapter.id,
99
+ createdAt: new Date().toISOString(),
100
+ files,
101
+ render: render ?? (amend ? parent.render : null),
102
+ poster: null,
103
+ preview: null,
104
+ timeline,
105
+ resolves: (args.values.resolves || "").split(",").map((s) => s.trim()).filter(Boolean),
106
+ starred: Boolean(args.values.star),
107
+ remote: null,
108
+ };
109
+ if (amend && parent.resolves?.length) v.resolves = [...new Set([...parent.resolves, ...v.resolves])];
110
+ repo.writeVersion(v);
111
+ cfg.head = v.n;
112
+ repo.saveConfig();
113
+
114
+ const parts = [`${d.total} file${d.total === 1 ? "" : "s"} changed`];
115
+ if (v.render) parts.push(`render ${v.render.duration ? v.render.duration.toFixed(1) + "s" : ""} ${v.render.width ? `${v.render.width}×${v.render.height}` : ""}`.trim());
116
+ else parts.push(c.yellow("no new render"));
117
+ console.log(`${c.green("✓")} ${amend ? "Amended" : "Saved"} ${c.bold("v" + v.n)} ${c.dim(parts.join(" · "))}`);
118
+ if (!v.render && adapter.renderHint) console.log(c.dim(` Render with \`${adapter.renderHint}\`, then \`${BRAND.bin} save --amend\`.`));
119
+ if (v.resolves.length) console.log(c.dim(` Resolves ${v.resolves.join(", ")} on push.`));
120
+ return v;
121
+ }
122
+
123
+ export async function log(args) {
124
+ const repo = openRepo();
125
+ const all = repo.versions().reverse();
126
+ if (args.values.json) return console.log(JSON.stringify(all.map(({ files, timeline, ...v }) => ({ ...v, fileCount: Object.keys(files).length })), null, 2));
127
+ if (!all.length) return console.log(`No versions yet. Run \`${BRAND.bin} save\` after your first render.`);
128
+ for (const v of all) {
129
+ const head = v.n === repo.config.head ? c.green(" ← HEAD") : "";
130
+ const render = v.render ? c.cyan(`▶ ${v.render.duration ? v.render.duration.toFixed(1) + "s" : "render"}`) : c.dim("no render");
131
+ const pushed = v.remote ? c.dim(" pushed") : c.yellow(" local");
132
+ console.log(`${c.bold(("v" + v.n).padEnd(5))} ${c.dim(ago(v.createdAt).padEnd(9))} ${v.agent.padEnd(11)} ${render}${pushed}${head}`);
133
+ console.log(` ${v.message}`);
134
+ if (v.prompt) console.log(c.dim(` “${v.prompt.length > 110 ? v.prompt.slice(0, 107) + "…" : v.prompt}”`));
135
+ }
136
+ }
137
+
138
+ export async function status() {
139
+ const repo = openRepo();
140
+ const cfg = repo.config;
141
+ const adapter = getAdapter(cfg.engine);
142
+ const head = cfg.head != null ? repo.version(cfg.head) : null;
143
+ const files = await scan(repo, adapter);
144
+ const d = diffManifests(head?.files, files);
145
+ console.log(`${c.bold(cfg.title)} ${c.dim(`· ${adapter.label} · ${head ? "HEAD v" + head.n : "no versions yet"}`)}`);
146
+ if (cfg.project) console.log(c.dim(` remote ${cfg.project.remote}/${cfg.project.handle}/${cfg.project.slug}`));
147
+ if (!d.total) console.log(" Source unchanged since HEAD.");
148
+ for (const f of d.added) console.log(` ${c.green("+ " + f)}`);
149
+ for (const f of d.changed) console.log(` ${c.yellow("~ " + f)}`);
150
+ for (const f of d.removed) console.log(` ${c.red("- " + f)}`);
151
+ const r = findRender(repo.root, adapter);
152
+ if (r) {
153
+ const h = await sha256File(r.path);
154
+ const isNew = head?.render?.h !== h;
155
+ console.log(` render ${path.relative(repo.root, r.path)} ${isNew ? c.green("(new, will attach on save)") : c.dim("(already on HEAD)")}`);
156
+ } else console.log(c.dim(" no render found yet"));
157
+ const unpushed = repo.versions().filter((v) => !v.remote).length;
158
+ if (unpushed) console.log(c.yellow(` ${unpushed} version${unpushed === 1 ? "" : "s"} not pushed`));
159
+ }
160
+
161
+ function readWorking(repo, rel) {
162
+ try {
163
+ return fs.readFileSync(path.join(repo.root, ...rel.split("/")));
164
+ } catch {
165
+ return null;
166
+ }
167
+ }
168
+
169
+ export async function diff(args) {
170
+ const repo = openRepo();
171
+ const adapter = getAdapter(repo.config.engine);
172
+ const [ra, rb] = args.positionals;
173
+ const a = repo.resolveRef(ra ?? "HEAD");
174
+ let bFiles;
175
+ let bLabel;
176
+ let readB;
177
+ if (rb) {
178
+ const b = repo.resolveRef(rb);
179
+ bFiles = b.files;
180
+ bLabel = `v${b.n}`;
181
+ readB = (rel) => (b.files[rel] ? repo.readObj(b.files[rel].h) : null);
182
+ if (a.render || b.render) {
183
+ const da = a.render?.duration;
184
+ const db = b.render?.duration;
185
+ console.log(c.dim(`render: ${da ? da.toFixed(2) + "s" : "none"} → ${db ? db.toFixed(2) + "s" : "none"}`));
186
+ }
187
+ if (b.prompt) console.log(c.dim(`prompt (v${b.n}): ${b.prompt}`));
188
+ } else {
189
+ bFiles = await scan(repo, adapter);
190
+ bLabel = "working tree";
191
+ readB = (rel) => readWorking(repo, rel);
192
+ }
193
+ const d = diffManifests(a.files, bFiles);
194
+ console.log(`${c.bold(`v${a.n} → ${bLabel}`)} ${d.total} file${d.total === 1 ? "" : "s"} changed`);
195
+ const showPatch = Boolean(args.values.patch);
196
+ for (const f of [...d.changed, ...d.added, ...d.removed]) {
197
+ const before = a.files[f] ? repo.readObj(a.files[f].h) : null;
198
+ const after = bFiles[f] ? readB(f) : null;
199
+ const mark = !before ? c.green("+") : !after ? c.red("-") : c.yellow("~");
200
+ if ((before && !looksText(before)) || (after && !looksText(after))) {
201
+ console.log(`${mark} ${f} ${c.dim(`(binary ${humanBytes(before?.length)} → ${humanBytes(after?.length)})`)}`);
202
+ continue;
203
+ }
204
+ const ops = lineDiff(before?.toString("utf8") ?? "", after?.toString("utf8") ?? "");
205
+ if (!ops) {
206
+ console.log(`${mark} ${f} ${c.dim("(too large to diff)")}`);
207
+ continue;
208
+ }
209
+ const n = countOps(ops);
210
+ console.log(`${mark} ${f} ${c.green("+" + n.add)} ${c.red("-" + n.del)}`);
211
+ if (showPatch)
212
+ for (const line of hunks(ops))
213
+ console.log(line.startsWith("@@") ? c.cyan(line) : line[0] === "+" ? c.green(line) : line[0] === "-" ? c.red(line) : c.dim(line));
214
+ }
215
+ if (!showPatch && d.total) console.log(c.dim(`\nAdd --patch for line-by-line changes.`));
216
+ }
217
+
218
+ export async function checkout(args) {
219
+ const repo = openRepo();
220
+ const adapter = getAdapter(repo.config.engine);
221
+ const target = repo.resolveRef(args.positionals[0]);
222
+ const head = repo.config.head != null ? repo.version(repo.config.head) : null;
223
+ const working = await scan(repo, adapter);
224
+ const dirty = diffManifests(head?.files, working);
225
+ if (dirty.total && !args.values.force)
226
+ fail(`You have ${dirty.total} unsaved change${dirty.total === 1 ? "" : "s"}. Save them first, or pass --force to discard.`);
227
+ for (const [rel, f] of Object.entries(target.files)) {
228
+ if (working[rel]?.h === f.h) continue;
229
+ if (!repo.hasObj(f.h)) fail(`Missing object for ${rel}; this version was not saved on this machine.`);
230
+ const dest = path.join(repo.root, ...rel.split("/"));
231
+ await fsp.mkdir(path.dirname(dest), { recursive: true });
232
+ await fsp.copyFile(repo.objPath(f.h), dest);
233
+ }
234
+ // Remove files that HEAD tracked but the target doesn't. Untracked files are left alone.
235
+ for (const rel of Object.keys(head?.files ?? {})) {
236
+ if (!(rel in target.files) && rel in working) await fsp.rm(path.join(repo.root, ...rel.split("/")), { force: true });
237
+ }
238
+ if (args.values.render && target.render && repo.hasObj(target.render.h)) {
239
+ const dest = path.join(repo.root, ...target.render.path.split("/"));
240
+ await fsp.mkdir(path.dirname(dest), { recursive: true });
241
+ await fsp.copyFile(repo.objPath(target.render.h), dest);
242
+ }
243
+ repo.config.head = target.n;
244
+ repo.saveConfig();
245
+ console.log(`${c.green("✓")} Checked out ${c.bold("v" + target.n)} — ${target.message}`);
246
+ console.log(c.dim(` The next save will branch from v${target.n}.`));
247
+ }
248
+
249
+ export function engines() {
250
+ for (const a of ADAPTERS) console.log(`${c.bold(a.id.padEnd(12))} ${a.label}${a.renderHint ? c.dim(" " + a.renderHint) : ""}`);
251
+ }
252
+
253
+ export { manifestBytes };