@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,238 @@
1
+ import { execFileSync } from "node:child_process"
2
+ import { createHash } from "node:crypto"
3
+ import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
4
+ import { dirname, join } from "node:path"
5
+
6
+ import { stepLabel } from "./loop.js"
7
+ import { canonical } from "./mcp.js"
8
+ import { CLIENT_VERSION, kriyaHome } from "./paths.js"
9
+ import { redact } from "../plugins/repo/repo.js"
10
+ import { readState } from "./release.js"
11
+ import { progressFiles, readProgress, verdict } from "./verify.js"
12
+
13
+ // Harness 2.0 W19, proof receipts (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
14
+ // DIFFERENTIATORS.md D1, WD-24). What Kriya Harness checked by code on this
15
+ // computer, copied from the session's ledger (progress file): verdicts,
16
+ // attempts, roles, tiers, gate results, cartridge versions. Nothing from model
17
+ // text, and no file contents, prompts, commands, output or paths. A hash chain
18
+ // over the ledger's run records makes any later edit of one visible: `kriya
19
+ // receipt verify` recomputes it and names the first link that fails. It is
20
+ // evidence of what was checked, labelled so, never a guarantee.
21
+
22
+ export const LABEL = "checked on this computer"
23
+ const SEED = "kriya-receipt-1"
24
+ const sha = (text) => createHash("sha256").update(text).digest("hex")
25
+ const CARTRIDGE = /^(kriya-role-[a-z]{2,20})@(\d{1,3}\.\d{1,3}\.\d{1,3})$/
26
+ const ID = /^[A-Za-z0-9_.-]{1,60}$/
27
+
28
+ export class ReceiptError extends Error {}
29
+
30
+ /** h_0 = sha256(seed); h_i = sha256(h_{i-1} ‖ canonical(run_i)). */
31
+ export function chainLinks(runs) {
32
+ const links = []
33
+ let h = sha(SEED)
34
+ for (const run of runs ?? []) links.push((h = sha(h + canonical(run))))
35
+ return links
36
+ }
37
+
38
+ /** The receipt for a ledger, by code only. `meta`: { project, session, commit, client }. */
39
+ export function receiptFrom(progress, meta) {
40
+ const runs = progress.runs ?? []
41
+ const plan = progress.plan
42
+ const v = verdict(progress)
43
+ const cartridges = {}
44
+ for (const b of progress.builders ?? []) {
45
+ const m = CARTRIDGE.exec(b.cartridge ?? "")
46
+ if (m) cartridges[m[1]] = m[2]
47
+ }
48
+ const steps = (plan?.steps ?? []).map((step, i) => {
49
+ const label = stepLabel(plan, i + 1)
50
+ const found = v.steps.find((s) => s.step === label)
51
+ const last = runs.findLast((r) => r.step === label)
52
+ return {
53
+ n: i + 1,
54
+ ...(typeof step.role === "string" && ID.test(step.role) && { role: step.role }),
55
+ verdict: found?.status ?? "not run",
56
+ attempts: found?.attempts ?? 0,
57
+ tiers: (progress.builders ?? []).filter((b) => b.step === label && typeof b.tier === "string" && ID.test(b.tier)).map((b) => b.tier),
58
+ gates: (last?.gates ?? []).filter((g) => /^G-[A-Z0-9-]{2,20}$/.test(g?.id ?? "")).map((g) => ({ id: g.id, status: String(g.status) })),
59
+ }
60
+ })
61
+ const links = chainLinks(runs)
62
+ return {
63
+ receipt: 1,
64
+ label: LABEL,
65
+ project: meta.project,
66
+ session: meta.session,
67
+ ...(meta.commit && { commit: meta.commit }),
68
+ ...(runs.at(-1)?.tree && { tree: runs.at(-1).tree }),
69
+ client: meta.client,
70
+ verdict: v.status,
71
+ ...(Object.keys(cartridges).length && { cartridges }),
72
+ steps,
73
+ runs: runs.length,
74
+ chain: `sha256:${links.at(-1) ?? sha(SEED)}`,
75
+ links,
76
+ }
77
+ }
78
+
79
+ /** The readable receipt: what was checked, how to verify it, and what it isn't. */
80
+ export function receiptMarkdown(r) {
81
+ const lines = [
82
+ `## Proof receipt (${LABEL})`,
83
+ "",
84
+ "What Kriya Harness checked by code on this computer, copied from its own records. Evidence of what was checked, not a guarantee.",
85
+ "",
86
+ `- Verdict: **${r.verdict}**, ${r.runs} check run${r.runs === 1 ? "" : "s"}`,
87
+ ...(r.commit ? [`- Commit: \`${r.commit.slice(0, 12)}\``] : []),
88
+ ...(r.cartridges ? [`- Cartridges: ${Object.entries(r.cartridges).map(([id, v]) => `${id}@${v}`).join(", ")}`] : []),
89
+ `- Kriya Harness ${r.client}`,
90
+ ]
91
+ if (r.steps.length) {
92
+ lines.push("", "| Step | Role | Verdict | Attempts | Tiers | Gates |", "| --- | --- | --- | --- | --- | --- |")
93
+ for (const s of r.steps) lines.push(`| ${s.n} | ${s.role ?? "—"} | ${s.verdict} | ${s.attempts} | ${s.tiers.join(", ") || "—"} | ${s.gates.map((g) => `${g.id} ${g.status}`).join(", ") || "—"} |`)
94
+ }
95
+ lines.push("", `Chain: \`${r.chain}\` (verify with \`kriya receipt verify\`).`)
96
+ return lines.join("\n")
97
+ }
98
+
99
+ const projectKey = (root) => sha(root).slice(0, 16)
100
+ const headOf = (root) => {
101
+ try {
102
+ return execFileSync("git", ["rev-parse", "--verify", "-q", "HEAD"], { cwd: root, encoding: "utf8", env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" }, stdio: ["ignore", "pipe", "ignore"] }).trim()
103
+ } catch {
104
+ return undefined
105
+ }
106
+ }
107
+
108
+ export const receiptFiles = (project, session) => {
109
+ const dir = join(kriyaHome(), "receipts", project)
110
+ return { json: join(dir, `${session}.json`), md: join(dir, `${session}.md`) }
111
+ }
112
+
113
+ /** Builds and writes a session's receipt; returns it with its readable form. */
114
+ export function makeReceipt(root, sessionId) {
115
+ progressFiles(root, sessionId)
116
+ const progress = readProgress(root, sessionId)
117
+ if (!progress.runs?.length && !progress.plan) throw new ReceiptError("That session has no plan and no check runs to put in a receipt.")
118
+ const commit = headOf(root)
119
+ const receipt = receiptFrom(progress, { project: projectKey(root), session: sessionId, ...(/^[0-9a-f]{40}$/.test(commit ?? "") && { commit }), client: CLIENT_VERSION })
120
+ // WD-22: what Kriya refused to run is written down for the person (readable part only: the verified fields stay the ledger's)
121
+ const left = readState(root).forPerson ?? []
122
+ const markdown = [
123
+ receiptMarkdown(receipt),
124
+ ...(left.length
125
+ ? ["", "### For you to run (Kriya never runs these)", "", ...left.map((p) => `- \`${redact(p.command).replace(/`/g, "'").replace(/(https?:\/\/[^\s?#]+)[?#]\S*/g, "$1")}\`: it ${p.why}`)]
126
+ : []),
127
+ ].join("\n")
128
+ const files = receiptFiles(receipt.project, sessionId)
129
+ mkdirSync(dirname(files.json), { recursive: true })
130
+ for (const [file, text] of [[files.json, `${JSON.stringify(receipt, null, 2)}\n`], [files.md, `${markdown}\n`]]) {
131
+ writeFileSync(`${file}.tmp`, text, { mode: 0o600 })
132
+ renameSync(`${file}.tmp`, file)
133
+ }
134
+ return { receipt, markdown, files }
135
+ }
136
+
137
+ /** The project's most recent session with a ledger, for `kriya receipt make` without an id. */
138
+ export function latestSession(root) {
139
+ const dir = dirname(progressFiles(root, "x").json)
140
+ let best
141
+ for (const f of (() => {
142
+ try {
143
+ return readdirSync(dir)
144
+ } catch {
145
+ return []
146
+ }
147
+ })()) {
148
+ if (!f.endsWith(".json") || f === "milestones.json") continue
149
+ const at = statSync(join(dir, f)).mtimeMs
150
+ if (!best || at > best.at) best = { id: f.slice(0, -5), at }
151
+ }
152
+ return best?.id
153
+ }
154
+
155
+ /**
156
+ * Recomputes a receipt from the ledger it names: the chain link by link
157
+ * (the first changed, missing or extra run is named), then every field.
158
+ * @returns {{ ok: boolean, problems: string[] }}
159
+ */
160
+ export function verifyReceipt(text) {
161
+ let r
162
+ try {
163
+ r = JSON.parse(text)
164
+ } catch {
165
+ return { ok: false, problems: ["The receipt isn't JSON."] }
166
+ }
167
+ if (r?.receipt !== 1 || !/^[0-9a-f]{16}$/.test(r.project ?? "") || !/^[A-Za-z0-9_-]{1,128}$/.test(r.session ?? "")) return { ok: false, problems: ["That isn't a Kriya receipt."] }
168
+ let progress
169
+ try {
170
+ progress = JSON.parse(readFileSync(join(kriyaHome(), "progress", r.project, `${r.session}.json`), "utf8"))
171
+ } catch {
172
+ return { ok: false, problems: ["The session's records aren't on this computer, so the receipt can't be checked here."] }
173
+ }
174
+ const problems = []
175
+ const now = chainLinks(progress.runs ?? [])
176
+ const was = Array.isArray(r.links) ? r.links : []
177
+ const n = Math.max(now.length, was.length)
178
+ for (let i = 0; i < n; i++) {
179
+ if (now[i] === was[i]) continue
180
+ problems.push(i >= now.length ? `Run ${i + 1} is in the receipt but no longer in the records.` : i >= was.length ? `Run ${i + 1} was added to the records after the receipt.` : `Run ${i + 1} (step ${progress.runs[i]?.step ?? "?"}) was changed after the receipt: the chain breaks at link ${i + 1}.`)
181
+ break
182
+ }
183
+ if (r.chain !== `sha256:${was.at(-1) ?? sha(SEED)}`) problems.push("The receipt's chain doesn't match its own links.")
184
+ const again = receiptFrom(progress, { project: r.project, session: r.session, ...(r.commit && { commit: r.commit }), client: r.client })
185
+ for (const key of new Set([...Object.keys(again), ...Object.keys(r)]))
186
+ if (key !== "links" && canonical(again[key]) !== canonical(r[key])) problems.push(`"${key}" doesn't match the records.`)
187
+ return { ok: problems.length === 0, problems }
188
+ }
189
+
190
+ /* ─────────────── Harness 2.0 W17: kriya report ─────────────── */
191
+
192
+ /**
193
+ * `kriya report`: a bundle the person attaches to a bug report themselves.
194
+ * Versions, the gates' capability matrix and self-tests, and this project's
195
+ * receipts (already free of file contents, prompts, commands, output, paths
196
+ * and secrets) with their chains, plus the release records' ids and statuses.
197
+ * Commands left for the person are kept with secrets redacted and query
198
+ * strings removed. Nothing is sent anywhere.
199
+ */
200
+ export async function makeReport(root, { gates, now = () => new Date() } = {}) {
201
+ const { gateMatrix, gateSelfTests } = await import("./doctor.js")
202
+ const { readState } = await import("./release.js")
203
+ const project = projectKey(root)
204
+ const receipts = []
205
+ for (const f of (() => {
206
+ try {
207
+ return readdirSync(join(kriyaHome(), "progress", project))
208
+ } catch {
209
+ return []
210
+ }
211
+ })()) {
212
+ if (!f.endsWith(".json") || f === "milestones.json") continue
213
+ const session = f.slice(0, -5)
214
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(session)) continue
215
+ try {
216
+ receipts.push(receiptFrom(readProgress(root, session), { project, session, client: CLIENT_VERSION }))
217
+ } catch {
218
+ // A record that isn't a session's
219
+ }
220
+ }
221
+ const state = readState(root)
222
+ const report = {
223
+ report: 1,
224
+ at: now().toISOString(),
225
+ client: CLIENT_VERSION,
226
+ node: process.versions.node,
227
+ platform: `${process.platform}-${process.arch}`,
228
+ project,
229
+ gates: gates ?? { matrix: await gateMatrix(), selfTests: await gateSelfTests() },
230
+ receipts,
231
+ releases: state.records.map((r) => ({ kind: r.kind, ...(r.target && { target: r.target }), commit: r.commit, ...(r.ready !== undefined && { ready: r.ready }), ...(r.ok !== undefined && { ok: r.ok }), ...(r.lines && { lines: r.lines }) })),
232
+ forPerson: (state.forPerson ?? []).map((p) => ({ why: p.why, command: redact(p.command).replace(/(https?:\/\/[^\s?#]+)[?#][^\s]*/g, "$1") })),
233
+ }
234
+ const file = join(kriyaHome(), "reports", `report-${report.at.replace(/[:.]/g, "-")}.json`)
235
+ mkdirSync(dirname(file), { recursive: true })
236
+ writeFileSync(file, `${JSON.stringify(report, null, 2)}\n`, { mode: 0o600 })
237
+ return { report, file }
238
+ }
package/src/release.js ADDED
@@ -0,0 +1,356 @@
1
+ import { createHash } from "node:crypto"
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
3
+ import { dirname, join, relative } from "node:path"
4
+
5
+ import { localUrl } from "./browser.js"
6
+ import { DETECTORS, findSecrets } from "./gates/detectors.js"
7
+ import { judgeA11y, judgeUi, uiReports } from "./gates/ui.js"
8
+ import { kriyaHome } from "./paths.js"
9
+ import { projectRoot } from "./skill-switches.js"
10
+
11
+ // Harness 2.0 W17, production delivery (Kriya-Tavi docs/kriya-harness/
12
+ // upgrade_2.0/DELIVERY_AND_STABILITY.md §1–4; WD-21, WD-22).
13
+ // - G-RELEASE: local checks of a production build, each line computed by code;
14
+ // `ready` only when every line passes (not checked withholds it).
15
+ // - The path to production: a production deploy needs `ready` and `smoked`
16
+ // records for the same commit.
17
+ // - G-DEPLOYED: the one gate that leaves this machine: GET/HEAD to the host a
18
+ // deploy printed, ≤ 20 requests, no cookies, credentials or body.
19
+ // - WD-22: hosted-database migrations, production environment and secret
20
+ // changes, DNS changes and merges are never run; they're written down for
21
+ // the person instead.
22
+
23
+ export class ReleaseError extends Error {}
24
+
25
+ const sha = (text) => createHash("sha256").update(text).digest("hex")
26
+ const projectKey = (root) => sha(root).slice(0, 16)
27
+ const releaseFile = () => join(kriyaHome(), "release.json")
28
+ const stateFile = (root) => join(kriyaHome(), "releases", `${projectKey(root)}.json`)
29
+
30
+ function readJson(file, fallback) {
31
+ try {
32
+ return JSON.parse(readFileSync(file, "utf8"))
33
+ } catch {
34
+ return fallback
35
+ }
36
+ }
37
+ function writeJson(file, value) {
38
+ mkdirSync(dirname(file), { recursive: true })
39
+ const temp = `${file}.${process.pid}.tmp`
40
+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
41
+ renameSync(temp, file)
42
+ }
43
+
44
+ /* ───────────────────────────── settings ───────────────────────────── */
45
+
46
+ const HOST = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/
47
+ const ROUTE = /^\/[A-Za-z0-9._~\/-]{0,200}$/
48
+
49
+ /**
50
+ * `kriya release use`: the person confirms how a production build is made and
51
+ * checked, once per project. The production server is one the person started
52
+ * and confirmed (`--app`, loopback only): spike S2 didn't establish that a
53
+ * sandboxed command may listen on loopback, so the harness doesn't start it.
54
+ */
55
+ export function useRelease(cwd, options = {}, now = () => new Date()) {
56
+ const root = projectRoot(cwd)
57
+ const all = readJson(releaseFile(), {})
58
+ const entry = { ...(all[root] ?? {}) }
59
+ if (options.build !== undefined) {
60
+ const b = String(options.build).trim()
61
+ if (!b || b.length > 300 || /[\r\n]/.test(b)) throw new ReleaseError("Give the production build command on one line, e.g. --build \"npm run build\".")
62
+ entry.build = b
63
+ }
64
+ if (options.app !== undefined) {
65
+ const checked = localUrl(String(options.app))
66
+ if (checked.error) throw new ReleaseError(`--app: ${checked.error}`)
67
+ entry.app = checked.url ?? String(options.app)
68
+ }
69
+ if (options.out !== undefined) {
70
+ const o = String(options.out).trim()
71
+ if (!o || o.startsWith("/") || o.split(/[\\/]/).includes("..")) throw new ReleaseError("--out is a folder inside the project, e.g. --out dist.")
72
+ entry.out = o
73
+ }
74
+ if (options.budgetKb !== undefined) {
75
+ const n = Number(options.budgetKb)
76
+ if (!Number.isInteger(n) || n < 1 || n > 100_000) throw new ReleaseError("--budget-kb is a whole number of kilobytes.")
77
+ entry.budgetKb = n
78
+ }
79
+ if (options.routes !== undefined) {
80
+ const list = String(options.routes).split(",").map((r) => r.trim()).filter(Boolean)
81
+ if (!list.length || list.length > 10 || list.some((r) => !ROUTE.test(r))) throw new ReleaseError("--routes is up to 10 paths like /,/pricing (no query strings).")
82
+ entry.routes = list
83
+ }
84
+ if (options.domain !== undefined) {
85
+ const d = String(options.domain).trim().toLowerCase()
86
+ if (!HOST.test(d)) throw new ReleaseError("--domain is a host name like app.example.com.")
87
+ entry.domain = d
88
+ }
89
+ if (options.headers !== undefined) {
90
+ const allowed = ["content-security-policy", "strict-transport-security", "x-content-type-options", "x-frame-options"]
91
+ const list = String(options.headers).split(",").map((h) => h.trim().toLowerCase()).filter(Boolean)
92
+ if (list.some((h) => !allowed.includes(h))) throw new ReleaseError(`--headers names some of: ${allowed.join(", ")}.`)
93
+ entry.headers = list
94
+ }
95
+ if (options.marker !== undefined) {
96
+ const m = String(options.marker)
97
+ if (!m || m.length > 120) throw new ReleaseError("--marker is a short text the home page contains.")
98
+ entry.marker = m
99
+ }
100
+ if (!entry.build) throw new ReleaseError('A release needs --build "<command>".')
101
+ entry.confirmedAt = now().toISOString()
102
+ all[root] = entry
103
+ writeJson(releaseFile(), all)
104
+ return entry
105
+ }
106
+
107
+ export const readRelease = (cwd) => readJson(releaseFile(), {})[projectRoot(cwd)]
108
+
109
+ /* ───────────────────────────── G-RELEASE ───────────────────────────── */
110
+
111
+ const line = (id, status, detail) => ({ id, status, ...(detail && { detail: String(detail).slice(0, 1500) }) })
112
+ const SOURCE = /\.(m?[jt]sx?|cjs|py|svelte|vue|astro)$/
113
+ const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", ".next", "out", "coverage", ".venv", "venv", "__pycache__"])
114
+ const ENV_READ = [/process\.env\.([A-Z][A-Z0-9_]*)/g, /process\.env\[["']([A-Z][A-Z0-9_]*)["']\]/g, /import\.meta\.env\.([A-Z][A-Z0-9_]*)/g, /os\.environ\[["']([A-Z][A-Z0-9_]*)["']\]/g, /os\.environ\.get\(["']([A-Z][A-Z0-9_]*)["']/g, /os\.getenv\(["']([A-Z][A-Z0-9_]*)["']/g]
115
+ // Set by platforms and runtimes themselves, never by the person's deployment
116
+ const PLATFORM_ENV = new Set(["NODE_ENV", "CI", "PORT", "HOME", "PATH", "PWD", "TZ", "LANG", "VERCEL", "VERCEL_ENV", "VERCEL_URL"])
117
+
118
+ function walk(root, dir = root, out = [], limit = 3000) {
119
+ for (const name of (() => {
120
+ try {
121
+ return readdirSync(dir)
122
+ } catch {
123
+ return []
124
+ }
125
+ })()) {
126
+ if (out.length >= limit) break
127
+ if (SKIP_DIRS.has(name) || name.startsWith(".")) continue
128
+ const full = join(dir, name)
129
+ let st
130
+ try {
131
+ st = statSync(full)
132
+ } catch {
133
+ continue
134
+ }
135
+ if (st.isDirectory()) walk(root, full, out, limit)
136
+ else out.push(relative(root, full))
137
+ }
138
+ return out
139
+ }
140
+
141
+ /** REL-ENV: every variable the source reads is named in .env.example (names only, never values). */
142
+ export function envCompleteness(root) {
143
+ const read = new Set()
144
+ for (const rel of walk(root).filter((f) => SOURCE.test(f))) {
145
+ let text
146
+ try {
147
+ text = readFileSync(join(root, rel), "utf8")
148
+ } catch {
149
+ continue
150
+ }
151
+ if (text.length > 1024 * 1024) continue
152
+ for (const re of ENV_READ) for (const m of text.matchAll(re)) if (!PLATFORM_ENV.has(m[1])) read.add(m[1])
153
+ }
154
+ const example = existsSync(join(root, ".env.example")) ? readFileSync(join(root, ".env.example"), "utf8") : ""
155
+ const named = new Set([...example.matchAll(/^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=/gm)].map((m) => m[1]))
156
+ const missing = [...read].filter((v) => !named.has(v)).sort()
157
+ if (!read.size) return line("REL-ENV", "pass", "the source reads no environment variables")
158
+ return missing.length ? line("REL-ENV", "fail", `Read in the source but not in .env.example: ${missing.join(", ")}. A deployment wouldn't know to set them.`) : line("REL-ENV", "pass")
159
+ }
160
+
161
+ /** The build output's JS and CSS against the budget in release.json. */
162
+ export function bundleBudget(root, release) {
163
+ if (!release?.budgetKb) return line("BUNDLE", "pass", "no budget set (kriya release use --budget-kb)")
164
+ const out = join(root, release.out ?? "dist")
165
+ if (!existsSync(out)) return line("BUNDLE", "not_checked", `no build output at ${release.out ?? "dist"}`)
166
+ let total = 0
167
+ for (const rel of walk(out, out, [], 20_000)) if (/\.(m?js|css)$/.test(rel)) total += statSync(join(out, rel)).size
168
+ const kb = Math.ceil(total / 1024)
169
+ return kb > release.budgetKb ? line("BUNDLE", "fail", `${kb} KB of JS and CSS, over the ${release.budgetKb} KB budget`) : line("BUNDLE", "pass", `${kb} KB of ${release.budgetKb} KB`)
170
+ }
171
+
172
+ /** Lockfile present and in step with package.json; production dependencies' licences on the allow-list. */
173
+ export function dependencies(root) {
174
+ const pkg = readJson(join(root, "package.json"), undefined)
175
+ if (!pkg) return line("DEPS", "pass", "no package.json")
176
+ const lock = readJson(join(root, "package-lock.json"), undefined)
177
+ const hasOther = ["pnpm-lock.yaml", "yarn.lock", "bun.lockb"].some((f) => existsSync(join(root, f)))
178
+ if (!lock && !hasOther) return line("DEPS", "fail", "no lockfile: the deployment could install other versions than the ones checked")
179
+ const problems = []
180
+ if (lock) {
181
+ const locked = lock.packages?.[""] ?? {}
182
+ for (const field of ["dependencies", "devDependencies"])
183
+ for (const [name, range] of Object.entries(pkg[field] ?? {}))
184
+ if (locked[field]?.[name] !== range) problems.push(`${name} ${range} isn't in package-lock.json as declared (run the install again)`)
185
+ }
186
+ const ALLOWED = /^(MIT|ISC|0BSD|BSD-2-Clause|BSD-3-Clause|Apache-2\.0|MPL-2\.0|Unlicense|CC0-1\.0|BlueOak-1\.0\.0)$/
187
+ for (const name of Object.keys(pkg.dependencies ?? {})) {
188
+ const dep = readJson(join(root, "node_modules", name, "package.json"), undefined)
189
+ if (!dep) continue
190
+ const lic = typeof dep.license === "string" ? dep.license : dep.license?.type
191
+ const ok = typeof lic === "string" && lic.replace(/[()]/g, "").split(/\s+OR\s+/).some((l) => ALLOWED.test(l.trim()))
192
+ if (!ok) problems.push(`${name}: licence ${lic ?? "not stated"} isn't on the allow-list`)
193
+ }
194
+ return problems.length ? line("DEPS", "fail", problems.slice(0, 12).join("\n")) : line("DEPS", "pass")
195
+ }
196
+
197
+ /** Migrations and secrets over the release diff: DB-DROP and OPS-MIGRATE-LOCK as errors here; G-SECRETS. */
198
+ export function diffChecks(files) {
199
+ const migrations = []
200
+ for (const id of ["DB-DROP", "OPS-MIGRATE-LOCK"]) {
201
+ const d = DETECTORS[id]
202
+ for (const f of files.filter((f) => d.files(f.path))) for (const hit of d.find(f)) migrations.push(`${f.path}:${hit.line} ${hit.why}`)
203
+ }
204
+ const secrets = files.flatMap((f) => findSecrets(f).map((s) => `${f.path}:${s.line} (${s.why})`))
205
+ return [
206
+ migrations.length ? line("MIGRATIONS", "fail", `Needs an explicit two-step plan in the contract:\n${migrations.join("\n")}`) : line("MIGRATIONS", "pass"),
207
+ secrets.length ? line("G-SECRETS", "fail", secrets.join("\n")) : line("G-SECRETS", "pass"),
208
+ ]
209
+ }
210
+
211
+ /**
212
+ * G-RELEASE on the current commit. `host.run(command)` runs the confirmed
213
+ * build under the session's sandbox; `host.files` gives the release diff's
214
+ * files ({ path, content, added }); `host.rendered(app)` runs G-UI and G-A11Y
215
+ * against the production server.
216
+ */
217
+ export async function gRelease(cwd, host) {
218
+ const root = projectRoot(cwd)
219
+ const release = readRelease(root)
220
+ if (!release) throw new ReleaseError('No release is confirmed for this project. The person runs kriya release use --build "<command>" --app http://localhost:<port> once.')
221
+ const lines = []
222
+ const built = await host.run(release.build)
223
+ lines.push(built.exitCode === 0 && !built.timedOut ? line("BUILD", "pass") : line("BUILD", "fail", `${release.build} exited ${built.timedOut ? "on its time limit" : built.exitCode}:\n${String(built.output ?? "").slice(-1200)}`))
224
+ if (!release.app) lines.push(line("RENDERED", "not_checked", "no production server is confirmed: start it and run kriya release use --app http://localhost:<port>"))
225
+ else {
226
+ const results = await (host.rendered ?? defaultRendered(root))(release.app)
227
+ for (const r of results) lines.push(line(r.id, r.status, r.excerpt ?? r.reason))
228
+ }
229
+ lines.push(envCompleteness(root), bundleBudget(root, release), dependencies(root), ...diffChecks(await host.files()))
230
+ const ready = lines.every((l) => l.status === "pass")
231
+ return { commit: await host.commit(), ready, lines }
232
+ }
233
+
234
+ const defaultRendered = (root) => async (app) => {
235
+ const pages = await uiReports({ root, label: "release", app })
236
+ return [judgeUi(pages), judgeA11y(pages)].map((r) => (r.status === "not_checked" && r.optional ? { ...r, status: "not_checked" } : r))
237
+ }
238
+
239
+ /* ─────────────────────────── ready and smoked ─────────────────────────── */
240
+
241
+ export const readState = (root) => readJson(stateFile(root), { records: [], forPerson: [] })
242
+ function record(root, entry) {
243
+ const state = readState(root)
244
+ state.records = [...state.records, entry].slice(-50)
245
+ writeJson(stateFile(root), state)
246
+ return state
247
+ }
248
+ export const recordReady = (root, commit, ready, lines) => record(root, { kind: "ready", commit, ready, lines: lines.map((l) => ({ id: l.id, status: l.status })), at: new Date().toISOString() })
249
+ export const recordSmoke = (root, entry) => record(root, { kind: "smoke", at: new Date().toISOString(), ...entry })
250
+
251
+ /** Production needs a passing `ready` and a passing preview `smoked` for this very commit. */
252
+ export function productionAllowed(root, commit) {
253
+ const records = readState(root).records
254
+ const ready = records.findLast((r) => r.kind === "ready" && r.commit === commit)
255
+ const smoked = records.findLast((r) => r.kind === "smoke" && r.target === "preview" && r.commit === commit)
256
+ if (!ready?.ready) return { ok: false, why: "G-RELEASE hasn't passed on this commit (release_check)." }
257
+ if (!smoked?.ok) return { ok: false, why: "No preview of this commit has passed G-DEPLOYED yet (deploy a preview first)." }
258
+ return { ok: true }
259
+ }
260
+
261
+ /* ─────────────────────────── WD-22: the person's ─────────────────────────── */
262
+
263
+ // Commands the harness never runs; each is written down for the person instead
264
+ export const PERSONS_ONLY = [
265
+ [/\bsupabase\s+db\s+(push|reset)\b/i, "applies migrations to a hosted database"],
266
+ [/\bsupabase\s+migration\s+up\b[^\n]*--linked/i, "applies migrations to a hosted database"],
267
+ [/\bprisma\s+(migrate\s+(deploy|reset)|db\s+push)\b/i, "changes the schema of the database DATABASE_URL points at"],
268
+ [/\b(drizzle-kit|knex|sequelize|typeorm|alembic|flyway|liquibase)\b[^\n]*\b(migrate|push|upgrade|migration:run)\b/i, "runs database migrations"],
269
+ [/\b(vercel|netlify)\s+env\s+(add|rm|remove|set|unset|pull)\b|\bnetlify\s+env:(set|unset|import)\b/i, "changes a deployment's environment variables"],
270
+ [/\bwrangler\s+secret\s+(put|delete|bulk)\b|\b(fly|flyctl)\s+secrets\s+(set|unset|import)\b|\bheroku\s+config:(set|unset)\b/i, "changes production secrets"],
271
+ [/\b(vercel\s+(dns|domains)|netlify\s+(dns|domains)|wrangler\s+dns|(fly|flyctl)\s+(certs|ips)|aws\s+route53|gcloud\s+dns)\b/i, "changes DNS or domains"],
272
+ [/\bgh\s+pr\s+merge\b|\bglab\s+mr\s+merge\b|\bgit\s+merge\b|\bgit\s+push\b[^\n]*\s(-f|--force|--force-with-lease)\b|\bgit\s+push\b[^\n]*[\s:](main|master)(\s|$)/i, "merges or rewrites a shared branch"],
273
+ [/\b(vercel\s+(rm|remove)|netlify\s+sites:delete|wrangler\s+pages\s+(project|deployment)\s+delete|(fly|flyctl)\s+(apps\s+destroy|destroy))\b/i, "deletes a deployment or app"],
274
+ ]
275
+
276
+ /** Why a command is the person's alone, or undefined. */
277
+ export const personsOnly = (command) => PERSONS_ONLY.find(([re]) => re.test(String(command ?? "")))?.[1]
278
+
279
+ /** Writes the refused command down for the person (it goes into the receipt and release state). */
280
+ export function forPerson(root, command, why) {
281
+ const state = readState(root)
282
+ const entry = { command: String(command).slice(0, 500), why, at: new Date().toISOString() }
283
+ state.forPerson = [...(state.forPerson ?? []), entry].slice(-20)
284
+ writeJson(stateFile(root), state)
285
+ return entry
286
+ }
287
+
288
+ /* ───────────────────────────── G-DEPLOYED ───────────────────────────── */
289
+
290
+ export const DEPLOYED_MAX_REQUESTS = 20
291
+ const SECURITY = { "content-security-policy": "Content-Security-Policy", "strict-transport-security": "Strict-Transport-Security", "x-content-type-options": "X-Content-Type-Options", "x-frame-options": "X-Frame-Options" }
292
+
293
+ /**
294
+ * Checks a deployed URL: only its host, GET/HEAD only, no cookies,
295
+ * credentials or body, redirects followed only within the host, at most 20
296
+ * requests. Each route in release.json must answer 2xx (HTML for pages),
297
+ * the home page must contain the marker if one is set, and the headers the
298
+ * project listed must be present. Latency is reported, never gated.
299
+ */
300
+ export async function gDeployed(target, release, { fetchImpl = fetch, now = Date.now } = {}) {
301
+ let base
302
+ try {
303
+ base = new URL(target)
304
+ } catch {
305
+ return { id: "G-DEPLOYED", status: "fail", problems: ["not a URL"], requests: 0 }
306
+ }
307
+ if (base.protocol !== "https:" || base.username || base.password) return { id: "G-DEPLOYED", status: "fail", problems: ["only an https URL without credentials is checked"], requests: 0 }
308
+ const host = base.host
309
+ let requests = 0
310
+ const problems = []
311
+ const timings = []
312
+ const get = async (path, method = "GET") => {
313
+ let url = new URL(path, base)
314
+ for (let hop = 0; hop < 5; hop++) {
315
+ if (url.host !== host || url.protocol !== "https:") throw new ReleaseError(`a redirect left ${host}`)
316
+ if (requests >= DEPLOYED_MAX_REQUESTS) throw new ReleaseError(`the ${DEPLOYED_MAX_REQUESTS}-request limit`)
317
+ requests++
318
+ const started = now()
319
+ const res = await fetchImpl(url, { method, redirect: "manual", credentials: "omit", headers: { accept: "text/html,*/*" }, signal: AbortSignal.timeout(15_000) })
320
+ timings.push(now() - started)
321
+ if (res.status >= 300 && res.status < 400 && res.headers.get("location")) {
322
+ url = new URL(res.headers.get("location"), url)
323
+ continue
324
+ }
325
+ return res
326
+ }
327
+ throw new ReleaseError("too many redirects")
328
+ }
329
+ const routes = release?.routes?.length ? release.routes : ["/"]
330
+ try {
331
+ for (const route of routes) {
332
+ const res = await get(route)
333
+ if (res.status < 200 || res.status > 299) problems.push(`${route} answered ${res.status}`)
334
+ else if (!/text\/html|application\/json/.test(res.headers.get("content-type") ?? "")) problems.push(`${route} answered ${res.headers.get("content-type") ?? "no content type"}`)
335
+ if (route === routes[0]) {
336
+ if (release?.marker && !(await res.text()).includes(release.marker)) problems.push(`${route} doesn't contain the marker text`)
337
+ for (const h of release?.headers ?? []) {
338
+ const v = res.headers.get(h)
339
+ if (h === "x-frame-options" && !v && /frame-ancestors/.test(res.headers.get("content-security-policy") ?? "")) continue
340
+ if (!v) problems.push(`the ${SECURITY[h]} header is missing`)
341
+ }
342
+ }
343
+ }
344
+ } catch (error) {
345
+ problems.push(`stopped: ${error?.message ?? error}`)
346
+ }
347
+ const sorted = [...timings].sort((a, b) => a - b)
348
+ return {
349
+ id: "G-DEPLOYED",
350
+ status: problems.length ? "fail" : "pass",
351
+ host,
352
+ requests,
353
+ ...(sorted.length && { medianMs: sorted[Math.floor((sorted.length - 1) / 2)] }),
354
+ ...(problems.length && { problems }),
355
+ }
356
+ }