@kriya-ai/harness 0.2.4 → 2.0.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 (134) hide show
  1. package/RELEASE_NOTES.md +121 -0
  2. package/SAFETY.md +181 -0
  3. package/THIRD_PARTY_NOTICES.md +113 -0
  4. package/bin/kriya.js +188 -2
  5. package/bundle/cordis.patch.yml +49 -0
  6. package/contract/SOURCE.md +3 -3
  7. package/contract/contract.json +504 -3
  8. package/contract/schemas/api.json +64 -0
  9. package/contract/schemas/auth_matrix.json +44 -0
  10. package/contract/schemas/component_states.json +33 -0
  11. package/contract/schemas/design_tokens.json +34 -0
  12. package/contract/schemas/scene_direction.json +82 -0
  13. package/contract/schemas/threat_model.json +44 -0
  14. package/package.json +2 -1
  15. package/plugins/changes/client.js +5 -3
  16. package/plugins/deploy/index.js +215 -0
  17. package/plugins/deploy/package.json +13 -0
  18. package/plugins/grounding/index.js +81 -0
  19. package/plugins/grounding/lookup.js +373 -0
  20. package/plugins/grounding/package.json +13 -0
  21. package/plugins/kriya-tools/index.js +2 -1
  22. package/plugins/loop/index.js +376 -10
  23. package/plugins/mcp/index.js +79 -0
  24. package/plugins/mcp/package.json +13 -0
  25. package/plugins/mirror/index.js +17 -0
  26. package/plugins/overview/client.js +5 -2
  27. package/plugins/preview/client.js +12 -6
  28. package/plugins/progress/client.js +7 -4
  29. package/plugins/repo/index.js +230 -0
  30. package/plugins/repo/package.json +13 -0
  31. package/plugins/repo/repo.js +348 -0
  32. package/plugins/runstrip/client.js +426 -0
  33. package/plugins/runstrip/index.js +301 -0
  34. package/plugins/runstrip/package.json +23 -0
  35. package/src/cartridges.js +133 -0
  36. package/src/contracts.js +130 -0
  37. package/src/critic.js +78 -0
  38. package/src/daemon.js +7 -1
  39. package/src/doctor.js +67 -0
  40. package/src/edit/core/effects.js +185 -0
  41. package/src/edit/core/ffmpeg.js +82 -5
  42. package/src/edit/core/layout.js +46 -1
  43. package/src/edit/core/ops.js +175 -3
  44. package/src/edit/core/plan.js +95 -9
  45. package/src/edit/core/project.d.ts +24 -0
  46. package/src/edit/core/project.js +64 -0
  47. package/src/edit/core/solver.js +34 -6
  48. package/src/edit/core/style-brief.js +211 -0
  49. package/src/edit/core/style-packs.js +57 -0
  50. package/src/edit/core/transitions.js +17 -0
  51. package/src/edit/core/type-kit.js +173 -0
  52. package/src/edit/director/ask.js +37 -3
  53. package/src/edit/director/assembly.js +829 -0
  54. package/src/edit/director/continuity.js +137 -0
  55. package/src/edit/director/custom-motion.js +88 -0
  56. package/src/edit/director/graphics.js +186 -0
  57. package/src/edit/director/intent.js +125 -0
  58. package/src/edit/director/mentions.js +52 -0
  59. package/src/edit/director/plan.js +89 -12
  60. package/src/edit/director/revise.js +172 -7
  61. package/src/edit/director/viewer.js +136 -0
  62. package/src/edit/director/watch-fix.js +119 -0
  63. package/src/edit/engine/captions.js +110 -5
  64. package/src/edit/engine/confine.js +81 -4
  65. package/src/edit/engine/custom.js +243 -0
  66. package/src/edit/engine/dna2.js +893 -0
  67. package/src/edit/engine/fonts.js +218 -0
  68. package/src/edit/engine/graphics.js +439 -0
  69. package/src/edit/engine/index.js +14 -5
  70. package/src/edit/engine/motion.js +153 -14
  71. package/src/edit/engine/music-bed.js +59 -1
  72. package/src/edit/engine/packs.js +11 -0
  73. package/src/edit/engine/reference2.js +26 -0
  74. package/src/edit/engine/sfx.js +56 -1
  75. package/src/edit/engine/tool.js +21 -5
  76. package/src/edit/gates/assembly.js +194 -0
  77. package/src/edit/gates/copy.js +7 -4
  78. package/src/edit/gates/index.js +76 -8
  79. package/src/edit/gates/picture.js +6 -3
  80. package/src/edit/gates/reference.js +115 -0
  81. package/src/edit/gates/tile.js +96 -0
  82. package/src/edit/host/client.js +4 -3
  83. package/src/edit/host/clips.js +33 -0
  84. package/src/edit/host/jobs.js +9 -3
  85. package/src/edit/host/layers.js +134 -0
  86. package/src/edit/host/main.js +17 -7
  87. package/src/edit/host/paths.js +34 -3
  88. package/src/edit/host/preview.js +108 -0
  89. package/src/edit/host/projects.js +494 -29
  90. package/src/edit/host/server.js +263 -19
  91. package/src/edit/host/tavi.js +77 -0
  92. package/src/edit/loop/make.js +44 -3
  93. package/src/edit/recipes/assembly.js +352 -0
  94. package/src/edit/recipes/graphic-clips.js +59 -0
  95. package/src/edit/recipes/openings.js +36 -0
  96. package/src/edit/recipes/reel.js +138 -17
  97. package/src/edit/recipes/reference-look.js +29 -0
  98. package/src/edit/recipes/short-from-long.js +3 -3
  99. package/src/edit/recipes/sound.js +71 -0
  100. package/src/edit/runtime/cli.js +26 -5
  101. package/src/edit/runtime/fetch.js +4 -3
  102. package/src/edit/runtime/licences.js +7 -1
  103. package/src/explore.js +103 -0
  104. package/src/failure.js +1 -1
  105. package/src/gate-commands.js +114 -0
  106. package/src/gates/api.js +127 -0
  107. package/src/gates/commands.js +111 -0
  108. package/src/gates/detectors.js +370 -0
  109. package/src/gates/http.js +62 -0
  110. package/src/gates/index.js +196 -0
  111. package/src/gates/page.js +264 -0
  112. package/src/gates/sast.js +64 -0
  113. package/src/gates/stack.js +110 -0
  114. package/src/gates/tenant.js +162 -0
  115. package/src/gates/three.js +407 -0
  116. package/src/gates/ui.js +111 -0
  117. package/src/launch.js +15 -3
  118. package/src/loop.js +199 -7
  119. package/src/mcp.js +126 -0
  120. package/src/milestones.js +188 -0
  121. package/src/modes.js +32 -0
  122. package/src/orchestra.js +43 -0
  123. package/src/outcomes.js +88 -0
  124. package/src/profiles.js +5 -0
  125. package/src/receipts.js +238 -0
  126. package/src/release.js +356 -0
  127. package/src/runstrip.js +122 -0
  128. package/src/stack.js +120 -0
  129. package/src/verify.js +67 -20
  130. package/studio/dist/fonts/fraunces.woff2 +0 -0
  131. package/studio/dist/fonts/geist.woff2 +0 -0
  132. package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
  133. package/studio/dist/studio.css +452 -3
  134. package/studio/dist/studio.js +3 -3
@@ -0,0 +1,407 @@
1
+ import { createHash } from "node:crypto"
2
+ import { existsSync, readFileSync } from "node:fs"
3
+ import { join } from "node:path"
4
+
5
+ import { localUrl } from "../browser.js"
6
+ import { CONTRACTS_DIR } from "../contracts.js"
7
+ import { kriyaHome } from "../paths.js"
8
+ import { readStack } from "../stack.js"
9
+ import { decodePng, keepShot, withGateBrowser } from "./page.js"
10
+
11
+ // Harness 2.0 W13 (WD-17): G-3D (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
12
+ // THREE_D_AND_CREATIVE.md §4). Every number comes from an init script on the
13
+ // gate's own page that wraps HTMLCanvasElement.prototype.getContext before
14
+ // the app runs, so each WebGL context the page creates is counted by the gate,
15
+ // never reported by the app (it can't flatter them). The counts live in a
16
+ // closure, read through a non-writable, non-configurable function. Frame
17
+ // time is reported with the renderer string and never gated: headless Chrome
18
+ // may render on a software path that says nothing about a phone's GPU.
19
+
20
+ /** Code ceilings per tier; scene_direction.json can only tighten them. */
21
+ export const CEILINGS = Object.freeze({
22
+ low: Object.freeze({ drawCalls: 100, triangles: 300_000, textureBytes: 64 * 2 ** 20, routeBytes: 8 * 2 ** 20, dpr: 1.5 }),
23
+ mid: Object.freeze({ drawCalls: 300, triangles: 1_000_000, textureBytes: 256 * 2 ** 20, routeBytes: 16 * 2 ** 20, dpr: 2 }),
24
+ high: Object.freeze({ drawCalls: 1000, triangles: 3_000_000, textureBytes: 512 * 2 ** 20, routeBytes: 32 * 2 ** 20, dpr: 2 }),
25
+ })
26
+ /** Each viewport, its device pixel ratio (above every cap, so an uncapped ratio shows) and the tier it is judged against. */
27
+ export const VIEWPORTS_3D = Object.freeze([
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"] }),
30
+ ])
31
+ export const FRAMES = 120
32
+ export const LEAK_SLACK = 0.05
33
+ const FRAME_WAIT_MS = 8_000
34
+ const NAV_MS = 30_000
35
+ const RESTORE_WAIT_MS = 2_000
36
+ const DIRECTION = "scene_direction.json"
37
+ const READ = "__kriya3dRead"
38
+
39
+ /** The tier's budget: the code ceiling, tightened (never loosened) by the contract. */
40
+ export function budgetFor(tiers, wanted) {
41
+ const tier = wanted.find((t) => tiers?.[t]) ?? wanted[0]
42
+ const ceiling = CEILINGS[tier]
43
+ const asked = tiers?.[tier] ?? {}
44
+ const out = { tier, dpr: ceiling.dpr }
45
+ for (const key of ["drawCalls", "triangles", "textureBytes", "routeBytes"]) out[key] = Number.isInteger(asked[key]) && asked[key] > 0 ? Math.min(asked[key], ceiling[key]) : ceiling[key]
46
+ return out
47
+ }
48
+
49
+ /**
50
+ * The drawing buffer against the CSS size: wider than CSS × min(DPR, cap) is an
51
+ * uncapped pixel ratio; narrower than the CSS size is a stretched, blurry canvas.
52
+ * A ratio below the cap is the app's choice (a lower tier), not a fault. 2 px slack.
53
+ */
54
+ export function bufferProblem(canvas, dpr, cap) {
55
+ if (!canvas || !canvas.clientWidth) return null
56
+ const most = Math.round(canvas.clientWidth * Math.min(dpr, cap))
57
+ if (canvas.width > most + 2) return `the drawing buffer is ${canvas.width}px wide for ${canvas.clientWidth} CSS px at DPR ${dpr}, over ${most} (the tier's cap of ${cap}): the pixel ratio is uncapped`
58
+ if (canvas.width < canvas.clientWidth - 2) return `the drawing buffer is ${canvas.width}px wide for ${canvas.clientWidth} CSS px: not synced to the CSS size, so it stretches and blurs`
59
+ return null
60
+ }
61
+
62
+ /** The direction, or null when absent or broken (G-CONTRACT reports a broken one). */
63
+ export function readDirection(root) {
64
+ const file = join(root, CONTRACTS_DIR, DIRECTION)
65
+ if (!existsSync(file)) return null
66
+ try {
67
+ const value = JSON.parse(readFileSync(file, "utf8"))
68
+ return Array.isArray(value?.routes) && value.routes.length ? value : null
69
+ } catch {
70
+ return null
71
+ }
72
+ }
73
+
74
+ // Installed on the gate's own page before any of the app's scripts
75
+ export const WRAP = `(() => {
76
+ const P = HTMLCanvasElement.prototype
77
+ const original = P.getContext
78
+ const WEBGL = new Set(["webgl", "webgl2", "experimental-webgl"])
79
+ const contexts = []
80
+ const frames = []
81
+ let errors = 0
82
+ let draws = 0
83
+ let triangles = 0
84
+ const prims = (mode, count, n) => {
85
+ const c = Math.max(0, count) * Math.max(1, n || 1)
86
+ return mode === 4 ? c / 3 : mode === 5 || mode === 6 ? Math.max(0, c - 2) : 0
87
+ }
88
+ const KINDS = { Texture: "textures", Buffer: "buffers", Program: "programs", Framebuffer: "framebuffers", Renderbuffer: "renderbuffers" }
89
+ function track(canvas, gl) {
90
+ const rec = { canvas, gl, live: { textures: new Set(), buffers: new Set(), programs: new Set(), framebuffers: new Set(), renderbuffers: new Set() }, bytes: new Map() }
91
+ contexts.push(rec)
92
+ const wrap = (name, fn) => {
93
+ const real = gl[name]
94
+ if (typeof real !== "function") return
95
+ Object.defineProperty(gl, name, { configurable: true, writable: true, value: function (...args) { return fn.call(this, real, args) } })
96
+ }
97
+ for (const [kind, set] of Object.entries(KINDS)) {
98
+ wrap("create" + kind, (real, args) => {
99
+ const o = real.apply(gl, args)
100
+ if (o) rec.live[set].add(o)
101
+ return o
102
+ })
103
+ wrap("delete" + kind, (real, args) => {
104
+ rec.live[set].delete(args[0])
105
+ rec.bytes.delete(args[0])
106
+ return real.apply(gl, args)
107
+ })
108
+ }
109
+ for (const name of ["drawArrays", "drawElements", "drawArraysInstanced", "drawElementsInstanced", "drawRangeElements"])
110
+ wrap(name, (real, args) => {
111
+ draws++
112
+ const count = name === "drawRangeElements" ? args[3] : args[name.startsWith("drawArrays") ? 2 : 1]
113
+ const n = name === "drawArraysInstanced" ? args[3] : name === "drawElementsInstanced" ? args[4] : 1
114
+ triangles += prims(args[0], count, n)
115
+ return real.apply(gl, args)
116
+ })
117
+ const bound = (pname) => { try { return gl.getParameter(pname) } catch { return null } }
118
+ const texBytes = (args, storage) => {
119
+ if (storage) return args[3] * args[4] * 4 * (args[1] > 1 ? 1.34 : 1)
120
+ if (args.length >= 9 || typeof args[3] === "number") return (args[3] || 0) * (args[4] || 0) * 4
121
+ const src = args[5]
122
+ return src ? (src.videoWidth || src.naturalWidth || src.width || 0) * (src.videoHeight || src.naturalHeight || src.height || 0) * 4 : 0
123
+ }
124
+ wrap("texImage2D", (real, args) => {
125
+ const t = bound(gl.TEXTURE_BINDING_2D)
126
+ if (t && args[1] === 0) rec.bytes.set(t, { kind: "texture", n: texBytes(args, false) })
127
+ return real.apply(gl, args)
128
+ })
129
+ wrap("texStorage2D", (real, args) => {
130
+ const t = bound(gl.TEXTURE_BINDING_2D)
131
+ if (t) rec.bytes.set(t, { kind: "texture", n: texBytes(args, true) })
132
+ return real.apply(gl, args)
133
+ })
134
+ wrap("bufferData", (real, args) => {
135
+ const b = bound(args[0] === gl.ELEMENT_ARRAY_BUFFER ? gl.ELEMENT_ARRAY_BUFFER_BINDING : gl.ARRAY_BUFFER_BINDING)
136
+ if (b) rec.bytes.set(b, { kind: "buffer", n: typeof args[1] === "number" ? args[1] : args[1]?.byteLength ?? 0 })
137
+ return real.apply(gl, args)
138
+ })
139
+ return rec
140
+ }
141
+ Object.defineProperty(P, "getContext", {
142
+ configurable: false,
143
+ writable: false,
144
+ value: function (type, ...rest) {
145
+ const gl = original.call(this, type, ...rest)
146
+ if (gl && WEBGL.has(type) && !contexts.some((c) => c.gl === gl)) track(this, gl)
147
+ return gl
148
+ },
149
+ })
150
+ let last = performance.now()
151
+ const raf = window.requestAnimationFrame.bind(window)
152
+ const tick = (now) => {
153
+ for (const c of contexts) {
154
+ try {
155
+ if (!c.gl.isContextLost() && c.gl.getError() !== 0) errors++
156
+ } catch {}
157
+ }
158
+ frames.push({ draws, triangles, ms: now - last })
159
+ last = now
160
+ draws = 0
161
+ triangles = 0
162
+ if (frames.length > 2000) frames.splice(0, 1000)
163
+ raf(tick)
164
+ }
165
+ raf(tick)
166
+ let lost = null
167
+ const read = (action) => {
168
+ const live = contexts.filter((c) => !c.gl.isContextLost())
169
+ if (action === "lose") {
170
+ const c = live.filter((x) => x.canvas.isConnected).sort((a, b) => b.canvas.clientWidth * b.canvas.clientHeight - a.canvas.clientWidth * a.canvas.clientHeight)[0]
171
+ // Kept: a lost context's getExtension returns null, so restore needs this same object
172
+ lost = c && c.gl.getExtension("WEBGL_lose_context")
173
+ if (!lost) return false
174
+ lost.loseContext()
175
+ return true
176
+ }
177
+ if (action === "restore") {
178
+ if (!lost) return false
179
+ try {
180
+ lost.restoreContext()
181
+ } catch {}
182
+ lost = null
183
+ return true
184
+ }
185
+ const shown = contexts.filter((c) => c.canvas.isConnected).sort((a, b) => b.canvas.clientWidth * b.canvas.clientHeight - a.canvas.clientWidth * a.canvas.clientHeight)[0]
186
+ const count = (set) => live.reduce((n, c) => n + c.live[set].size, 0)
187
+ let textureBytes = 0
188
+ let bufferBytes = 0
189
+ for (const c of live) for (const b of c.bytes.values()) b.kind === "texture" ? (textureBytes += b.n) : (bufferBytes += b.n)
190
+ let renderer = null
191
+ if (shown) {
192
+ try {
193
+ const d = shown.gl.getExtension("WEBGL_debug_renderer_info")
194
+ renderer = String(shown.gl.getParameter(d ? d.UNMASKED_RENDERER_WEBGL : shown.gl.RENDERER))
195
+ } catch {}
196
+ }
197
+ return {
198
+ contexts: contexts.length,
199
+ frames: frames.length,
200
+ recent: frames.slice(-${FRAMES}),
201
+ errors,
202
+ live: { textures: count("textures"), buffers: count("buffers"), programs: count("programs"), framebuffers: count("framebuffers"), renderbuffers: count("renderbuffers") },
203
+ textureBytes: Math.round(textureBytes),
204
+ bufferBytes: Math.round(bufferBytes),
205
+ renderer,
206
+ canvas: shown ? { width: shown.canvas.width, height: shown.canvas.height, clientWidth: shown.canvas.clientWidth, clientHeight: shown.canvas.clientHeight, lost: shown.gl.isContextLost() } : null,
207
+ }
208
+ }
209
+ Object.defineProperty(window, "${READ}", { configurable: false, writable: false, value: read })
210
+ })()`
211
+
212
+ const median = (xs) => {
213
+ if (!xs.length) return 0
214
+ const s = [...xs].sort((a, b) => a - b)
215
+ return s[Math.floor((s.length - 1) / 2)]
216
+ }
217
+ const p95 = (xs) => {
218
+ if (!xs.length) return 0
219
+ const s = [...xs].sort((a, b) => a - b)
220
+ return s[Math.min(s.length - 1, Math.ceil(s.length * 0.95) - 1)]
221
+ }
222
+
223
+ /** A screenshot's look over a downsampled grid: luminance variance and distinct (4-bit) colours. */
224
+ export function canvasLook(png) {
225
+ const p = decodePng(png)
226
+ if (!p) return null
227
+ const step = Math.max(1, Math.floor(Math.min(p.width, p.height) / 48))
228
+ const colours = new Set()
229
+ let n = 0
230
+ let sum = 0
231
+ let sq = 0
232
+ const samples = []
233
+ for (let y = 0; y < p.height; y += step)
234
+ for (let x = 0; x < p.width; x += step) {
235
+ const i = (y * p.width + x) * p.channels
236
+ const [r, g, b] = [p.data[i], p.data[i + 1], p.data[i + 2]]
237
+ colours.add(((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4))
238
+ const l = 0.2126 * r + 0.7152 * g + 0.0722 * b
239
+ n++
240
+ sum += l
241
+ sq += l * l
242
+ samples.push(r, g, b)
243
+ }
244
+ return { variance: n ? sq / n - (sum / n) ** 2 : 0, colours: colours.size, samples }
245
+ }
246
+ export const blank = (look) => !look || look.variance < 4 || look.colours < 8
247
+ /** The share of sampled channels that differ between two looks. */
248
+ export const moved = (a, b) => {
249
+ if (!a || !b || a.samples.length !== b.samples.length) return 0
250
+ let d = 0
251
+ for (let i = 0; i < a.samples.length; i++) if (Math.abs(a.samples[i] - b.samples[i]) > 6) d++
252
+ return d / a.samples.length
253
+ }
254
+
255
+ const evidenceDir = (root, label) =>
256
+ join(kriyaHome(), "evidence", createHash("sha256").update(root).digest("hex").slice(0, 16), String(label ?? "g-3d").replace(/[^\w.-]+/g, "-").slice(0, 60), `3d-${new Date().toISOString().replace(/[:.]/g, "-")}`)
257
+
258
+ /**
259
+ * G-3D on the confirmed app's direction routes. `app` and `direction` may be
260
+ * given (tests); otherwise the stack's app and the project's scene_direction.json.
261
+ * @returns {Promise<{ id: "G-3D", status: "pass" | "fail" | "not_checked", reason?: string, kind?: string, excerpt?: string, note?: string, optional?: true, report?: any }>}
262
+ */
263
+ export async function threeGate({ root, label, launch, app: givenApp, direction: givenDirection }) {
264
+ const app = givenApp ?? readStack(root).app
265
+ 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
+ const direction = givenDirection ?? readDirection(root)
267
+ 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
+ const dir = evidenceDir(root, label)
269
+ const run = await withGateBrowser((_open, browser) => checkScenes(browser, app, direction, dir), { launch })
270
+ if (run.unavailable) return { id: "G-3D", status: "not_checked", reason: run.unavailable }
271
+ return run.value
272
+ }
273
+
274
+ async function openPage(browser, url, { viewport, reducedMotion = "no-preference" }) {
275
+ const target = localUrl(url)
276
+ if (target.error) throw new Error(target.error)
277
+ const context = await browser.newContext({ viewport: { width: viewport.width, height: viewport.height }, deviceScaleFactor: viewport.dpr, reducedMotion, acceptDownloads: false, serviceWorkers: "block" })
278
+ await context.route("**/*", (route) => (route.request().isNavigationRequest() && localUrl(route.request().url()).error ? route.abort("blockedbyclient") : route.continue()))
279
+ // The gate's own page only: never the agent's page, never the whole context
280
+ const page = await context.newPage()
281
+ await page.addInitScript(WRAP)
282
+ const consoleErrors = []
283
+ let bytes = 0
284
+ page.on("console", (m) => m.type() === "error" && consoleErrors.push(m.text().slice(0, 300)))
285
+ page.on("pageerror", (e) => consoleErrors.push(String(e?.message ?? e).slice(0, 300)))
286
+ page.on("response", async (r) => {
287
+ const n = Number(r.headers()["content-length"])
288
+ bytes += Number.isFinite(n) ? n : (await r.body().catch(() => Buffer.alloc(0))).length
289
+ })
290
+ const started = Date.now()
291
+ try {
292
+ await page.goto(target.url, { waitUntil: "load", timeout: NAV_MS })
293
+ } catch (error) {
294
+ await context.close().catch(() => {})
295
+ return { unreachable: /ERR_CONNECTION_REFUSED/.test(String(error?.message)) ? "nothing answers there" : String(error?.message ?? error).split("\n")[0].slice(0, 200) }
296
+ }
297
+ const read = (action) => page.evaluate(({ name, action }) => window[name]?.(action), { name: READ, action })
298
+ 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(() => {})
300
+ return read()
301
+ }
302
+ const shot = async () => {
303
+ const canvas = page.locator("canvas").first()
304
+ if (!(await canvas.count())) return null
305
+ return canvas.screenshot({ timeout: 5_000 }).catch(() => null)
306
+ }
307
+ return { page, context, read, framesFrom, shot, consoleErrors, bytes: () => bytes, started }
308
+ }
309
+
310
+ async function checkScenes(browser, app, direction, dir) {
311
+ const problems = []
312
+ const reported = []
313
+ const motion = direction.motion ?? "none"
314
+ // Does this browser make WebGL at all? Otherwise not_checked, never pass
315
+ const probe = await openPage(browser, new URL(direction.routes[0].path, app).href, { viewport: VIEWPORTS_3D[0] })
316
+ if (probe.unreachable) return { id: "G-3D", status: "not_checked", reason: `${app} doesn't answer (${probe.unreachable}); start the app, or confirm another with kriya stack use --app` }
317
+ const hasGl = await probe.page.evaluate(() => Boolean(document.createElement("canvas").getContext("webgl2") || document.createElement("canvas").getContext("webgl"))).catch(() => false)
318
+ await probe.context.close().catch(() => {})
319
+ if (!hasGl) return { id: "G-3D", status: "not_checked", reason: "no WebGL in this browser" }
320
+ let renderer = null
321
+ for (const route of direction.routes)
322
+ for (const viewport of VIEWPORTS_3D) {
323
+ const at = `${route.path} at ${viewport.name}px`
324
+ const budget = budgetFor(direction.tiers, viewport.tiers)
325
+ const v = await openPage(browser, new URL(route.path, app).href, { viewport })
326
+ if (v.unreachable) return { id: "G-3D", status: "not_checked", reason: `${app}${route.path} doesn't answer (${v.unreachable})` }
327
+ try {
328
+ const first = await v.framesFrom(0, 30)
329
+ if (!first?.contexts) {
330
+ problems.push(`${at}: no WebGL context was created`)
331
+ continue
332
+ }
333
+ const a = await v.shot()
334
+ const mid = await v.framesFrom(first.frames, 60)
335
+ const b = await v.shot()
336
+ const r = await v.framesFrom(mid.frames, FRAMES - 60)
337
+ renderer ??= r.renderer
338
+ const lookA = canvasLook(a)
339
+ const lookB = canvasLook(b)
340
+ keepShot(dir, `${route.path.replace(/\W+/g, "_") || "root"}-${viewport.name}-f30.png`, a)
341
+ keepShot(dir, `${route.path.replace(/\W+/g, "_") || "root"}-${viewport.name}-f90.png`, b)
342
+ if (v.consoleErrors.length) problems.push(`${at}: console errors (shader compile and link failures are logged here): ${v.consoleErrors.slice(0, 3).join(" | ")}`)
343
+ 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`)
345
+ 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
+ const recent = r.recent ?? []
347
+ const drawCalls = median(recent.map((f) => f.draws))
348
+ const tris = median(recent.map((f) => f.triangles))
349
+ if (drawCalls > budget.drawCalls) problems.push(`${at}: ${drawCalls} draw calls a frame (median) over the ${budget.tier} budget of ${budget.drawCalls}; instance or merge`)
350
+ if (tris > budget.triangles) problems.push(`${at}: ${Math.round(tris)} triangles a frame over the ${budget.tier} budget of ${budget.triangles}; use LODs or simplify`)
351
+ if (r.textureBytes > budget.textureBytes) problems.push(`${at}: ${mb(r.textureBytes)} of textures over the ${budget.tier} budget of ${mb(budget.textureBytes)}; compress (KTX2) or resize`)
352
+ if (v.bytes() > budget.routeBytes) problems.push(`${at}: the route transferred ${mb(v.bytes())}, over the ${budget.tier} budget of ${mb(budget.routeBytes)}`)
353
+ const sizing = bufferProblem(r.canvas, viewport.dpr, budget.dpr)
354
+ if (sizing) problems.push(`${at}: ${sizing}`)
355
+ const deltas = recent.map((f) => f.ms).filter((ms) => ms > 0 && ms < 1000)
356
+ 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
358
+ if (viewport !== VIEWPORTS_3D[0]) continue
359
+ // Resize: the buffer follows the new CSS size
360
+ await v.page.setViewportSize({ width: viewport.width - 60, height: viewport.height - 100 })
361
+ const resized = await v.framesFrom((await v.read()).frames, 20)
362
+ const after = bufferProblem(resized.canvas, viewport.dpr, budget.dpr)
363
+ if (after) problems.push(`${at}, after a resize: ${after}`)
364
+ // Leaks: unmount and mount again, through the route's own unmount path
365
+ if (route.unmount) {
366
+ const before = (await v.framesFrom((await v.read()).frames, 10)).live
367
+ const go = (path) => v.page.evaluate((p) => (history.pushState({}, "", p), dispatchEvent(new PopStateEvent("popstate"))), path)
368
+ await go(route.unmount)
369
+ await v.framesFrom((await v.read()).frames, 20)
370
+ await go(route.path)
371
+ const after = (await v.framesFrom((await v.read()).frames, 30)).live
372
+ const grew = Object.keys(before).filter((k) => after[k] > before[k] * (1 + LEAK_SLACK) && after[k] > before[k])
373
+ if (grew.length) problems.push(`${at}: GPU objects leak over unmount → mount: ${grew.map((k) => `${k} ${before[k]} → ${after[k]}`).join(", ")}; dispose on unmount`)
374
+ } else reported.push(`${at}: leaks not checked (no "unmount" path for this route in ${DIRECTION})`)
375
+ // Context loss: lose, restore, wait, draw again
376
+ if (await v.read("lose")) {
377
+ await v.page.waitForTimeout(100)
378
+ await v.read("restore")
379
+ await v.page.waitForTimeout(RESTORE_WAIT_MS)
380
+ const after = await v.read()
381
+ 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`)
383
+ } else reported.push(`${at}: context loss not checked (no WEBGL_lose_context)`)
384
+ } finally {
385
+ await v.context.close().catch(() => {})
386
+ }
387
+ // Reduced motion: decorative motion stops
388
+ if (motion !== "none" && viewport === VIEWPORTS_3D[0]) {
389
+ const q = await openPage(browser, new URL(route.path, app).href, { viewport, reducedMotion: "reduce" })
390
+ if (!q.unreachable)
391
+ try {
392
+ await q.framesFrom(0, 30)
393
+ const a = canvasLook(await q.shot())
394
+ await q.framesFrom((await q.read()).frames, 60)
395
+ const b = canvasLook(await q.shot())
396
+ if (moved(a, b) > 0) problems.push(`${at}: decorative motion still runs under prefers-reduced-motion`)
397
+ } finally {
398
+ await q.context.close().catch(() => {})
399
+ }
400
+ }
401
+ }
402
+ const note = [`renderer: ${renderer ?? "unknown"}`, ...reported].join("\n")
403
+ 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 }
404
+ return { id: "G-3D", status: "pass", note }
405
+ }
406
+
407
+ const mb = (n) => `${(n / 2 ** 20).toFixed(1)} MB`
@@ -0,0 +1,111 @@
1
+ import { createHash } from "node:crypto"
2
+ import { existsSync, readFileSync } from "node:fs"
3
+ import { join } from "node:path"
4
+
5
+ import { CONTRACTS_DIR } from "../contracts.js"
6
+ import { kriyaHome } from "../paths.js"
7
+ import { readStack } from "../stack.js"
8
+ import { keepShot, SCHEMES, VIEWPORTS, withGateBrowser } from "./page.js"
9
+
10
+ // Harness 2.0 W4: G-UI and G-A11Y (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
11
+ // GATES.md §3). Both read the same rendered pages, so they share one visit per
12
+ // route × viewport × scheme, made once per verify. The app is the one the
13
+ // person confirmed with `kriya stack use --app`; routes are "/" plus the
14
+ // component previews named in .kriya/contracts/component_states.json.
15
+
16
+ export const MAX_ROUTES = 4
17
+ export const CLS_LIMIT = 0.1
18
+ export const TARGET_MIN = 24
19
+ export const TARGET_WARN = 44
20
+
21
+ /** The routes to render: "/" and each component preview (contract, hash-locked by its owner), at most MAX_ROUTES. */
22
+ export function uiRoutes(root) {
23
+ const routes = ["/"]
24
+ const file = join(root, CONTRACTS_DIR, "component_states.json")
25
+ if (existsSync(file)) {
26
+ try {
27
+ for (const c of Object.values(JSON.parse(readFileSync(file, "utf8")))) if (typeof c?.preview === "string" && /^\/\S*$/.test(c.preview) && !routes.includes(c.preview)) routes.push(c.preview)
28
+ } catch {
29
+ // G-CONTRACT reports a broken contract
30
+ }
31
+ }
32
+ return routes.slice(0, MAX_ROUTES)
33
+ }
34
+
35
+ const evidenceDir = (root, label) =>
36
+ join(kriyaHome(), "evidence", createHash("sha256").update(root).digest("hex").slice(0, 16), String(label).replace(/[^\w.-]+/g, "-").slice(0, 60), new Date().toISOString().replace(/[:.]/g, "-"))
37
+
38
+ /**
39
+ * Every page report for this verify, or { skip: reason }. Made once and shared by G-UI and G-A11Y.
40
+ * @param {{ root: string, label: string, launch?: () => Promise<any> }} input
41
+ */
42
+ export async function uiReports({ root, label, launch, app: given }) {
43
+ // Harness 2.0 W17: G-RELEASE points the same visits at the production server it was given
44
+ const app = given ?? readStack(root).app
45
+ if (!app) return { skip: "no app is confirmed for this project (kriya stack use --app http://localhost:<port>)", optional: true }
46
+ const routes = uiRoutes(root)
47
+ const dir = evidenceDir(root, label)
48
+ const visited = await withGateBrowser(
49
+ async (open) => {
50
+ const reports = []
51
+ for (const route of routes)
52
+ for (const viewport of VIEWPORTS)
53
+ for (const scheme of SCHEMES) {
54
+ const report = await open(new URL(route, app).href, { viewport, scheme })
55
+ if (report.unreachable) return { unreachable: `${app} doesn't answer (${report.unreachable}); start the app, or confirm another with kriya stack use --app` }
56
+ const sha = keepShot(dir, `${route.replace(/\W+/g, "_") || "root"}-${viewport.name}-${scheme}.png`, report.shot)
57
+ delete report.shot
58
+ reports.push({ route, ...report, ...(sha && { evidence: sha }) })
59
+ }
60
+ return { reports }
61
+ },
62
+ { launch }
63
+ )
64
+ if (visited.unavailable) return { skip: visited.unavailable }
65
+ if (visited.value.unreachable) return { skip: visited.value.unreachable }
66
+ return { reports: visited.value.reports, dir }
67
+ }
68
+
69
+ const at = (r) => `${r.route} at ${r.viewport}px ${r.scheme}`
70
+ const lines = (items, n = 12) => items.slice(0, n).map((x) => `- ${x}`).join("\n") + (items.length > n ? `\n- … and ${items.length - n} more` : "")
71
+
72
+ /** G-UI over the shared reports */
73
+ export function judgeUi(ui) {
74
+ if (ui.skip) return { id: "G-UI", status: "not_checked", reason: ui.skip, ...(ui.optional && { optional: true }) }
75
+ const problems = []
76
+ const warnings = []
77
+ for (const r of ui.reports) {
78
+ for (const e of r.consoleErrors) problems.push(`${at(r)}: console error: ${e}`)
79
+ for (const f of r.failed) problems.push(`${at(r)}: request ${f}`)
80
+ if (r.status !== null && r.status >= 400) problems.push(`${at(r)}: the page answered ${r.status}`)
81
+ if (r.overflow) problems.push(`${at(r)}: the page scrolls sideways (content wider than the screen)`)
82
+ if (r.cls > CLS_LIMIT) problems.push(`${at(r)}: layout shift ${r.cls} (over ${CLS_LIMIT})`)
83
+ if (Number(r.viewport) < 768) {
84
+ for (const s of r.small) {
85
+ if (Math.min(...s.size) < TARGET_MIN) problems.push(`${at(r)}: ${s.what} is ${s.size.join("×")} px, under the ${TARGET_MIN} px minimum to tap`)
86
+ else if (Math.min(...s.size) < TARGET_WARN) warnings.push(`${at(r)}: ${s.what} is ${s.size.join("×")} px; ${TARGET_WARN} px is easier to tap`)
87
+ }
88
+ }
89
+ }
90
+ const unique = [...new Set(problems)]
91
+ const evidence = ui.reports.map((r) => r.evidence).filter(Boolean)
92
+ if (unique.length) return { id: "G-UI", status: "fail", kind: "gate", excerpt: `G-UI (rendered at ${VIEWPORTS.map((v) => v.name).join(", ")} px, light and dark):\n${lines(unique)}`, evidence }
93
+ return { id: "G-UI", status: "pass", evidence, ...(warnings.length && { warnings: warnings.length, note: lines([...new Set(warnings)], 6) }) }
94
+ }
95
+
96
+ /** G-A11Y over the shared reports: names, language, contrast (plain and over glass), heading order as a warning */
97
+ export function judgeA11y(ui) {
98
+ if (ui.skip) return { id: "G-A11Y", status: "not_checked", reason: ui.skip, ...(ui.optional && { optional: true }) }
99
+ const problems = []
100
+ const warnings = []
101
+ for (const r of ui.reports) {
102
+ if (!r.lang) problems.push(`${at(r)}: <html> has no lang`)
103
+ for (const u of r.unnamed) problems.push(`${at(r)}: ${u} has no accessible name`)
104
+ for (const c of r.lowContrast) problems.push(`${at(r)}: "${c.text}" (${c.what}) has contrast ${c.ratio}:1, needs ${c.need}:1`)
105
+ for (const g of r.glass) if (g.worst < g.need) problems.push(`${at(r)}: text on a glass surface (${g.what}) reaches only ${Math.round(g.worst * 100) / 100}:1 over its backdrop, needs ${g.need}:1; make the surface more opaque or add a solid fallback`)
106
+ if (r.headingSkips) warnings.push(`${at(r)}: heading levels skip ${r.headingSkips} time(s)`)
107
+ }
108
+ const unique = [...new Set(problems)]
109
+ if (unique.length) return { id: "G-A11Y", status: "fail", kind: "gate", excerpt: `G-A11Y:\n${lines(unique)}` }
110
+ return { id: "G-A11Y", status: "pass", ...(warnings.length && { warnings: warnings.length, note: lines([...new Set(warnings)], 6) }) }
111
+ }
package/src/launch.js CHANGED
@@ -37,7 +37,10 @@ export async function planTiers(device, list = models) {
37
37
  const encodings = Array.isArray(answer.bodyEncodings) ? answer.bodyEncodings.filter((e) => typeof e === "string") : []
38
38
  const offered = new Set(data.map((model) => model.id))
39
39
  const allowed = START_TIERS.filter((tier) => offered.has(tier))
40
- return allowed.length ? { start: allowed[0], allowed, names: modelNames(data, allowed), limits: modelLimits(data, allowed), images: allowed.filter((tier) => data.find((m) => m.id === tier)?.images === true), encodings } : { ...all, encodings }
40
+ // Harness 2.0 W2: the owner's head and worker levels, only if both are offered and differ
41
+ const o = answer.orchestra
42
+ const orchestra = o && allowed.includes(o.head) && allowed.includes(o.worker) && o.head !== o.worker ? { head: o.head, worker: o.worker } : undefined
43
+ return allowed.length ? { start: allowed[0], allowed, names: modelNames(data, allowed), limits: modelLimits(data, allowed), images: allowed.filter((tier) => data.find((m) => m.id === tier)?.images === true), encodings, ...(orchestra && { orchestra }) } : { ...all, encodings }
41
44
  } catch {
42
45
  // Kriya answers the first request with the reason if it's refused
43
46
  return all
@@ -96,7 +99,7 @@ export async function startTier(device, list = models) {
96
99
  }
97
100
 
98
101
  /** @param {{ url: string, token: string } | null} device */
99
- export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier = START_TIERS[0], allowed = START_TIERS, names = {}, limits = {}, images = []) {
102
+ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier = START_TIERS[0], allowed = START_TIERS, names = {}, limits = {}, images = [], orchestra) {
100
103
  const env = {
101
104
  ...base,
102
105
  // The mode always comes from `--mode` (or the default), never the shell
@@ -115,6 +118,13 @@ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier
115
118
  // The tiers whose model takes images, as GET /models says. Never from the shell
116
119
  KRIYA_MODEL_IMAGES: images.filter((t) => START_TIERS.includes(t)).join(","),
117
120
  }
121
+ // Harness 2.0 W2: the head and worker levels come only from Kriya's GET /models, never the shell
122
+ delete env.KRIYA_ORCHESTRA_HEAD
123
+ delete env.KRIYA_ORCHESTRA_WORKER
124
+ if (orchestra && START_TIERS.includes(orchestra.head) && START_TIERS.includes(orchestra.worker)) {
125
+ env.KRIYA_ORCHESTRA_HEAD = orchestra.head
126
+ env.KRIYA_ORCHESTRA_WORKER = orchestra.worker
127
+ }
118
128
  // A token from the person's environment never stands in for the sign-in
119
129
  delete env[TOKEN_ENV]
120
130
  delete env.KRIYA_GATEWAY_URL
@@ -237,6 +247,8 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
237
247
  ensureProfile(profile)
238
248
  const headless = profile === "kriya-run"
239
249
  const tiers = await planTiers(device)
250
+ // Harness 2.0 W2: with --orchestra and Kriya's offer, the session itself runs on the head level
251
+ const orchestra = process.env.KRIYA_ORCHESTRA === "on" && process.env.KRIYA_LOOP === "on" ? tiers.orchestra : undefined
240
252
  // DSH and the Kriya plugins reach Kriya through the local relay
241
253
  // (src/gateway-proxy.js): encoded bodies past the host's firewall, and a
242
254
  // block said as such. KRIYA_RELAY=off talks to Kriya directly, as before
@@ -262,7 +274,7 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
262
274
  // stdout: the answer (kriya run) and ACP's protocol frames pass untouched;
263
275
  // the Web UI's stdout carries only log lines, rebranded like stderr
264
276
  stdio: ["inherit", profile === "kriya" ? "pipe" : "inherit", "pipe"],
265
- env: launchEnv(relay ? { ...device, url: relay.url } : device, process.env, mode, tiers.start, tiers.allowed, tiers.names, tiers.limits, tiers.images),
277
+ env: launchEnv(relay ? { ...device, url: relay.url } : device, process.env, mode, orchestra ? orchestra.head : tiers.start, tiers.allowed, tiers.names, tiers.limits, tiers.images, orchestra),
266
278
  })
267
279
  let explained = null
268
280
  const filter = htmlFilter((text) => process.stderr.write(rebrand(text)))