@kriya-ai/harness 0.2.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/RELEASE_NOTES.md +121 -0
  2. package/SAFETY.md +181 -0
  3. package/THIRD_PARTY_NOTICES.md +113 -0
  4. package/bin/kriya.js +188 -2
  5. package/bundle/cordis.patch.yml +49 -0
  6. package/contract/SOURCE.md +3 -3
  7. package/contract/contract.json +504 -3
  8. package/contract/schemas/api.json +64 -0
  9. package/contract/schemas/auth_matrix.json +44 -0
  10. package/contract/schemas/component_states.json +33 -0
  11. package/contract/schemas/design_tokens.json +34 -0
  12. package/contract/schemas/scene_direction.json +82 -0
  13. package/contract/schemas/threat_model.json +44 -0
  14. package/package.json +2 -1
  15. package/plugins/changes/client.js +5 -3
  16. package/plugins/deploy/index.js +215 -0
  17. package/plugins/deploy/package.json +13 -0
  18. package/plugins/grounding/index.js +81 -0
  19. package/plugins/grounding/lookup.js +373 -0
  20. package/plugins/grounding/package.json +13 -0
  21. package/plugins/kriya-tools/index.js +2 -1
  22. package/plugins/loop/index.js +376 -10
  23. package/plugins/mcp/index.js +79 -0
  24. package/plugins/mcp/package.json +13 -0
  25. package/plugins/mirror/index.js +17 -0
  26. package/plugins/overview/client.js +5 -2
  27. package/plugins/preview/client.js +12 -6
  28. package/plugins/progress/client.js +7 -4
  29. package/plugins/repo/index.js +230 -0
  30. package/plugins/repo/package.json +13 -0
  31. package/plugins/repo/repo.js +348 -0
  32. package/plugins/runstrip/client.js +426 -0
  33. package/plugins/runstrip/index.js +301 -0
  34. package/plugins/runstrip/package.json +23 -0
  35. package/src/cartridges.js +133 -0
  36. package/src/contracts.js +130 -0
  37. package/src/critic.js +78 -0
  38. package/src/daemon.js +7 -1
  39. package/src/doctor.js +67 -0
  40. package/src/edit/core/effects.js +185 -0
  41. package/src/edit/core/ffmpeg.js +82 -5
  42. package/src/edit/core/layout.js +46 -1
  43. package/src/edit/core/ops.js +175 -3
  44. package/src/edit/core/plan.js +95 -9
  45. package/src/edit/core/project.d.ts +24 -0
  46. package/src/edit/core/project.js +64 -0
  47. package/src/edit/core/solver.js +34 -6
  48. package/src/edit/core/style-brief.js +211 -0
  49. package/src/edit/core/style-packs.js +57 -0
  50. package/src/edit/core/transitions.js +17 -0
  51. package/src/edit/core/type-kit.js +173 -0
  52. package/src/edit/director/ask.js +37 -3
  53. package/src/edit/director/assembly.js +829 -0
  54. package/src/edit/director/continuity.js +137 -0
  55. package/src/edit/director/custom-motion.js +88 -0
  56. package/src/edit/director/graphics.js +186 -0
  57. package/src/edit/director/intent.js +125 -0
  58. package/src/edit/director/mentions.js +52 -0
  59. package/src/edit/director/plan.js +89 -12
  60. package/src/edit/director/revise.js +172 -7
  61. package/src/edit/director/viewer.js +136 -0
  62. package/src/edit/director/watch-fix.js +119 -0
  63. package/src/edit/engine/captions.js +110 -5
  64. package/src/edit/engine/confine.js +81 -4
  65. package/src/edit/engine/custom.js +243 -0
  66. package/src/edit/engine/dna2.js +893 -0
  67. package/src/edit/engine/fonts.js +218 -0
  68. package/src/edit/engine/graphics.js +439 -0
  69. package/src/edit/engine/index.js +14 -5
  70. package/src/edit/engine/motion.js +153 -14
  71. package/src/edit/engine/music-bed.js +59 -1
  72. package/src/edit/engine/packs.js +11 -0
  73. package/src/edit/engine/reference2.js +26 -0
  74. package/src/edit/engine/sfx.js +56 -1
  75. package/src/edit/engine/tool.js +21 -5
  76. package/src/edit/gates/assembly.js +194 -0
  77. package/src/edit/gates/copy.js +7 -4
  78. package/src/edit/gates/index.js +76 -8
  79. package/src/edit/gates/picture.js +6 -3
  80. package/src/edit/gates/reference.js +115 -0
  81. package/src/edit/gates/tile.js +96 -0
  82. package/src/edit/host/client.js +4 -3
  83. package/src/edit/host/clips.js +33 -0
  84. package/src/edit/host/jobs.js +9 -3
  85. package/src/edit/host/layers.js +134 -0
  86. package/src/edit/host/main.js +17 -7
  87. package/src/edit/host/paths.js +34 -3
  88. package/src/edit/host/preview.js +108 -0
  89. package/src/edit/host/projects.js +494 -29
  90. package/src/edit/host/server.js +263 -19
  91. package/src/edit/host/tavi.js +77 -0
  92. package/src/edit/loop/make.js +44 -3
  93. package/src/edit/recipes/assembly.js +352 -0
  94. package/src/edit/recipes/graphic-clips.js +59 -0
  95. package/src/edit/recipes/openings.js +36 -0
  96. package/src/edit/recipes/reel.js +138 -17
  97. package/src/edit/recipes/reference-look.js +29 -0
  98. package/src/edit/recipes/short-from-long.js +3 -3
  99. package/src/edit/recipes/sound.js +71 -0
  100. package/src/edit/runtime/cli.js +26 -5
  101. package/src/edit/runtime/fetch.js +4 -3
  102. package/src/edit/runtime/licences.js +7 -1
  103. package/src/explore.js +103 -0
  104. package/src/failure.js +1 -1
  105. package/src/gate-commands.js +114 -0
  106. package/src/gates/api.js +127 -0
  107. package/src/gates/commands.js +111 -0
  108. package/src/gates/detectors.js +370 -0
  109. package/src/gates/http.js +62 -0
  110. package/src/gates/index.js +196 -0
  111. package/src/gates/page.js +264 -0
  112. package/src/gates/sast.js +64 -0
  113. package/src/gates/stack.js +110 -0
  114. package/src/gates/tenant.js +162 -0
  115. package/src/gates/three.js +407 -0
  116. package/src/gates/ui.js +111 -0
  117. package/src/launch.js +15 -3
  118. package/src/loop.js +199 -7
  119. package/src/mcp.js +126 -0
  120. package/src/milestones.js +188 -0
  121. package/src/modes.js +32 -0
  122. package/src/orchestra.js +43 -0
  123. package/src/outcomes.js +88 -0
  124. package/src/profiles.js +5 -0
  125. package/src/receipts.js +238 -0
  126. package/src/release.js +356 -0
  127. package/src/runstrip.js +122 -0
  128. package/src/stack.js +120 -0
  129. package/src/verify.js +67 -20
  130. package/studio/dist/fonts/fraunces.woff2 +0 -0
  131. package/studio/dist/fonts/geist.woff2 +0 -0
  132. package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
  133. package/studio/dist/studio.css +452 -3
  134. package/studio/dist/studio.js +3 -3
package/src/modes.js CHANGED
@@ -107,6 +107,38 @@ export const SWITCHES = [
107
107
  ["browser-tools", "KRIYA_BROWSER", true],
108
108
  // The intent router (plugins/router): on (owner, 2026-11-05, unmeasured)
109
109
  ["router", "KRIYA_ROUTER", true],
110
+ // Harness 2.0 role cartridges (Kriya-Tavi docs/kriya-harness/upgrade_2.0, W1):
111
+ // one discipline's guidance per builder; opt-in until measured; needs the loop
112
+ ["cartridges", "KRIYA_CARTRIDGES", false],
113
+ // Harness 2.0 orchestra (W2): the session on the owner's head level, builders on the
114
+ // worker level, the head taking over when the worker is stuck; opt-in until measured; needs the loop
115
+ ["orchestra", "KRIYA_ORCHESTRA", false],
116
+ // Harness 2.0 gates (W3): deterministic checks after the person's check passes
117
+ // (secrets, contracts, the cartridge's detectors, flake and trace); opt-in until measured; needs the loop
118
+ ["gates", "KRIYA_GATES", false],
119
+ // Harness 2.0 critic (W6, WD-13): after a pass, a read-only head-level reviewer may earn one
120
+ // polish attempt, kept only if every check still passes; opt-in until measured; needs the loop
121
+ ["critic", "KRIYA_CRITIC", false],
122
+ // Harness 2.0 milestones (W10, WD-12): long work as a ledger of at most 12 bounded plans,
123
+ // each done only when its plan's every step passed; opt-in until measured; needs the loop
124
+ ["milestones", "KRIYA_MILESTONES", false],
125
+ // Harness 2.0 grounding (W15, WD-20): api_lookup, api_changes and api_version answer facts
126
+ // about installed packages from their own files; nothing imported or run; opt-in until measured
127
+ ["grounding", "KRIYA_GROUNDING", false],
128
+ // Harness 2.0 repository tools (W16, WD-19): typed git and gh tools through the person's own login;
129
+ // branch, commit, push and draft PR only with their approval, never in Auto; opt-in until measured
130
+ ["repo-tools", "KRIYA_REPO_TOOLS", false],
131
+ // Harness 2.0 MCP P3a (W16): the owner's registry servers that need no sign-in, tools pinned by hash; opt-in
132
+ ["mcp", "KRIYA_MCP", false],
133
+ // Harness 2.0 deploy (W17, WD-21, WD-22): G-RELEASE, preview and production deploys with approval,
134
+ // G-DEPLOYED, and the person's own commands refused in the shell; opt-in
135
+ ["deploy", "KRIYA_DEPLOY", false],
136
+ // Harness 2.0 Explore (W14, WD-18): 2–3 gated takes of a creative step (frontend, designer, graphics) in one
137
+ // folder, the person (or the critic, headless) keeping one; inside MAX_ATTEMPTS; needs the loop and cartridges; opt-in
138
+ ["explore", "KRIYA_EXPLORE", false],
139
+ // Harness 2.0 interface (W18, WD-23): the Run strip, gate chips, Mission Control and the
140
+ // Live/Proof/Changes/Project tracks (old tab ids kept); off, the Web UI is as before; opt-in
141
+ ["runstrip", "KRIYA_RUNSTRIP", false],
110
142
  // The Editing Studio (track E): off until the owner turns it on; off, nothing
111
143
  // under src/edit/ loads
112
144
  ["edit", "KRIYA_EDIT", false],
@@ -0,0 +1,43 @@
1
+ // Harness 2.0 W2, the orchestra (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
2
+ // ORCHESTRA.md, ARCHITECTURE.md §5): the session runs on the owner's head
3
+ // level; a step's builders run on the worker level and the head takes over
4
+ // after `escalateAfter` failed attempts, or when the worker is stuck, inside
5
+ // the existing 4 attempts. Pure: code decides, from recorded failure classes
6
+ // and signatures, never from model text. Off unless kriya was started with
7
+ // --orchestra (KRIYA_ORCHESTRA=on) and Kriya offered both levels (GET /models
8
+ // `orchestra`); otherwise every builder runs on the session's own level, as before.
9
+
10
+ export const DEFAULT_ESCALATE_AFTER = 2
11
+
12
+ /** The head and worker levels for this process, or undefined: only aliases the plan allows, never from the shell alone. */
13
+ export function orchestraFromEnv(env = process.env) {
14
+ if (env.KRIYA_ORCHESTRA !== "on" || env.KRIYA_LOOP !== "on") return undefined
15
+ const allowed = String(env.KRIYA_ALLOWED_TIERS ?? "").split(",").filter(Boolean)
16
+ const head = env.KRIYA_ORCHESTRA_HEAD
17
+ const worker = env.KRIYA_ORCHESTRA_WORKER
18
+ if (!head || !worker || head === worker || !allowed.includes(head) || !allowed.includes(worker)) return undefined
19
+ return { head, worker }
20
+ }
21
+
22
+ /**
23
+ * The level for attempt `attempt` (1-based) of a step.
24
+ * head when attempt > escalateAfter (architect steps: always),
25
+ * head when `force` (the loop guard would stall a worker; ARCHITECTURE §5),
26
+ * head when the worker is stuck: the last two failures had the same signature,
27
+ * worker otherwise, and always after an `environment` failure (a stronger
28
+ * model can't install a tool or fix a machine).
29
+ * @param {{ orchestra?: { head: string, worker: string }, attempt: number, previous?: { kind?: string, sig?: string }, earlier?: { sig?: string }, force?: boolean, escalateAfter?: number, role?: string }} input
30
+ */
31
+ export function tierFor({ orchestra, attempt, previous, earlier, force = false, escalateAfter = DEFAULT_ESCALATE_AFTER, role }) {
32
+ if (!orchestra) return undefined
33
+ if (previous?.kind === "environment") return orchestra.worker
34
+ const after = role === "architect" ? 0 : Number.isInteger(escalateAfter) && escalateAfter >= 0 && escalateAfter <= 4 ? escalateAfter : DEFAULT_ESCALATE_AFTER
35
+ if (force || attempt > after) return orchestra.head
36
+ if (previous?.sig && earlier?.sig === previous.sig) return orchestra.head
37
+ return orchestra.worker
38
+ }
39
+
40
+ /** KRHE's escalateAfter (W10): a profile pins it with KRIYA_ESCALATE_AFTER, 0 to 4; anything else leaves the default. */
41
+ export function escalateAfterFromEnv(env = process.env) {
42
+ return /^[0-4]$/.test(env.KRIYA_ESCALATE_AFTER ?? "") ? Number(env.KRIYA_ESCALATE_AFTER) : undefined
43
+ }
@@ -0,0 +1,88 @@
1
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
2
+ import { dirname, join } from "node:path"
3
+
4
+ import { kriyaHome } from "./paths.js"
5
+
6
+ // Harness 2.0 W11 (Kriya-Tavi docs/kriya-harness/upgrade_2.0/SELF_EVOLUTION.md
7
+ // §6; HD-24, WD-15): the person's sharing opt-in, and the outcome counts it
8
+ // allows. Off by default (`kriya share on|off|status`, stored in the Kriya
9
+ // home, never in a project). Off, nothing is counted or kept. On, each step
10
+ // built with a role cartridge adds one to that cartridge version's count of
11
+ // verified, blocked or not checked steps; the mirror sends the counts with
12
+ // its next turn, if Kriya takes them. Counts only: no text, names or files.
13
+
14
+ const shareFile = () => join(kriyaHome(), "share.json")
15
+ const pendingFile = () => join(kriyaHome(), "outcomes-pending.json")
16
+
17
+ const readJson = (file) => {
18
+ try {
19
+ return JSON.parse(readFileSync(file, "utf8"))
20
+ } catch {
21
+ return undefined
22
+ }
23
+ }
24
+ function writeJson(file, value) {
25
+ mkdirSync(dirname(file), { recursive: true })
26
+ const temp = `${file}.${process.pid}.tmp`
27
+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
28
+ renameSync(temp, file)
29
+ }
30
+
31
+ /** The person's choice: on only when they turned it on. */
32
+ export function shareStatus() {
33
+ const saved = readJson(shareFile())
34
+ return { on: saved?.on === true, ...(saved?.changedAt && { changedAt: saved.changedAt }) }
35
+ }
36
+
37
+ /** `kriya share on|off`. Turning it off drops counts not yet sent. */
38
+ export function setShare(on, now = () => new Date().toISOString()) {
39
+ writeJson(shareFile(), { on: Boolean(on), changedAt: now() })
40
+ if (!on) writeJson(pendingFile(), {})
41
+ }
42
+
43
+ const KEY = /^(kriya-role-[a-z]{2,20})@(\d{1,3}\.\d{1,3}\.\d{1,3})$/
44
+ const FIELD = { pass: "verified", blocked: "blocked", "not checked": "notChecked" }
45
+
46
+ /**
47
+ * One step's outcome for the cartridge version that built it ("id@version").
48
+ * Nothing without the opt-in, for another status, or for a step built
49
+ * without a cartridge.
50
+ */
51
+ export function recordOutcome(cartridge, status) {
52
+ if (!shareStatus().on || !KEY.test(cartridge ?? "") || !FIELD[status]) return false
53
+ // shortcut: two sessions finishing a step in the same instant can lose one count; a lock comes if counts matter more
54
+ const pending = readJson(pendingFile()) ?? {}
55
+ const row = pending[cartridge] ?? { verified: 0, blocked: 0, notChecked: 0, undone: 0 }
56
+ row[FIELD[status]] = Math.min(10_000, row[FIELD[status]] + 1)
57
+ pending[cartridge] = row
58
+ writeJson(pendingFile(), pending)
59
+ return true
60
+ }
61
+
62
+ /** The counts to send (at most 20 versions), taken off the pending file; [] without the opt-in. */
63
+ export function takeOutcomes() {
64
+ if (!shareStatus().on) return []
65
+ const pending = readJson(pendingFile()) ?? {}
66
+ const keys = Object.keys(pending).filter((k) => KEY.test(k)).slice(0, 20)
67
+ if (!keys.length) return []
68
+ const out = keys.map((k) => {
69
+ const [, cartridgeId, version] = KEY.exec(k)
70
+ return { cartridgeId, version, ...pending[k] }
71
+ })
72
+ for (const k of keys) delete pending[k]
73
+ writeJson(pendingFile(), pending)
74
+ return out
75
+ }
76
+
77
+ /** Counts taken for a turn that Kriya then didn't store: back into the pending file. */
78
+ export function returnOutcomes(outcomes) {
79
+ if (!outcomes?.length || !shareStatus().on) return
80
+ const pending = readJson(pendingFile()) ?? {}
81
+ for (const o of outcomes) {
82
+ const key = `${o.cartridgeId}@${o.version}`
83
+ const row = pending[key] ?? { verified: 0, blocked: 0, notChecked: 0, undone: 0 }
84
+ for (const f of ["verified", "blocked", "notChecked", "undone"]) row[f] = Math.min(10_000, row[f] + (o[f] ?? 0))
85
+ pending[key] = row
86
+ }
87
+ writeJson(pendingFile(), pending)
88
+ }
package/src/profiles.js CHANGED
@@ -53,6 +53,11 @@ export const LINKED = {
53
53
  "@kriya-ai/harness-fs-freshness": join(PACKAGE_ROOT, "plugins", "fs-freshness"),
54
54
  "@kriya-ai/harness-loop": join(PACKAGE_ROOT, "plugins", "loop"),
55
55
  "@kriya-ai/harness-budget": join(PACKAGE_ROOT, "plugins", "budget"),
56
+ "@kriya-ai/harness-grounding": join(PACKAGE_ROOT, "plugins", "grounding"),
57
+ "@kriya-ai/harness-repo": join(PACKAGE_ROOT, "plugins", "repo"),
58
+ "@kriya-ai/harness-mcp": join(PACKAGE_ROOT, "plugins", "mcp"),
59
+ "@kriya-ai/harness-deploy": join(PACKAGE_ROOT, "plugins", "deploy"),
60
+ "@kriya-ai/harness-runstrip": join(PACKAGE_ROOT, "plugins", "runstrip"),
56
61
  "@kriya-ai/harness-anchor": join(PACKAGE_ROOT, "plugins", "anchor"),
57
62
  "@kriya-ai/harness-edit": join(PACKAGE_ROOT, "plugins", "edit"),
58
63
  }
@@ -0,0 +1,238 @@
1
+ import { execFileSync } from "node:child_process"
2
+ import { createHash } from "node:crypto"
3
+ import { mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
4
+ import { dirname, join } from "node:path"
5
+
6
+ import { stepLabel } from "./loop.js"
7
+ import { canonical } from "./mcp.js"
8
+ import { CLIENT_VERSION, kriyaHome } from "./paths.js"
9
+ import { redact } from "../plugins/repo/repo.js"
10
+ import { readState } from "./release.js"
11
+ import { progressFiles, readProgress, verdict } from "./verify.js"
12
+
13
+ // Harness 2.0 W19, proof receipts (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
14
+ // DIFFERENTIATORS.md D1, WD-24). What Kriya Harness checked by code on this
15
+ // computer, copied from the session's ledger (progress file): verdicts,
16
+ // attempts, roles, tiers, gate results, cartridge versions. Nothing from model
17
+ // text, and no file contents, prompts, commands, output or paths. A hash chain
18
+ // over the ledger's run records makes any later edit of one visible: `kriya
19
+ // receipt verify` recomputes it and names the first link that fails. It is
20
+ // evidence of what was checked, labelled so, never a guarantee.
21
+
22
+ export const LABEL = "checked on this computer"
23
+ const SEED = "kriya-receipt-1"
24
+ const sha = (text) => createHash("sha256").update(text).digest("hex")
25
+ const CARTRIDGE = /^(kriya-role-[a-z]{2,20})@(\d{1,3}\.\d{1,3}\.\d{1,3})$/
26
+ const ID = /^[A-Za-z0-9_.-]{1,60}$/
27
+
28
+ export class ReceiptError extends Error {}
29
+
30
+ /** h_0 = sha256(seed); h_i = sha256(h_{i-1} ‖ canonical(run_i)). */
31
+ export function chainLinks(runs) {
32
+ const links = []
33
+ let h = sha(SEED)
34
+ for (const run of runs ?? []) links.push((h = sha(h + canonical(run))))
35
+ return links
36
+ }
37
+
38
+ /** The receipt for a ledger, by code only. `meta`: { project, session, commit, client }. */
39
+ export function receiptFrom(progress, meta) {
40
+ const runs = progress.runs ?? []
41
+ const plan = progress.plan
42
+ const v = verdict(progress)
43
+ const cartridges = {}
44
+ for (const b of progress.builders ?? []) {
45
+ const m = CARTRIDGE.exec(b.cartridge ?? "")
46
+ if (m) cartridges[m[1]] = m[2]
47
+ }
48
+ const steps = (plan?.steps ?? []).map((step, i) => {
49
+ const label = stepLabel(plan, i + 1)
50
+ const found = v.steps.find((s) => s.step === label)
51
+ const last = runs.findLast((r) => r.step === label)
52
+ return {
53
+ n: i + 1,
54
+ ...(typeof step.role === "string" && ID.test(step.role) && { role: step.role }),
55
+ verdict: found?.status ?? "not run",
56
+ attempts: found?.attempts ?? 0,
57
+ tiers: (progress.builders ?? []).filter((b) => b.step === label && typeof b.tier === "string" && ID.test(b.tier)).map((b) => b.tier),
58
+ gates: (last?.gates ?? []).filter((g) => /^G-[A-Z0-9-]{2,20}$/.test(g?.id ?? "")).map((g) => ({ id: g.id, status: String(g.status) })),
59
+ }
60
+ })
61
+ const links = chainLinks(runs)
62
+ return {
63
+ receipt: 1,
64
+ label: LABEL,
65
+ project: meta.project,
66
+ session: meta.session,
67
+ ...(meta.commit && { commit: meta.commit }),
68
+ ...(runs.at(-1)?.tree && { tree: runs.at(-1).tree }),
69
+ client: meta.client,
70
+ verdict: v.status,
71
+ ...(Object.keys(cartridges).length && { cartridges }),
72
+ steps,
73
+ runs: runs.length,
74
+ chain: `sha256:${links.at(-1) ?? sha(SEED)}`,
75
+ links,
76
+ }
77
+ }
78
+
79
+ /** The readable receipt: what was checked, how to verify it, and what it isn't. */
80
+ export function receiptMarkdown(r) {
81
+ const lines = [
82
+ `## Proof receipt (${LABEL})`,
83
+ "",
84
+ "What Kriya Harness checked by code on this computer, copied from its own records. Evidence of what was checked, not a guarantee.",
85
+ "",
86
+ `- Verdict: **${r.verdict}**, ${r.runs} check run${r.runs === 1 ? "" : "s"}`,
87
+ ...(r.commit ? [`- Commit: \`${r.commit.slice(0, 12)}\``] : []),
88
+ ...(r.cartridges ? [`- Cartridges: ${Object.entries(r.cartridges).map(([id, v]) => `${id}@${v}`).join(", ")}`] : []),
89
+ `- Kriya Harness ${r.client}`,
90
+ ]
91
+ if (r.steps.length) {
92
+ lines.push("", "| Step | Role | Verdict | Attempts | Tiers | Gates |", "| --- | --- | --- | --- | --- | --- |")
93
+ for (const s of r.steps) lines.push(`| ${s.n} | ${s.role ?? "—"} | ${s.verdict} | ${s.attempts} | ${s.tiers.join(", ") || "—"} | ${s.gates.map((g) => `${g.id} ${g.status}`).join(", ") || "—"} |`)
94
+ }
95
+ lines.push("", `Chain: \`${r.chain}\` (verify with \`kriya receipt verify\`).`)
96
+ return lines.join("\n")
97
+ }
98
+
99
+ const projectKey = (root) => sha(root).slice(0, 16)
100
+ const headOf = (root) => {
101
+ try {
102
+ return execFileSync("git", ["rev-parse", "--verify", "-q", "HEAD"], { cwd: root, encoding: "utf8", env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" }, stdio: ["ignore", "pipe", "ignore"] }).trim()
103
+ } catch {
104
+ return undefined
105
+ }
106
+ }
107
+
108
+ export const receiptFiles = (project, session) => {
109
+ const dir = join(kriyaHome(), "receipts", project)
110
+ return { json: join(dir, `${session}.json`), md: join(dir, `${session}.md`) }
111
+ }
112
+
113
+ /** Builds and writes a session's receipt; returns it with its readable form. */
114
+ export function makeReceipt(root, sessionId) {
115
+ progressFiles(root, sessionId)
116
+ const progress = readProgress(root, sessionId)
117
+ if (!progress.runs?.length && !progress.plan) throw new ReceiptError("That session has no plan and no check runs to put in a receipt.")
118
+ const commit = headOf(root)
119
+ const receipt = receiptFrom(progress, { project: projectKey(root), session: sessionId, ...(/^[0-9a-f]{40}$/.test(commit ?? "") && { commit }), client: CLIENT_VERSION })
120
+ // WD-22: what Kriya refused to run is written down for the person (readable part only: the verified fields stay the ledger's)
121
+ const left = readState(root).forPerson ?? []
122
+ const markdown = [
123
+ receiptMarkdown(receipt),
124
+ ...(left.length
125
+ ? ["", "### For you to run (Kriya never runs these)", "", ...left.map((p) => `- \`${redact(p.command).replace(/`/g, "'").replace(/(https?:\/\/[^\s?#]+)[?#]\S*/g, "$1")}\`: it ${p.why}`)]
126
+ : []),
127
+ ].join("\n")
128
+ const files = receiptFiles(receipt.project, sessionId)
129
+ mkdirSync(dirname(files.json), { recursive: true })
130
+ for (const [file, text] of [[files.json, `${JSON.stringify(receipt, null, 2)}\n`], [files.md, `${markdown}\n`]]) {
131
+ writeFileSync(`${file}.tmp`, text, { mode: 0o600 })
132
+ renameSync(`${file}.tmp`, file)
133
+ }
134
+ return { receipt, markdown, files }
135
+ }
136
+
137
+ /** The project's most recent session with a ledger, for `kriya receipt make` without an id. */
138
+ export function latestSession(root) {
139
+ const dir = dirname(progressFiles(root, "x").json)
140
+ let best
141
+ for (const f of (() => {
142
+ try {
143
+ return readdirSync(dir)
144
+ } catch {
145
+ return []
146
+ }
147
+ })()) {
148
+ if (!f.endsWith(".json") || f === "milestones.json") continue
149
+ const at = statSync(join(dir, f)).mtimeMs
150
+ if (!best || at > best.at) best = { id: f.slice(0, -5), at }
151
+ }
152
+ return best?.id
153
+ }
154
+
155
+ /**
156
+ * Recomputes a receipt from the ledger it names: the chain link by link
157
+ * (the first changed, missing or extra run is named), then every field.
158
+ * @returns {{ ok: boolean, problems: string[] }}
159
+ */
160
+ export function verifyReceipt(text) {
161
+ let r
162
+ try {
163
+ r = JSON.parse(text)
164
+ } catch {
165
+ return { ok: false, problems: ["The receipt isn't JSON."] }
166
+ }
167
+ if (r?.receipt !== 1 || !/^[0-9a-f]{16}$/.test(r.project ?? "") || !/^[A-Za-z0-9_-]{1,128}$/.test(r.session ?? "")) return { ok: false, problems: ["That isn't a Kriya receipt."] }
168
+ let progress
169
+ try {
170
+ progress = JSON.parse(readFileSync(join(kriyaHome(), "progress", r.project, `${r.session}.json`), "utf8"))
171
+ } catch {
172
+ return { ok: false, problems: ["The session's records aren't on this computer, so the receipt can't be checked here."] }
173
+ }
174
+ const problems = []
175
+ const now = chainLinks(progress.runs ?? [])
176
+ const was = Array.isArray(r.links) ? r.links : []
177
+ const n = Math.max(now.length, was.length)
178
+ for (let i = 0; i < n; i++) {
179
+ if (now[i] === was[i]) continue
180
+ problems.push(i >= now.length ? `Run ${i + 1} is in the receipt but no longer in the records.` : i >= was.length ? `Run ${i + 1} was added to the records after the receipt.` : `Run ${i + 1} (step ${progress.runs[i]?.step ?? "?"}) was changed after the receipt: the chain breaks at link ${i + 1}.`)
181
+ break
182
+ }
183
+ if (r.chain !== `sha256:${was.at(-1) ?? sha(SEED)}`) problems.push("The receipt's chain doesn't match its own links.")
184
+ const again = receiptFrom(progress, { project: r.project, session: r.session, ...(r.commit && { commit: r.commit }), client: r.client })
185
+ for (const key of new Set([...Object.keys(again), ...Object.keys(r)]))
186
+ if (key !== "links" && canonical(again[key]) !== canonical(r[key])) problems.push(`"${key}" doesn't match the records.`)
187
+ return { ok: problems.length === 0, problems }
188
+ }
189
+
190
+ /* ─────────────── Harness 2.0 W17: kriya report ─────────────── */
191
+
192
+ /**
193
+ * `kriya report`: a bundle the person attaches to a bug report themselves.
194
+ * Versions, the gates' capability matrix and self-tests, and this project's
195
+ * receipts (already free of file contents, prompts, commands, output, paths
196
+ * and secrets) with their chains, plus the release records' ids and statuses.
197
+ * Commands left for the person are kept with secrets redacted and query
198
+ * strings removed. Nothing is sent anywhere.
199
+ */
200
+ export async function makeReport(root, { gates, now = () => new Date() } = {}) {
201
+ const { gateMatrix, gateSelfTests } = await import("./doctor.js")
202
+ const { readState } = await import("./release.js")
203
+ const project = projectKey(root)
204
+ const receipts = []
205
+ for (const f of (() => {
206
+ try {
207
+ return readdirSync(join(kriyaHome(), "progress", project))
208
+ } catch {
209
+ return []
210
+ }
211
+ })()) {
212
+ if (!f.endsWith(".json") || f === "milestones.json") continue
213
+ const session = f.slice(0, -5)
214
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(session)) continue
215
+ try {
216
+ receipts.push(receiptFrom(readProgress(root, session), { project, session, client: CLIENT_VERSION }))
217
+ } catch {
218
+ // A record that isn't a session's
219
+ }
220
+ }
221
+ const state = readState(root)
222
+ const report = {
223
+ report: 1,
224
+ at: now().toISOString(),
225
+ client: CLIENT_VERSION,
226
+ node: process.versions.node,
227
+ platform: `${process.platform}-${process.arch}`,
228
+ project,
229
+ gates: gates ?? { matrix: await gateMatrix(), selfTests: await gateSelfTests() },
230
+ receipts,
231
+ releases: state.records.map((r) => ({ kind: r.kind, ...(r.target && { target: r.target }), commit: r.commit, ...(r.ready !== undefined && { ready: r.ready }), ...(r.ok !== undefined && { ok: r.ok }), ...(r.lines && { lines: r.lines }) })),
232
+ forPerson: (state.forPerson ?? []).map((p) => ({ why: p.why, command: redact(p.command).replace(/(https?:\/\/[^\s?#]+)[?#][^\s]*/g, "$1") })),
233
+ }
234
+ const file = join(kriyaHome(), "reports", `report-${report.at.replace(/[:.]/g, "-")}.json`)
235
+ mkdirSync(dirname(file), { recursive: true })
236
+ writeFileSync(file, `${JSON.stringify(report, null, 2)}\n`, { mode: 0o600 })
237
+ return { report, file }
238
+ }