@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
@@ -8,6 +8,7 @@ import { mkdirSync, mkdtempSync, rmSync } from "node:fs"
8
8
  import { join } from "node:path"
9
9
 
10
10
  import { busOf, speechSpans } from "../core/audio.js"
11
+ import { isSceneBlock } from "../core/layout.js"
11
12
  import { wholeSegment } from "../core/plan.js"
12
13
  import { solve } from "../core/solver.js"
13
14
  import { measureLoudness } from "../engine/loudness.js"
@@ -306,7 +307,8 @@ async function qg04(input) {
306
307
  async function qg07({ file, plan, run, thresholds }) {
307
308
  const health = readHealth(await run("ffmpeg", healthArgs(file), { timeoutMs: 600_000 }))
308
309
  const picture = wholeSegment(plan).node.picture.sort((a, b) => a.at - b.at)
309
- const holds = picture.filter((p) => p.hold).map(({ at, end }) => ({ at, end }))
310
+ // A freeze the plan asks for; and a scene may rest on a finished diagram while the voice explains it
311
+ const holds = [...picture.filter((p) => p.hold), ...plan.tiles.filter((tile) => isSceneBlock(tile.node))].map(({ at, end }) => ({ at, end }))
310
312
  const cuts = picture.slice(1).map((p, i) => ({ t: p.at, same: p.asset === picture[i].asset && !p.hold && !picture[i].hold }))
311
313
  return outcome("QG-07", judgeHealth(health, { duration: plan.duration, fps: plan.output.fps, holds, cuts }, thresholds))
312
314
  }
@@ -324,10 +326,16 @@ async function qg10({ plan, run, thresholds, tilePath, binDir, work }) {
324
326
  try {
325
327
  // Each tile at rest, over mid grey, as the reader sees it
326
328
  for (const [i, tile] of tiles.entries()) {
327
- const at = Math.min(((tile.end - tile.at) / FLICKS) * 0.9, tile.kind === "caption" ? 0.4 : 1)
328
- await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-ss", at.toFixed(3), "-i", tilePath(tile.key), "-f", "lavfi", "-i", `color=c=0x808080:s=${plan.output.width}x${plan.output.height}`, "-filter_complex", "[1:v][0:v]overlay=shortest=1", "-frames:v", "1", "-y", join(dir, `t${String(i).padStart(4, "0")}.png`)], { timeoutMs: 60_000 })
329
+ const length = (tile.end - tile.at) / FLICKS
330
+ // A scene's labels come in as they're said, so it's read when they're all in, before it fades
331
+ const at = isSceneBlock(tile.node) ? Math.max(0, length - 0.5) : Math.min(length * 0.9, tile.kind === "caption" ? 0.4 : 1)
332
+ // The tile from zero: a seek rounded to just before a frame made the overlay's first output plain grey, an empty read (found on real footage)
333
+ await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-ss", at.toFixed(3), "-i", tilePath(tile.key), "-f", "lavfi", "-i", `color=c=0x808080:s=${plan.output.width}x${plan.output.height}`, "-filter_complex", "[0:v]setpts=PTS-STARTPTS[tile];[1:v][tile]overlay=shortest=1", "-frames:v", "1", "-y", join(dir, `t${String(i).padStart(4, "0")}.png`)], { timeoutMs: 60_000 })
329
334
  }
330
- const seen = readOcr(await run(helper.path, [dir], { timeoutMs: 300_000 }))
335
+ let seen = readOcr(await run(helper.path, [dir], { timeoutMs: 300_000 }))
336
+ // The reader swallows its own errors: every tile blank at once is the reader, not the screen (found under load).
337
+ // One more read; a render that's really blank still fails
338
+ if (tiles.length > 1 && tiles.every((_, i) => !seen.get(`t${String(i).padStart(4, "0")}.png`)?.text)) seen = readOcr(await run(helper.path, [dir], { timeoutMs: 300_000 }))
331
339
  const judged = judgeCopy(tiles.map((tile, i) => {
332
340
  const read = seen.get(`t${String(i).padStart(4, "0")}.png`)
333
341
  return { tile, seen: read?.text ?? "", unsure: read?.unsure ?? [] }
@@ -121,6 +121,11 @@ export function judgeMotion(tiles, { minMotion }) {
121
121
  // The entrance: how far the first second moves from the first frame
122
122
  let moved = 0
123
123
  for (let i = 1; i < Math.min(frames.length, 30); i++) moved = Math.max(moved, meanDiff(frames[0], frames[i]))
124
+ // Against the text's own share of the frame, so a two-word page that springs in isn't called still
125
+ // (found on real footage: 0.48 for a small caption). A tile that doesn't move still scores 0
126
+ const last = frames[Math.min(frames.length, 30) - 1]
127
+ const covered = last ? last.reduce((sum, a) => sum + (a > 0 ? 1 : 0), 0) / last.length : 1
128
+ if (covered > 0 && covered < 0.25) moved *= 0.25 / covered
124
129
  if (moved < minMotion) {
125
130
  still++
126
131
  failures.push({ kind: "no_motion", t: tile.at, change: round(moved, 2), needed: minMotion })
@@ -7,7 +7,7 @@ import { join } from "node:path"
7
7
 
8
8
  import { outputFaces } from "../core/faces.js"
9
9
  import { segmentArgs } from "../core/ffmpeg.js"
10
- import { safeZoneFor } from "../core/layout.js"
10
+ import { isSceneBlock, safeZoneFor } from "../core/layout.js"
11
11
  import { wholeSegment } from "../core/plan.js"
12
12
  import { captionComposition, READING_LIMITS, scriptOf } from "../engine/captions.js"
13
13
  import { compositionFor, measureText } from "../engine/motion.js"
@@ -15,6 +15,7 @@ import { compositionFor, measureText } from "../engine/motion.js"
15
15
  const FLICKS = 705_600_000
16
16
  const SETTLE_MS = { caption: 350, block: 950 } // the entrances' lengths, so a beat sees text at rest
17
17
 
18
+ const MIN_PAGE_SECONDS = 1.2
18
19
  const overlaps = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
19
20
  const frameMs = (fps) => (1000 * fps.d) / fps.n
20
21
  const rounded = (box) => ({ x: Math.round(box.x), y: Math.round(box.y), w: Math.round(box.w), h: Math.round(box.h) })
@@ -85,7 +86,10 @@ export function judgeLayout({ plan, project, index, measured }) {
85
86
  if (box.clipped) fail("clipped", item)
86
87
  // Behind-the-speaker text may cross the face: the matte draws the speaker over it
87
88
  const behind = item.tile.node.behind === true && !item.tile.front
88
- if (!behind) {
89
+ // A scene covers the frame while it's on: no face is in the picture under its text or its captions
90
+ // Other footage laid over the whole frame hides it the same way
91
+ const covered = plan.tiles.some((tile) => isSceneBlock(tile.node) && tile.at <= item.t && item.t < tile.end) || wholeSegment(plan).node.overlays.some((o) => o.at <= item.t && item.t < o.end)
92
+ if (!behind && !covered) {
89
93
  const face = faces.find((f) => Math.abs(f.t - item.t) <= FLICKS * 0.6 && overlaps(box, f.box))
90
94
  if (face) fail("on_face", item, { face: face.box })
91
95
  }
@@ -142,6 +146,14 @@ export function boxContrast(rgb, width, height, box, { colours, plate }, share =
142
146
  return values.length ? values[Math.floor(values.length * share)] : null
143
147
  }
144
148
 
149
+ /** The contrast of text against its own outline, when the outline is thick enough to read as one; else null. */
150
+ export function strokeContrast({ colours, stroke, strokeWidth, size }) {
151
+ const edge = parseColour(stroke)
152
+ if (!edge || !(strokeWidth >= Math.max(2, (size ?? 0) * 0.05))) return null
153
+ const texts = (colours ?? []).map(parseColour).filter(Boolean).map((c) => luminance(c.rgb))
154
+ return texts.length ? Math.min(...texts.map((t) => contrast(t, luminance(edge.rgb)))) : null
155
+ }
156
+
145
157
  /** Raw RGB frames of the plan, without the tiles `without` names, at frame numbers. */
146
158
  async function stills(plan, frames, { inputPath, tilePath, run, without }) {
147
159
  const { width, height } = plan.output
@@ -176,7 +188,10 @@ export async function judgeLegibility({ plan, measured, inputPath, tilePath, run
176
188
  const pictures = await stills(plan, frames, { inputPath, tilePath, run, without })
177
189
  if (pictures.length !== frames.length) throw new Error("the frames behind the text couldn't be read")
178
190
  for (const item of own) {
179
- const value = boxContrast(pictures[frames.indexOf(frameOf(item.t))], width, height, item.box, item.box)
191
+ const seen = boxContrast(pictures[frames.indexOf(frameOf(item.t))], width, height, item.box, item.box)
192
+ // A real outline separates text from any picture: it counts as what's behind the text (found on real footage)
193
+ const outline = strokeContrast(item.box)
194
+ const value = seen === null ? null : Math.max(seen, outline ?? 0)
180
195
  if (value === null) continue
181
196
  worst = Math.min(worst, value)
182
197
  if (value < thresholds.contrast) fail("low_contrast", item, { contrast: Math.round(value * 100) / 100, needed: thresholds.contrast })
@@ -189,7 +204,8 @@ export async function judgeLegibility({ plan, measured, inputPath, tilePath, run
189
204
  const words = item.tile.node.words.length
190
205
  const script = scriptOf(item.tile.node.text)
191
206
  const rate = words / Math.max(seconds, 1e-3)
192
- if (rate > READING_LIMITS[script]) fail("too_fast", item, { wordsPerSecond: Math.round(rate * 100) / 100, limit: READING_LIMITS[script], script })
207
+ // Captions show what's said, so a fast speaker's page can't be slower than the speech. What a reader can't take is a page that flashes by
208
+ if (rate > READING_LIMITS[script] && seconds < MIN_PAGE_SECONDS) fail("too_fast", item, { wordsPerSecond: Math.round(rate * 100) / 100, limit: READING_LIMITS[script], script })
193
209
  }
194
210
  const numbers = { texts: items.length, worstContrast: worst === Infinity ? null : Math.round(worst * 100) / 100, needed: thresholds.contrast, failures: failures.length }
195
211
  return { status: failures.length ? "failed" : "passed", numbers, failures }
@@ -5,7 +5,7 @@
5
5
 
6
6
  import { availableParallelism } from "node:os"
7
7
 
8
- export const DEFAULT_SLOTS = { cpu: Math.max(2, availableParallelism() - 2), gpu: 1, encoder: 2, chrome: 1, model: 2, disk: 2 }
8
+ export const DEFAULT_SLOTS = { cpu: Math.max(2, availableParallelism() - 2), gpu: 1, encoder: 2, chrome: Math.min(3, Math.max(1, Math.floor(availableParallelism() / 3))), model: 2, disk: 2 }
9
9
 
10
10
  export function createScheduler(slots = DEFAULT_SLOTS) {
11
11
  const held = new Map()
@@ -7,7 +7,7 @@ import { request } from "node:http"
7
7
  import { join } from "node:path"
8
8
 
9
9
  import { kriyaHome } from "../../paths.js"
10
- import { editHome, logPath, socketPath } from "./paths.js"
10
+ import { codeStamp, editHome, logPath, socketPath } from "./paths.js"
11
11
 
12
12
  const START_MS = 15_000
13
13
 
@@ -33,10 +33,34 @@ export function hostCall(home, method, path, body) {
33
33
 
34
34
  const contact = (home) => hostCall(home, "GET", "/internal/info").catch(() => null)
35
35
 
36
- /** The running Host, started if need be. @returns {Promise<{ pid: number, port: number }>} */
37
- export async function ensureHost({ env = process.env, home = kriyaHome() } = {}) {
36
+ const gone = async (pid) => {
37
+ for (let i = 0; i < 100; i++) {
38
+ try {
39
+ process.kill(pid, 0)
40
+ } catch {
41
+ return
42
+ }
43
+ await new Promise((done) => setTimeout(done, 50))
44
+ }
45
+ }
46
+
47
+ /** Jobs a Host is running; an old Host doesn't report it, so its job list is asked. */
48
+ const activeOf = async (home, live) =>
49
+ live.busy ?? (await hostCall(home, "GET", "/jobs").then(({ jobs }) => jobs.filter((j) => ["pending", "running"].includes(j.status)).length).catch(() => 1))
50
+
51
+ /**
52
+ * The running Host, started if need be. A Host running older code than this one is
53
+ * stopped and replaced, unless it's in the middle of work: then it's left to finish.
54
+ * @returns {Promise<{ pid: number, port: number }>}
55
+ */
56
+ export async function ensureHost({ env = process.env, home = kriyaHome(), stamp = codeStamp() } = {}) {
38
57
  const live = await contact(home)
39
- if (live) return live
58
+ if (live && live.stamp === stamp) return live
59
+ if (live) {
60
+ if (await activeOf(home, live)) return live
61
+ await stopHost(home)
62
+ await gone(live.pid)
63
+ }
40
64
  mkdirSync(editHome(home), { recursive: true })
41
65
  const log = openSync(logPath(home), "a")
42
66
  const main = join(import.meta.dirname, "main.js")
@@ -64,7 +64,14 @@ export async function writeDelivery({ file, title, project, parent, plan, source
64
64
  const rights = project.assets.filter((a) => used.has(a.id)).map((a) => ({ id: a.id, rights: a.rights, role: a.role }))
65
65
  const report = reportPath(file)
66
66
  writeFileSync(report, reportHtml({ receipt, title, before, after, changes, notes, rights, repairs }))
67
- return { receipt: receiptFile, report, verdict: receipt.verdict }
67
+ // What the viewer's description must carry (CC BY asks for it): who made what was borrowed, and what's quoted
68
+ const credits = [...project.assets.filter((a) => used.has(a.id) && a.rights !== "own" && a.rightsNote && a.kind !== "reference").map((a) => a.rightsNote), ...plan.tiles.filter((t) => t.node.blockId === "term").map((t) => `"${t.node.variables.quote}" ${t.node.variables.source}${t.node.variables.page ? `, ${t.node.variables.page}` : ""}`)]
69
+ let creditsFile = null
70
+ if (credits.length) {
71
+ creditsFile = `${file}.credits.txt`
72
+ writeFileSync(creditsFile, `${[...new Set(credits)].join("\n")}\n`)
73
+ }
74
+ return { receipt: receiptFile, report, verdict: receipt.verdict, ...(creditsFile ? { credits: creditsFile } : {}) }
68
75
  }
69
76
 
70
77
  /**
@@ -1,6 +1,9 @@
1
1
  // The Host owns jobs (EDD-03): each lives in its project's journal, so a job in
2
2
  // progress when the Host dies resumes on the next start with no finished node redone.
3
3
 
4
+ import { existsSync } from "node:fs"
5
+ import { basename, dirname, join, resolve } from "node:path"
6
+
4
7
  import { projectAt } from "../core/history.js"
5
8
 
6
9
  // A render is of the version it was asked for, not whatever the project has become by
@@ -62,6 +65,8 @@ export function createJobs({ projects, emit, log, onDispatch, beforeStory }) {
62
65
 
63
66
  return {
64
67
  count: () => running.size,
68
+ /** Whether a project has a job running now. */
69
+ runningIn: (project) => [...running.keys()].some((id) => id.startsWith(`${project}.`)),
65
70
 
66
71
  start(state, request) {
67
72
  const number = state.journal.addJob({ kind: request.kind ?? "render", projectVersion: state.log.head, request })
@@ -69,6 +74,44 @@ export function createJobs({ projects, emit, log, onDispatch, beforeStory }) {
69
74
  return view(state, state.journal.job(number))
70
75
  },
71
76
 
77
+ /**
78
+ * The project's finished films, newest first: renders, and the masters makes and revisions
79
+ * wrote. Only files in its exports folder that still exist; `current` says whether the film
80
+ * shows the project as it is now (a render is of the version it was asked for).
81
+ */
82
+ renders(state) {
83
+ const exportsDir = resolve(join(state.folder, "exports"))
84
+ const out = []
85
+ for (const row of state.journal.jobs("done")) {
86
+ let file = null
87
+ let version = null
88
+ let quality = "master"
89
+ let verdict = null
90
+ if (row.kind === "render") {
91
+ file = row.dispatch
92
+ version = row.project_version
93
+ try {
94
+ quality = JSON.parse(row.request ?? "{}").quality ?? "draft"
95
+ } catch {}
96
+ } else if (row.kind === "make" || row.kind === "revise") {
97
+ try {
98
+ const done = JSON.parse(row.dispatch ?? "{}")
99
+ ;({ file = null, head: version = null, verdict = null } = done)
100
+ } catch {}
101
+ } else continue
102
+ if (typeof file !== "string" || dirname(resolve(file)) !== exportsDir || !existsSync(file)) continue
103
+ out.push({ job: row.id, kind: row.kind, quality, name: basename(file), verdict, current: version !== null && version === state.log.head, at: row.finished_at })
104
+ }
105
+ // The Engine names a film by what it shows, so two jobs can share a file: listed once, newest
106
+ const seen = new Set()
107
+ return out.reverse().filter((r) => !seen.has(r.name) && seen.add(r.name))
108
+ },
109
+ /** A finished film's path, only through renders(): never a path the browser names. */
110
+ renderFile(state, number) {
111
+ const found = this.renders(state).find((r) => r.job === number)
112
+ return found ? join(state.folder, "exports", found.name) : null
113
+ },
114
+
72
115
  async list() {
73
116
  const jobs = []
74
117
  await projects.each((state) => {
@@ -12,7 +12,7 @@ import { createScheduler, DEFAULT_SLOTS } from "../graph/scheduler.js"
12
12
  import { createGovernor } from "../loop/governor.js"
13
13
  import { kriyaHome } from "../../paths.js"
14
14
  import { createJobs } from "./jobs.js"
15
- import { editHome, lockPath, portPath, socketPath } from "./paths.js"
15
+ import { codeStamp, editHome, lockPath, portPath, socketPath } from "./paths.js"
16
16
  import { createProjects } from "./projects.js"
17
17
  import { createHandler } from "./server.js"
18
18
  import { createTavi } from "./tavi.js"
@@ -76,7 +76,9 @@ const watcher = createWatcher({ home, send: tavi.post, log })
76
76
  let lastActive = Date.now()
77
77
  let inFlight = 0 // a request still running isn't idle, however long it takes
78
78
  let port = 0
79
- const handle = createHandler({ home, roots, projects, jobs, tavi, tools: readTools, tokenTtlMs, port: () => port, onActivity: (change = 0) => ((inFlight += change), (lastActive = Date.now())), onStop: () => shutdown(), onLive: () => (liveAt = Date.now()), sse, log, pid: process.pid })
79
+ // What code this process runs, so an outdated Host is replaced once it's idle (client.js)
80
+ const stamp = codeStamp()
81
+ const handle = createHandler({ home, roots, projects, jobs, tavi, tools: readTools, tokenTtlMs, port: () => port, stamp, busy: () => jobs.count() + tavi.pending(), onActivity: (change = 0) => ((inFlight += change), (lastActive = Date.now())), onStop: () => shutdown(), onLive: () => (liveAt = Date.now()), sse, log, pid: process.pid })
80
82
  const web = createServer((req, res) => handle(req, res, false))
81
83
  const local = createServer((req, res) => handle(req, res, true))
82
84
 
@@ -1,5 +1,7 @@
1
1
  // Where the Host keeps things (ARCHITECTURE §5): never in a synced folder (EF-28).
2
2
 
3
+ import { createHash } from "node:crypto"
4
+ import { readdirSync, statSync } from "node:fs"
3
5
  import { join } from "node:path"
4
6
 
5
7
  import { kriyaHome } from "../../paths.js"
@@ -9,3 +11,26 @@ export const socketPath = (home) => join(editHome(home), "host.sock")
9
11
  export const lockPath = (home) => join(editHome(home), "host.lock")
10
12
  export const portPath = (home) => join(editHome(home), "port")
11
13
  export const logPath = (home) => join(editHome(home), "host.log")
14
+
15
+ const SRC = join(import.meta.dirname, "..", "..")
16
+
17
+ /**
18
+ * A fingerprint of the code a Host runs: every source file's name, size and time. A
19
+ * running Host keeps the code it started with, so after an update the Studio looked new
20
+ * (its files are read per request) while the Host ran the old Director (found 2026-11-09).
21
+ */
22
+ export function codeStamp(root = SRC) {
23
+ const hash = createHash("sha256")
24
+ const walk = (dir) => {
25
+ for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
26
+ const path = join(dir, entry.name)
27
+ if (entry.isDirectory()) walk(path)
28
+ else if (/\.(js|swift)$/.test(entry.name)) {
29
+ const { size, mtimeMs } = statSync(path)
30
+ hash.update(`${path.slice(root.length)}:${size}:${mtimeMs}\n`)
31
+ }
32
+ }
33
+ }
34
+ walk(root)
35
+ return hash.digest("hex").slice(0, 16)
36
+ }