rushes 0.4.0 → 0.5.1

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,82 @@
1
+ import { createHash } from "node:crypto";
2
+ // §24 step 2: brief.md is the file of record for a film's brief. These are pure functions over its
3
+ // text: parse it into sections, replace one section's body, set the Status line. Everything else in
4
+ // the file (the preamble, other sections, the user's own formatting) is left exactly as it was.
5
+ /** The brief's file name, in the project folder's root. */
6
+ export const BRIEF_FILE = "brief.md";
7
+ /** `Status: approved`, and the same in bold or italics (`**Status:** approved`): an agent often writes the line that way. */
8
+ const STATUS_LINE = /^[*_]{0,2}Status[*_]{0,2}:[*_]{0,2}[ \t]*(draft|approved)[ \t]*$/i;
9
+ /** A short fingerprint of the file's text: what a page sends back to prove it saw the current file. */
10
+ export function hashText(text) {
11
+ return createHash("sha1").update(text).digest("hex").slice(0, 12);
12
+ }
13
+ /** The file's own line ending: CRLF when its first line break is one, else LF. */
14
+ const eolOf = (text) => (/\r?\n/.exec(text)?.[0] === "\r\n" ? "\r\n" : "\n");
15
+ /** Lines of `text` (either line ending), and the "## " headings in them. A "## " inside a fenced code block is not a heading. */
16
+ function scan(text) {
17
+ const lines = text.split(/\r?\n/);
18
+ const spans = [];
19
+ let fenced = false;
20
+ lines.forEach((line, i) => {
21
+ if (/^(```|~~~)/.test(line))
22
+ fenced = !fenced;
23
+ const m = !fenced && /^## +(.+?) *$/.exec(line);
24
+ if (m) {
25
+ if (spans.length)
26
+ spans[spans.length - 1].end = i;
27
+ spans.push({ heading: m[1], at: i, end: lines.length });
28
+ }
29
+ });
30
+ return { lines, spans };
31
+ }
32
+ const trimBlank = (ls) => {
33
+ let a = 0;
34
+ let b = ls.length;
35
+ while (a < b && ls[a].trim() === "")
36
+ a++;
37
+ while (b > a && ls[b - 1].trim() === "")
38
+ b--;
39
+ return ls.slice(a, b);
40
+ };
41
+ export function parseBrief(text) {
42
+ const { lines, spans } = scan(text);
43
+ const preamble = lines.slice(0, spans.length ? spans[0].at : lines.length);
44
+ const titleLine = preamble.map((l) => /^# +(.+?) *$/.exec(l)).find(Boolean);
45
+ const title = titleLine ? titleLine[1].replace(/^Brief:[ \t]*/i, "") : "";
46
+ const statusMatch = preamble.map((l) => STATUS_LINE.exec(l)).find(Boolean);
47
+ const status = statusMatch ? statusMatch[1].toLowerCase() : null;
48
+ const sections = spans.map((s) => ({ heading: s.heading, body: trimBlank(lines.slice(s.at + 1, s.end)).join("\n") }));
49
+ return { title, status, sections };
50
+ }
51
+ /**
52
+ * `text` with the body of the section at `index` replaced by `body`. `heading` must be that section's
53
+ * heading (so a file that was reordered under you is refused, not edited in the wrong place).
54
+ * Spacing is kept: one blank line before the next heading, and a single newline at the end of the file.
55
+ */
56
+ export function setSectionBody(text, index, heading, body) {
57
+ const { lines, spans } = scan(text);
58
+ const span = spans[index];
59
+ if (!span || span.heading !== heading)
60
+ throw new Error(`No section "${heading}" at position ${index + 1}`);
61
+ const next = trimBlank(body.replace(/\r\n/g, "\n").split("\n"));
62
+ const isLast = index === spans.length - 1;
63
+ const replacement = [...next, ...(isLast ? [] : [""])];
64
+ const out = [...lines.slice(0, span.at + 1), ...replacement, ...lines.slice(span.end)];
65
+ const eol = eolOf(text);
66
+ return out.join(eol).replace(/(\r?\n)*$/, eol);
67
+ }
68
+ /** `text` with its `Status:` line set. With no such line, one is added under the title (or at the top). */
69
+ export function setStatus(text, status) {
70
+ const { lines, spans } = scan(text);
71
+ const limit = spans.length ? spans[0].at : lines.length;
72
+ const at = lines.slice(0, limit).findIndex((l) => STATUS_LINE.test(l));
73
+ if (at >= 0) {
74
+ const out = [...lines];
75
+ out[at] = `Status: ${status}`;
76
+ return out.join(eolOf(text));
77
+ }
78
+ const title = lines.slice(0, limit).findIndex((l) => /^# /.test(l));
79
+ const insertAt = title >= 0 ? title + 1 : 0;
80
+ const out = [...lines.slice(0, insertAt), "", `Status: ${status}`, ...(title >= 0 ? [] : [""]), ...lines.slice(insertAt)];
81
+ return out.join(eolOf(text));
82
+ }
@@ -3,7 +3,12 @@ import { InvalidError, NotFoundError, RushesError } from "./errors.js";
3
3
  import { labelOfId, versionFormats } from "./formats.js";
4
4
  import { newId } from "./ids.js";
5
5
  export function addNote(file, input, now = new Date()) {
6
- const parsed = NoteSchema.safeParse({ ...input, id: newId("n"), createdAt: now.toISOString() });
6
+ // Ids are short and random (24 bits), so a long file can draw one a note already has, and a reply
7
+ // for one note would then land on the other. Draw again, as the log does.
8
+ let id = newId("n");
9
+ while (file.notes.some((n) => n.id === id))
10
+ id = newId("n");
11
+ const parsed = NoteSchema.safeParse({ ...input, id, createdAt: now.toISOString() });
7
12
  if (!parsed.success)
8
13
  throw new InvalidError("Note is invalid", parsed.error.issues);
9
14
  file.notes.push(parsed.data);
@@ -0,0 +1,22 @@
1
+ // §24.12: is the plan approved? The brief, every script section and every storyboard shot, in that order.
2
+ // A film with no script (an instrumental one) is not waiting on one.
3
+ export function buildState(i) {
4
+ const waitingOn = [];
5
+ if (!(i.brief.exists && i.brief.status === "approved"))
6
+ waitingOn.push("brief");
7
+ if (!i.script.every((s) => s.status === "approved"))
8
+ waitingOn.push("script");
9
+ if (!(i.storyboard.exists && i.storyboard.total > 0 && i.storyboard.approved === i.storyboard.total))
10
+ waitingOn.push("storyboard");
11
+ const started = (i.brief.exists && i.brief.status !== null) || (i.storyboard.exists && i.storyboard.total > 0);
12
+ return { started, ready: started && waitingOn.length === 0, waitingOn };
13
+ }
14
+ /** The words a cut registered before the plan is approved comes back with, or null when there is nothing to say. */
15
+ export function planWarning(b) {
16
+ if (!b.started || b.ready)
17
+ return null;
18
+ const names = { brief: "the brief", script: "the script", storyboard: "the storyboard" };
19
+ const list = b.waitingOn.map((p) => names[p]);
20
+ const text = list.length > 1 ? `${list.slice(0, -1).join(", ")} and ${list[list.length - 1]}` : list[0];
21
+ return `The plan isn't approved yet: still waiting on ${text}.`;
22
+ }
@@ -2,19 +2,29 @@ import { z } from "zod";
2
2
  import { FORMAT_ID_RE, isPictureSize, labelOfId, ratioId, ratioLabel } from "./formats.js";
3
3
  import { oneLineOf } from "./labels.js";
4
4
  import { LOG_AREAS, LOG_BY, LOG_KINDS, LOG_MAX, LOG_TEXT_MAX } from "./logText.js";
5
+ /**
6
+ * An object in one of the project's files. Every write parses the whole file through its schema,
7
+ * and a plain z.object drops the fields it doesn't know, so an older Rushes saving a file that a
8
+ * newer one wrote would quietly delete what the newer one added. This keeps them, at every depth.
9
+ * The type stays the plain shape on purpose: the code reads only the fields it declares, and an
10
+ * index signature on every type would ripple through the whole dashboard.
11
+ */
12
+ function fileObject(shape) {
13
+ return z.looseObject(shape);
14
+ }
5
15
  export const STAGES = ["script", "picture", "voice", "music", "sfx", "mix"];
6
16
  export const StageSchema = z.enum(STAGES);
7
17
  export const LaneStageSchema = z.enum(["voice", "music", "sfx"]);
8
18
  const id = z.string().min(1).max(64);
9
19
  const seconds = z.number().nonnegative();
10
20
  export const ProjectIdSchema = z.string().regex(/^[abcdefghjkmnpqrstuvwxyz23456789]{8}$/);
11
- export const ShotSchema = z.object({
21
+ export const ShotSchema = fileObject({
12
22
  n: z.number().int().positive(),
13
23
  name: z.string().trim().min(1).max(80),
14
24
  start: z.number().nonnegative(),
15
25
  tag: z.string().trim().max(24).default(""),
16
26
  });
17
- export const ProxySchema = z.object({
27
+ export const ProxySchema = fileObject({
18
28
  /** Manifest path, always "proxies/<film-slug>_<version>_proxy.mp4". */
19
29
  file: z.string().min(1),
20
30
  width: z.number().int().positive(),
@@ -23,7 +33,7 @@ export const ProxySchema = z.object({
23
33
  createdAt: z.string(),
24
34
  });
25
35
  // §21.3: another render of the same cut at another aspect ratio. Its id is its label with ":" as "x".
26
- export const FormatSchema = z.object({
36
+ export const FormatSchema = fileObject({
27
37
  id: z.string().max(16).regex(FORMAT_ID_RE),
28
38
  label: z.string().min(3).max(16),
29
39
  file: z.string().min(1),
@@ -69,13 +79,13 @@ export const VersionSchema = z
69
79
  seen.add(f.id);
70
80
  });
71
81
  });
72
- export const VideoSchema = z.object({
82
+ export const VideoSchema = fileObject({
73
83
  id,
74
84
  name: z.string().min(1),
75
85
  versions: z.array(VersionSchema).default([]),
76
86
  lockedVersion: z.string().nullable().default(null),
77
87
  });
78
- export const CueSchema = z.object({
88
+ export const CueSchema = fileObject({
79
89
  id,
80
90
  name: z.string().min(1),
81
91
  t: seconds,
@@ -83,21 +93,21 @@ export const CueSchema = z.object({
83
93
  // absent on every older cue, so a 0.2.x project loads and writes back unchanged.
84
94
  file: z.string().min(1).max(1024).optional(),
85
95
  });
86
- export const VariantSchema = z.object({
96
+ export const VariantSchema = fileObject({
87
97
  id,
88
98
  name: z.string().min(1),
89
99
  file: z.string().min(1),
90
100
  meta: z.record(z.string(), z.union([z.string(), z.number()])).default({}),
91
101
  cues: z.array(CueSchema).default([]),
92
102
  });
93
- export const LaneSchema = z.object({
103
+ export const LaneSchema = fileObject({
94
104
  id,
95
105
  stage: LaneStageSchema,
96
106
  name: z.string().min(1),
97
107
  variants: z.array(VariantSchema).default([]),
98
108
  });
99
109
  export const FileKindSchema = z.enum(["doc", "image", "caption", "export", "delivery", "edit"]);
100
- export const FileEntrySchema = z.object({
110
+ export const FileEntrySchema = fileObject({
101
111
  id,
102
112
  kind: FileKindSchema,
103
113
  file: z.string().min(1),
@@ -106,7 +116,7 @@ export const FileEntrySchema = z.object({
106
116
  video: z.string().nullable().default(null),
107
117
  addedAt: z.string(),
108
118
  });
109
- export const ProjectSchema = z.object({
119
+ export const ProjectSchema = fileObject({
110
120
  schema: z.literal(1),
111
121
  rev: z.number().int().nonnegative(),
112
122
  id: ProjectIdSchema.optional(),
@@ -118,7 +128,7 @@ export const ProjectSchema = z.object({
118
128
  // §19.5: start a proxy straight away for a new cut that meets the criteria. Off by default.
119
129
  autoProxy: z.boolean().default(false),
120
130
  });
121
- export const TakeSchema = z.object({
131
+ export const TakeSchema = fileObject({
122
132
  id,
123
133
  file: z.string().min(1),
124
134
  duration: seconds.nullable().default(null),
@@ -137,13 +147,17 @@ export const SectionSchema = z
137
147
  takes: z.array(TakeSchema).default([]),
138
148
  })
139
149
  .refine((s) => s.end > s.start, { message: "end must be after start", path: ["end"] });
140
- export const ScriptSchema = z.object({
150
+ export const ScriptSchema = fileObject({
141
151
  schema: z.literal(1),
142
152
  rev: z.number().int().nonnegative(),
143
153
  wordsPerSecond: z.number().positive().default(2.6),
144
154
  sections: z.array(SectionSchema).default([]),
155
+ // The highest s<n> number ever given to a section, so a removed section's id is never handed out
156
+ // again for new words. Absent on a script saved before this; setSections then works it out from
157
+ // the ids it can see.
158
+ sectionCounter: z.number().int().nonnegative().optional(),
145
159
  });
146
- export const BoxSchema = z.object({
160
+ export const BoxSchema = fileObject({
147
161
  x: z.number().min(0).max(1),
148
162
  y: z.number().min(0).max(1),
149
163
  w: z.number().min(0).max(1),
@@ -153,7 +167,7 @@ export const BoxSchema = z.object({
153
167
  // need a dB amount (chosen from 1, 2, 3, 6 or 9 in the UI, 3 the default); rise/fall never carry
154
168
  // one. Both rules, plus "no duplicate kinds" and "only on audio-ish stages", are enforced on the
155
169
  // note as a whole below, since they depend on more than one mark (or on the note's stage).
156
- export const MarkSchema = z.object({
170
+ export const MarkSchema = fileObject({
157
171
  kind: z.enum(["rise", "fall", "louder", "quieter"]),
158
172
  db: z.number().min(0.5).max(24).optional(),
159
173
  });
@@ -186,7 +200,7 @@ export const NoteSchema = z
186
200
  text: z.string().trim().min(1).max(4000),
187
201
  box: BoxSchema.nullable().default(null),
188
202
  grab: z.string().nullable().default(null),
189
- shot: z.object({ n: z.number().int().positive(), name: z.string() }).nullable().default(null),
203
+ shot: fileObject({ n: z.number().int().positive(), name: z.string() }).nullable().default(null),
190
204
  marks: z.array(MarkSchema).max(4).default([]),
191
205
  // §21.3: the format this note belongs to (a Format id such as "9x16"), or null for every format:
192
206
  // the default, and every note from before formats. The server checks it against the note's version.
@@ -228,7 +242,7 @@ export const NoteSchema = z
228
242
  seenKinds.add(m.kind);
229
243
  }
230
244
  });
231
- export const NotesFileSchema = z.object({
245
+ export const NotesFileSchema = fileObject({
232
246
  schema: z.literal(1),
233
247
  rev: z.number().int().nonnegative(),
234
248
  notes: z.array(NoteSchema).default([]),
@@ -238,8 +252,8 @@ export const NotesFileSchema = z.object({
238
252
  export const LEVEL_MIN = -24;
239
253
  export const LEVEL_MAX = 6;
240
254
  export const LEVEL_STEP = 0.5;
241
- export const LevelsSchema = z.object({ voice: z.number(), music: z.number(), sfx: z.number() }).partial().default({});
242
- export const PicksSchema = z.object({
255
+ export const LevelsSchema = fileObject({ voice: z.number(), music: z.number(), sfx: z.number() }).partial().default({});
256
+ export const PicksSchema = fileObject({
243
257
  schema: z.literal(1),
244
258
  rev: z.number().int().nonnegative(),
245
259
  lanes: z.record(z.string(), z.string()).default({}),
@@ -247,7 +261,7 @@ export const PicksSchema = z.object({
247
261
  // §19.6: each Mix lane's level in dB, defaulting to 0 (absent). Keyed the same as LaneStage.
248
262
  levels: LevelsSchema,
249
263
  });
250
- export const BatchSchema = z.object({
264
+ export const BatchSchema = fileObject({
251
265
  id,
252
266
  stage: StageSchema,
253
267
  noteIds: z.array(z.string()).default([]),
@@ -255,14 +269,14 @@ export const BatchSchema = z.object({
255
269
  sentAt: z.string(),
256
270
  prompt: z.string(),
257
271
  });
258
- export const BatchesFileSchema = z.object({
272
+ export const BatchesFileSchema = fileObject({
259
273
  schema: z.literal(1),
260
274
  rev: z.number().int().nonnegative(),
261
275
  batches: z.array(BatchSchema).default([]),
262
276
  });
263
277
  // §20.6: the found files the user dismissed ("Not these"), as manifest paths. The candidates
264
278
  // themselves live in the server's memory; only this list is kept. Created on its first write.
265
- export const FoundFileSchema = z.object({
279
+ export const FoundFileSchema = fileObject({
266
280
  schema: z.literal(1),
267
281
  rev: z.number().int().nonnegative(),
268
282
  dismissed: z.array(z.string().max(1024)).max(10000).default([]),
@@ -270,7 +284,7 @@ export const FoundFileSchema = z.object({
270
284
  // ids), so the scoring never also adds a file of that kind for that cut, on any later scan,
271
285
  // start-up or restart. Files from before this field read as empty.
272
286
  settled: z
273
- .array(z.object({
287
+ .array(fileObject({
274
288
  video: z.string().max(200),
275
289
  version: z.string().max(200),
276
290
  kinds: z.array(z.enum(["voice", "music", "sfx", "cut", "other"])).max(5),
@@ -280,7 +294,7 @@ export const FoundFileSchema = z.object({
280
294
  });
281
295
  // §22.3: the Change Log, .rushes/log.json, oldest first on disk. Written by the server as things
282
296
  // happen, created on its first write. Every field is new, so nothing older reads differently.
283
- export const LogEntrySchema = z.object({
297
+ export const LogEntrySchema = fileObject({
284
298
  id,
285
299
  at: z.string(),
286
300
  area: z.enum(LOG_AREAS),
@@ -296,7 +310,7 @@ export const LogEntrySchema = z.object({
296
310
  n: z.number().int().positive().default(1),
297
311
  subject: z.string().max(200).default(""),
298
312
  });
299
- export const LogFileSchema = z.object({
313
+ export const LogFileSchema = fileObject({
300
314
  schema: z.literal(1),
301
315
  rev: z.number().int().nonnegative(),
302
316
  // §22.6: set once the dated history has been read in, so it never happens twice.
@@ -362,6 +376,15 @@ function cleanLine(item) {
362
376
  }
363
377
  /** How log.json is read (see tolerantLog); the store writes it against LogFileSchema. */
364
378
  export const LogFileReadSchema = z.preprocess(tolerantLog, LogFileSchema);
379
+ // §24 step 2: what Rushes remembers about brief.md, which is itself the file of record. `baseline` is the
380
+ // text the last time someone other than the dashboard wrote it (the agent's version: the "Current" column),
381
+ // and `seen` is the hash of the text Rushes last looked at, so a change made behind its back is noticed.
382
+ export const BriefStateSchema = fileObject({
383
+ schema: z.literal(1),
384
+ rev: z.number().int().nonnegative(),
385
+ baseline: z.string().max(1_000_000).default(""),
386
+ seen: z.string().max(64).default(""),
387
+ });
365
388
  export const FILES = {
366
389
  project: { name: "project.json", schema: ProjectSchema },
367
390
  script: { name: "script.json", schema: ScriptSchema },
@@ -370,4 +393,7 @@ export const FILES = {
370
393
  batches: { name: "batches.json", schema: BatchesFileSchema },
371
394
  found: { name: "found.json", schema: FoundFileSchema },
372
395
  log: { name: "log.json", schema: LogFileSchema, read: LogFileReadSchema },
396
+ brief: { name: "brief.json", schema: BriefStateSchema },
397
+ // §24.12: the storyboard is kept the same way as the brief: its file, plus the agent's last text and the hash last seen.
398
+ storyboard: { name: "storyboard.json", schema: BriefStateSchema },
373
399
  };
@@ -26,8 +26,14 @@ export function isTakeStale(take, s) {
26
26
  *
27
27
  * Either way, a section that keeps its id keeps the user's proposed text,
28
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.
29
+ * is cleared because it has landed. A section whose line the agent changed goes
30
+ * back to draft, whatever its status: a flag has been acted on, and an approval
31
+ * was for the words the user read, not the new ones. Re-sending the same words
32
+ * (spacing aside) leaves the status alone.
33
+ *
34
+ * A section sent without an id is given the next s<n> number that has never been
35
+ * used in this script, so a replace with no ids carries on from where the old
36
+ * numbers stopped instead of starting again at s1.
31
37
  */
32
38
  export function setSections(script, input, { replace = false } = {}) {
33
39
  const seen = new Set();
@@ -53,7 +59,7 @@ export function setSections(script, input, { replace = false } = {}) {
53
59
  const prev = s.id === undefined ? undefined : old.get(s.id);
54
60
  const landed = prev?.proposed != null && prev.proposed.trim() === s.current.trim();
55
61
  const reworked = prev !== undefined && prev.current.trim() !== s.current.trim();
56
- const status = !prev || landed || (reworked && prev.status === "flagged") ? "draft" : prev.status;
62
+ const status = !prev || landed || reworked ? "draft" : prev.status;
57
63
  return {
58
64
  id: s.id ?? null,
59
65
  start: s.start,
@@ -70,18 +76,26 @@ export function setSections(script, input, { replace = false } = {}) {
70
76
  if (sorted[i].start < sorted[i - 1].end)
71
77
  throw new InvalidError(`Sections overlap at ${sorted[i].start}s`);
72
78
  }
73
- // New sections without an id get s<n>, starting from their position, skipping ids already taken.
79
+ // New sections without an id get s<n>, starting from their position, skipping ids already taken
80
+ // and every number that was ever handed out: notes and picks name a section by id, so a removed
81
+ // section's id must not come back for new words. `top` is the highest number seen, whether it is
82
+ // in the script now, was in it before this call, or was recorded when it was given out.
74
83
  const taken = new Set(sorted.flatMap((s) => (s.id === null ? [] : [s.id])));
84
+ let top = script.sectionCounter ?? 0;
85
+ for (const id of [...taken, ...existing])
86
+ top = Math.max(top, Number(/^s(\d+)$/.exec(id)?.[1] ?? 0));
75
87
  const next = sorted.map((s, i) => {
76
88
  if (s.id !== null)
77
89
  return s;
78
- let n = i + 1;
90
+ let n = Math.max(i + 1, top + 1);
79
91
  while (taken.has(`s${n}`))
80
92
  n++;
81
93
  taken.add(`s${n}`);
94
+ top = n;
82
95
  return { ...s, id: `s${n}` };
83
96
  });
84
97
  script.sections = next;
98
+ script.sectionCounter = top;
85
99
  return next;
86
100
  }
87
101
  export function findSection(script, id) {
@@ -21,13 +21,16 @@ function defaults(key, name) {
21
21
  return { schema: 1, rev: 0, dismissed: [], settled: [] };
22
22
  case "log":
23
23
  return { schema: 1, rev: 0, backfilled: false, undated: [], dropped: 0, entries: [] };
24
+ case "brief":
25
+ case "storyboard":
26
+ return { schema: 1, rev: 0, baseline: "", seen: "" };
24
27
  }
25
28
  }
26
29
  /**
27
- * Files `init` doesn't write (found.json, log.json). Each is created by its first write, and reads
30
+ * Files `init` doesn't write (found.json, log.json, brief.json, storyboard.json). Each is created by its first write, and reads
28
31
  * as its default until then, so a project made before the file existed needs nothing done to it.
29
32
  */
30
- const CREATED_ON_WRITE = new Set(["found", "log"]);
33
+ const CREATED_ON_WRITE = new Set(["found", "log", "brief", "storyboard"]);
31
34
  /**
32
35
  * The only writer of a project's .rushes folder. Every write is validated,
33
36
  * serialised per file, written atomically (tmp + rename) and announced with
@@ -133,8 +136,11 @@ export class Store extends EventEmitter {
133
136
  export function serialise(data) {
134
137
  return JSON.stringify(data, null, 2) + "\n";
135
138
  }
139
+ // Counts every atomic write in this process. Two Store objects on one project don't see each other's
140
+ // writes, so pid + millisecond alone can repeat and send both to the same temp file.
141
+ let writes = 0;
136
142
  async function atomicWrite(path, text) {
137
- const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
143
+ const tmp = `${path}.${process.pid}.${Date.now()}.${++writes}.tmp`;
138
144
  await writeFile(tmp, text, "utf8");
139
145
  await rename(tmp, path);
140
146
  }
@@ -0,0 +1,109 @@
1
+ import { parseBrief, setSectionBody } from "./brief.js";
2
+ // §24.12: storyboard.md is the file of record for the shots, as brief.md is for the brief. One section per
3
+ // shot ("## Shot 02 · Drop a folder"). Its facts are the lines above the first blank line (Tag, Length, Still,
4
+ // Status, Direction); what follows is what happens. These are pure functions over the text: everything the
5
+ // page does not touch (the title, other sections, the user's formatting) is left exactly as it was.
6
+ /** The storyboard's file name, in the project folder's root. */
7
+ export const STORYBOARD_FILE = "storyboard.md";
8
+ const HEADING = /^Shot\s+(\d+)\s*[·:–—-]\s*(.+?)\s*$/i;
9
+ const META = /^(Tag|Length|Still|Status|Direction):[ \t]*(.*?)[ \t]*$/i;
10
+ /** What a still may be: pictures a browser shows inline. */
11
+ const IMAGE = /\.(png|jpe?g|webp|gif)$/i;
12
+ /** A still's path as the page may use it: relative, inside the project, a picture. Anything else is no still. */
13
+ export function stillPath(raw) {
14
+ const p = raw.trim().replace(/^\.\//, "");
15
+ if (!p || p.startsWith("/") || p.startsWith("~") || /^[a-z]:/i.test(p) || p.includes("\\") || p.includes("\0"))
16
+ return null;
17
+ if (p.split("/").some((seg) => seg === ".." || seg === "" || seg === "."))
18
+ return null;
19
+ return IMAGE.test(p) ? p : null;
20
+ }
21
+ /** A shot section's body split into its fact lines and what happens. */
22
+ function split(body) {
23
+ const lines = body.split("\n");
24
+ let i = 0;
25
+ while (i < lines.length && META.test(lines[i]))
26
+ i++;
27
+ const meta = lines.slice(0, i);
28
+ if (i < lines.length && lines[i].trim() === "")
29
+ i++;
30
+ return { meta, description: lines.slice(i).join("\n").replace(/\s+$/, "") };
31
+ }
32
+ const metaOf = (meta, key) => {
33
+ for (const l of meta) {
34
+ const m = META.exec(l);
35
+ if (m && m[1].toLowerCase() === key.toLowerCase())
36
+ return m[2];
37
+ }
38
+ return undefined;
39
+ };
40
+ export function parseStoryboard(text) {
41
+ const brief = parseBrief(text);
42
+ const shots = [];
43
+ brief.sections.forEach((s, index) => {
44
+ const h = HEADING.exec(s.heading);
45
+ if (!h)
46
+ return;
47
+ const { meta, description } = split(s.body);
48
+ const length = Number(metaOf(meta, "Length"));
49
+ shots.push({
50
+ index,
51
+ heading: s.heading,
52
+ n: Number(h[1]),
53
+ name: h[2],
54
+ tag: metaOf(meta, "Tag") ?? "",
55
+ length: Number.isFinite(length) && length > 0 ? length : null,
56
+ still: stillPath(metaOf(meta, "Still") ?? ""),
57
+ status: (metaOf(meta, "Status") ?? "").toLowerCase() === "approved" ? "approved" : "draft",
58
+ direction: metaOf(meta, "Direction") ?? "",
59
+ description,
60
+ });
61
+ });
62
+ return { title: brief.title.replace(/^Storyboard:[ \t]*/i, ""), shots };
63
+ }
64
+ /** The section's body rebuilt from its fact lines and its description. */
65
+ function join(meta, description) {
66
+ const d = description.replace(/\r\n/g, "\n").replace(/^\s*\n+/, "").replace(/\s+$/, "");
67
+ return d ? [...meta, "", d].join("\n") : meta.join("\n");
68
+ }
69
+ function withMeta(meta, key, value) {
70
+ const at = meta.findIndex((l) => META.exec(l)?.[1].toLowerCase() === key.toLowerCase());
71
+ if (at >= 0) {
72
+ const name = META.exec(meta[at])[1];
73
+ return meta.map((l, i) => (i === at ? `${name}: ${value}`.trimEnd() : l));
74
+ }
75
+ return [...meta, `${key}: ${value}`.trimEnd()];
76
+ }
77
+ /**
78
+ * `text` with one shot changed. `heading` must be the heading at `index` (a file that was reordered under you
79
+ * is refused, not edited in the wrong place). Only the fields given change; a missing fact line is added.
80
+ */
81
+ export function editShot(text, index, heading, edit) {
82
+ const section = parseBrief(text).sections[index];
83
+ if (!section || section.heading !== heading || !HEADING.test(heading))
84
+ throw new Error(`No shot "${heading}" at position ${index + 1}`);
85
+ const parts = split(section.body);
86
+ let meta = parts.meta;
87
+ if (edit.direction !== undefined)
88
+ meta = withMeta(meta, "Direction", edit.direction.replace(/\s*\r?\n\s*/g, " ").trim());
89
+ if (edit.status !== undefined)
90
+ meta = withMeta(meta, "Status", edit.status);
91
+ const description = edit.description !== undefined ? edit.description : parts.description;
92
+ return setSectionBody(text, index, heading, join(meta, description));
93
+ }
94
+ /**
95
+ * The shots as a cut's shot list: each `start` is the running total of the lengths before it. A shot with
96
+ * no usable Length counts as one second, so two shots never start together.
97
+ */
98
+ export function cutShots(shots) {
99
+ let start = 0;
100
+ let last = -1;
101
+ // A shot list holds at most 200 shots, and no two may start together: lengths too small to tell apart still step by a millisecond.
102
+ return shots.slice(0, 200).map((s) => {
103
+ const at = Math.max(Math.round(start * 1000) / 1000, last + 0.001);
104
+ const out = { name: s.name.slice(0, 80), start: Math.round(at * 1000) / 1000, tag: s.tag.slice(0, 24) };
105
+ last = out.start;
106
+ start += s.length ?? 1;
107
+ return out;
108
+ });
109
+ }
package/dist/mcp/stdio.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { homedir } from "node:os";
3
- import { dirname, resolve } from "node:path";
3
+ import { dirname, join, resolve } from "node:path";
4
4
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
5
  import { createMcpServer } from "./tools.js";
6
6
  import { ensureServer } from "./ensure.js";
@@ -17,7 +17,7 @@ export function openBrowser(url) {
17
17
  * project, so those throw and ask the agent to name one.
18
18
  */
19
19
  export function resolveProjectRoot(defaultRoot, project) {
20
- const root = resolve(defaultRoot, project ?? ".");
20
+ const root = projectPath(defaultRoot, project);
21
21
  if (dirname(root) === root || root === resolve(homedir())) {
22
22
  throw new Error('Tell me which project folder to use: pass "project" (e.g. "/Users/you/Videos/launch-film").');
23
23
  }
@@ -30,7 +30,16 @@ export function resolveProjectRoot(defaultRoot, project) {
30
30
  * folder" there, same as any other folder with no .rushes.
31
31
  */
32
32
  export function resolveDoctorRoot(defaultRoot, project) {
33
- return resolve(defaultRoot, project ?? ".");
33
+ return projectPath(defaultRoot, project);
34
+ }
35
+ /**
36
+ * `project` against the launch folder. A leading "~" or "~/" is the home folder, as a shell would
37
+ * read it: agents write paths that way, and resolve() alone would make a folder called "~" in the
38
+ * working directory.
39
+ */
40
+ function projectPath(defaultRoot, project = ".") {
41
+ const fromHome = project === "~" || /^~[\\/]/.test(project);
42
+ return resolve(defaultRoot, fromHome ? join(homedir(), project.slice(2)) : project);
34
43
  }
35
44
  /** The tool context runStdio uses. */
36
45
  export function stdioContext(defaultRoot, ensure) {
package/dist/mcp/tools.js CHANGED
@@ -146,12 +146,12 @@ export function createMcpServer(ctx) {
146
146
  }, safe(async ({ project, video, version }) => (await ctx.client(project)).put(`/api/videos/${encodeURIComponent(video)}/lock`, { version })));
147
147
  server.registerTool("rushes_status", {
148
148
  title: "Rushes status",
149
- description: "Which tabs are unlocked and how many open items each has.",
149
+ description: "Which tabs are unlocked and how many open items each has. Also `brief`: whether brief.md exists, its status (draft or approved, set when the user presses Approve) and how many sections the user changed; `storyboard`: whether storyboard.md exists, how many shots there are, how many are approved and how many the user changed; and `build`: whether planning has begun (`started`), whether the brief, every script section (when there is a script) and every shot are approved (`ready`), and what it is `waitingOn`.",
150
150
  inputSchema: { project },
151
151
  }, safe(async ({ project }) => (await ctx.client(project)).get("/api/tabs")));
152
152
  server.registerTool("rushes_add_version", {
153
153
  title: "Add a cut",
154
- description: "Register a new cut of a video. The first cut creates the video. Returns the new version id (v1, v2 ...). When the cut is likely to play badly in a browser (4K, over 1.5 GB, or a codec such as ProRes), it also returns proxySuggested: true and proxyReason; Picture offers the user a proxy. If the project has autoProxy on, proxyJob is the proxy already being made. Give every cut a short `label` (" + LABEL_MAX + " characters at most) saying what changed, e.g. \"launch 1.45x slower\", and put the detail in `note`: the version list shows the label. Pass `formats` to register the other shapes of the same cut in one call; the reply then carries `formatWarnings` (a list, one entry for each shape more than 0.1 s off the cut's length; `warning` here means Picture is locked).",
154
+ description: "Register a new cut of a video. The first cut creates the video. Returns the new version id (v1, v2 ...). When the cut is likely to play badly in a browser (4K, over 1.5 GB, or a codec such as ProRes), it also returns proxySuggested: true and proxyReason; Picture offers the user a proxy. If the project has autoProxy on, proxyJob is the proxy already being made. Give every cut a short `label` (" + LABEL_MAX + " characters at most) saying what changed, e.g. \"launch 1.45x slower\", and put the detail in `note`: the version list shows the label. Pass `formats` to register the other shapes of the same cut in one call; the reply then carries `formatWarnings` (a list, one entry for each shape more than 0.1 s off the cut's length; `warning` here means Picture is locked). When the plan (brief, script, storyboard) has been started but is not all approved, it carries `planWarning` saying what is outstanding: a nudge, never a refusal. A film's first cut also starts with the storyboard's shots.",
155
155
  inputSchema: {
156
156
  project,
157
157
  video: z.string().describe("Video id or name, e.g. \"Hero 60s\"."),