@kriya-ai/harness 2.0.0 → 2.1.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.
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "@kriya-ai/harness-providers",
3
+ "description": "Kriya Harness: Supabase and Render tools through the person's own CLIs; reads free, the one local write approved",
4
+ "version": "0.1.0",
5
+ "private": true,
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "exports": {
9
+ ".": "./index.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "license": "UNLICENSED"
13
+ }
@@ -327,6 +327,16 @@ window.__ModuleLoader__.load({
327
327
  React.Fragment,
328
328
  null,
329
329
  Section("Repository", h(React.Fragment, null, h("div", { className: "kh-tx-row" }, h("b", null, d.repo.state)), h("div", { className: "kh-tx-note", style: { whiteSpace: "pre-line" } }, d.repo.text)), refresh),
330
+ d.workforce &&
331
+ Section(
332
+ "Harness 2.0",
333
+ h(
334
+ React.Fragment,
335
+ null,
336
+ h("div", { className: "kh-tx-row" }, d.workforce.orchestra ? `Orchestra: head ${d.workforce.orchestra.headName ?? d.workforce.orchestra.head}, worker ${d.workforce.orchestra.workerName ?? d.workforce.orchestra.worker}` : "Orchestra: off (one level for everything)"),
337
+ h("div", { className: "kh-tx-grid" }, d.workforce.switches.flatMap((x) => [h("span", { key: `${x.flag}a`, className: "kh-tx-mono" }, x.flag), h("span", { key: `${x.flag}b`, className: x.on ? "" : "kh-tx-note" }, x.on ? "on" : "off")]))
338
+ )
339
+ ),
330
340
  Section("MCP servers", d.mcp.length ? d.mcp.map((m) => h("div", { key: m.id, className: "kh-tx-row" }, m.name)) : h("div", { className: "kh-tx-note" }, "None offered (kriya --mcp, and the owner's registry).")),
331
341
  Section(
332
342
  "What can be checked here",
@@ -8,6 +8,7 @@ import { listCheckpoints, restoreTree, trackedRoot } from "../../src/checkpoints
8
8
  import { gateMatrix } from "../../src/doctor.js"
9
9
  import { liveBuild } from "../../src/loop.js"
10
10
  import { readMilestones } from "../../src/milestones.js"
11
+ import { SWITCHES } from "../../src/modes.js"
11
12
  import { orchestraFromEnv } from "../../src/orchestra.js"
12
13
  import { kriyaHome } from "../../src/paths.js"
13
14
  import { readState } from "../../src/release.js"
@@ -84,6 +85,16 @@ export function spendTracker({ account }) {
84
85
  }
85
86
  }
86
87
 
88
+ /** What this harness was launched with: the head and worker levels (with their models' names) and each switch. */
89
+ export function workforceOf(env = process.env) {
90
+ const o = orchestraFromEnv(env)
91
+ const named = names(env)
92
+ return {
93
+ orchestra: o ? { head: o.head, worker: o.worker, headName: named[o.head] ?? null, workerName: named[o.worker] ?? null } : null,
94
+ switches: SWITCHES.map(([flag, name]) => ({ flag, on: env[name] === "on" })),
95
+ }
96
+ }
97
+
87
98
  /** Ledgers on this computer: ~/.kriya/progress/<project>/milestones.json, each with its project's folder from a session record beside it. */
88
99
  export function ledgers(home = kriyaHome()) {
89
100
  const dir = join(home, "progress")
@@ -215,7 +226,7 @@ export function handlers(host) {
215
226
  (host.matrix ?? gateMatrix)(),
216
227
  (host.mcp ?? (async () => []))().catch(() => []),
217
228
  ])
218
- return { repo, matrix, mcp }
229
+ return { repo, matrix, mcp, workforce: workforceOf(env) }
219
230
  }
220
231
  throw new ChangesError("Which part?")
221
232
  }
package/src/cockpit.js ADDED
@@ -0,0 +1,223 @@
1
+ import { execFile, spawn } from "node:child_process"
2
+ import { appendFileSync, existsSync, readFileSync, realpathSync } from "node:fs"
3
+ import { join, relative, sep } from "node:path"
4
+
5
+ import { confirmedCheck } from "./verify.js"
6
+
7
+ // The Developer tab's data and actions (plugins/cockpit; Kriya-Tavi
8
+ // docs/kriya-harness/DEVELOPER_COCKPIT.md). Connections are each provider's
9
+ // own CLI and the person's own login there: Kriya runs fixed argv (execFile,
10
+ // never a shell), never reads a token or a credential file, and never types a
11
+ // login code. Secrets are found by file name only; no value is read.
12
+
13
+ export class CockpitError extends Error {}
14
+
15
+ // Telemetry off and no prompts for every provider CLI Kriya runs
16
+ const QUIET = { NO_COLOR: "1", DO_NOT_TRACK: "1", RENDER_CLI_DISABLE_ANALYTICS: "1", GH_NO_UPDATE_NOTIFIER: "1", GH_PROMPT_DISABLED: "1", GIT_TERMINAL_PROMPT: "0", SUPABASE_TELEMETRY_DISABLED: "1" }
17
+
18
+ /** argv only, bounded, stdin closed. Resolves { code, stdout, stderr, missing }. */
19
+ export function runner({ env = process.env, timeoutMs = 20_000 } = {}) {
20
+ return (file, args, cwd) =>
21
+ new Promise((done) => {
22
+ const child = execFile(file, args, { cwd, env: { ...env, ...QUIET }, timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024 }, (error, stdout, stderr) =>
23
+ done({ code: error ? (typeof error.code === "number" ? error.code : 1) : 0, stdout: String(stdout ?? ""), stderr: String(stderr ?? ""), missing: error?.code === "ENOENT" })
24
+ )
25
+ child.stdin?.end()
26
+ })
27
+ }
28
+
29
+ /**
30
+ * The providers the Developer tab connects through. `status` exits 0 only when
31
+ * signed in (for Render the docs don't state whoami's exit code, so a non-zero
32
+ * exit reads as "not signed in or not checked"). `login` is what the person
33
+ * runs; GitHub's is also one click (githubSignIn).
34
+ */
35
+ export const PROVIDERS = [
36
+ { id: "github", name: "GitHub", cli: "gh", version: ["--version"], status: ["auth", "status", "--hostname", "github.com"], login: "gh auth login", install: "brew install gh", docs: "https://cli.github.com" },
37
+ { id: "supabase", name: "Supabase", cli: "supabase", version: ["--version"], status: ["projects", "list", "-o", "json"], login: "supabase login", install: "brew install supabase/tap/supabase", docs: "https://supabase.com/docs/guides/cli" },
38
+ { id: "render", name: "Render", cli: "render", version: ["--version"], status: ["whoami", "-o", "json"], login: "render login", install: "brew install render", docs: "https://render.com/docs/cli" },
39
+ { id: "vercel", name: "Vercel", cli: "vercel", version: ["--version"], status: ["whoami"], login: "vercel login", install: "npm install -g vercel", docs: "https://vercel.com/docs/cli" },
40
+ ]
41
+
42
+ /** "gh version 2.103.3 (2026-10-26)" → "2.103.3" */
43
+ export const versionOf = (text) => /\b(\d+\.\d+(?:\.\d+)?)\b/.exec(String(text ?? ""))?.[1] ?? null
44
+
45
+ /** One provider's state: installed, its version, signed in (true, false), and GitHub's account name */
46
+ export async function connection(provider, run = runner()) {
47
+ const base = { id: provider.id, name: provider.name, cli: provider.cli, login: provider.login, install: provider.install, docs: provider.docs }
48
+ const v = await run(provider.cli, provider.version)
49
+ if (v.missing) return { ...base, installed: false, signedIn: false }
50
+ const s = await run(provider.cli, provider.status)
51
+ const signedIn = s.code === 0
52
+ // gh says "Logged in to github.com account <name>"; the other CLIs' account isn't parsed
53
+ const account = provider.id === "github" && signedIn ? /account\s+([A-Za-z0-9-]{1,39})\b/.exec(`${s.stdout}\n${s.stderr}`)?.[1] ?? null : null
54
+ return { ...base, installed: true, version: versionOf(v.stdout || v.stderr), signedIn, ...(account && { account }) }
55
+ }
56
+
57
+ export const connections = (run = runner()) => Promise.all(PROVIDERS.map((p) => connection(p, run)))
58
+
59
+ /**
60
+ * GitHub's one-click sign-in: `gh auth login --web`, whose one-time code the
61
+ * person enters on github.com in their browser (gh opens it). Kriya only shows
62
+ * the code gh prints for that purpose; the token stays in gh's own store.
63
+ * One at a time.
64
+ */
65
+ export function githubSignIn({ spawnImpl = spawn, env = process.env } = {}) {
66
+ let current = null
67
+ return {
68
+ // The code only while the person still needs it
69
+ state: () => (current ? { status: current.status, ...(current.status === "waiting" && { code: current.code }), ...(current.error && { error: current.error }) } : { status: "idle" }),
70
+ start() {
71
+ if (current?.status === "waiting" || current?.status === "starting") return this.state()
72
+ const child = spawnImpl("gh", ["auth", "login", "--web", "--hostname", "github.com", "--git-protocol", "https", "--skip-ssh-key"], {
73
+ env: { ...env, NO_COLOR: "1", GH_NO_UPDATE_NOTIFIER: "1" },
74
+ stdio: ["pipe", "pipe", "pipe"],
75
+ })
76
+ const run = { status: "starting", code: null, error: null, child }
77
+ current = run
78
+ let seen = ""
79
+ const read = (chunk) => {
80
+ seen = (seen + chunk).slice(-4000)
81
+ const code = /one-time code:\s*([A-Z0-9]{4}-[A-Z0-9]{4})/.exec(seen)?.[1]
82
+ if (code && !run.code) {
83
+ run.code = code
84
+ run.status = "waiting"
85
+ // gh waits for Enter before it opens the browser
86
+ child.stdin?.write("\n")
87
+ }
88
+ }
89
+ child.stdout?.on("data", read)
90
+ child.stderr?.on("data", read)
91
+ child.on("error", (e) => Object.assign(run, { status: "failed", error: e.code === "ENOENT" ? "The GitHub CLI (gh) isn't installed." : "gh couldn't start." }))
92
+ child.on("close", (exit) => {
93
+ if (run.status === "failed") return
94
+ Object.assign(run, exit === 0 ? { status: "done" } : { status: "failed", error: "GitHub sign-in didn't finish. Try again, or run gh auth login in a terminal." })
95
+ })
96
+ const timer = setTimeout(() => run.status === "waiting" || run.status === "starting" ? (child.kill("SIGTERM"), Object.assign(run, { status: "failed", error: "GitHub sign-in timed out after 10 minutes." })) : null, 10 * 60_000)
97
+ timer.unref?.()
98
+ return this.state()
99
+ },
100
+ cancel() {
101
+ if (current && (current.status === "waiting" || current.status === "starting")) {
102
+ current.child.kill("SIGTERM")
103
+ Object.assign(current, { status: "failed", error: "Canceled." })
104
+ }
105
+ return this.state()
106
+ },
107
+ }
108
+ }
109
+
110
+ /* ─────────────────────────── running servers ─────────────────────────── */
111
+
112
+ const inside = (root, path) => {
113
+ const rel = relative(root, path)
114
+ return rel === "" || (!rel.startsWith("..") && !rel.startsWith(sep) && !/^[A-Za-z]:/.test(rel))
115
+ }
116
+
117
+ /** lsof -F output → [{ pid, command, ports }] for listening TCP sockets */
118
+ export function parseListeners(text) {
119
+ const byPid = new Map()
120
+ let cur = null
121
+ for (const line of String(text ?? "").split("\n")) {
122
+ const tag = line[0]
123
+ const value = line.slice(1)
124
+ if (tag === "p") {
125
+ const pid = Number(value)
126
+ cur = byPid.get(pid) ?? { pid, command: "", ports: [] }
127
+ byPid.set(pid, cur)
128
+ } else if (tag === "c" && cur) cur.command = value.slice(0, 60)
129
+ else if (tag === "n" && cur) {
130
+ const port = Number(/:(\d+)$/.exec(value)?.[1])
131
+ if (Number.isInteger(port) && port > 0 && !cur.ports.includes(port)) cur.ports.push(port)
132
+ }
133
+ }
134
+ return [...byPid.values()].filter((p) => Number.isInteger(p.pid) && p.pid > 0 && p.ports.length)
135
+ }
136
+
137
+ /** Servers listening on TCP whose working folder is inside the project; never this process or its parent */
138
+ export async function servers(folder, run = runner({ timeoutMs: 10_000 })) {
139
+ let root
140
+ try {
141
+ root = realpathSync(folder)
142
+ } catch {
143
+ return { available: true, list: [] }
144
+ }
145
+ const all = await run("lsof", ["-nP", "-iTCP", "-sTCP:LISTEN", "-Fpcn"])
146
+ if (all.missing) return { available: false, list: [] }
147
+ const list = []
148
+ for (const p of parseListeners(all.stdout)) {
149
+ if (p.pid === process.pid || p.pid === process.ppid) continue
150
+ const cwd = /^n(.+)$/m.exec((await run("lsof", ["-a", "-p", String(p.pid), "-d", "cwd", "-Fn"])).stdout)?.[1]
151
+ if (!cwd) continue
152
+ let real
153
+ try {
154
+ real = realpathSync(cwd)
155
+ } catch {
156
+ continue
157
+ }
158
+ if (inside(root, real)) list.push({ ...p, ports: p.ports.sort((a, b) => a - b).slice(0, 8), folder: relative(root, real) || "." })
159
+ }
160
+ return { available: true, list: list.slice(0, 20) }
161
+ }
162
+
163
+ /** Stops one listed server: only a pid the current list shows for this project */
164
+ export async function stopServer(folder, pid, run, kill = process.kill.bind(process)) {
165
+ const { list } = await servers(folder, run)
166
+ if (!list.some((s) => s.pid === pid)) throw new CockpitError("That server isn't running in this project any more.")
167
+ kill(pid, "SIGTERM")
168
+ return { stopped: pid }
169
+ }
170
+
171
+ /* ─────────────────────────── project health ─────────────────────────── */
172
+
173
+ const ENV_FILE = /(^|\/)\.env(\.[^/]*)?$/
174
+ const ENV_OK = /(^|\/)\.env\.(example|sample|template)$/
175
+ const KEY_FILE = /\.(pem|key|p12|pfx)$/
176
+
177
+ const readJson = (file) => {
178
+ try {
179
+ return JSON.parse(readFileSync(file, "utf8"))
180
+ } catch {
181
+ return null
182
+ }
183
+ }
184
+
185
+ /** What the project is, how it's checked, and secret files git would expose (names only) */
186
+ export async function health(folder, run = runner()) {
187
+ const has = (f) => existsSync(join(folder, f))
188
+ const pkg = has("package.json") ? readJson(join(folder, "package.json")) : null
189
+ const manager = has("pnpm-lock.yaml") ? "pnpm" : has("yarn.lock") ? "yarn" : has("bun.lockb") || has("bun.lock") ? "bun" : pkg ? "npm" : null
190
+ const stack = [
191
+ pkg && { id: "node", label: `Node.js${manager ? ` · ${manager}` : ""}` },
192
+ (has("pyproject.toml") || has("requirements.txt")) && { id: "python", label: "Python" },
193
+ has("go.mod") && { id: "go", label: "Go" },
194
+ has("Cargo.toml") && { id: "rust", label: "Rust" },
195
+ has("supabase/config.toml") && { id: "supabase", label: "Supabase project" },
196
+ has("render.yaml") && { id: "render", label: "Render blueprint" },
197
+ (has("vercel.json") || has(".vercel")) && { id: "vercel", label: "Vercel project" },
198
+ ].filter(Boolean)
199
+ const scripts = pkg?.scripts && typeof pkg.scripts === "object" ? ["dev", "build", "test", "lint", "start"].filter((s) => typeof pkg.scripts[s] === "string") : []
200
+ const check = confirmedCheck(folder)
201
+ const git = await run("git", ["-C", folder, "rev-parse", "--show-toplevel"])
202
+ if (git.code !== 0) return { stack, scripts, check: check?.command ?? null, git: false, tracked: [], unignored: [] }
203
+ const root = git.stdout.trim()
204
+ const list = async (args) => (await run("git", ["-C", root, ...args])).stdout.split("\0").filter(Boolean)
205
+ const secret = (f) => (ENV_FILE.test(f) && !ENV_OK.test(f)) || KEY_FILE.test(f)
206
+ const tracked = (await list(["ls-files", "-z"])).filter(secret).slice(0, 20)
207
+ const unignored = (await list(["ls-files", "--others", "--exclude-standard", "-z"])).filter(secret).slice(0, 20)
208
+ return { stack, scripts, check: check?.command ?? null, git: true, tracked, unignored }
209
+ }
210
+
211
+ /** Adds the named, not-yet-ignored secret files to .gitignore (the person clicked it); only files health() listed */
212
+ export async function ignoreSecrets(folder, files, run = runner()) {
213
+ const { git, unignored } = await health(folder, run)
214
+ if (!git) throw new CockpitError("This folder isn't a git repository.")
215
+ const wanted = (Array.isArray(files) ? files : []).filter((f) => unignored.includes(f))
216
+ if (!wanted.length) throw new CockpitError("Those files are already ignored, or aren't secret files here.")
217
+ const root = (await run("git", ["-C", folder, "rev-parse", "--show-toplevel"])).stdout.trim()
218
+ const file = join(root, ".gitignore")
219
+ const current = existsSync(file) ? readFileSync(file, "utf8") : ""
220
+ const lines = wanted.map((f) => `/${f}`).filter((l) => !current.split("\n").includes(l))
221
+ if (lines.length) appendFileSync(file, `${current && !current.endsWith("\n") ? "\n" : ""}# Secrets (added by Kriya Harness)\n${lines.join("\n")}\n`)
222
+ return { added: lines }
223
+ }
package/src/daemon.js CHANGED
@@ -8,6 +8,7 @@ import { gzipSync } from "node:zlib"
8
8
  import { BASE_PATH, call, KriyaError, models } from "./api.js"
9
9
  import { doctor } from "./doctor.js"
10
10
  import { CLIENT_VERSION, kriyaHome } from "./paths.js"
11
+ import { baseline, changesSince } from "./proof.js"
11
12
  import { confirmRule, dismissRule, listRules } from "./rules.js"
12
13
 
13
14
  // `kriya daemon` (the Control Center, CONTROL_CENTER.md in the Kriya
@@ -294,8 +295,12 @@ export async function runDaemon(options) {
294
295
  if (running.size >= MAX_RUNNING) return refuse(`This computer is already running ${MAX_RUNNING} tasks from Kriya.`)
295
296
  await report(id, "running")
296
297
  log(`kriya daemon: task in ${folder.shown} (${payload.mode})`)
297
- const flow = payload.plan || payload.profile ? mkdtempSync(join(tmpdir(), "kriya-flow-")) : null
298
+ // S-3: Kriya asked for the proof card (harness.taskProof): live steps, the verdict, changed files
299
+ const proofOn = payload.proof === true
300
+ const flow = payload.plan || payload.profile || proofOn ? mkdtempSync(join(tmpdir(), "kriya-flow-")) : null
298
301
  const env = flow ? flowEnv(payload, flow) : {}
302
+ if (proofOn) Object.assign(env, { KRIYA_TASK_PROOF: "on", KRIYA_PROGRESS_FILE: env.KRIYA_PROGRESS_FILE ?? join(flow, "progress.json") })
303
+ const base = proofOn ? await baseline(folder.path) : null
299
304
  let sent = ""
300
305
  const beat = () => {
301
306
  const seen = env.KRIYA_PROGRESS_FILE && readProgressFile(env.KRIYA_PROGRESS_FILE)
@@ -308,6 +313,7 @@ export async function runDaemon(options) {
308
313
  const r = await child(id, runArgs(payload), folder.path, env)
309
314
  clearInterval(reporting)
310
315
  const progress = env.KRIYA_PROGRESS_FILE ? readProgressFile(env.KRIYA_PROGRESS_FILE) : null
316
+ const changes = proofOn ? await changesSince(base) : null
311
317
  if (flow) rmSync(flow, { recursive: true, force: true })
312
318
  const stopped = r.canceled
313
319
  // The answer on success; on failure the last error lines too (DSH writes the reason to stderr)
@@ -316,7 +322,8 @@ export async function runDaemon(options) {
316
322
  .filter((line) => line.trim() && !/^(dsh: warning: \d+ entries did not activate|kriya-[\w-]+ \(@kriya-ai\/[\w-]+\): pending)/.test(line))
317
323
  .join("\n")
318
324
  const answer = r.code === 0 ? r.out.trim() || errors : [r.out.trim(), errors].filter(Boolean).join("\n\n")
319
- return report(id, stopped ? "canceled" : r.code === 0 ? "done" : "failed", { exitCode: r.code, answer: tail(answer), ...(progress && { plan: progress.plan }) })
325
+ const proof = proofOn ? { ...(progress?.proof ?? {}), ...(changes && { changes }) } : null
326
+ return report(id, stopped ? "canceled" : r.code === 0 ? "done" : "failed", { exitCode: r.code, answer: tail(answer), ...(progress?.plan && { plan: progress.plan }), ...(proof && { proof }) })
320
327
  }
321
328
  if (kind === "edit") {
322
329
  if (!capabilities.edit) return report(id, "failed", { code: "not_allowed" })
@@ -77,7 +77,11 @@ export async function ensureHost({ env = process.env, home = kriyaHome(), stamp
77
77
 
78
78
  /** Stops the Host and waits until it's gone. */
79
79
  export async function stopHost(home = kriyaHome()) {
80
+ const live = await contact(home)
80
81
  await hostCall(home, "POST", "/internal/stop").catch(() => null)
81
82
  const started = Date.now()
82
83
  while ((await contact(home)) && Date.now() - started < START_MS) await new Promise((done) => setTimeout(done, 25))
84
+ // The Host closes its channel first, then removes its token, socket and lock and exits: until the
85
+ // process is gone a caller could still read the old token (found on CI, edit-tp11)
86
+ if (live?.pid) await gone(live.pid)
83
87
  }
@@ -32,7 +32,8 @@ const unavailable = (message) => {
32
32
  /**
33
33
  * @param {{ db: ReturnType<import("./db.js").openIndexDb>, cache: string, binDir: string, language?: string, run?: typeof runTool, runtime?: () => object | null, acquire?: (resources: string[], signal?: AbortSignal) => Promise<() => void> }} options
34
34
  */
35
- export function createIndexer({ db, cache, binDir, language = "en", run = runTool, runtime = () => activeRuntime(), acquire = async () => () => {} }) {
35
+ // platform: which face helper this system has (faces.js); a parameter so tests that fake every tool can say which system they fake
36
+ export function createIndexer({ db, cache, binDir, language = "en", run = runTool, runtime = () => activeRuntime(), acquire = async () => () => {}, platform = process.platform }) {
36
37
  const layers = {
37
38
  L0: {
38
39
  version: PROBE_VERSION,
@@ -138,7 +139,7 @@ export function createIndexer({ db, cache, binDir, language = "en", run = runToo
138
139
  needs: ["L6"],
139
140
  async run({ path, facts, signal, fingerprint }) {
140
141
  if (!facts.width) unavailable("This file has no picture.")
141
- const helper = await faceHelper(binDir, run)
142
+ const helper = await faceHelper(binDir, run, platform)
142
143
  if (helper.missing) unavailable(helper.missing)
143
144
  const folder = join(cache, "faces", fingerprint)
144
145
  rmSync(folder, { recursive: true, force: true })
@@ -26,11 +26,17 @@ export const CEILINGS = Object.freeze({
26
26
  /** Each viewport, its device pixel ratio (above every cap, so an uncapped ratio shows) and the tier it is judged against. */
27
27
  export const VIEWPORTS_3D = Object.freeze([
28
28
  Object.freeze({ name: "390", width: 390, height: 844, dpr: 3, tiers: ["low", "mid", "high"] }),
29
- Object.freeze({ name: "1440", width: 1440, height: 900, dpr: 3, tiers: ["high", "mid", "low"] }),
29
+ // DPR 2, not 3: a 4,320 px software-rendered buffer (CI has no GPU) costs minutes and shows nothing DPR 2 doesn't
30
+ Object.freeze({ name: "1440", width: 1440, height: 900, dpr: 2, tiers: ["high", "mid", "low"] }),
30
31
  ])
31
32
  export const FRAMES = 120
32
33
  export const LEAK_SLACK = 0.05
33
- const FRAME_WAIT_MS = 8_000
34
+ // Each wait for frames is bounded by wall time: on a software renderer (no GPU, as on CI) a heavy scene
35
+ // draws a few frames a second, so the gate measures the frames that came instead of waiting for 120
36
+ const FRAME_WAIT_MS = 3_000
37
+ const SHOT_MS = 10_000
38
+ /** The whole gate's time budget: what isn't checked by then is reported not checked, never passed */
39
+ export const GATE_MS = 60_000
34
40
  const NAV_MS = 30_000
35
41
  const RESTORE_WAIT_MS = 2_000
36
42
  const DIRECTION = "scene_direction.json"
@@ -165,6 +171,7 @@ export const WRAP = `(() => {
165
171
  raf(tick)
166
172
  let lost = null
167
173
  const read = (action) => {
174
+ if (action === "frames") return frames.length
168
175
  const live = contexts.filter((c) => !c.gl.isContextLost())
169
176
  if (action === "lose") {
170
177
  const c = live.filter((x) => x.canvas.isConnected).sort((a, b) => b.canvas.clientWidth * b.canvas.clientHeight - a.canvas.clientWidth * a.canvas.clientHeight)[0]
@@ -260,13 +267,13 @@ const evidenceDir = (root, label) =>
260
267
  * given (tests); otherwise the stack's app and the project's scene_direction.json.
261
268
  * @returns {Promise<{ id: "G-3D", status: "pass" | "fail" | "not_checked", reason?: string, kind?: string, excerpt?: string, note?: string, optional?: true, report?: any }>}
262
269
  */
263
- export async function threeGate({ root, label, launch, app: givenApp, direction: givenDirection }) {
270
+ export async function threeGate({ root, label, launch, app: givenApp, direction: givenDirection, budgetMs }) {
264
271
  const app = givenApp ?? readStack(root).app
265
272
  if (!app) return { id: "G-3D", status: "not_checked", reason: "no app is confirmed for this project (kriya stack use --app http://localhost:<port>)", optional: true }
266
273
  const direction = givenDirection ?? readDirection(root)
267
274
  if (!direction) return { id: "G-3D", status: "not_checked", reason: `no ${DIRECTION} with routes in .kriya/contracts (the designer step writes it)`, optional: true }
268
275
  const dir = evidenceDir(root, label)
269
- const run = await withGateBrowser((_open, browser) => checkScenes(browser, app, direction, dir), { launch })
276
+ const run = await withGateBrowser((_open, browser) => checkScenes(browser, app, direction, dir, budgetMs ? { budgetMs } : {}), { launch })
270
277
  if (run.unavailable) return { id: "G-3D", status: "not_checked", reason: run.unavailable }
271
278
  return run.value
272
279
  }
@@ -296,19 +303,23 @@ async function openPage(browser, url, { viewport, reducedMotion = "no-preference
296
303
  }
297
304
  const read = (action) => page.evaluate(({ name, action }) => window[name]?.(action), { name: READ, action })
298
305
  const framesFrom = async (from, n = FRAMES) => {
299
- await page.waitForFunction(({ name, want }) => (window[name]?.().frames ?? 0) >= want, { name: READ, want: from + n }, { timeout: FRAME_WAIT_MS, polling: 50 }).catch(() => {})
306
+ await page.waitForFunction(({ name, want }) => (window[name]?.("frames") ?? 0) >= want, { name: READ, want: from + n }, { timeout: FRAME_WAIT_MS, polling: 50 }).catch(() => {})
300
307
  return read()
301
308
  }
302
309
  const shot = async () => {
303
310
  const canvas = page.locator("canvas").first()
304
311
  if (!(await canvas.count())) return null
305
- return canvas.screenshot({ timeout: 5_000 }).catch(() => null)
312
+ return canvas.screenshot({ timeout: SHOT_MS }).catch(() => null)
306
313
  }
307
314
  return { page, context, read, framesFrom, shot, consoleErrors, bytes: () => bytes, started }
308
315
  }
309
316
 
310
- async function checkScenes(browser, app, direction, dir) {
317
+ async function checkScenes(browser, app, direction, dir, { budgetMs = GATE_MS } = {}) {
318
+ const deadline = Date.now() + budgetMs
319
+ const late = () => Date.now() > deadline
311
320
  const problems = []
321
+ // Checks that couldn't be made here (e.g. a screenshot that timed out): never a pass, never a made-up failure
322
+ const unknown = []
312
323
  const reported = []
313
324
  const motion = direction.motion ?? "none"
314
325
  // Does this browser make WebGL at all? Otherwise not_checked, never pass
@@ -321,6 +332,10 @@ async function checkScenes(browser, app, direction, dir) {
321
332
  for (const route of direction.routes)
322
333
  for (const viewport of VIEWPORTS_3D) {
323
334
  const at = `${route.path} at ${viewport.name}px`
335
+ if (late()) {
336
+ unknown.push(`${at}: not reached within the gate's ${budgetMs / 1000} s budget (the scene draws slowly here)`)
337
+ continue
338
+ }
324
339
  const budget = budgetFor(direction.tiers, viewport.tiers)
325
340
  const v = await openPage(browser, new URL(route.path, app).href, { viewport })
326
341
  if (v.unreachable) return { id: "G-3D", status: "not_checked", reason: `${app}${route.path} doesn't answer (${v.unreachable})` }
@@ -341,7 +356,8 @@ async function checkScenes(browser, app, direction, dir) {
341
356
  keepShot(dir, `${route.path.replace(/\W+/g, "_") || "root"}-${viewport.name}-f90.png`, b)
342
357
  if (v.consoleErrors.length) problems.push(`${at}: console errors (shader compile and link failures are logged here): ${v.consoleErrors.slice(0, 3).join(" | ")}`)
343
358
  if (r.errors) problems.push(`${at}: ${r.errors} WebGL error${r.errors === 1 ? "" : "s"} (gl.getError) while drawing`)
344
- if (blank(lookB)) problems.push(`${at}: the canvas is blank or one colour (${lookB ? `${lookB.colours} colours` : "no screenshot"}); check the shader, the camera and the light`)
359
+ if (!lookA || !lookB) unknown.push(`${at}: the canvas couldn't be captured to check it draws`)
360
+ else if (blank(lookB)) problems.push(`${at}: the canvas is blank or one colour (${lookB.colours} colours); check the shader, the camera and the light`)
345
361
  else if (motion !== "none" && moved(lookA, lookB) === 0) problems.push(`${at}: motion is "${motion}" in the direction, but frame 30 and frame 90 are identical`)
346
362
  const recent = r.recent ?? []
347
363
  const drawCalls = median(recent.map((f) => f.draws))
@@ -354,8 +370,12 @@ async function checkScenes(browser, app, direction, dir) {
354
370
  if (sizing) problems.push(`${at}: ${sizing}`)
355
371
  const deltas = recent.map((f) => f.ms).filter((ms) => ms > 0 && ms < 1000)
356
372
  reported.push(`${at}: ${drawCalls} draws, ${Math.round(tris)} triangles, ${mb(r.textureBytes)} textures, frame ${median(deltas).toFixed(1)} ms median / ${p95(deltas).toFixed(1)} ms p95 (reported, not gated)`)
357
- // The deeper checks once per route, at the phone width
373
+ // The deeper checks once per route, at the phone width, while the budget lasts
358
374
  if (viewport !== VIEWPORTS_3D[0]) continue
375
+ if (late()) {
376
+ unknown.push(`${at}: resize, leak and context-loss checks not reached within the gate's ${budgetMs / 1000} s budget`)
377
+ continue
378
+ }
359
379
  // Resize: the buffer follows the new CSS size
360
380
  await v.page.setViewportSize({ width: viewport.width - 60, height: viewport.height - 100 })
361
381
  const resized = await v.framesFrom((await v.read()).frames, 20)
@@ -379,13 +399,15 @@ async function checkScenes(browser, app, direction, dir) {
379
399
  await v.page.waitForTimeout(RESTORE_WAIT_MS)
380
400
  const after = await v.read()
381
401
  const look = canvasLook(await v.shot())
382
- if (after.canvas?.lost || blank(look)) problems.push(`${at}: after a lost and restored WebGL context the canvas stays ${after.canvas?.lost ? "lost" : "blank"}; prevent default on webglcontextlost and rebuild on webglcontextrestored`)
402
+ if (!after.canvas?.lost && !look) unknown.push(`${at}: the canvas couldn't be captured after a restored context`)
403
+ else if (after.canvas?.lost || blank(look)) problems.push(`${at}: after a lost and restored WebGL context the canvas stays ${after.canvas?.lost ? "lost" : "blank"}; prevent default on webglcontextlost and rebuild on webglcontextrestored`)
383
404
  } else reported.push(`${at}: context loss not checked (no WEBGL_lose_context)`)
384
405
  } finally {
385
406
  await v.context.close().catch(() => {})
386
407
  }
387
408
  // Reduced motion: decorative motion stops
388
- if (motion !== "none" && viewport === VIEWPORTS_3D[0]) {
409
+ if (motion !== "none" && viewport === VIEWPORTS_3D[0] && late()) unknown.push(`${at}: reduced motion not checked within the gate's ${budgetMs / 1000} s budget`)
410
+ else if (motion !== "none" && viewport === VIEWPORTS_3D[0]) {
389
411
  const q = await openPage(browser, new URL(route.path, app).href, { viewport, reducedMotion: "reduce" })
390
412
  if (!q.unreachable)
391
413
  try {
@@ -393,14 +415,16 @@ async function checkScenes(browser, app, direction, dir) {
393
415
  const a = canvasLook(await q.shot())
394
416
  await q.framesFrom((await q.read()).frames, 60)
395
417
  const b = canvasLook(await q.shot())
396
- if (moved(a, b) > 0) problems.push(`${at}: decorative motion still runs under prefers-reduced-motion`)
418
+ if (!a || !b) unknown.push(`${at}: the canvas couldn't be captured under reduced motion`)
419
+ else if (moved(a, b) > 0) problems.push(`${at}: decorative motion still runs under prefers-reduced-motion`)
397
420
  } finally {
398
421
  await q.context.close().catch(() => {})
399
422
  }
400
423
  }
401
424
  }
402
- const note = [`renderer: ${renderer ?? "unknown"}`, ...reported].join("\n")
425
+ const note = [`renderer: ${renderer ?? "unknown"}`, ...reported, ...unknown.map((u) => `not checked: ${u}`)].join("\n")
403
426
  if (problems.length) return { id: "G-3D", status: "fail", kind: "gate", excerpt: `G-3D:\n${problems.slice(0, 12).map((p) => `- ${p}`).join("\n")}${problems.length > 12 ? `\n- … and ${problems.length - 12} more` : ""}\n(${note.split("\n")[0]})`, note }
427
+ if (unknown.length) return { id: "G-3D", status: "not_checked", reason: unknown[0], note }
404
428
  return { id: "G-3D", status: "pass", note }
405
429
  }
406
430