@kriya-ai/harness 0.2.5 → 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 (132) 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 +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 +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 +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 +4 -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/loop/make.js +28 -3
  91. package/src/edit/recipes/assembly.js +352 -0
  92. package/src/edit/recipes/graphic-clips.js +4 -2
  93. package/src/edit/recipes/openings.js +36 -0
  94. package/src/edit/recipes/reel.js +104 -14
  95. package/src/edit/recipes/reference-look.js +29 -0
  96. package/src/edit/recipes/short-from-long.js +3 -3
  97. package/src/edit/recipes/sound.js +71 -0
  98. package/src/edit/runtime/cli.js +26 -5
  99. package/src/edit/runtime/fetch.js +4 -4
  100. package/src/edit/runtime/licences.js +7 -1
  101. package/src/explore.js +103 -0
  102. package/src/failure.js +1 -1
  103. package/src/gate-commands.js +114 -0
  104. package/src/gates/api.js +127 -0
  105. package/src/gates/commands.js +111 -0
  106. package/src/gates/detectors.js +370 -0
  107. package/src/gates/http.js +62 -0
  108. package/src/gates/index.js +196 -0
  109. package/src/gates/page.js +264 -0
  110. package/src/gates/sast.js +64 -0
  111. package/src/gates/stack.js +110 -0
  112. package/src/gates/tenant.js +162 -0
  113. package/src/gates/three.js +407 -0
  114. package/src/gates/ui.js +111 -0
  115. package/src/launch.js +15 -3
  116. package/src/loop.js +199 -7
  117. package/src/mcp.js +126 -0
  118. package/src/milestones.js +188 -0
  119. package/src/modes.js +32 -0
  120. package/src/orchestra.js +43 -0
  121. package/src/outcomes.js +88 -0
  122. package/src/profiles.js +5 -0
  123. package/src/receipts.js +238 -0
  124. package/src/release.js +356 -0
  125. package/src/runstrip.js +122 -0
  126. package/src/stack.js +120 -0
  127. package/src/verify.js +67 -20
  128. package/studio/dist/fonts/fraunces.woff2 +0 -0
  129. package/studio/dist/fonts/geist.woff2 +0 -0
  130. package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
  131. package/studio/dist/studio.css +449 -1
  132. 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,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`