@morshoto/framekit 0.1.17 → 0.2.2

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 (58) hide show
  1. package/README.md +25 -14
  2. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +8 -2
  3. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery-guard.js +275 -0
  4. package/dist-package/adapters/final-cut/typescript/src/canonical.js +557 -84
  5. package/dist-package/adapters/final-cut/typescript/src/connection.js +10 -3
  6. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +6 -0
  7. package/dist-package/adapters/final-cut/typescript/src/experimental.js +8 -0
  8. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +150 -37
  9. package/dist-package/adapters/final-cut/typescript/src/index.js +2 -7
  10. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +60 -1
  11. package/dist-package/adapters/final-cut/typescript/src/live.js +29 -4
  12. package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.js +175 -0
  13. package/dist-package/adapters/final-cut/typescript/src/native-session.js +11 -6
  14. package/dist-package/adapters/final-cut/typescript/src/native.js +201 -82
  15. package/dist-package/adapters/final-cut/typescript/src/publish-readback.js +214 -0
  16. package/dist-package/adapters/final-cut/typescript/src/publisher.js +1008 -243
  17. package/dist-package/adapters/final-cut/typescript/src/session.js +49 -14
  18. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +203 -49
  19. package/dist-package/adapters/headless/typescript/src/audio-output.js +3 -0
  20. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +48 -20
  21. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +9 -4
  22. package/dist-package/apps/cli/src/dev-doctor.js +198 -0
  23. package/dist-package/apps/cli/src/headless-projects.js +5 -0
  24. package/dist-package/apps/cli/src/main.js +76 -19
  25. package/dist-package/apps/mcp-server/runtime/speech-analyzer-wrapper.mjs +54 -0
  26. package/dist-package/apps/mcp-server/runtime/whisper-speech-backend.py +181 -0
  27. package/dist-package/apps/mcp-server/src/build-alignment.js +59 -0
  28. package/dist-package/apps/mcp-server/src/build-identity.js +30 -0
  29. package/dist-package/apps/mcp-server/src/build-identity.json +5 -0
  30. package/dist-package/apps/mcp-server/src/canonical-native-snapshot.js +18 -0
  31. package/dist-package/apps/mcp-server/src/final-cut-runtime-config.js +3 -0
  32. package/dist-package/apps/mcp-server/src/headless-project-snapshot.js +101 -0
  33. package/dist-package/apps/mcp-server/src/main.js +50 -21
  34. package/dist-package/apps/mcp-server/src/materialization-jobs.js +143 -10
  35. package/dist-package/apps/mcp-server/src/routing.js +2 -0
  36. package/dist-package/apps/mcp-server/src/server.js +986 -180
  37. package/dist-package/apps/mcp-server/src/tools/skills/catalog.js +142 -0
  38. package/dist-package/apps/mcp-server/src/tools/skills/metadata.js +71 -0
  39. package/dist-package/apps/mcp-server/src/tools/skills/register.js +101 -0
  40. package/dist-package/apps/mcp-server/src/version.js +21 -2
  41. package/dist-package/packages/headless-application/src/headless-projects.js +942 -0
  42. package/dist-package/packages/headless-application/src/index.js +1 -0
  43. package/dist-package/packages/runtime/src/application/media-analysis-service.js +15 -5
  44. package/dist-package/packages/runtime/src/application/project-service.js +5 -1
  45. package/dist-package/packages/runtime/src/application/project-store.js +13 -36
  46. package/dist-package/packages/runtime/src/application/transaction-store.js +1 -1
  47. package/dist-package/packages/runtime/src/capabilities.js +1 -1
  48. package/dist-package/packages/runtime/src/context/context-engine.js +22 -16
  49. package/dist-package/packages/runtime/src/context/context-service.js +2 -2
  50. package/dist-package/packages/runtime/src/editing/edit-service.js +76 -10
  51. package/dist-package/packages/runtime/src/index.js +1 -0
  52. package/dist-package/packages/runtime/src/runtime.js +22 -7
  53. package/dist-package/packages/runtime/src/timeline/editing-session.js +23 -2
  54. package/dist-package/packages/testkit/src/in-memory-editor.js +3 -3
  55. package/dist-package/packages/testkit/src/index.js +1 -0
  56. package/dist-package/packages/testkit/src/sender-lifecycle-fixture.js +192 -0
  57. package/package.json +36 -14
  58. package/dist-package/apps/mcp-server/src/headless-projects.js +0 -370
@@ -1,10 +1,11 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { execFile } from "node:child_process";
3
3
  import { createReadStream } from "node:fs";
4
- import { access, link, lstat, mkdtemp, rename, rm, unlink } from "node:fs/promises";
4
+ import { access, link, lstat, mkdtemp, rename, rm, unlink, writeFile } from "node:fs/promises";
5
5
  import { existsSync } from "node:fs";
6
6
  import { dirname, join, resolve } from "node:path";
7
7
  import { promisify } from "node:util";
8
+ import { HEADLESS_AUDIO_CHANNELS, HEADLESS_AUDIO_CODEC, HEADLESS_AUDIO_SAMPLE_RATE } from "./audio-output.js";
8
9
  import { createFramekitRenderResult, } from "../../../../packages/runtime/src/index.js";
9
10
  const execFileAsync = promisify(execFile);
10
11
  export class FfmpegRenderError extends Error {
@@ -64,10 +65,11 @@ export class FfmpegTimelineRenderer {
64
65
  const stagingDirectory = await mkdtemp(join(outputDirectory, ".framekit-render-"));
65
66
  const stagingPath = join(stagingDirectory, `render.${plan.parameters.format}`);
66
67
  try {
67
- const args = buildFfmpegArguments(model, stagingPath, this.fontFile);
68
+ const titleTextFiles = await writeTitleTextFiles(model.timeline.sequence.titles ?? [], stagingDirectory);
69
+ const args = buildFfmpegArguments(model, stagingPath, this.fontFile, titleTextFiles);
68
70
  try {
69
71
  await execFileAsync(this.ffmpegPath, args, {
70
- cwd: process.cwd(),
72
+ cwd: stagingDirectory,
71
73
  env: this.environment,
72
74
  maxBuffer: 8 * 1024 * 1024,
73
75
  });
@@ -126,8 +128,8 @@ async function prepareRenderModel(plan) {
126
128
  throw new FfmpegRenderError("HEADLESS_RENDER_UNSUPPORTED", "occurrence roles and lanes do not form a primary video storyline with connected audio layers");
127
129
  }
128
130
  const duration = rationalSeconds(sequence.durationTime, "sequence duration");
129
- const frameRate = 1 / rationalSeconds(sequence.frameDuration, "sequence frame duration");
130
- if (!Number.isFinite(duration) || duration <= 0 || !Number.isFinite(frameRate) || frameRate <= 0) {
131
+ const sequenceFrameRate = 1 / rationalSeconds(sequence.frameDuration, "sequence frame duration");
132
+ if (!Number.isFinite(duration) || duration <= 0 || !Number.isFinite(sequenceFrameRate) || sequenceFrameRate <= 0) {
131
133
  throw new FfmpegRenderError("HEADLESS_RENDER_UNSUPPORTED", "sequence duration and frame rate must be finite and positive");
132
134
  }
133
135
  if (!Number.isSafeInteger(plan.parameters.width) || !Number.isSafeInteger(plan.parameters.height)) {
@@ -190,8 +192,9 @@ async function prepareRenderModel(plan) {
190
192
  if (audioAvailability.size > 1) {
191
193
  throw new FfmpegRenderError("HEADLESS_RENDER_UNSUPPORTED", "all primary occurrences must agree on audio availability");
192
194
  }
193
- if (Math.abs(previousEnd - duration) > 1e-7) {
194
- throw new FfmpegRenderError("HEADLESS_RENDER_UNSUPPORTED", "occurrences do not cover the sequence duration");
195
+ const tailDuration = duration - previousEnd;
196
+ if (tailDuration < -1e-7) {
197
+ throw new FfmpegRenderError("HEADLESS_RENDER_UNSUPPORTED", "primary occurrences exceed the sequence duration");
195
198
  }
196
199
  const transitions = timeline.sequence.transitions ?? [];
197
200
  if (transitions.length > 1) {
@@ -204,7 +207,8 @@ async function prepareRenderModel(plan) {
204
207
  resources,
205
208
  sourcePaths,
206
209
  duration,
207
- frameRate,
210
+ tailDuration: Math.max(0, tailDuration),
211
+ frameRate: structuredClone(plan.parameters.frameRate),
208
212
  width: plan.parameters.width,
209
213
  height: plan.parameters.height,
210
214
  format: plan.parameters.format,
@@ -290,13 +294,13 @@ async function assertSourcesUnchanged(model) {
290
294
  }
291
295
  }
292
296
  }
293
- function buildFfmpegArguments(model, stagingPath, fontFile) {
297
+ function buildFfmpegArguments(model, stagingPath, fontFile, titleTextFiles) {
294
298
  const filters = [];
295
299
  const inputArguments = [];
296
300
  const videoLabels = [];
297
301
  const audioLabels = [];
298
302
  const musicLabels = [];
299
- const fps = formatNumber(model.frameRate);
303
+ const fps = `${model.frameRate.value}/${model.frameRate.timescale}`;
300
304
  const inputIndices = new Map();
301
305
  for (const [index, occurrence] of [...model.occurrences, ...model.audioOccurrences].entries()) {
302
306
  const resource = model.resources.get(occurrence.mediaId);
@@ -317,7 +321,7 @@ function buildFfmpegArguments(model, stagingPath, fontFile) {
317
321
  if (hasAudio) {
318
322
  const audioLabel = `clipa${index}`;
319
323
  const gain = occurrence.gainDb ?? 0;
320
- filters.push(`${`[${index}:a]`}atrim=start=${formatNumber(sourceStart)}:duration=${formatNumber(duration)},asetpts=PTS-STARTPTS,aresample=48000,volume=${formatNumber(Math.pow(10, gain / 20))}[${audioLabel}]`);
324
+ filters.push(`${`[${index}:a]`}atrim=start=${formatNumber(sourceStart)}:duration=${formatNumber(duration)},asetpts=PTS-STARTPTS,aresample=${HEADLESS_AUDIO_SAMPLE_RATE},volume=${formatNumber(Math.pow(10, gain / 20))}[${audioLabel}]`);
321
325
  audioLabels.push(`[${audioLabel}]`);
322
326
  }
323
327
  }
@@ -327,14 +331,15 @@ function buildFfmpegArguments(model, stagingPath, fontFile) {
327
331
  const start = rationalSeconds(occurrence.startTime, `${occurrence.id}.startTime`);
328
332
  const duration = rationalSeconds(occurrence.durationTime, `${occurrence.id}.durationTime`);
329
333
  const gain = occurrence.gainDb ?? 0;
330
- const delaySamples = Math.round(start * 48_000);
334
+ const delaySamples = Math.round(start * HEADLESS_AUDIO_SAMPLE_RATE);
331
335
  const audioLabel = `bed-audio${index}`;
332
- filters.push(`[${index}:a]atrim=start=${formatNumber(sourceStart)}:duration=${formatNumber(duration)},asetpts=PTS-STARTPTS,aresample=48000,aformat=channel_layouts=mono,volume=${formatNumber(Math.pow(10, gain / 20))},adelay=${delaySamples}S:all=1,apad,atrim=duration=${formatNumber(model.duration)},asetpts=PTS-STARTPTS[${audioLabel}]`);
336
+ filters.push(`[${index}:a]atrim=start=${formatNumber(sourceStart)}:duration=${formatNumber(duration)},asetpts=PTS-STARTPTS,aresample=${HEADLESS_AUDIO_SAMPLE_RATE},aformat=channel_layouts=mono,volume=${formatNumber(Math.pow(10, gain / 20))},adelay=${delaySamples}S:all=1,apad=whole_dur=${formatNumber(model.duration)},asetpts=PTS-STARTPTS[${audioLabel}]`);
333
337
  musicLabels.push(`[${audioLabel}]`);
334
338
  }
335
339
  const transition = model.timeline.sequence.transitions?.[0];
336
340
  const videoBase = addVideoComposition(filters, videoLabels, model, transition);
337
- const videoOutput = addTitleOverlays(filters, videoBase, model, fontFile);
341
+ const videoWithTail = addBlackVideoTail(filters, videoBase, model.tailDuration);
342
+ const videoOutput = addTitleOverlays(filters, videoWithTail, model, fontFile, titleTextFiles);
338
343
  let audioOutput;
339
344
  if (audioLabels.length > 0)
340
345
  audioOutput = addAudioComposition(filters, audioLabels, model, transition);
@@ -345,7 +350,7 @@ function buildFfmpegArguments(model, stagingPath, fontFile) {
345
350
  const args = ["-hide_banner", "-loglevel", "error", "-nostdin", "-y", ...inputArguments, "-filter_complex", filters.join(";")];
346
351
  args.push("-map", `[${videoOutput}]`, "-c:v", "libx264", "-preset", "ultrafast", "-threads", "1", "-pix_fmt", "yuv420p", "-r", fps);
347
352
  if (audioOutput) {
348
- args.push("-map", `[${audioOutput}]`, "-c:a", "aac", "-b:a", "128k", "-ar", "48000", "-ac", "1");
353
+ args.push("-map", `[${audioOutput}]`, "-c:a", HEADLESS_AUDIO_CODEC, "-b:a", "128k", "-ar", String(HEADLESS_AUDIO_SAMPLE_RATE), "-ac", String(HEADLESS_AUDIO_CHANNELS));
349
354
  }
350
355
  args.push("-map_metadata", "-1", "-t", formatNumber(model.duration), "-movflags", "+faststart", stagingPath);
351
356
  return args;
@@ -357,6 +362,13 @@ function addAudioMix(filters, labels, duration) {
357
362
  filters.push(`${labels.join("")}amix=inputs=${labels.length}:duration=longest:dropout_transition=0:normalize=0,apad,atrim=duration=${formatNumber(duration)},asetpts=PTS-STARTPTS[${output}]`);
358
363
  return output;
359
364
  }
365
+ function addBlackVideoTail(filters, input, duration) {
366
+ if (duration <= 1e-7)
367
+ return input;
368
+ const output = "video-black-tail";
369
+ filters.push(`[${input}]tpad=stop_mode=add:stop_duration=${formatNumber(duration)}:color=black[${output}]`);
370
+ return output;
371
+ }
360
372
  function addVideoComposition(filters, labels, model, transition) {
361
373
  if (labels.length === 1) {
362
374
  const output = "video-base";
@@ -395,9 +407,22 @@ function addAudioComposition(filters, labels, model, transition) {
395
407
  filters.push(`${labels.join("")}concat=n=${labels.length}:v=0:a=1[${output}]`);
396
408
  return output;
397
409
  }
398
- function addTitleOverlays(filters, input, model, fontFile) {
399
- let current = input;
400
- for (const [index, title] of (model.timeline.sequence.titles ?? []).entries()) {
410
+ async function writeTitleTextFiles(titles, stagingDirectory) {
411
+ const files = [];
412
+ for (const [index, title] of titles.entries()) {
413
+ const filename = `title-${index}.txt`;
414
+ await writeFile(join(stagingDirectory, filename), title.text, "utf8");
415
+ files.push(filename);
416
+ }
417
+ return files;
418
+ }
419
+ function addTitleOverlays(filters, input, model, fontFile, titleTextFiles) {
420
+ const titles = model.timeline.sequence.titles ?? [];
421
+ if (titles.length === 0)
422
+ return input;
423
+ filters.push(`[${input}]format=yuv420p[video-titles-base]`);
424
+ let current = "video-titles-base";
425
+ for (const [index, title] of titles.entries()) {
401
426
  const start = rationalSeconds(title.startTime, `${title.id}.startTime`);
402
427
  const end = start + rationalSeconds(title.durationTime, `${title.id}.durationTime`);
403
428
  const style = title.style;
@@ -411,7 +436,10 @@ function addTitleOverlays(filters, input, model, fontFile) {
411
436
  : "(h-text_h)/2";
412
437
  const output = `title-${index}`;
413
438
  const font = fontFile ? `fontfile='${escapeFilterValue(fontFile)}':` : "";
414
- filters.push(`[${current}]drawtext=${font}text='${escapeFilterValue(title.text)}':fontcolor=${color}:fontsize=${size}:x=${x}:y=${y}:enable='between(t,${formatNumber(start)},${formatNumber(end)})'[${output}]`);
439
+ const textFile = titleTextFiles[index];
440
+ if (!textFile)
441
+ throw new FfmpegRenderError("HEADLESS_RENDER_FAILED", `title text file is missing: ${index}`);
442
+ filters.push(`[${current}]drawtext=${font}textfile='${textFile}':expansion=none:fontcolor=${color}:fontsize=${size}:x=${x}:y=${y}:enable='between(t,${formatNumber(start)},${formatNumber(end)})'[${output}]`);
415
443
  current = output;
416
444
  }
417
445
  return current;
@@ -538,7 +566,7 @@ function formatNumber(value) {
538
566
  return Number(value.toFixed(6)).toString();
539
567
  }
540
568
  function escapeFilterValue(value) {
541
- return value.replaceAll("\\", "\\\\").replaceAll("'", "\\'").replaceAll(":", "\\:").replaceAll(",", "\\,").replaceAll("[", "\\[").replaceAll("]", "\\]").replaceAll("\n", "\\n");
569
+ return value.replaceAll("\\", "\\\\").replaceAll("'", "'\\''").replaceAll(":", "\\:").replaceAll(",", "\\,").replaceAll("[", "\\[").replaceAll("]", "\\]").replaceAll("\n", "\\n");
542
570
  }
543
571
  function resolveFontFile(preferred) {
544
572
  const candidates = [
@@ -4,6 +4,7 @@ import { createReadStream } from "node:fs";
4
4
  import { lstat, stat } from "node:fs/promises";
5
5
  import { resolve } from "node:path";
6
6
  import { promisify } from "node:util";
7
+ import { HEADLESS_AUDIO_CHANNELS, HEADLESS_AUDIO_CODEC, HEADLESS_AUDIO_SAMPLE_RATE } from "./audio-output.js";
7
8
  const execFileAsync = promisify(execFile);
8
9
  /** Independently verifies the committed output; it does not trust provider metadata. */
9
10
  export class FfmpegRenderVerifier {
@@ -78,8 +79,9 @@ export class FfmpegRenderVerifier {
78
79
  checks.push({ name: "frame-rate", passed: frameRatePassed, detail: "output rational frame rate matches the explicit request", expected: expectedFrameRate, observed: observedFrameRate });
79
80
  const audioPassed = expectedAudio === undefined || (audio !== undefined
80
81
  && (expectedAudio.sampleRate === undefined || Number(audio.sample_rate) === expectedAudio.sampleRate)
81
- && (expectedAudio.channels === undefined || audio.channels === expectedAudio.channels));
82
- checks.push({ name: "audio-stream", passed: audioPassed, detail: "canonical audio stream presence and metadata are preserved", expected: expectedAudio ?? { kind: "none" }, observed: audio ?? { kind: "none" } });
82
+ && (expectedAudio.channels === undefined || audio.channels === expectedAudio.channels)
83
+ && (expectedAudio.codec === undefined || audio.codec_name === expectedAudio.codec));
84
+ checks.push({ name: "audio-stream", passed: audioPassed, detail: "audio stream matches the expected output contract", expected: expectedAudio ?? { kind: "none" }, observed: audio ?? { kind: "none" } });
83
85
  checks.push({ name: "duration", passed: durationPassed, detail: `output duration is within ${tolerance} seconds of the canonical sequence`, expected: expectedDuration, observed: probe.format.duration });
84
86
  const artifact = {
85
87
  path: result.output.path,
@@ -118,8 +120,11 @@ function expectedAudioStream(plan) {
118
120
  for (const occurrence of plan.timeline.sequence.occurrences) {
119
121
  const resource = occurrence.mediaId ? resources.get(occurrence.mediaId) : undefined;
120
122
  const stream = resource?.metadata?.streams.find((candidate) => candidate.kind === "audio");
121
- if (stream)
122
- return { sampleRate: stream.sampleRate, channels: stream.channels };
123
+ if (stream) {
124
+ return plan.renderer.id === "ffmpeg-headless"
125
+ ? { sampleRate: HEADLESS_AUDIO_SAMPLE_RATE, channels: HEADLESS_AUDIO_CHANNELS, codec: HEADLESS_AUDIO_CODEC }
126
+ : { sampleRate: stream.sampleRate, channels: stream.channels };
127
+ }
123
128
  }
124
129
  return undefined;
125
130
  }
@@ -0,0 +1,198 @@
1
+ import { execFile as execFileCallback } from "node:child_process";
2
+ import { constants } from "node:fs";
3
+ import { access, readFile, stat } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { promisify } from "node:util";
7
+ const execFile = promisify(execFileCallback);
8
+ const tools = [
9
+ { name: "FFmpeg", command: "ffmpeg", args: ["-version"], install: "ffmpeg" },
10
+ { name: "ffprobe", command: "ffprobe", args: ["-version"], install: "ffmpeg" },
11
+ { name: "SQLite", command: "sqlite3", args: ["--version"], install: "sqlite" },
12
+ ];
13
+ export async function collectDevDoctorReport(options) {
14
+ const environment = options.environment ?? process.env;
15
+ const homeDirectory = options.homeDirectory ?? environment.HOME ?? homedir();
16
+ const runCommand = options.runCommand ?? defaultRunCommand;
17
+ const isPathWritable = options.isPathWritable ?? defaultIsPathWritable;
18
+ const platform = options.platform ?? process.platform;
19
+ const pins = await readToolchainPins(options.rootDirectory);
20
+ const checks = [];
21
+ if (!pins.node) {
22
+ checks.push({
23
+ name: "Node.js",
24
+ requirement: "required",
25
+ status: "fail",
26
+ message: "The repository .node-version pin is missing or invalid.",
27
+ });
28
+ }
29
+ else {
30
+ const currentNode = options.nodeVersion ?? process.version;
31
+ const supported = versionAtLeast(currentNode, pins.node);
32
+ checks.push({
33
+ name: "Node.js",
34
+ requirement: "required",
35
+ status: supported ? "pass" : "fail",
36
+ message: supported
37
+ ? `Node.js ${currentNode.replace(/^v/, "")} meets the ${pins.node} contributor minimum.`
38
+ : `Node.js ${pins.node} or newer is required; found ${currentNode}. Use nix develop ./nix or install the contributor toolchain.`,
39
+ });
40
+ }
41
+ if (!pins.pnpm) {
42
+ checks.push({
43
+ name: "pnpm",
44
+ requirement: "required",
45
+ status: "fail",
46
+ message: "package.json must pin an exact pnpm version in packageManager.",
47
+ });
48
+ }
49
+ else {
50
+ try {
51
+ const actual = (await runCommand("pnpm", ["--version"])).trim();
52
+ const matches = actual === pins.pnpm;
53
+ checks.push({
54
+ name: "pnpm",
55
+ requirement: "required",
56
+ status: matches ? "pass" : "fail",
57
+ message: matches
58
+ ? `pnpm ${actual} matches the repository pin.`
59
+ : `pnpm ${pins.pnpm} is required; found ${actual || "an unknown version"}. Run pnpm through Corepack inside nix develop ./nix.`,
60
+ });
61
+ }
62
+ catch {
63
+ checks.push({
64
+ name: "pnpm",
65
+ requirement: "required",
66
+ status: "fail",
67
+ message: `pnpm ${pins.pnpm} is required; it was not available. Run pnpm through Corepack inside nix develop ./nix.`,
68
+ });
69
+ }
70
+ }
71
+ const statePath = resolve(environment.FRAMEKIT_STATE_DIR ?? join(homeDirectory, ".framekit"));
72
+ const cachePath = resolve(environment.XDG_CACHE_HOME
73
+ ?? environment.npm_config_cache
74
+ ?? environment.NPM_CONFIG_CACHE
75
+ ?? join(homeDirectory, ".cache"));
76
+ for (const [name, path] of [["State directory", statePath], ["Cache directory", cachePath]]) {
77
+ const writable = await isPathWritable(path);
78
+ checks.push({
79
+ name,
80
+ requirement: "required",
81
+ status: writable ? "pass" : "fail",
82
+ path,
83
+ message: writable
84
+ ? `${path} is writable or can be created under a writable parent.`
85
+ : `${path} is not writable. Choose a writable path with ${name === "State directory" ? "FRAMEKIT_STATE_DIR" : "XDG_CACHE_HOME"}.`,
86
+ });
87
+ }
88
+ const requiredTools = options.profile === "fixture" ? new Set() : new Set(["ffmpeg", "ffprobe", "sqlite3"]);
89
+ for (const tool of tools) {
90
+ const requirement = requiredTools.has(tool.command) ? "required" : "optional";
91
+ try {
92
+ await runCommand(tool.command, [...tool.args]);
93
+ checks.push({
94
+ name: tool.name,
95
+ requirement,
96
+ status: "pass",
97
+ message: `${tool.command} is available.`,
98
+ });
99
+ }
100
+ catch {
101
+ checks.push({
102
+ name: tool.name,
103
+ requirement,
104
+ status: requirement === "required" ? "fail" : "unavailable",
105
+ message: requirement === "required"
106
+ ? `${tool.command} is required for the ${options.profile} profile. Install ${tool.install} with nix develop ./nix.`
107
+ : `${tool.command} is unavailable; the fixture profile does not require it.`,
108
+ });
109
+ }
110
+ }
111
+ if (options.profile === "native") {
112
+ if (platform !== "darwin") {
113
+ checks.push({
114
+ name: "Xcode",
115
+ requirement: "required",
116
+ status: "fail",
117
+ message: "The native profile requires macOS with Xcode selected; fixture and headless profiles do not.",
118
+ });
119
+ }
120
+ else {
121
+ try {
122
+ await runCommand("xcodebuild", ["-version"]);
123
+ checks.push({
124
+ name: "Xcode",
125
+ requirement: "required",
126
+ status: "pass",
127
+ message: "xcodebuild is available.",
128
+ });
129
+ }
130
+ catch {
131
+ checks.push({
132
+ name: "Xcode",
133
+ requirement: "required",
134
+ status: "fail",
135
+ message: "The native profile requires Xcode selected with xcode-select.",
136
+ });
137
+ }
138
+ }
139
+ }
140
+ return {
141
+ profile: options.profile,
142
+ ready: checks.every((check) => check.requirement !== "required" || check.status === "pass"),
143
+ checks,
144
+ };
145
+ }
146
+ async function readToolchainPins(rootDirectory) {
147
+ try {
148
+ const [node, packageJson] = await Promise.all([
149
+ readFile(join(rootDirectory, ".node-version"), "utf8"),
150
+ readFile(join(rootDirectory, "package.json"), "utf8"),
151
+ ]);
152
+ const packageManager = JSON.parse(packageJson).packageManager;
153
+ return {
154
+ node: /^\d+\.\d+\.\d+$/.test(node.trim()) ? node.trim() : "",
155
+ pnpm: typeof packageManager === "string" ? packageManager.match(/^pnpm@(\d+\.\d+\.\d+)$/)?.[1] ?? "" : "",
156
+ };
157
+ }
158
+ catch {
159
+ return { node: "", pnpm: "" };
160
+ }
161
+ }
162
+ function versionAtLeast(actualVersion, minimumVersion) {
163
+ const actual = actualVersion.replace(/^v/, "").split(".").map(Number);
164
+ const minimum = minimumVersion.split(".").map(Number);
165
+ if (actual.length < 3 || actual.some((part) => !Number.isInteger(part)) || minimum.length < 3)
166
+ return false;
167
+ for (let index = 0; index < 3; index += 1) {
168
+ if (actual[index] > minimum[index])
169
+ return true;
170
+ if (actual[index] < minimum[index])
171
+ return false;
172
+ }
173
+ return true;
174
+ }
175
+ async function defaultRunCommand(command, args) {
176
+ const result = await execFile(command, args, { timeout: 5_000, maxBuffer: 1024 * 1024 });
177
+ return result.stdout;
178
+ }
179
+ async function defaultIsPathWritable(path) {
180
+ let candidate = path;
181
+ while (true) {
182
+ try {
183
+ const information = await stat(candidate);
184
+ if (!information.isDirectory())
185
+ return false;
186
+ await access(candidate, constants.W_OK | constants.X_OK);
187
+ return true;
188
+ }
189
+ catch (error) {
190
+ if (error.code !== "ENOENT")
191
+ return false;
192
+ const parent = dirname(candidate);
193
+ if (parent === candidate)
194
+ return false;
195
+ candidate = parent;
196
+ }
197
+ }
198
+ }
@@ -0,0 +1,5 @@
1
+ import { HeadlessProjectService, } from "../../../packages/headless-application/src/index.js";
2
+ /** Creates the shared headless workflow for CLI-owned operations. */
3
+ export function createCliHeadlessProjectService(options) {
4
+ return new HeadlessProjectService(options);
5
+ }
@@ -1,9 +1,10 @@
1
1
  import { execFile as execFileCallback, spawn } from "node:child_process";
2
2
  import { access } from "node:fs/promises";
3
3
  import { fileURLToPath } from "node:url";
4
- import { dirname, join } from "node:path";
4
+ import { dirname, join, resolve } from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import { FinalCutConnectionManager } from "../../../adapters/final-cut/typescript/src/index.js";
7
+ import { collectDevDoctorReport } from "./dev-doctor.js";
7
8
  const execFile = promisify(execFileCallback);
8
9
  async function main() {
9
10
  const argv = process.argv.slice(2);
@@ -15,6 +16,10 @@ async function main() {
15
16
  return;
16
17
  }
17
18
  if (command === "doctor") {
19
+ if (args[0] === "dev") {
20
+ await doctorDev(args.slice(1));
21
+ return;
22
+ }
18
23
  await doctorFinalCut(args);
19
24
  return;
20
25
  }
@@ -26,7 +31,7 @@ async function main() {
26
31
  if (command !== "help")
27
32
  process.exitCode = 1;
28
33
  }
29
- async function connectFinalCut(args) {
34
+ async function connectFinalCut(args, output = process.stdout) {
30
35
  if (args[0] !== "finalcut") {
31
36
  throw new Error("Usage: framekit connect finalcut [--development] [--json]");
32
37
  }
@@ -40,11 +45,13 @@ async function connectFinalCut(args) {
40
45
  const manager = new FinalCutConnectionManager({
41
46
  extensionSourcePath,
42
47
  restartAfterInstall: true,
48
+ installBeforeProbe: development,
43
49
  });
44
50
  const status = await manager.ensureConnected();
45
- printStatus(status, json);
51
+ printStatus(status, json, output);
46
52
  if (status.state !== "ready")
47
53
  process.exitCode = 1;
54
+ return status;
48
55
  }
49
56
  async function doctorFinalCut(args) {
50
57
  if (args[0] !== "finalcut")
@@ -54,24 +61,60 @@ async function doctorFinalCut(args) {
54
61
  if (status.state !== "ready")
55
62
  process.exitCode = 1;
56
63
  }
57
- async function runMcp(args) {
64
+ async function doctorDev(args) {
65
+ let profile = "fixture";
66
+ let json = false;
67
+ for (let index = 0; index < args.length; index += 1) {
68
+ const argument = args[index];
69
+ if (argument === "--json") {
70
+ json = true;
71
+ continue;
72
+ }
73
+ if (argument === "--profile") {
74
+ const value = args[index + 1];
75
+ if (value !== "fixture" && value !== "headless" && value !== "native") {
76
+ throw new Error("Usage: framekit doctor dev [--profile fixture|headless|native] [--json]");
77
+ }
78
+ profile = value;
79
+ index += 1;
80
+ continue;
81
+ }
82
+ throw new Error("Usage: framekit doctor dev [--profile fixture|headless|native] [--json]");
83
+ }
84
+ const report = await collectDevDoctorReport({ profile, rootDirectory: repoRoot() });
85
+ printDevDoctorReport(report, json);
86
+ if (!report.ready)
87
+ process.exitCode = 1;
88
+ }
89
+ export async function runMcp(args, dependencies = {}) {
58
90
  const editorIndex = args.indexOf("--editor");
59
91
  const editor = editorIndex >= 0 ? args[editorIndex + 1] : "final-cut-live";
60
92
  const headless = args.includes("--headless");
93
+ const development = args.includes("--development");
61
94
  if (editor !== "final-cut-live" && editor !== "fixture") {
62
- throw new Error("Usage: framekit mcp [--editor final-cut-live|fixture] [--headless]");
95
+ throw new Error("Usage: framekit mcp [--editor final-cut-live|fixture] [--headless] [--development]");
63
96
  }
64
97
  if (headless && editor !== "final-cut-live") {
65
98
  throw new Error("Usage: --headless is only supported with --editor final-cut-live");
66
99
  }
100
+ if (development && editor !== "final-cut-live") {
101
+ throw new Error("Usage: --development is only supported with --editor final-cut-live");
102
+ }
103
+ if (development) {
104
+ const connect = dependencies.connectDevelopmentExtension ?? connectFinalCut;
105
+ const status = await connect(["finalcut", "--development", "--json"], dependencies.stderr ?? process.stderr);
106
+ if (status.state !== "ready")
107
+ return;
108
+ }
67
109
  const root = repoRoot();
68
110
  const compiled = fileURLToPath(import.meta.url).endsWith(".js");
69
111
  const entrypoint = join(root, `apps/mcp-server/src/main.${compiled ? "js" : "ts"}`);
70
- const child = spawn(process.execPath, [...(compiled ? [] : ["--import", "tsx"]), entrypoint], {
112
+ const child = (dependencies.spawnChild ?? spawn)(process.execPath, [...(compiled ? [] : ["--import", "tsx"]), entrypoint], {
71
113
  stdio: "inherit",
72
114
  env: {
73
115
  ...process.env,
74
116
  FRAMEKIT_EDITOR: editor,
117
+ ...(development ? { FRAMEKIT_REQUIRE_BUILD_ALIGNMENT: "1" } : {}),
75
118
  ...(headless
76
119
  ? {
77
120
  FRAMEKIT_FINAL_CUT_HEADLESS: "1",
@@ -97,19 +140,30 @@ async function buildDevelopmentExtension() {
97
140
  function repoRoot() {
98
141
  return join(dirname(fileURLToPath(import.meta.url)), "../../..");
99
142
  }
100
- function printStatus(status, json) {
143
+ function printStatus(status, json, output = process.stdout) {
101
144
  if (json) {
102
- process.stdout.write(`${JSON.stringify(status)}\n`);
145
+ output.write(`${JSON.stringify(status)}\n`);
103
146
  return;
104
147
  }
105
- process.stdout.write(`Framekit Final Cut: ${status.state}\n`);
106
- process.stdout.write(`Final Cut detected: ${status.editorDetected ? "yes" : "no"}\n`);
107
- process.stdout.write(`Extension: ${status.extensionInstalled ? status.extensionPath : "not installed"}\n`);
108
- process.stdout.write(`Socket: ${status.socketPath}\n`);
148
+ output.write(`Framekit Final Cut: ${status.state}\n`);
149
+ output.write(`Final Cut detected: ${status.editorDetected ? "yes" : "no"}\n`);
150
+ output.write(`Extension: ${status.extensionInstalled ? status.extensionPath : "not installed"}\n`);
151
+ output.write(`Socket: ${status.socketPath}\n`);
109
152
  if (status.identity)
110
- process.stdout.write(`Editor: ${status.identity.name} (${status.identity.backend})\n`);
153
+ output.write(`Editor: ${status.identity.name} (${status.identity.backend})\n`);
111
154
  if (status.lastError)
112
- process.stdout.write(`Reason: ${status.lastError.code}: ${status.lastError.message}\n`);
155
+ output.write(`Reason: ${status.lastError.code}: ${status.lastError.message}\n`);
156
+ }
157
+ function printDevDoctorReport(report, json) {
158
+ if (json) {
159
+ process.stdout.write(`${JSON.stringify(report)}\n`);
160
+ return;
161
+ }
162
+ process.stdout.write(`Framekit development profile ${report.profile}: ${report.ready ? "ready" : "needs attention"}\n`);
163
+ for (const check of report.checks) {
164
+ const status = check.status === "pass" ? "OK" : check.status === "unavailable" ? "OPTIONAL" : "MISSING";
165
+ process.stdout.write(`${status} ${check.name}: ${check.message}\n`);
166
+ }
113
167
  }
114
168
  function printHelp() {
115
169
  process.stdout.write([
@@ -117,14 +171,17 @@ function printHelp() {
117
171
  "",
118
172
  " framekit connect finalcut [--development] [--json]",
119
173
  " framekit doctor finalcut [--json]",
120
- " framekit mcp --editor final-cut-live [--headless]",
174
+ " framekit doctor dev [--profile fixture|headless|native] [--json]",
175
+ " framekit mcp --editor final-cut-live [--headless] [--development]",
121
176
  "",
122
177
  "Codex registration:",
123
178
  " codex mcp add framekit -- framekit mcp --editor final-cut-live --headless",
124
179
  "",
125
180
  ].join("\n"));
126
181
  }
127
- void main().catch((error) => {
128
- process.stderr.write(`${String(error)}\n`);
129
- process.exitCode = 1;
130
- });
182
+ if (process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
183
+ void main().catch((error) => {
184
+ process.stderr.write(`${String(error)}\n`);
185
+ process.exitCode = 1;
186
+ });
187
+ }
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { spawn } from "node:child_process";
4
+ import { access } from "node:fs/promises";
5
+ import { constants } from "node:fs";
6
+
7
+ const backend = process.env.FRAMEKIT_SPEECH_BACKEND?.trim();
8
+ if (!backend) fail(78, "SPEECH_ANALYZER_SETUP_REQUIRED: set FRAMEKIT_SPEECH_BACKEND to one executable Whisper/VAD backend path");
9
+
10
+ try {
11
+ await access(backend, constants.X_OK);
12
+ } catch {
13
+ fail(78, `SPEECH_ANALYZER_SETUP_REQUIRED: speech backend is not executable: ${backend}`);
14
+ }
15
+
16
+ let input = "";
17
+ for await (const chunk of process.stdin) input += chunk;
18
+
19
+ let request;
20
+ try {
21
+ request = JSON.parse(input);
22
+ } catch (error) {
23
+ fail(65, `SPEECH_ANALYZER_REQUEST_INVALID: wrapper received invalid JSON: ${String(error)}`);
24
+ }
25
+
26
+ const child = spawn(backend, [], { stdio: ["pipe", "pipe", "pipe"] });
27
+ const stdout = [];
28
+ const stderr = [];
29
+ child.stdout.on("data", (chunk) => stdout.push(chunk));
30
+ child.stderr.on("data", (chunk) => stderr.push(chunk));
31
+ child.once("error", (error) => {
32
+ fail(78, `SPEECH_ANALYZER_SETUP_REQUIRED: speech backend could not start: ${String(error)}`);
33
+ });
34
+ child.stdin.end(JSON.stringify(request));
35
+
36
+ const exitCode = await new Promise((resolve) => child.once("close", (code) => resolve(code ?? 1)));
37
+ const diagnostic = stderr.length > 0 ? `: ${Buffer.concat(stderr).toString("utf8").trim()}` : "";
38
+ if (exitCode !== 0) fail(78, `SPEECH_ANALYZER_BACKEND_FAILED: backend exited with code ${exitCode}${diagnostic}`);
39
+
40
+ let result;
41
+ try {
42
+ result = JSON.parse(Buffer.concat(stdout).toString("utf8"));
43
+ } catch (error) {
44
+ fail(65, `SPEECH_ANALYZER_BACKEND_INVALID_OUTPUT: backend returned invalid JSON: ${String(error)}`);
45
+ }
46
+ if (!result || typeof result !== "object" || Array.isArray(result)) {
47
+ fail(65, "SPEECH_ANALYZER_BACKEND_INVALID_OUTPUT: backend must return one JSON object");
48
+ }
49
+ process.stdout.write(JSON.stringify(result));
50
+
51
+ function fail(code, message) {
52
+ process.stderr.write(`${message}\n`);
53
+ process.exit(code);
54
+ }