@kriya-ai/harness 0.2.4 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/RELEASE_NOTES.md +121 -0
- package/SAFETY.md +181 -0
- package/THIRD_PARTY_NOTICES.md +113 -0
- package/bin/kriya.js +188 -2
- package/bundle/cordis.patch.yml +49 -0
- package/contract/SOURCE.md +3 -3
- package/contract/contract.json +504 -3
- package/contract/schemas/api.json +64 -0
- package/contract/schemas/auth_matrix.json +44 -0
- package/contract/schemas/component_states.json +33 -0
- package/contract/schemas/design_tokens.json +34 -0
- package/contract/schemas/scene_direction.json +82 -0
- package/contract/schemas/threat_model.json +44 -0
- package/package.json +2 -1
- package/plugins/changes/client.js +5 -3
- package/plugins/deploy/index.js +215 -0
- package/plugins/deploy/package.json +13 -0
- package/plugins/grounding/index.js +81 -0
- package/plugins/grounding/lookup.js +373 -0
- package/plugins/grounding/package.json +13 -0
- package/plugins/kriya-tools/index.js +2 -1
- package/plugins/loop/index.js +376 -10
- package/plugins/mcp/index.js +79 -0
- package/plugins/mcp/package.json +13 -0
- package/plugins/mirror/index.js +17 -0
- package/plugins/overview/client.js +5 -2
- package/plugins/preview/client.js +12 -6
- package/plugins/progress/client.js +7 -4
- package/plugins/repo/index.js +230 -0
- package/plugins/repo/package.json +13 -0
- package/plugins/repo/repo.js +348 -0
- package/plugins/runstrip/client.js +426 -0
- package/plugins/runstrip/index.js +301 -0
- package/plugins/runstrip/package.json +23 -0
- package/src/cartridges.js +133 -0
- package/src/contracts.js +130 -0
- package/src/critic.js +78 -0
- package/src/daemon.js +7 -1
- package/src/doctor.js +67 -0
- package/src/edit/core/effects.js +185 -0
- package/src/edit/core/ffmpeg.js +82 -5
- package/src/edit/core/layout.js +46 -1
- package/src/edit/core/ops.js +175 -3
- package/src/edit/core/plan.js +95 -9
- package/src/edit/core/project.d.ts +24 -0
- package/src/edit/core/project.js +64 -0
- package/src/edit/core/solver.js +34 -6
- package/src/edit/core/style-brief.js +211 -0
- package/src/edit/core/style-packs.js +57 -0
- package/src/edit/core/transitions.js +17 -0
- package/src/edit/core/type-kit.js +173 -0
- package/src/edit/director/ask.js +37 -3
- package/src/edit/director/assembly.js +829 -0
- package/src/edit/director/continuity.js +137 -0
- package/src/edit/director/custom-motion.js +88 -0
- package/src/edit/director/graphics.js +186 -0
- package/src/edit/director/intent.js +125 -0
- package/src/edit/director/mentions.js +52 -0
- package/src/edit/director/plan.js +89 -12
- package/src/edit/director/revise.js +172 -7
- package/src/edit/director/viewer.js +136 -0
- package/src/edit/director/watch-fix.js +119 -0
- package/src/edit/engine/captions.js +110 -5
- package/src/edit/engine/confine.js +81 -4
- package/src/edit/engine/custom.js +243 -0
- package/src/edit/engine/dna2.js +893 -0
- package/src/edit/engine/fonts.js +218 -0
- package/src/edit/engine/graphics.js +439 -0
- package/src/edit/engine/index.js +14 -5
- package/src/edit/engine/motion.js +153 -14
- package/src/edit/engine/music-bed.js +59 -1
- package/src/edit/engine/packs.js +11 -0
- package/src/edit/engine/reference2.js +26 -0
- package/src/edit/engine/sfx.js +56 -1
- package/src/edit/engine/tool.js +21 -5
- package/src/edit/gates/assembly.js +194 -0
- package/src/edit/gates/copy.js +7 -4
- package/src/edit/gates/index.js +76 -8
- package/src/edit/gates/picture.js +6 -3
- package/src/edit/gates/reference.js +115 -0
- package/src/edit/gates/tile.js +96 -0
- package/src/edit/host/client.js +4 -3
- package/src/edit/host/clips.js +33 -0
- package/src/edit/host/jobs.js +9 -3
- package/src/edit/host/layers.js +134 -0
- package/src/edit/host/main.js +17 -7
- package/src/edit/host/paths.js +34 -3
- package/src/edit/host/preview.js +108 -0
- package/src/edit/host/projects.js +494 -29
- package/src/edit/host/server.js +263 -19
- package/src/edit/host/tavi.js +77 -0
- package/src/edit/loop/make.js +44 -3
- package/src/edit/recipes/assembly.js +352 -0
- package/src/edit/recipes/graphic-clips.js +59 -0
- package/src/edit/recipes/openings.js +36 -0
- package/src/edit/recipes/reel.js +138 -17
- package/src/edit/recipes/reference-look.js +29 -0
- package/src/edit/recipes/short-from-long.js +3 -3
- package/src/edit/recipes/sound.js +71 -0
- package/src/edit/runtime/cli.js +26 -5
- package/src/edit/runtime/fetch.js +4 -3
- package/src/edit/runtime/licences.js +7 -1
- package/src/explore.js +103 -0
- package/src/failure.js +1 -1
- package/src/gate-commands.js +114 -0
- package/src/gates/api.js +127 -0
- package/src/gates/commands.js +111 -0
- package/src/gates/detectors.js +370 -0
- package/src/gates/http.js +62 -0
- package/src/gates/index.js +196 -0
- package/src/gates/page.js +264 -0
- package/src/gates/sast.js +64 -0
- package/src/gates/stack.js +110 -0
- package/src/gates/tenant.js +162 -0
- package/src/gates/three.js +407 -0
- package/src/gates/ui.js +111 -0
- package/src/launch.js +15 -3
- package/src/loop.js +199 -7
- package/src/mcp.js +126 -0
- package/src/milestones.js +188 -0
- package/src/modes.js +32 -0
- package/src/orchestra.js +43 -0
- package/src/outcomes.js +88 -0
- package/src/profiles.js +5 -0
- package/src/receipts.js +238 -0
- package/src/release.js +356 -0
- package/src/runstrip.js +122 -0
- package/src/stack.js +120 -0
- package/src/verify.js +67 -20
- package/studio/dist/fonts/fraunces.woff2 +0 -0
- package/studio/dist/fonts/geist.woff2 +0 -0
- package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
- package/studio/dist/studio.css +452 -3
- package/studio/dist/studio.js +3 -3
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
|
-
|
|
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
|
-
|
|
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
|
+
}
|
package/src/mcp.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
|
|
3
|
+
import { CLIENT_VERSION } from "./paths.js"
|
|
4
|
+
|
|
5
|
+
// Harness 2.0 W16, MCP P3a (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
|
|
6
|
+
// GROUNDING_AND_CONNECTORS.md §4): servers from the owner's registry that need
|
|
7
|
+
// no sign-in, each tool used only if its full definition still hashes to what
|
|
8
|
+
// the owner pinned. The hash is Kriya's own (lib/mcp/tools.ts definitionHash
|
|
9
|
+
// over lib/agent/episodes.ts canonical), so a device and Kriya agree on drift.
|
|
10
|
+
// A minimal Streamable HTTP client: https only (http only to this machine),
|
|
11
|
+
// no redirects followed, and no credential of any kind sent: no
|
|
12
|
+
// Authorization, no cookie, never the device's Kriya token.
|
|
13
|
+
|
|
14
|
+
const PINNED = ["name", "title", "description", "inputSchema", "outputSchema", "annotations"]
|
|
15
|
+
|
|
16
|
+
/** Kriya's canonical JSON: keys sorted, undefined dropped (lib/agent/episodes.ts). */
|
|
17
|
+
export const canonical = (value) => {
|
|
18
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`
|
|
19
|
+
if (value && typeof value === "object") {
|
|
20
|
+
const entries = Object.entries(value).filter(([, v]) => v !== undefined)
|
|
21
|
+
return `{${entries
|
|
22
|
+
.sort(([a], [b]) => (a < b ? -1 : 1))
|
|
23
|
+
.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)
|
|
24
|
+
.join(",")}}`
|
|
25
|
+
}
|
|
26
|
+
return JSON.stringify(value)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The pinned parts of a tool definition, hashed as Kriya hashes them. */
|
|
30
|
+
export function definitionHash(definition) {
|
|
31
|
+
const pinned = Object.fromEntries(PINNED.filter((k) => definition?.[k] !== undefined).map((k) => [k, definition[k]]))
|
|
32
|
+
return createHash("sha256").update(canonical(pinned)).digest("hex")
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The tools a server lists that the owner pinned, unchanged: `{ tool, pin }`.
|
|
37
|
+
* A listed tool with no pin, or whose definition drifted, is left out.
|
|
38
|
+
*/
|
|
39
|
+
export function pinnedTools(listed, pins) {
|
|
40
|
+
const out = []
|
|
41
|
+
const dropped = []
|
|
42
|
+
for (const tool of listed ?? []) {
|
|
43
|
+
const pin = (pins ?? []).find((p) => p.name === tool?.name)
|
|
44
|
+
if (!pin) continue
|
|
45
|
+
if (definitionHash(tool) !== pin.definitionHash) dropped.push(tool.name)
|
|
46
|
+
else out.push({ tool, pin })
|
|
47
|
+
}
|
|
48
|
+
return { tools: out, drifted: dropped }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export class McpError extends Error {}
|
|
52
|
+
|
|
53
|
+
/** https, or http only to this machine; no credentials in the address. */
|
|
54
|
+
export function serverUrl(text) {
|
|
55
|
+
let url
|
|
56
|
+
try {
|
|
57
|
+
url = new URL(text)
|
|
58
|
+
} catch {
|
|
59
|
+
throw new McpError("That isn't a server address.")
|
|
60
|
+
}
|
|
61
|
+
const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)
|
|
62
|
+
if (url.username || url.password) throw new McpError("A server address carries no credentials.")
|
|
63
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) throw new McpError("Registry servers are https.")
|
|
64
|
+
return url
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const PROTOCOL = "2025-06-18"
|
|
68
|
+
|
|
69
|
+
/** One server's session: initialize, list, call. `fetchImpl` for tests. */
|
|
70
|
+
export function mcpSession(address, { fetchImpl = fetch, timeoutMs = 30_000 } = {}) {
|
|
71
|
+
const url = serverUrl(address)
|
|
72
|
+
let session
|
|
73
|
+
let id = 0
|
|
74
|
+
const post = async (body, signal) => {
|
|
75
|
+
const headers = { "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-protocol-version": PROTOCOL }
|
|
76
|
+
if (session) headers["mcp-session-id"] = session
|
|
77
|
+
const response = await fetchImpl(url, { method: "POST", headers, body: JSON.stringify(body), redirect: "error", signal: signal ?? AbortSignal.timeout(timeoutMs) })
|
|
78
|
+
const next = response.headers.get("mcp-session-id")
|
|
79
|
+
if (next) session = next
|
|
80
|
+
return response
|
|
81
|
+
}
|
|
82
|
+
async function request(method, params, signal) {
|
|
83
|
+
const want = ++id
|
|
84
|
+
const response = await post({ jsonrpc: "2.0", id: want, method, params }, signal)
|
|
85
|
+
if (!response.ok) throw new McpError(`The server answered ${response.status}.`)
|
|
86
|
+
const type = response.headers.get("content-type") ?? ""
|
|
87
|
+
let message
|
|
88
|
+
if (type.includes("text/event-stream")) {
|
|
89
|
+
const text = await response.text()
|
|
90
|
+
for (const line of text.split("\n")) {
|
|
91
|
+
if (!line.startsWith("data:")) continue
|
|
92
|
+
try {
|
|
93
|
+
const m = JSON.parse(line.slice(5))
|
|
94
|
+
if (m?.id === want) message = m
|
|
95
|
+
} catch {
|
|
96
|
+
// Not a message
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
} else message = await response.json()
|
|
100
|
+
if (!message) throw new McpError("The server sent no answer.")
|
|
101
|
+
if (message.error) throw new McpError(`The server refused: ${String(message.error.message ?? "error").slice(0, 300)}`)
|
|
102
|
+
return message.result
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
async open() {
|
|
106
|
+
await request("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "kriya-harness", version: CLIENT_VERSION } })
|
|
107
|
+
await post({ jsonrpc: "2.0", method: "notifications/initialized" })
|
|
108
|
+
},
|
|
109
|
+
async tools() {
|
|
110
|
+
const all = []
|
|
111
|
+
let cursor
|
|
112
|
+
for (let page = 0; page < 10; page++) {
|
|
113
|
+
const result = await request("tools/list", cursor ? { cursor } : {})
|
|
114
|
+
all.push(...(result?.tools ?? []))
|
|
115
|
+
cursor = result?.nextCursor
|
|
116
|
+
if (!cursor) break
|
|
117
|
+
}
|
|
118
|
+
return all
|
|
119
|
+
},
|
|
120
|
+
call: (name, args, signal) => request("tools/call", { name, arguments: args ?? {} }, signal),
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** A model-facing name: mcp__<server>__<tool>, within DeepSeek's function-name rules. */
|
|
125
|
+
export const toolName = (serverId, name) =>
|
|
126
|
+
`mcp__${serverId}__${name}`.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64)
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import { closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
|
|
3
|
+
import { dirname, join } from "node:path"
|
|
4
|
+
|
|
5
|
+
import { planStatus } from "./loop.js"
|
|
6
|
+
import { projectRoot } from "./skill-switches.js"
|
|
7
|
+
import { progressFiles, readProgress, VerifyError } from "./verify.js"
|
|
8
|
+
|
|
9
|
+
// Harness 2.0 milestones (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
|
|
10
|
+
// ORCHESTRA.md §4, WD-12): long work as a ledger of at most 12 milestones,
|
|
11
|
+
// each one bounded plan (MAX_STEPS and MAX_ATTEMPTS unchanged). The ledger
|
|
12
|
+
// lives in ~/.kriya/progress/<project>/milestones.json, outside the project,
|
|
13
|
+
// written only by this code: a milestone is done only when its plan's every
|
|
14
|
+
// step passed the person's check, never because the model says so. The head
|
|
15
|
+
// plans milestone i+1 only after milestone i is done; a blocked one stops the
|
|
16
|
+
// work for the person. Off unless kriya was started with --milestones.
|
|
17
|
+
|
|
18
|
+
export const MAX_MILESTONES = 12
|
|
19
|
+
export const LOCK_STALE_MS = 10_000
|
|
20
|
+
const LOCK_WAIT_MS = 2_000
|
|
21
|
+
|
|
22
|
+
/** The ledger's file: beside the project's progress records. */
|
|
23
|
+
export function milestonesFile(root) {
|
|
24
|
+
return join(dirname(progressFiles(root, "ledger").json), "milestones.json")
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The ledger, or undefined. */
|
|
28
|
+
export function readMilestones(root) {
|
|
29
|
+
try {
|
|
30
|
+
return JSON.parse(readFileSync(milestonesFile(root), "utf8"))
|
|
31
|
+
} catch {
|
|
32
|
+
return undefined
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Runs `change(ledger)` under the ledger's lock and writes its result
|
|
40
|
+
* atomically (temp file + rename). Two sessions in one project may run at
|
|
41
|
+
* once: a second writer waits briefly, then is told; a lock older than
|
|
42
|
+
* LOCK_STALE_MS (a crashed session) is taken over.
|
|
43
|
+
*/
|
|
44
|
+
export async function updateMilestones(root, change, { now = Date.now, waitMs = LOCK_WAIT_MS } = {}) {
|
|
45
|
+
const file = milestonesFile(root)
|
|
46
|
+
const lock = `${file}.lock`
|
|
47
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
48
|
+
const started = now()
|
|
49
|
+
for (;;) {
|
|
50
|
+
try {
|
|
51
|
+
closeSync(openSync(lock, "wx", 0o600))
|
|
52
|
+
break
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (error.code !== "EEXIST") throw error
|
|
55
|
+
let age = 0
|
|
56
|
+
try {
|
|
57
|
+
age = now() - statSync(lock).mtimeMs
|
|
58
|
+
} catch {
|
|
59
|
+
continue
|
|
60
|
+
}
|
|
61
|
+
if (age > LOCK_STALE_MS) {
|
|
62
|
+
rmSync(lock, { force: true })
|
|
63
|
+
continue
|
|
64
|
+
}
|
|
65
|
+
if (now() - started >= waitMs) throw new VerifyError("Another session is updating milestones; try again in a moment.")
|
|
66
|
+
await sleep(50)
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
const next = change(readMilestones(root))
|
|
71
|
+
if (next !== undefined) {
|
|
72
|
+
const temp = `${file}.${process.pid}.tmp`
|
|
73
|
+
writeFileSync(temp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 })
|
|
74
|
+
renameSync(temp, file)
|
|
75
|
+
}
|
|
76
|
+
return next
|
|
77
|
+
} finally {
|
|
78
|
+
rmSync(lock, { force: true })
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const text = (v, max) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim().slice(0, max) : "")
|
|
83
|
+
|
|
84
|
+
/** 1 to 12 milestones, each a title and a done-when, roles checked against `roles` when given. */
|
|
85
|
+
export function validateMilestones(input, roles) {
|
|
86
|
+
const list = Array.isArray(input) ? input : []
|
|
87
|
+
if (!list.length) throw new VerifyError("Milestones need at least one milestone.")
|
|
88
|
+
if (list.length > MAX_MILESTONES) throw new VerifyError(`At most ${MAX_MILESTONES} milestones; split the work differently.`)
|
|
89
|
+
const out = list.map((m, i) => {
|
|
90
|
+
const title = text(m?.title, 200)
|
|
91
|
+
const doneWhen = text(m?.done_when ?? m?.doneWhen, 500)
|
|
92
|
+
if (!title || !doneWhen) throw new VerifyError(`Milestone ${i + 1} needs a title and done_when.`)
|
|
93
|
+
const asked = Array.isArray(m?.roles) ? [...new Set(m.roles.filter((r) => typeof r === "string"))] : []
|
|
94
|
+
if (roles && asked.some((r) => !roles.includes(r))) throw new VerifyError(`Milestone ${i + 1} names a role Kriya doesn't have.`)
|
|
95
|
+
return { title, doneWhen, roles: roles ? asked : [], status: "todo" }
|
|
96
|
+
})
|
|
97
|
+
if (new Set(out.map((m) => m.title.toLowerCase())).size !== out.length) throw new VerifyError("Two milestones have the same title.")
|
|
98
|
+
return out
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const open = (ledger) => ledger?.milestones?.some((m) => m.status !== "done")
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Records the milestones. While some are still open, a new list is refused
|
|
105
|
+
* unless `replan` (the person chose to replace them, asked by the harness).
|
|
106
|
+
*/
|
|
107
|
+
export async function saveMilestones(root, input, { roles, replan = false, now = () => new Date().toISOString() } = {}) {
|
|
108
|
+
const milestones = validateMilestones(input, roles)
|
|
109
|
+
return updateMilestones(root, (ledger) => {
|
|
110
|
+
if (open(ledger) && !replan) throw new VerifyError("This project already has milestones in progress. Work through them with kriya_plan, one milestone at a time; only the person can replace them.")
|
|
111
|
+
return { version: 1, createdAt: now(), milestones, ...(ledger && { replaced: (ledger.replaced ?? 0) + 1 }) }
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const planHash = (plan) => createHash("sha256").update(JSON.stringify(plan)).digest("hex").slice(0, 16)
|
|
116
|
+
|
|
117
|
+
/** The first milestone not done: the only one a plan may be for. */
|
|
118
|
+
export const currentMilestone = (ledger) => ledger?.milestones?.findIndex((m) => m.status !== "done") ?? -1
|
|
119
|
+
|
|
120
|
+
/** Before a plan is recorded: refused when every milestone is done or the current one is blocked. */
|
|
121
|
+
export function checkPlanAllowed(root) {
|
|
122
|
+
const ledger = readMilestones(root)
|
|
123
|
+
if (!ledger) return
|
|
124
|
+
const i = currentMilestone(ledger)
|
|
125
|
+
if (i === -1) throw new VerifyError("Every milestone is done. Tell the person; they can set new milestones.")
|
|
126
|
+
if (ledger.milestones[i].status === "blocked")
|
|
127
|
+
throw new VerifyError(`Milestone ${i + 1} (${ledger.milestones[i].title}) is blocked. Stop and tell the person what failed.`)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** After a plan is recorded: it belongs to the current milestone, which becomes active. */
|
|
131
|
+
export function bindPlan(root, sessionId, { now = () => new Date().toISOString() } = {}) {
|
|
132
|
+
const plan = readProgress(root, sessionId).plan
|
|
133
|
+
if (!plan) return Promise.resolve(undefined)
|
|
134
|
+
return updateMilestones(root, (ledger) => {
|
|
135
|
+
if (!ledger) return undefined
|
|
136
|
+
const i = currentMilestone(ledger)
|
|
137
|
+
if (i === -1) return undefined
|
|
138
|
+
const m = ledger.milestones[i]
|
|
139
|
+
ledger.milestones[i] = { ...m, status: "active", startedAt: m.startedAt ?? now(), plan: { sessionId, hash: planHash(plan) }, verdicts: [] }
|
|
140
|
+
return ledger
|
|
141
|
+
})
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* After a step: the active milestone's status from its plan's records, by
|
|
146
|
+
* code. Done only when every step passed; blocked when a step is blocked.
|
|
147
|
+
*/
|
|
148
|
+
export function syncMilestones(cwd, sessionId, { now = () => new Date().toISOString() } = {}) {
|
|
149
|
+
const root = projectRoot(cwd)
|
|
150
|
+
const ledger = readMilestones(root)
|
|
151
|
+
const i = currentMilestone(ledger)
|
|
152
|
+
if (i === -1 || ledger.milestones[i].plan?.sessionId !== sessionId) return Promise.resolve(ledger)
|
|
153
|
+
const rows = planStatus(cwd, sessionId)
|
|
154
|
+
if (!rows) return Promise.resolve(ledger)
|
|
155
|
+
const hash = planHash(readProgress(root, sessionId).plan)
|
|
156
|
+
return updateMilestones(root, (current) => {
|
|
157
|
+
const m = current?.milestones?.[i]
|
|
158
|
+
if (!m || m.plan?.sessionId !== sessionId || m.plan.hash !== hash) return undefined
|
|
159
|
+
const verdicts = rows.map((r) => ({ n: r.n, title: r.title, status: r.status }))
|
|
160
|
+
const status = rows.every((r) => r.status === "pass") ? "done" : rows.some((r) => r.status === "blocked") ? "blocked" : "active"
|
|
161
|
+
current.milestones[i] = { ...m, status, verdicts, ...(status === "done" && { doneAt: now() }) }
|
|
162
|
+
return current
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The late system-prompt section: where the long work stands, for a new or resumed session. Empty without milestones. */
|
|
167
|
+
export function milestonesText(root) {
|
|
168
|
+
const ledger = readMilestones(root)
|
|
169
|
+
if (!ledger?.milestones?.length) return ""
|
|
170
|
+
const i = currentMilestone(ledger)
|
|
171
|
+
const lines = ["# Milestones (from Kriya's ledger; only passing checks complete one)", ""]
|
|
172
|
+
ledger.milestones.forEach((m, n) => lines.push(`${n + 1}. ${m.title}: ${m.status}`))
|
|
173
|
+
lines.push("")
|
|
174
|
+
if (i === -1) lines.push("Every milestone is done.")
|
|
175
|
+
else {
|
|
176
|
+
const m = ledger.milestones[i]
|
|
177
|
+
lines.push(`Current: milestone ${i + 1}, ${m.title}. Done when: ${m.doneWhen}.${m.roles.length ? ` Roles: ${m.roles.join(", ")}.` : ""}`)
|
|
178
|
+
if (m.verdicts?.length) lines.push(`Last verdicts: ${m.verdicts.map((v) => `${v.n}. ${v.title}: ${v.status}`).join("; ")}.`)
|
|
179
|
+
lines.push(
|
|
180
|
+
m.status === "blocked"
|
|
181
|
+
? "It is blocked: stop and tell the person what failed."
|
|
182
|
+
: m.plan
|
|
183
|
+
? "Run its plan's remaining steps with kriya_step; the next milestone is planned only after this one is done."
|
|
184
|
+
: "Plan it with kriya_plan (one plan for this milestone only)."
|
|
185
|
+
)
|
|
186
|
+
}
|
|
187
|
+
return lines.join("\n")
|
|
188
|
+
}
|