@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,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
+ }
package/src/verify.js CHANGED
@@ -220,15 +220,22 @@ const git = (cwd, args, input, encoding = "utf8") =>
220
220
  * @returns {Promise<{ fingerprint: string, changed: string[] } | undefined>}
221
221
  * changed: paths that differ from HEAD (staged, unstaged, untracked)
222
222
  */
223
- export async function workTree(cwd) {
223
+ export async function workTree(cwd, base = "HEAD") {
224
224
  const status = await git(cwd, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"])
225
225
  if (status === null) return undefined
226
226
  const head = ((await git(cwd, ["rev-parse", "--verify", "-q", "HEAD"])) ?? "no commit").trim()
227
227
  const root = ((await git(cwd, ["rev-parse", "--show-toplevel"])) ?? cwd).trim()
228
- const changed = status
229
- .split("\0")
230
- .filter(Boolean)
231
- .map((entry) => entry.slice(3))
228
+ // Harness 2.0 W16: with a plan's base (repository tools on), files committed since it count as changed too
229
+ const committed = base === "HEAD" ? "" : ((await git(root, ["diff", "--name-only", "-z", "--no-renames", base, "HEAD"])) ?? "")
230
+ const changed = [
231
+ ...new Set([
232
+ ...status
233
+ .split("\0")
234
+ .filter(Boolean)
235
+ .map((entry) => entry.slice(3)),
236
+ ...committed.split("\0").filter(Boolean),
237
+ ]),
238
+ ]
232
239
  const present = changed.filter((rel) => existsSync(join(root, rel)))
233
240
  const hashes = present.length ? await git(root, ["hash-object", "--stdin-paths"], present.join("\n") + "\n") : ""
234
241
  const fingerprint = createHash("sha256").update(`${head}\0${status}\0${hashes ?? "unreadable"}`).digest("hex").slice(0, 16)
@@ -258,14 +265,14 @@ export const checkFiles = (paths) => paths.filter((p) => CHECK_FILE.some((re) =>
258
265
  * session's first checkpoint.
259
266
  * @returns {Promise<undefined | Awaited<ReturnType<typeof run>>>} undefined outside a repository or before a first commit
260
267
  */
261
- export async function onOriginals(cwd, paths, run) {
268
+ export async function onOriginals(cwd, paths, run, base = "HEAD") {
262
269
  const root = (await git(cwd, ["rev-parse", "--show-toplevel"]))?.trim()
263
- if (!root || (await git(root, ["rev-parse", "--verify", "-q", "HEAD"])) === null) return undefined
270
+ if (!root || (await git(root, ["rev-parse", "--verify", "-q", base])) === null) return undefined
264
271
  const saved = []
265
272
  try {
266
273
  for (const rel of paths) {
267
274
  const file = join(root, rel)
268
- const original = await git(root, ["show", `HEAD:${rel}`], undefined, "buffer")
275
+ const original = await git(root, ["show", `${base}:${rel}`], undefined, "buffer")
269
276
  const entry = { file, mine: existsSync(file) ? readFileSync(file) : null }
270
277
  saved.push(entry)
271
278
  if (original === null) rmSync(file, { force: true })
@@ -303,7 +310,8 @@ const matches = (pattern, rel) => (/\*+$/.test(pattern) ? rel.startsWith(pattern
303
310
  async function strictBefore(cwd, plan, work, run, defensive) {
304
311
  const root = await gitRoot(cwd)
305
312
  if (!root || !work?.changed.length) return undefined
306
- const head = (rel) => git(root, ["show", `HEAD:${rel}`])
313
+ const base = baseOf(plan)
314
+ const head = (rel) => git(root, ["show", `${base}:${rel}`])
307
315
  const hit = work.changed.find((rel) => plan?.invariants?.some((p) => matches(p, rel)))
308
316
  if (hit) return refusal("invariant broken", "the plan's invariants", `${hit} must not change in this task (the plan's invariants). Put it back and solve this another way.`)
309
317
  const checks = new Set(checkFiles(work.changed))
@@ -321,7 +329,7 @@ async function strictBefore(cwd, plan, work, run, defensive) {
321
329
  let neighbours = []
322
330
  if (defensive) {
323
331
  const graph = importGraph(root)
324
- const diffs = await diffsOf(root, work.changed)
332
+ const diffs = await diffsOf(root, work.changed, base)
325
333
  const found = sentinel(diffs, { tenancy: graph.files.some((rel) => /\bwithUser\(/.test(graph.text(rel))) })
326
334
  if (found.length) return refusal("invariant violated", "the invariant sentinel", findings(found.map((f) => `${f.file}:${f.line} [${f.rule}] ${f.why}`)))
327
335
  // The neighbours' suites too: the work isn't done if it passes here and breaks there
@@ -338,8 +346,15 @@ async function strictBefore(cwd, plan, work, run, defensive) {
338
346
  return undefined
339
347
  }
340
348
 
341
- const diffsOf = async (root, changed) =>
342
- Promise.all(changed.map(async (rel) => ({ rel, before: await git(root, ["show", `HEAD:${rel}`]), after: fileNow(join(root, rel)) })))
349
+ const diffsOf = async (root, changed, base = "HEAD") =>
350
+ Promise.all(changed.map(async (rel) => ({ rel, before: await git(root, ["show", `${base}:${rel}`]), after: fileNow(join(root, rel)) })))
351
+
352
+ /**
353
+ * Harness 2.0 W16 (repository tools): "the code before this session" is the
354
+ * commit kriya_plan recorded, so a commit made in the session can't make
355
+ * weakened tests the new originals. Without one, HEAD, exactly as before.
356
+ */
357
+ export const baseOf = (plan) => (typeof plan?.base === "string" && /^[0-9a-f]{40}$/.test(plan.base) ? plan.base : "HEAD")
343
358
 
344
359
  const findings = (lines) => `${lines.slice(0, 12).join("\n")}${lines.length > 12 ? `\n… ${lines.length - 12} more` : ""}`
345
360
 
@@ -351,7 +366,7 @@ const findings = (lines) => `${lines.slice(0, 12).join("\n")}${lines.length > 12
351
366
  async function defensiveAfter(cwd, plan, work) {
352
367
  const root = await gitRoot(cwd)
353
368
  if (!root || !work?.changed.length) return undefined
354
- const diffs = await diffsOf(root, work.changed)
369
+ const diffs = await diffsOf(root, work.changed, baseOf(plan))
355
370
  const hazards = reviewDiff(importGraph(root), diffs)
356
371
  if (hazards.length) return refusal("regression hazard", "the diff review", findings(hazards.map((h) => `${h.file}${h.line ? `:${h.line}` : ""} [${h.hazard}] ${h.why}`)))
357
372
  const surface = newSurface(diffs)
@@ -377,7 +392,7 @@ async function strictAfter(cwd, sessionId, plan, work, check, run, defensive, fi
377
392
  if (!code.length) return undefined
378
393
  // The red phase, proved: on the code as it was, the check (with any new test) must fail
379
394
  const kept = await checkpoint(cwd, sessionId, "before the check on the old code").catch(() => undefined)
380
- const old = kept && (await onOriginals(cwd, code, () => run(check.command)))
395
+ const old = kept && (await onOriginals(cwd, code, () => run(check.command), baseOf(plan)))
381
396
  if (old?.aborted) throw new VerifyError("The check was stopped.")
382
397
  if (old?.exitCode === 0 && !old.timedOut)
383
398
  return refusal("no reproduction", check.command, "The check also passes on the code before your change, so nothing proves the bug or its fix. Add a test that fails on the old code and passes on the new.")
@@ -499,7 +514,7 @@ export const stepLabel = (plan, n) => normalStep(`${n} ${plan.steps[n - 1].title
499
514
  * guard (KRIYA_LOOP_GUARD=on): a failure's class and excerpt too, with its signature, and the excerpt kept in the run so a resumed step can use it
500
515
  * strict (KRIYA_STRICT_LOOP=on): the checks of strictBefore and strictAfter around the person's check; never in Read only
501
516
  */
502
- export async function verifyStep({ cwd, sessionId, step, run, now = () => new Date(), tree = workTree, v2, guard, strict }) {
517
+ export async function verifyStep({ cwd, sessionId, step, run, now = () => new Date(), tree = workTree, v2, guard, strict, gates, expect }) {
503
518
  const label = normalStep(step)
504
519
  const check = confirmedCheck(cwd)
505
520
  if (!check) return { status: "not configured", step: label, suggestions: discoverChecks(cwd) }
@@ -507,9 +522,10 @@ export async function verifyStep({ cwd, sessionId, step, run, now = () => new Da
507
522
  if (before?.status === "blocked") return { status: "blocked", step: label, attempts: before.attempts, command: check.command }
508
523
  // The files this run checks, taken before the command (a check that writes
509
524
  // files, e.g. a build, doesn't make its own pass stale)
510
- const work = await tree(cwd)
525
+ const base = baseOf(readProgress(check.root, sessionId).plan)
526
+ const work = await (base === "HEAD" ? tree(cwd) : tree(cwd, base))
511
527
  const started = now()
512
- const hard = strict && !strict.readOnly
528
+ const hard = strict && !strict.readOnly && expect !== "red"
513
529
  const plan = hard ? readProgress(check.root, sessionId).plan : undefined
514
530
  const early = hard ? await strictBefore(cwd, plan, work, run, strict.defensive) : undefined
515
531
  const result = early ?? (await run(check.command))
@@ -517,13 +533,33 @@ export async function verifyStep({ cwd, sessionId, step, run, now = () => new Da
517
533
  const passes = (r) => r.exitCode === 0 && !r.timedOut
518
534
  let status = passes(result) ? "pass" : "fail"
519
535
  let touched = work && status === "pass" ? checkFiles(work.changed) : []
536
+ // Harness 2.0 W5, a spec-test step (ORCHESTRA §7): its tests can't pass before the code exists, so it passes
537
+ // only red for the right reason: the check fails now, passes with the new check files moved aside (the
538
+ // strict loop's red-phase proof), and the failure isn't a syntax error
539
+ let red
540
+ if (expect === "red") {
541
+ const tests = work ? checkFiles(work.changed) : []
542
+ const failing = classify(result)
543
+ if (passes(result)) red = refusal("not red", check.command, "The check passes with the new tests, so they test nothing the code lacks yet. Write tests for what the next steps add, named after their criteria (AC-1, AC-2, …), so they fail now.")
544
+ else if (failing.kind === "syntax") red = refusal("syntax", check.command, failing.excerpt)
545
+ else if (!tests.length) red = refusal("not red", check.command, "This step changed no test file. A spec step writes the tests, and only the tests.")
546
+ else {
547
+ const without = await onOriginals(cwd, tests, () => run(check.command), base)
548
+ if (without?.aborted) throw new VerifyError("The check was stopped.")
549
+ if (!without) red = refusal("not red", check.command, "Kriya can't set the new tests aside here (no git repository with a commit), so it can't prove they are what fails.")
550
+ else if (!passes(without)) red = refusal("red for another reason", check.command, `The check fails even without the new tests, so their failure proves nothing. Fix that first:\n${classify(without).excerpt}`)
551
+ else red = { ...result, exitCode: 0, red: true }
552
+ }
553
+ if (red.own) [status, touched] = ["fail", []]
554
+ else [status, touched] = ["pass", []]
555
+ }
520
556
  // v2 and strict: a pass that changed tests or the check's files must hold on the originals too
521
- let checked = result
557
+ let checked = red ?? result
522
558
  let weakened
523
559
  if (((v2 && !v2.readOnly) || hard) && touched.length) {
524
560
  // The work's own files are saved first, so a crash mid-swap loses nothing (kriya undo); no save, no swap
525
561
  const kept = await checkpoint(cwd, sessionId, "before the check on the committed tests").catch(() => undefined)
526
- const originals = kept && (await onOriginals(cwd, touched, () => run(check.command)))
562
+ const originals = kept && (await onOriginals(cwd, touched, () => run(check.command), base))
527
563
  if (originals?.aborted) throw new VerifyError("The check was stopped.")
528
564
  if (originals && !passes(originals)) [status, checked, weakened, touched] = ["fail", originals, touched, []]
529
565
  }
@@ -533,9 +569,15 @@ export async function verifyStep({ cwd, sessionId, step, run, now = () => new Da
533
569
  const late = await strictAfter(cwd, sessionId, plan, work, check, run, strict.defensive, !open.length)
534
570
  if (late) [status, checked, touched] = ["fail", late, []]
535
571
  }
572
+ // Harness 2.0 gates (--gates): after a pass, the step's gates; the first failure fails the run
573
+ let gated
574
+ if (gates && status === "pass") {
575
+ gated = await gates({ root: check.root, changed: work?.changed ?? [], output: checked.output ?? "", rerun: () => run(check.command), command: (c) => run(c), label, recorded: readProgress(check.root, sessionId).contracts ?? {} })
576
+ if (gated.failure) [status, checked, touched] = ["fail", refusal(gated.failure.kind, `gate ${gated.failure.id}`, gated.failure.excerpt), []]
577
+ }
536
578
  // A refusal's words are its whole output; a rung's error is cut like any other
537
579
  const classified = () => (checked.own ? { kind: checked.kind, excerpt: checked.output } : weakened ? { kind: "tests changed", excerpt: classify(checked).excerpt } : { ...classify(checked), ...(checked.kind && { kind: checked.kind }) })
538
- const failure = (v2 || guard) && status === "fail" ? classified() : undefined
580
+ const failure = (v2 || guard || gated?.failure || red?.own) && status === "fail" ? classified() : undefined
539
581
  const sig = guard && failure ? createHash("sha256").update(signature(check.command, failure)).digest("hex").slice(0, 16) : undefined
540
582
  const progress = recordRun(check.root, sessionId, {
541
583
  at: started.toISOString(),
@@ -551,7 +593,11 @@ export async function verifyStep({ cwd, sessionId, step, run, now = () => new Da
551
593
  ...(weakened && { weakened }),
552
594
  ...(sig && { sig, excerpt: failure.excerpt.slice(0, KEPT_OUTPUT) }),
553
595
  ...(checked.level && { level: checked.level }),
596
+ ...(checked.red && { red: true }),
597
+ ...(gated && { gates: gated.results.map(({ id, status: s, reason, note }) => ({ id, status: s, ...(reason && { reason }), ...(note && { note: String(note).slice(0, 600) }) })) }),
554
598
  })
599
+ // The owning role's contracts, hashed once its step passes (the contract bus's ledger)
600
+ if (gated && status === "pass" && Object.keys(gated.contracts).length) writeProgress(check.root, sessionId, { ...progress, contracts: { ...(progress.contracts ?? {}), ...gated.contracts } })
555
601
  const proposed = (v2 || strict) && failure && noteFailure(check.root, check.command, failure, now)
556
602
  const after = verdict(progress)
557
603
  const mine = after.steps.find((s) => s.step === label)
@@ -570,6 +616,7 @@ export async function verifyStep({ cwd, sessionId, step, run, now = () => new Da
570
616
  ...(weakened && { weakened }),
571
617
  ...(proposed && { proposed: proposed.text }),
572
618
  ...(sig && { signature: sig }),
619
+ ...(gated && { gates: gated.results }),
573
620
  }
574
621
  }
575
622
 
Binary file
Binary file