@kriya-ai/harness 0.0.0-stage → 0.2.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.
- package/README.md +379 -2
- package/SAFETY.md +162 -0
- package/THIRD_PARTY_NOTICES.md +7911 -0
- package/bin/kriya.js +577 -0
- package/bundle/cordis.patch.yml +397 -0
- package/contract/SOURCE.md +15 -0
- package/contract/contract.json +1355 -0
- package/package.json +57 -4
- package/plugins/anchor/index.js +56 -0
- package/plugins/anchor/package.json +13 -0
- package/plugins/approvals/index.js +183 -0
- package/plugins/approvals/package.json +13 -0
- package/plugins/brand/DESIGN.md +112 -0
- package/plugins/brand/client.js +826 -0
- package/plugins/brand/index.js +15 -0
- package/plugins/brand/package.json +25 -0
- package/plugins/brand/src/client.js +823 -0
- package/plugins/browser/index.js +218 -0
- package/plugins/browser/package.json +13 -0
- package/plugins/budget/index.js +108 -0
- package/plugins/budget/package.json +13 -0
- package/plugins/changes/client.js +245 -0
- package/plugins/changes/index.js +75 -0
- package/plugins/changes/package.json +22 -0
- package/plugins/edit/client.js +113 -0
- package/plugins/edit/index.js +58 -0
- package/plugins/edit/package.json +23 -0
- package/plugins/fs-freshness/index.js +28 -0
- package/plugins/fs-freshness/package.json +13 -0
- package/plugins/graph/client.js +178 -0
- package/plugins/graph/index.js +4 -0
- package/plugins/graph/package.json +22 -0
- package/plugins/kriya-handoff/index.js +194 -0
- package/plugins/kriya-handoff/package.json +13 -0
- package/plugins/kriya-tools/index.js +189 -0
- package/plugins/kriya-tools/package.json +13 -0
- package/plugins/loop/index.js +743 -0
- package/plugins/loop/package.json +13 -0
- package/plugins/mirror/index.js +235 -0
- package/plugins/mirror/package.json +13 -0
- package/plugins/overview/client.js +276 -0
- package/plugins/overview/index.js +95 -0
- package/plugins/overview/package.json +22 -0
- package/plugins/preview/client.js +337 -0
- package/plugins/preview/index.js +4 -0
- package/plugins/preview/package.json +22 -0
- package/plugins/progress/client.js +290 -0
- package/plugins/progress/index.js +100 -0
- package/plugins/progress/package.json +22 -0
- package/plugins/projects/client.js +249 -0
- package/plugins/projects/index.js +30 -0
- package/plugins/projects/package.json +24 -0
- package/plugins/rea/index.js +256 -0
- package/plugins/rea/package.json +10 -0
- package/plugins/rea/skill/LICENSE +21 -0
- package/plugins/rea/skill/SKILL.md +360 -0
- package/plugins/rea/skill/references/android-applications.md +36 -0
- package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
- package/plugins/rea/skill/references/evidence-workflows.md +71 -0
- package/plugins/rea/skill/references/javascript-applications.md +218 -0
- package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
- package/plugins/rea/skill/references/runtime-observation.md +78 -0
- package/plugins/remote/index.js +297 -0
- package/plugins/remote/package.json +10 -0
- package/plugins/router/index.js +84 -0
- package/plugins/router/package.json +13 -0
- package/plugins/sessions/client.js +68 -0
- package/plugins/sessions/index.js +79 -0
- package/plugins/sessions/package.json +20 -0
- package/plugins/skills/client.js +504 -0
- package/plugins/skills/index.js +166 -0
- package/plugins/skills/package.json +23 -0
- package/src/api.js +97 -0
- package/src/browser.js +286 -0
- package/src/changes.js +191 -0
- package/src/checkpoints.js +313 -0
- package/src/daemon.js +503 -0
- package/src/doctor.js +137 -0
- package/src/edit/core/anchors.js +102 -0
- package/src/edit/core/audio.js +158 -0
- package/src/edit/core/faces.js +99 -0
- package/src/edit/core/ffmpeg.js +258 -0
- package/src/edit/core/handoff.js +220 -0
- package/src/edit/core/history.js +90 -0
- package/src/edit/core/layout.js +92 -0
- package/src/edit/core/mix.js +115 -0
- package/src/edit/core/ops.js +602 -0
- package/src/edit/core/plan.js +266 -0
- package/src/edit/core/project.d.ts +134 -0
- package/src/edit/core/project.js +307 -0
- package/src/edit/core/reframe.js +125 -0
- package/src/edit/core/solver.js +416 -0
- package/src/edit/core/time.js +110 -0
- package/src/edit/core/tonemap.js +57 -0
- package/src/edit/director/ask.js +120 -0
- package/src/edit/director/gateway.js +16 -0
- package/src/edit/director/revise.js +186 -0
- package/src/edit/engine/capabilities.js +33 -0
- package/src/edit/engine/captions.js +154 -0
- package/src/edit/engine/color.js +269 -0
- package/src/edit/engine/confine.js +67 -0
- package/src/edit/engine/dna.js +148 -0
- package/src/edit/engine/index.js +473 -0
- package/src/edit/engine/loudness.js +43 -0
- package/src/edit/engine/media.js +57 -0
- package/src/edit/engine/motion.js +281 -0
- package/src/edit/engine/packs.js +87 -0
- package/src/edit/engine/probe.js +101 -0
- package/src/edit/engine/receipt.js +123 -0
- package/src/edit/engine/tool.js +101 -0
- package/src/edit/gates/copy.js +113 -0
- package/src/edit/gates/index.js +430 -0
- package/src/edit/gates/picture.js +130 -0
- package/src/edit/gates/sound.js +58 -0
- package/src/edit/gates/speech.js +127 -0
- package/src/edit/gates/text.js +196 -0
- package/src/edit/gates/text.swift +22 -0
- package/src/edit/graph/index.js +139 -0
- package/src/edit/graph/journal.js +69 -0
- package/src/edit/graph/scheduler.js +79 -0
- package/src/edit/host/client.js +58 -0
- package/src/edit/host/deliver.js +119 -0
- package/src/edit/host/jobs.js +84 -0
- package/src/edit/host/main.js +135 -0
- package/src/edit/host/paths.js +11 -0
- package/src/edit/host/projects.js +415 -0
- package/src/edit/host/server.js +391 -0
- package/src/edit/host/taste.js +135 -0
- package/src/edit/host/tavi.js +417 -0
- package/src/edit/host/watch.js +141 -0
- package/src/edit/index/db.js +109 -0
- package/src/edit/index/index.js +236 -0
- package/src/edit/index/layers/faces.js +78 -0
- package/src/edit/index/layers/faces.swift +18 -0
- package/src/edit/index/layers/meta.js +35 -0
- package/src/edit/index/layers/music.js +146 -0
- package/src/edit/index/layers/quality.js +120 -0
- package/src/edit/index/layers/retakes.js +132 -0
- package/src/edit/index/layers/screen.js +99 -0
- package/src/edit/index/layers/shots.js +29 -0
- package/src/edit/index/layers/sound.js +42 -0
- package/src/edit/index/layers/words.js +64 -0
- package/src/edit/index/story.js +248 -0
- package/src/edit/index/views.js +71 -0
- package/src/edit/loop/governor.js +112 -0
- package/src/edit/loop/loop.js +69 -0
- package/src/edit/loop/make.js +115 -0
- package/src/edit/loop/repair.js +97 -0
- package/src/edit/loop/replay.js +32 -0
- package/src/edit/recipes/multicam.js +461 -0
- package/src/edit/recipes/reel.js +202 -0
- package/src/edit/recipes/short-from-long.js +237 -0
- package/src/edit/recipes/tutorial.js +137 -0
- package/src/edit/recipes/youtube.js +155 -0
- package/src/edit/runtime/cli.js +126 -0
- package/src/edit/runtime/doctor.js +122 -0
- package/src/edit/runtime/fetch.js +15 -0
- package/src/edit/runtime/licences.js +88 -0
- package/src/edit/runtime/manifest.js +73 -0
- package/src/edit/runtime/setup.js +252 -0
- package/src/failure.js +69 -0
- package/src/gateway-proxy.js +213 -0
- package/src/intent.js +130 -0
- package/src/launch.js +315 -0
- package/src/live.js +81 -0
- package/src/local-skills.js +284 -0
- package/src/login.js +82 -0
- package/src/loop.js +428 -0
- package/src/modes.js +128 -0
- package/src/overview.js +71 -0
- package/src/paths.js +30 -0
- package/src/profiles.js +92 -0
- package/src/projects.js +104 -0
- package/src/recon.js +244 -0
- package/src/rules.js +139 -0
- package/src/runner.bundle.js +21172 -0
- package/src/sentinel.js +248 -0
- package/src/skill-switches.js +130 -0
- package/src/store.js +58 -0
- package/src/strict.js +124 -0
- package/src/verify.js +659 -0
- package/src/world.js +268 -0
- package/studio/dist/index.html +14 -0
- package/studio/dist/studio.css +163 -0
- package/studio/dist/studio.js +1 -0
package/src/verify.js
ADDED
|
@@ -0,0 +1,659 @@
|
|
|
1
|
+
import { execFile } from "node:child_process"
|
|
2
|
+
import { createHash } from "node:crypto"
|
|
3
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, readdirSync } from "node:fs"
|
|
4
|
+
import { dirname, join } from "node:path"
|
|
5
|
+
|
|
6
|
+
import { checkpoint } from "./checkpoints.js"
|
|
7
|
+
import { classify, signature } from "./failure.js"
|
|
8
|
+
import { kriyaHome } from "./paths.js"
|
|
9
|
+
import { noteFailure } from "./rules.js"
|
|
10
|
+
import { affectedTests, blastRadius, importGraph } from "./recon.js"
|
|
11
|
+
import { hasBoundaryTest, newSurface, reviewDiff, sentinel } from "./sentinel.js"
|
|
12
|
+
import { projectRoot } from "./skill-switches.js"
|
|
13
|
+
import { isSource, ladder, silencers, weakenedTest } from "./strict.js"
|
|
14
|
+
|
|
15
|
+
// The Kriya loop's verify step (H14a, docs/kriya-harness/KRIYA_LOOP.md in
|
|
16
|
+
// the Kriya repository). "Passed" comes only from the exit code of the
|
|
17
|
+
// project's own check, run by the harness, never from what the model says.
|
|
18
|
+
//
|
|
19
|
+
// - discoverChecks: commands the project already defines (package.json
|
|
20
|
+
// scripts, Makefile targets, cargo, go, pytest…). Only suggestions.
|
|
21
|
+
// - The confirmed check: the one command the person chose for a project
|
|
22
|
+
// (`kriya verify use`), kept in ~/.kriya/verify.json by project root. No
|
|
23
|
+
// tool can set it: the agent runs it, the person picks it.
|
|
24
|
+
// - Progress: every verify run per session and step, in
|
|
25
|
+
// ~/.kriya/progress/<project>/<session>.json and a readable .md beside
|
|
26
|
+
// it; never inside the project, so Read only stays read-only.
|
|
27
|
+
// - The verdict, computed from those runs: verified, failed, blocked at a
|
|
28
|
+
// step, or not checked.
|
|
29
|
+
|
|
30
|
+
export const MAX_ATTEMPTS = 4 // the first try and 3 fixes (KRIYA_LOOP.md §1, (5))
|
|
31
|
+
export const OUTPUT_LIMIT = 4000
|
|
32
|
+
// What a failed run keeps of its output (loop guard), so a resumed step's next builder still sees it
|
|
33
|
+
const KEPT_OUTPUT = 2500
|
|
34
|
+
const COMMAND_LIMIT = 500
|
|
35
|
+
|
|
36
|
+
export class VerifyError extends Error {}
|
|
37
|
+
|
|
38
|
+
/* ───────────────────────────── discovery ───────────────────────────── */
|
|
39
|
+
|
|
40
|
+
const read = (file) => {
|
|
41
|
+
try {
|
|
42
|
+
return readFileSync(file, "utf8")
|
|
43
|
+
} catch {
|
|
44
|
+
return undefined
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function packageManager(dir) {
|
|
49
|
+
if (existsSync(join(dir, "pnpm-lock.yaml"))) return "pnpm"
|
|
50
|
+
if (existsSync(join(dir, "yarn.lock"))) return "yarn"
|
|
51
|
+
if (existsSync(join(dir, "bun.lock")) || existsSync(join(dir, "bun.lockb"))) return "bun"
|
|
52
|
+
return "npm"
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const runScript = (pm, script) =>
|
|
56
|
+
pm === "npm" ? (script === "test" ? "npm test" : `npm run ${script}`) : pm === "yarn" ? `yarn ${script}` : `${pm} run ${script}`
|
|
57
|
+
|
|
58
|
+
// npm init's placeholder isn't a check
|
|
59
|
+
const PLACEHOLDER = /no test specified/
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The checks a project already defines, best first. Suggestions only: none
|
|
63
|
+
* runs until the person confirms it.
|
|
64
|
+
* @param {string} cwd
|
|
65
|
+
* @returns {Array<{ command: string, source: string }>}
|
|
66
|
+
*/
|
|
67
|
+
export function discoverChecks(cwd) {
|
|
68
|
+
const root = projectRoot(cwd)
|
|
69
|
+
const here = checksIn(root)
|
|
70
|
+
if (here.length) return here
|
|
71
|
+
// A workspace holding its projects in subfolders (e.g. benchmarks/<app>):
|
|
72
|
+
// each one's checks, run from the workspace with `cd <folder> && …`
|
|
73
|
+
const found = []
|
|
74
|
+
for (const rel of projectFolders(root)) for (const c of checksIn(join(root, rel))) found.push({ command: `cd ${rel} && ${c.command}`, source: `${rel}/${c.source}` })
|
|
75
|
+
return found
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Folders never searched for projects: dependencies, build output, caches, VCS
|
|
79
|
+
const SKIP_DIRS = new Set(["node_modules", "dist", "build", "out", "target", "coverage", "vendor", "venv", "__pycache__"])
|
|
80
|
+
const SAFE_REL = /^[A-Za-z0-9_][A-Za-z0-9_.-]*(\/[A-Za-z0-9_][A-Za-z0-9_.-]*)?$/
|
|
81
|
+
const PROJECT_FILES = ["package.json", "Makefile", "makefile", "Cargo.toml", "go.mod", "pyproject.toml", "pytest.ini", "deno.json", "deno.jsonc", "gradlew", "pom.xml"]
|
|
82
|
+
|
|
83
|
+
/** Subfolders (one or two levels down, at most 5) that hold a project, as safe relative paths */
|
|
84
|
+
export function projectFolders(root, limit = 5) {
|
|
85
|
+
const out = []
|
|
86
|
+
const list = (dir) => {
|
|
87
|
+
try {
|
|
88
|
+
return readdirSync(dir, { withFileTypes: true })
|
|
89
|
+
.filter((d) => d.isDirectory() && !d.name.startsWith(".") && !SKIP_DIRS.has(d.name))
|
|
90
|
+
.map((d) => d.name)
|
|
91
|
+
.sort()
|
|
92
|
+
} catch {
|
|
93
|
+
return []
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const isProject = (dir) => PROJECT_FILES.some((f) => existsSync(join(dir, f)))
|
|
97
|
+
for (const a of list(root)) {
|
|
98
|
+
if (out.length >= limit) break
|
|
99
|
+
if (isProject(join(root, a))) {
|
|
100
|
+
if (SAFE_REL.test(a)) out.push(a)
|
|
101
|
+
continue
|
|
102
|
+
}
|
|
103
|
+
for (const b of list(join(root, a))) {
|
|
104
|
+
if (out.length >= limit) break
|
|
105
|
+
const rel = `${a}/${b}`
|
|
106
|
+
if (SAFE_REL.test(rel) && isProject(join(root, rel))) out.push(rel)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return out
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The checks one folder's project defines, best first */
|
|
113
|
+
function checksIn(dir) {
|
|
114
|
+
const found = []
|
|
115
|
+
const add = (command, source) => {
|
|
116
|
+
if (!found.some((c) => c.command === command)) found.push({ command, source })
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const pkg = read(join(dir, "package.json"))
|
|
120
|
+
if (pkg) {
|
|
121
|
+
let scripts = {}
|
|
122
|
+
try {
|
|
123
|
+
scripts = JSON.parse(pkg).scripts ?? {}
|
|
124
|
+
} catch {
|
|
125
|
+
// Unreadable package.json: nothing to suggest from it
|
|
126
|
+
}
|
|
127
|
+
const pm = packageManager(dir)
|
|
128
|
+
for (const name of ["check", "test", "typecheck", "lint", "build"])
|
|
129
|
+
if (typeof scripts[name] === "string" && !PLACEHOLDER.test(scripts[name])) add(runScript(pm, name), `package.json script "${name}"`)
|
|
130
|
+
}
|
|
131
|
+
const makefile = read(join(dir, "Makefile")) ?? read(join(dir, "makefile"))
|
|
132
|
+
if (makefile) for (const target of ["check", "test"]) if (new RegExp(`^${target}\\s*:`, "m").test(makefile)) add(`make ${target}`, `Makefile target "${target}"`)
|
|
133
|
+
if (existsSync(join(dir, "Cargo.toml"))) add("cargo test", "Cargo.toml")
|
|
134
|
+
if (existsSync(join(dir, "go.mod"))) add("go test ./...", "go.mod")
|
|
135
|
+
const pyproject = read(join(dir, "pyproject.toml")) ?? ""
|
|
136
|
+
if (/pytest/.test(pyproject) || existsSync(join(dir, "pytest.ini")) || /pytest/.test(read(join(dir, "tox.ini")) ?? "") || /pytest/.test(read(join(dir, "setup.cfg")) ?? ""))
|
|
137
|
+
add("python -m pytest", "pytest configuration")
|
|
138
|
+
const deno = read(join(dir, "deno.json")) ?? read(join(dir, "deno.jsonc"))
|
|
139
|
+
if (deno && /"test"\s*:/.test(deno)) add("deno task test", "deno.json task \"test\"")
|
|
140
|
+
if (existsSync(join(dir, "gradlew"))) add("./gradlew test", "Gradle wrapper")
|
|
141
|
+
else if (existsSync(join(dir, "pom.xml"))) add("mvn -q test", "pom.xml")
|
|
142
|
+
return found
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/* ─────────────────────────── the confirmed check ──────────────────────── */
|
|
146
|
+
|
|
147
|
+
export const checksFile = () => join(kriyaHome(), "verify.json")
|
|
148
|
+
|
|
149
|
+
function readChecks() {
|
|
150
|
+
try {
|
|
151
|
+
const raw = JSON.parse(readFileSync(checksFile(), "utf8"))
|
|
152
|
+
return raw && typeof raw.projects === "object" ? raw.projects : {}
|
|
153
|
+
} catch {
|
|
154
|
+
return {}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function writeJson(file, value) {
|
|
159
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
160
|
+
const temp = `${file}.${process.pid}.tmp`
|
|
161
|
+
writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
|
|
162
|
+
renameSync(temp, file)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* The person's confirmed check for the project `cwd` is in, if any. A check
|
|
167
|
+
* in KRIYA_VERIFY_CHECK (set in the person's own shell, e.g. by a benchmark
|
|
168
|
+
* run; the model can't set the harness's environment) wins for this run.
|
|
169
|
+
*/
|
|
170
|
+
export function confirmedCheck(cwd) {
|
|
171
|
+
const root = projectRoot(cwd)
|
|
172
|
+
const fromEnv = (process.env.KRIYA_VERIFY_CHECK ?? "").trim()
|
|
173
|
+
if (fromEnv && fromEnv.length <= COMMAND_LIMIT && !/[\r\n]/.test(fromEnv)) return { root, command: fromEnv, source: "KRIYA_VERIFY_CHECK" }
|
|
174
|
+
const entry = readChecks()[root]
|
|
175
|
+
return entry && typeof entry.command === "string" ? { root, ...entry } : undefined
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* The person confirms the project's check: in the CLI, the Progress tab, or answering the harness's own question. No tool calls this.
|
|
180
|
+
* @param {string} cwd
|
|
181
|
+
* @param {string} command
|
|
182
|
+
*/
|
|
183
|
+
export function confirmCheck(cwd, command, now = () => new Date()) {
|
|
184
|
+
const text = typeof command === "string" ? command.trim() : ""
|
|
185
|
+
if (!text) throw new VerifyError("Which command? kriya verify use <number> or kriya verify use \"<command>\"")
|
|
186
|
+
if (text.length > COMMAND_LIMIT || /[\r\n]/.test(text)) throw new VerifyError(`A check is one line of at most ${COMMAND_LIMIT} characters.`)
|
|
187
|
+
const root = projectRoot(cwd)
|
|
188
|
+
const projects = readChecks()
|
|
189
|
+
projects[root] = { command: text, confirmedAt: now().toISOString() }
|
|
190
|
+
writeJson(checksFile(), { version: 1, projects })
|
|
191
|
+
return { root, command: text }
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** The person removes the project's check: its runs end "not checked" again. */
|
|
195
|
+
export function clearCheck(cwd) {
|
|
196
|
+
const root = projectRoot(cwd)
|
|
197
|
+
const projects = readChecks()
|
|
198
|
+
const had = root in projects
|
|
199
|
+
delete projects[root]
|
|
200
|
+
writeJson(checksFile(), { version: 1, projects })
|
|
201
|
+
return had
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/* ─────────────────────────── the work's state ─────────────────────────── */
|
|
205
|
+
|
|
206
|
+
// Harness upgrade U8: a pass belongs to the files it ran on. The working
|
|
207
|
+
// tree's fingerprint (HEAD, the changed and untracked paths, and their
|
|
208
|
+
// contents) is taken with read-only git commands (no objects written, no
|
|
209
|
+
// index refresh), so Read only stays read-only. Outside a repository there
|
|
210
|
+
// is none, and a pass stays a pass.
|
|
211
|
+
const git = (cwd, args, input, encoding = "utf8") =>
|
|
212
|
+
new Promise((done) => {
|
|
213
|
+
const child = execFile("git", args, { cwd, encoding, env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" }, maxBuffer: 64 * 1024 * 1024 }, (error, stdout) =>
|
|
214
|
+
done(error ? null : stdout)
|
|
215
|
+
)
|
|
216
|
+
if (input !== undefined) child.stdin.end(input)
|
|
217
|
+
})
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* @returns {Promise<{ fingerprint: string, changed: string[] } | undefined>}
|
|
221
|
+
* changed: paths that differ from HEAD (staged, unstaged, untracked)
|
|
222
|
+
*/
|
|
223
|
+
export async function workTree(cwd) {
|
|
224
|
+
const status = await git(cwd, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"])
|
|
225
|
+
if (status === null) return undefined
|
|
226
|
+
const head = ((await git(cwd, ["rev-parse", "--verify", "-q", "HEAD"])) ?? "no commit").trim()
|
|
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))
|
|
232
|
+
const present = changed.filter((rel) => existsSync(join(root, rel)))
|
|
233
|
+
const hashes = present.length ? await git(root, ["hash-object", "--stdin-paths"], present.join("\n") + "\n") : ""
|
|
234
|
+
const fingerprint = createHash("sha256").update(`${head}\0${status}\0${hashes ?? "unreadable"}`).digest("hex").slice(0, 16)
|
|
235
|
+
return { fingerprint, changed: changed.sort() }
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// Files that decide what "passing" means: tests and the checks' own config.
|
|
239
|
+
// A pass that changed one is still a pass, but the person is told which
|
|
240
|
+
const CHECK_FILE = [
|
|
241
|
+
/(^|\/)(tests?|__tests__|spec|specs)\//,
|
|
242
|
+
/\.(test|spec)\.[^/]+$/,
|
|
243
|
+
/(^|\/)test_[^/]+\.py$/,
|
|
244
|
+
/_test\.(go|py|rs)$/,
|
|
245
|
+
/(^|\/)(package\.json|Makefile|makefile|pytest\.ini|pyproject\.toml|setup\.cfg|tox\.ini|Cargo\.toml|go\.mod|deno\.jsonc?|conftest\.py)$/,
|
|
246
|
+
/(^|\/)(jest|vitest|playwright|karma|mocha)\.config\.[^/]+$/,
|
|
247
|
+
/(^|\/)\.mocharc[^/]*$/,
|
|
248
|
+
]
|
|
249
|
+
export const checkFiles = (paths) => paths.filter((p) => CHECK_FILE.some((re) => re.test(p)))
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Loop v2: runs `run` with the given test and check files as they are at
|
|
253
|
+
* HEAD (an added one is moved aside), then puts the work's own versions
|
|
254
|
+
* back. A pass that holds only with the changed tests is a weakened check.
|
|
255
|
+
* Reads git (`show`), never writes it: the person's index and refs stay.
|
|
256
|
+
* shortcut: the baseline is HEAD, so the person's own uncommitted test edits
|
|
257
|
+
* count too; commit them first (or use the v1 loop) until the baseline is the
|
|
258
|
+
* session's first checkpoint.
|
|
259
|
+
* @returns {Promise<undefined | Awaited<ReturnType<typeof run>>>} undefined outside a repository or before a first commit
|
|
260
|
+
*/
|
|
261
|
+
export async function onOriginals(cwd, paths, run) {
|
|
262
|
+
const root = (await git(cwd, ["rev-parse", "--show-toplevel"]))?.trim()
|
|
263
|
+
if (!root || (await git(root, ["rev-parse", "--verify", "-q", "HEAD"])) === null) return undefined
|
|
264
|
+
const saved = []
|
|
265
|
+
try {
|
|
266
|
+
for (const rel of paths) {
|
|
267
|
+
const file = join(root, rel)
|
|
268
|
+
const original = await git(root, ["show", `HEAD:${rel}`], undefined, "buffer")
|
|
269
|
+
const entry = { file, mine: existsSync(file) ? readFileSync(file) : null }
|
|
270
|
+
saved.push(entry)
|
|
271
|
+
if (original === null) rmSync(file, { force: true })
|
|
272
|
+
else {
|
|
273
|
+
// The first folder this had to make (a deleted test's), removed again after
|
|
274
|
+
entry.made = mkdirSync(dirname(file), { recursive: true })
|
|
275
|
+
writeFileSync(file, original)
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return await run()
|
|
279
|
+
} finally {
|
|
280
|
+
for (const { file, mine, made } of saved.toReversed()) {
|
|
281
|
+
if (mine === null) rmSync(made ?? file, { recursive: true, force: true })
|
|
282
|
+
else writeFileSync(file, mine)
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/* ───────────────────────────── the strict loop ─────────────────────── */
|
|
288
|
+
|
|
289
|
+
const gitRoot = async (cwd) => (await git(cwd, ["rev-parse", "--show-toplevel"]))?.trim()
|
|
290
|
+
const fileNow = (file) => (existsSync(file) ? readFileSync(file, "utf8") : null)
|
|
291
|
+
const refusal = (kind, command, output) => ({ exitCode: 1, timedOut: false, output, command, kind, own: true })
|
|
292
|
+
|
|
293
|
+
// `a/*` and `a/**` match below a folder; anything else is one path
|
|
294
|
+
const matches = (pattern, rel) => (/\*+$/.test(pattern) ? rel.startsWith(pattern.replace(/\*+$/, "")) : rel === pattern)
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* What fails a step before the person's check runs (strict loop): a broken
|
|
298
|
+
* invariant, a weakened test, a silenced compiler, then the ladder's fast
|
|
299
|
+
* rungs. Each can only fail: a pass still needs the confirmed check. Against
|
|
300
|
+
* HEAD, so outside a repository none of this applies.
|
|
301
|
+
* @returns {Promise<undefined | { exitCode: number | null, timedOut: boolean, output: string, command: string, kind?: string, level?: number }>}
|
|
302
|
+
*/
|
|
303
|
+
async function strictBefore(cwd, plan, work, run, defensive) {
|
|
304
|
+
const root = await gitRoot(cwd)
|
|
305
|
+
if (!root || !work?.changed.length) return undefined
|
|
306
|
+
const head = (rel) => git(root, ["show", `HEAD:${rel}`])
|
|
307
|
+
const hit = work.changed.find((rel) => plan?.invariants?.some((p) => matches(p, rel)))
|
|
308
|
+
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
|
+
const checks = new Set(checkFiles(work.changed))
|
|
310
|
+
for (const rel of checks) {
|
|
311
|
+
const before = await head(rel)
|
|
312
|
+
const why = before !== null && !/(package\.json|Makefile|makefile|\.toml|\.ini|\.cfg|go\.mod|deno\.jsonc?|\.config\.[^/]+|\.mocharc[^/]*)$/.test(rel) && weakenedTest(before, fileNow(join(root, rel)))
|
|
313
|
+
if (why) return refusal("tests changed", "the test files", `${rel} was weakened: ${why}. Put the test back and fix the code; adding tests is fine.`)
|
|
314
|
+
}
|
|
315
|
+
for (const rel of work.changed.filter((f) => isSource(f) && !checks.has(f))) {
|
|
316
|
+
const now = fileNow(join(root, rel))
|
|
317
|
+
const added = now === null ? [] : silencers(await head(rel), now)
|
|
318
|
+
if (added.length) return refusal("silenced", "the changed source", `${rel} adds ${added.join(" and ")} to get past a check. Fix the cause instead.`)
|
|
319
|
+
}
|
|
320
|
+
const tests = affectedTests(root, work.changed)
|
|
321
|
+
let neighbours = []
|
|
322
|
+
if (defensive) {
|
|
323
|
+
const graph = importGraph(root)
|
|
324
|
+
const diffs = await diffsOf(root, work.changed)
|
|
325
|
+
const found = sentinel(diffs, { tenancy: graph.files.some((rel) => /\bwithUser\(/.test(graph.text(rel))) })
|
|
326
|
+
if (found.length) return refusal("invariant violated", "the invariant sentinel", findings(found.map((f) => `${f.file}:${f.line} [${f.rule}] ${f.why}`)))
|
|
327
|
+
// The neighbours' suites too: the work isn't done if it passes here and breaks there
|
|
328
|
+
neighbours = blastRadius(graph, diffs).tests.filter((rel) => !tests.includes(rel))
|
|
329
|
+
}
|
|
330
|
+
for (const rung of ladder(root, work.changed, tests, neighbours)) {
|
|
331
|
+
const result = await run(rung.command)
|
|
332
|
+
if (result.aborted) throw new VerifyError("The check was stopped.")
|
|
333
|
+
if (result.exitCode === 0 && !result.timedOut) continue
|
|
334
|
+
// A type error in a file this work never touched is older than it
|
|
335
|
+
if (rung.names && !rung.names.some((rel) => result.output.includes(rel))) continue
|
|
336
|
+
return { ...result, command: rung.command, level: rung.level, ...(rung.kind && { kind: rung.kind }) }
|
|
337
|
+
}
|
|
338
|
+
return undefined
|
|
339
|
+
}
|
|
340
|
+
|
|
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)) })))
|
|
343
|
+
|
|
344
|
+
const findings = (lines) => `${lines.slice(0, 12).join("\n")}${lines.length > 12 ? `\n… ${lines.length - 12} more` : ""}`
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Before a plan can read verified (defensive): the whole diff against code it
|
|
348
|
+
* didn't touch, a bad-input test for anything new, and each pre-mortem claim
|
|
349
|
+
* backed by the test it named.
|
|
350
|
+
*/
|
|
351
|
+
async function defensiveAfter(cwd, plan, work) {
|
|
352
|
+
const root = await gitRoot(cwd)
|
|
353
|
+
if (!root || !work?.changed.length) return undefined
|
|
354
|
+
const diffs = await diffsOf(root, work.changed)
|
|
355
|
+
const hazards = reviewDiff(importGraph(root), diffs)
|
|
356
|
+
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
|
+
const surface = newSurface(diffs)
|
|
358
|
+
if (surface.length && !hasBoundaryTest(diffs)) return refusal("no negative test", "the diff review", `${surface[0]} adds something callers can reach, and no added test tries a bad input (invalid, empty, unauthorized, a boundary). Add one that shows it fails cleanly.`)
|
|
359
|
+
const open = plan?.premortem?.failures.find((f) => !existsSync(join(root, f.coveredBy)))
|
|
360
|
+
if (open) return refusal("premortem open", "the pre-mortem", `"${open.what}" was to be covered by ${open.coveredBy}, which doesn't exist. Write that test.`)
|
|
361
|
+
return undefined
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** What fails a passing step afterwards: the plan's acceptance commands, and a bug fix with no proof of the bug */
|
|
365
|
+
async function strictAfter(cwd, sessionId, plan, work, check, run, defensive, finishing) {
|
|
366
|
+
for (const command of plan?.acceptance ?? []) {
|
|
367
|
+
const result = await run(command)
|
|
368
|
+
if (result.aborted) throw new VerifyError("The check was stopped.")
|
|
369
|
+
if (result.exitCode !== 0 || result.timedOut) return { ...result, command, kind: "acceptance" }
|
|
370
|
+
}
|
|
371
|
+
if (defensive && finishing) {
|
|
372
|
+
const late = await defensiveAfter(cwd, plan, work)
|
|
373
|
+
if (late) return late
|
|
374
|
+
}
|
|
375
|
+
if (plan?.kind !== "surgical_bugfix") return undefined
|
|
376
|
+
const code = (work?.changed ?? []).filter((rel) => !checkFiles([rel]).length)
|
|
377
|
+
if (!code.length) return undefined
|
|
378
|
+
// The red phase, proved: on the code as it was, the check (with any new test) must fail
|
|
379
|
+
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)))
|
|
381
|
+
if (old?.aborted) throw new VerifyError("The check was stopped.")
|
|
382
|
+
if (old?.exitCode === 0 && !old.timedOut)
|
|
383
|
+
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.")
|
|
384
|
+
return undefined
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/* ───────────────────────────── progress ───────────────────────────── */
|
|
388
|
+
|
|
389
|
+
const projectKey = (root) => createHash("sha256").update(root).digest("hex").slice(0, 16)
|
|
390
|
+
const SESSION = /^[A-Za-z0-9_-]{1,128}$/
|
|
391
|
+
|
|
392
|
+
export function progressFiles(root, sessionId) {
|
|
393
|
+
if (!SESSION.test(sessionId)) throw new VerifyError("That session id can't name a progress file.")
|
|
394
|
+
const dir = join(kriyaHome(), "progress", projectKey(root))
|
|
395
|
+
return { json: join(dir, `${sessionId}.json`), md: join(dir, `${sessionId}.md`) }
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
export function readProgress(root, sessionId) {
|
|
399
|
+
try {
|
|
400
|
+
const value = JSON.parse(readFileSync(progressFiles(root, sessionId).json, "utf8"))
|
|
401
|
+
if (Array.isArray(value.runs)) return value
|
|
402
|
+
} catch {
|
|
403
|
+
// None yet
|
|
404
|
+
}
|
|
405
|
+
return { version: 1, root, sessionId, runs: [] }
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* The session's verdict, from its runs and plan. A step that failed its
|
|
410
|
+
* MAX_ATTEMPTS-th run, or that the loop guard stopped as stalled, is blocked;
|
|
411
|
+
* otherwise each step's last run decides. With a plan, "verified" needs every
|
|
412
|
+
* step of it passed: passes with steps still open are "partial", never verified.
|
|
413
|
+
* With `current` (the work's fingerprint now, U8): "verified" holds only for
|
|
414
|
+
* the files the last run saw; changed since, it's "not checked" and stale.
|
|
415
|
+
* `touched`: test or check files the last passing run's work had changed.
|
|
416
|
+
* @returns {{ status: "verified" | "partial" | "failed" | "blocked" | "not checked", stale?: true, touched?: string[], steps: Array<{ step: string, status: "pass" | "fail" | "blocked", attempts: number, failures: number }> }}
|
|
417
|
+
*/
|
|
418
|
+
export function verdict(progress, current) {
|
|
419
|
+
const steps = new Map()
|
|
420
|
+
for (const run of progress.runs) {
|
|
421
|
+
const prev = steps.get(run.step) ?? { step: run.step, attempts: 0, failures: 0, status: "fail" }
|
|
422
|
+
if (prev.status === "blocked") continue
|
|
423
|
+
const failures = run.status === "pass" ? prev.failures : prev.failures + 1
|
|
424
|
+
steps.set(run.step, {
|
|
425
|
+
step: run.step,
|
|
426
|
+
attempts: prev.attempts + 1,
|
|
427
|
+
failures,
|
|
428
|
+
status: run.status === "pass" ? "pass" : failures >= MAX_ATTEMPTS || run.stalled ? "blocked" : "fail",
|
|
429
|
+
})
|
|
430
|
+
}
|
|
431
|
+
const list = [...steps.values()]
|
|
432
|
+
const open = progress.plan?.steps.some((_, i) => steps.get(stepLabel(progress.plan, i + 1))?.status !== "pass")
|
|
433
|
+
const status = !list.length
|
|
434
|
+
? "not checked"
|
|
435
|
+
: list.some((s) => s.status === "blocked")
|
|
436
|
+
? "blocked"
|
|
437
|
+
: list.every((s) => s.status === "pass")
|
|
438
|
+
? open
|
|
439
|
+
? "partial"
|
|
440
|
+
: "verified"
|
|
441
|
+
: "failed"
|
|
442
|
+
const last = progress.runs.at(-1)
|
|
443
|
+
const touched = progress.runs.findLast((r) => r.status === "pass")?.touched
|
|
444
|
+
const extra = touched?.length ? { touched } : {}
|
|
445
|
+
if (status === "verified" && current && last?.tree && last.tree !== current) return { status: "not checked", stale: true, steps: list, ...extra }
|
|
446
|
+
return { status, steps: list, ...extra }
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function renderProgress(progress) {
|
|
450
|
+
const { status, steps, touched } = verdict(progress)
|
|
451
|
+
const lines = [`# Progress`, "", `Project: ${progress.root}`, `Session: ${progress.sessionId}`, `Verdict: ${status}`, ""]
|
|
452
|
+
if (touched) lines.push(`Changed test or check files: ${touched.join(", ")}`, "")
|
|
453
|
+
if (progress.plan) {
|
|
454
|
+
lines.push(`## Plan`, "", `Goal: ${progress.plan.goal}`, "")
|
|
455
|
+
progress.plan.steps.forEach((step, i) => lines.push(`${i + 1}. ${step.title}: done when ${step.doneWhen}`))
|
|
456
|
+
lines.push("")
|
|
457
|
+
}
|
|
458
|
+
for (const s of steps) lines.push(`- ${s.step}: ${s.status} (${s.attempts} run${s.attempts === 1 ? "" : "s"})`)
|
|
459
|
+
lines.push("", "## Runs", "")
|
|
460
|
+
for (const run of progress.runs)
|
|
461
|
+
lines.push(`- ${run.at} · ${run.step} · ${run.status} · exit ${run.exitCode ?? "none"}${run.timedOut ? " (timed out)" : ""} · ${run.durationMs} ms · \`${run.command}\``)
|
|
462
|
+
return `${lines.join("\n")}\n`
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** Saves a session's whole progress record (its plan, if any, and its runs) */
|
|
466
|
+
export function writeProgress(root, sessionId, progress) {
|
|
467
|
+
const files = progressFiles(root, sessionId)
|
|
468
|
+
writeJson(files.json, progress)
|
|
469
|
+
writeFileSync(files.md, renderProgress(progress), { mode: 0o600 })
|
|
470
|
+
return progress
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function recordRun(root, sessionId, run) {
|
|
474
|
+
const progress = readProgress(root, sessionId)
|
|
475
|
+
progress.runs.push(run)
|
|
476
|
+
return writeProgress(root, sessionId, progress)
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/* ───────────────────────────── the verify step ──────────────────────── */
|
|
480
|
+
|
|
481
|
+
/** The failing part of a long output: its end, where test runners report. */
|
|
482
|
+
export function trimOutput(text, limit = OUTPUT_LIMIT) {
|
|
483
|
+
if (text.length <= limit) return text
|
|
484
|
+
return `… (${text.length - limit} earlier characters left out)\n${text.slice(-limit)}`
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// A label is only a name for the runs: models write plan titles with commas and pluses,
|
|
488
|
+
// and refusing those spent a call on nothing, so it's cleaned instead
|
|
489
|
+
export const normalStep = (step) => (typeof step === "string" ? step : "").replace(/[^\p{L}\p{N} ._:/#()-]/gu, " ").replace(/\s+/g, " ").replace(/^[^\p{L}\p{N}]+/u, "").slice(0, 80).trim() || "all"
|
|
490
|
+
|
|
491
|
+
/** The step label kriya_verify records runs under: "<n> <title>", within its limits */
|
|
492
|
+
export const stepLabel = (plan, n) => normalStep(`${n} ${plan.steps[n - 1].title}`)
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Runs the project's confirmed check for one step and records it.
|
|
496
|
+
* @param {{ cwd: string, sessionId: string, step?: string, run: (command: string) => Promise<{ exitCode: number | null, timedOut: boolean, aborted?: boolean, output: string }>, now?: () => Date, tree?: (cwd: string) => Promise<{ fingerprint: string, changed: string[] } | undefined>, v2?: { readOnly?: boolean }, guard?: boolean }} input
|
|
497
|
+
* run executes the command under the session's own sandbox (the tool passes DSH's shell)
|
|
498
|
+
* v2 (loop v2, KRIYA_LOOP_V2=on): a failure's class and excerpt, a pass that changed tests re-run on the originals, repeated failures proposed as rules
|
|
499
|
+
* 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
|
+
* strict (KRIYA_STRICT_LOOP=on): the checks of strictBefore and strictAfter around the person's check; never in Read only
|
|
501
|
+
*/
|
|
502
|
+
export async function verifyStep({ cwd, sessionId, step, run, now = () => new Date(), tree = workTree, v2, guard, strict }) {
|
|
503
|
+
const label = normalStep(step)
|
|
504
|
+
const check = confirmedCheck(cwd)
|
|
505
|
+
if (!check) return { status: "not configured", step: label, suggestions: discoverChecks(cwd) }
|
|
506
|
+
const before = verdict(readProgress(check.root, sessionId)).steps.find((s) => s.step === label)
|
|
507
|
+
if (before?.status === "blocked") return { status: "blocked", step: label, attempts: before.attempts, command: check.command }
|
|
508
|
+
// The files this run checks, taken before the command (a check that writes
|
|
509
|
+
// files, e.g. a build, doesn't make its own pass stale)
|
|
510
|
+
const work = await tree(cwd)
|
|
511
|
+
const started = now()
|
|
512
|
+
const hard = strict && !strict.readOnly
|
|
513
|
+
const plan = hard ? readProgress(check.root, sessionId).plan : undefined
|
|
514
|
+
const early = hard ? await strictBefore(cwd, plan, work, run, strict.defensive) : undefined
|
|
515
|
+
const result = early ?? (await run(check.command))
|
|
516
|
+
if (result.aborted) throw new VerifyError("The check was stopped.")
|
|
517
|
+
const passes = (r) => r.exitCode === 0 && !r.timedOut
|
|
518
|
+
let status = passes(result) ? "pass" : "fail"
|
|
519
|
+
let touched = work && status === "pass" ? checkFiles(work.changed) : []
|
|
520
|
+
// v2 and strict: a pass that changed tests or the check's files must hold on the originals too
|
|
521
|
+
let checked = result
|
|
522
|
+
let weakened
|
|
523
|
+
if (((v2 && !v2.readOnly) || hard) && touched.length) {
|
|
524
|
+
// The work's own files are saved first, so a crash mid-swap loses nothing (kriya undo); no save, no swap
|
|
525
|
+
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)))
|
|
527
|
+
if (originals?.aborted) throw new VerifyError("The check was stopped.")
|
|
528
|
+
if (originals && !passes(originals)) [status, checked, weakened, touched] = ["fail", originals, touched, []]
|
|
529
|
+
}
|
|
530
|
+
if (hard && status === "pass") {
|
|
531
|
+
// The whole diff is reviewed when this pass could finish the work: a plan's last open step, or no plan
|
|
532
|
+
const open = plan ? plan.steps.filter((_, i) => verdict(readProgress(check.root, sessionId)).steps.find((s) => s.step === stepLabel(plan, i + 1))?.status !== "pass" && stepLabel(plan, i + 1) !== label) : []
|
|
533
|
+
const late = await strictAfter(cwd, sessionId, plan, work, check, run, strict.defensive, !open.length)
|
|
534
|
+
if (late) [status, checked, touched] = ["fail", late, []]
|
|
535
|
+
}
|
|
536
|
+
// A refusal's words are its whole output; a rung's error is cut like any other
|
|
537
|
+
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
|
|
539
|
+
const sig = guard && failure ? createHash("sha256").update(signature(check.command, failure)).digest("hex").slice(0, 16) : undefined
|
|
540
|
+
const progress = recordRun(check.root, sessionId, {
|
|
541
|
+
at: started.toISOString(),
|
|
542
|
+
step: label,
|
|
543
|
+
command: checked.command ?? check.command,
|
|
544
|
+
status,
|
|
545
|
+
exitCode: checked.exitCode,
|
|
546
|
+
timedOut: checked.timedOut,
|
|
547
|
+
durationMs: Math.max(0, now().getTime() - started.getTime()),
|
|
548
|
+
...(work && { tree: work.fingerprint }),
|
|
549
|
+
...(touched.length && { touched }),
|
|
550
|
+
...(failure && { kind: failure.kind }),
|
|
551
|
+
...(weakened && { weakened }),
|
|
552
|
+
...(sig && { sig, excerpt: failure.excerpt.slice(0, KEPT_OUTPUT) }),
|
|
553
|
+
...(checked.level && { level: checked.level }),
|
|
554
|
+
})
|
|
555
|
+
const proposed = (v2 || strict) && failure && noteFailure(check.root, check.command, failure, now)
|
|
556
|
+
const after = verdict(progress)
|
|
557
|
+
const mine = after.steps.find((s) => s.step === label)
|
|
558
|
+
return {
|
|
559
|
+
status: mine.status,
|
|
560
|
+
step: label,
|
|
561
|
+
attempts: mine.attempts,
|
|
562
|
+
attemptsLeft: mine.status === "fail" ? MAX_ATTEMPTS - mine.failures : 0,
|
|
563
|
+
command: checked.command ?? check.command,
|
|
564
|
+
exitCode: checked.exitCode,
|
|
565
|
+
timedOut: checked.timedOut,
|
|
566
|
+
output: status === "pass" ? "" : failure ? failure.excerpt : trimOutput(result.output),
|
|
567
|
+
verdict: after.status,
|
|
568
|
+
...(touched.length && { touched }),
|
|
569
|
+
...(failure && { failure: failure.kind }),
|
|
570
|
+
...(weakened && { weakened }),
|
|
571
|
+
...(proposed && { proposed: proposed.text }),
|
|
572
|
+
...(sig && { signature: sig }),
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* Loop guard: the last failed run stopped the step early, so the step is
|
|
578
|
+
* blocked though it has attempts left. Marked on the run, so the verdict and
|
|
579
|
+
* every later read agree; the reason says why more builders can't help.
|
|
580
|
+
*/
|
|
581
|
+
export function markStalled(root, sessionId, reason) {
|
|
582
|
+
const progress = readProgress(root, sessionId)
|
|
583
|
+
const run = progress.runs.at(-1)
|
|
584
|
+
if (run) run.stalled = reason
|
|
585
|
+
return verdict(writeProgress(root, sessionId, progress))
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** What a session's records say happened, in numbers: the bench's and KRHE's view of a run */
|
|
589
|
+
export function trajectory(progress) {
|
|
590
|
+
const { steps } = verdict(progress)
|
|
591
|
+
const failedRuns = progress.runs.filter((r) => r.status !== "pass")
|
|
592
|
+
const classes = {}
|
|
593
|
+
for (const run of failedRuns) if (run.kind) classes[run.kind] = (classes[run.kind] ?? 0) + 1
|
|
594
|
+
const planned = progress.plan?.steps.length ?? 0
|
|
595
|
+
const passed = steps.filter((s) => s.status === "pass").length
|
|
596
|
+
return {
|
|
597
|
+
plans: (progress.earlier?.length ?? 0) + (progress.plan ? 1 : 0),
|
|
598
|
+
planned,
|
|
599
|
+
// Plan steps with no pass and no block: work the session left undone
|
|
600
|
+
open: progress.plan ? progress.plan.steps.filter((_, i) => !["pass", "blocked"].includes(steps.find((s) => s.step === stepLabel(progress.plan, i + 1))?.status)).length : 0,
|
|
601
|
+
passed,
|
|
602
|
+
blocked: steps.filter((s) => s.status === "blocked").length,
|
|
603
|
+
// Steps that failed at least once and then passed
|
|
604
|
+
recovered: steps.filter((s) => s.status === "pass" && s.failures > 0).length,
|
|
605
|
+
checkRuns: progress.runs.length,
|
|
606
|
+
failedRuns: failedRuns.length,
|
|
607
|
+
stalled: failedRuns.filter((r) => r.stalled).length,
|
|
608
|
+
builders: progress.builders?.length ?? 0,
|
|
609
|
+
builderSteps: (progress.builders ?? []).reduce((n, b) => n + (b.steps ?? 0), 0),
|
|
610
|
+
interrupted: Object.values(progress.interrupted ?? {}).reduce((n, c) => n + c, 0),
|
|
611
|
+
rollbacks: progress.rollbacks ?? 0,
|
|
612
|
+
// Failures the fast rungs caught before the full check ran
|
|
613
|
+
earlyFailures: failedRuns.filter((r) => r.level).length,
|
|
614
|
+
peakTokens: Math.max(0, ...(progress.builders ?? []).map((b) => b.tokens ?? 0)),
|
|
615
|
+
classes,
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** This project's newest session with a record (the one `kriya verify status` reports), or `sessionId`'s */
|
|
620
|
+
export function latestSession(cwd, sessionId) {
|
|
621
|
+
if (sessionId) return sessionId
|
|
622
|
+
const root = confirmedCheck(cwd)?.root ?? projectRoot(cwd)
|
|
623
|
+
const dir = dirname(progressFiles(root, "x").json)
|
|
624
|
+
const names = existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith(".json")) : []
|
|
625
|
+
// The parent's record, not a builder's: a plan first, then the newest
|
|
626
|
+
const rows = names.map((f) => ({ id: f.slice(0, -5), at: statSync(join(dir, f)).mtimeMs, plan: Boolean(readProgress(root, f.slice(0, -5)).plan) }))
|
|
627
|
+
return rows.sort((a, b) => Number(b.plan) - Number(a.plan) || b.at - a.at)[0]?.id
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/** Where a session stands, with its evidence: the verdict on the files as they are now, each step, each run */
|
|
631
|
+
export async function sessionReport(cwd, sessionId) {
|
|
632
|
+
const id = latestSession(cwd, sessionId)
|
|
633
|
+
if (!id) return { status: "not checked", steps: [], runs: [], trajectory: null }
|
|
634
|
+
const root = confirmedCheck(cwd)?.root ?? projectRoot(cwd)
|
|
635
|
+
const progress = readProgress(root, id)
|
|
636
|
+
const now = await currentVerdict(cwd, id)
|
|
637
|
+
return {
|
|
638
|
+
session: id,
|
|
639
|
+
status: now.status,
|
|
640
|
+
...(now.stale && { stale: true }),
|
|
641
|
+
...(now.touched && { touched: now.touched }),
|
|
642
|
+
goal: progress.plan?.goal ?? null,
|
|
643
|
+
steps: now.steps,
|
|
644
|
+
runs: progress.runs.map((r) => ({ at: r.at, step: r.step, status: r.status, exitCode: r.exitCode ?? null, command: r.command, ...(r.kind && { kind: r.kind }), ...(r.stalled && { stalled: r.stalled }) })),
|
|
645
|
+
trajectory: trajectory(progress),
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* The session's verdict against the files as they are now (U8): what the
|
|
651
|
+
* loop checks before a turn ends, and what `kriya verify` reports.
|
|
652
|
+
*/
|
|
653
|
+
export async function currentVerdict(cwd, sessionId, tree = workTree) {
|
|
654
|
+
const check = confirmedCheck(cwd)
|
|
655
|
+
const root = check?.root ?? projectRoot(cwd)
|
|
656
|
+
const progress = readProgress(root, sessionId)
|
|
657
|
+
if (!progress.runs.length) return { status: "not checked", steps: [] }
|
|
658
|
+
return verdict(progress, (await tree(cwd))?.fingerprint)
|
|
659
|
+
}
|