rushes 0.2.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.
Files changed (77) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/.claude-plugin/plugin.json +10 -0
  3. package/.mcp.json +8 -0
  4. package/AGENTS.md +110 -0
  5. package/LICENSE +21 -0
  6. package/README.md +204 -0
  7. package/dist/cli/demo.js +339 -0
  8. package/dist/cli/doctor.js +307 -0
  9. package/dist/cli/index.js +11 -0
  10. package/dist/cli/main.js +469 -0
  11. package/dist/core/batches.js +58 -0
  12. package/dist/core/errors.js +37 -0
  13. package/dist/core/exportNotes.js +132 -0
  14. package/dist/core/ids.js +42 -0
  15. package/dist/core/media.js +128 -0
  16. package/dist/core/notes.js +117 -0
  17. package/dist/core/paths.js +17 -0
  18. package/dist/core/project.js +200 -0
  19. package/dist/core/schema.js +220 -0
  20. package/dist/core/script.js +113 -0
  21. package/dist/core/store.js +132 -0
  22. package/dist/core/tabs.js +24 -0
  23. package/dist/mcp/client.js +50 -0
  24. package/dist/mcp/ensure.js +69 -0
  25. package/dist/mcp/stdio.js +47 -0
  26. package/dist/mcp/tools.js +191 -0
  27. package/dist/server/app.js +710 -0
  28. package/dist/server/assets.js +234 -0
  29. package/dist/server/files.js +170 -0
  30. package/dist/server/lock.js +148 -0
  31. package/dist/server/loudness.js +331 -0
  32. package/dist/server/proxy.js +575 -0
  33. package/dist/server/reveal.js +71 -0
  34. package/dist/server/start.js +125 -0
  35. package/dist/server/watch.js +133 -0
  36. package/dist/setup/env.js +42 -0
  37. package/dist/setup/harnesses.js +93 -0
  38. package/dist/setup/setup.js +92 -0
  39. package/package.json +54 -0
  40. package/skills/rushes/SKILL.md +30 -0
  41. package/web-dist/assets/figtree-latin-400-normal-BD4aNku5.woff +0 -0
  42. package/web-dist/assets/figtree-latin-400-normal-g7Dtegnw.woff2 +0 -0
  43. package/web-dist/assets/figtree-latin-500-normal-BWnGEVsr.woff2 +0 -0
  44. package/web-dist/assets/figtree-latin-500-normal-B_yy1phn.woff +0 -0
  45. package/web-dist/assets/figtree-latin-600-normal-BM_oTo4n.woff +0 -0
  46. package/web-dist/assets/figtree-latin-600-normal-Cv_xCTDl.woff2 +0 -0
  47. package/web-dist/assets/figtree-latin-700-normal-BCCt2T1q.woff +0 -0
  48. package/web-dist/assets/figtree-latin-700-normal-th6qEP7c.woff2 +0 -0
  49. package/web-dist/assets/figtree-latin-ext-400-normal-CXAzuTZb.woff2 +0 -0
  50. package/web-dist/assets/figtree-latin-ext-400-normal-Gbh-3PTk.woff +0 -0
  51. package/web-dist/assets/figtree-latin-ext-500-normal-BOEJvrb_.woff +0 -0
  52. package/web-dist/assets/figtree-latin-ext-500-normal-Du0rIuHj.woff2 +0 -0
  53. package/web-dist/assets/figtree-latin-ext-600-normal-CQqsimlV.woff +0 -0
  54. package/web-dist/assets/figtree-latin-ext-600-normal-DJlfifZj.woff2 +0 -0
  55. package/web-dist/assets/figtree-latin-ext-700-normal-BoDi4KL2.woff +0 -0
  56. package/web-dist/assets/figtree-latin-ext-700-normal-CS4sQkGV.woff2 +0 -0
  57. package/web-dist/assets/index-BjDIT_wL.css +1 -0
  58. package/web-dist/assets/index-DF6Rl-Ac.js +3 -0
  59. package/web-dist/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  60. package/web-dist/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  61. package/web-dist/assets/jetbrains-mono-cyrillic-500-normal-DJqRU3vO.woff +0 -0
  62. package/web-dist/assets/jetbrains-mono-cyrillic-500-normal-DmUKJPL_.woff2 +0 -0
  63. package/web-dist/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  64. package/web-dist/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  65. package/web-dist/assets/jetbrains-mono-greek-500-normal-D7SFKleX.woff +0 -0
  66. package/web-dist/assets/jetbrains-mono-greek-500-normal-JpySY46c.woff2 +0 -0
  67. package/web-dist/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  68. package/web-dist/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  69. package/web-dist/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
  70. package/web-dist/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
  71. package/web-dist/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  72. package/web-dist/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  73. package/web-dist/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
  74. package/web-dist/assets/jetbrains-mono-latin-ext-500-normal-ckzbgY84.woff +0 -0
  75. package/web-dist/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  76. package/web-dist/assets/jetbrains-mono-vietnamese-500-normal-DNRqzVM1.woff +0 -0
  77. package/web-dist/index.html +14 -0
@@ -0,0 +1,220 @@
1
+ import { z } from "zod";
2
+ export const STAGES = ["script", "picture", "voice", "music", "sfx", "mix"];
3
+ export const StageSchema = z.enum(STAGES);
4
+ export const LaneStageSchema = z.enum(["voice", "music", "sfx"]);
5
+ const id = z.string().min(1).max(64);
6
+ const seconds = z.number().nonnegative();
7
+ export const ProjectIdSchema = z.string().regex(/^[abcdefghjkmnpqrstuvwxyz23456789]{8}$/);
8
+ export const ShotSchema = z.object({
9
+ n: z.number().int().positive(),
10
+ name: z.string().trim().min(1).max(80),
11
+ start: z.number().nonnegative(),
12
+ tag: z.string().trim().max(24).default(""),
13
+ });
14
+ export const ProxySchema = z.object({
15
+ /** Manifest path, always "proxies/<film-slug>_<version>_proxy.mp4". */
16
+ file: z.string().min(1),
17
+ width: z.number().int().positive(),
18
+ height: z.number().int().positive(),
19
+ bytes: z.number().int().nonnegative(),
20
+ createdAt: z.string(),
21
+ });
22
+ export const VersionSchema = z.object({
23
+ id,
24
+ file: z.string().min(1),
25
+ duration: seconds.nullable().default(null),
26
+ fps: z.number().positive().nullable().default(null),
27
+ addedAt: z.string(),
28
+ note: z.string().default(""),
29
+ shots: z.array(ShotSchema).max(200).default([]),
30
+ // §19.5: a lightweight H.264 copy for smooth preview. Set only once a render has completed.
31
+ proxy: ProxySchema.nullable().default(null),
32
+ });
33
+ export const VideoSchema = z.object({
34
+ id,
35
+ name: z.string().min(1),
36
+ versions: z.array(VersionSchema).default([]),
37
+ lockedVersion: z.string().nullable().default(null),
38
+ });
39
+ export const CueSchema = z.object({ id, name: z.string().min(1), t: seconds });
40
+ export const VariantSchema = z.object({
41
+ id,
42
+ name: z.string().min(1),
43
+ file: z.string().min(1),
44
+ meta: z.record(z.string(), z.union([z.string(), z.number()])).default({}),
45
+ cues: z.array(CueSchema).default([]),
46
+ });
47
+ export const LaneSchema = z.object({
48
+ id,
49
+ stage: LaneStageSchema,
50
+ name: z.string().min(1),
51
+ variants: z.array(VariantSchema).default([]),
52
+ });
53
+ export const FileKindSchema = z.enum(["doc", "image", "caption", "export", "delivery", "edit"]);
54
+ export const FileEntrySchema = z.object({
55
+ id,
56
+ kind: FileKindSchema,
57
+ file: z.string().min(1),
58
+ name: z.string().min(1).max(120),
59
+ note: z.string().max(500).default(""),
60
+ video: z.string().nullable().default(null),
61
+ addedAt: z.string(),
62
+ });
63
+ export const ProjectSchema = z.object({
64
+ schema: z.literal(1),
65
+ rev: z.number().int().nonnegative(),
66
+ id: ProjectIdSchema.optional(),
67
+ name: z.string().min(1),
68
+ fps: z.number().positive().default(30),
69
+ videos: z.array(VideoSchema).default([]),
70
+ lanes: z.array(LaneSchema).default([]),
71
+ files: z.array(FileEntrySchema).default([]),
72
+ // §19.5: start a proxy straight away for a new cut that meets the criteria. Off by default.
73
+ autoProxy: z.boolean().default(false),
74
+ });
75
+ export const TakeSchema = z.object({
76
+ id,
77
+ file: z.string().min(1),
78
+ duration: seconds.nullable().default(null),
79
+ forText: z.string(),
80
+ });
81
+ export const SectionStatusSchema = z.enum(["draft", "approved", "flagged"]);
82
+ export const SectionSchema = z
83
+ .object({
84
+ id,
85
+ start: seconds,
86
+ end: seconds,
87
+ current: z.string(),
88
+ proposed: z.string().nullable().default(null),
89
+ direction: z.string().default(""),
90
+ status: SectionStatusSchema.default("draft"),
91
+ takes: z.array(TakeSchema).default([]),
92
+ })
93
+ .refine((s) => s.end > s.start, { message: "end must be after start", path: ["end"] });
94
+ export const ScriptSchema = z.object({
95
+ schema: z.literal(1),
96
+ rev: z.number().int().nonnegative(),
97
+ wordsPerSecond: z.number().positive().default(2.6),
98
+ sections: z.array(SectionSchema).default([]),
99
+ });
100
+ export const BoxSchema = z.object({
101
+ x: z.number().min(0).max(1),
102
+ y: z.number().min(0).max(1),
103
+ w: z.number().min(0).max(1),
104
+ h: z.number().min(0).max(1),
105
+ });
106
+ // §14.5/§17.1: a range note on an audio tab can carry up to four quick marks. Louder/quieter
107
+ // need a dB amount (chosen from 1, 2, 3, 6 or 9 in the UI, 3 the default); rise/fall never carry
108
+ // one. Both rules, plus "no duplicate kinds" and "only on audio-ish stages", are enforced on the
109
+ // note as a whole below, since they depend on more than one mark (or on the note's stage).
110
+ export const MarkSchema = z.object({
111
+ kind: z.enum(["rise", "fall", "louder", "quieter"]),
112
+ db: z.number().min(0.5).max(24).optional(),
113
+ });
114
+ const MARK_STAGES = ["voice", "music", "sfx", "mix"];
115
+ /** "Rise" | "Fall" | "Louder 3 dB" | "Quieter 3 dB". */
116
+ export function markLabel(m) {
117
+ const label = m.kind === "rise" ? "Rise" : m.kind === "fall" ? "Fall" : m.kind === "louder" ? "Louder" : "Quieter";
118
+ return m.db === undefined ? label : `${label} ${m.db} dB`;
119
+ }
120
+ export const NoteSchema = z
121
+ .object({
122
+ id,
123
+ stage: StageSchema,
124
+ video: z.string().nullable().default(null),
125
+ version: z.string().nullable().default(null),
126
+ // What the note is about (§5, §17): null on Picture (and the whole mix on Mix); "<lane>/<variant>"
127
+ // for a variant; "<lane>/<variant>:<cue>" for an SFX cue; "vo" for the assembled read (or Mix's
128
+ // VO lane); "<section>:<take>" for a take; a section id for a section. Older notes may carry a
129
+ // bare variant id, "<variant>:<cue>" or a bare cue id; they still resolve. Not checked here,
130
+ // so every older file still loads.
131
+ on: z
132
+ .string()
133
+ .nullable()
134
+ .default(null)
135
+ .describe('What the note is about: null (Picture, or the whole mix), "<lane>/<variant>", "<lane>/<variant>:<cue>", "vo", "<section>:<take>" or a section id.'),
136
+ scope: z.enum(["point", "range", "whole"]),
137
+ t: seconds.nullable().default(null),
138
+ tOut: seconds.nullable().default(null),
139
+ frame: z.number().int().nonnegative().nullable().default(null),
140
+ text: z.string().trim().min(1).max(4000),
141
+ box: BoxSchema.nullable().default(null),
142
+ grab: z.string().nullable().default(null),
143
+ shot: z.object({ n: z.number().int().positive(), name: z.string() }).nullable().default(null),
144
+ marks: z.array(MarkSchema).max(4).default([]),
145
+ status: z.enum(["todo", "done"]).default("todo"),
146
+ reply: z.string().default(""),
147
+ fixT: seconds.nullable().default(null),
148
+ fixVersion: z.string().nullable().default(null),
149
+ batch: z.string().nullable().default(null),
150
+ createdAt: z.string(),
151
+ by: z.enum(["user", "agent"]).default("user"),
152
+ })
153
+ .superRefine((n, ctx) => {
154
+ if (n.scope === "point" && n.t === null)
155
+ ctx.addIssue({ code: "custom", path: ["t"], message: "a point note needs t" });
156
+ if (n.scope === "range") {
157
+ if (n.t === null || n.tOut === null)
158
+ ctx.addIssue({ code: "custom", path: ["tOut"], message: "a range note needs t and tOut" });
159
+ else if (n.tOut <= n.t)
160
+ ctx.addIssue({ code: "custom", path: ["tOut"], message: "tOut must be after t" });
161
+ }
162
+ if (n.scope === "whole" && (n.t !== null || n.tOut !== null))
163
+ ctx.addIssue({ code: "custom", path: ["scope"], message: "a whole-track note has no t or tOut" });
164
+ if (n.marks.length > 0 && !MARK_STAGES.includes(n.stage)) {
165
+ ctx.addIssue({ code: "custom", path: ["marks"], message: `marks don't apply to the ${n.stage} stage` });
166
+ }
167
+ const seenKinds = new Set();
168
+ for (let i = 0; i < n.marks.length; i++) {
169
+ const m = n.marks[i];
170
+ if ((m.kind === "louder" || m.kind === "quieter") && m.db === undefined) {
171
+ ctx.addIssue({ code: "custom", path: ["marks", i, "db"], message: `${m.kind} needs a db amount` });
172
+ }
173
+ if ((m.kind === "rise" || m.kind === "fall") && m.db !== undefined) {
174
+ ctx.addIssue({ code: "custom", path: ["marks", i, "db"], message: `${m.kind} doesn't take a db amount` });
175
+ }
176
+ if (seenKinds.has(m.kind)) {
177
+ ctx.addIssue({ code: "custom", path: ["marks", i, "kind"], message: `duplicate mark "${m.kind}"` });
178
+ }
179
+ seenKinds.add(m.kind);
180
+ }
181
+ });
182
+ export const NotesFileSchema = z.object({
183
+ schema: z.literal(1),
184
+ rev: z.number().int().nonnegative(),
185
+ notes: z.array(NoteSchema).default([]),
186
+ });
187
+ // §19.6: a Mix lane's level, in dB. −24..6 in 0.5 dB steps; PUT /api/picks enforces the range and
188
+ // step (a value outside it, or off the step, is a 400), so the stored file is never checked again here.
189
+ export const LEVEL_MIN = -24;
190
+ export const LEVEL_MAX = 6;
191
+ export const LEVEL_STEP = 0.5;
192
+ export const LevelsSchema = z.object({ voice: z.number(), music: z.number(), sfx: z.number() }).partial().default({});
193
+ export const PicksSchema = z.object({
194
+ schema: z.literal(1),
195
+ rev: z.number().int().nonnegative(),
196
+ lanes: z.record(z.string(), z.string()).default({}),
197
+ sections: z.record(z.string(), z.string()).default({}),
198
+ // §19.6: each Mix lane's level in dB, defaulting to 0 (absent). Keyed the same as LaneStage.
199
+ levels: LevelsSchema,
200
+ });
201
+ export const BatchSchema = z.object({
202
+ id,
203
+ stage: StageSchema,
204
+ noteIds: z.array(z.string()).default([]),
205
+ sectionIds: z.array(z.string()).default([]),
206
+ sentAt: z.string(),
207
+ prompt: z.string(),
208
+ });
209
+ export const BatchesFileSchema = z.object({
210
+ schema: z.literal(1),
211
+ rev: z.number().int().nonnegative(),
212
+ batches: z.array(BatchSchema).default([]),
213
+ });
214
+ export const FILES = {
215
+ project: { name: "project.json", schema: ProjectSchema },
216
+ script: { name: "script.json", schema: ScriptSchema },
217
+ notes: { name: "notes.json", schema: NotesFileSchema },
218
+ picks: { name: "picks.json", schema: PicksSchema },
219
+ batches: { name: "batches.json", schema: BatchesFileSchema },
220
+ };
@@ -0,0 +1,113 @@
1
+ import { InvalidError, NotFoundError } from "./errors.js";
2
+ import { uniqueId } from "./ids.js";
3
+ /** Does this line fit its slot at reading speed? "tight" means over 80% of the slot. */
4
+ export function fit(text, slotSeconds, wordsPerSecond) {
5
+ const words = (text.trim().match(/\S+/g) ?? []).length;
6
+ const seconds = words / wordsPerSecond;
7
+ const ratio = slotSeconds > 0 ? seconds / slotSeconds : Infinity;
8
+ const state = ratio > 1 ? "over" : ratio > 0.8 ? "tight" : "ok";
9
+ return { words, seconds, ratio, state };
10
+ }
11
+ /** A row counts as changed when the user's version differs from the agent's line. */
12
+ export function isChanged(s) {
13
+ return s.proposed !== null && s.proposed.trim() !== s.current.trim();
14
+ }
15
+ /** A take is stale once the section's line no longer matches the text it was read from. */
16
+ export function isTakeStale(take, s) {
17
+ return take.forText.trim() !== s.current.trim();
18
+ }
19
+ /**
20
+ * Write the agent's sections into the script and return the full, sorted list.
21
+ *
22
+ * By default this merges: an input whose id exists updates that section's
23
+ * start, end and current line; an input with no id or an unknown id is a new
24
+ * section; sections left out stay as they are. With `replace: true` the input
25
+ * becomes the whole list.
26
+ *
27
+ * Either way, a section that keeps its id keeps the user's proposed text,
28
+ * direction, status and takes. A proposal the agent adopts as the current line
29
+ * is cleared because it has landed, and a flagged section whose line the agent
30
+ * changed goes back to draft because the agent has acted on the flag.
31
+ */
32
+ export function setSections(script, input, { replace = false } = {}) {
33
+ const seen = new Set();
34
+ const existing = new Set(script.sections.map((s) => s.id));
35
+ for (const s of input) {
36
+ if (!(s.end > s.start))
37
+ throw new InvalidError(`Section at ${s.start}s must end after it starts`);
38
+ if (s.id === undefined)
39
+ continue;
40
+ if (seen.has(s.id))
41
+ throw new InvalidError(`Section id "${s.id}" appears twice`);
42
+ // A note's `on` reads "vo" as the read, "<section>:<take>" as a take and "<lane>/<variant>" as
43
+ // a variant, so a new section can't take an id that would read as one of those. Only new ids
44
+ // are checked: a script saved before this rule still loads and updates.
45
+ if (!existing.has(s.id) && (s.id === "vo" || /[:/]/.test(s.id))) {
46
+ throw new InvalidError(`Section id "${s.id}" can't be "vo" or contain ":" or "/"`);
47
+ }
48
+ seen.add(s.id);
49
+ }
50
+ const old = new Map(script.sections.map((s) => [s.id, s]));
51
+ const kept = replace ? [] : script.sections.filter((s) => !seen.has(s.id));
52
+ const incoming = input.map((s) => {
53
+ const prev = s.id === undefined ? undefined : old.get(s.id);
54
+ const landed = prev?.proposed != null && prev.proposed.trim() === s.current.trim();
55
+ const reworked = prev !== undefined && prev.current.trim() !== s.current.trim();
56
+ const status = !prev || landed || (reworked && prev.status === "flagged") ? "draft" : prev.status;
57
+ return {
58
+ id: s.id ?? null,
59
+ start: s.start,
60
+ end: s.end,
61
+ current: s.current,
62
+ proposed: landed ? null : prev?.proposed ?? null,
63
+ direction: prev?.direction ?? "",
64
+ status,
65
+ takes: prev?.takes ?? [],
66
+ };
67
+ });
68
+ const sorted = [...kept, ...incoming].sort((a, b) => a.start - b.start);
69
+ for (let i = 1; i < sorted.length; i++) {
70
+ if (sorted[i].start < sorted[i - 1].end)
71
+ throw new InvalidError(`Sections overlap at ${sorted[i].start}s`);
72
+ }
73
+ // New sections without an id get s<n>, starting from their position, skipping ids already taken.
74
+ const taken = new Set(sorted.flatMap((s) => (s.id === null ? [] : [s.id])));
75
+ const next = sorted.map((s, i) => {
76
+ if (s.id !== null)
77
+ return s;
78
+ let n = i + 1;
79
+ while (taken.has(`s${n}`))
80
+ n++;
81
+ taken.add(`s${n}`);
82
+ return { ...s, id: `s${n}` };
83
+ });
84
+ script.sections = next;
85
+ return next;
86
+ }
87
+ export function findSection(script, id) {
88
+ const s = script.sections.find((x) => x.id === id);
89
+ if (!s)
90
+ throw new NotFoundError("section", id);
91
+ return s;
92
+ }
93
+ export function editSection(script, id, edit) {
94
+ const s = findSection(script, id);
95
+ if (edit.proposed !== undefined)
96
+ s.proposed = edit.proposed;
97
+ if (edit.direction !== undefined)
98
+ s.direction = edit.direction;
99
+ if (edit.status !== undefined)
100
+ s.status = edit.status;
101
+ return s;
102
+ }
103
+ export function addTake(script, sectionId, input) {
104
+ const s = findSection(script, sectionId);
105
+ const take = {
106
+ id: uniqueId(`t${s.takes.length + 1}`, s.takes.map((t) => t.id)),
107
+ file: input.file,
108
+ duration: input.duration ?? null,
109
+ forText: s.current,
110
+ };
111
+ s.takes.push(take);
112
+ return take;
113
+ }
@@ -0,0 +1,132 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { mkdir, readFile, rename, writeFile, copyFile, access } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { FILES } from "./schema.js";
5
+ import { CorruptFileError, InvalidError, RevConflictError } from "./errors.js";
6
+ export const RUSHES_DIR = ".rushes";
7
+ const GITIGNORE = "proxies/\npeaks/\nserver.json\nserver.log\n*.tmp\n*.bak\n";
8
+ function defaults(key, name) {
9
+ switch (key) {
10
+ case "project":
11
+ return { schema: 1, rev: 0, name, fps: 30, videos: [], lanes: [], files: [], autoProxy: false };
12
+ case "script":
13
+ return { schema: 1, rev: 0, wordsPerSecond: 2.6, sections: [] };
14
+ case "notes":
15
+ return { schema: 1, rev: 0, notes: [] };
16
+ case "picks":
17
+ return { schema: 1, rev: 0, lanes: {}, sections: {}, levels: {} };
18
+ case "batches":
19
+ return { schema: 1, rev: 0, batches: [] };
20
+ }
21
+ }
22
+ /**
23
+ * The only writer of a project's .rushes folder. Every write is validated,
24
+ * serialised per file, written atomically (tmp + rename) and announced with
25
+ * a "change" event.
26
+ */
27
+ export class Store extends EventEmitter {
28
+ root;
29
+ dir;
30
+ queues = new Map();
31
+ /** The last rev announced for each file, so a watcher can tell our writes from hand edits. */
32
+ announced = new Map();
33
+ constructor(root) {
34
+ super();
35
+ this.root = root;
36
+ this.dir = join(root, RUSHES_DIR);
37
+ }
38
+ path(key) {
39
+ return join(this.dir, FILES[key].name);
40
+ }
41
+ async init(name) {
42
+ await mkdir(join(this.dir, "grabs"), { recursive: true });
43
+ await writeIfMissing(join(this.dir, ".gitignore"), GITIGNORE);
44
+ for (const key of Object.keys(FILES)) {
45
+ await writeIfMissing(this.path(key), serialise(defaults(key, name)));
46
+ }
47
+ }
48
+ async read(key) {
49
+ const file = FILES[key].name;
50
+ let raw;
51
+ try {
52
+ raw = await readFile(this.path(key), "utf8");
53
+ }
54
+ catch (e) {
55
+ if (e.code === "ENOENT")
56
+ throw new CorruptFileError(file, "missing; run rushes init");
57
+ throw e;
58
+ }
59
+ let json;
60
+ try {
61
+ json = JSON.parse(raw);
62
+ }
63
+ catch (e) {
64
+ throw new CorruptFileError(file, `invalid JSON (${e.message})`);
65
+ }
66
+ const parsed = FILES[key].schema.safeParse(json);
67
+ if (!parsed.success)
68
+ throw new CorruptFileError(file, parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "));
69
+ return parsed.data;
70
+ }
71
+ /**
72
+ * Read, change and write one file. `fn` mutates the draft and may return a
73
+ * value, which update() passes back. Pass `expectedRev` to reject the write
74
+ * if the file changed since the caller read it.
75
+ */
76
+ update(key, fn, expectedRev) {
77
+ const prev = this.queues.get(key) ?? Promise.resolve();
78
+ const run = prev.catch(() => undefined).then(async () => {
79
+ const draft = await this.read(key);
80
+ if (expectedRev !== undefined && expectedRev !== draft.rev)
81
+ throw new RevConflictError(FILES[key].name, expectedRev, draft.rev);
82
+ const result = fn(draft);
83
+ draft.rev += 1;
84
+ const checked = FILES[key].schema.safeParse(draft);
85
+ if (!checked.success)
86
+ throw new InvalidError(`Change to ${FILES[key].name} is invalid`, checked.error.issues);
87
+ const data = checked.data;
88
+ await atomicWrite(this.path(key), serialise(data));
89
+ this.announce(key, data.rev);
90
+ return { data, result };
91
+ });
92
+ this.queues.set(key, run);
93
+ return run;
94
+ }
95
+ /** Emit a change for `key` at `rev` unless that rev was already announced. Returns whether it emitted. */
96
+ announce(key, rev) {
97
+ if (this.announced.get(key) === rev)
98
+ return false;
99
+ this.announced.set(key, rev);
100
+ this.emit("change", { file: key, rev });
101
+ return true;
102
+ }
103
+ /** Forget the last announced rev for `key`, so the next valid read announces even at the same rev it had before. */
104
+ forget(key) {
105
+ this.announced.delete(key);
106
+ }
107
+ /** Record `rev` as already announced for `key`, without emitting. Used to seed a freshly attached watcher with a file's starting state, so it isn't mistaken for a hand edit. */
108
+ seed(key, rev) {
109
+ this.announced.set(key, rev);
110
+ }
111
+ async backup(key) {
112
+ const to = this.path(key) + ".bak";
113
+ await copyFile(this.path(key), to);
114
+ return to;
115
+ }
116
+ }
117
+ export function serialise(data) {
118
+ return JSON.stringify(data, null, 2) + "\n";
119
+ }
120
+ async function atomicWrite(path, text) {
121
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
122
+ await writeFile(tmp, text, "utf8");
123
+ await rename(tmp, path);
124
+ }
125
+ async function writeIfMissing(path, text) {
126
+ try {
127
+ await access(path);
128
+ }
129
+ catch {
130
+ await writeFile(path, text, "utf8");
131
+ }
132
+ }
@@ -0,0 +1,24 @@
1
+ import { STAGES } from "./schema.js";
2
+ import { isChanged } from "./script.js";
3
+ function laneHasVariants(p, stage) {
4
+ return p.lanes.some((l) => l.stage === stage && l.variants.length > 0);
5
+ }
6
+ export function tabStates(p, s, n) {
7
+ const picture = p.videos.some((v) => v.versions.length > 0);
8
+ const voice = laneHasVariants(p, "voice");
9
+ const music = laneHasVariants(p, "music");
10
+ const sfx = laneHasVariants(p, "sfx");
11
+ const unlocked = {
12
+ script: s.sections.length > 0,
13
+ picture,
14
+ voice,
15
+ music,
16
+ sfx,
17
+ mix: picture && (voice || music || sfx),
18
+ };
19
+ return STAGES.map((stage) => {
20
+ const notes = n.notes.filter((x) => x.stage === stage && x.status === "todo").length;
21
+ const rows = stage === "script" ? s.sections.filter((x) => isChanged(x) || x.status === "flagged").length : 0;
22
+ return { stage, unlocked: unlocked[stage], todo: notes + rows };
23
+ });
24
+ }
@@ -0,0 +1,50 @@
1
+ import { ProjectIdSchema } from "../core/schema.js";
2
+ /** Thin HTTP client for the Rushes server API, used by the MCP server and the CLI. */
3
+ export class ApiError extends Error {
4
+ status;
5
+ body;
6
+ constructor(status, body) {
7
+ super(body.message ?? `Rushes server returned ${status}`);
8
+ this.status = status;
9
+ this.body = body;
10
+ }
11
+ }
12
+ export class RushesClient {
13
+ baseUrl;
14
+ constructor(baseUrl) {
15
+ this.baseUrl = baseUrl;
16
+ }
17
+ async call(method, path, json) {
18
+ const res = await fetch(this.baseUrl + path, {
19
+ method,
20
+ headers: json === undefined ? {} : { "content-type": "application/json" },
21
+ body: json === undefined ? undefined : JSON.stringify(json),
22
+ });
23
+ const text = await res.text();
24
+ const body = text ? JSON.parse(text) : {};
25
+ if (!res.ok)
26
+ throw new ApiError(res.status, body);
27
+ return body;
28
+ }
29
+ get(path) { return this.call("GET", path); }
30
+ post(path, json) { return this.call("POST", path, json); }
31
+ put(path, json) { return this.call("PUT", path, json); }
32
+ patch(path, json) { return this.call("PATCH", path, json); }
33
+ }
34
+ /**
35
+ * The dashboard address for a running server, read from its own health check: `${base}/p/${id}/`
36
+ * for a current server, or `${base}/` for an older one (before project ids) that serves its
37
+ * own dashboard there instead of at a `/p/<id>/` address.
38
+ */
39
+ export async function dashboardUrlFor(base) {
40
+ let health;
41
+ try {
42
+ health = await new RushesClient(base).get("/api/health");
43
+ }
44
+ catch {
45
+ throw new Error(`Rushes at ${base} didn't answer its health check`);
46
+ }
47
+ if (!health.id || !ProjectIdSchema.safeParse(health.id).success)
48
+ return `${base}/`;
49
+ return `${base}/p/${health.id}/`;
50
+ }
@@ -0,0 +1,69 @@
1
+ import { spawn } from "node:child_process";
2
+ import { closeSync, mkdirSync, openSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { canonicalRoot, isRushesFor, readLock } from "../server/lock.js";
6
+ import { RushesClient } from "./client.js";
7
+ import { SOURCE } from "../setup/harnesses.js";
8
+ import { RUSHES_DIR } from "../core/store.js";
9
+ /** URL of a live Rushes server for exactly this project root, or null. */
10
+ export async function findServer(rootDir) {
11
+ const root = await canonicalRoot(rootDir);
12
+ const lock = await readLock(root);
13
+ if (!lock)
14
+ return null;
15
+ // A reused port or pid can point at something else, so check it's ours.
16
+ return (await isRushesFor(lock.port, root)) ? `http://127.0.0.1:${lock.port}` : null;
17
+ }
18
+ /** Background servers started for an agent stop after this long with nothing connected. */
19
+ export const BACKGROUND_IDLE_MINUTES = 120;
20
+ /** Where a background server's output goes, so a failed start leaves evidence. */
21
+ export function serverLogPath(root) {
22
+ return join(root, RUSHES_DIR, "server.log");
23
+ }
24
+ function defaultSpawn(root) {
25
+ const cli = fileURLToPath(new URL("../cli/index.js", import.meta.url));
26
+ let log = "ignore";
27
+ try {
28
+ mkdirSync(join(root, RUSHES_DIR), { recursive: true });
29
+ log = openSync(serverLogPath(root), "a");
30
+ }
31
+ catch {
32
+ // No log if the folder can't be written; the start may still work.
33
+ }
34
+ try {
35
+ const child = spawn(process.execPath, [cli, "serve", root, "--idle-minutes", String(BACKGROUND_IDLE_MINUTES)], { detached: true, stdio: ["ignore", log, log], windowsHide: true });
36
+ child.on("error", () => undefined);
37
+ child.unref();
38
+ }
39
+ finally {
40
+ if (typeof log === "number")
41
+ closeSync(log);
42
+ }
43
+ }
44
+ /** One in-flight ensure per root, so parallel tool calls share a single spawn. */
45
+ const pending = new Map();
46
+ /** Find the project's server, starting one in the background if needed. */
47
+ export async function ensureServer(rootDir, opts = {}) {
48
+ const root = await canonicalRoot(rootDir);
49
+ const inFlight = pending.get(root);
50
+ if (inFlight)
51
+ return inFlight;
52
+ const run = ensure(root, opts).finally(() => pending.delete(root));
53
+ pending.set(root, run);
54
+ return run;
55
+ }
56
+ async function ensure(root, opts) {
57
+ const found = await findServer(root);
58
+ if (found)
59
+ return new RushesClient(found);
60
+ (opts.spawnServer ?? defaultSpawn)(root);
61
+ const deadline = Date.now() + (opts.timeoutMs ?? 8000);
62
+ while (Date.now() < deadline) {
63
+ await new Promise((r) => setTimeout(r, 150));
64
+ const url = await findServer(root);
65
+ if (url)
66
+ return new RushesClient(url);
67
+ }
68
+ throw new Error(`Rushes server did not start for ${root}. Its output is in ${serverLogPath(root)}. Try running "npx -y ${SOURCE} open" in that folder.`);
69
+ }
@@ -0,0 +1,47 @@
1
+ import { spawn } from "node:child_process";
2
+ import { homedir } from "node:os";
3
+ import { dirname, resolve } from "node:path";
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ import { createMcpServer } from "./tools.js";
6
+ import { ensureServer } from "./ensure.js";
7
+ import { runDoctor, realDoctorEnv } from "../cli/doctor.js";
8
+ export function openBrowser(url) {
9
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
10
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
11
+ spawn(cmd, args, { detached: true, stdio: "ignore", windowsHide: true }).on("error", () => undefined).unref();
12
+ }
13
+ /**
14
+ * The project folder a tool call is about: `project` resolved against the
15
+ * folder the harness launched us in. Claude Desktop launches MCP servers in
16
+ * "/" (and some harnesses in the home folder), which is never a video
17
+ * project, so those throw and ask the agent to name one.
18
+ */
19
+ export function resolveProjectRoot(defaultRoot, project) {
20
+ const root = resolve(defaultRoot, project ?? ".");
21
+ if (dirname(root) === root || root === resolve(homedir())) {
22
+ throw new Error('Tell me which project folder to use: pass "project" (e.g. "/Users/you/Videos/launch-film").');
23
+ }
24
+ return root;
25
+ }
26
+ /**
27
+ * Same resolution as `resolveProjectRoot`, but for `rushes_doctor`: controller ruling, doctor
28
+ * never refuses to run just because it was launched at "/" or the home folder. It still reports
29
+ * the Node/ffmpeg/agent checks; its own project checks fall back to "No Rushes project in this
30
+ * folder" there, same as any other folder with no .rushes.
31
+ */
32
+ export function resolveDoctorRoot(defaultRoot, project) {
33
+ return resolve(defaultRoot, project ?? ".");
34
+ }
35
+ /** The tool context runStdio uses. */
36
+ export function stdioContext(defaultRoot, ensure) {
37
+ return {
38
+ client: async (project) => ensureServer(resolveProjectRoot(defaultRoot, project), ensure),
39
+ openBrowser,
40
+ doctor: async (project) => runDoctor(realDoctorEnv(resolveDoctorRoot(defaultRoot, project))),
41
+ };
42
+ }
43
+ /** Run the MCP server over stdio. Projects default to the directory the agent launched it in. */
44
+ export async function runStdio(defaultRoot = process.cwd()) {
45
+ const server = createMcpServer(stdioContext(defaultRoot));
46
+ await server.connect(new StdioServerTransport());
47
+ }