@kriya-ai/harness 0.2.5 → 2.0.1

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 +60 -5
  6. package/contract/SOURCE.md +3 -3
  7. package/contract/contract.json +498 -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 +381 -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 +436 -0
  33. package/plugins/runstrip/index.js +312 -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 +65 -6
  42. package/src/edit/core/layout.js +46 -1
  43. package/src/edit/core/ops.js +169 -2
  44. package/src/edit/core/plan.js +65 -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/type-kit.js +173 -0
  51. package/src/edit/director/ask.js +37 -3
  52. package/src/edit/director/assembly.js +829 -0
  53. package/src/edit/director/continuity.js +9 -1
  54. package/src/edit/director/custom-motion.js +88 -0
  55. package/src/edit/director/graphics.js +44 -10
  56. package/src/edit/director/intent.js +125 -0
  57. package/src/edit/director/mentions.js +52 -0
  58. package/src/edit/director/plan.js +43 -11
  59. package/src/edit/director/revise.js +132 -9
  60. package/src/edit/director/viewer.js +136 -0
  61. package/src/edit/director/watch-fix.js +119 -0
  62. package/src/edit/engine/captions.js +110 -5
  63. package/src/edit/engine/confine.js +81 -4
  64. package/src/edit/engine/custom.js +243 -0
  65. package/src/edit/engine/dna2.js +893 -0
  66. package/src/edit/engine/fonts.js +218 -0
  67. package/src/edit/engine/graphics.js +271 -10
  68. package/src/edit/engine/index.js +14 -5
  69. package/src/edit/engine/motion.js +148 -13
  70. package/src/edit/engine/music-bed.js +59 -1
  71. package/src/edit/engine/packs.js +11 -0
  72. package/src/edit/engine/reference2.js +26 -0
  73. package/src/edit/engine/sfx.js +56 -1
  74. package/src/edit/engine/tool.js +21 -5
  75. package/src/edit/gates/assembly.js +194 -0
  76. package/src/edit/gates/copy.js +7 -4
  77. package/src/edit/gates/index.js +72 -7
  78. package/src/edit/gates/reference.js +115 -0
  79. package/src/edit/gates/tile.js +96 -0
  80. package/src/edit/host/client.js +8 -3
  81. package/src/edit/host/clips.js +33 -0
  82. package/src/edit/host/jobs.js +9 -3
  83. package/src/edit/host/layers.js +134 -0
  84. package/src/edit/host/main.js +10 -3
  85. package/src/edit/host/paths.js +21 -3
  86. package/src/edit/host/preview.js +108 -0
  87. package/src/edit/host/projects.js +443 -34
  88. package/src/edit/host/server.js +235 -20
  89. package/src/edit/host/tavi.js +77 -0
  90. package/src/edit/index/index.js +3 -2
  91. package/src/edit/loop/make.js +28 -3
  92. package/src/edit/recipes/assembly.js +352 -0
  93. package/src/edit/recipes/graphic-clips.js +4 -2
  94. package/src/edit/recipes/openings.js +36 -0
  95. package/src/edit/recipes/reel.js +104 -14
  96. package/src/edit/recipes/reference-look.js +29 -0
  97. package/src/edit/recipes/short-from-long.js +3 -3
  98. package/src/edit/recipes/sound.js +71 -0
  99. package/src/edit/runtime/cli.js +26 -5
  100. package/src/edit/runtime/fetch.js +4 -4
  101. package/src/edit/runtime/licences.js +7 -1
  102. package/src/explore.js +103 -0
  103. package/src/failure.js +1 -1
  104. package/src/gate-commands.js +114 -0
  105. package/src/gates/api.js +127 -0
  106. package/src/gates/commands.js +111 -0
  107. package/src/gates/detectors.js +370 -0
  108. package/src/gates/http.js +62 -0
  109. package/src/gates/index.js +196 -0
  110. package/src/gates/page.js +264 -0
  111. package/src/gates/sast.js +64 -0
  112. package/src/gates/stack.js +110 -0
  113. package/src/gates/tenant.js +162 -0
  114. package/src/gates/three.js +431 -0
  115. package/src/gates/ui.js +111 -0
  116. package/src/gateway-proxy.js +20 -2
  117. package/src/launch.js +39 -5
  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 +67 -0
  122. package/src/orchestra.js +50 -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 +449 -1
  134. package/studio/dist/studio.js +3 -3
@@ -0,0 +1,162 @@
1
+ import { existsSync, readFileSync } from "node:fs"
2
+ import { join } from "node:path"
3
+
4
+ import { Ajv2020 } from "ajv/dist/2020.js"
5
+
6
+ import { CONTRACTS_DIR } from "../contracts.js"
7
+ import { readStack } from "../stack.js"
8
+ import { Budget, fill, local } from "./http.js"
9
+
10
+ // Harness 2.0 W5: G-TENANT (Kriya-Tavi docs/kriya-harness/upgrade_2.0/GATES.md
11
+ // §3). For every tenant-scoped resource of .kriya/contracts/auth_matrix.json:
12
+ // two local test identities A and B, proved different first; B creates an
13
+ // object (control), B reads it (control), then A tries to read, change,
14
+ // delete and list it, as the matrix allows, and each must be refused
15
+ // (403/404) with B's object unchanged. A server that refuses everything fails
16
+ // its controls, so it can't pass. How to sign in and call each resource is in
17
+ // .kriya/gates/tenants.json (written by the security step; test identities of
18
+ // the local app only). Credentials and tokens never appear in an excerpt.
19
+
20
+ export const TENANTS_FILE = join(".kriya", "gates", "tenants.json")
21
+
22
+ const call = { type: "object", required: ["path"], additionalProperties: false, properties: { path: { type: "string", pattern: "^/\\S{0,300}$" }, method: { enum: ["GET", "POST", "PUT", "PATCH", "DELETE"] }, body: {}, idField: { type: "string", maxLength: 80 } } }
23
+ const SCHEMA = {
24
+ type: "object",
25
+ required: ["signIn", "tenants", "token", "whoami", "resources"],
26
+ additionalProperties: false,
27
+ properties: {
28
+ signIn: call,
29
+ tenants: { type: "object", required: ["A", "B"], additionalProperties: false, properties: { A: { type: "object", properties: { body: {} } }, B: { type: "object", properties: { body: {} } } } },
30
+ token: {
31
+ oneOf: [
32
+ { type: "object", required: ["from", "field"], additionalProperties: false, properties: { from: { const: "json" }, field: { type: "string", maxLength: 80 } } },
33
+ { type: "object", required: ["from", "name"], additionalProperties: false, properties: { from: { const: "cookie" }, name: { type: "string", pattern: "^[\\w.-]{1,80}$" } } },
34
+ ],
35
+ },
36
+ whoami: { type: "object", required: ["path"], additionalProperties: false, properties: { path: { type: "string", pattern: "^/\\S{0,300}$" }, field: { type: "string", maxLength: 80 } } },
37
+ resources: { type: "object", maxProperties: 50, additionalProperties: { type: "object", additionalProperties: false, properties: { create: call, read: call, update: call, delete: call, list: call } } },
38
+ },
39
+ }
40
+ const validate = new Ajv2020({ strict: false, allErrors: true }).compile(SCHEMA)
41
+
42
+ /** The project's tenants.json, checked: { config } or { problem } */
43
+ export function tenantConfig(root) {
44
+ const file = join(root, TENANTS_FILE)
45
+ if (!existsSync(file)) return { problem: `${TENANTS_FILE} is missing: the security step writes how two local test identities sign in and how each tenant-scoped resource is called` }
46
+ let value
47
+ try {
48
+ value = JSON.parse(readFileSync(file, "utf8"))
49
+ } catch {
50
+ return { problem: `${TENANTS_FILE} isn't valid JSON` }
51
+ }
52
+ if (!validate(value)) return { problem: `${TENANTS_FILE}: ${validate.errors.slice(0, 3).map((e) => `${e.instancePath || "/"} ${e.message}`).join("; ")}` }
53
+ return { config: value }
54
+ }
55
+
56
+ /** "data.user.id" → the value in a JSON body */
57
+ export const pick = (value, field = "id") => String(field).split(".").reduce((v, k) => (v === null || v === undefined ? undefined : v[k]), value)
58
+
59
+ /** Signs one test identity in; its request headers (never shown) */
60
+ export async function signIn(app, config, who, budget, request) {
61
+ const res = await local(app, config.signIn.path, { method: config.signIn.method ?? "POST", body: config.tenants[who].body, budget, request })
62
+ if (res.status < 200 || res.status >= 300) throw new Error(`signing in as ${who} answered ${res.status || res.error}`)
63
+ if (config.token.from === "json") {
64
+ const token = pick(res.json, config.token.field)
65
+ if (typeof token !== "string" || !token) throw new Error(`signing in as ${who} returned no token at "${config.token.field}"`)
66
+ return { headers: { authorization: `Bearer ${token}` } }
67
+ }
68
+ const cookie = (res.headers?.getSetCookie?.() ?? []).map((c) => c.split(";")[0]).find((c) => c.startsWith(`${config.token.name}=`))
69
+ if (!cookie) throw new Error(`signing in as ${who} set no "${config.token.name}" cookie`)
70
+ return { headers: { cookie } }
71
+ }
72
+
73
+ /** True when any object in a JSON value has `field` equal to `id` */
74
+ const holds = (value, field, id) => {
75
+ if (Array.isArray(value)) return value.some((v) => holds(v, field, id))
76
+ if (value && typeof value === "object") return String(pick(value, field)) === String(id) || Object.values(value).some((v) => holds(v, field, id))
77
+ return false
78
+ }
79
+ const refused = (s) => s === 403 || s === 404
80
+
81
+ /** Tenant-scoped resources and the actions the matrix allows on each */
82
+ export function scopedResources(root) {
83
+ const file = join(root, CONTRACTS_DIR, "auth_matrix.json")
84
+ if (!existsSync(file)) return new Map()
85
+ let rows = []
86
+ try {
87
+ rows = JSON.parse(readFileSync(file, "utf8"))
88
+ } catch {
89
+ return new Map()
90
+ }
91
+ const out = new Map()
92
+ for (const r of Array.isArray(rows) ? rows : []) if (r?.tenantScoped) out.set(r.resource, new Set([...(out.get(r.resource) ?? []), r.action]))
93
+ return out
94
+ }
95
+
96
+ /** @param {{ root: string, request?: typeof fetch }} input */
97
+ export async function tenantGate({ root, request }) {
98
+ const id = "G-TENANT"
99
+ const scoped = scopedResources(root)
100
+ if (!scoped.size) return { id, status: "pass", note: "nothing in the auth matrix is tenant-scoped" }
101
+ const { app } = readStack(root)
102
+ if (!app) return { id, status: "not_checked", optional: true, reason: "no app is confirmed for this project (kriya stack use --app http://localhost:<port>)" }
103
+ const { config, problem } = tenantConfig(root)
104
+ if (problem) return { id, status: "not_checked", reason: problem }
105
+ const budget = new Budget()
106
+ const leaks = []
107
+ const broken = []
108
+ try {
109
+ const A = await signIn(app, config, "A", budget, request)
110
+ const B = await signIn(app, config, "B", budget, request)
111
+ const [whoA, whoB] = [await local(app, config.whoami.path, { headers: A.headers, budget, request }), await local(app, config.whoami.path, { headers: B.headers, budget, request })]
112
+ const [idA, idB] = [pick(whoA.json, config.whoami.field), pick(whoB.json, config.whoami.field)]
113
+ if (whoA.status !== 200 || whoB.status !== 200 || idA === undefined || idB === undefined) return { id, status: "fail", kind: "gate", excerpt: `G-TENANT: ${config.whoami.path} must answer 200 with "${config.whoami.field ?? "id"}" for both test identities (answered ${whoA.status}, ${whoB.status})` }
114
+ if (String(idA) === String(idB)) return { id, status: "fail", kind: "gate", excerpt: "G-TENANT: test identities A and B are the same user, so isolation can't be proved; give them different accounts in tenants.json" }
115
+ for (const [name, actions] of scoped) {
116
+ const r = config.resources[name]
117
+ if (!r?.create) {
118
+ broken.push(`${name}: tenants.json has no "create" call for it, so there's no object of B's to probe`)
119
+ continue
120
+ }
121
+ const made = await local(app, r.create.path, { method: r.create.method ?? "POST", body: r.create.body, headers: B.headers, budget, request })
122
+ const objectId = pick(made.json, r.create.idField ?? "id")
123
+ if (made.status < 200 || made.status >= 300 || objectId === undefined) {
124
+ broken.push(`${name}: control failed: B couldn't create one (${made.status || made.error})`)
125
+ continue
126
+ }
127
+ const path = (c) => fill(c.path, { id: objectId })
128
+ const ownRead = r.read && (await local(app, path(r.read), { headers: B.headers, budget, request }))
129
+ if (r.read && ownRead.status !== 200) {
130
+ broken.push(`${name}: control failed: B couldn't read its own #${objectId} (${ownRead.status || ownRead.error})`)
131
+ continue
132
+ }
133
+ const still = async () => r.read && (await local(app, path(r.read), { headers: B.headers, budget, request }))
134
+ if (actions.has("read") && r.read) {
135
+ const probe = await local(app, path(r.read), { headers: A.headers, budget, request })
136
+ if (!refused(probe.status)) leaks.push(`${name}: tenant A read B's #${objectId} (expected 403/404, got ${probe.status})`)
137
+ }
138
+ if (actions.has("update") && r.update) {
139
+ const probe = await local(app, path(r.update), { method: r.update.method ?? "PATCH", body: r.update.body, headers: A.headers, budget, request })
140
+ if (!refused(probe.status)) leaks.push(`${name}: tenant A changed B's #${objectId} (expected 403/404, got ${probe.status})`)
141
+ const after = await still()
142
+ if (after && after.text !== ownRead.text) leaks.push(`${name}: B's #${objectId} is different after A's refused update`)
143
+ }
144
+ if (actions.has("delete") && r.delete) {
145
+ const probe = await local(app, path(r.delete), { method: "DELETE", headers: A.headers, budget, request })
146
+ if (!refused(probe.status)) leaks.push(`${name}: tenant A deleted B's #${objectId} (expected 403/404, got ${probe.status})`)
147
+ const after = await still()
148
+ if (after && after.status !== 200) leaks.push(`${name}: B's #${objectId} is gone after A's delete`)
149
+ }
150
+ if (actions.has("list") && r.list) {
151
+ const probe = await local(app, r.list.path, { headers: A.headers, budget, request })
152
+ if (probe.status === 200 && holds(probe.json, r.create.idField ?? "id", objectId)) leaks.push(`${name}: tenant A's list includes B's #${objectId}`)
153
+ }
154
+ for (const action of actions) if (!r[action] && action !== "create") broken.push(`${name}: the matrix allows "${action}" but tenants.json has no call for it to probe`)
155
+ }
156
+ } catch (error) {
157
+ return { id, status: "fail", kind: "gate", excerpt: `G-TENANT: ${String(error?.message ?? error).slice(0, 300)}` }
158
+ }
159
+ if (leaks.length || broken.length)
160
+ return { id, status: "fail", kind: "gate", excerpt: `G-TENANT (against ${app}):\n${[...leaks, ...broken].slice(0, 15).map((p) => `- ${p}`).join("\n")}${leaks.length ? "\nEnforce ownership from the verified session in the service and with row-level security, not from ids the client sends." : ""}` }
161
+ return { id, status: "pass", note: `${scoped.size} tenant-scoped resource(s) probed with paired controls` }
162
+ }
@@ -0,0 +1,431 @@
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
+ // 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"] }),
31
+ ])
32
+ export const FRAMES = 120
33
+ export const LEAK_SLACK = 0.05
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
40
+ const NAV_MS = 30_000
41
+ const RESTORE_WAIT_MS = 2_000
42
+ const DIRECTION = "scene_direction.json"
43
+ const READ = "__kriya3dRead"
44
+
45
+ /** The tier's budget: the code ceiling, tightened (never loosened) by the contract. */
46
+ export function budgetFor(tiers, wanted) {
47
+ const tier = wanted.find((t) => tiers?.[t]) ?? wanted[0]
48
+ const ceiling = CEILINGS[tier]
49
+ const asked = tiers?.[tier] ?? {}
50
+ const out = { tier, dpr: ceiling.dpr }
51
+ 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]
52
+ return out
53
+ }
54
+
55
+ /**
56
+ * The drawing buffer against the CSS size: wider than CSS × min(DPR, cap) is an
57
+ * uncapped pixel ratio; narrower than the CSS size is a stretched, blurry canvas.
58
+ * A ratio below the cap is the app's choice (a lower tier), not a fault. 2 px slack.
59
+ */
60
+ export function bufferProblem(canvas, dpr, cap) {
61
+ if (!canvas || !canvas.clientWidth) return null
62
+ const most = Math.round(canvas.clientWidth * Math.min(dpr, cap))
63
+ 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`
64
+ 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`
65
+ return null
66
+ }
67
+
68
+ /** The direction, or null when absent or broken (G-CONTRACT reports a broken one). */
69
+ export function readDirection(root) {
70
+ const file = join(root, CONTRACTS_DIR, DIRECTION)
71
+ if (!existsSync(file)) return null
72
+ try {
73
+ const value = JSON.parse(readFileSync(file, "utf8"))
74
+ return Array.isArray(value?.routes) && value.routes.length ? value : null
75
+ } catch {
76
+ return null
77
+ }
78
+ }
79
+
80
+ // Installed on the gate's own page before any of the app's scripts
81
+ export const WRAP = `(() => {
82
+ const P = HTMLCanvasElement.prototype
83
+ const original = P.getContext
84
+ const WEBGL = new Set(["webgl", "webgl2", "experimental-webgl"])
85
+ const contexts = []
86
+ const frames = []
87
+ let errors = 0
88
+ let draws = 0
89
+ let triangles = 0
90
+ const prims = (mode, count, n) => {
91
+ const c = Math.max(0, count) * Math.max(1, n || 1)
92
+ return mode === 4 ? c / 3 : mode === 5 || mode === 6 ? Math.max(0, c - 2) : 0
93
+ }
94
+ const KINDS = { Texture: "textures", Buffer: "buffers", Program: "programs", Framebuffer: "framebuffers", Renderbuffer: "renderbuffers" }
95
+ function track(canvas, gl) {
96
+ const rec = { canvas, gl, live: { textures: new Set(), buffers: new Set(), programs: new Set(), framebuffers: new Set(), renderbuffers: new Set() }, bytes: new Map() }
97
+ contexts.push(rec)
98
+ const wrap = (name, fn) => {
99
+ const real = gl[name]
100
+ if (typeof real !== "function") return
101
+ Object.defineProperty(gl, name, { configurable: true, writable: true, value: function (...args) { return fn.call(this, real, args) } })
102
+ }
103
+ for (const [kind, set] of Object.entries(KINDS)) {
104
+ wrap("create" + kind, (real, args) => {
105
+ const o = real.apply(gl, args)
106
+ if (o) rec.live[set].add(o)
107
+ return o
108
+ })
109
+ wrap("delete" + kind, (real, args) => {
110
+ rec.live[set].delete(args[0])
111
+ rec.bytes.delete(args[0])
112
+ return real.apply(gl, args)
113
+ })
114
+ }
115
+ for (const name of ["drawArrays", "drawElements", "drawArraysInstanced", "drawElementsInstanced", "drawRangeElements"])
116
+ wrap(name, (real, args) => {
117
+ draws++
118
+ const count = name === "drawRangeElements" ? args[3] : args[name.startsWith("drawArrays") ? 2 : 1]
119
+ const n = name === "drawArraysInstanced" ? args[3] : name === "drawElementsInstanced" ? args[4] : 1
120
+ triangles += prims(args[0], count, n)
121
+ return real.apply(gl, args)
122
+ })
123
+ const bound = (pname) => { try { return gl.getParameter(pname) } catch { return null } }
124
+ const texBytes = (args, storage) => {
125
+ if (storage) return args[3] * args[4] * 4 * (args[1] > 1 ? 1.34 : 1)
126
+ if (args.length >= 9 || typeof args[3] === "number") return (args[3] || 0) * (args[4] || 0) * 4
127
+ const src = args[5]
128
+ return src ? (src.videoWidth || src.naturalWidth || src.width || 0) * (src.videoHeight || src.naturalHeight || src.height || 0) * 4 : 0
129
+ }
130
+ wrap("texImage2D", (real, args) => {
131
+ const t = bound(gl.TEXTURE_BINDING_2D)
132
+ if (t && args[1] === 0) rec.bytes.set(t, { kind: "texture", n: texBytes(args, false) })
133
+ return real.apply(gl, args)
134
+ })
135
+ wrap("texStorage2D", (real, args) => {
136
+ const t = bound(gl.TEXTURE_BINDING_2D)
137
+ if (t) rec.bytes.set(t, { kind: "texture", n: texBytes(args, true) })
138
+ return real.apply(gl, args)
139
+ })
140
+ wrap("bufferData", (real, args) => {
141
+ const b = bound(args[0] === gl.ELEMENT_ARRAY_BUFFER ? gl.ELEMENT_ARRAY_BUFFER_BINDING : gl.ARRAY_BUFFER_BINDING)
142
+ if (b) rec.bytes.set(b, { kind: "buffer", n: typeof args[1] === "number" ? args[1] : args[1]?.byteLength ?? 0 })
143
+ return real.apply(gl, args)
144
+ })
145
+ return rec
146
+ }
147
+ Object.defineProperty(P, "getContext", {
148
+ configurable: false,
149
+ writable: false,
150
+ value: function (type, ...rest) {
151
+ const gl = original.call(this, type, ...rest)
152
+ if (gl && WEBGL.has(type) && !contexts.some((c) => c.gl === gl)) track(this, gl)
153
+ return gl
154
+ },
155
+ })
156
+ let last = performance.now()
157
+ const raf = window.requestAnimationFrame.bind(window)
158
+ const tick = (now) => {
159
+ for (const c of contexts) {
160
+ try {
161
+ if (!c.gl.isContextLost() && c.gl.getError() !== 0) errors++
162
+ } catch {}
163
+ }
164
+ frames.push({ draws, triangles, ms: now - last })
165
+ last = now
166
+ draws = 0
167
+ triangles = 0
168
+ if (frames.length > 2000) frames.splice(0, 1000)
169
+ raf(tick)
170
+ }
171
+ raf(tick)
172
+ let lost = null
173
+ const read = (action) => {
174
+ if (action === "frames") return frames.length
175
+ const live = contexts.filter((c) => !c.gl.isContextLost())
176
+ if (action === "lose") {
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]
178
+ // Kept: a lost context's getExtension returns null, so restore needs this same object
179
+ lost = c && c.gl.getExtension("WEBGL_lose_context")
180
+ if (!lost) return false
181
+ lost.loseContext()
182
+ return true
183
+ }
184
+ if (action === "restore") {
185
+ if (!lost) return false
186
+ try {
187
+ lost.restoreContext()
188
+ } catch {}
189
+ lost = null
190
+ return true
191
+ }
192
+ const shown = contexts.filter((c) => c.canvas.isConnected).sort((a, b) => b.canvas.clientWidth * b.canvas.clientHeight - a.canvas.clientWidth * a.canvas.clientHeight)[0]
193
+ const count = (set) => live.reduce((n, c) => n + c.live[set].size, 0)
194
+ let textureBytes = 0
195
+ let bufferBytes = 0
196
+ for (const c of live) for (const b of c.bytes.values()) b.kind === "texture" ? (textureBytes += b.n) : (bufferBytes += b.n)
197
+ let renderer = null
198
+ if (shown) {
199
+ try {
200
+ const d = shown.gl.getExtension("WEBGL_debug_renderer_info")
201
+ renderer = String(shown.gl.getParameter(d ? d.UNMASKED_RENDERER_WEBGL : shown.gl.RENDERER))
202
+ } catch {}
203
+ }
204
+ return {
205
+ contexts: contexts.length,
206
+ frames: frames.length,
207
+ recent: frames.slice(-${FRAMES}),
208
+ errors,
209
+ live: { textures: count("textures"), buffers: count("buffers"), programs: count("programs"), framebuffers: count("framebuffers"), renderbuffers: count("renderbuffers") },
210
+ textureBytes: Math.round(textureBytes),
211
+ bufferBytes: Math.round(bufferBytes),
212
+ renderer,
213
+ canvas: shown ? { width: shown.canvas.width, height: shown.canvas.height, clientWidth: shown.canvas.clientWidth, clientHeight: shown.canvas.clientHeight, lost: shown.gl.isContextLost() } : null,
214
+ }
215
+ }
216
+ Object.defineProperty(window, "${READ}", { configurable: false, writable: false, value: read })
217
+ })()`
218
+
219
+ const median = (xs) => {
220
+ if (!xs.length) return 0
221
+ const s = [...xs].sort((a, b) => a - b)
222
+ return s[Math.floor((s.length - 1) / 2)]
223
+ }
224
+ const p95 = (xs) => {
225
+ if (!xs.length) return 0
226
+ const s = [...xs].sort((a, b) => a - b)
227
+ return s[Math.min(s.length - 1, Math.ceil(s.length * 0.95) - 1)]
228
+ }
229
+
230
+ /** A screenshot's look over a downsampled grid: luminance variance and distinct (4-bit) colours. */
231
+ export function canvasLook(png) {
232
+ const p = decodePng(png)
233
+ if (!p) return null
234
+ const step = Math.max(1, Math.floor(Math.min(p.width, p.height) / 48))
235
+ const colours = new Set()
236
+ let n = 0
237
+ let sum = 0
238
+ let sq = 0
239
+ const samples = []
240
+ for (let y = 0; y < p.height; y += step)
241
+ for (let x = 0; x < p.width; x += step) {
242
+ const i = (y * p.width + x) * p.channels
243
+ const [r, g, b] = [p.data[i], p.data[i + 1], p.data[i + 2]]
244
+ colours.add(((r >> 4) << 8) | ((g >> 4) << 4) | (b >> 4))
245
+ const l = 0.2126 * r + 0.7152 * g + 0.0722 * b
246
+ n++
247
+ sum += l
248
+ sq += l * l
249
+ samples.push(r, g, b)
250
+ }
251
+ return { variance: n ? sq / n - (sum / n) ** 2 : 0, colours: colours.size, samples }
252
+ }
253
+ export const blank = (look) => !look || look.variance < 4 || look.colours < 8
254
+ /** The share of sampled channels that differ between two looks. */
255
+ export const moved = (a, b) => {
256
+ if (!a || !b || a.samples.length !== b.samples.length) return 0
257
+ let d = 0
258
+ for (let i = 0; i < a.samples.length; i++) if (Math.abs(a.samples[i] - b.samples[i]) > 6) d++
259
+ return d / a.samples.length
260
+ }
261
+
262
+ const evidenceDir = (root, label) =>
263
+ 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, "-")}`)
264
+
265
+ /**
266
+ * G-3D on the confirmed app's direction routes. `app` and `direction` may be
267
+ * given (tests); otherwise the stack's app and the project's scene_direction.json.
268
+ * @returns {Promise<{ id: "G-3D", status: "pass" | "fail" | "not_checked", reason?: string, kind?: string, excerpt?: string, note?: string, optional?: true, report?: any }>}
269
+ */
270
+ export async function threeGate({ root, label, launch, app: givenApp, direction: givenDirection, budgetMs }) {
271
+ const app = givenApp ?? readStack(root).app
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 }
273
+ const direction = givenDirection ?? readDirection(root)
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 }
275
+ const dir = evidenceDir(root, label)
276
+ const run = await withGateBrowser((_open, browser) => checkScenes(browser, app, direction, dir, budgetMs ? { budgetMs } : {}), { launch })
277
+ if (run.unavailable) return { id: "G-3D", status: "not_checked", reason: run.unavailable }
278
+ return run.value
279
+ }
280
+
281
+ async function openPage(browser, url, { viewport, reducedMotion = "no-preference" }) {
282
+ const target = localUrl(url)
283
+ if (target.error) throw new Error(target.error)
284
+ const context = await browser.newContext({ viewport: { width: viewport.width, height: viewport.height }, deviceScaleFactor: viewport.dpr, reducedMotion, acceptDownloads: false, serviceWorkers: "block" })
285
+ await context.route("**/*", (route) => (route.request().isNavigationRequest() && localUrl(route.request().url()).error ? route.abort("blockedbyclient") : route.continue()))
286
+ // The gate's own page only: never the agent's page, never the whole context
287
+ const page = await context.newPage()
288
+ await page.addInitScript(WRAP)
289
+ const consoleErrors = []
290
+ let bytes = 0
291
+ page.on("console", (m) => m.type() === "error" && consoleErrors.push(m.text().slice(0, 300)))
292
+ page.on("pageerror", (e) => consoleErrors.push(String(e?.message ?? e).slice(0, 300)))
293
+ page.on("response", async (r) => {
294
+ const n = Number(r.headers()["content-length"])
295
+ bytes += Number.isFinite(n) ? n : (await r.body().catch(() => Buffer.alloc(0))).length
296
+ })
297
+ const started = Date.now()
298
+ try {
299
+ await page.goto(target.url, { waitUntil: "load", timeout: NAV_MS })
300
+ } catch (error) {
301
+ await context.close().catch(() => {})
302
+ return { unreachable: /ERR_CONNECTION_REFUSED/.test(String(error?.message)) ? "nothing answers there" : String(error?.message ?? error).split("\n")[0].slice(0, 200) }
303
+ }
304
+ const read = (action) => page.evaluate(({ name, action }) => window[name]?.(action), { name: READ, action })
305
+ const framesFrom = async (from, n = FRAMES) => {
306
+ await page.waitForFunction(({ name, want }) => (window[name]?.("frames") ?? 0) >= want, { name: READ, want: from + n }, { timeout: FRAME_WAIT_MS, polling: 50 }).catch(() => {})
307
+ return read()
308
+ }
309
+ const shot = async () => {
310
+ const canvas = page.locator("canvas").first()
311
+ if (!(await canvas.count())) return null
312
+ return canvas.screenshot({ timeout: SHOT_MS }).catch(() => null)
313
+ }
314
+ return { page, context, read, framesFrom, shot, consoleErrors, bytes: () => bytes, started }
315
+ }
316
+
317
+ async function checkScenes(browser, app, direction, dir, { budgetMs = GATE_MS } = {}) {
318
+ const deadline = Date.now() + budgetMs
319
+ const late = () => Date.now() > deadline
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 = []
323
+ const reported = []
324
+ const motion = direction.motion ?? "none"
325
+ // Does this browser make WebGL at all? Otherwise not_checked, never pass
326
+ const probe = await openPage(browser, new URL(direction.routes[0].path, app).href, { viewport: VIEWPORTS_3D[0] })
327
+ 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` }
328
+ const hasGl = await probe.page.evaluate(() => Boolean(document.createElement("canvas").getContext("webgl2") || document.createElement("canvas").getContext("webgl"))).catch(() => false)
329
+ await probe.context.close().catch(() => {})
330
+ if (!hasGl) return { id: "G-3D", status: "not_checked", reason: "no WebGL in this browser" }
331
+ let renderer = null
332
+ for (const route of direction.routes)
333
+ for (const viewport of VIEWPORTS_3D) {
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
+ }
339
+ const budget = budgetFor(direction.tiers, viewport.tiers)
340
+ const v = await openPage(browser, new URL(route.path, app).href, { viewport })
341
+ if (v.unreachable) return { id: "G-3D", status: "not_checked", reason: `${app}${route.path} doesn't answer (${v.unreachable})` }
342
+ try {
343
+ const first = await v.framesFrom(0, 30)
344
+ if (!first?.contexts) {
345
+ problems.push(`${at}: no WebGL context was created`)
346
+ continue
347
+ }
348
+ const a = await v.shot()
349
+ const mid = await v.framesFrom(first.frames, 60)
350
+ const b = await v.shot()
351
+ const r = await v.framesFrom(mid.frames, FRAMES - 60)
352
+ renderer ??= r.renderer
353
+ const lookA = canvasLook(a)
354
+ const lookB = canvasLook(b)
355
+ keepShot(dir, `${route.path.replace(/\W+/g, "_") || "root"}-${viewport.name}-f30.png`, a)
356
+ keepShot(dir, `${route.path.replace(/\W+/g, "_") || "root"}-${viewport.name}-f90.png`, b)
357
+ if (v.consoleErrors.length) problems.push(`${at}: console errors (shader compile and link failures are logged here): ${v.consoleErrors.slice(0, 3).join(" | ")}`)
358
+ if (r.errors) problems.push(`${at}: ${r.errors} WebGL error${r.errors === 1 ? "" : "s"} (gl.getError) while drawing`)
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`)
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`)
362
+ const recent = r.recent ?? []
363
+ const drawCalls = median(recent.map((f) => f.draws))
364
+ const tris = median(recent.map((f) => f.triangles))
365
+ if (drawCalls > budget.drawCalls) problems.push(`${at}: ${drawCalls} draw calls a frame (median) over the ${budget.tier} budget of ${budget.drawCalls}; instance or merge`)
366
+ 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`)
367
+ 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`)
368
+ if (v.bytes() > budget.routeBytes) problems.push(`${at}: the route transferred ${mb(v.bytes())}, over the ${budget.tier} budget of ${mb(budget.routeBytes)}`)
369
+ const sizing = bufferProblem(r.canvas, viewport.dpr, budget.dpr)
370
+ if (sizing) problems.push(`${at}: ${sizing}`)
371
+ const deltas = recent.map((f) => f.ms).filter((ms) => ms > 0 && ms < 1000)
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)`)
373
+ // The deeper checks once per route, at the phone width, while the budget lasts
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
+ }
379
+ // Resize: the buffer follows the new CSS size
380
+ await v.page.setViewportSize({ width: viewport.width - 60, height: viewport.height - 100 })
381
+ const resized = await v.framesFrom((await v.read()).frames, 20)
382
+ const after = bufferProblem(resized.canvas, viewport.dpr, budget.dpr)
383
+ if (after) problems.push(`${at}, after a resize: ${after}`)
384
+ // Leaks: unmount and mount again, through the route's own unmount path
385
+ if (route.unmount) {
386
+ const before = (await v.framesFrom((await v.read()).frames, 10)).live
387
+ const go = (path) => v.page.evaluate((p) => (history.pushState({}, "", p), dispatchEvent(new PopStateEvent("popstate"))), path)
388
+ await go(route.unmount)
389
+ await v.framesFrom((await v.read()).frames, 20)
390
+ await go(route.path)
391
+ const after = (await v.framesFrom((await v.read()).frames, 30)).live
392
+ const grew = Object.keys(before).filter((k) => after[k] > before[k] * (1 + LEAK_SLACK) && after[k] > before[k])
393
+ if (grew.length) problems.push(`${at}: GPU objects leak over unmount → mount: ${grew.map((k) => `${k} ${before[k]} → ${after[k]}`).join(", ")}; dispose on unmount`)
394
+ } else reported.push(`${at}: leaks not checked (no "unmount" path for this route in ${DIRECTION})`)
395
+ // Context loss: lose, restore, wait, draw again
396
+ if (await v.read("lose")) {
397
+ await v.page.waitForTimeout(100)
398
+ await v.read("restore")
399
+ await v.page.waitForTimeout(RESTORE_WAIT_MS)
400
+ const after = await v.read()
401
+ const look = canvasLook(await v.shot())
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`)
404
+ } else reported.push(`${at}: context loss not checked (no WEBGL_lose_context)`)
405
+ } finally {
406
+ await v.context.close().catch(() => {})
407
+ }
408
+ // Reduced motion: decorative motion stops
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]) {
411
+ const q = await openPage(browser, new URL(route.path, app).href, { viewport, reducedMotion: "reduce" })
412
+ if (!q.unreachable)
413
+ try {
414
+ await q.framesFrom(0, 30)
415
+ const a = canvasLook(await q.shot())
416
+ await q.framesFrom((await q.read()).frames, 60)
417
+ const b = canvasLook(await q.shot())
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`)
420
+ } finally {
421
+ await q.context.close().catch(() => {})
422
+ }
423
+ }
424
+ }
425
+ const note = [`renderer: ${renderer ?? "unknown"}`, ...reported, ...unknown.map((u) => `not checked: ${u}`)].join("\n")
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 }
428
+ return { id: "G-3D", status: "pass", note }
429
+ }
430
+
431
+ const mb = (n) => `${(n / 2 ** 20).toFixed(1)} MB`