Compare commits

..
3 Commits
Author SHA1 Message Date
shaneandshinyobjectz 06a48730d1 A box says a Claude agent's turn has ended from its Stop hook (#302)
The hook is written into the socket's own settings and touches a file the box watches; as with a transcript's end, it's said only when nothing the agent started still runs.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 21:53:29 -08:00
shaneandshinyobjectz 28d89f8ffd Goal check: montage reads frames from a file, and keeps its findings beside the video (#301)
* The montage pack reads a video's frames from a file, not down a pipe

13 MB of small frames through the pipe took 9.7 s of a 35 s cut's read on a cloud box; into a file, 4.6 s.

* A video's montage findings are kept beside it, measured again when it or its beats change

Reading a 35 s cut's frames took 7 s each time the goal was checked, on files that hadn't changed.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 21:40:48 -08:00
shaneandshinyobjectz 7b8317764a A made video's floor report is kept beside it, measured again only for cause (#300)
The measure took 26 s a cut and ran again on the same file at publish and at done. A kept report with an error is always measured again: what it names can be put right without the video changing.

Co-authored-by: shinyobjectz <[email protected]>
2026-12-01 20:59:21 -08:00
8 changed files with 207 additions and 34 deletions

No files matched your search

+17 -10
View File
@@ -34,7 +34,7 @@
// Every route but /healthz needs RAEA_CLOUD_TOKEN: `Authorization: Bearer TOKEN`, or ?token= (a browser's WebSocket
// can't set headers). The agent and raea get the container's environment without the token or the state keys.
import { jobsOf, watchTurnEnd } from "./turn-end.ts"
import { claudeStopHook, jobsOf, markedEnd, watchEnd, watchTurnEnd } from "./turn-end.ts"
import { execFileSync, spawn } from "node:child_process"
import { timingSafeEqual } from "node:crypto"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
@@ -417,15 +417,22 @@ server.on("upgrade", (req, socket, head) => {
ws.on("message", (m) => ((heard = heardFromCaller = Date.now()), child.stdin.write(m.toString() + "\n")))
// the turn's end from the agent's own transcript, said along the socket (turn-end.ts): raea cloud closes the turn
// on it without waiting for an answer to session/prompt that may not come
if (agent.id === "antigravity-acp" && env.GEMINI_HOME) {
const stopWatch = watchTurnEnd(
env.GEMINI_HOME,
() => heardFromCaller,
(by) => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/turn_end", params: { by } })),
() => !!child.pid && jobsOf(child.pid, path.dirname(agent.command), WORK).length > 0,
)
ws.on("close", stopWatch)
child.on("exit", stopWatch)
{
const tellEnd = (by: string) => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/turn_end", params: { by } }))
const busy = () => !!child.pid && jobsOf(child.pid, path.dirname(agent.command), WORK).length > 0
let stopWatch: (() => void) | undefined
if (agent.id === "antigravity-acp" && env.GEMINI_HOME) stopWatch = watchTurnEnd(env.GEMINI_HOME, () => heardFromCaller, tellEnd, busy)
else if (agent.id === "claude-acp" && own && env.CLAUDE_CONFIG_DIR) {
// Claude says it itself, through a Stop hook in the socket's own settings (never the box's own home's)
try {
const mark = claudeStopHook(env.CLAUDE_CONFIG_DIR)
stopWatch = watchEnd(() => markedEnd(mark), "its Stop hook", () => heardFromCaller, tellEnd, busy)
} catch {}
}
if (stopWatch) {
ws.on("close", stopWatch)
child.on("exit", stopWatch)
}
}
ws.on("close", stopAll)
child.on("error", (e) => ws.close(1011, `couldn't start ${agent.id}: ${e.message}`.slice(0, 120)))
+47 -9
View File
@@ -5,9 +5,9 @@
//
// Antigravity keeps a transcript of each session, a JSON line a step. A model step that finished and called no tool is
// the end of its turn only when nothing it started still runs: it ends a step the same way to wait on a render it left
// in the background (123 of 131 such steps in one StreetTalk run), and is woken when that finishes. So both are read:
// in the background (123 of 131 such steps in one run), and is woken when that finishes. So both are read:
// the transcript's last line, and the processes that are the agent's own.
import { closeSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, statSync } from "node:fs"
import { closeSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
/** the step a transcript line ends a turn at, and when it was made (ms); null for any other line */
@@ -105,23 +105,61 @@ export function jobsOf(pid: number, agentDir: string, work: string, proc = "/pro
.map((p) => p.pid)
}
/** Watches an Antigravity agent's transcript and calls `said` once for each turn that ends after `told()` (when the
* agent was last sent anything: a turn that ended before its newest prompt isn't this one's), once `busy()` has been
/** Claude Code's own word that its turn ended: a Stop hook in the agent's settings (CLAUDE_CONFIG_DIR/settings.json)
* that touches a file here. Other settings and hooks already there are kept. Returns the file. */
export function claudeStopHook(configDir: string): string {
const mark = path.join(configDir, ".raea-turn-end")
const file = path.join(configDir, "settings.json")
let settings: any = {}
try {
settings = JSON.parse(readFileSync(file, "utf8"))
} catch {}
if (!settings || typeof settings !== "object" || Array.isArray(settings)) settings = {}
const command = `touch '${mark.replace(/'/g, "'\\''")}'`
const hooks = (settings.hooks ??= {})
const stop: any[] = Array.isArray(hooks.Stop) ? hooks.Stop : (hooks.Stop = [])
if (!stop.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h: any) => h?.command === command))) {
stop.push({ hooks: [{ type: "command", command }] })
writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`)
}
return mark
}
/** when a Stop hook's file was last touched, as a turn's end; null before the first */
export function markedEnd(mark: string): { step: number; at: number } | null {
try {
const at = statSync(mark).mtimeMs
return { step: at, at }
} catch {
return null
}
}
/** Calls `said` once for each turn's end that `ended` reads (an agent's own record of it) after `told()` (when the
* agent was last sent anything: an end from before its newest prompt isn't this turn's), once `busy()` has been
* false two looks running. Returns its stop. */
export function watchTurnEnd(geminiHome: string, told: () => number, said: (by: string) => void, busy: () => boolean = () => false, everyMs = 1000): () => void {
export function watchEnd(ended: () => { step: number; at: number } | null, by: string, told: () => number, said: (by: string) => void, busy: () => boolean = () => false, everyMs = 1000): () => void {
let seen = -1
let idle = 0
const t = setInterval(() => {
try {
const tr = newestTranscript(geminiHome)
const end = tr ? turnEndOf(lastLine(tr.file)) : null
// a second's slack: the transcript's times are whole seconds
const end = ended()
// a second's slack: a transcript's times are whole seconds
if (!end || end.step === seen || end.at < told() - 1000 || busy()) return void (idle = 0)
if (++idle < 2) return
seen = end.step
said("its transcript, and nothing of its own running")
said(`${by}, and nothing of its own running`)
} catch {}
}, everyMs)
t.unref?.()
return () => clearInterval(t)
}
/** watchEnd on an Antigravity agent's transcript */
export function watchTurnEnd(geminiHome: string, told: () => number, said: (by: string) => void, busy: () => boolean = () => false, everyMs = 1000): () => void {
const ended = () => {
const tr = newestTranscript(geminiHome)
return tr ? turnEndOf(lastLine(tr.file)) : null
}
return watchEnd(ended, "its transcript", told, said, busy, everyMs)
}
+21 -2
View File
@@ -3,13 +3,14 @@
// paths read on the worker)
import assert from "node:assert/strict"
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
import { execSync } from "node:child_process"
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { parseSummary, pick } from "../server/gpu.ts"
import { plan, projectRoot } from "../server/offload.ts"
import { shellEnv } from "../server/shell-os.ts"
import { jobsOf, lastLine, newestTranscript, turnEndOf, watchTurnEnd } from "../server/turn-end.ts"
import { claudeStopHook, jobsOf, lastLine, markedEnd, newestTranscript, turnEndOf, watchEnd, watchTurnEnd } from "../server/turn-end.ts"
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
const L4 = `Devices:
@@ -157,6 +158,24 @@ console.log("units: ok")
put(200, 101, 100, "/opt/raea/bin/raea", "raea render edit.tsx")
put(300, 1, 300, "/usr/bin/ffmpeg", "ffmpeg -i a.mp4", "/srv/work/threads/r1/out")
assert.deepEqual(jobsOf(100, "/opt/raea-cloud/agents/antigravity-acp", "/srv/work", proc).sort(), [200, 300])
// Claude's Stop hook: added to the settings there once, what was there kept; its file's touch is the turn's end
const cfg = path.join(home, "claude")
mkdirSync(cfg, { recursive: true })
writeFileSync(path.join(cfg, "settings.json"), JSON.stringify({ model: "opus", hooks: { Stop: [{ hooks: [{ type: "command", command: "true" }] }] } }))
const mark = claudeStopHook(cfg)
claudeStopHook(cfg)
const set = JSON.parse(readFileSync(path.join(cfg, "settings.json"), "utf8"))
assert.equal(set.model, "opus")
assert.deepEqual(set.hooks.Stop.map((g: any) => g.hooks[0].command), ["true", `touch '${mark}'`])
assert.equal(markedEnd(mark), null)
const heard: string[] = []
const stop2 = watchEnd(() => markedEnd(mark), "its Stop hook", () => Date.now() - 500, (by) => heard.push(by), () => false, 10)
await new Promise((ok) => setTimeout(ok, 40))
assert.deepEqual(heard, [])
execSync(set.hooks.Stop[1].hooks[0].command)
await new Promise((ok) => setTimeout(ok, 80))
stop2()
assert.deepEqual(heard, ["its Stop hook, and nothing of its own running"])
rmSync(home, { recursive: true, force: true })
console.log("ok turn-end")
}
+27 -3
View File
@@ -4,7 +4,7 @@
// stills a composition as it's saved (`raea check EDIT.tsx --quick`): three stills rendered with their manifest, and
// the text rules and the person's text taste on them; what it can't see waits for the export's floor
import { spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { check, found } from "raea/check"
@@ -12,7 +12,7 @@ import type { FileFacts } from "../facts.ts"
import { RAEA, stem } from "../media.ts"
import { bookkeeping } from "./naming.ts"
type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
export type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
/** raea's measure of a file, its findings as it wrote them (-o) */
function measure(args: string[], cwd: string): Measured[] {
@@ -27,12 +27,36 @@ function measure(args: string[], cwd: string): Measured[] {
}
}
/** a video's floor report, kept beside it */
export const FLOOR_EXT = "floor.json"
let version: string | undefined
const raeaVersion = () => (version ??= String(spawnSync(RAEA, ["--version"], { encoding: "utf8" }).stdout ?? "").trim())
const when = (f: string) => (existsSync(f) ? statSync(f).mtimeMs : 0)
/** A made video's floor findings: kept beside it (FILE.floor.json) and measured again only when the video or its
* manifest is newer, raea is another version, or the kept report holds an error. The measure took 26 s a cut and ran
* again on the same file at publish and at done (12-01). An error is always measured again, since what it names (a
* placeholder brand kit) can be put right without the video changing, and a kept error would hold a finished run. */
export function floorOf(abs: string, manifest: string | undefined, cwd: string, by: (args: string[], cwd: string) => Measured[] = measure): Measured[] {
const kept = `${stem(abs)}.${FLOOR_EXT}`
try {
const k = JSON.parse(readFileSync(kept, "utf8")) as { raea: string; findings: Measured[] }
const fresh = when(kept) >= when(abs) && (!manifest || when(kept) >= when(manifest))
if (fresh && k.raea === raeaVersion() && !k.findings.some((x) => x.level === "error")) return k.findings
} catch {}
const findings = by([abs, ...(manifest ? ["--manifest", manifest] : [])], cwd)
try {
writeFileSync(kept, `${JSON.stringify({ raea: raeaVersion(), findings })}\n`)
} catch {}
return findings
}
const say = (x: Measured) => found({ level: x.level, says: x.says, fix: x.fix ?? undefined, frames: x.frames ?? undefined })
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["render", "publish", "done"] }, async (f) => {
if (!f.made || f.kind !== "video" || bookkeeping(f.path)) return
const m = [`${stem(f.abs)}.render.json`, `${stem(f.abs)}.manifest.json`].find(existsSync)
for (const x of measure([f.abs, ...(m ? ["--manifest", m] : [])], f.root)) say(x)
for (const x of floorOf(f.abs, m, f.root)) say(x)
})
export const stillsPack = check<FileFacts>({ id: "stills", text: "a composition's stills: no clipped or cramped text, nothing out of the safe areas", over: "file", at: ["edit"], needs: "render" }, async (f) => {
+1 -1
View File
@@ -22,7 +22,7 @@ const NOT_WORK = new Set(["review", ".git", "node_modules", ".raea", "target", "
/** what a check keeps beside a file it read (its report, its words, its scene): a reading of the work, not a change
* to it. A done check that heard a cut's words wrote them beside it, and the critic's verdict of a minute before read
* as older than the work (12-01) */
const READING = /\.(check|words|scene)\.json$/
const READING = /\.(check|words|scene|floor|montage)\.json$/
/** when the work last changed (ms): the newest file under dir, its own bookkeeping left out (a bounded walk) */
export function newest(dir: string): number | null {
+41 -8
View File
@@ -13,6 +13,9 @@
// eye, plane and tone are warnings at each cut, in Murch's order; one becomes an error when it breaks at more than half
// of a file's cuts (a habit, not a choice). A cut on a word is the sound pack's (edit-on-sound), not this one's.
import { spawnSync } from "node:child_process"
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { check, found } from "raea/check"
import type { Beat } from "raea/brief.gen"
import type { FileFacts } from "../facts.ts"
@@ -42,9 +45,18 @@ export type Finding = { level: "error" | "warn"; kind: "pace" | "tempo" | "eye"
export function read(file: string, fps: number, width: number, height: number): Read {
const w = READ_W
const h = Math.max(2, Math.round((READ_W * height) / width / 2) * 2)
const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `scale=${w}:${h},format=rgb24`, "-f", "rawvideo", "-"], { maxBuffer: 1 << 30 })
if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${file}: ${String(r.stderr).trim().slice(-200)}`)
const buf = r.stdout as Buffer
// into a file, not down a pipe: 13 MB of frames through the pipe took 9.7 s of a 35 s cut's read on a cloud box, and
// 4.6 s into a file (12-01)
const dir = mkdtempSync(path.join(tmpdir(), "raea-montage-read-"))
let buf: Buffer
try {
const raw = path.join(dir, "frames.raw")
const r = spawnSync("ffmpeg", ["-v", "error", "-an", "-i", file, "-vf", `scale=${w}:${h},format=rgb24`, "-f", "rawvideo", raw], { encoding: "utf8" })
if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${file}: ${String(r.stderr).trim().slice(-200)}`)
buf = readFileSync(raw)
} finally {
rmSync(dir, { recursive: true, force: true })
}
const size = w * h * 3
const frames: Frame[] = []
for (let o = 0; o + size <= buf.length; o += size) {
@@ -235,6 +247,25 @@ export function acrossCuts(r: Read, cuts: number[], o: { faces?: Faces[]; rate?:
return out
}
/** a video's montage findings, kept beside it */
export const MONTAGE_EXT = "montage.json"
/** A video's findings from `measure`, kept beside it (FILE.montage.json) and measured again only when the video is
* newer or what they were measured against (`given`: its beats, its scene reading) is another. Reading a 35 s cut's
* frames took 7 s each time the goal was checked, on files that hadn't changed (12-01). */
export function keptOr(abs: string, given: string, measure: () => Finding[]): Finding[] {
const kept = `${abs.replace(/\.[^./]+$/, "")}.${MONTAGE_EXT}`
try {
const k = JSON.parse(readFileSync(kept, "utf8")) as { given: string; findings: Finding[] }
if (statSync(kept).mtimeMs >= statSync(abs).mtimeMs && k.given === given) return k.findings
} catch {}
const findings = measure()
try {
writeFileSync(kept, `${JSON.stringify({ given, findings })}\n`)
} catch {}
return findings
}
const where = ([x, y]: [number, number]) => `${y < 0.34 ? "top" : y > 0.66 ? "bottom" : "middle"} ${x < 0.34 ? "left" : x > 0.66 ? "right" : "centre"}`
export default check<FileFacts>(
@@ -244,9 +275,6 @@ export default check<FileFacts>(
const c = f.contract?.kind === "cut" ? f.contract.cut : undefined
const plan = c ? cutOf(c, f.path) : null
const beats = plan?.plan.beats ?? []
const r = read(f.abs, f.fps, f.width, f.height)
if (r.frames.length < 2) return
const cuts = cutsOf(r)
let faces: Faces[] | undefined
let rate = 0
try {
@@ -258,7 +286,12 @@ export default check<FileFacts>(
if (!(e instanceof Unmet)) throw e
}
const say = (x: Finding) => found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
for (const x of pace(beats, cuts, r.fps, r.frames.length / r.fps)) say(x)
for (const x of acrossCuts(r, cuts, { faces, rate, beatsAt: beats.map((b) => b.at) })) say(x)
for (const x of keptOr(f.abs, JSON.stringify({ beats, faces: faces?.length ?? null, rate }), () => {
const r = read(f.abs, f.fps, f.width!, f.height!)
if (r.frames.length < 2) return []
const cuts = cutsOf(r)
return [...pace(beats, cuts, r.fps, r.frames.length / r.fps), ...acrossCuts(r, cuts, { faces, rate, beatsAt: beats.map((b) => b.at) })]
}))
say(x)
},
)
+52
View File
@@ -0,0 +1,52 @@
// A made video's floor report is kept beside it and measured again only for cause (packs/floor.ts)
import { expect, test } from "bun:test"
import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { floorOf, type Measured } from "../src/packs/floor.ts"
import { keptOr } from "../src/packs/montage.ts"
test("a floor report is kept: measured once, again when the video is newer, and always while it holds an error", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-floor-kept-"))
const v = path.join(d, "a.mp4")
writeFileSync(v, "x")
let runs = 0
let out: Measured[] = [{ level: "warn", says: "quiet" }]
const by = () => (runs++, out)
expect(floorOf(v, undefined, d, by)).toEqual(out)
expect(floorOf(v, undefined, d, by)).toEqual(out)
expect(runs).toBe(1)
// the video made again
const later = new Date(Date.now() + 60_000)
utimesSync(v, later, later)
floorOf(v, undefined, d, by)
expect(runs).toBe(2)
utimesSync(path.join(d, "a.floor.json"), new Date(Date.now() + 120_000), new Date(Date.now() + 120_000))
floorOf(v, undefined, d, by)
expect(runs).toBe(2)
// an error isn't kept as an answer
utimesSync(v, new Date(Date.now() + 180_000), new Date(Date.now() + 180_000))
out = [{ level: "error", says: "a placeholder brand kit" }]
floorOf(v, undefined, d, by)
utimesSync(path.join(d, "a.floor.json"), new Date(Date.now() + 240_000), new Date(Date.now() + 240_000))
floorOf(v, undefined, d, by)
expect(runs).toBe(4)
rmSync(d, { recursive: true, force: true })
})
test("montage findings are kept: measured again when the video is newer or its beats are others", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-montage-kept-"))
const v = path.join(d, "a.mp4")
writeFileSync(v, "x")
let runs = 0
const by = () => (runs++, [{ level: "warn" as const, kind: "pace" as const, at: 1, says: "long" }])
keptOr(v, "a", by)
expect(keptOr(v, "a", by)).toEqual([{ level: "warn", kind: "pace", at: 1, says: "long" }])
expect(runs).toBe(1)
keptOr(v, "b", by)
expect(runs).toBe(2)
utimesSync(v, new Date(Date.now() + 60_000), new Date(Date.now() + 60_000))
keptOr(v, "b", by)
expect(runs).toBe(3)
rmSync(d, { recursive: true, force: true })
})
+1 -1
View File
@@ -87,7 +87,7 @@ test("a reading kept beside a file isn't the work changing", () => {
const cut = path.join(d, "out/cuts/a_b_c_v1_9x16.mp4")
writeFileSync(cut, "x")
utimesSync(cut, 1000, 1000)
for (const ext of ["words.json", "scene.json", "check.json"]) writeFileSync(path.join(d, `out/cuts/a_b_c_v1_9x16.${ext}`), "{}")
for (const ext of ["words.json", "scene.json", "check.json", "floor.json", "montage.json"]) writeFileSync(path.join(d, `out/cuts/a_b_c_v1_9x16.${ext}`), "{}")
expect(newest(d)).toBe(1_000_000)
writeFileSync(path.join(d, "out/cuts/a_b_c_v1_9x16.render.json"), "{}")
expect(newest(d)!).toBeGreaterThan(1_000_000)