@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,111 @@
1
+ import { createHash } from "node:crypto"
2
+ import { existsSync, readFileSync } from "node:fs"
3
+ import { join } from "node:path"
4
+
5
+ import { CONTRACTS_DIR } from "../contracts.js"
6
+ import { kriyaHome } from "../paths.js"
7
+ import { readStack } from "../stack.js"
8
+ import { keepShot, SCHEMES, VIEWPORTS, withGateBrowser } from "./page.js"
9
+
10
+ // Harness 2.0 W4: G-UI and G-A11Y (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
11
+ // GATES.md §3). Both read the same rendered pages, so they share one visit per
12
+ // route × viewport × scheme, made once per verify. The app is the one the
13
+ // person confirmed with `kriya stack use --app`; routes are "/" plus the
14
+ // component previews named in .kriya/contracts/component_states.json.
15
+
16
+ export const MAX_ROUTES = 4
17
+ export const CLS_LIMIT = 0.1
18
+ export const TARGET_MIN = 24
19
+ export const TARGET_WARN = 44
20
+
21
+ /** The routes to render: "/" and each component preview (contract, hash-locked by its owner), at most MAX_ROUTES. */
22
+ export function uiRoutes(root) {
23
+ const routes = ["/"]
24
+ const file = join(root, CONTRACTS_DIR, "component_states.json")
25
+ if (existsSync(file)) {
26
+ try {
27
+ for (const c of Object.values(JSON.parse(readFileSync(file, "utf8")))) if (typeof c?.preview === "string" && /^\/\S*$/.test(c.preview) && !routes.includes(c.preview)) routes.push(c.preview)
28
+ } catch {
29
+ // G-CONTRACT reports a broken contract
30
+ }
31
+ }
32
+ return routes.slice(0, MAX_ROUTES)
33
+ }
34
+
35
+ const evidenceDir = (root, label) =>
36
+ join(kriyaHome(), "evidence", createHash("sha256").update(root).digest("hex").slice(0, 16), String(label).replace(/[^\w.-]+/g, "-").slice(0, 60), new Date().toISOString().replace(/[:.]/g, "-"))
37
+
38
+ /**
39
+ * Every page report for this verify, or { skip: reason }. Made once and shared by G-UI and G-A11Y.
40
+ * @param {{ root: string, label: string, launch?: () => Promise<any> }} input
41
+ */
42
+ export async function uiReports({ root, label, launch, app: given }) {
43
+ // Harness 2.0 W17: G-RELEASE points the same visits at the production server it was given
44
+ const app = given ?? readStack(root).app
45
+ if (!app) return { skip: "no app is confirmed for this project (kriya stack use --app http://localhost:<port>)", optional: true }
46
+ const routes = uiRoutes(root)
47
+ const dir = evidenceDir(root, label)
48
+ const visited = await withGateBrowser(
49
+ async (open) => {
50
+ const reports = []
51
+ for (const route of routes)
52
+ for (const viewport of VIEWPORTS)
53
+ for (const scheme of SCHEMES) {
54
+ const report = await open(new URL(route, app).href, { viewport, scheme })
55
+ if (report.unreachable) return { unreachable: `${app} doesn't answer (${report.unreachable}); start the app, or confirm another with kriya stack use --app` }
56
+ const sha = keepShot(dir, `${route.replace(/\W+/g, "_") || "root"}-${viewport.name}-${scheme}.png`, report.shot)
57
+ delete report.shot
58
+ reports.push({ route, ...report, ...(sha && { evidence: sha }) })
59
+ }
60
+ return { reports }
61
+ },
62
+ { launch }
63
+ )
64
+ if (visited.unavailable) return { skip: visited.unavailable }
65
+ if (visited.value.unreachable) return { skip: visited.value.unreachable }
66
+ return { reports: visited.value.reports, dir }
67
+ }
68
+
69
+ const at = (r) => `${r.route} at ${r.viewport}px ${r.scheme}`
70
+ const lines = (items, n = 12) => items.slice(0, n).map((x) => `- ${x}`).join("\n") + (items.length > n ? `\n- … and ${items.length - n} more` : "")
71
+
72
+ /** G-UI over the shared reports */
73
+ export function judgeUi(ui) {
74
+ if (ui.skip) return { id: "G-UI", status: "not_checked", reason: ui.skip, ...(ui.optional && { optional: true }) }
75
+ const problems = []
76
+ const warnings = []
77
+ for (const r of ui.reports) {
78
+ for (const e of r.consoleErrors) problems.push(`${at(r)}: console error: ${e}`)
79
+ for (const f of r.failed) problems.push(`${at(r)}: request ${f}`)
80
+ if (r.status !== null && r.status >= 400) problems.push(`${at(r)}: the page answered ${r.status}`)
81
+ if (r.overflow) problems.push(`${at(r)}: the page scrolls sideways (content wider than the screen)`)
82
+ if (r.cls > CLS_LIMIT) problems.push(`${at(r)}: layout shift ${r.cls} (over ${CLS_LIMIT})`)
83
+ if (Number(r.viewport) < 768) {
84
+ for (const s of r.small) {
85
+ if (Math.min(...s.size) < TARGET_MIN) problems.push(`${at(r)}: ${s.what} is ${s.size.join("×")} px, under the ${TARGET_MIN} px minimum to tap`)
86
+ else if (Math.min(...s.size) < TARGET_WARN) warnings.push(`${at(r)}: ${s.what} is ${s.size.join("×")} px; ${TARGET_WARN} px is easier to tap`)
87
+ }
88
+ }
89
+ }
90
+ const unique = [...new Set(problems)]
91
+ const evidence = ui.reports.map((r) => r.evidence).filter(Boolean)
92
+ if (unique.length) return { id: "G-UI", status: "fail", kind: "gate", excerpt: `G-UI (rendered at ${VIEWPORTS.map((v) => v.name).join(", ")} px, light and dark):\n${lines(unique)}`, evidence }
93
+ return { id: "G-UI", status: "pass", evidence, ...(warnings.length && { warnings: warnings.length, note: lines([...new Set(warnings)], 6) }) }
94
+ }
95
+
96
+ /** G-A11Y over the shared reports: names, language, contrast (plain and over glass), heading order as a warning */
97
+ export function judgeA11y(ui) {
98
+ if (ui.skip) return { id: "G-A11Y", status: "not_checked", reason: ui.skip, ...(ui.optional && { optional: true }) }
99
+ const problems = []
100
+ const warnings = []
101
+ for (const r of ui.reports) {
102
+ if (!r.lang) problems.push(`${at(r)}: <html> has no lang`)
103
+ for (const u of r.unnamed) problems.push(`${at(r)}: ${u} has no accessible name`)
104
+ for (const c of r.lowContrast) problems.push(`${at(r)}: "${c.text}" (${c.what}) has contrast ${c.ratio}:1, needs ${c.need}:1`)
105
+ for (const g of r.glass) if (g.worst < g.need) problems.push(`${at(r)}: text on a glass surface (${g.what}) reaches only ${Math.round(g.worst * 100) / 100}:1 over its backdrop, needs ${g.need}:1; make the surface more opaque or add a solid fallback`)
106
+ if (r.headingSkips) warnings.push(`${at(r)}: heading levels skip ${r.headingSkips} time(s)`)
107
+ }
108
+ const unique = [...new Set(problems)]
109
+ if (unique.length) return { id: "G-A11Y", status: "fail", kind: "gate", excerpt: `G-A11Y:\n${lines(unique)}` }
110
+ return { id: "G-A11Y", status: "pass", ...(warnings.length && { warnings: warnings.length, note: lines([...new Set(warnings)], 6) }) }
111
+ }
@@ -75,6 +75,24 @@ async function readAll(req) {
75
75
  return Buffer.concat(chunks)
76
76
  }
77
77
 
78
+ // Harness 2.0: the picker's local aliases (the "orchestra" choice), turned into the
79
+ // plan tier they stand for before a request leaves this computer, so Kriya only
80
+ // ever sees its own tier names (track H rule 4). Any other body passes untouched.
81
+ export const ORCHESTRA_ALIAS = "orchestra"
82
+ export function aliased(body, path, headers, aliases) {
83
+ if (!body || !Object.keys(aliases).length || !path.endsWith("/chat/completions") || !/^application\/json\b/i.test(headers["content-type"] ?? "")) return body
84
+ const text = body.toString("utf8")
85
+ if (!Object.keys(aliases).some((alias) => text.includes(`"${alias}"`))) return body
86
+ let value
87
+ try {
88
+ value = JSON.parse(text)
89
+ } catch {
90
+ return body
91
+ }
92
+ if (typeof value?.model !== "string" || !Object.hasOwn(aliases, value.model)) return body
93
+ return Buffer.from(JSON.stringify({ ...value, model: aliases[value.model] }))
94
+ }
95
+
78
96
  /**
79
97
  * Starts the relay in front of `target` (the signed-in Kriya's address).
80
98
  * `encode`: whether Kriya decodes encoded bodies, as known at launch.
@@ -87,7 +105,7 @@ async function readAll(req) {
87
105
  * @param {{ target: string, encode: boolean, checkSupport?: () => Promise<boolean>, fetchImpl?: typeof fetch, log?: (text: string) => void, now?: () => number, retryMs?: number }} options
88
106
  * @returns {Promise<{ url: string, close: () => Promise<void>, encoding: () => boolean }>} url stands in for device.url inside DSH
89
107
  */
90
- export async function startGatewayProxy({ target, encode, checkSupport, fetchImpl = fetch, log = () => {}, now = Date.now, retryMs = RETRY_MS, outageMs = OUTAGE_MS, outageWaitMs = OUTAGE_WAIT_MS }) {
108
+ export async function startGatewayProxy({ target, encode, checkSupport, aliases = {}, fetchImpl = fetch, log = () => {}, now = Date.now, retryMs = RETRY_MS, outageMs = OUTAGE_MS, outageWaitMs = OUTAGE_WAIT_MS }) {
91
109
  const origin = new URL(target).origin
92
110
  const support = { on: Boolean(encode), checked: now(), pending: null }
93
111
  // One question at a time; a failed question changes nothing
@@ -121,7 +139,7 @@ export async function startGatewayProxy({ target, encode, checkSupport, fetchImp
121
139
  if (body === null) return error(413, "This request is larger than Kriya Harness sends (64 MB).")
122
140
  const headers = {}
123
141
  for (const [name, value] of Object.entries(req.headers)) if (!DROP_REQUEST.has(name) && value !== undefined) headers[name] = Array.isArray(value) ? value.join(", ") : value
124
- const plain = body?.length ? body : undefined
142
+ const plain = aliased(body?.length ? body : undefined, path, headers, aliases)
125
143
  const encodable = Boolean(plain) && /^application\/json\b/i.test(headers["content-type"] ?? "")
126
144
  if (encodable && !support.on && now() - support.checked >= RECHECK_MS) await recheck()
127
145
  const once = (encoded) => {
package/src/launch.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { spawn, spawnSync } from "node:child_process"
2
2
 
3
3
  import { broadcastRun } from "./daemon.js"
4
- import { BODY_ENCODING, startGatewayProxy } from "./gateway-proxy.js"
4
+ import { BODY_ENCODING, ORCHESTRA_ALIAS, startGatewayProxy } from "./gateway-proxy.js"
5
5
  import { BASE_PATH, models } from "./api.js"
6
- import { DEFAULT_MODE, modeEnv } from "./modes.js"
6
+ import { applyWorkforce, DEFAULT_MODE, modeEnv } from "./modes.js"
7
7
  import { CLIENT_VERSION, DSH_BIN, kriyaHome } from "./paths.js"
8
8
  import { ensureProfile } from "./profiles.js"
9
9
 
@@ -37,7 +37,12 @@ export async function planTiers(device, list = models) {
37
37
  const encodings = Array.isArray(answer.bodyEncodings) ? answer.bodyEncodings.filter((e) => typeof e === "string") : []
38
38
  const offered = new Set(data.map((model) => model.id))
39
39
  const allowed = START_TIERS.filter((tier) => offered.has(tier))
40
- return allowed.length ? { start: allowed[0], allowed, names: modelNames(data, allowed), limits: modelLimits(data, allowed), images: allowed.filter((tier) => data.find((m) => m.id === tier)?.images === true), encodings } : { ...all, encodings }
40
+ // Harness 2.0 W2: the owner's head and worker levels, only if both are offered and differ
41
+ const o = answer.orchestra
42
+ const orchestra = o && allowed.includes(o.head) && allowed.includes(o.worker) && o.head !== o.worker ? { head: o.head, worker: o.worker } : undefined
43
+ // Harness 2.0: the owner turned the workforce on for this device (Kriya's harness.workforce)
44
+ const workforce = answer.workforce === 1
45
+ return allowed.length ? { start: allowed[0], allowed, names: modelNames(data, allowed), limits: modelLimits(data, allowed), images: allowed.filter((tier) => data.find((m) => m.id === tier)?.images === true), encodings, ...(orchestra && { orchestra }), ...(workforce && { workforce }) } : { ...all, encodings }
41
46
  } catch {
42
47
  // Kriya answers the first request with the reason if it's refused
43
48
  return all
@@ -96,7 +101,13 @@ export async function startTier(device, list = models) {
96
101
  }
97
102
 
98
103
  /** @param {{ url: string, token: string } | null} device */
99
- export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier = START_TIERS[0], allowed = START_TIERS, names = {}, limits = {}, images = []) {
104
+ /** The picker's name for the Orchestration choice: which model leads and which builds. */
105
+ export function orchestraName(orchestra, names = {}) {
106
+ const plain = (tier) => String(names[tier] ?? `Kriya ${tier}`).replace(/ · (budget|balanced|escalation)$/, "")
107
+ return `Orchestration · ${plain(orchestra.head)} leads, ${plain(orchestra.worker)} builds`.slice(0, 120)
108
+ }
109
+
110
+ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier = START_TIERS[0], allowed = START_TIERS, names = {}, limits = {}, images = [], orchestra, pick = false) {
100
111
  const env = {
101
112
  ...base,
102
113
  // The mode always comes from `--mode` (or the default), never the shell
@@ -115,6 +126,22 @@ export function launchEnv(device, base = process.env, mode = DEFAULT_MODE, tier
115
126
  // The tiers whose model takes images, as GET /models says. Never from the shell
116
127
  KRIYA_MODEL_IMAGES: images.filter((t) => START_TIERS.includes(t)).join(","),
117
128
  }
129
+ // Harness 2.0 W2: the head and worker levels come only from Kriya's GET /models, never the shell
130
+ delete env.KRIYA_ORCHESTRA_HEAD
131
+ delete env.KRIYA_ORCHESTRA_WORKER
132
+ delete env.KRIYA_ORCHESTRA_PICK
133
+ delete env.KRIYA_ORCHESTRA_NAME
134
+ if (orchestra && START_TIERS.includes(orchestra.head) && START_TIERS.includes(orchestra.worker)) {
135
+ env.KRIYA_ORCHESTRA_HEAD = orchestra.head
136
+ env.KRIYA_ORCHESTRA_WORKER = orchestra.worker
137
+ // The picker's own "Orchestration" choice (only through the local relay, which turns it into the head tier):
138
+ // sessions start on it, and picking a single model instead runs everything on that one model
139
+ if (pick) {
140
+ env.KRIYA_ORCHESTRA_PICK = ORCHESTRA_ALIAS
141
+ env.KRIYA_ORCHESTRA_NAME = orchestraName(orchestra, names)
142
+ env.KRIYA_START_TIER = ORCHESTRA_ALIAS
143
+ }
144
+ }
118
145
  // A token from the person's environment never stands in for the sign-in
119
146
  delete env[TOKEN_ENV]
120
147
  delete env.KRIYA_GATEWAY_URL
@@ -237,6 +264,11 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
237
264
  ensureProfile(profile)
238
265
  const headless = profile === "kriya-run"
239
266
  const tiers = await planTiers(device)
267
+ // Harness 2.0: the owner's switches, where the person set none of their own (src/modes.js applyWorkforce)
268
+ const turned = applyWorkforce(process.env, tiers.workforce)
269
+ if (turned.length) process.stderr.write(`kriya: Harness 2.0 is on from your Kriya owner settings: ${turned.join(", ")}. Turn one off with --no-<name>, e.g. --no-${turned[0]}.\n`)
270
+ // Harness 2.0 W2: with --orchestra and Kriya's offer, the session itself runs on the head level
271
+ const orchestra = process.env.KRIYA_ORCHESTRA === "on" && process.env.KRIYA_LOOP === "on" ? tiers.orchestra : undefined
240
272
  // DSH and the Kriya plugins reach Kriya through the local relay
241
273
  // (src/gateway-proxy.js): encoded bodies past the host's firewall, and a
242
274
  // block said as such. KRIYA_RELAY=off talks to Kriya directly, as before
@@ -245,6 +277,8 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
245
277
  ? await startGatewayProxy({
246
278
  target: device.url,
247
279
  encode: tiers.encodings.includes(BODY_ENCODING),
280
+ // Harness 2.0: the picker's Orchestration choice reaches Kriya as the head tier
281
+ ...(orchestra && { aliases: { [ORCHESTRA_ALIAS]: orchestra.head } }),
248
282
  // A Kriya deployed after launch is picked up without a restart
249
283
  checkSupport: async () => ((await models(device.url, device.token)).bodyEncodings ?? []).includes(BODY_ENCODING),
250
284
  log: (text) => process.stderr.write(`kriya: ${text}\n`),
@@ -262,7 +296,7 @@ export async function runDsh(profile, rest, device, mode = DEFAULT_MODE) {
262
296
  // stdout: the answer (kriya run) and ACP's protocol frames pass untouched;
263
297
  // the Web UI's stdout carries only log lines, rebranded like stderr
264
298
  stdio: ["inherit", profile === "kriya" ? "pipe" : "inherit", "pipe"],
265
- env: launchEnv(relay ? { ...device, url: relay.url } : device, process.env, mode, tiers.start, tiers.allowed, tiers.names, tiers.limits, tiers.images),
299
+ env: launchEnv(relay ? { ...device, url: relay.url } : device, process.env, mode, orchestra ? orchestra.head : tiers.start, tiers.allowed, tiers.names, tiers.limits, tiers.images, orchestra, Boolean(relay)),
266
300
  })
267
301
  let explained = null
268
302
  const filter = htmlFilter((text) => process.stderr.write(rebrand(text)))
package/src/loop.js CHANGED
@@ -5,6 +5,9 @@ import { checkPremortem } from "./sentinel.js"
5
5
  import { PLAN_LIMITS, taskKind, TASK_KINDS } from "./strict.js"
6
6
  import { confirmCheck, markStalled, MAX_ATTEMPTS, readProgress, stepLabel, trimOutput, verdict, VerifyError, writeProgress } from "./verify.js"
7
7
  import { projectRoot } from "./skill-switches.js"
8
+ import { cartridgeSection } from "./cartridges.js"
9
+ import { polishSection } from "./critic.js"
10
+ import { directionHints, EXPLORE_ROLES, MAX_TAKES, MIN_TAKES, takeSection } from "./explore.js"
8
11
 
9
12
  // The Kriya loop's plan and steps (H14c; KRIYA_LOOP.md in the Kriya
10
13
  // repository). The task is split into at most MAX_STEPS ordered steps
@@ -71,7 +74,7 @@ function dependencies(value, n) {
71
74
  * can only add to what must hold; it can't replace the person's check.
72
75
  * @returns {{ goal: string, steps: Array<{ title: string, doneWhen: string, files: string[], after?: number[] }>, kind?: string, invariants?: string[], acceptance?: string[] }}
73
76
  */
74
- export function validatePlan(input, { v2 = false, strict = false, defensive = false } = {}) {
77
+ export function validatePlan(input, { v2 = false, strict = false, defensive = false, roles, contracts: contractNames, specTests = false, explore = false } = {}) {
75
78
  const goal = clean(input?.goal, GOAL)
76
79
  if (!goal) throw new VerifyError("A plan needs a goal: one sentence on what the task is for.")
77
80
  const steps = Array.isArray(input?.steps) ? input.steps : []
@@ -83,8 +86,34 @@ export function validatePlan(input, { v2 = false, strict = false, defensive = fa
83
86
  if (!title) throw new VerifyError(`Step ${i + 1} needs a title.`)
84
87
  if (!doneWhen) throw new VerifyError(`Step ${i + 1} needs done_when: what is true when it's finished.`)
85
88
  const files = (Array.isArray(step?.files) ? step.files : []).map((f) => clean(f, 300)).filter(Boolean).slice(0, FILES)
86
- return { title, doneWhen, files, ...(v2 && { after: dependencies(step?.after, i + 1) }) }
89
+ // Harness 2.0 cartridges: an optional role from Kriya's list; without `roles`, never read
90
+ const role = roles && step?.role !== undefined && step?.role !== null && step?.role !== "" ? String(step.role) : undefined
91
+ if (role && !roles.includes(role)) throw new VerifyError(`Step ${i + 1}'s role is one of: ${roles.join(", ")}; or leave it out.`)
92
+ // Harness 2.0 gates: the contract slices this step builds to ("api#/paths/~1orders"); without the option, never read
93
+ let contracts
94
+ if (contractNames && Array.isArray(step?.contracts) && step.contracts.length) {
95
+ contracts = step.contracts.map((c) => String(c).trim()).filter(Boolean).slice(0, 8)
96
+ const bad = contracts.find((c) => !contractNames.includes(c.split("#")[0]) || (c.includes("#") && !/^[a-z_]+#\/\S*$/.test(c)))
97
+ if (bad) throw new VerifyError(`Step ${i + 1}'s contract "${bad}" isn't one of ${contractNames.join(", ")}, optionally with #/a/json/pointer.`)
98
+ }
99
+ // Harness 2.0 W5: a spec-test step (judged red, ORCHESTRA §7); without the option, never read
100
+ const spec = specTests && step?.spec_tests === true
101
+ // Harness 2.0 W14 (WD-18): 2 or 3 takes of a creative step; without the option, never read
102
+ let takes
103
+ if (explore && step?.explore !== undefined && step?.explore !== null && step?.explore !== 0) {
104
+ takes = Number(step.explore)
105
+ if (!Number.isInteger(takes) || takes < MIN_TAKES || takes > MAX_TAKES) throw new VerifyError(`Step ${i + 1}'s explore is ${MIN_TAKES} or ${MAX_TAKES} takes; or leave it out.`)
106
+ if (!EXPLORE_ROLES.includes(role)) throw new VerifyError(`Step ${i + 1} explores only with role ${EXPLORE_ROLES.join(", ")}: takes are for creative work.`)
107
+ }
108
+ return { title, doneWhen, files, ...(v2 && { after: dependencies(step?.after, i + 1) }), ...(role && { role }), ...(contracts?.length && { contracts }), ...(spec && { specTests: true }), ...(takes && { explore: takes }) }
87
109
  })
110
+ // A spec step writes tests from the contracts and criteria before the code exists: nothing that
111
+ // builds the code may come before it
112
+ const first = out.findIndex((s) => s.specTests)
113
+ if (first !== -1) {
114
+ const early = out.slice(0, first).find((s) => s.role && IMPLEMENTING.has(s.role))
115
+ if (early) throw new VerifyError(`Step ${first + 1} writes spec tests, so it comes before the code they test; "${early.title}" (${early.role}) builds code and is listed first. Put the spec step right after the contracts.`)
116
+ }
88
117
  const titles = new Set(out.map((s) => s.title.toLowerCase()))
89
118
  if (titles.size !== out.length) throw new VerifyError("Two steps have the same title; each step is one distinct piece of work.")
90
119
  const { premortem, problem } = defensive ? checkPremortem(input?.premortem, out.length) : {}
@@ -103,6 +132,9 @@ function contract(input, goal, steps) {
103
132
 
104
133
  export { stepLabel }
105
134
 
135
+ /** Roles whose steps build the code a spec step's tests are about (Harness 2.0) */
136
+ export const IMPLEMENTING = new Set(["frontend", "backend", "fullstack", "mobile", "game", "devops", "cloud", "systems", "data", "ml"])
137
+
106
138
  /**
107
139
  * Saves the session's plan beside its runs. A new plan starts its steps
108
140
  * over; the earlier plans and runs are kept, and at most MAX_PLANS are made.
@@ -207,9 +239,13 @@ export function loopStateText(cwd, sessionId) {
207
239
  }
208
240
 
209
241
  /** What a fresh builder is told: the goal, the plan, its one step and, on a retry, what failed; with v2, the person's confirmed rules */
210
- export function builderPrompt(plan, n, previous, rules = [], { limits = builderLimits(), checked = true, briefing = [] } = {}) {
242
+ export function builderPrompt(plan, n, previous, rules = [], { limits = builderLimits(), checked = true, briefing = [], cartridge, slices, polish } = {}) {
211
243
  const step = plan.steps[n - 1]
212
244
  const lines = [
245
+ // Harness 2.0: the role's cartridge first and byte-stable, so a cached prefix holds across builders
246
+ ...(cartridge ? cartridgeSection(cartridge.name, cartridge.body) : []),
247
+ // Harness 2.0 contract bus: this step's slices, stable for all its attempts
248
+ ...(slices ? ["Contracts for this step. Build to them as written; only the role that owns a contract changes it, and the harness fails a step that changes one it doesn't own.", "", slices, "", "---", ""] : []),
213
249
  `You are building one step of a larger task. Do only this step, then stop.`,
214
250
  "",
215
251
  `Goal of the task: ${plan.goal}`,
@@ -255,6 +291,8 @@ export function builderPrompt(plan, n, previous, rules = [], { limits = builderL
255
291
  if (previous?.kind === "tests changed")
256
292
  lines.push("The check passed only with changed tests or check files; on the originals it fails (above). Fix the code so the original tests pass; don't change existing tests.")
257
293
  if (previous?.note) lines.push(previous.note)
294
+ // Harness 2.0 W6: one polish attempt after a pass, with the critic's major defects
295
+ if (polish?.length) lines.push(...polishSection(polish))
258
296
  return lines.join("\n")
259
297
  }
260
298
 
@@ -309,7 +347,7 @@ const textOf = (blocks) =>
309
347
  * undo --list`. Nothing but Kriya's own restore touches the person's git.
310
348
  * @param {{ cwd: string, sessionId: string, n: number, spawn: (prompt: string, label: string, live: { n: number, attempt: number, startedAt: number, steps: number, last?: string, stopped?: string }) => Promise<{ output: any[], stopReason?: string }>, verify: (label: string) => Promise<any>, v2?: { snapshot?: (label: string) => Promise<string | undefined>, restore?: (tree: string, label: string) => Promise<unknown>, rules?: string[] }, guard?: { snapshot?: (label: string) => Promise<string | undefined>, restore?: (tree: string, label: string) => Promise<unknown>, briefing?: (step: any) => Promise<string[]> }, hasCheck?: boolean, limits?: { maxSteps: number, maxMinutes: number }, now?: () => number }} input
311
349
  */
312
- export async function runStep({ cwd, sessionId, n, spawn, verify, v2, guard, hasCheck = true, limits = builderLimits(), now = Date.now, pickCheck }) {
350
+ export async function runStep({ cwd, sessionId, n, spawn, verify, v2, guard, hasCheck = true, limits = builderLimits(), now = Date.now, pickCheck, cartridge: cartridgeFor, orchestra, slices: slicesFor, polish, explore }) {
313
351
  const plan = readPlan(cwd, sessionId)
314
352
  if (!plan) throw new VerifyError("There's no plan yet: call kriya_plan first.")
315
353
  if (!Number.isInteger(n) || n < 1 || n > plan.steps.length) throw new VerifyError(`The plan has steps 1 to ${plan.steps.length}.`)
@@ -337,7 +375,15 @@ export async function runStep({ cwd, sessionId, n, spawn, verify, v2, guard, has
337
375
  let start = guard ? await save?.(`before step ${n}`) : undefined
338
376
  const base = start
339
377
  const briefing = (await guard?.briefing?.(plan.steps[n - 1])) ?? []
378
+ // Harness 2.0: one cartridge for every attempt of this step (undefined: the prompt as before)
379
+ const cartridge = cartridgeFor ? await cartridgeFor(plan.steps[n - 1]).catch(() => undefined) : undefined
380
+ const slices = slicesFor && plan.steps[n - 1].contracts?.length ? slicesFor(plan.steps[n - 1]) : ""
340
381
  let broken = 0
382
+ // Harness 2.0 orchestra: the failure before `previous`, whether a head-level builder already
383
+ // ran on this step, and a one-time "use the head" instead of a stall (ARCHITECTURE §5)
384
+ let earlierRun
385
+ let headTried = false
386
+ let forceHead = false
341
387
  const rollBack = async (why) => {
342
388
  if (!guard?.restore || !base) return false
343
389
  await guard.restore(base, why)
@@ -345,19 +391,36 @@ export async function runStep({ cwd, sessionId, n, spawn, verify, v2, guard, has
345
391
  writeProgress(root, sessionId, { ...progress, rollbacks: (progress.rollbacks ?? 0) + 1 })
346
392
  return true
347
393
  }
394
+ // Harness 2.0 W14 (WD-18): a step marked explore builds its takes first (only with explore given)
395
+ const takes = explore && status[n - 1].status !== "pass" && status[n - 1].attempts === 0 ? plan.steps[n - 1].explore : undefined
396
+ if (takes) {
397
+ if (explore.readOnly) throw new VerifyError("Read only mode can't explore: each take changes files.")
398
+ const done = await exploreTakes({ plan, n, label, takes, root, cwd, sessionId, spawn, verify, explore, cartridge, slices, briefing, limits, hasCheck, v2, orchestra, builders, now })
399
+ if (done.result) return done.result
400
+ // No take passed: the normal retry rules go on from the best-ranked failure
401
+ previous = done.previous
402
+ start = done.tree
403
+ status[n - 1] = { ...status[n - 1], status: "fail", attempts: done.attempts }
404
+ }
348
405
  for (;;) {
349
406
  const before = status[n - 1]
350
407
  if (before.status === "pass") return { status: "pass", step: n, title: plan.steps[n - 1].title, attempts: before.attempts, builders, note: "This step already passed." }
351
408
  const live = { n, attempt: builders.length + 1, startedAt: now(), steps: 0 }
409
+ const tier = orchestra?.tier({ attempt: (before.attempts ?? 0) + 1, previous, earlier: earlierRun, force: forceHead, step: plan.steps[n - 1] })
410
+ if (tier) {
411
+ live.tier = tier
412
+ if (tier === orchestra.head) headTried = true
413
+ }
414
+ forceHead = false
352
415
  building.set(sessionId, live)
353
416
  let built
354
417
  try {
355
- built = await spawn(builderPrompt(plan, n, previous, v2?.rules, { limits, checked: hasCheck, briefing }), `Step ${n}: ${plan.steps[n - 1].title}`, live)
418
+ built = await spawn(builderPrompt(plan, n, previous, v2?.rules, { limits, checked: hasCheck, briefing, ...(cartridge && { cartridge }), ...(slices && { slices }) }), `Step ${n}: ${plan.steps[n - 1].title}`, live)
356
419
  } finally {
357
420
  if (building.get(sessionId) === live) building.delete(sessionId)
358
421
  }
359
422
  builders.push({ stopReason: built.stopReason ?? "completed", summary: textOf(built.output).slice(-600), steps: live.steps, ...(live.stopped && { limit: live.stopped }) })
360
- noteBuilder(root, sessionId, { step: label, stopReason: builders.at(-1).stopReason, steps: live.steps, ms: now() - live.startedAt, ...(live.tokens && { tokens: live.tokens }), ...(live.stopped && { limit: live.stopped }) })
423
+ noteBuilder(root, sessionId, { step: label, stopReason: builders.at(-1).stopReason, steps: live.steps, ms: now() - live.startedAt, ...(live.tokens && { tokens: live.tokens }), ...(live.stopped && { limit: live.stopped }), ...(cartridge && { cartridge: `${cartridge.id}@${cartridge.version}` }), ...(live.tier && { tier: live.tier }), ...(live.advice && { advice: live.advice }) })
361
424
  const tree = await save?.(`attempt ${builders.length} of step ${n}`)
362
425
  const untouched = tree !== undefined && tree === start
363
426
  if (guard && built.stopReason === "error" && untouched && noteInterruption(root, sessionId, label))
@@ -387,15 +450,45 @@ export async function runStep({ cwd, sessionId, n, spawn, verify, v2, guard, has
387
450
  const judged = verdict(readProgress(root, sessionId)).steps
388
451
  for (const b of built.filter((b) => !judged.some((s) => s.step === b.step))) checked.verdict = (await verify(b.step)).verdict
389
452
  }
453
+ // Harness 2.0 W6 (WD-13): after a pass, the critic may earn one polish attempt; kept only if
454
+ // every check and gate still passes, otherwise the passing files go back and are checked again
455
+ if (checked.status === "pass" && polish) {
456
+ const failures = verdict(readProgress(root, sessionId)).steps.find((s) => s.step === label)?.failures ?? 0
457
+ const defects = failures + 1 < MAX_ATTEMPTS ? ((await polish.critique(plan.steps[n - 1], n).catch(() => [])) ?? []).filter((d) => d.severity === "major") : []
458
+ const passing = defects.length ? await polish.snapshot(`step ${n} passed, before polish`).catch(() => undefined) : undefined
459
+ if (passing) {
460
+ const live = { n, attempt: builders.length + 1, startedAt: now(), steps: 0, polish: true }
461
+ const tier = orchestra?.tier({ attempt: MAX_ATTEMPTS, step: plan.steps[n - 1] })
462
+ if (tier) live.tier = tier
463
+ building.set(sessionId, live)
464
+ let built
465
+ try {
466
+ built = await spawn(builderPrompt(plan, n, undefined, v2?.rules, { limits, checked: hasCheck, briefing, ...(cartridge && { cartridge }), ...(slices && { slices }), polish: defects }), `Step ${n}: ${plan.steps[n - 1].title} (polish)`, live)
467
+ } finally {
468
+ if (building.get(sessionId) === live) building.delete(sessionId)
469
+ }
470
+ builders.push({ stopReason: built.stopReason ?? "completed", summary: textOf(built.output).slice(-600), steps: live.steps, polish: true })
471
+ noteBuilder(root, sessionId, { step: label, stopReason: builders.at(-1).stopReason, steps: live.steps, ms: now() - live.startedAt, polish: defects.length, ...(live.tier && { tier: live.tier }), ...(cartridge && { cartridge: `${cartridge.id}@${cartridge.version}` }) })
472
+ const after = await verify(label)
473
+ if (after.status === "pass") return { status: "pass", step: n, title: plan.steps[n - 1].title, attempts: after.attempts, builders, command: after.command, output: "", verdict: after.verdict, polished: defects.length }
474
+ await polish.restore(passing, `polish of step ${n} broke a check`)
475
+ const again = await verify(label)
476
+ return { status: again.status, step: n, title: plan.steps[n - 1].title, attempts: again.attempts, builders, command: again.command, output: again.output ?? "", verdict: again.verdict, polishReverted: true }
477
+ }
478
+ }
390
479
  if (checked.status === "pass" || checked.status === "blocked")
391
480
  return { status: checked.status, step: n, title: plan.steps[n - 1].title, attempts: checked.attempts, builders, command: checked.command, output: checked.output ?? "", verdict: checked.verdict, ...(undone && { rolledBack: true }) }
392
481
  const earlier = previous
482
+ earlierRun = earlier
393
483
  previous = { attempt: checked.attempts, command: checked.command, exitCode: checked.exitCode, timedOut: checked.timedOut, output: checked.output, ...(checked.failure && { kind: checked.failure }), ...(checked.signature && { sig: checked.signature }) }
394
484
  const repeated = guard && checked.signature && earlier?.sig === checked.signature
395
485
  // A builder that died on an error says nothing about the code; its attempts just run out
396
486
  // Only exit 126/127 proves the command can't run; ENOENT or a missing module can be the code's own bug
397
487
  const cantRun = checked.exitCode === 126 || checked.exitCode === 127
398
- if (repeated && built.stopReason !== "error" && (untouched || cantRun)) {
488
+ // Orchestra: a worker that repeats itself without changing a file gets one head-level attempt
489
+ // first; the head repeating itself, or a check that can't run, stalls exactly as before
490
+ if (repeated && built.stopReason !== "error" && untouched && !cantRun && orchestra && !headTried) forceHead = true
491
+ else if (repeated && built.stopReason !== "error" && (untouched || cantRun)) {
399
492
  const reason = untouched ? "the same failure again with no file changed" : "the check can't run on this machine"
400
493
  const after = markStalled(root, sessionId, reason)
401
494
  const undone = await rollBack(`step ${n} blocked`)
@@ -426,3 +519,102 @@ export async function runStep({ cwd, sessionId, n, spawn, verify, v2, guard, has
426
519
  status[n - 1] = { ...before, status: "fail", attempts: checked.attempts }
427
520
  }
428
521
  }
522
+
523
+ /**
524
+ * Harness 2.0 W14 (WD-18): Explore. `takes` (2–3) builders one after another
525
+ * in the same folder, each from the step's starting files with its own
526
+ * direction hint (src/explore.js), each snapshotted and checked (a failed take
527
+ * counts as an attempt). Passing takes are offered to the person (`pick`);
528
+ * with no answer, the critic's ranking (`rank`), else take order, decides. The
529
+ * kept take's files are restored and checked again, so the step's last run is
530
+ * the kept take's; every take stays in `kriya undo --list`. No polish here,
531
+ * so takes + one retry stays inside MAX_ATTEMPTS.
532
+ * @returns {Promise<{ result?: object, previous?: object, tree?: string, attempts?: number }>}
533
+ */
534
+ async function exploreTakes({ plan, n, label, takes, root, cwd, sessionId, spawn, verify, explore, cartridge, slices, briefing, limits, hasCheck, v2, orchestra, builders, now }) {
535
+ const step = plan.steps[n - 1]
536
+ const hints = directionHints(step.role, takes, root)
537
+ const base = await explore.snapshot(`before explore of step ${n}`)
538
+ const done = []
539
+ for (let v = 1; v <= takes; v++) {
540
+ if (v > 1) await explore.restore(base, `explore: back to the start of step ${n} for take ${v}`)
541
+ const hint = hints[v - 1]
542
+ const served = await explore.served?.()
543
+ const live = { n, attempt: builders.length + 1, startedAt: now(), steps: 0, take: v }
544
+ // Takes are built on the worker level (the first attempt's level)
545
+ const tier = orchestra?.tier({ attempt: 1, step })
546
+ if (tier) live.tier = tier
547
+ building.set(sessionId, live)
548
+ let built
549
+ try {
550
+ const prompt = `${builderPrompt(plan, n, undefined, v2?.rules, { limits, checked: hasCheck, briefing, ...(cartridge && { cartridge }), ...(slices && { slices }) })}\n\n${takeSection(v, takes, hint)}`
551
+ built = await spawn(prompt, `Step ${n}: ${step.title} (take ${v} of ${takes})`, live)
552
+ } finally {
553
+ if (building.get(sessionId) === live) building.delete(sessionId)
554
+ }
555
+ builders.push({ stopReason: built.stopReason ?? "completed", summary: textOf(built.output).slice(-600), steps: live.steps, take: v })
556
+ noteBuilder(root, sessionId, { step: label, stopReason: builders.at(-1).stopReason, steps: live.steps, ms: now() - live.startedAt, take: v, direction: hint.id, ...(live.tier && { tier: live.tier }), ...(cartridge && { cartridge: `${cartridge.id}@${cartridge.version}` }) })
557
+ const tree = await explore.snapshot(`explore take ${v} of step ${n}: ${hint.id}`)
558
+ // The dev server must serve this take before any gate looks at it
559
+ const reload = served !== undefined && explore.reloaded ? await explore.reloaded(served) : { ok: true }
560
+ if (!reload.ok) {
561
+ done.push({ v, hint, tree, status: "not checked", reason: reload.reason })
562
+ continue
563
+ }
564
+ const checked = await verify(label)
565
+ done.push({ v, hint, tree, status: checked.status, checked })
566
+ if (checked.status === "blocked") break
567
+ }
568
+ const survivors = done.filter((t) => t.status === "pass")
569
+ const record = (kept, by) => {
570
+ const progress = readProgress(root, sessionId)
571
+ writeProgress(root, sessionId, { ...progress, explore: [...(progress.explore ?? []), { step: label, takes: done.map((t) => ({ take: t.v, direction: t.hint.id, status: t.status, tree: t.tree, ...(t.reason && { reason: t.reason }) })), ...(kept && { kept, by }) }] })
572
+ }
573
+ if (!survivors.length) {
574
+ record(undefined)
575
+ // A take the dev server never served wasn't checked, so it isn't an attempt: stop rather than spend builders past the bound
576
+ const unserved = done.find((t) => t.status === "not checked")
577
+ if (unserved) return { result: { status: "not checked", step: n, title: step.title, builders, note: `Take ${unserved.v} wasn't checked: ${unserved.reason}. Make sure the dev server reloads on file changes, then run the step again.`, explore: { takes: done.map((t) => ({ take: t.v, direction: t.hint.id, status: t.status })) } } }
578
+ const failed = done.filter((t) => t.checked && t.status !== "pass")
579
+ const ranked = [...failed].sort((a, b) => (RANK[a.checked.failure] ?? RANK.unknown) - (RANK[b.checked.failure] ?? RANK.unknown) || b.v - a.v)
580
+ const best = ranked.at(-1)
581
+ const attempts = done.reduce((most, t) => Math.max(most, t.checked?.attempts ?? 0), 0)
582
+ if (!best) return { tree: base, attempts }
583
+ if (done.some((t) => t.status === "blocked")) return { result: { status: "blocked", step: n, title: step.title, attempts, builders, command: best.checked.command, output: best.checked.output ?? "", verdict: best.checked.verdict, explore: { takes: done.map((t) => ({ take: t.v, direction: t.hint.id, status: t.status })) } } }
584
+ await explore.restore(best.tree, `explore: no take of step ${n} passed; going on from take ${best.v}`)
585
+ const c = best.checked
586
+ return {
587
+ tree: best.tree,
588
+ attempts,
589
+ previous: { attempt: c.attempts, command: c.command, exitCode: c.exitCode, timedOut: c.timedOut, output: c.output, ...(c.failure && { kind: c.failure }), ...(c.signature && { sig: c.signature }), note: `None of the ${takes} takes passed. The files are as take ${best.v} (${best.hint.id}) left them, the closest to passing; fix that take.` },
590
+ }
591
+ }
592
+ let winner
593
+ let by = "only"
594
+ if (survivors.length > 1) {
595
+ const picked = await explore.pick?.(survivors, step, n)
596
+ winner = survivors.find((t) => t.v === picked)
597
+ by = "person"
598
+ if (!winner) {
599
+ const ranked = (await explore.rank?.(survivors, step, n).catch(() => undefined)) ?? []
600
+ winner = survivors.find((t) => t.v === ranked[0]) ?? survivors[0]
601
+ by = ranked.length ? "critic" : "order"
602
+ }
603
+ } else winner = survivors[0]
604
+ await explore.restore(winner.tree, `explore: keep take ${winner.v} of step ${n}`)
605
+ record(winner.v, by)
606
+ const final = await verify(label)
607
+ return {
608
+ result: {
609
+ status: final.status,
610
+ step: n,
611
+ title: step.title,
612
+ attempts: final.attempts,
613
+ builders,
614
+ command: final.command,
615
+ output: final.output ?? "",
616
+ verdict: final.verdict,
617
+ explore: { kept: winner.v, by, direction: winner.hint.id, takes: done.map((t) => ({ take: t.v, direction: t.hint.id, status: t.status })) },
618
+ },
619
+ }
620
+ }