rushes 0.10.1 → 0.12.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 (41) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/AGENTS.md +14 -4
  3. package/README.md +14 -8
  4. package/dist/cli/demo.js +3 -2
  5. package/dist/cli/main.js +33 -1
  6. package/dist/core/agentRules.js +7 -0
  7. package/dist/core/balance.js +238 -0
  8. package/dist/core/batches.js +29 -11
  9. package/dist/core/exportNotes.js +4 -2
  10. package/dist/core/films.js +114 -0
  11. package/dist/core/log.js +35 -3
  12. package/dist/core/logEvents.js +7 -7
  13. package/dist/core/notes.js +19 -1
  14. package/dist/core/schema.js +69 -14
  15. package/dist/core/script.js +67 -0
  16. package/dist/core/tabs.js +15 -7
  17. package/dist/core/takes.js +1 -1
  18. package/dist/mcp/tools.js +90 -23
  19. package/dist/server/agent/adapters.js +39 -8
  20. package/dist/server/agent/rules.js +106 -9
  21. package/dist/server/agent/runner.js +135 -35
  22. package/dist/server/agent/setupOnce.js +44 -0
  23. package/dist/server/app.js +348 -65
  24. package/dist/server/assets.js +40 -14
  25. package/dist/server/balance.js +103 -0
  26. package/dist/server/brief.js +9 -7
  27. package/dist/server/files.js +3 -2
  28. package/dist/server/films.js +43 -0
  29. package/dist/server/found.js +2 -1
  30. package/dist/server/logbook.js +28 -2
  31. package/dist/server/plans.js +68 -0
  32. package/dist/server/record.js +31 -13
  33. package/dist/server/start.js +15 -7
  34. package/dist/server/storyboard.js +8 -6
  35. package/dist/version.js +1 -1
  36. package/package.json +1 -1
  37. package/skills/rushes/SKILL.md +4 -4
  38. package/web-dist/assets/{index-BIJlv6zN.css → index-BCYA0Awp.css} +1 -1
  39. package/web-dist/assets/index-LPvsS2vO.js +70 -0
  40. package/web-dist/index.html +2 -2
  41. package/web-dist/assets/index-D430jOsg.js +0 -70
@@ -3,8 +3,10 @@ import { streamSSE } from "hono/streaming";
3
3
  import { z } from "zod";
4
4
  import { RushesError, InvalidError, NotFoundError } from "../core/errors.js";
5
5
  import { addFile, addFormat, addVariant, addVersion, ensureProjectIdOnce, lockPicture, noteInPlay, resolveCut, resolveVideo, setShots, setVariantFilms, shelveFilm, shotAt } from "../core/project.js";
6
- import { addTake, editSection, setSections } from "../core/script.js";
7
- import { addNote, addUserReply, applyReply, applyUserEdit, checkNoteFormat, filterNotes } from "../core/notes.js";
6
+ import { addTake, allSections, editSection, filmScript, filmScriptDraft, setSections } from "../core/script.js";
7
+ import { chooseFilm, filmPlace, firstFilm } from "../core/films.js";
8
+ import { moveToFirstFilmOnce } from "./films.js";
9
+ import { addNote, addUserReply, applyReply, applyUserEdit, byFilm, checkNoteFormat, filterNotes } from "../core/notes.js";
8
10
  import { FORMAT_ID_RE, MAX_FORMATS, isPictureSize, labelOfId, versionFormats } from "../core/formats.js";
9
11
  import { createBatch, latestBatch } from "../core/batches.js";
10
12
  import { markSent, noteState, NOTE_STATES, withState } from "../core/noteState.js";
@@ -30,15 +32,18 @@ import { filmTakes, putAway } from "../core/takes.js";
30
32
  import { AGENTS, AgentPermissionsSchema, AlwaysRuleSchema, LaneStageSchema, SectionStatusSchema, StageSchema, BoxSchema, PinSchema, FileKindSchema, MarkSchema, ProjectIdSchema, ShotSchema, LEVEL_MIN, LEVEL_MAX, LEVEL_STEP, lanesForVideo, picksForVideo, variantFilms } from "../core/schema.js";
31
33
  import { LABEL_MAX, oneLineOf } from "../core/labels.js";
32
34
  import { byOf, logBookFor } from "./logbook.js";
33
- import { BriefService } from "./brief.js";
34
- import { StoryboardService } from "./storyboard.js";
35
+ import { briefRecords, storyboardRecords } from "./plans.js";
36
+ import { slugify, uniqueId } from "../core/ids.js";
35
37
  import { buildState, planWarning } from "../core/plan.js";
36
38
  import { broughtInEvent, cutEvent, fileEvent, filmEvent, formatEvent, lineEvent, lockEvent, notesSentEvent, picksEvent, repliesEvent, scriptEvent, takeEvent, variantEvent, variantFilmsEvent, visualEvent, } from "../core/logEvents.js";
37
39
  import { LOG_AREAS, LOG_MAX, changeLogFileName, logText, recentChanges } from "../core/logText.js";
38
40
  import { defaultRunner, measureMix } from "./loudness.js";
41
+ import { balanceFilm } from "./balance.js";
42
+ import { balanceSummary } from "../core/balance.js";
39
43
  import { clearDetectCache, detectAgents } from "./agent/detect.js";
40
44
  import { openInTerminal } from "./agent/terminal.js";
41
45
  import { agentRulesFor } from "./agent/rules.js";
46
+ import { adoptAgentDefaultsOnce, rememberDefault } from "./agent/setupOnce.js";
42
47
  import { notifyWhenWaiting, osNotifier } from "./agent/notify.js";
43
48
  import { VERSION } from "../version.js";
44
49
  export { VERSION };
@@ -151,23 +156,29 @@ const VariantBody = z.object({
151
156
  cues: z.array(z.object({ name: z.string().min(1), t, file: z.string().min(1).optional() })).optional(),
152
157
  });
153
158
  const VariantFilmsBody = z.object({ videos: z.array(z.string().min(1).max(200)).max(100) });
159
+ // §31.6: the script, brief and storyboard are a film's: a write names its film (`video`, an id or a name). With one
160
+ // film it may be left out; with several, leaving it out is refused with the films listed.
161
+ const filmRef = z.string().min(1).max(200).optional();
154
162
  const ScriptBody = z.object({
163
+ video: filmRef,
155
164
  wordsPerSecond: z.number().positive().optional(),
156
165
  replace: z.boolean().optional(),
157
166
  sections: z.array(z.object({ id: z.string().min(1).optional(), start: t, end: t, current: z.string() })),
158
167
  });
159
168
  const SectionEditBody = z.object({
169
+ video: filmRef,
160
170
  proposed: z.string().nullable().optional(),
161
171
  direction: z.string().optional(),
162
172
  status: SectionStatusSchema.optional(),
163
173
  });
164
- const TakeBody = z.object({ file: z.string().min(1) });
174
+ const TakeBody = z.object({ file: z.string().min(1), video: filmRef });
165
175
  // §24 step 2: a save of one brief.md section, and the approval. `hash` proves the page saw the current file.
166
- const BriefSectionBody = z.object({ heading: z.string().min(1).max(200), text: z.string().max(100_000), hash: z.string().min(1).max(64) });
167
- const BriefStatusBody = z.object({ status: z.enum(["draft", "approved"]), hash: z.string().min(1).max(64) });
176
+ const BriefSectionBody = z.object({ video: filmRef, heading: z.string().min(1).max(200), text: z.string().max(100_000), hash: z.string().min(1).max(64) });
177
+ const BriefStatusBody = z.object({ video: filmRef, status: z.enum(["draft", "approved"]), hash: z.string().min(1).max(64) });
168
178
  // §24.12: a change to one storyboard shot: its words, its direction, its status, in any combination.
169
179
  const StoryboardShotBody = z
170
180
  .object({
181
+ video: filmRef,
171
182
  heading: z.string().min(1).max(200),
172
183
  description: z.string().max(100_000).optional(),
173
184
  direction: z.string().max(1000).optional(),
@@ -185,9 +196,12 @@ const PicksBody = z.object({ video: z.string().min(1).max(200).optional(), lanes
185
196
  // §28: the Send to AI switch, the agent and what it may do unasked.
186
197
  // `batch` (I3): the filed batch the copy dialog was showing when its Set up opened the sheet. Once Send to AI is on, it is
187
198
  // handed to the agent, as Send would have.
188
- const AgentSetupBody = z.object({ on: z.boolean(), agent: z.enum(AGENTS).optional(), permissions: AgentPermissionsSchema.optional(), batch: z.string().min(1).optional() });
189
- // No stage: every tab's open notes (Send). A stage: that tab's only.
190
- const BatchBody = z.object({ stage: StageSchema.optional() });
199
+ // §32: `prompt`: the first-Send sheet's Copy a prompt (off, and no agent for new projects either). The switch turned off
200
+ // sends no `prompt`, so it leaves the Mac-wide default as it is.
201
+ const AgentSetupBody = z.object({ on: z.boolean(), agent: z.enum(AGENTS).optional(), permissions: AgentPermissionsSchema.optional(), batch: z.string().min(1).optional(), prompt: z.boolean().optional() });
202
+ // No stage: every tab's open notes (Send). A stage: that tab's only. §31.2.2: `video`, the film Send is pressed on:
203
+ // only its notes and its script go. Without one, every film in play (an older client).
204
+ const BatchBody = z.object({ stage: StageSchema.optional(), video: filmRef });
191
205
  const NoteQuery = z.object({
192
206
  stage: StageSchema.optional(),
193
207
  status: z.enum(["todo", "done"]).optional(),
@@ -199,7 +213,11 @@ const NoteQuery = z.object({
199
213
  onlyThisFormat: z.enum(["true", "false"]).optional(),
200
214
  // §26: the notes of a shelved film are left out unless asked for (or a batch is: it lists what it sent).
201
215
  includeShelved: z.enum(["true", "false"]).optional(),
216
+ // §31.6: one film's notes (and the visuals', which are on every film).
217
+ video: z.string().min(1).max(200).optional(),
202
218
  });
219
+ // §31.6: the film a read is about, for the routes that take ?video= alone.
220
+ const VideoQuery = z.object({ video: z.string().min(1).max(200).optional() });
203
221
  // ShotSchema's own limits (name trimmed 1-80 chars, tag at most 24) apply at the boundary; `n` is server-assigned.
204
222
  const ShotsBody = z.object({
205
223
  version: z.string().optional(),
@@ -208,6 +226,7 @@ const ShotsBody = z.object({
208
226
  const LockBody = z.object({ version: z.string().nullable() });
209
227
  const ShelveBody = z.object({ shelved: z.boolean() });
210
228
  const MixLoudnessBody = z.object({ lanes: z.array(LaneStageSchema).min(1), video: z.string().min(1).max(200).optional() });
229
+ const BalanceBody = z.object({ video: z.string().min(1).max(200).optional() });
211
230
  const SettingsBody = z.object({ autoProxy: z.boolean() }).strict();
212
231
  // A time in seconds, 0 to 24 h: an empty value, NaN, Infinity or anything huge is a 400.
213
232
  const FrameQuery = z.object({
@@ -267,6 +286,8 @@ const LogQuery = z.object({
267
286
  .string()
268
287
  .refine((s) => ISO_DATE.test(s) && Number.isFinite(Date.parse(s)), "since must be a date and time, e.g. 2026-10-07T09:00:00Z")
269
288
  .optional(),
289
+ // §31.6: the lines Activity shows on this film: its own and the project's.
290
+ video: z.string().min(1).max(200).optional(),
270
291
  });
271
292
  const LogLineBody = z.object({
272
293
  text: z.string().max(2000),
@@ -322,25 +343,34 @@ export function createApp(store, opts = {}) {
322
343
  const jobs = opts.proxyJobs ?? new ProxyJobs(store);
323
344
  const peaks = opts.peakJobs ?? new PeakJobs(store, { run: jobs.run, available: () => jobs.available() });
324
345
  const found = opts.found ?? new FoundScanner({ store, probe: ffprobeDuration, announce: foundAnnouncer(store) });
325
- const brief = opts.brief ?? new BriefService(store);
326
- const storyboard = opts.storyboard ?? new StoryboardService(store);
346
+ const briefs = opts.briefs ?? briefRecords(store, opts.brief);
347
+ const storyboards = opts.storyboards ?? storyboardRecords(store, opts.storyboard);
327
348
  // §28: made before any route is reachable, so every agent route and Send has it.
328
349
  const agent = opts.agent ?? noAgent();
329
350
  const sendWaitMs = opts.sendWaitMs ?? SEND_WAIT_MS;
330
351
  const detect = opts.detect ?? (() => detectAgents());
331
352
  const terminal = opts.terminal ?? openInTerminal;
332
- /** §24.12: whether the plan (brief, script, storyboard) is approved, from the files as they are now. */
333
- const planBuild = async () => {
334
- const [b, script, sb] = await Promise.all([brief.view(), store.read("script"), storyboard.view()]);
335
- return buildState({ brief: b, script: script.sections, storyboard: sb });
353
+ /** §24.12, §31.5: whether a film's plan (its brief, script and storyboard) is approved, from the files as they are now. */
354
+ const planBuild = async (video) => {
355
+ const project = await store.read("project");
356
+ const place = filmPlace(project, video);
357
+ const [b, script, sb] = await Promise.all([briefs.at(place).view(), store.read("script"), storyboards.at(place).view()]);
358
+ return buildState({ brief: b, script: filmScript(script, project, place.video).sections, storyboard: sb });
336
359
  };
360
+ /**
361
+ * §31.6: the film a request for a film's material is about: the one it names, or the only one. With several films
362
+ * and none named, a 400 that lists them. Null while the project has no film.
363
+ */
364
+ const filmOf = async (given, what) => chooseFilm(await store.read("project"), given, what)?.id ?? null;
365
+ /** The whole script's sections, for what must know every take whichever film it is in (the log, refs). */
366
+ const everySection = (script) => ({ sections: allSections(script) });
337
367
  // §22: the Change Log, shared with the found scanner (logBookFor keeps one per store).
338
368
  const log = logBookFor(store);
339
369
  const by = (c) => byOf(c.req.header("x-rushes-project"));
340
370
  /** R17: writes exports/change-log-YYYY-MM-DD.md (a same-day export replaces it) and returns its path. Written as Export notes writes. */
341
371
  async function exportChangeLog(now) {
342
372
  const [project, script] = await Promise.all([store.read("project"), store.read("script")]);
343
- const md = await log.markdown({ project, script }, now);
373
+ const md = await log.markdown({ project, script: everySection(script) }, now);
344
374
  const name = changeLogFileName(now);
345
375
  const dir = join(store.root, "exports");
346
376
  await mkdir(dir, { recursive: true });
@@ -497,8 +527,15 @@ export function createApp(store, opts = {}) {
497
527
  if (!known && registeredMedia(project, script, await store.read("visuals")).has(path))
498
528
  known = true;
499
529
  // §24.12: a picture storyboard.md names (a safe, project-relative image path) is served too, registered or not.
500
- if (!known && (await storyboard.stills()).has(path))
501
- known = true;
530
+ // §31.3: any film's storyboard.
531
+ if (!known) {
532
+ for (const sb of await storyboards.all()) {
533
+ if ((await sb.stills()).has(path)) {
534
+ known = true;
535
+ break;
536
+ }
537
+ }
538
+ }
502
539
  // The file on disk to send. For a found file it's exactly the path that was checked.
503
540
  let file = fromManifestPath(store.root, path);
504
541
  let viaFound = false;
@@ -586,11 +623,18 @@ export function createApp(store, opts = {}) {
586
623
  });
587
624
  // ---- assets: the Assets tab and rushes_list_assets ----
588
625
  app.get("/api/assets", async (c) => {
589
- const [project, script] = await Promise.all([store.read("project"), store.read("script")]);
590
- let assets = await listAssets(store, project, script);
626
+ const [project, script, visuals] = await Promise.all([store.read("project"), store.read("script"), store.read("visuals")]);
627
+ let assets = await listAssets(store, project, script, visuals);
591
628
  const kind = c.req.query("kind");
592
629
  if (kind)
593
630
  assets = assets.filter((a) => a.kind === kind);
631
+ // §31.6: one film's files: its own, the shared visuals, and (naming no film) the first film's.
632
+ const video = c.req.query("video");
633
+ if (video) {
634
+ const film = chooseFilm(project, video).id;
635
+ const first = firstFilm(project);
636
+ assets = assets.filter((a) => a.shared || (a.videos ? a.videos.includes(film) : a.video ? a.video === film : film === first));
637
+ }
594
638
  return c.json({ assets });
595
639
  });
596
640
  app.post("/api/reveal", async (c) => {
@@ -656,7 +700,8 @@ export function createApp(store, opts = {}) {
656
700
  app.post("/api/files", async (c) => {
657
701
  const b = await body(c, AddFileBody);
658
702
  const file = toManifestPath(store.root, b.file);
659
- const { result } = await store.update("project", (p) => addFile(p, { ...b, file }));
703
+ // §31.2.4: with several films, a file that names none is the first film's.
704
+ const { result } = await store.update("project", (p) => addFile(p, { ...b, file, video: b.video ?? (p.videos.length > 1 ? p.videos[0].id : undefined) }));
660
705
  await log.add(() => fileEvent(result), by(c));
661
706
  return c.json(result, 201);
662
707
  });
@@ -665,7 +710,8 @@ export function createApp(store, opts = {}) {
665
710
  store.read("project"), store.read("notes"), store.read("script"), store.read("picks"), store.read("visuals"),
666
711
  ]);
667
712
  const now = new Date();
668
- const md = notesMarkdown(project, notesFile.notes, now, script, picks, visuals);
713
+ // §31.3: a note on the script names a line of its own film's script.
714
+ const md = notesMarkdown(project, notesFile.notes, now, (video) => filmScript(script, project, video), picks, visuals);
669
715
  const name = exportFileName(project.name, now);
670
716
  const dir = join(store.root, "exports");
671
717
  await mkdir(dir, { recursive: true });
@@ -707,17 +753,44 @@ export function createApp(store, opts = {}) {
707
753
  app.get("/api/state", async (c) => {
708
754
  // §20.6: found is what the last scan left in memory; it never waits on a scan or a probe.
709
755
  // §22.8: the log's head is read-only, so a state request never writes (R6).
710
- const [project, script, notes, picks, batches, ffmpeg, foundSummary, logHead, briefView, storyboardView, visuals] = await Promise.all([
711
- store.read("project"), store.read("script"), store.read("notes"), store.read("picks"), store.read("batches"), jobs.available(), found.summary(), log.head(), brief.view(), storyboard.view(), store.read("visuals"),
756
+ const [project, scriptFile, notes, picks, batches, ffmpeg, foundSummary, logHead, visuals] = await Promise.all([
757
+ store.read("project"), store.read("script"), store.read("notes"), store.read("picks"), store.read("batches"), jobs.available(), found.summary(), log.head(), store.read("visuals"),
712
758
  ]);
713
- const tabs = tabStates(project, script, notes, visuals);
759
+ // §31.5: everything Plan and Review show for each film: its script, brief, storyboard and plan state, its tabs
760
+ // (counts, to-do dots, unlocking) and its Activity head (the "new" dot). The desk picks the film on screen.
761
+ const heads = await log.filmHeads({ videos: project.videos, lanes: project.lanes, notes: notes.notes });
762
+ const planOf = async (video) => {
763
+ const place = filmPlace(project, video);
764
+ const [b, sb] = await Promise.all([briefs.at(place).view(), storyboards.at(place).view()]);
765
+ const s = filmScript(scriptFile, project, place.video);
766
+ return {
767
+ script: s,
768
+ brief: b,
769
+ storyboard: sb,
770
+ build: buildState({ brief: b, script: s.sections, storyboard: sb }),
771
+ tabs: tabStates(project, s, notes, visuals, place.video),
772
+ log: (place.video && heads[place.video]) ?? logHead,
773
+ // Where the agent finds this film's plan files.
774
+ paths: { brief: place.brief, storyboard: place.storyboard },
775
+ };
776
+ };
777
+ const films = {};
778
+ for (const v of project.videos)
779
+ films[v.id] = await planOf(v.id);
780
+ // The first film's (or, with no film yet, the project's) plan, at the top level as before, with the whole
781
+ // project's tabs and Activity head.
782
+ const first = project.videos.length > 0 ? films[project.videos[0].id] : await planOf(null);
783
+ const script = first.script;
784
+ const briefView = first.brief;
785
+ const storyboardView = first.storyboard;
786
+ const tabs = tabStates(project, filmScript(scriptFile, project, null), notes, visuals);
714
787
  // §19.5: why each cut may play badly (or null). Never waits on a probe: an unprobed cut is
715
788
  // null until its background probe lands, which then announces a change (ruling B).
716
789
  const videos = await Promise.all(project.videos.map(async (v) => ({
717
790
  ...v,
718
791
  versions: await Promise.all(v.versions.map(async (ver) => ({ ...ver, proxyNeed: await jobs.needNow(fromManifestPath(store.root, ver.file)) }))),
719
792
  })));
720
- return c.json({ version: VERSION, project: { ...project, videos }, script, notes, picks: withUse(project, picks), batches, tabs, visuals, proxies: { ffmpeg, jobs: jobs.list() }, found: foundSummary, log: logHead, brief: briefView, storyboard: storyboardView, build: buildState({ brief: briefView, script: script.sections, storyboard: storyboardView }) });
793
+ return c.json({ version: VERSION, project: { ...project, videos }, script, notes, picks: withUse(project, picks), batches, tabs, visuals, proxies: { ffmpeg, jobs: jobs.list() }, found: foundSummary, log: logHead, brief: briefView, storyboard: storyboardView, build: first.build, films });
721
794
  });
722
795
  // ---- found: the project's other files (§20) ----
723
796
  app.get("/api/found", async (c) => {
@@ -806,36 +879,69 @@ export function createApp(store, opts = {}) {
806
879
  await found.restore(b.paths);
807
880
  return c.json({ ok: true });
808
881
  });
882
+ // §31.6: ?video= is one film's: its tabs, its brief, storyboard and plan. Without one, the first film's plan (with
883
+ // one film, the same as ever) and the whole project's tabs.
809
884
  app.get("/api/tabs", async (c) => {
885
+ const q = VideoQuery.safeParse(c.req.query());
886
+ if (!q.success)
887
+ throw new InvalidError("Query is invalid", q.error.issues);
810
888
  const [project, script, notes, visuals] = await Promise.all([store.read("project"), store.read("script"), store.read("notes"), store.read("visuals")]);
811
- const [b, sb] = await Promise.all([brief.view(), storyboard.view()]);
889
+ const film = q.data.video ? chooseFilm(project, q.data.video).id : null;
890
+ const place = filmPlace(project, film);
891
+ const [b, sb] = await Promise.all([briefs.at(place).view(), storyboards.at(place).view()]);
892
+ const own = filmScript(script, project, place.video);
812
893
  return c.json({
813
- tabs: tabStates(project, script, notes, visuals),
894
+ tabs: tabStates(project, film ? own : filmScript(script, project, null), notes, visuals, film),
814
895
  // §26: every film and whether it is shelved, so an agent leaves the shelved ones alone.
815
896
  films: project.videos.map((v) => ({ id: v.id, name: v.name, shelved: v.shelved ?? null })),
897
+ // §31.3: where each film's own brief and storyboard are.
898
+ plans: Object.fromEntries(project.videos.map((v) => {
899
+ const p = filmPlace(project, v.id);
900
+ return [v.id, { brief: p.brief, storyboard: p.storyboard }];
901
+ })),
902
+ ...(film ? { film } : {}),
816
903
  brief: { exists: b.exists, status: b.status, changed: b.changed },
817
904
  storyboard: { exists: sb.exists, shots: sb.total, approved: sb.approved, changed: sb.changed },
818
- build: buildState({ brief: b, script: script.sections, storyboard: sb }),
905
+ build: buildState({ brief: b, script: own.sections, storyboard: sb }),
819
906
  });
820
907
  });
821
- // ---- brief: brief.md is the file of record (§24 step 2) ----
908
+ // ---- brief: brief.md is the file of record (§24 step 2); §31.3: each film has its own ----
909
+ const videoQuery = (c) => {
910
+ const q = VideoQuery.safeParse(c.req.query());
911
+ if (!q.success)
912
+ throw new InvalidError("Query is invalid", q.error.issues);
913
+ return q.data.video;
914
+ };
915
+ app.get("/api/brief", async (c) => {
916
+ const film = await filmOf(videoQuery(c), "the brief");
917
+ const place = filmPlace(await store.read("project"), film);
918
+ return c.json({ brief: await briefs.at(place).view(), film, path: place.brief });
919
+ });
822
920
  app.put("/api/brief/sections/:index", async (c) => {
823
921
  const index = Number(c.req.param("index"));
824
922
  if (!Number.isInteger(index) || index < 0)
825
923
  throw new InvalidError("Section index must be a whole number from 0");
826
924
  const b = await body(c, BriefSectionBody);
925
+ const brief = await briefs.of(await filmOf(b.video, "the brief"));
827
926
  return c.json({ brief: await brief.setSection(index, b.heading, b.text, b.hash) });
828
927
  });
829
- // ---- storyboard: storyboard.md is the file of record (§24.12) ----
928
+ // ---- storyboard: storyboard.md is the file of record (§24.12); §31.3: each film has its own ----
929
+ app.get("/api/storyboard", async (c) => {
930
+ const film = await filmOf(videoQuery(c), "the storyboard");
931
+ const place = filmPlace(await store.read("project"), film);
932
+ return c.json({ storyboard: await storyboards.at(place).view(), film, path: place.storyboard });
933
+ });
830
934
  app.put("/api/storyboard/shots/:index", async (c) => {
831
935
  const index = Number(c.req.param("index"));
832
936
  if (!Number.isInteger(index) || index < 0)
833
937
  throw new InvalidError("Shot index must be a whole number from 0");
834
938
  const b = await body(c, StoryboardShotBody);
939
+ const storyboard = await storyboards.of(await filmOf(b.video, "the storyboard"));
835
940
  return c.json({ storyboard: await storyboard.setShot(index, b.heading, { description: b.description, direction: b.direction, status: b.status }, b.hash) });
836
941
  });
837
942
  app.put("/api/brief/status", async (c) => {
838
943
  const b = await body(c, BriefStatusBody);
944
+ const brief = await briefs.of(await filmOf(b.video, "the brief"));
839
945
  return c.json({ brief: await brief.setStatus(b.status, b.hash) });
840
946
  });
841
947
  // ---- notes ----
@@ -844,7 +950,8 @@ export function createApp(store, opts = {}) {
844
950
  if (!q.success)
845
951
  throw new InvalidError("Query is invalid", q.error.issues);
846
952
  const [{ notes }, visuals, project] = await Promise.all([store.read("notes"), store.read("visuals"), store.read("project")]);
847
- const listed = filterNotes(notes, { ...q.data, onlyThisFormat: q.data.onlyThisFormat === "true" }).filter((n) => q.data.includeShelved === "true" || q.data.batch !== undefined || noteInPlay(n, project));
953
+ const video = q.data.video ? chooseFilm(project, q.data.video).id : undefined;
954
+ const listed = filterNotes(notes, { ...q.data, video, videos: project.videos, onlyThisFormat: q.data.onlyThisFormat === "true" }).filter((n) => q.data.includeShelved === "true" || q.data.batch !== undefined || noteInPlay(n, project));
848
955
  return c.json({ notes: withVisualViews(listed, visuals) });
849
956
  });
850
957
  app.post("/api/notes", async (c) => {
@@ -864,7 +971,15 @@ export function createApp(store, opts = {}) {
864
971
  shot = shotAt(version.shots, b.t);
865
972
  }
866
973
  }
867
- const { result } = await store.update("notes", (f) => addNote(f, { ...b, shot, by: "user" }));
974
+ // §31.2.4: nothing is made on no film. A note that names none, in a project with several films, is the first film's
975
+ // (a visual's is on every film and names none). With one film, or none yet, it is left as it is.
976
+ let video = b.video ?? null;
977
+ if (!video && b.stage !== "visuals") {
978
+ const project = await store.read("project");
979
+ if (project.videos.length > 1)
980
+ video = project.videos[0].id;
981
+ }
982
+ const { result } = await store.update("notes", (f) => addNote(f, { ...b, video, shot, by: "user" }));
868
983
  return c.json({ note: withState(result) }, 201);
869
984
  });
870
985
  app.patch("/api/notes/:id", async (c) => {
@@ -886,7 +1001,9 @@ export function createApp(store, opts = {}) {
886
1001
  app.post("/api/replies", async (c) => {
887
1002
  const b = await body(c, RepliesBody);
888
1003
  const { result } = await store.update("notes", (f) => b.replies.map((r) => applyReply(f, r)));
889
- await log.add(() => repliesEvent(result), by(c));
1004
+ // §30: one line per film, so each film's Activity counts only its own notes.
1005
+ for (const [film, notes] of byFilm(result, (n) => n.video))
1006
+ await log.add(() => repliesEvent(notes, film), by(c));
890
1007
  return c.json({ notes: result.map(withState) });
891
1008
  });
892
1009
  // ---- media ----
@@ -935,8 +1052,14 @@ export function createApp(store, opts = {}) {
935
1052
  // before formats (a formats call was refused above).
936
1053
  const size = read && isPictureSize(read.width, read.height) ? read : null;
937
1054
  const formatWarnings = [];
938
- // §24.12: the storyboard's shots, read before the write so the write itself waits for nothing.
939
- const planned = await storyboard.cutShots();
1055
+ // §24.12: the storyboard's shots, read before the write so the write itself waits for nothing. §31.3: the film's
1056
+ // own storyboard, and only for its first cut: work out which film the cut is for, as addVersion will.
1057
+ const before = await store.read("project");
1058
+ const known = before.videos.find((v) => v.id === b.video || v.id === slugify(b.video));
1059
+ const plannedFor = known?.id ?? uniqueId(slugify(b.video), before.videos.map((v) => v.id));
1060
+ const planned = known && known.versions.length > 0
1061
+ ? []
1062
+ : await storyboards.at(filmPlace({ videos: known ? before.videos : [...before.videos, { id: plannedFor }] }, plannedFor)).cutShots();
940
1063
  let lockedVersion = null;
941
1064
  let autoProxy = false;
942
1065
  let films = 1;
@@ -964,7 +1087,7 @@ export function createApp(store, opts = {}) {
964
1087
  formatWarnings.push(added.warning);
965
1088
  }
966
1089
  // A film's first cut starts with the storyboard's shots, once (never recomputed). Those at or past the cut's end are left out.
967
- if (planned.length && out.video.versions.length === 1 && out.version.shots.length === 0) {
1090
+ if (planned.length && out.video.id === plannedFor && out.video.versions.length === 1 && out.version.shots.length === 0) {
968
1091
  const reachable = planned.filter((s) => out.version.duration === null || s.start < out.version.duration);
969
1092
  if (reachable.length)
970
1093
  setShots(p, out.video.id, out.version.id, reachable);
@@ -996,7 +1119,10 @@ export function createApp(store, opts = {}) {
996
1119
  proxy.proxyJob = jobs.start(result.video.id, result.version.id);
997
1120
  }
998
1121
  // §24.12: a soft nudge, never a refusal: the plan (brief, script, storyboard) is not all approved yet.
999
- const planNote = planWarning(await planBuild());
1122
+ const planNote = planWarning(await planBuild(result.video.id));
1123
+ // §31.4: a project that has just gained its second film moves what was on no film to the first one.
1124
+ if (films > 1)
1125
+ await moveToFirstFilmOnce(store, log).catch((e) => console.error(`Rushes: couldn't move what was on no film: ${e.message}`));
1000
1126
  const warnings = { ...(formatWarnings.length ? { formatWarnings } : {}), ...(planNote ? { planWarning: planNote } : {}) };
1001
1127
  const reply = { video: result.video, version: result.version, ...(restored ? { restored: true } : {}) };
1002
1128
  if (lockedVersion)
@@ -1185,10 +1311,15 @@ export function createApp(store, opts = {}) {
1185
1311
  const cues = b.cues?.map((q) => (q.file === undefined ? q : { ...q, file: toManifestPath(store.root, q.file) }));
1186
1312
  const { result } = await store.update("project", (p) => {
1187
1313
  const added = addVariant(p, { ...b, cues, file: toManifestPath(store.root, b.file) });
1188
- // With more than one film, a variant on no film is listed on none of their tabs: say so, so the agent names one.
1189
- const warning = variantFilms(added.variant).length === 0 && p.videos.length > 1
1190
- ? `No film was named, and none could be told from the names, so this ${added.lane.stage === "voice" ? "read" : added.lane.stage === "music" ? "bed" : "pass"} is on no film: it waits, folded, under "Not on this film" on each film's tab. Pass \`video\` (a film's id or name, or a list of them) to put it on films.`
1191
- : undefined;
1314
+ // §31.2.4: nothing is made on no film. With more than one film, one that names none and can't be told from its
1315
+ // names goes on the first film: say so, so the agent names one next time (or moves it with rushes_set_films).
1316
+ let warning;
1317
+ if (variantFilms(added.variant).length === 0 && p.videos.length > 1) {
1318
+ const first = p.videos[0];
1319
+ added.variant.videos = [first.id];
1320
+ const what = added.lane.stage === "voice" ? "read" : added.lane.stage === "music" ? "bed" : "pass";
1321
+ warning = `No film was named, and none could be told from the names, so this ${what} is on ${first.name}, the project's first film. Pass \`video\` (a film's id or name, or a list of them) to put it on the films it was made for, or move it with rushes_set_films.`;
1322
+ }
1192
1323
  return { ...added, ...(warning ? { warning } : {}) };
1193
1324
  });
1194
1325
  await log.add(() => variantEvent(result.lane, result.variant), by(c));
@@ -1230,29 +1361,45 @@ export function createApp(store, opts = {}) {
1230
1361
  return c.json({ variant: result });
1231
1362
  });
1232
1363
  // ---- script ----
1233
- app.get("/api/script", async (c) => c.json({ script: await store.read("script") }));
1364
+ // §31.3: each film has its own script. ?video= (or `video` in a write's body) names it: with one film it may be
1365
+ // left out; with several, leaving it out is refused with the films listed (§31.6).
1366
+ app.get("/api/script", async (c) => {
1367
+ const [project, file] = await Promise.all([store.read("project"), store.read("script")]);
1368
+ const film = chooseFilm(project, videoQuery(c), "the script")?.id ?? null;
1369
+ const own = filmScript(file, project, film);
1370
+ // The shape it always had (schema, rev, wordsPerSecond, sections), now one film's, with the film named.
1371
+ return c.json({ script: { schema: file.schema === 1 && film === firstFilm(project) ? 1 : 2, rev: file.rev, ...own, ...(film ? { video: film } : {}) } });
1372
+ });
1234
1373
  app.put("/api/script", async (c) => {
1235
1374
  const b = await body(c, ScriptBody);
1236
- const { result } = await store.update("script", (s) => {
1375
+ const project = await store.read("project");
1376
+ const film = chooseFilm(project, b.video, "the script")?.id ?? null;
1377
+ const { result } = await store.update("script", (f) => {
1378
+ const s = filmScriptDraft(f, project, film);
1237
1379
  if (b.wordsPerSecond)
1238
1380
  s.wordsPerSecond = b.wordsPerSecond;
1239
1381
  return setSections(s, b.sections, { replace: b.replace });
1240
1382
  });
1241
- await log.add(() => scriptEvent(result.length), by(c));
1242
- return c.json({ sections: result });
1383
+ // The film is named on the line only with several films, so a one-film project's log reads as it always did.
1384
+ await log.add(() => scriptEvent(result.length, project.videos.length > 1 ? film : null), by(c));
1385
+ return c.json({ sections: result, ...(film ? { video: film } : {}) });
1243
1386
  });
1244
1387
  app.patch("/api/script/:id", async (c) => {
1245
- const b = await body(c, SectionEditBody);
1246
- const { result } = await store.update("script", (s) => editSection(s, c.req.param("id"), b));
1388
+ const { video, ...b } = await body(c, SectionEditBody);
1389
+ const project = await store.read("project");
1390
+ const film = chooseFilm(project, video, "the script")?.id ?? null;
1391
+ const { result } = await store.update("script", (f) => editSection(filmScriptDraft(f, project, film), c.req.param("id"), b));
1247
1392
  return c.json({ section: result });
1248
1393
  });
1249
1394
  app.post("/api/script/:id/takes", async (c) => {
1250
1395
  const b = await body(c, TakeBody);
1396
+ const project = await store.read("project");
1397
+ const film = chooseFilm(project, b.video, "the take")?.id ?? null;
1251
1398
  const file = toManifestPath(store.root, b.file);
1252
1399
  const info = await probe(fromManifestPath(store.root, file), { formats: AUDIO_FORMATS });
1253
- const { data, result } = await store.update("script", (s) => addTake(s, c.req.param("id"), { file, duration: info.duration }));
1400
+ const { data, result } = await store.update("script", (f) => addTake(filmScriptDraft(f, project, film), c.req.param("id"), { file, duration: info.duration }));
1254
1401
  await log.add(() => {
1255
- const section = data.sections.find((s) => s.id === c.req.param("id"));
1402
+ const section = filmScript(data, project, film).sections.find((s) => s.id === c.req.param("id"));
1256
1403
  return takeEvent(section, result, section.takes.findIndex((t) => t.id === result.id) + 1);
1257
1404
  }, by(c));
1258
1405
  return c.json({ take: result }, 201);
@@ -1263,7 +1410,7 @@ export function createApp(store, opts = {}) {
1263
1410
  // agent and the loudness readout can never disagree about it.
1264
1411
  // Always among the takes the film hears (lanesForVideo), which is what Mix plays and the readout
1265
1412
  // measures: a take that has left the film is never its take in use.
1266
- const filmUse = (project, picks, video) => inUse({ lanes: lanesForVideo(project.lanes, video, project.videos.length) }, picksForVideo(picks, video));
1413
+ const filmUse = (project, picks, video) => inUse({ lanes: lanesForVideo(project.lanes, video, project.videos) }, picksForVideo(picks, video));
1267
1414
  const withUse = (project, picks, video) => {
1268
1415
  if (video)
1269
1416
  return { ...picksForVideo(picks, video), use: filmUse(project, picks, video) };
@@ -1356,6 +1503,12 @@ export function createApp(store, opts = {}) {
1356
1503
  const usedNow = project ? filmUse(project, data, b.video) : {};
1357
1504
  const sameUse = ["voice", "music", "sfx"].every((s) => usedBefore[s]?.lane === usedNow[s]?.lane && usedBefore[s]?.variant === usedNow[s]?.variant);
1358
1505
  const changed = Object.keys({ ...before, ...after }).some((k) => before[k] !== after[k]) || !sameUse;
1506
+ // §29: a new take in use is balanced against the others by itself, unless a fader has been moved by hand.
1507
+ if (opts.autoBalance && project && !sameUse && b.levels === undefined) {
1508
+ const own = b.video ? data.videos[b.video] : data;
1509
+ if (own && balanceOwned(own))
1510
+ autoBalance(b.video, by(c));
1511
+ }
1359
1512
  if (changed) {
1360
1513
  const inUseLanes = Object.fromEntries(Object.values(usedNow).map((u) => [u.lane, u.variant]));
1361
1514
  if (project)
@@ -1365,13 +1518,86 @@ export function createApp(store, opts = {}) {
1365
1518
  }
1366
1519
  return c.json(project ? withUse(project, data, b.video) : b.video ? picksForVideo(data, b.video) : data);
1367
1520
  });
1521
+ // ---- §29: balance ----
1522
+ // Levels are the balance's own while none are set, or while they still equal what the last balance set
1523
+ // (an unset level is 0 dB). Moving a fader by hand ends that until Balance is pressed again.
1524
+ const sameLevels = (a, b) => ["voice", "music", "sfx"].every((k) => (a[k] ?? 0) === (b[k] ?? 0));
1525
+ const balanceOwned = (own) => own.balanced ? sameLevels(own.levels, own.balanced.levels) : ["voice", "music", "sfx"].every((k) => (own.levels[k] ?? 0) === 0);
1526
+ /**
1527
+ * Measures the film's takes in use and sets its levels to the house balance (core/balance.ts). `guard` (the
1528
+ * automatic run) is asked again inside the write, against the picks as they are then: if a fader was moved or
1529
+ * another take picked while ffmpeg ran, nothing is written.
1530
+ */
1531
+ const runBalance = async (video, who, guard) => {
1532
+ const [project, picks] = await Promise.all([store.read("project"), store.read("picks")]);
1533
+ const heard = { ...project, lanes: lanesForVideo(project.lanes, video, project.videos) };
1534
+ const result = await balanceFilm(heard, picksForVideo(picks, video), store.root, opts.loudnessRunner ?? defaultRunner, opts.loudnessTimeoutMs);
1535
+ if (!result.available)
1536
+ return { result, written: false, project, picks };
1537
+ let written = false;
1538
+ const { data } = await store.update("picks", (p) => {
1539
+ const own = video ? (p.videos[video] ??= { lanes: {}, levels: {} }) : p;
1540
+ if (guard && !guard(own, p, project))
1541
+ return;
1542
+ // Each sound in use takes its balanced level (0 dB is stored as unset, as a fader reset is); the others keep theirs.
1543
+ for (const stage of ["voice", "music", "sfx"]) {
1544
+ const v = result.levels[stage];
1545
+ if (v === undefined)
1546
+ continue;
1547
+ if (v === 0)
1548
+ delete own.levels[stage];
1549
+ else
1550
+ own.levels[stage] = v;
1551
+ }
1552
+ own.balanced = { levels: { ...own.levels }, at: new Date().toISOString() };
1553
+ written = true;
1554
+ });
1555
+ if (written) {
1556
+ const film = project.videos.find((v) => v.id === video);
1557
+ const event = { area: "mix", kind: "entry", merge: "replace", subject: `balance:${film?.id ?? ""}`, video: film?.id ?? null, version: null, text: `Mix balanced${film ? ` for ${film.name}` : ""}: ${balanceSummary(result.report)}` };
1558
+ await log.add(() => event, who);
1559
+ }
1560
+ return { result, written, project, picks: data };
1561
+ };
1562
+ // The automatic run, one at a time per film: a pick arriving while one is measuring runs again after it.
1563
+ const autoRuns = new Map();
1564
+ const autoBalance = (video, who) => {
1565
+ const key = video ?? "";
1566
+ const prev = autoRuns.get(key) ?? Promise.resolve();
1567
+ const run = prev.then(async () => {
1568
+ const before = await store.read("picks").catch(() => null);
1569
+ const project = await store.read("project").catch(() => null);
1570
+ if (!before || !project)
1571
+ return opts.onAutoBalance?.(video, null);
1572
+ const useAt = JSON.stringify(filmUse(project, before, video));
1573
+ const { result, written } = await runBalance(video, who, (own, p, proj) => balanceOwned(own) && JSON.stringify(filmUse(proj, p, video)) === useAt);
1574
+ opts.onAutoBalance?.(video, written && result.available ? balanceSummary(result.report) : null);
1575
+ }).catch(() => opts.onAutoBalance?.(video, null));
1576
+ autoRuns.set(key, run);
1577
+ void run.finally(() => {
1578
+ if (autoRuns.get(key) === run)
1579
+ autoRuns.delete(key);
1580
+ });
1581
+ };
1582
+ app.post("/api/mix/balance", async (c) => {
1583
+ const b = await body(c, BalanceBody);
1584
+ if (b.video) {
1585
+ const project = await store.read("project");
1586
+ if (!project.videos.some((v) => v.id === b.video))
1587
+ throw new RushesError(`No film "${b.video}"`, 404, "not_found");
1588
+ }
1589
+ const { result, project, picks } = await runBalance(b.video, by(c));
1590
+ if (!result.available)
1591
+ return c.json({ available: false, summary: "Install ffmpeg to balance the mix." });
1592
+ return c.json({ available: true, levels: result.levels, report: result.report, summary: balanceSummary(result.report), picks: withUse(project, picks, b.video) });
1593
+ });
1368
1594
  // ---- mix loudness (§17.6) ----
1369
1595
  app.post("/api/mix/loudness", async (c) => {
1370
1596
  const b = await body(c, MixLoudnessBody);
1371
1597
  const [project, picks] = await Promise.all([store.read("project"), store.read("picks")]);
1372
1598
  const run = opts.loudnessRunner ?? defaultRunner;
1373
1599
  // A film hears only its own reads, beds and passes, as its Mix tab plays them.
1374
- const heard = { ...project, lanes: lanesForVideo(project.lanes, b.video, project.videos.length) };
1600
+ const heard = { ...project, lanes: lanesForVideo(project.lanes, b.video, project.videos) };
1375
1601
  const result = await measureMix(heard, picksForVideo(picks, b.video), b.lanes, store.root, run, opts.loudnessTimeoutMs);
1376
1602
  return c.json(result);
1377
1603
  });
@@ -1397,23 +1623,43 @@ export function createApp(store, opts = {}) {
1397
1623
  return settled === late ? { handedTo: agent.status().agent, starting: true } : settled;
1398
1624
  };
1399
1625
  app.post("/api/batches", async (c) => {
1400
- const { stage } = await body(c, BatchBody);
1626
+ const { stage, video } = await body(c, BatchBody);
1627
+ // §32: a Send before the desk has read the agent still goes where the Mac-wide default says.
1628
+ await adoptAgentDefaultsOnce(store);
1629
+ // §31.2.2: Send on a film sends that film's notes and script alone, and the batch carries the film.
1630
+ const film = video ? chooseFilm(await store.read("project"), video).id : null;
1401
1631
  let handing;
1402
1632
  const run = batchQueue.catch(() => undefined).then(async () => {
1403
1633
  const [project, script, notes, batches] = await Promise.all([store.read("project"), store.read("script"), store.read("notes"), store.read("batches")]);
1404
1634
  // createBatch marks the notes it takes and files the batch in `batches`; on copies, it only
1405
1635
  // tells us what goes in.
1406
- const result = createBatch({ project, script, notes: structuredClone(notes), batches: structuredClone(batches) }, stage);
1636
+ const result = createBatch({ project, script: filmScript(script, project, film), notes: structuredClone(notes), batches: structuredClone(batches), video: film }, stage);
1407
1637
  // R11: the prompt ends with the last five lines of the log, from before this send. A log that
1408
- // can't be read adds nothing: the batch must still be sent.
1638
+ // can't be read adds nothing: the batch must still be sent. §31.5: with a film, the lines Activity shows on it.
1409
1639
  const recent = await Promise.all([store.read("project"), store.read("script")])
1410
- .then(async ([projectNow, scriptNow]) => recentChanges((await log.view({ limit: 5 }, { project: projectNow, script: scriptNow })).entries))
1640
+ .then(async ([projectNow, scriptNow]) => recentChanges((await log.view({ limit: 5, ...(film ? { video: film } : {}) }, { project: projectNow, script: everySection(scriptNow), films: { videos: projectNow.videos, lanes: projectNow.lanes, notes: notes.notes } })).entries))
1411
1641
  .catch(() => "");
1412
1642
  if (recent)
1413
1643
  result.prompt = `${result.prompt}\n\n${recent}`;
1414
1644
  await store.update("batches", (f) => { f.batches.push(result); });
1415
1645
  await store.update("notes", (f) => markSent(f.notes, result));
1416
- await log.add(() => notesSentEvent(result), by(c));
1646
+ // §30: one line per film the batch's notes are on (its script edits go with the notes on no film). §31.2.2: a
1647
+ // batch sent on a film is that film's alone: one line, script edits and the shared visuals' notes included.
1648
+ const noteFilm = new Map(notes.notes.map((n) => [n.id, n.video ?? null]));
1649
+ const stageOf = new Map(notes.notes.map((n) => [n.id, n.stage]));
1650
+ const own = film && project.videos.length > 1 ? film : null;
1651
+ const groups = own ? [[own, result.noteIds]] : byFilm(result.noteIds, (id) => noteFilm.get(id));
1652
+ const takesEdits = (f) => f === null || f === own;
1653
+ if (groups.length === 0 || (result.sectionIds.length > 0 && !groups.some(([f]) => takesEdits(f))))
1654
+ groups.push([own, []]);
1655
+ for (const [lineFilm, ids] of groups) {
1656
+ const sectionIds = takesEdits(lineFilm) ? result.sectionIds : [];
1657
+ // Each film's line names the tab its own notes came from ("from Picture"), not the whole batch's.
1658
+ const stages = new Set([...ids.map((id) => stageOf.get(id)), ...(sectionIds.length ? ["script"] : [])]);
1659
+ const stage = stages.size === 1 ? ([...stages][0] ?? result.stage) : result.stage;
1660
+ const part = { ...result, stage, noteIds: ids, sectionIds };
1661
+ await log.add(() => notesSentEvent(part, lineFilm), by(c));
1662
+ }
1417
1663
  handing = (async () => agent.send(result))();
1418
1664
  return result;
1419
1665
  });
@@ -1421,16 +1667,40 @@ export function createApp(store, opts = {}) {
1421
1667
  const batch = await run;
1422
1668
  return c.json({ batch, agent: await handOverOf(handing) }, 201);
1423
1669
  });
1670
+ // I3, Send again: a batch whose hand-over was refused while Send to AI was on (its `undelivered` mark) goes to the
1671
+ // agent now, while notes of it still wait. The mark is in batches.json, so this works after a restart too. Refused
1672
+ // again (still not signed in), it says why and keeps the mark, as Send does.
1673
+ app.post("/api/batches/:id/resend", async (c) => {
1674
+ const id = c.req.param("id");
1675
+ const [batches, notes] = await Promise.all([store.read("batches"), store.read("notes")]);
1676
+ const batch = batches.batches.find((b) => b.id === id);
1677
+ if (!batch)
1678
+ throw new NotFoundError("batch", id);
1679
+ if (!notes.notes.some((n) => n.batch === id && noteState(n) === "sent")) {
1680
+ throw new RushesError(`Nothing in ${id} is waiting for the agent any more.`, 409, "batch_not_waiting");
1681
+ }
1682
+ if (!batch.undelivered)
1683
+ throw new RushesError(`${id} already reached the agent.`, 409, "batch_delivered");
1684
+ const handed = await handOverOf(agent.resend(batch));
1685
+ // Null: another Send again took it a moment ago.
1686
+ if (!handed)
1687
+ throw new RushesError(`${id} already reached the agent.`, 409, "batch_delivered");
1688
+ return c.json({ batch: { ...batch, undelivered: null }, agent: handed });
1689
+ });
1424
1690
  app.get("/api/batches/:id", async (c) => {
1425
- const [batches, notes, script, visuals] = await Promise.all([store.read("batches"), store.read("notes"), store.read("script"), store.read("visuals")]);
1691
+ const [batches, notes, script, visuals, project] = await Promise.all([store.read("batches"), store.read("notes"), store.read("script"), store.read("visuals"), store.read("project")]);
1426
1692
  const id = c.req.param("id");
1427
1693
  const batch = id === "latest" ? latestBatch(batches) : batches.batches.find((b) => b.id === id);
1428
1694
  if (!batch)
1429
1695
  throw new NotFoundError("batch", id);
1696
+ // §31.6: a batch is about one film (its `video`): its sections are that film's script's, and the film is named so an
1697
+ // agent working the batch passes it on. A batch from before names none: its sections are the first film's.
1698
+ const film = batch.video ? project.videos.find((v) => v.id === batch.video) : undefined;
1430
1699
  return c.json({
1431
1700
  batch,
1701
+ ...(film ? { film: { id: film.id, name: film.name } } : {}),
1432
1702
  notes: withVisualViews(notes.notes.filter((n) => batch.noteIds.includes(n.id)), visuals),
1433
- sections: script.sections.filter((s) => batch.sectionIds.includes(s.id)),
1703
+ sections: filmScript(script, project, batch.video ?? null).sections.filter((s) => batch.sectionIds.includes(s.id)),
1434
1704
  });
1435
1705
  });
1436
1706
  // ---- visuals (§25) ----
@@ -1453,8 +1723,9 @@ export function createApp(store, opts = {}) {
1453
1723
  const q = LogQuery.safeParse(c.req.query());
1454
1724
  if (!q.success)
1455
1725
  throw new InvalidError(q.error.issues.map((i) => i.message).join("; "), q.error.issues);
1456
- const [project, script] = await Promise.all([store.read("project"), store.read("script")]);
1457
- return c.json(await log.view(q.data, { project, script }));
1726
+ const [project, script, notes] = await Promise.all([store.read("project"), store.read("script"), store.read("notes")]);
1727
+ const video = q.data.video ? chooseFilm(project, q.data.video).id : undefined;
1728
+ return c.json(await log.view({ ...q.data, video }, { project, script: everySection(script), films: { videos: project.videos, lanes: project.lanes, notes: notes.notes } }));
1458
1729
  });
1459
1730
  app.post("/api/log", async (c) => {
1460
1731
  const b = await body(c, LogLineBody);
@@ -1489,7 +1760,7 @@ export function createApp(store, opts = {}) {
1489
1760
  const script = await store.read("script");
1490
1761
  const refs = new Set([
1491
1762
  ...project.lanes.flatMap((l) => l.variants.map((x) => `${l.id}/${x.id}`)),
1492
- ...script.sections.flatMap((s) => s.takes.map((x) => `${s.id}:${x.id}`)),
1763
+ ...allSections(script).flatMap((s) => s.takes.map((x) => `${s.id}:${x.id}`)),
1493
1764
  ]);
1494
1765
  if (!refs.has(b.ref))
1495
1766
  throw new NotFoundError("ref", shown(b.ref));
@@ -1501,7 +1772,11 @@ export function createApp(store, opts = {}) {
1501
1772
  });
1502
1773
  // ---- Send to AI (§28) ----
1503
1774
  const agentStatusOf = async () => ({ status: await agent.reload() });
1504
- app.get("/api/agent", async (c) => c.json(await agentStatusOf()));
1775
+ // §32: the desk reads this as it loads: a project with no rules of its own starts from the Mac-wide default first.
1776
+ app.get("/api/agent", async (c) => {
1777
+ await adoptAgentDefaultsOnce(store);
1778
+ return c.json(await agentStatusOf());
1779
+ });
1505
1780
  // ?fresh=1 checks again now (after the user signs in), not from the last 30 s.
1506
1781
  app.get("/api/agent/detect", async (c) => {
1507
1782
  if (c.req.query("fresh") === "1")
@@ -1518,7 +1793,9 @@ export function createApp(store, opts = {}) {
1518
1793
  // else. It never chooses an agent, never keeps one the user didn't choose, and leaves the switch as it is.
1519
1794
  const permissions = b.permissions;
1520
1795
  if (permissions !== undefined && b.agent === undefined) {
1521
- await rules.update((f) => void (f.permissions = permissions));
1796
+ const { data } = await rules.update((f) => void (f.permissions = permissions));
1797
+ // §32: the menu's choice is the default for new projects too.
1798
+ await rememberDefault({ permissions }, data);
1522
1799
  return c.json(await agentStatusOf());
1523
1800
  }
1524
1801
  // The row's switch names no agent: it turns on the one agent.json names, so it can't stand in for the sheet's "who"
@@ -1567,6 +1844,12 @@ export function createApp(store, opts = {}) {
1567
1844
  });
1568
1845
  if (b.on)
1569
1846
  await consent();
1847
+ // §32: the user's choice is Send to AI's default for every new project on this Mac (last choice wins): the agent
1848
+ // turned on, with what it may do, or no agent after Copy a prompt. Turning the switch off leaves it as it is.
1849
+ if (b.on || b.prompt) {
1850
+ const now = await rules.read();
1851
+ await rememberDefault({ agent: b.on ? checked : null, ...(permissions !== undefined ? { permissions } : {}) }, now);
1852
+ }
1570
1853
  // I3: the batch the dialog showed goes to the agent now, if its hand-over was refused and it hasn't gone since (the
1571
1854
  // runner takes it from its refused set once, under its send lock), while notes of it still wait.
1572
1855
  if (b.on && filed && (await store.read("notes")).notes.some((n) => n.batch === filed.id && noteState(n) === "sent")) {