@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,114 @@
1
+ import { createHash } from "node:crypto"
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
3
+ import { dirname, join } from "node:path"
4
+
5
+ import { kriyaHome } from "./paths.js"
6
+ import { projectRoot } from "./skill-switches.js"
7
+
8
+ // Harness 2.0 W6: the commands the command-running gates use (Kriya-Tavi
9
+ // docs/kriya-harness/upgrade_2.0/GATES.md §3: G-DATA, G-EVAL, G-SAN, G-IAC,
10
+ // G-SIM, G-SIM-HEADLESS). A model never writes a gate's command (WD-04): the
11
+ // person confirms each one per project with `kriya gates use`, the same trust
12
+ // as `kriya verify use`. Kept in ~/.kriya/gates.json, outside the project; the
13
+ // G-EVAL baseline beside it, in ~/.kriya/evidence, so a builder can't move it.
14
+
15
+ export class GateCommandError extends Error {}
16
+
17
+ export const COMMAND_GATES = {
18
+ data: { id: "G-DATA", what: "runs the data pipeline on its dirty fixture", options: ["output"] },
19
+ eval: { id: "G-EVAL", what: "runs the evaluation and writes a metrics JSON file", options: ["metrics", "metric", "direction", "margin"] },
20
+ san: { id: "G-SAN", what: "builds and tests with warnings as errors and sanitizers on", options: [] },
21
+ iac: { id: "G-IAC", what: "validates and policy-checks the infrastructure offline (no apply)", options: [] },
22
+ sim: { id: "G-SIM", what: "builds and launches the app on a simulator or emulator", options: [] },
23
+ "sim-headless": { id: "G-SIM-HEADLESS", what: "runs the game's seeded headless simulation and prints STATE-HASH:", options: ["frameBudgetMs"] },
24
+ }
25
+ const LIMIT = 500
26
+
27
+ export const gatesFile = () => join(kriyaHome(), "gates.json")
28
+
29
+ function read() {
30
+ try {
31
+ const v = JSON.parse(readFileSync(gatesFile(), "utf8"))
32
+ return v && typeof v.projects === "object" ? v.projects : {}
33
+ } catch {
34
+ return {}
35
+ }
36
+ }
37
+
38
+ function write(file, value) {
39
+ mkdirSync(dirname(file), { recursive: true })
40
+ const temp = `${file}.${process.pid}.tmp`
41
+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
42
+ renameSync(temp, file)
43
+ }
44
+
45
+ const relative = (value) => {
46
+ const v = String(value ?? "").trim()
47
+ if (!v || v.startsWith("/") || v.split(/[\\/]/).includes("..")) throw new GateCommandError("Paths are relative to the project and stay inside it.")
48
+ return v
49
+ }
50
+
51
+ /** Confirms one gate's command (and its options) for this project. */
52
+ export function useGateCommand(cwd, gate, command, options = {}, now = () => new Date()) {
53
+ const spec = COMMAND_GATES[gate]
54
+ if (!spec) throw new GateCommandError(`The gates that run a command are: ${Object.keys(COMMAND_GATES).join(", ")}.`)
55
+ const text = typeof command === "string" ? command.trim() : ""
56
+ if (!text || text.length > LIMIT || /[\r\n]/.test(text)) throw new GateCommandError(`A gate command is one line of at most ${LIMIT} characters.`)
57
+ const entry = { command: text, confirmedAt: now().toISOString() }
58
+ if (gate === "data") {
59
+ if (!options.output) throw new GateCommandError("G-DATA needs --output <file or folder the pipeline writes>, to compare two runs.")
60
+ entry.output = relative(options.output)
61
+ }
62
+ if (gate === "eval") {
63
+ if (!options.metrics || !options.metric) throw new GateCommandError("G-EVAL needs --metrics <file.json> and --metric <name>, e.g. --metrics eval/metrics.json --metric f1.")
64
+ entry.metrics = relative(options.metrics)
65
+ entry.metric = String(options.metric).slice(0, 80)
66
+ entry.direction = options.direction === "lower" ? "lower" : "higher"
67
+ const margin = Number(options.margin ?? 0)
68
+ if (!Number.isFinite(margin) || margin < 0) throw new GateCommandError("--margin is a number ≥ 0.")
69
+ entry.margin = margin
70
+ }
71
+ if (gate === "sim-headless" && options.frameBudgetMs !== undefined) {
72
+ const ms = Number(options.frameBudgetMs)
73
+ if (!Number.isFinite(ms) || ms <= 0) throw new GateCommandError("--frame-budget-ms is a number above 0.")
74
+ entry.frameBudgetMs = ms
75
+ }
76
+ const root = projectRoot(cwd)
77
+ const projects = read()
78
+ projects[root] = { ...(projects[root] ?? {}), [gate]: entry }
79
+ write(gatesFile(), { version: 1, projects })
80
+ return { root, gate, ...entry }
81
+ }
82
+
83
+ export function forgetGateCommand(cwd, gate) {
84
+ const root = projectRoot(cwd)
85
+ const projects = read()
86
+ const had = Boolean(projects[root]?.[gate])
87
+ if (projects[root]) delete projects[root][gate]
88
+ write(gatesFile(), { version: 1, projects })
89
+ return had
90
+ }
91
+
92
+ /** This project's confirmed gate commands: { data?: {...}, eval?: {...}, … } */
93
+ export const gateCommands = (cwd) => read()[projectRoot(cwd)] ?? {}
94
+
95
+ const baselineFile = (root) => join(kriyaHome(), "evidence", createHash("sha256").update(root).digest("hex").slice(0, 16), "eval-baseline.json")
96
+ const candidateFile = (root) => baselineFile(root).replace(/baseline\.json$/, "candidate.json")
97
+
98
+ export function readBaseline(root) {
99
+ try {
100
+ return JSON.parse(readFileSync(baselineFile(root), "utf8"))
101
+ } catch {
102
+ return null
103
+ }
104
+ }
105
+ export const writeCandidate = (root, value) => write(candidateFile(root), value)
106
+
107
+ /** `kriya eval baseline confirm`: the last recorded first run becomes the baseline; only the person does this. */
108
+ export function confirmBaseline(cwd) {
109
+ const root = projectRoot(cwd)
110
+ if (!existsSync(candidateFile(root))) throw new GateCommandError("There's no recorded run to confirm yet: run the work with --gates once, then confirm.")
111
+ const candidate = JSON.parse(readFileSync(candidateFile(root), "utf8"))
112
+ write(baselineFile(root), { ...candidate, confirmedAt: new Date().toISOString() })
113
+ return candidate
114
+ }
@@ -0,0 +1,127 @@
1
+ import { randomUUID } from "node:crypto"
2
+ import { existsSync, readFileSync } from "node:fs"
3
+ import { join } from "node:path"
4
+
5
+ import { Ajv2020 } from "ajv/dist/2020.js"
6
+
7
+ import { CONTRACTS_DIR, resolvePointer } from "../contracts.js"
8
+ import { readStack } from "../stack.js"
9
+ import { Budget, fill, local, median, p95 } from "./http.js"
10
+ import { signIn, tenantConfig } from "./tenant.js"
11
+
12
+ // Harness 2.0 W5: G-API (Kriya-Tavi docs/kriya-harness/upgrade_2.0/GATES.md
13
+ // §3). Against the app the person confirmed (`kriya stack use --app`), for
14
+ // each operation of .kriya/contracts/api.openapi.json that carries an
15
+ // `x-kriya-example`: the example answers the contract's status with a body
16
+ // its schema accepts; seeded bad inputs get a 4xx, never a 5xx or a 2xx; an
17
+ // operation marked `x-kriya-idempotent` has one effect for ten concurrent
18
+ // requests with one Idempotency-Key. Latency is reported, never gated.
19
+ // These requests reach the person's local app, writes included; never anything else.
20
+
21
+ export const MAX_OPERATIONS = 10
22
+ const METHODS = ["get", "post", "put", "patch", "delete"]
23
+ const esc = (s) => String(s).replace(/~/g, "~0").replace(/\//g, "~1")
24
+
25
+ /** Bad request bodies made from the request schema, deterministic: [why, body] */
26
+ export function badBodies(schema, example) {
27
+ const out = []
28
+ const props = schema?.properties ?? {}
29
+ const base = example && typeof example === "object" && !Array.isArray(example) ? example : {}
30
+ for (const field of (schema?.required ?? []).slice(0, 3)) {
31
+ const { [field]: _gone, ...rest } = base
32
+ void _gone
33
+ out.push([`without required "${field}"`, rest])
34
+ }
35
+ const WRONG = { string: 12345, integer: "not a number", number: "not a number", boolean: "not a boolean", array: { not: "an array" }, object: "not an object" }
36
+ for (const [field, p] of Object.entries(props).slice(0, 3)) if (WRONG[p?.type] !== undefined) out.push([`"${field}" of the wrong type`, { ...base, [field]: WRONG[p.type] }])
37
+ for (const [field, p] of Object.entries(props)) {
38
+ if (p?.type === "string" && Number.isInteger(p.maxLength)) {
39
+ out.push([`"${field}" longer than its maxLength ${p.maxLength}`, { ...base, [field]: "x".repeat(p.maxLength + 1) }])
40
+ break
41
+ }
42
+ }
43
+ out.push(["a body that isn't JSON", "{"])
44
+ return out
45
+ }
46
+
47
+ const countOf = (r) => (Array.isArray(r.json) ? r.json.length : Number.isFinite(r.json?.count) ? r.json.count : Number.isFinite(r.json?.total) ? r.json.total : undefined)
48
+
49
+ /**
50
+ * @param {{ root: string, request?: typeof fetch }} input
51
+ * @returns {Promise<{ id: string, status: string, kind?: string, excerpt?: string, reason?: string, optional?: boolean, note?: string }>}
52
+ */
53
+ export async function apiGate({ root, request }) {
54
+ const id = "G-API"
55
+ const file = join(root, CONTRACTS_DIR, "api.openapi.json")
56
+ if (!existsSync(file)) return { id, status: "pass", note: "no API contract in this project" }
57
+ const { app } = readStack(root)
58
+ if (!app) return { id, status: "not_checked", optional: true, reason: "no app is confirmed for this project (kriya stack use --app http://localhost:<port>)" }
59
+ let doc
60
+ try {
61
+ doc = JSON.parse(readFileSync(file, "utf8"))
62
+ } catch {
63
+ return { id, status: "not_checked", reason: "api.openapi.json isn't valid JSON (G-CONTRACT reports it)" }
64
+ }
65
+ const ops = Object.entries(doc.paths ?? {})
66
+ .flatMap(([path, item]) => METHODS.filter((m) => item?.[m]?.["x-kriya-example"]).map((method) => ({ path, method, op: item[method] })))
67
+ .slice(0, MAX_OPERATIONS)
68
+ if (!ops.length) return { id, status: "not_checked", reason: 'no operation in api.openapi.json has an "x-kriya-example" to call' }
69
+ const ajv = new Ajv2020({ strict: false, allErrors: true, validateFormats: false })
70
+ ajv.addSchema(doc, "kriya-api")
71
+ const budget = new Budget()
72
+ const problems = []
73
+ const times = []
74
+ const tenants = tenantConfig(root)
75
+ const auth = {}
76
+ const headersFor = async (who) => {
77
+ if (!who) return {}
78
+ if (!tenants.config) throw new Error(`the example signs in as ${who}, but .kriya/gates/tenants.json is missing`)
79
+ auth[who] ??= await signIn(app, tenants.config, who, budget, request)
80
+ return auth[who].headers
81
+ }
82
+ try {
83
+ for (const { path, method, op } of ops) {
84
+ const ex = op["x-kriya-example"]
85
+ const label = `${method.toUpperCase()} ${path}`
86
+ const url = fill(ex.path ?? path, ex.params)
87
+ const headers = await headersFor(ex.auth)
88
+ const res = await local(app, url, { method: method.toUpperCase(), body: ex.body, headers, budget, request })
89
+ times.push(res.ms)
90
+ const wanted = ex.status ?? Number(Object.keys(op.responses ?? {}).find((s) => /^2\d\d$/.test(s)))
91
+ if (res.status === 0) {
92
+ problems.push(`${label}: no answer (${res.error})`)
93
+ continue
94
+ }
95
+ if (res.status !== wanted) problems.push(`${label}: answered ${res.status}, the contract's example expects ${wanted}${res.status >= 500 ? " (a server error)" : ""}`)
96
+ const pointer = `/paths/${esc(path)}/${method}/responses/${res.status}/content/application~1json/schema`
97
+ if (resolvePointer(doc, pointer) !== undefined) {
98
+ const validate = ajv.compile({ $ref: `kriya-api#${pointer}` })
99
+ if (!validate(res.json)) problems.push(`${label}: the ${res.status} body doesn't match the contract: ${validate.errors.slice(0, 3).map((e) => `${e.instancePath || "/"} ${e.message}`).join("; ")}`)
100
+ }
101
+ const reqPointer = `/paths/${esc(path)}/${method}/requestBody/content/application~1json/schema`
102
+ let schema = resolvePointer(doc, reqPointer)
103
+ if (schema?.$ref?.startsWith("#/")) schema = resolvePointer(doc, schema.$ref.slice(1))
104
+ if (schema && ["post", "put", "patch"].includes(method))
105
+ for (const [why, body] of badBodies(schema, ex.body)) {
106
+ const bad = await local(app, url, { method: method.toUpperCase(), body, headers, budget, request })
107
+ if (bad.status < 400 || bad.status >= 500) problems.push(`${label} ${why}: answered ${bad.status || bad.error}, expected a 4xx`)
108
+ }
109
+ const idem = op["x-kriya-idempotent"]
110
+ if (idem?.count) {
111
+ const before = countOf(await local(app, idem.count, { headers, budget, request }))
112
+ const key = randomUUID()
113
+ const replies = await Promise.all(Array.from({ length: 10 }, () => local(app, url, { method: method.toUpperCase(), body: ex.body, headers: { ...headers, "Idempotency-Key": key }, budget, request })))
114
+ const after = countOf(await local(app, idem.count, { headers, budget, request }))
115
+ const statuses = [...new Set(replies.map((r) => r.status))]
116
+ if (before === undefined || after === undefined) problems.push(`${label}: ${idem.count} doesn't return a list or { count }, so the effect can't be counted`)
117
+ else if (after - before !== 1) problems.push(`${label}: ten requests with one Idempotency-Key made ${after - before} effects, expected 1`)
118
+ if (statuses.some((s) => s < 200 || s >= 300)) problems.push(`${label}: with one Idempotency-Key, answers were ${statuses.join(", ")}`)
119
+ }
120
+ }
121
+ } catch (error) {
122
+ return { id, status: "fail", kind: "gate", excerpt: `G-API: ${String(error?.message ?? error).slice(0, 300)}` }
123
+ }
124
+ const note = `${ops.length} operation(s); latency p50 ${Math.round(median(times) ?? 0)} ms, p95 ${Math.round(p95(times) ?? 0)} ms (reported, not gated)`
125
+ if (problems.length) return { id, status: "fail", kind: "gate", excerpt: `G-API (against ${app}):\n${problems.slice(0, 15).map((p) => `- ${p}`).join("\n")}`, note }
126
+ return { id, status: "pass", note }
127
+ }
@@ -0,0 +1,111 @@
1
+ import { createHash } from "node:crypto"
2
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
3
+ import { join, relative } from "node:path"
4
+
5
+ import { gateCommands, readBaseline, writeCandidate } from "../gate-commands.js"
6
+
7
+ // Harness 2.0 W6: the gates that run a command the person confirmed (`kriya
8
+ // gates use`): G-DATA, G-EVAL, G-SAN, G-IAC, G-SIM, G-SIM-HEADLESS
9
+ // (Kriya-Tavi docs/kriya-harness/upgrade_2.0/GATES.md §3). Commands run
10
+ // through the same sandboxed runner as the project's check; none is ever
11
+ // written by a model. Without a confirmed command: not_checked, never pass.
12
+
13
+ const tail = (s, n = 1500) => String(s ?? "").slice(-n)
14
+ const nc = (id, gate) => ({ id, status: "not_checked", reason: `no command is confirmed for ${id} (kriya gates use ${gate} "<command>")` })
15
+ const ran = (r) => r.exitCode === 0 && !r.timedOut
16
+
17
+ /** A content hash of a file or a folder (paths and bytes, sorted), and its line count; null if missing */
18
+ export function outputDigest(root, rel) {
19
+ const abs = join(root, rel)
20
+ if (!existsSync(abs)) return null
21
+ const files = []
22
+ const walk = (p) => {
23
+ if (statSync(p).isDirectory()) for (const n of readdirSync(p).sort()) walk(join(p, n))
24
+ else files.push(p)
25
+ }
26
+ walk(abs)
27
+ const h = createHash("sha256")
28
+ let lines = 0
29
+ for (const f of files.slice(0, 2000)) {
30
+ const bytes = readFileSync(f)
31
+ h.update(relative(abs, f)).update("\0").update(bytes)
32
+ lines += bytes.toString("utf8").split("\n").length - 1
33
+ }
34
+ return { sha: h.digest("hex").slice(0, 16), files: files.length, lines }
35
+ }
36
+
37
+ /** G-DATA: the pipeline twice on its fixture: both succeed, and the output is identical */
38
+ export async function dataGate({ root, command }) {
39
+ const cfg = gateCommands(root).data
40
+ if (!cfg) return nc("G-DATA", "data")
41
+ const first = await command(cfg.command)
42
+ if (!ran(first)) return { id: "G-DATA", status: "fail", kind: "gate", excerpt: `G-DATA: the pipeline failed (${first.timedOut ? "timed out" : `exit ${first.exitCode}`}):\n${tail(first.output)}` }
43
+ const a = outputDigest(root, cfg.output)
44
+ const second = await command(cfg.command)
45
+ if (!ran(second)) return { id: "G-DATA", status: "fail", kind: "gate", excerpt: `G-DATA: the pipeline failed when run again (${second.timedOut ? "timed out" : `exit ${second.exitCode}`}):\n${tail(second.output)}` }
46
+ const b = outputDigest(root, cfg.output)
47
+ if (!a || !b) return { id: "G-DATA", status: "fail", kind: "gate", excerpt: `G-DATA: the pipeline wrote nothing at ${cfg.output}` }
48
+ if (a.sha !== b.sha) return { id: "G-DATA", status: "fail", kind: "gate", excerpt: `G-DATA: running the pipeline twice changed its output at ${cfg.output} (${a.lines} → ${b.lines} lines): it isn't idempotent. Upsert or merge on a key, and replace partitions atomically.` }
49
+ return { id: "G-DATA", status: "pass", note: `two runs, identical output (${b.files} file(s), ${b.lines} lines)` }
50
+ }
51
+
52
+ // The evaluation itself: a work that changes it can't be judged by it
53
+ export const EVAL_FILES = /(^|\/)(evals?|evaluation|benchmarks?)\/|(^|\/)(eval|evaluate|evaluation)[\w-]*\.(py|js|mjs|ts|ipynb|ya?ml|json)$/
54
+
55
+ /** G-EVAL: the confirmed evaluation; its metric must not regress past the confirmed baseline */
56
+ export async function evalGate({ root, command, changed = [], now = Date.now }) {
57
+ const cfg = gateCommands(root).eval
58
+ if (!cfg) return nc("G-EVAL", "eval")
59
+ const touched = changed.filter((rel) => EVAL_FILES.test(rel) && rel !== cfg.metrics)
60
+ if (touched.length) return { id: "G-EVAL", status: "not_checked", reason: `this work changed the evaluation itself (${touched.slice(0, 3).join(", ")}), so it can't judge the work; a person reviews evaluation changes` }
61
+ const started = now()
62
+ const out = await command(cfg.command)
63
+ if (!ran(out)) return { id: "G-EVAL", status: "fail", kind: "gate", excerpt: `G-EVAL: the evaluation failed (${out.timedOut ? "timed out" : `exit ${out.exitCode}`}):\n${tail(out.output)}` }
64
+ const file = join(root, cfg.metrics)
65
+ if (!existsSync(file) || statSync(file).mtimeMs < started - 1000) return { id: "G-EVAL", status: "fail", kind: "gate", excerpt: `G-EVAL: the evaluation didn't write ${cfg.metrics} in this run` }
66
+ let value
67
+ try {
68
+ value = JSON.parse(readFileSync(file, "utf8"))?.[cfg.metric]
69
+ } catch {
70
+ // Reported below
71
+ }
72
+ if (!Number.isFinite(value)) return { id: "G-EVAL", status: "fail", kind: "gate", excerpt: `G-EVAL: ${cfg.metrics} has no number "${cfg.metric}"` }
73
+ const baseline = readBaseline(root)
74
+ if (!baseline || baseline.metric !== cfg.metric) {
75
+ writeCandidate(root, { metric: cfg.metric, value, direction: cfg.direction, at: new Date().toISOString() })
76
+ return { id: "G-EVAL", status: "not_checked", reason: `no confirmed baseline yet: ${cfg.metric} = ${value} recorded; kriya eval baseline confirm makes it the baseline` }
77
+ }
78
+ const worse = cfg.direction === "lower" ? value > baseline.value + cfg.margin : value < baseline.value - cfg.margin
79
+ if (worse) return { id: "G-EVAL", status: "fail", kind: "gate", excerpt: `G-EVAL: ${cfg.metric} is ${value}, worse than the confirmed baseline ${baseline.value} (${cfg.direction} is better, margin ${cfg.margin}). A change ships only if it holds or beats the baseline.` }
80
+ return { id: "G-EVAL", status: "pass", note: `${cfg.metric} ${value} vs baseline ${baseline.value}` }
81
+ }
82
+
83
+ const SANITIZER = /==\d+==ERROR: (AddressSanitizer|LeakSanitizer)|WARNING: ThreadSanitizer|runtime error: |ERROR: AddressSanitizer|SUMMARY: (Address|Thread|Undefined|Leak)Sanitizer/
84
+
85
+ /** G-SAN, G-IAC, G-SIM: the confirmed command exits 0 (G-SAN also fails on any sanitizer report) */
86
+ export async function commandGate({ root, command, gate, id }) {
87
+ const cfg = gateCommands(root)[gate]
88
+ if (!cfg) return nc(id, gate)
89
+ const out = await command(cfg.command)
90
+ if (id === "G-SAN" && SANITIZER.test(out.output ?? "")) return { id, status: "fail", kind: "gate", excerpt: `G-SAN: a sanitizer reported a problem:\n${tail(String(out.output).split("\n").filter((l) => SANITIZER.test(l) || /^\s+#\d+ /.test(l)).slice(0, 30).join("\n"))}` }
91
+ if (!ran(out)) return { id, status: "fail", kind: "gate", excerpt: `${id}: \`${cfg.command}\` ${out.timedOut ? "timed out" : `exited ${out.exitCode}`}:\n${tail(out.output)}` }
92
+ return { id, status: "pass" }
93
+ }
94
+
95
+ const HASH = /^STATE-HASH:\s*([0-9a-fA-F]{8,128})\s*$/m
96
+ const FRAME = /^FRAME-MS-MEDIAN:\s*([\d.]+)\s*$/m
97
+
98
+ /** G-SIM-HEADLESS: the seeded simulation twice; the same STATE-HASH both times; the median frame time within budget if one is set */
99
+ export async function simHeadlessGate({ root, command }) {
100
+ const cfg = gateCommands(root)["sim-headless"]
101
+ if (!cfg) return nc("G-SIM-HEADLESS", "sim-headless")
102
+ const runs = [await command(cfg.command), await command(cfg.command)]
103
+ const bad = runs.find((r) => !ran(r))
104
+ if (bad) return { id: "G-SIM-HEADLESS", status: "fail", kind: "gate", excerpt: `G-SIM-HEADLESS: the simulation ${bad.timedOut ? "timed out" : `exited ${bad.exitCode}`}:\n${tail(bad.output)}` }
105
+ const hashes = runs.map((r) => HASH.exec(r.output ?? "")?.[1])
106
+ if (hashes.some((h) => !h)) return { id: "G-SIM-HEADLESS", status: "fail", kind: "gate", excerpt: "G-SIM-HEADLESS: the simulation must print STATE-HASH: <hex> of its final state" }
107
+ if (hashes[0] !== hashes[1]) return { id: "G-SIM-HEADLESS", status: "fail", kind: "gate", excerpt: `G-SIM-HEADLESS: the same seed gave two different final states (${hashes[0]} vs ${hashes[1]}): the simulation isn't deterministic (wall clock, unseeded random, frame-rate-dependent steps)` }
108
+ const frame = Number(FRAME.exec(runs[1].output ?? "")?.[1])
109
+ if (cfg.frameBudgetMs && Number.isFinite(frame) && frame > cfg.frameBudgetMs) return { id: "G-SIM-HEADLESS", status: "fail", kind: "gate", excerpt: `G-SIM-HEADLESS: median frame time ${frame} ms is over the ${cfg.frameBudgetMs} ms budget` }
110
+ return { id: "G-SIM-HEADLESS", status: "pass", note: `deterministic (${hashes[0].slice(0, 12)})${Number.isFinite(frame) ? `, median frame ${frame} ms` : ""}` }
111
+ }