@kriya-ai/harness 0.2.2 → 0.2.4

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 (45) hide show
  1. package/contract/SOURCE.md +3 -3
  2. package/contract/contract.json +188 -0
  3. package/package.json +1 -1
  4. package/src/edit/core/ffmpeg.js +5 -1
  5. package/src/edit/core/layout.js +26 -1
  6. package/src/edit/core/ops.js +74 -6
  7. package/src/edit/core/plan.js +2 -1
  8. package/src/edit/core/project.js +6 -1
  9. package/src/edit/core/solver.js +66 -15
  10. package/src/edit/director/ask.js +42 -27
  11. package/src/edit/director/beats.js +335 -0
  12. package/src/edit/director/lookups.js +133 -0
  13. package/src/edit/director/plan.js +365 -0
  14. package/src/edit/director/playbooks.js +131 -0
  15. package/src/edit/director/revise.js +171 -12
  16. package/src/edit/engine/captions.js +32 -0
  17. package/src/edit/engine/found-media.js +64 -0
  18. package/src/edit/engine/motion.js +78 -18
  19. package/src/edit/engine/music-bed.js +110 -0
  20. package/src/edit/engine/reference.js +134 -0
  21. package/src/edit/engine/scenes.js +480 -0
  22. package/src/edit/engine/sfx.js +63 -0
  23. package/src/edit/gates/copy.js +25 -5
  24. package/src/edit/gates/index.js +12 -4
  25. package/src/edit/gates/picture.js +5 -0
  26. package/src/edit/gates/text.js +20 -4
  27. package/src/edit/graph/scheduler.js +1 -1
  28. package/src/edit/host/client.js +28 -4
  29. package/src/edit/host/deliver.js +8 -1
  30. package/src/edit/host/jobs.js +43 -0
  31. package/src/edit/host/main.js +4 -2
  32. package/src/edit/host/paths.js +25 -0
  33. package/src/edit/host/projects.js +328 -38
  34. package/src/edit/host/server.js +106 -8
  35. package/src/edit/index/db.js +5 -0
  36. package/src/edit/index/layers/retakes.js +7 -1
  37. package/src/edit/index/views.js +9 -0
  38. package/src/edit/loop/make.js +9 -6
  39. package/src/edit/recipes/montage.js +74 -0
  40. package/src/edit/recipes/programme.js +24 -0
  41. package/src/edit/recipes/reel.js +149 -20
  42. package/src/edit/recipes/scene-clips.js +127 -0
  43. package/src/edit/runtime/fetch.js +32 -0
  44. package/studio/dist/studio.css +62 -4
  45. package/studio/dist/studio.js +4 -2
@@ -0,0 +1,110 @@
1
+ // A music bed made by code (2026-11-09): chords, bass and a light beat, written sample by
2
+ // sample to a WAV. Nobody else's recording is in it, so it carries no licence question,
3
+ // and the same mood and length always give the same file. It goes through the ED9 path
4
+ // like any song: its beats are indexed, it's fitted on downbeats and ducked under speech.
5
+
6
+ import { writeFileSync } from "node:fs"
7
+
8
+ const RATE = 48_000
9
+
10
+ /** Moods: tempo, chords (MIDI notes), and how much beat. Data only. */
11
+ export const MOODS = {
12
+ calm: { bpm: 80, chords: [[57, 60, 64], [53, 57, 60], [48, 52, 55], [55, 59, 62]], kick: 0, hat: 0, pulse: 0.15 },
13
+ upbeat: { bpm: 112, chords: [[57, 60, 64], [53, 57, 60], [48, 52, 55], [55, 59, 62]], kick: 0.55, hat: 0.12, pulse: 0.35 },
14
+ warm: { bpm: 92, chords: [[48, 52, 55, 59], [45, 48, 52, 55], [53, 57, 60, 64], [55, 59, 62, 65]], kick: 0.3, hat: 0.06, pulse: 0.25 },
15
+ }
16
+
17
+ const hz = (note) => 440 * 2 ** ((note - 69) / 12)
18
+
19
+ /**
20
+ * Writes a stereo 16-bit WAV of `seconds` (plus a short tail) for `mood`.
21
+ * @returns {{ file: string, seconds: number, bpm: number }}
22
+ */
23
+ export function writeMusicBed(file, { mood = "calm", seconds = 60, bpm } = {}) {
24
+ // A music reference's tempo can set the bed's (classified by analyseReference)
25
+ const spec = { ...(MOODS[mood] ?? MOODS.calm), ...(bpm >= 60 && bpm <= 180 ? { bpm: Math.round(bpm) } : {}) }
26
+ const total = Math.ceil((Math.max(5, seconds) + 2) * RATE)
27
+ const beat = (60 / spec.bpm) * RATE // samples a beat
28
+ const bar = beat * 4
29
+ const chordLength = bar * 2 // each chord holds two bars
30
+ const left = new Float32Array(total)
31
+ const right = new Float32Array(total)
32
+ let seed = 0x9e3779b9
33
+ const noise = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 2 ** 32) * 2 - 1
34
+ let lastNoise = 0
35
+ for (let i = 0; i < total; i++) {
36
+ const t = i / RATE
37
+ const c = Math.floor(i / chordLength) % spec.chords.length
38
+ const inChord = (i % chordLength) / chordLength
39
+ // A soft swell into each chord and out of it, so changes never click
40
+ const swell = Math.min(1, inChord * 12) * Math.min(1, (1 - inChord) * 12)
41
+ let l = 0
42
+ let r = 0
43
+ for (const note of spec.chords[c]) {
44
+ const f = hz(note)
45
+ // Two slightly detuned voices per note: one leans left, one right
46
+ const a = Math.sin(2 * Math.PI * f * 0.998 * t) + 0.3 * Math.sin(2 * Math.PI * f * 2 * t)
47
+ const b = Math.sin(2 * Math.PI * f * 1.002 * t) + 0.25 * Math.sin(2 * Math.PI * f * 3 * t)
48
+ l += a
49
+ r += b
50
+ }
51
+ const pad = (0.1 * swell) / spec.chords[c].length
52
+ l *= pad
53
+ r *= pad
54
+ // Bass: the chord's root an octave down, pulsing on the beat
55
+ const inBeat = (i % beat) / beat
56
+ const bass = Math.sin(2 * Math.PI * hz(spec.chords[c][0] - 12) * t) * (1 - spec.pulse * inBeat) * 0.12 * swell
57
+ l += bass
58
+ r += bass
59
+ // Kick on every beat: a falling sine with a fast decay
60
+ if (spec.kick) {
61
+ const k = (i % beat) / RATE
62
+ const kick = Math.sin(2 * Math.PI * (50 + 70 * Math.exp(-k * 30)) * k) * Math.exp(-k * 18) * spec.kick
63
+ l += kick
64
+ r += kick
65
+ }
66
+ // A closed hat on the off-beat: high-passed noise, very short
67
+ if (spec.hat) {
68
+ const off = ((i + beat / 2) % beat) / RATE
69
+ const white = noise()
70
+ const bright = white - lastNoise
71
+ lastNoise = white
72
+ const hat = bright * Math.exp(-off * 90) * spec.hat
73
+ l += hat * 0.9
74
+ r += hat
75
+ }
76
+ // Fade in over 1.5 s, out over the last 2 s
77
+ const fade = Math.min(1, t / 1.5) * Math.min(1, (total - i) / (2 * RATE))
78
+ left[i] = l * fade
79
+ right[i] = r * fade
80
+ }
81
+ writeWav(file, left, right)
82
+ return { file, seconds: total / RATE, bpm: spec.bpm }
83
+ }
84
+
85
+ /** A stereo 16-bit WAV at 48 kHz, peaking at about -6 dBFS (the mix sets the level). */
86
+ export function writeWav(file, left, right) {
87
+ const total = left.length
88
+ let peak = 0
89
+ for (let i = 0; i < total; i++) peak = Math.max(peak, Math.abs(left[i]), Math.abs(right[i]))
90
+ const scale = peak ? 0.5 / peak : 0
91
+ const data = Buffer.alloc(total * 4)
92
+ for (let i = 0; i < total; i++) {
93
+ data.writeInt16LE(Math.round(left[i] * scale * 32767), i * 4)
94
+ data.writeInt16LE(Math.round(right[i] * scale * 32767), i * 4 + 2)
95
+ }
96
+ const head = Buffer.alloc(44)
97
+ head.write("RIFF", 0)
98
+ head.writeUInt32LE(36 + data.length, 4)
99
+ head.write("WAVEfmt ", 8)
100
+ head.writeUInt32LE(16, 16)
101
+ head.writeUInt16LE(1, 20)
102
+ head.writeUInt16LE(2, 22)
103
+ head.writeUInt32LE(RATE, 24)
104
+ head.writeUInt32LE(RATE * 4, 28)
105
+ head.writeUInt16LE(4, 32)
106
+ head.writeUInt16LE(16, 34)
107
+ head.write("data", 36)
108
+ head.writeUInt32LE(data.length, 40)
109
+ writeFileSync(file, Buffer.concat([head, data]))
110
+ }
@@ -0,0 +1,134 @@
1
+ // References, classified (2026-11-09): a video gives its editing pace and captions (Edit
2
+ // DNA) and its colour; an image gives its colour grade; a piece of music gives its tempo and
3
+ // energy. Every value is a number or a fixed word, never a pixel, sound or word of the
4
+ // reference (EDD-23), and each turns into something the cut can really do.
5
+
6
+ import { extractDna } from "./dna.js"
7
+ import { measureLoudness } from "./loudness.js"
8
+ import { runTool } from "./tool.js"
9
+ import { analyseMusic, musicArgs, pcmCollector } from "../index/layers/music.js"
10
+
11
+ const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v))
12
+ const round = (v, places = 2) => Math.round(v * 10 ** places) / 10 ** places
13
+
14
+ /** Averages of FFmpeg's signalstats over sampled frames (a frame every 2 s, the first 90 s). */
15
+ export async function colourStats(file, { image = false, run = runTool, signal } = {}) {
16
+ const vf = `${image ? "" : "fps=1/2,"}scale=160:-2,signalstats,metadata=print:file=-`
17
+ const text = await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-protocol_whitelist", "file,pipe", ...(image ? [] : ["-t", "90"]), "-i", file, "-vf", vf, "-an", "-f", "null", "-"], { signal, timeoutMs: 180_000 })
18
+ const sums = {}
19
+ const counts = {}
20
+ for (const m of text.matchAll(/lavfi\.signalstats\.(YAVG|UAVG|VAVG|SATAVG|YLOW|YHIGH)=([\d.]+)/g)) {
21
+ sums[m[1]] = (sums[m[1]] ?? 0) + Number(m[2])
22
+ counts[m[1]] = (counts[m[1]] ?? 0) + 1
23
+ }
24
+ if (!counts.YAVG) return null
25
+ return Object.fromEntries(Object.keys(sums).map((key) => [key, sums[key] / counts[key]]))
26
+ }
27
+
28
+ /**
29
+ * The grade that moves a picture toward a reference's colour, and the words for it.
30
+ * shortcut: a fixed mapping from 8-bit averages, approximate by design; a measured match
31
+ * against the person's own footage (colour.js) is the precise path, for a later phase
32
+ */
33
+ export function gradeFromStats(stats) {
34
+ const warmth = stats.VAVG - stats.UAVG // above 0 leans red and orange, below leans blue
35
+ const grade = {
36
+ // Kept within a tasteful range: a reference leans the cut, it doesn't overpower it
37
+ temperature: Math.round(clamp(6500 - warmth * 60, 4200, 9000) / 100) * 100,
38
+ saturation: round(clamp(stats.SATAVG / 32, 0.75, 1.3)),
39
+ gain: round(clamp((stats.YHIGH - stats.YLOW) / 190, 0.9, 1.2)),
40
+ lift: round(clamp((stats.YAVG - 115) / 700, -0.05, 0.05), 3),
41
+ }
42
+ const words = [warmth > 4 ? "warm" : warmth < -4 ? "cool" : "neutral", grade.saturation > 1.15 ? "saturated" : grade.saturation < 0.85 ? "muted" : "natural colour", grade.gain > 1.08 ? "contrasty" : grade.gain < 0.93 ? "soft contrast" : "even contrast", stats.YAVG > 140 ? "bright" : stats.YAVG < 85 ? "dark" : "mid brightness"]
43
+ return { grade, words }
44
+ }
45
+
46
+ /** Tempo and energy of music: the bed's mood and tempo follow it. */
47
+ export async function musicOf(file, { run = runTool, signal } = {}) {
48
+ const pcm = pcmCollector()
49
+ // The first minute is enough to hear a tempo
50
+ await run("ffmpeg", [...musicArgs(file).slice(0, -1), "-t", "60", "pipe:1"], { onStdout: pcm.add, signal, timeoutMs: 180_000 })
51
+ const { bpm } = analyseMusic(pcm.finish())
52
+ const { integrated } = await measureLoudness(file, { run, signal })
53
+ const mood = bpm === null ? (integrated !== null && integrated > -14 ? "upbeat" : "calm") : bpm >= 104 ? "upbeat" : bpm <= 86 ? "calm" : "warm"
54
+ return { bpm: bpm === null ? null : Math.round(bpm), lufs: integrated === null ? null : round(integrated, 1), mood }
55
+ }
56
+
57
+ /**
58
+ * @param {string} file
59
+ * @param {{ width?: number, duration?: number, hasAudio?: boolean }} facts from probe
60
+ * @returns {Promise<{ kind: "video" | "image" | "audio", colour?: object, pace?: object, captions?: boolean, music?: object, lines: string[] }>}
61
+ */
62
+ export async function analyseReference(file, facts, { run = runTool, signal } = {}) {
63
+ const kind = facts.width ? (facts.duration ? "video" : "image") : "audio"
64
+ // `parts`: each line under the aspect it informs, so a reference taken for one aspect gives only that
65
+ const out = { kind, lines: [], parts: {} }
66
+ const line = (aspect, text) => (out.lines.push(text), (out.parts[aspect] = text))
67
+ if (kind !== "audio") {
68
+ const stats = await colourStats(file, { image: kind === "image", run, signal })
69
+ if (stats) {
70
+ out.colour = gradeFromStats(stats)
71
+ line("colour", `Colour: ${out.colour.words.join(", ")}`)
72
+ }
73
+ }
74
+ if (kind === "video") {
75
+ const dna = await extractDna(file, { run, signal }).catch(() => null)
76
+ if (dna?.pace?.median) {
77
+ out.pace = { every: dna.pace.median, shots: dna.pace.shots }
78
+ line("editing", `Pace: the picture changes every ${dna.pace.median.toFixed(1)} s (${dna.pace.shots} shots)`)
79
+ }
80
+ if (dna) {
81
+ out.captions = !!dna.captions?.present
82
+ line("graphics", out.captions ? "Captions: yes, on screen" : "Captions: none")
83
+ }
84
+ }
85
+ // A video's soundtrack is measured too: it's what a reference taken for its sound gives
86
+ if (kind === "audio" || (kind === "video" && facts.hasAudio)) {
87
+ out.music = await musicOf(file, { run, signal }).catch(() => null)
88
+ if (out.music) line("sound", `Music: ${out.music.bpm ? `${out.music.bpm} bpm, ` : ""}${out.music.mood}${out.music.lufs !== null ? `, ${out.music.lufs} LUFS` : ""}`)
89
+ }
90
+ return out
91
+ }
92
+
93
+ /** What a reference can be taken for: the person picks one per reference, or all of it. */
94
+ export const ASPECTS = {
95
+ all: "Everything it shows",
96
+ editing: "Editing: cuts and pace",
97
+ sound: "Sound: music and feel",
98
+ colour: "Colour grade",
99
+ graphics: "Graphics: captions and text",
100
+ }
101
+
102
+ /** References as the person sent them: ids, or { id, aspect }; anything else dropped. At most six. */
103
+ export function cleanRefs(list) {
104
+ if (!Array.isArray(list)) return []
105
+ const safe = (v) => typeof v === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(v)
106
+ const out = []
107
+ for (const item of list) {
108
+ const ref = safe(item) ? { id: item, aspect: "all" } : item && safe(item.id) ? { id: item.id, aspect: Object.hasOwn(ASPECTS, item.aspect) ? item.aspect : "all" } : null
109
+ if (ref && !out.some((r) => r.id === ref.id)) out.push(ref)
110
+ }
111
+ return out.slice(0, 6)
112
+ }
113
+
114
+ /**
115
+ * Only what the reference was taken for. "all" keeps the earlier rule for a video's sound: used
116
+ * only when it has no cuts to read, since a cut video's soundtrack is usually speech.
117
+ */
118
+ export function takeFrom(found, aspect = "all") {
119
+ const wants = (a) => aspect === "all" || aspect === a
120
+ const parts = found.parts ?? {}
121
+ const out = { kind: found.kind, lines: [] }
122
+ const keep = (a, key) => {
123
+ if (!wants(a) || found[key] === undefined || found[key] === null) return
124
+ out[key] = found[key]
125
+ if (parts[a]) out.lines.push(parts[a])
126
+ }
127
+ keep("colour", "colour")
128
+ keep("editing", "pace")
129
+ keep("graphics", "captions")
130
+ if (aspect === "sound" || (aspect === "all" && !(found.kind === "video" && found.pace))) keep("sound", "music")
131
+ // An analysis kept from before `parts` existed: its lines, for everything
132
+ if (!found.parts && aspect === "all") out.lines = [...(found.lines ?? [])]
133
+ return out
134
+ }