@kriya-ai/harness 0.0.0-stage → 0.2.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 (185) hide show
  1. package/README.md +379 -2
  2. package/SAFETY.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +7911 -0
  4. package/bin/kriya.js +577 -0
  5. package/bundle/cordis.patch.yml +397 -0
  6. package/contract/SOURCE.md +15 -0
  7. package/contract/contract.json +1355 -0
  8. package/package.json +57 -4
  9. package/plugins/anchor/index.js +56 -0
  10. package/plugins/anchor/package.json +13 -0
  11. package/plugins/approvals/index.js +183 -0
  12. package/plugins/approvals/package.json +13 -0
  13. package/plugins/brand/DESIGN.md +112 -0
  14. package/plugins/brand/client.js +826 -0
  15. package/plugins/brand/index.js +15 -0
  16. package/plugins/brand/package.json +25 -0
  17. package/plugins/brand/src/client.js +823 -0
  18. package/plugins/browser/index.js +218 -0
  19. package/plugins/browser/package.json +13 -0
  20. package/plugins/budget/index.js +108 -0
  21. package/plugins/budget/package.json +13 -0
  22. package/plugins/changes/client.js +245 -0
  23. package/plugins/changes/index.js +75 -0
  24. package/plugins/changes/package.json +22 -0
  25. package/plugins/edit/client.js +113 -0
  26. package/plugins/edit/index.js +58 -0
  27. package/plugins/edit/package.json +23 -0
  28. package/plugins/fs-freshness/index.js +28 -0
  29. package/plugins/fs-freshness/package.json +13 -0
  30. package/plugins/graph/client.js +178 -0
  31. package/plugins/graph/index.js +4 -0
  32. package/plugins/graph/package.json +22 -0
  33. package/plugins/kriya-handoff/index.js +194 -0
  34. package/plugins/kriya-handoff/package.json +13 -0
  35. package/plugins/kriya-tools/index.js +189 -0
  36. package/plugins/kriya-tools/package.json +13 -0
  37. package/plugins/loop/index.js +743 -0
  38. package/plugins/loop/package.json +13 -0
  39. package/plugins/mirror/index.js +235 -0
  40. package/plugins/mirror/package.json +13 -0
  41. package/plugins/overview/client.js +276 -0
  42. package/plugins/overview/index.js +95 -0
  43. package/plugins/overview/package.json +22 -0
  44. package/plugins/preview/client.js +337 -0
  45. package/plugins/preview/index.js +4 -0
  46. package/plugins/preview/package.json +22 -0
  47. package/plugins/progress/client.js +290 -0
  48. package/plugins/progress/index.js +100 -0
  49. package/plugins/progress/package.json +22 -0
  50. package/plugins/projects/client.js +249 -0
  51. package/plugins/projects/index.js +30 -0
  52. package/plugins/projects/package.json +24 -0
  53. package/plugins/rea/index.js +256 -0
  54. package/plugins/rea/package.json +10 -0
  55. package/plugins/rea/skill/LICENSE +21 -0
  56. package/plugins/rea/skill/SKILL.md +360 -0
  57. package/plugins/rea/skill/references/android-applications.md +36 -0
  58. package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
  59. package/plugins/rea/skill/references/evidence-workflows.md +71 -0
  60. package/plugins/rea/skill/references/javascript-applications.md +218 -0
  61. package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
  62. package/plugins/rea/skill/references/runtime-observation.md +78 -0
  63. package/plugins/remote/index.js +297 -0
  64. package/plugins/remote/package.json +10 -0
  65. package/plugins/router/index.js +84 -0
  66. package/plugins/router/package.json +13 -0
  67. package/plugins/sessions/client.js +68 -0
  68. package/plugins/sessions/index.js +79 -0
  69. package/plugins/sessions/package.json +20 -0
  70. package/plugins/skills/client.js +504 -0
  71. package/plugins/skills/index.js +166 -0
  72. package/plugins/skills/package.json +23 -0
  73. package/src/api.js +97 -0
  74. package/src/browser.js +286 -0
  75. package/src/changes.js +191 -0
  76. package/src/checkpoints.js +313 -0
  77. package/src/daemon.js +503 -0
  78. package/src/doctor.js +137 -0
  79. package/src/edit/core/anchors.js +102 -0
  80. package/src/edit/core/audio.js +158 -0
  81. package/src/edit/core/faces.js +99 -0
  82. package/src/edit/core/ffmpeg.js +258 -0
  83. package/src/edit/core/handoff.js +220 -0
  84. package/src/edit/core/history.js +90 -0
  85. package/src/edit/core/layout.js +92 -0
  86. package/src/edit/core/mix.js +115 -0
  87. package/src/edit/core/ops.js +602 -0
  88. package/src/edit/core/plan.js +266 -0
  89. package/src/edit/core/project.d.ts +134 -0
  90. package/src/edit/core/project.js +307 -0
  91. package/src/edit/core/reframe.js +125 -0
  92. package/src/edit/core/solver.js +416 -0
  93. package/src/edit/core/time.js +110 -0
  94. package/src/edit/core/tonemap.js +57 -0
  95. package/src/edit/director/ask.js +120 -0
  96. package/src/edit/director/gateway.js +16 -0
  97. package/src/edit/director/revise.js +186 -0
  98. package/src/edit/engine/capabilities.js +33 -0
  99. package/src/edit/engine/captions.js +154 -0
  100. package/src/edit/engine/color.js +269 -0
  101. package/src/edit/engine/confine.js +67 -0
  102. package/src/edit/engine/dna.js +148 -0
  103. package/src/edit/engine/index.js +473 -0
  104. package/src/edit/engine/loudness.js +43 -0
  105. package/src/edit/engine/media.js +57 -0
  106. package/src/edit/engine/motion.js +281 -0
  107. package/src/edit/engine/packs.js +87 -0
  108. package/src/edit/engine/probe.js +101 -0
  109. package/src/edit/engine/receipt.js +123 -0
  110. package/src/edit/engine/tool.js +101 -0
  111. package/src/edit/gates/copy.js +113 -0
  112. package/src/edit/gates/index.js +430 -0
  113. package/src/edit/gates/picture.js +130 -0
  114. package/src/edit/gates/sound.js +58 -0
  115. package/src/edit/gates/speech.js +127 -0
  116. package/src/edit/gates/text.js +196 -0
  117. package/src/edit/gates/text.swift +22 -0
  118. package/src/edit/graph/index.js +139 -0
  119. package/src/edit/graph/journal.js +69 -0
  120. package/src/edit/graph/scheduler.js +79 -0
  121. package/src/edit/host/client.js +58 -0
  122. package/src/edit/host/deliver.js +119 -0
  123. package/src/edit/host/jobs.js +84 -0
  124. package/src/edit/host/main.js +135 -0
  125. package/src/edit/host/paths.js +11 -0
  126. package/src/edit/host/projects.js +415 -0
  127. package/src/edit/host/server.js +391 -0
  128. package/src/edit/host/taste.js +135 -0
  129. package/src/edit/host/tavi.js +417 -0
  130. package/src/edit/host/watch.js +141 -0
  131. package/src/edit/index/db.js +109 -0
  132. package/src/edit/index/index.js +236 -0
  133. package/src/edit/index/layers/faces.js +78 -0
  134. package/src/edit/index/layers/faces.swift +18 -0
  135. package/src/edit/index/layers/meta.js +35 -0
  136. package/src/edit/index/layers/music.js +146 -0
  137. package/src/edit/index/layers/quality.js +120 -0
  138. package/src/edit/index/layers/retakes.js +132 -0
  139. package/src/edit/index/layers/screen.js +99 -0
  140. package/src/edit/index/layers/shots.js +29 -0
  141. package/src/edit/index/layers/sound.js +42 -0
  142. package/src/edit/index/layers/words.js +64 -0
  143. package/src/edit/index/story.js +248 -0
  144. package/src/edit/index/views.js +71 -0
  145. package/src/edit/loop/governor.js +112 -0
  146. package/src/edit/loop/loop.js +69 -0
  147. package/src/edit/loop/make.js +115 -0
  148. package/src/edit/loop/repair.js +97 -0
  149. package/src/edit/loop/replay.js +32 -0
  150. package/src/edit/recipes/multicam.js +461 -0
  151. package/src/edit/recipes/reel.js +202 -0
  152. package/src/edit/recipes/short-from-long.js +237 -0
  153. package/src/edit/recipes/tutorial.js +137 -0
  154. package/src/edit/recipes/youtube.js +155 -0
  155. package/src/edit/runtime/cli.js +126 -0
  156. package/src/edit/runtime/doctor.js +122 -0
  157. package/src/edit/runtime/fetch.js +15 -0
  158. package/src/edit/runtime/licences.js +88 -0
  159. package/src/edit/runtime/manifest.js +73 -0
  160. package/src/edit/runtime/setup.js +252 -0
  161. package/src/failure.js +69 -0
  162. package/src/gateway-proxy.js +213 -0
  163. package/src/intent.js +130 -0
  164. package/src/launch.js +315 -0
  165. package/src/live.js +81 -0
  166. package/src/local-skills.js +284 -0
  167. package/src/login.js +82 -0
  168. package/src/loop.js +428 -0
  169. package/src/modes.js +128 -0
  170. package/src/overview.js +71 -0
  171. package/src/paths.js +30 -0
  172. package/src/profiles.js +92 -0
  173. package/src/projects.js +104 -0
  174. package/src/recon.js +244 -0
  175. package/src/rules.js +139 -0
  176. package/src/runner.bundle.js +21172 -0
  177. package/src/sentinel.js +248 -0
  178. package/src/skill-switches.js +130 -0
  179. package/src/store.js +58 -0
  180. package/src/strict.js +124 -0
  181. package/src/verify.js +659 -0
  182. package/src/world.js +268 -0
  183. package/studio/dist/index.html +14 -0
  184. package/studio/dist/studio.css +163 -0
  185. package/studio/dist/studio.js +1 -0
@@ -0,0 +1,135 @@
1
+ // The Edit Host: one process per machine, detached, owning every job (EDD-03). It
2
+ // holds a lock, listens on loopback and on an owner-only socket, and exits when idle.
3
+
4
+ import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
5
+ import { createServer } from "node:http"
6
+ import { homedir } from "node:os"
7
+ import { delimiter } from "node:path"
8
+
9
+ import { readCapabilities, toolVersion } from "../engine/capabilities.js"
10
+ import { gatewaySend } from "../director/gateway.js"
11
+ import { createScheduler, DEFAULT_SLOTS } from "../graph/scheduler.js"
12
+ import { createGovernor } from "../loop/governor.js"
13
+ import { kriyaHome } from "../../paths.js"
14
+ import { createJobs } from "./jobs.js"
15
+ import { editHome, lockPath, portPath, socketPath } from "./paths.js"
16
+ import { createProjects } from "./projects.js"
17
+ import { createHandler } from "./server.js"
18
+ import { createTavi } from "./tavi.js"
19
+ import { createWatcher } from "./watch.js"
20
+
21
+ const home = kriyaHome()
22
+ const roots = (process.env.KRIYA_EDIT_ROOTS || homedir()).split(delimiter).filter(Boolean)
23
+ const idleMs = Number(process.env.KRIYA_EDIT_IDLE_MS) || 30 * 60_000
24
+ const tokenTtlMs = Number(process.env.KRIYA_EDIT_TOKEN_TTL_MS) || 60_000
25
+ const log = (line) => process.stdout.write(`${new Date().toISOString()} ${line}\n`)
26
+
27
+ function takeLock() {
28
+ mkdirSync(editHome(home), { recursive: true })
29
+ for (let attempt = 0; attempt < 2; attempt++) {
30
+ try {
31
+ writeFileSync(lockPath(home), String(process.pid), { flag: "wx", mode: 0o600 })
32
+ return true
33
+ } catch (error) {
34
+ if (error.code !== "EEXIST") throw error
35
+ const holder = Number(readFileSync(lockPath(home), "utf8"))
36
+ try {
37
+ process.kill(holder, 0)
38
+ return false // A live Host holds it: whoever started this attaches to that one
39
+ } catch {
40
+ rmSync(lockPath(home), { force: true })
41
+ }
42
+ }
43
+ }
44
+ return false
45
+ }
46
+
47
+ if (!takeLock()) process.exit(0)
48
+
49
+ let tools
50
+ const readTools = () =>
51
+ (tools ??= Promise.all([readCapabilities(), toolVersion()])
52
+ .then(([capabilities, version]) => ({ capabilities, version }))
53
+ .catch(() => ({ capabilities: { filters: new Set(), encoders: new Set() }, version: "missing" })))
54
+
55
+ const scheduler = createScheduler(DEFAULT_SLOTS)
56
+ const sse = new Set()
57
+ // One Governor for every Director call on this machine (EDIT_LOOP §8). "Live" is a
58
+ // harness Web UI with the Studio row that pinged in the last minute
59
+ let liveAt = 0
60
+ const governor = createGovernor({ send: gatewaySend(), live: () => Date.now() - liveAt < 60_000 })
61
+ const projects = createProjects({ home, roots, scheduler, tools: readTools, governor })
62
+ const tavi = createTavi({ home, projects, jobs: () => jobs, tools: readTools, log })
63
+ const jobs = createJobs({
64
+ projects,
65
+ log,
66
+ onDispatch: (request, view, error) => tavi.onUpdate(request, view, error),
67
+ beforeStory: (...args) => tavi.chooseTakes(...args),
68
+ emit: (event, data) => {
69
+ for (const res of sse) res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
70
+ },
71
+ })
72
+
73
+ // New recordings, only for folders the person added on this computer (EDD-47)
74
+ const watcher = createWatcher({ home, send: tavi.post, log })
75
+
76
+ let lastActive = Date.now()
77
+ let inFlight = 0 // a request still running isn't idle, however long it takes
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 })
80
+ const web = createServer((req, res) => handle(req, res, false))
81
+ const local = createServer((req, res) => handle(req, res, true))
82
+
83
+ let stopping = false
84
+ function shutdown() {
85
+ if (stopping) return
86
+ stopping = true
87
+ log("stopping")
88
+ for (const server of [web, local]) {
89
+ server.close()
90
+ server.closeAllConnections()
91
+ }
92
+ rmSync(socketPath(home), { force: true })
93
+ tavi.close()
94
+ watcher.close()
95
+ projects.close()
96
+ rmSync(lockPath(home), { force: true })
97
+ process.exit(0)
98
+ }
99
+
100
+ process.on("SIGTERM", shutdown)
101
+ process.on("SIGINT", shutdown)
102
+
103
+ function listen(wanted) {
104
+ return new Promise((done, fail) => {
105
+ const failed = (error) => (error.code === "EADDRINUSE" && wanted !== 0 ? listen(0).then(done, fail) : fail(error))
106
+ web.once("error", failed)
107
+ web.listen(wanted, "127.0.0.1", () => {
108
+ web.off("error", failed)
109
+ done(web.address().port)
110
+ })
111
+ })
112
+ }
113
+
114
+ function storedPort() {
115
+ try {
116
+ return Number(readFileSync(portPath(home), "utf8")) || 0
117
+ } catch {
118
+ return 0
119
+ }
120
+ }
121
+
122
+ port = await listen(storedPort())
123
+ writeFileSync(portPath(home), String(port))
124
+ rmSync(socketPath(home), { force: true })
125
+ await new Promise((done) => local.listen(socketPath(home), done))
126
+ chmodSync(socketPath(home), 0o600)
127
+ log(`listening on 127.0.0.1:${port}`)
128
+
129
+ void readTools()
130
+ void tavi.flush().catch(() => {})
131
+ await jobs.resume()
132
+
133
+ setInterval(() => {
134
+ if (jobs.count() === 0 && tavi.pending() === 0 && watcher.count() === 0 && sse.size === 0 && inFlight === 0 && Date.now() - lastActive > idleMs) shutdown()
135
+ }, Math.max(50, Math.min(idleMs / 4, 30_000)))
@@ -0,0 +1,11 @@
1
+ // Where the Host keeps things (ARCHITECTURE §5): never in a synced folder (EF-28).
2
+
3
+ import { join } from "node:path"
4
+
5
+ import { kriyaHome } from "../../paths.js"
6
+
7
+ export const editHome = (home = kriyaHome()) => join(home, "edit")
8
+ export const socketPath = (home) => join(editHome(home), "host.sock")
9
+ export const lockPath = (home) => join(editHome(home), "host.lock")
10
+ export const portPath = (home) => join(editHome(home), "port")
11
+ export const logPath = (home) => join(editHome(home), "host.log")
@@ -0,0 +1,415 @@
1
+ // Projects on disk (DATA_MODEL §2): the project file is written atomically in the
2
+ // person's folder; its history and cache stay in ~/.kriya/edit/<id>/, never synced.
3
+
4
+ import { randomBytes } from "node:crypto"
5
+ import { appendFileSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeSync } from "node:fs"
6
+ import { dirname, extname, isAbsolute, join, relative, sep } from "node:path"
7
+
8
+ import { checkout, commit, createLog, parseEntry, undo, versions } from "../core/history.js"
9
+ import { canonical, newProject, parseProject, serialize, sha256 } from "../core/project.js"
10
+ import { createEngine, ENGINE_VERSION, guardPath } from "../engine/index.js"
11
+ import { motionRuntime } from "../engine/motion.js"
12
+ import { parseCube } from "../engine/color.js"
13
+ import { fingerprint } from "../engine/media.js"
14
+ import { probe } from "../engine/probe.js"
15
+ import { EngineFailure, runTool } from "../engine/tool.js"
16
+ import { openJournal } from "../graph/journal.js"
17
+ import { solve } from "../core/solver.js"
18
+ import { createAsk } from "../director/ask.js"
19
+ import { LOOKS } from "../engine/captions.js"
20
+ import { cleanSelection, describe, noteWord, revise } from "../director/revise.js"
21
+ import { openIndexDb } from "../index/db.js"
22
+ import { makeReel, rebase } from "../loop/make.js"
23
+ import { runGates } from "../gates/index.js"
24
+ import { REEL_TALKING_HEAD } from "../recipes/reel.js"
25
+ import { compareRuns, replayAsk } from "../loop/replay.js"
26
+ import { verifiedRecogniser, writeDelivery, writeHandoff } from "./deliver.js"
27
+ import { createIndexer, layersFor } from "../index/index.js"
28
+ import { activeRuntime } from "../runtime/setup.js"
29
+ import { editHome } from "./paths.js"
30
+ import { createTaste } from "./taste.js"
31
+
32
+ function atomicWrite(file, text) {
33
+ const part = `${file}.${process.pid}.tmp`
34
+ const handle = openSync(part, "w")
35
+ try {
36
+ writeSync(handle, text)
37
+ fsyncSync(handle)
38
+ } finally {
39
+ closeSync(handle)
40
+ }
41
+ renameSync(part, file)
42
+ }
43
+
44
+ // EG-3: a damaged database is set aside, never deleted (the index keeps the person's
45
+ // transcript corrections), and an empty one opens in its place. Other errors stand.
46
+ function openOrSetAside(file, open) {
47
+ try {
48
+ return { value: open(file), damaged: false }
49
+ } catch (error) {
50
+ if (!/not a database|malformed|corrupt/i.test(error.message)) throw error
51
+ const aside = `${file}.damaged-${Date.now()}`
52
+ for (const suffix of ["", "-wal", "-shm"]) if (existsSync(file + suffix)) renameSync(file + suffix, aside + suffix)
53
+ return { value: open(file), damaged: true }
54
+ }
55
+ }
56
+
57
+ const readIndex = (file) => {
58
+ const db = openIndexDb(file)
59
+ try {
60
+ return { db, index: db.read() }
61
+ } catch (error) {
62
+ db.close()
63
+ throw error
64
+ }
65
+ }
66
+
67
+ const kindOf = ({ width, hasAudio }) => (width ? "video" : hasAudio ? "audio" : "data")
68
+
69
+ /**
70
+ * @param {{ home: string, roots: string[], scheduler: object, tools: () => Promise<{ capabilities: object, version: string }> }} options
71
+ */
72
+ // Director model calls a job may make (DIRECTOR_AND_AGENT §13, short form)
73
+ const JOB_CALLS = 40
74
+
75
+ export function createProjects({ home, roots, scheduler, tools, governor = null }) {
76
+ const base = editHome(home)
77
+ const taste = createTaste({ home })
78
+ const registry = join(base, "projects.json")
79
+ const open = new Map()
80
+
81
+ const list = () => (existsSync(registry) ? JSON.parse(readFileSync(registry, "utf8")) : [])
82
+ const entry = (id) => list().find((item) => item.id === id)
83
+ const dirOf = (id) => join(base, id)
84
+ // Where an asset's file is, fenced to the roots and the project's folder
85
+ const sourcesOf = (state) => (id) => {
86
+ const found = state.log.current.assets.find((a) => a.id === id)
87
+ return guardPath(isAbsolute(found.path) ? found.path : join(state.folder, found.path), [...roots, state.folder])
88
+ }
89
+
90
+ function persist(state) {
91
+ const project = { ...state.log.current, head: state.log.head, history: versions(state.log) }
92
+ atomicWrite(state.file, serialize(project))
93
+ atomicWrite(join(dirOf(project.id), "head"), state.log.head ?? "")
94
+ state.engine.load(state.log.current, state.index)
95
+ }
96
+
97
+ async function attach(id, file) {
98
+ const dir = dirOf(id)
99
+ const root = parseProject(readFileSync(join(dir, "root.json"), "utf8"))
100
+ if (!root.ok) throw new EngineFailure("input", "unreadable", root.errors[0].reason)
101
+ const lines = existsSync(join(dir, "ops.jsonl")) ? readFileSync(join(dir, "ops.jsonl"), "utf8").split("\n").filter(Boolean) : []
102
+ const entries = lines.map((line) => {
103
+ const parsed = parseEntry(line)
104
+ if (!parsed.ok) throw new EngineFailure("input", "unreadable", "This project's history is damaged.")
105
+ return parsed.entry
106
+ })
107
+ const head = existsSync(join(dir, "head")) ? readFileSync(join(dir, "head"), "utf8") || null : null
108
+ const opened = openOrSetAside(join(dir, "index.sqlite"), readIndex)
109
+ const { db: indexDb, index } = opened.value
110
+ const log = checkout({ ...createLog(root.project), entries }, head, { index })
111
+ const { capabilities, version } = await tools()
112
+ const folder = dirname(file)
113
+ const journaled = openOrSetAside(join(dir, "journal.sqlite"), openJournal)
114
+ const journal = journaled.value
115
+ const engine = createEngine({ folder, roots: [...roots, folder], cache: join(dir, "cache"), exports: join(folder, "exports"), journal, toolVersion: version, capabilities, scheduler, motion: () => motionRuntime(activeRuntime(home)) })
116
+ engine.load(log.current, index)
117
+ const state = { id, file, folder, log, journal, engine, indexDb, index, proposals: new Map(), damaged: [...(opened.damaged ? ["index"] : []), ...(journaled.damaged ? ["journal"] : [])] }
118
+ open.set(id, state)
119
+ return state
120
+ }
121
+
122
+ // One attach per project at a time: two at once (the start's resume and a request) opened
123
+ // its databases twice, and the second saw the first's repair, not the damage (found in ED17)
124
+ const opening = new Map()
125
+ async function get(id) {
126
+ if (open.has(id)) return open.get(id)
127
+ if (opening.has(id)) return opening.get(id)
128
+ const known = entry(id)
129
+ if (!known) return null
130
+ const pending = attach(id, known.file).finally(() => opening.delete(id))
131
+ opening.set(id, pending)
132
+ return pending
133
+ }
134
+
135
+ function change(state, { ops, author }) {
136
+ const result = commit(state.log, { ops, author, at: new Date().toISOString() }, { index: state.index })
137
+ if (!result.ok) return result
138
+ state.log = result.log
139
+ appendFileSync(join(dirOf(state.id), "ops.jsonl"), `${JSON.stringify(state.log.entries.at(-1))}\n`)
140
+ persist(state)
141
+ // What the person does; a job's own operations teach nothing
142
+ if (author === "person") taste.note(state.id, ops, state.log.head)
143
+ return result
144
+ }
145
+
146
+ return {
147
+ list,
148
+ get,
149
+ change,
150
+ taste,
151
+ each: async (visit) => {
152
+ for (const { id } of list()) {
153
+ // One damaged project never stops the others, or the Host's start (EG-3); opening it says why
154
+ const state = await get(id).catch(() => null)
155
+ if (state) await visit(state)
156
+ }
157
+ },
158
+ close: () => {
159
+ for (const state of open.values()) {
160
+ state.journal.close()
161
+ state.indexDb.close()
162
+ }
163
+ },
164
+
165
+ undo(state) {
166
+ taste.forget(state.id, state.log.head)
167
+ state.log = undo(state.log, { index: state.index })
168
+ persist(state)
169
+ },
170
+
171
+ /** @param {{ name: string, folder: string, offered?: boolean }} input offered: the person offered this folder on this computer (CC-D2) */
172
+ async create({ name, folder, offered = false }) {
173
+ const real = guardPath(folder, offered ? [folder] : roots)
174
+ const id = randomBytes(8).toString("hex")
175
+ const dir = dirOf(id)
176
+ mkdirSync(dir, { recursive: true })
177
+ const project = newProject({ id, name })
178
+ const file = join(real, `${name.replace(/[^\p{L}\p{N} _-]+/gu, "-")}.kriya-edit`)
179
+ if (existsSync(file)) throw new EngineFailure("input", "exists", "A project with that name is already in this folder.")
180
+ atomicWrite(join(dir, "root.json"), serialize(project))
181
+ atomicWrite(file, serialize(project))
182
+ atomicWrite(registry, JSON.stringify([...list(), { id, name, file }]))
183
+ return attach(id, file)
184
+ },
185
+
186
+ /** Brings a file in by reference: probed, fingerprinted, never copied or written. */
187
+ async addAsset(state, path) {
188
+ const real = guardPath(path, [...roots, state.folder])
189
+ // A .cube is a LUT (ED13): read and checked here, before FFmpeg ever sees it, never probed as media
190
+ const lut = extname(real).toLowerCase() === ".cube"
191
+ if (lut) {
192
+ try {
193
+ parseCube(readFileSync(real, "utf8"))
194
+ } catch (error) {
195
+ throw new EngineFailure("input", "refused", error.message)
196
+ }
197
+ }
198
+ const { facts } = lut ? { facts: {} } : await probe(real)
199
+ const id = `a${state.log.current.assets.length + 1}`
200
+ const within = relative(state.folder, real)
201
+ const stored = within.startsWith("..") || isAbsolute(within) ? real : within.split(sep).join("/")
202
+ const op = { op: "add_asset", id, kind: lut ? "lut" : kindOf(facts), fingerprint: await fingerprint(real), path: stored, linked: true, rights: "unknown", facts }
203
+ const result = change(state, { ops: [op], author: "code" })
204
+ if (!result.ok) throw new EngineFailure("input", "refused", result.diagnostics[0].message)
205
+ return state.log.current.assets.at(-1)
206
+ },
207
+
208
+ /** Runs the Footage Index on one asset; word and shot anchors resolve once it has. */
209
+ async indexAsset(state, assetId, { signal, onStep } = {}) {
210
+ const asset = state.log.current.assets.find((item) => item.id === assetId)
211
+ if (!asset || !["video", "audio"].includes(asset.kind)) throw new EngineFailure("input", "unknown_asset", "There is no such video or sound in this project.")
212
+ const path = guardPath(isAbsolute(asset.path) ? asset.path : join(state.folder, asset.path), [...roots, state.folder])
213
+ const owner = Symbol("index")
214
+ const indexer = createIndexer({
215
+ db: state.indexDb,
216
+ cache: join(dirOf(state.id), "cache"),
217
+ binDir: join(base, "bin"),
218
+ language: state.log.current.brief?.language ?? "en",
219
+ runtime: () => activeRuntime(home),
220
+ acquire: (resources, abort) => scheduler.acquire(resources, { signal: abort, owner }),
221
+ })
222
+ const report = await indexer.indexAsset(asset, path, { signal, onStep, only: layersFor(asset.kind) })
223
+ state.index = state.indexDb.read()
224
+ state.damaged = state.damaged.filter((part) => part !== "index")
225
+ state.engine.load(state.log.current, state.index)
226
+ return report
227
+ },
228
+
229
+ /** The Director for one job: the Governor's queue, the job's call budget, the journal's record. */
230
+ askFor(state, job = 0) {
231
+ if (!governor) throw new EngineFailure("environment", "no_director", "This Host has no Director.")
232
+ let left = JOB_CALLS
233
+ const ask = createAsk({ governor, record: (row) => state.journal.call({ job, ...row }), budget: { take: () => left-- > 0 } })
234
+ // Each slot's final answer, so the job can be replayed with no model call
235
+ return async (slot) => {
236
+ const answer = await ask(slot)
237
+ state.journal.answer({ job, task: slot.task, source: answer.source, value: answer.value })
238
+ return answer
239
+ }
240
+ },
241
+
242
+ /** The console: words → a proposal, applied to a copy, nothing landing yet (UX_SPEC §4, §5). */
243
+ async ask(state, { text, selection, job = 0 }) {
244
+ const chosen = cleanSelection(selection, state.log.current, state.index)
245
+ const result = await revise({ ask: this.askFor(state, job), project: state.log.current, index: state.index, text, selection: chosen })
246
+ if (!result.ops.length) return { proposal: null, source: result.source, reason: result.reason ?? "Kriya couldn't turn that into an edit. Try saying it another way." }
247
+ const id = randomBytes(6).toString("hex")
248
+ state.proposals.set(id, { ops: result.ops, head: state.log.head })
249
+ const { picture, duration } = solve(result.project, state.index)
250
+ return { proposal: { id, ops: result.ops, changes: result.changes, timeline: { picture, duration } }, source: result.source, ...(result.reason ? { reason: result.reason } : {}) }
251
+ },
252
+
253
+ /** Accept all, accept some, or reject a proposal. Rebased onto HEAD; the person's own edits never move. */
254
+ decide(state, id, { accept, only }) {
255
+ const proposal = state.proposals.get(id)
256
+ if (!proposal) throw new EngineFailure("input", "no_proposal", "That proposal has gone. Ask again.")
257
+ state.proposals.delete(id)
258
+ if (!accept) return { applied: 0, dropped: [] }
259
+ const chosen = Array.isArray(only) ? proposal.ops.filter((_, i) => only.includes(i)) : proposal.ops
260
+ const { ops, dropped } = rebase(state.log.current, chosen, state.index)
261
+ if (ops.length) {
262
+ const result = change(state, { ops, author: "agent" })
263
+ if (!result.ok) throw new EngineFailure("input", "refused", result.diagnostics[0].message)
264
+ // Accepting a proposal is the person's choice
265
+ taste.note(state.id, ops, state.log.head)
266
+ }
267
+ return { applied: ops.length, dropped: dropped.map((d) => ({ change: describe(d.op, state.index), reason: d.reason })) }
268
+ },
269
+
270
+ /** A make job: the reel recipe through the Edit Loop, checked by the gates. */
271
+ /**
272
+ * A make job. With `replay`, the Director's slots are answered from that job's
273
+ * recording (no model call), and nothing lands on the project (EDIT_LOOP §10).
274
+ */
275
+ async make(state, request, { job = 0, signal, onStep = () => {}, replay, beforeStory } = {}) {
276
+ const video = state.log.current.assets.filter((a) => a.kind === "video")
277
+ const asset = request.asset ?? video[0]?.id
278
+ if (!asset || !video.some((a) => a.id === asset)) throw new EngineFailure("input", "no_take", "Add a video first.")
279
+ if (!state.index.words.some((w) => w.asset === asset)) await this.indexAsset(state, asset, { signal })
280
+ // The song's beats, so the music can be fitted on its downbeats
281
+ const song = request.brief?.music && state.log.current.assets.find((a) => a.id === request.brief.music && a.kind === "audio")
282
+ if (song && !state.index.beats?.some((b) => b.asset === song.id)) await this.indexAsset(state, song.id, { signal })
283
+ // A real choice goes to the person before the story is planned (TAVI_INTEGRATION §5)
284
+ const picks = !replay && beforeStory ? await beforeStory(state, asset, { signal, sourcePath: sourcesOf(state) }) : null
285
+ // The person's confirmed rules, under anything the brief says, and their choices. A
286
+ // replay uses what the job really used. Captions only where they can render
287
+ const recorded = replay?.answers.find((a) => a.task === "brief_extra")
288
+ const extra = recorded ? JSON.parse(recorded.value) : { ...taste.defaults(), ...(picks && { picks }) }
289
+ if (extra.captions && (!Object.hasOwn(LOOKS, extra.captions) || !state.engine.motion())) delete extra.captions
290
+ if (!replay && Object.keys(extra).length) state.journal.answer({ job, task: "brief_extra", source: "person", value: extra })
291
+ const usedRules = [...(extra.captions && !request.brief?.captions ? [`Used your rule: ${extra.captions} captions`] : []), ...(extra.zoom && !request.brief?.zoom ? [`Used your rule: ${extra.zoom.toFixed(2)}× zoom`] : [])]
292
+ const stages = ["story", "check", "repair"]
293
+ const run = runTool
294
+ const work = join(dirOf(state.id), "cache", "gates")
295
+ const sourcePath = sourcesOf(state)
296
+ const runtime = activeRuntime(home)
297
+ const ask = replay ? replayAsk(replay.answers) : this.askFor(state, job)
298
+ const parent = state.log.head
299
+ const result = await makeReel({
300
+ project: state.log.current,
301
+ head: state.log.head,
302
+ index: state.index,
303
+ asset,
304
+ brief: { ...extra, ...request.brief },
305
+ ask,
306
+ render: (project, deliverable, abort) => state.engine.render({ quality: "master", deliverable, project, job, signal: abort }),
307
+ sourcePath,
308
+ signal,
309
+ onStage: (stage) => onStep(stages.indexOf(stage) + 1, stages.length + 1),
310
+ gateKit: {
311
+ tilePath: state.engine.tilePath,
312
+ motion: state.engine.motion(),
313
+ work,
314
+ stems: state.engine.stems,
315
+ binDir: join(base, "bin"),
316
+ recognise: verifiedRecogniser(runtime, { run, work, language: state.log.current.brief?.language ?? "en" }),
317
+ ask,
318
+ },
319
+ })
320
+ // Each attempt as ranked, for the report: never the model's words
321
+ const attempts = result.outcome.history.slice(1).map((h) => ({ round: h.round, accepted: h.accepted, level: h.verdict?.level ?? null, rank: h.rank, ...(h.verdict?.error ? { error: h.verdict.error } : {}) }))
322
+ if (!result.best) return { verdict: "not_checked", notes: result.notes, calls: result.calls, stop: result.outcome.stop, changes: [], dropped: [], attempts }
323
+ const gates = result.best.gates
324
+ const planHash = result.best.plan ? sha256(canonical(result.best.plan)) : null
325
+ const repairs = result.best.repairs ?? []
326
+ const person = result.best.person ?? []
327
+ const notes = [...result.notes, ...person.map((p) => `${p.gate}: ${p.message} This is yours to decide.`)]
328
+ if (replay) return { replayOf: replay.of, verdict: gates?.verdict ?? "not_checked", gates: gates?.gates ?? [], planHash, notes, repairs, calls: result.calls, stop: result.outcome.stop }
329
+ const { ops, dropped } = state.log.head === result.head ? { ops: result.best.ops, dropped: [] } : rebase(state.log.current, result.best.ops, state.index)
330
+ const landed = change(state, { ops, author: "agent" })
331
+ if (!landed.ok) throw new EngineFailure("plan", "refused", landed.diagnostics[0].message)
332
+ const changes = [...usedRules, ...ops.filter((op) => !["ripple_delete", "reframe"].includes(op.op)).map((op) => describe(op, state.index))]
333
+ const { version } = await tools()
334
+ const delivery = result.best.file
335
+ ? await writeDelivery({ file: result.best.file, title: state.log.current.name, project: result.best.project, parent, plan: result.best.plan, sourcePath, tools: { engine: ENGINE_VERSION, ffmpeg: version, runtime: runtime?.version ?? null }, gates: gates?.gates ?? [], verdict: gates?.verdict ?? "not_checked", calls: state.journal.calls(job), changes, notes, repairs, beforeFrom: sourcePath(asset), run, work })
336
+ : null
337
+ return {
338
+ verdict: gates?.verdict ?? "not_checked",
339
+ file: result.best.file ?? null,
340
+ receipt: delivery?.receipt ?? null,
341
+ report: delivery?.report ?? null,
342
+ planHash,
343
+ gates: gates?.gates ?? [],
344
+ changes,
345
+ notes,
346
+ repairs,
347
+ calls: result.calls,
348
+ slots: result.slots,
349
+ stop: result.outcome.stop,
350
+ attempts,
351
+ dropped: dropped.map((d) => ({ change: describe(d.op, state.index), reason: d.reason })),
352
+ }
353
+ },
354
+
355
+ /**
356
+ * A revision: each note or change, in the person's words, through the same validated
357
+ * console as the Studio (ES-20), then this cut rendered and gated. A note is pinned to
358
+ * the word it was made at, so it shows on the Studio's timeline and survives re-cuts. A
359
+ * note that can't become an edit is counted and left for the person, never forced.
360
+ */
361
+ async revise(state, request, { job = 0, signal, onStep = () => {} } = {}) {
362
+ const recipe = REEL_TALKING_HEAD
363
+ const deliverableOf = () => state.log.current.deliverables.find((d) => d.preset === recipe.deliverable.preset) ?? state.log.current.deliverables[0]
364
+ if (!deliverableOf()) throw new EngineFailure("input", "no_cut", "There's no cut in this project to revise yet.")
365
+ const notes = request.notes ?? []
366
+ const steps = notes.length + 2
367
+ let applied = 0
368
+ let skipped = 0
369
+ for (const [i, note] of notes.entries()) {
370
+ signal?.throwIfAborted()
371
+ onStep(i, steps)
372
+ const word = Number.isSafeInteger(note.at) ? noteWord(state.log.current, state.index, note.at) : null
373
+ if (word) change(state, { ops: [{ op: "mark", name: `Note: ${note.text}`.slice(0, 80), at: { word, edge: "start" } }], author: "code" })
374
+ const { proposal } = await this.ask(state, { text: note.text, job, ...(word && { selection: { words: [word, word] } }) })
375
+ if (proposal && this.decide(state, proposal.id, { accept: true }).applied > 0) applied++
376
+ else skipped++
377
+ }
378
+ onStep(notes.length, steps)
379
+ const parent = state.log.head
380
+ const project = state.log.current
381
+ const run = runTool
382
+ const work = join(dirOf(state.id), "cache", "gates")
383
+ const sourcePath = sourcesOf(state)
384
+ const runtime = activeRuntime(home)
385
+ const { file, plan } = await state.engine.render({ quality: "master", deliverable: deliverableOf().id, project, job, signal })
386
+ onStep(notes.length + 1, steps)
387
+ // shortcut: one render and its verdict, with no repair ladder; a make job climbs it, and a blocked revision says so
388
+ const gates = await runGates({ file, plan, project, index: state.index, sourcePath, thresholds: recipe.thresholds, tilePath: state.engine.tilePath, motion: state.engine.motion(), work, stems: state.engine.stems, binDir: join(base, "bin"), recognise: verifiedRecogniser(runtime, { run, work, language: project.brief?.language ?? "en" }), ask: this.askFor(state, job) })
389
+ const { version } = await tools()
390
+ const mentions = gates.gates.filter((g) => g.status === "not_checked" || (g.status === "failed" && g.severity === "note")).map((g) => g.id)
391
+ const delivery = await writeDelivery({ file, title: project.name, project, parent, plan, sourcePath, tools: { engine: ENGINE_VERSION, ffmpeg: version, runtime: runtime?.version ?? null }, gates: gates.gates, verdict: gates.verdict, calls: state.journal.calls(job), changes: [], notes: mentions, repairs: [], beforeFrom: null, run, work })
392
+ return { verdict: gates.verdict, file, receipt: delivery?.receipt ?? null, report: delivery?.report ?? null, planHash: sha256(canonical(plan)), gates: gates.gates, notes: mentions, applied, skipped }
393
+ },
394
+
395
+ /** `kriya edit replay`: a make job again from its recording; it compares, and lands nothing. */
396
+ async replay(state, number, { job = 0, signal, onStep } = {}) {
397
+ const original = state.journal.job(number)
398
+ if (!original || original.kind !== "make" || original.status !== "done") throw new EngineFailure("input", "no_job", "Only a finished make job can be replayed.")
399
+ const answers = state.journal.answers(number)
400
+ const again = await this.make(state, JSON.parse(original.request), { job, signal, onStep, replay: { of: `${state.id}.${number}`, answers } })
401
+ const before = JSON.parse(original.dispatch)
402
+ return { ...again, ...compareRuns(before, again) }
403
+ },
404
+
405
+ /** The current cut as a handoff package (OTIO, FCPXML, EDL, SRT) in the project's exports folder (EDIT_ENGINE §11). */
406
+ handoff(state) {
407
+ const done = writeHandoff({ project: state.log.current, index: state.index, exportsDir: join(state.folder, "exports"), sourcePath: sourcesOf(state) })
408
+ return { ...done, folder: relative(state.folder, done.folder) }
409
+ },
410
+
411
+ /** What each layer found or why it couldn't, per asset, for the Studio to say. */
412
+ indexStatus: (state) => state.log.current.assets.filter((asset) => state.indexDb.mediaOf(asset.id)).map((asset) => ({ asset: asset.id, layers: state.indexDb.layers(state.indexDb.mediaOf(asset.id)) })),
413
+ }
414
+ }
415
+