@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
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
+ }
@@ -0,0 +1,122 @@
1
+ import { basename } from "node:path"
2
+
3
+ import { currentMilestone } from "./milestones.js"
4
+ import { MAX_ATTEMPTS, stepLabel } from "./verify.js"
5
+
6
+ // Harness 2.0 W18 (WD-23; Kriya-Tavi docs/kriya-harness/upgrade_2.0/HARNESS_UX.md):
7
+ // what the Run strip, the gate chips and Mission Control show, computed only
8
+ // from the loop's ledger (progress file, the live build record, the milestone
9
+ // ledger) and Kriya's /me figures. Never from model text (track-A rule 7).
10
+ // Pure, so the browser halves only draw what this returns.
11
+
12
+ /** The four right-column tracks and the existing tab kinds they are (the old ids stay valid). */
13
+ export const TRACKS = Object.freeze({ live: "kriya-preview", proof: "kriya-progress", changes: "kriya-changes", project: "kriya-overview" })
14
+ export const TRACK_ORDER = Object.freeze(["live", "proof", "changes", "project"])
15
+
16
+ /** A gate chip's five states (HARNESS_UX §3.2) and the word each shows; colour is never alone. */
17
+ export const CHIP_STATES = Object.freeze(["waiting", "running", "passed", "failed", "not-checked"])
18
+ const WORD = { waiting: "waiting", running: "checking", passed: "passed", failed: "failed", "not-checked": "not checked" }
19
+ const FROM_RUN = { pass: "passed", fail: "failed", not_checked: "not-checked", running: "running", waiting: "waiting" }
20
+
21
+ export const gateName = (id) => String(id ?? "").replace(/^G-/, "")
22
+ const oneLine = (text, limit) => String(text ?? "").replace(/\s+/g, " ").trim().slice(0, limit)
23
+
24
+ /**
25
+ * One gate result as a chip. `pending`: the step is being built again, so a
26
+ * recorded result is only waiting to be re-checked.
27
+ * @param {{ id: string, status?: string, reason?: string, note?: string }} gate
28
+ */
29
+ export function chipOf(gate, { pending = false } = {}) {
30
+ const state = pending ? "waiting" : (FROM_RUN[gate?.status] ?? "waiting")
31
+ const detail = state === "failed" || state === "not-checked" ? oneLine(gate.reason ?? gate.note, 80) : ""
32
+ return { id: String(gate?.id ?? ""), state, text: `${gateName(gate?.id)} · ${WORD[state]}${detail ? `: ${detail}` : ""}` }
33
+ }
34
+
35
+ /** Micro-INR (an integer) as rupees and paise, for display only; no float crosses this line. */
36
+ export function formatInr(micro) {
37
+ const paise = Math.round(Math.max(0, Math.trunc(Number(micro) || 0)) / 10_000)
38
+ return `₹${Math.trunc(paise / 100)}.${String(paise % 100).padStart(2, "0")}`
39
+ }
40
+
41
+ /** "6m", "1h 04m", "42s": the strip's elapsed time. */
42
+ export function formatElapsed(ms) {
43
+ const s = Math.max(0, Math.floor((Number(ms) || 0) / 1000))
44
+ if (s < 60) return `${s}s`
45
+ const m = Math.floor(s / 60)
46
+ return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h ${String(m % 60).padStart(2, "0")}m`
47
+ }
48
+
49
+ /**
50
+ * The Run strip for one session, or `{ running: false }` when nothing is
51
+ * being built (the strip is then 0 px).
52
+ * @param {{ sessionId: string, progress: any, live?: any, ledger?: any, orchestra?: { head: string, worker: string }, names?: Record<string, string>, since?: number, spend?: { inr: string, estimated: boolean } | null, now?: number }} input
53
+ */
54
+ export function stripState({ sessionId, progress, live, ledger, orchestra, names = {}, since, spend = null, now = Date.now() }) {
55
+ const plan = progress?.plan
56
+ if (!live || !plan?.steps?.[live.n - 1]) return { running: false }
57
+ const label = stepLabel(plan, live.n)
58
+ const runs = (progress.runs ?? []).filter((r) => r.step === label)
59
+ const builders = (progress.builders ?? []).filter((b) => b.step === label && !b.polish)
60
+ const tier = (t) => (typeof t === "string" && t ? { level: orchestra && t === orchestra.head ? "Head" : "Worker", model: oneLine(names[t], 80) || `Kriya ${t}` } : null)
61
+ const m = currentMilestone(ledger)
62
+ return {
63
+ running: true,
64
+ sessionId,
65
+ milestone: ledger?.milestones?.length && m !== -1 ? { n: m + 1, of: ledger.milestones.length } : null,
66
+ step: { n: live.n, of: plan.steps.length, title: oneLine(plan.steps[live.n - 1].title, 120) },
67
+ attempt: { n: Math.min(runs.length + 1, MAX_ATTEMPTS), of: MAX_ATTEMPTS, ...(live.polish && { polish: true }) },
68
+ tier: tier(live.tier),
69
+ gates: (runs.at(-1)?.gates ?? []).map((g) => chipOf(g, { pending: true })),
70
+ elapsedMs: Math.max(0, now - (since ?? live.startedAt)),
71
+ spend,
72
+ attempts: [
73
+ ...runs.map((r, i) => ({
74
+ n: i + 1,
75
+ tier: tier(builders[i]?.tier)?.level ?? null,
76
+ outcome: r.status === "pass" ? "passed" : (r.kind ?? (r.status === "blocked" ? "blocked" : "failed")),
77
+ gates: (r.gates ?? []).map((g) => chipOf(g)),
78
+ durationMs: (builders[i]?.ms ?? 0) + (r.durationMs ?? 0),
79
+ })),
80
+ { n: runs.length + 1, tier: tier(live.tier)?.level ?? null, outcome: "building", gates: [], durationMs: Math.max(0, now - live.startedAt) },
81
+ ],
82
+ }
83
+ }
84
+
85
+ /** Each plan step's chips: its last run's gates (Proof track). */
86
+ export const stepChips = (progress) =>
87
+ (progress?.plan?.steps ?? []).map((_, i) => {
88
+ const label = stepLabel(progress.plan, i + 1)
89
+ return { n: i + 1, chips: ((progress.runs ?? []).findLast((r) => r.step === label)?.gates ?? []).map((g) => chipOf(g)) }
90
+ })
91
+
92
+ /** The latest result of the page gates (G-UI, G-A11Y) the Live track draws over the frame. */
93
+ export function liveGates(progress) {
94
+ const seen = new Map()
95
+ for (const r of progress?.runs ?? []) for (const g of r.gates ?? []) if (g.id === "G-UI" || g.id === "G-A11Y") seen.set(g.id, chipOf(g))
96
+ return [...seen.values()]
97
+ }
98
+
99
+ /**
100
+ * Mission Control's rows: one per milestone ledger (a mission), with what it
101
+ * waits for, decided by code from the ledger's statuses.
102
+ * @param {Array<{ root: string, ledger: any, running?: boolean }>} entries
103
+ */
104
+ export function missionRows(entries) {
105
+ return entries
106
+ .filter((e) => e.ledger?.milestones?.length)
107
+ .map(({ root, ledger, running = false }) => {
108
+ const list = ledger.milestones
109
+ const i = currentMilestone(ledger)
110
+ const done = list.filter((x) => x.status === "done").length
111
+ const current = i === -1 ? null : list[i]
112
+ const status = i === -1 ? "done" : current.status === "blocked" ? "blocked" : running ? "running" : current.status === "active" ? "active" : "todo"
113
+ const waiting = {
114
+ done: "Nothing: every milestone is done.",
115
+ blocked: `You: milestone ${i + 1} is blocked; see its Proof track.`,
116
+ running: "Nothing: a step is being built.",
117
+ active: "You: ask the agent to go on with this milestone.",
118
+ todo: "You: ask the agent to plan the next milestone.",
119
+ }[status]
120
+ return { project: basename(root), root, done, of: list.length, current: current ? { n: i + 1, title: oneLine(current.title, 120) } : null, status, waiting }
121
+ })
122
+ }
package/src/stack.js ADDED
@@ -0,0 +1,120 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
2
+ import { dirname, join } from "node:path"
3
+
4
+ import { localUrl } from "./browser.js"
5
+ import { kriyaHome } from "./paths.js"
6
+ import { projectRoot } from "./skill-switches.js"
7
+
8
+ // Harness 2.0 W4, the local stack (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
9
+ // GATES.md §2, WD-05): the app and database the person runs on this computer
10
+ // for live gates (G-UI, G-A11Y, G-STACK). The harness never starts Docker or a
11
+ // database itself. The person confirms them once per project with `kriya
12
+ // stack use`; both must be loopback addresses. Kept in ~/.kriya/stack.json,
13
+ // outside the project, so the agent can't point a gate somewhere else.
14
+
15
+ export class StackError extends Error {}
16
+
17
+ export const stackFile = () => join(kriyaHome(), "stack.json")
18
+
19
+ const LOOPBACK = (host) => host === "localhost" || host.endsWith(".localhost") || host === "::1" || /^127(\.\d{1,3}){3}$/.test(host)
20
+
21
+ /** A postgres URL's host, if it parses; "" for a socket path (local by definition) */
22
+ export function databaseHost(url) {
23
+ try {
24
+ const u = new URL(url)
25
+ if (!/^postgres(ql)?:$/.test(u.protocol)) return null
26
+ const fromQuery = u.searchParams.get("host")
27
+ if (!u.hostname && fromQuery?.startsWith("/")) return ""
28
+ return u.hostname.replace(/^\[|\]$/g, "") || (fromQuery ?? "")
29
+ } catch {
30
+ return null
31
+ }
32
+ }
33
+
34
+ export const isLocalDatabase = (url) => {
35
+ const host = databaseHost(url)
36
+ return host !== null && (host === "" || LOOPBACK(host))
37
+ }
38
+
39
+ /** The database URL in a form safe to show: no password. */
40
+ export function shownDatabase(url) {
41
+ try {
42
+ const u = new URL(url)
43
+ u.password = u.password ? "****" : ""
44
+ return u.href
45
+ } catch {
46
+ return "(unreadable)"
47
+ }
48
+ }
49
+
50
+ function read() {
51
+ try {
52
+ const value = JSON.parse(readFileSync(stackFile(), "utf8"))
53
+ return value && typeof value.projects === "object" ? value.projects : {}
54
+ } catch {
55
+ return {}
56
+ }
57
+ }
58
+
59
+ function write(projects) {
60
+ const file = stackFile()
61
+ mkdirSync(dirname(file), { recursive: true })
62
+ const temp = `${file}.${process.pid}.tmp`
63
+ writeFileSync(temp, `${JSON.stringify({ version: 1, projects }, null, 2)}\n`, { mode: 0o600 })
64
+ renameSync(temp, file)
65
+ }
66
+
67
+ /** Confirms the project's app and/or database; refuses anything that isn't on this computer. */
68
+ export function useStack(cwd, { app, db } = {}, now = () => new Date()) {
69
+ if (!app && !db) throw new StackError('Give --app http://localhost:<port> and/or --db postgresql://…@127.0.0.1:<port>/<db>.')
70
+ const root = projectRoot(cwd)
71
+ const entry = { ...(read()[root] ?? {}) }
72
+ if (app) {
73
+ const checked = localUrl(app)
74
+ if (checked.error) throw new StackError(`--app: ${checked.error}`)
75
+ entry.app = checked.url
76
+ }
77
+ if (db) {
78
+ if (!isLocalDatabase(db)) throw new StackError("--db must be a postgres URL on this computer (localhost, 127.0.0.1, ::1 or a socket). Gates never touch a hosted database.")
79
+ entry.db = db
80
+ }
81
+ entry.confirmedAt = now().toISOString()
82
+ const projects = read()
83
+ projects[root] = entry
84
+ write(projects)
85
+ return { root, ...entry }
86
+ }
87
+
88
+ export function forgetStack(cwd) {
89
+ const root = projectRoot(cwd)
90
+ const projects = read()
91
+ const had = root in projects
92
+ delete projects[root]
93
+ write(projects)
94
+ return had
95
+ }
96
+
97
+ /** The confirmed stack for this project, or {} */
98
+ export function readStack(cwd) {
99
+ return read()[projectRoot(cwd)] ?? {}
100
+ }
101
+
102
+ const ENV_FILES = [".env", ".env.local", ".env.development", ".env.development.local"]
103
+ const DB_VARS = /^\s*(?:export\s+)?(DATABASE_URL|DIRECT_URL|POSTGRES_URL|POSTGRES_PRISMA_URL|SUPABASE_DB_URL|PG_URL|DB_URL)\s*=\s*["']?([^"'\s#]+)/
104
+
105
+ /**
106
+ * A database URL in the project's own env files that points off this computer
107
+ * (operator rule 6's lesson: a project's .env may be the live database). Stack
108
+ * gates refuse to run while one exists. Returns the variable and file, never the URL.
109
+ */
110
+ export function hostedDatabase(root) {
111
+ for (const name of ENV_FILES) {
112
+ const file = join(root, name)
113
+ if (!existsSync(file)) continue
114
+ for (const line of readFileSync(file, "utf8").split("\n")) {
115
+ const m = DB_VARS.exec(line)
116
+ if (m && /^postgres(ql)?:\/\//.test(m[2]) && !isLocalDatabase(m[2])) return { variable: m[1], file: name }
117
+ }
118
+ }
119
+ return null
120
+ }