@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
@@ -0,0 +1,301 @@
1
+ import { createHash } from "node:crypto"
2
+ import { existsSync, readdirSync, readFileSync } from "node:fs"
3
+ import { join } from "node:path"
4
+
5
+ import { call, me } from "../../src/api.js"
6
+ import { ChangesError } from "../../src/changes.js"
7
+ import { listCheckpoints, restoreTree, trackedRoot } from "../../src/checkpoints.js"
8
+ import { gateMatrix } from "../../src/doctor.js"
9
+ import { liveBuild } from "../../src/loop.js"
10
+ import { readMilestones } from "../../src/milestones.js"
11
+ import { orchestraFromEnv } from "../../src/orchestra.js"
12
+ import { kriyaHome } from "../../src/paths.js"
13
+ import { readState } from "../../src/release.js"
14
+ import { receiptFiles, verifyReceipt } from "../../src/receipts.js"
15
+ import { formatInr, liveGates, missionRows, stepChips, stripState } from "../../src/runstrip.js"
16
+ import { projectRoot } from "../../src/skill-switches.js"
17
+ import { readProgress } from "../../src/verify.js"
18
+ import { readDevice } from "../../src/store.js"
19
+ import { createRepo } from "../repo/repo.js"
20
+
21
+ // Harness 2.0 W18 (WD-23), node half: the Run strip, Mission Control and the
22
+ // four tracks' extra sections, as read-only routes inside Connection's fence
23
+ // (as plugins/progress). Two routes act, both the person's own clicks in the
24
+ // Web UI and never an agent tool: Stop (DSH's own user cancel, as the
25
+ // composer's stop button) and "Restore this point" (as `kriya undo`, which
26
+ // saves the files it replaces first). Mounted only with --runstrip.
27
+
28
+ export const name = "kriya-runstrip"
29
+ export const inject = ["connection", "sessions", "agents"]
30
+
31
+ export const ROUTES = {
32
+ strip: "/api/kriya.runstrip",
33
+ stop: "/api/kriya.runstrip.stop",
34
+ missions: "/api/kriya.missions",
35
+ track: "/api/kriya.tracks",
36
+ restore: "/api/kriya.tracks.restore",
37
+ verify: "/api/kriya.tracks.receipt-verify",
38
+ }
39
+
40
+ const SESSION = /^[A-Za-z0-9_-]{1,128}$/
41
+ const sessionOf = (value) => {
42
+ if (typeof value !== "string" || !SESSION.test(value)) throw new ChangesError("Which session?")
43
+ return value
44
+ }
45
+ const json = async (request) => {
46
+ if (!/^application\/json\b/i.test(request.headers.get("content-type") ?? "")) throw new ChangesError("Send JSON.")
47
+ return (await request.json().catch(() => null)) ?? {}
48
+ }
49
+ const names = (env = process.env) => {
50
+ try {
51
+ return JSON.parse(env.KRIYA_MODEL_NAMES || "{}")
52
+ } catch {
53
+ return {}
54
+ }
55
+ }
56
+
57
+ /**
58
+ * This task's spend: the device's month total from GET /me when the task's
59
+ * first builder starts, and again once per later builder (HARNESS_UX §3.1);
60
+ * shown as the difference, "estimated" while Kriya has unpriced requests.
61
+ * @param {{ account: () => Promise<any> }} host
62
+ */
63
+ export function spendTracker({ account }) {
64
+ const tasks = new Map() // session → { plan, since, builder, base?, used?, unpriced? }
65
+ return {
66
+ get(sessionId, plan, live) {
67
+ let t = tasks.get(sessionId)
68
+ if (!t || t.plan !== plan) tasks.set(sessionId, (t = { plan, since: live.startedAt, builder: undefined }))
69
+ if (t.builder !== live.startedAt) {
70
+ t.builder = live.startedAt
71
+ account().then(
72
+ (a) => {
73
+ const used = Number(a?.harness?.usedMicroInr)
74
+ if (!Number.isFinite(used)) return
75
+ t.base ??= used
76
+ t.used = used
77
+ t.unpriced = Boolean(a.harness.unpriced)
78
+ },
79
+ () => {}
80
+ )
81
+ }
82
+ return { since: t.since, spend: t.base === undefined ? null : { inr: formatInr(t.used - t.base), estimated: t.unpriced } }
83
+ },
84
+ }
85
+ }
86
+
87
+ /** Ledgers on this computer: ~/.kriya/progress/<project>/milestones.json, each with its project's folder from a session record beside it. */
88
+ export function ledgers(home = kriyaHome()) {
89
+ const dir = join(home, "progress")
90
+ const out = []
91
+ let keys = []
92
+ try {
93
+ keys = readdirSync(dir)
94
+ } catch {
95
+ return out
96
+ }
97
+ for (const key of keys) {
98
+ const folder = join(dir, key)
99
+ if (!existsSync(join(folder, "milestones.json"))) continue
100
+ const record = readdirSync(folder).find((f) => f.endsWith(".json") && f !== "milestones.json")
101
+ let root
102
+ try {
103
+ root = JSON.parse(readFileSync(join(folder, record), "utf8")).root
104
+ } catch {
105
+ continue
106
+ }
107
+ if (typeof root === "string" && root) out.push({ root, ledger: readMilestones(root) })
108
+ }
109
+ return out
110
+ }
111
+
112
+ /** @param {{ folderOf: (id: string) => Promise<string | undefined>, running: () => string[], cancel: (id: string) => boolean, account: () => Promise<any>, env?: NodeJS.ProcessEnv, now?: () => number, home?: string, repoOf?: (cwd: string) => any, matrix?: () => Promise<any>, mcp?: () => Promise<any[]>, liveOf?: (id: string) => any }} host */
113
+ export function handlers(host) {
114
+ const env = host.env ?? process.env
115
+ const now = host.now ?? Date.now
116
+ const liveOf = host.liveOf ?? liveBuild
117
+ const spend = spendTracker(host)
118
+ const folder = async (id) => {
119
+ const cwd = await host.folderOf(id)
120
+ if (!cwd) throw new ChangesError("That session isn't known here.")
121
+ return cwd
122
+ }
123
+ const progressOf = (cwd, id) => {
124
+ try {
125
+ return readProgress(projectRoot(cwd), id)
126
+ } catch {
127
+ return { runs: [] }
128
+ }
129
+ }
130
+
131
+ async function strip() {
132
+ const runs = []
133
+ for (const id of host.running()) {
134
+ const live = liveOf(id)
135
+ const cwd = live && (await host.folderOf(id))
136
+ if (!cwd) continue
137
+ const progress = progressOf(cwd, id)
138
+ if (!progress.plan) continue
139
+ const root = projectRoot(cwd)
140
+ const { since, spend: money } = spend.get(id, progress.plan.at, live)
141
+ const state = stripState({ sessionId: id, progress, live, ledger: readMilestones(root), orchestra: orchestraFromEnv(env), names: names(env), since, spend: money, now: now() })
142
+ if (state.running) runs.push(state)
143
+ }
144
+ return { runs }
145
+ }
146
+
147
+ async function stop(request) {
148
+ const id = sessionOf((await json(request)).session)
149
+ if (!liveOf(id)) throw new ChangesError("Nothing is running in that session.")
150
+ if (!host.cancel(id)) throw new ChangesError("That session isn't running here.")
151
+ return { stopped: true }
152
+ }
153
+
154
+ async function missions() {
155
+ const running = new Set()
156
+ for (const id of host.running()) {
157
+ const cwd = liveOf(id) && (await host.folderOf(id))
158
+ if (cwd) running.add(projectRoot(cwd))
159
+ }
160
+ let account = null
161
+ try {
162
+ const a = await host.account()
163
+ account = a?.harness ? { plan: a.plan ?? null, used: formatInr(a.harness.usedMicroInr), cap: formatInr(a.harness.capMicroInr), estimated: Boolean(a.harness.unpriced) } : null
164
+ } catch {
165
+ account = null
166
+ }
167
+ return {
168
+ signedIn: Boolean(readDevice()),
169
+ account,
170
+ missions: missionRows(ledgers(host.home).map((e) => ({ ...e, running: running.has(e.root) }))),
171
+ }
172
+ }
173
+
174
+ async function track(request) {
175
+ const params = new URL(request.url).searchParams
176
+ const id = sessionOf(params.get("session"))
177
+ const part = params.get("part")
178
+ const cwd = await folder(id)
179
+ const root = projectRoot(cwd)
180
+ const progress = progressOf(cwd, id)
181
+ if (part === "live") return { gates: liveGates(progress) }
182
+ if (part === "proof") {
183
+ const ready = readState(root).records.findLast((r) => r.kind === "ready")
184
+ let receipt = null
185
+ try {
186
+ const files = receiptOf(id, root)
187
+ receipt = { ...JSON.parse(readFileSync(files.json, "utf8")), markdown: readFileSync(files.md, "utf8") }
188
+ } catch {
189
+ receipt = null
190
+ }
191
+ return {
192
+ steps: stepChips(progress),
193
+ release: ready ? { commit: String(ready.commit).slice(0, 12), ready: Boolean(ready.ready), at: ready.at, lines: ready.lines ?? [] } : null,
194
+ receipt: receipt && { verdict: receipt.verdict, chain: receipt.chain, runs: receipt.runs, commit: receipt.commit ? String(receipt.commit).slice(0, 12) : null, markdown: receipt.markdown },
195
+ }
196
+ }
197
+ if (part === "changes") {
198
+ const tracked = (await trackedRoot(cwd))?.root
199
+ if (!tracked) return { points: [] }
200
+ const mine = (await listCheckpoints(tracked)).filter((c) => c.kind === "checkpoint" && c.session === id).reverse()
201
+ const runs = progress.runs ?? []
202
+ return {
203
+ points: mine.map((c, i) => {
204
+ const next = mine[i + 1]?.at
205
+ const run = runs.find((r) => r.at >= c.at && (!next || r.at < next))
206
+ return { commit: c.commit, at: c.at, label: c.label, verdict: run ? run.status : null }
207
+ }),
208
+ }
209
+ }
210
+ if (part === "project") {
211
+ const [repo, matrix, mcp] = await Promise.all([
212
+ (host.repoOf ?? ((dir) => createRepo({ root: dir })))(cwd)
213
+ .status()
214
+ .then((s) => ({ state: s.state, text: s.text }), (e) => ({ state: "unknown", text: String(e?.message ?? e).slice(0, 300) })),
215
+ (host.matrix ?? gateMatrix)(),
216
+ (host.mcp ?? (async () => []))().catch(() => []),
217
+ ])
218
+ return { repo, matrix, mcp }
219
+ }
220
+ throw new ChangesError("Which part?")
221
+ }
222
+
223
+ async function restore(request) {
224
+ const body = await json(request)
225
+ const id = sessionOf(body.session)
226
+ const cwd = await folder(id)
227
+ if (liveOf(id)) throw new ChangesError("Stop the running step before restoring a point.")
228
+ const tracked = (await trackedRoot(cwd))?.root
229
+ const point = tracked && (await listCheckpoints(tracked)).find((c) => c.kind === "checkpoint" && c.session === id && c.commit === body.commit)
230
+ if (!point) throw new ChangesError("That point isn't one of this session's checkpoints.")
231
+ const done = await restoreTree(cwd, point.tree, `before restoring ${point.label}`)
232
+ return { restored: point.label, changed: done?.changed ?? 0 }
233
+ }
234
+
235
+ async function verify(request) {
236
+ const id = sessionOf((await json(request)).session)
237
+ const cwd = await folder(id)
238
+ try {
239
+ return verifyReceipt(readFileSync(receiptOf(id, projectRoot(cwd)).json, "utf8"))
240
+ } catch {
241
+ return { ok: false, problems: ["This session has no receipt yet: ask for one, or run kriya receipt make."] }
242
+ }
243
+ }
244
+
245
+ return { strip, stop, missions, track, restore, verify }
246
+ }
247
+
248
+ // The receipt's project key: the root's hash, as src/receipts.js and src/verify.js name it
249
+ const projectKey = (root) => createHash("sha256").update(root).digest("hex").slice(0, 16)
250
+ const receiptOf = (id, root) => receiptFiles(projectKey(root), id)
251
+
252
+ const reply = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store" } })
253
+
254
+ export async function answer(route, request, log = () => {}) {
255
+ try {
256
+ return reply(await route(request))
257
+ } catch (error) {
258
+ if (error instanceof ChangesError) return reply({ error: error.message }, 400)
259
+ log(error)
260
+ return reply({ error: "Kriya couldn't read this; see the terminal for details." }, 500)
261
+ }
262
+ }
263
+
264
+ export function apply(ctx) {
265
+ const folderOf = async (id) => {
266
+ const live = ctx.sessions.get(id)?.header
267
+ const stored = live === undefined ? await ctx.get("sessionPersistence")?.stat(id) : undefined
268
+ return (live ?? stored?.header)?.cwd
269
+ }
270
+ const account = () => {
271
+ const device = readDevice()
272
+ return device ? me(device.url, device.token) : Promise.resolve(null)
273
+ }
274
+ const routes = handlers({
275
+ folderOf,
276
+ running: () => [...(ctx.agents.list?.() ?? [])].map((a) => String(a.id)),
277
+ // DSH's own stop: the turn ends, queued messages stay (the composer's stop button)
278
+ cancel: (id) => {
279
+ const agent = ctx.agents.get?.(id)
280
+ if (!agent) return false
281
+ agent.cancel({ kind: "user" }, { keepInbox: true })
282
+ return true
283
+ },
284
+ account,
285
+ mcp: async () => {
286
+ if (process.env.KRIYA_MCP !== "on") return []
287
+ const device = readDevice()
288
+ if (!device) return []
289
+ const servers = (await call(device.url, "GET", "/mcp", { token: device.token })).servers ?? []
290
+ return servers.map((s) => ({ id: String(s.id ?? ""), name: String(s.name ?? s.id ?? "").slice(0, 80) }))
291
+ },
292
+ })
293
+ const log = (error) => ctx.logger("kriya-runstrip").warn(error)
294
+ const register = (path, method, route) => ctx.effect(() => ctx.connection.fetch.register({ path, methods: [method], requestBody: "buffered", fetch: (request) => answer(route, request, log) }))
295
+ register(ROUTES.strip, "GET", routes.strip)
296
+ register(ROUTES.stop, "POST", routes.stop)
297
+ register(ROUTES.missions, "GET", routes.missions)
298
+ register(ROUTES.track, "GET", routes.track)
299
+ register(ROUTES.restore, "POST", routes.restore)
300
+ register(ROUTES.verify, "POST", routes.verify)
301
+ }
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "@kriya-ai/harness-runstrip",
3
+ "description": "The Run strip, gate chips, Mission Control and the four right-column tracks of the Kriya Harness Web UI (Harness 2.0 W18)",
4
+ "version": "0.1.0",
5
+ "private": true,
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "exports": {
9
+ ".": "./index.js",
10
+ "./client": "./client.js",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "dsh": {
14
+ "client": {
15
+ "inject": [
16
+ "@deepseek-ai/dsh-client-ui-layout",
17
+ "@deepseek-ai/dsh-client-ui-sidebar"
18
+ ],
19
+ "platform": "web"
20
+ }
21
+ },
22
+ "license": "UNLICENSED"
23
+ }
@@ -0,0 +1,133 @@
1
+ import { createHash } from "node:crypto"
2
+ import { readFileSync } from "node:fs"
3
+ import { join } from "node:path"
4
+
5
+ import { call, deviceFromEnv } from "./api.js"
6
+ import { rankSkills } from "./intent.js"
7
+ import { PACKAGE_ROOT } from "./paths.js"
8
+
9
+ // Harness 2.0 role cartridges (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
10
+ // CARTRIDGES.md, W1): one discipline's guidance per builder, mounted first in
11
+ // its prompt. Kriya serves them (GET /skills, items with a `cartridge` block,
12
+ // only with harness.workforce on); this module picks one for a plan step, by
13
+ // code, and fetches its text. Off unless kriya was started with --cartridges
14
+ // (KRIYA_CARTRIDGES=on): off, nothing here is called.
15
+
16
+ /** The role ids Kriya's contract allows (contract/contract.json, copied from Kriya). */
17
+ export const ROLES = (() => {
18
+ try {
19
+ return JSON.parse(readFileSync(join(PACKAGE_ROOT, "contract", "contract.json"), "utf8")).cartridgeIds?.roles ?? []
20
+ } catch {
21
+ return []
22
+ }
23
+ })()
24
+
25
+ /** A simple glob (`*`, `**`, literal names) as a regex over a forward-slash path. */
26
+ export function globRegex(glob) {
27
+ let out = ""
28
+ for (let i = 0; i < glob.length; i++) {
29
+ const c = glob[i]
30
+ if (c === "*" && glob[i + 1] === "*") {
31
+ // `**/` matches zero or more folders; a trailing `**` matches the rest
32
+ if (glob[i + 2] === "/") {
33
+ out += "(?:.*/)?"
34
+ i += 2
35
+ } else {
36
+ out += ".*"
37
+ i += 1
38
+ }
39
+ } else if (c === "*") out += "[^/]*"
40
+ else out += c.replace(/[.+?^${}()|[\]\\]/g, "\\$&")
41
+ }
42
+ return new RegExp(`^${out}$`)
43
+ }
44
+
45
+ /**
46
+ * The cartridge for one plan step, deterministic: the role the plan named (if
47
+ * Kriya serves it), else the role whose globs match most of the step's files
48
+ * (ties: more gates, then the name), else the best BM25 match of the step's
49
+ * title and done-when over the roles' descriptions; undefined when nothing fits.
50
+ * @param {{ title: string, doneWhen: string, files: string[], role?: string }} step
51
+ * @param {Array<{ id: string, description: string, cartridge: { role: string, gates: string[], globs: string[] } }>} cartridges
52
+ */
53
+ export function selectCartridge(step, cartridges) {
54
+ if (!cartridges.length) return undefined
55
+ if (step.role) {
56
+ const named = cartridges.find((c) => c.cartridge.role === step.role)
57
+ if (named) return named
58
+ }
59
+ const files = (step.files ?? []).map((f) => f.replace(/\\/g, "/").replace(/^\.\//, ""))
60
+ if (files.length) {
61
+ const scored = cartridges
62
+ .map((c) => {
63
+ const res = c.cartridge.globs.map(globRegex)
64
+ return { c, hits: files.filter((f) => res.some((re) => re.test(f))).length }
65
+ })
66
+ .filter((s) => s.hits > 0)
67
+ .sort((a, b) => b.hits - a.hits || b.c.cartridge.gates.length - a.c.cartridge.gates.length || a.c.id.localeCompare(b.c.id))
68
+ if (scored.length) return scored[0].c
69
+ }
70
+ const [best] = rankSkills(`${step.title} ${step.doneWhen}`, cartridges.map((c) => ({ name: c.id, description: c.description })))
71
+ return best ? cartridges.find((c) => c.id === best.name) : undefined
72
+ }
73
+
74
+ /** The first lines of a builder's prompt with a cartridge: stable text only, so the cached prefix holds across builders of one role. */
75
+ export function cartridgeSection(name, body) {
76
+ return [`Your role for this step: ${name}. Work as the best engineer in this discipline would, following this guidance.`, "", body.trim(), "", "---", ""]
77
+ }
78
+
79
+ /**
80
+ * KriyaBench's candidate arm (Kriya-Tavi upgrade_2.0/SELF_EVOLUTION.md §3,
81
+ * OR-20): with KRIYA_BENCH=on, which only the bench runner sets, the
82
+ * candidate file's body replaces one cartridge's text. Without it the file
83
+ * is never read. A file whose body doesn't match its sha256 is refused.
84
+ */
85
+ export function benchCandidate(env = process.env) {
86
+ if (env.KRIYA_BENCH !== "on" || !env.KRIYA_CARTRIDGE_FILE) return undefined
87
+ const file = JSON.parse(readFileSync(env.KRIYA_CARTRIDGE_FILE, "utf8"))
88
+ if (file?.kind !== "kriya-cartridge-candidate" || typeof file.body !== "string" || typeof file.cartridgeId !== "string")
89
+ throw new Error("KRIYA_CARTRIDGE_FILE isn't a cartridge candidate.")
90
+ if (createHash("sha256").update(file.body).digest("hex") !== file.sha256) throw new Error("The cartridge candidate doesn't match its sha256.")
91
+ return { cartridgeId: file.cartridgeId, body: file.body.slice(0, 6000) }
92
+ }
93
+
94
+ /**
95
+ * Kriya's served cartridges and their texts, fetched once per process
96
+ * (a session's builders share them). Signed out or unreachable: none, and
97
+ * builders get the prompt they get without cartridges.
98
+ */
99
+ export function cartridgeSource({ device = deviceFromEnv, request = call, env = process.env } = {}) {
100
+ let listed
101
+ const bodies = new Map()
102
+ const candidate = benchCandidate(env)
103
+ return {
104
+ async list() {
105
+ if (listed) return listed
106
+ const d = device()
107
+ if (!d) return []
108
+ try {
109
+ const { skills } = await request(d.url, "GET", "/skills", { token: d.token })
110
+ listed = (skills ?? []).filter((s) => s.cartridge && ROLES.includes(s.cartridge.role))
111
+ } catch {
112
+ return []
113
+ }
114
+ return listed
115
+ },
116
+ async body(c) {
117
+ if (candidate && c.id === candidate.cartridgeId) return candidate.body
118
+ const key = `${c.id}@${c.version}`
119
+ if (bodies.has(key)) return bodies.get(key)
120
+ const d = device()
121
+ if (!d) return undefined
122
+ try {
123
+ const response = await request(d.url, "GET", `/skills/${c.id}/${c.version}`, { token: d.token, raw: true })
124
+ if (!response.ok) return undefined
125
+ const text = (await response.text()).slice(0, 6000)
126
+ bodies.set(key, text)
127
+ return text
128
+ } catch {
129
+ return undefined
130
+ }
131
+ },
132
+ }
133
+ }
@@ -0,0 +1,130 @@
1
+ import { createHash } from "node:crypto"
2
+ import { existsSync, readFileSync } from "node:fs"
3
+ import { join } from "node:path"
4
+
5
+ import { Ajv2020 } from "ajv/dist/2020.js"
6
+
7
+ import { PACKAGE_ROOT } from "./paths.js"
8
+
9
+ // Harness 2.0 W3, the contract bus (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
10
+ // ORCHESTRA.md §5): typed files steps hand each other instead of chat, kept in
11
+ // the project under .kriya/contracts/ so the person can read and commit them.
12
+ // Code validates them, records each one's hash when the step whose role owns
13
+ // it passes, and fails any later step of another role that changes it
14
+ // (failure class "contract changed"). Builders get slices by JSON Pointer.
15
+
16
+ export const CONTRACTS_DIR = join(".kriya", "contracts")
17
+ export const CONTRACT_FILES = {
18
+ api: "api.openapi.json",
19
+ schema: "schema.sql",
20
+ auth_matrix: "auth_matrix.json",
21
+ design_tokens: "design_tokens.json",
22
+ component_states: "component_states.json",
23
+ threat_model: "threat_model.json",
24
+ // Harness 2.0 W13 (WD-17): the designer's art direction for 3D, read by G-3D
25
+ scene_direction: "scene_direction.json",
26
+ }
27
+ export const CONTRACT_NAMES = Object.keys(CONTRACT_FILES)
28
+
29
+ const ajv = new Ajv2020({ strict: false, allErrors: true, validateFormats: false })
30
+ const validators = new Map()
31
+ function validator(name) {
32
+ if (!validators.has(name)) {
33
+ const file = join(PACKAGE_ROOT, "contract", "schemas", `${name}.json`)
34
+ validators.set(name, existsSync(file) ? ajv.compile(JSON.parse(readFileSync(file, "utf8"))) : null)
35
+ }
36
+ return validators.get(name)
37
+ }
38
+
39
+ const path = (root, name) => join(root, CONTRACTS_DIR, CONTRACT_FILES[name])
40
+ const sha = (bytes) => createHash("sha256").update(bytes).digest("hex")
41
+
42
+ /** The contracts present in the project, with their bytes' sha256. */
43
+ export function presentContracts(root) {
44
+ const out = {}
45
+ for (const name of CONTRACT_NAMES) {
46
+ const file = path(root, name)
47
+ if (existsSync(file)) out[name] = sha(readFileSync(file))
48
+ }
49
+ return out
50
+ }
51
+
52
+ /** Problems with one present contract: parse, schema, references; [] when sound. */
53
+ export function contractProblems(root, name, { gates = [], exists = (rel) => existsSync(join(root, rel)) } = {}) {
54
+ const file = path(root, name)
55
+ if (!existsSync(file)) return []
56
+ const text = readFileSync(file, "utf8")
57
+ if (name === "schema") return text.trim() ? [] : ["schema.sql is empty"]
58
+ let value
59
+ try {
60
+ value = JSON.parse(text)
61
+ } catch (error) {
62
+ return [`${CONTRACT_FILES[name]} isn't valid JSON (${String(error.message).slice(0, 120)})`]
63
+ }
64
+ const validate = validator(name)
65
+ if (validate && !validate(value)) return validate.errors.slice(0, 8).map((e) => `${CONTRACT_FILES[name]}${e.instancePath || ""} ${e.message}`)
66
+ const problems = []
67
+ if (name === "api") {
68
+ for (const ref of JSON.stringify(value).match(/"\$ref":"[^"]*"/g) ?? []) {
69
+ const pointer = ref.slice(8, -1)
70
+ if (!pointer.startsWith("#/") || resolvePointer(value, pointer.slice(1)) === undefined) problems.push(`${CONTRACT_FILES[name]}: ${pointer} doesn't resolve`)
71
+ }
72
+ }
73
+ if (name === "threat_model")
74
+ for (const [i, row] of value.entries()) if (!gates.includes(row.test) && !exists(row.test)) problems.push(`${CONTRACT_FILES[name]}/${i}/test: "${row.test}" is neither a gate id nor a file in the project`)
75
+ return problems
76
+ }
77
+
78
+ /** RFC 6901 JSON Pointer ("" is the whole document). */
79
+ export function resolvePointer(value, pointer) {
80
+ if (pointer === "") return value
81
+ if (!pointer.startsWith("/")) return undefined
82
+ let node = value
83
+ for (const part of pointer.slice(1).split("/").map((p) => p.replace(/~1/g, "/").replace(/~0/g, "~"))) {
84
+ if (node === null || typeof node !== "object" || !Object.hasOwn(node, part)) return undefined
85
+ node = node[part]
86
+ }
87
+ return node
88
+ }
89
+
90
+ /**
91
+ * Contracts this role doesn't own that changed since their owner's step passed.
92
+ * @param {Record<string, { sha: string }>} recorded the ledger's hashes
93
+ */
94
+ export function drifted(root, recorded = {}, owns = []) {
95
+ const now = presentContracts(root)
96
+ return Object.entries(recorded)
97
+ .filter(([name, r]) => !owns.includes(name) && now[name] !== r.sha)
98
+ .map(([name]) => ({ name, file: join(CONTRACTS_DIR, CONTRACT_FILES[name]), removed: now[name] === undefined }))
99
+ }
100
+
101
+ /** The contracts a passing step of this role owns, hashed for the ledger. */
102
+ export function ownedHashes(root, owns = [], step) {
103
+ const now = presentContracts(root)
104
+ return Object.fromEntries(owns.filter((name) => now[name]).map((name) => [name, { sha: now[name], step }]))
105
+ }
106
+
107
+ export const SLICE_CHARS = 6000
108
+
109
+ /** Text for a builder: the named contract slices ("api#/paths/~1orders", "design_tokens"), deterministic and bounded. */
110
+ export function contractSlices(root, refs = []) {
111
+ const parts = []
112
+ for (const ref of refs) {
113
+ const [name, pointer = ""] = String(ref).split("#")
114
+ if (!CONTRACT_NAMES.includes(name) || !existsSync(path(root, name))) continue
115
+ const text = readFileSync(path(root, name), "utf8")
116
+ let body = text
117
+ if (name !== "schema" && pointer) {
118
+ try {
119
+ const found = resolvePointer(JSON.parse(text), pointer)
120
+ if (found === undefined) continue
121
+ body = JSON.stringify(found, null, 2)
122
+ } catch {
123
+ continue
124
+ }
125
+ }
126
+ parts.push(`${CONTRACT_FILES[name]}${pointer ? `#${pointer}` : ""}:\n\`\`\`\n${body.trim()}\n\`\`\``)
127
+ }
128
+ const out = parts.join("\n\n")
129
+ return out.length <= SLICE_CHARS ? out : `${out.slice(0, SLICE_CHARS)}\n… (cut at ${SLICE_CHARS} characters; read the file for the rest)`
130
+ }
package/src/critic.js ADDED
@@ -0,0 +1,78 @@
1
+ import { Ajv2020 } from "ajv/dist/2020.js"
2
+
3
+ // Harness 2.0 W6, the critic (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
4
+ // ARCHITECTURE.md §4, WD-13). After a step passes every hard gate, a fresh,
5
+ // read-only child on the head level judges the work against the role's
6
+ // judgement items (taste code can't measure). It answers with JSON defects
7
+ // only. It never decides pass, fail or done: a major defect earns one polish
8
+ // attempt, which the loop keeps only if every check and gate still passes.
9
+
10
+ export const MAX_DEFECTS = 12
11
+ export const CRITIC_MS = 90_000
12
+
13
+ const SCHEMA = {
14
+ type: "object",
15
+ required: ["defects"],
16
+ additionalProperties: false,
17
+ properties: {
18
+ defects: {
19
+ type: "array",
20
+ maxItems: MAX_DEFECTS,
21
+ items: {
22
+ type: "object",
23
+ required: ["severity", "where", "fix"],
24
+ additionalProperties: false,
25
+ properties: {
26
+ id: { type: "string", maxLength: 60 },
27
+ severity: { enum: ["major", "minor"] },
28
+ where: { type: "string", minLength: 1, maxLength: 200 },
29
+ fix: { type: "string", minLength: 1, maxLength: 300 },
30
+ },
31
+ },
32
+ },
33
+ },
34
+ }
35
+ const validate = new Ajv2020({ strict: false, allErrors: false }).compile(SCHEMA)
36
+
37
+ /** What the critic is told: the role's judgement items, the step, what changed and what the gates noted. */
38
+ export function critiquePrompt({ role, judgement = [], plan, n, changed = [], notes = [] }) {
39
+ const step = plan?.steps?.[n - 1]
40
+ return [
41
+ `You are reviewing one finished step as the best ${role ?? "engineer"} you know would. You can read files; you change nothing and run nothing.`,
42
+ "Every automatic check already passed. Judge only what they can't: the standards below.",
43
+ "",
44
+ ...(plan ? [`Goal of the task: ${plan.goal}`] : []),
45
+ ...(step ? [`The step: ${n}. ${step.title}`, `It is done when: ${step.doneWhen}`] : []),
46
+ ...(changed.length ? ["", `Files the work changed: ${changed.slice(0, 40).join(", ")}`] : []),
47
+ ...(notes.length ? ["", "What the checks noted (warnings, not failures):", ...notes.slice(0, 12).map((x) => `- ${x}`)] : []),
48
+ "",
49
+ "Standards for this role:",
50
+ ...(judgement.length ? judgement.map((j) => `- ${j.id ? `${j.id}: ` : ""}${j.ask} (${j.severity})`) : ["- The result is what a person asking for it would be proud to ship."]),
51
+ "",
52
+ `Answer with JSON only, no other text: {"defects":[{"id":"<standard id>","severity":"major"|"minor","where":"<file:line or screen>","fix":"<one sentence>"}]}, at most ${MAX_DEFECTS}. Use major only for what a principal would block the step for. No defects: {"defects":[]}.`,
53
+ ].join("\n")
54
+ }
55
+
56
+ /** The critic's defects from its answer; anything that isn't exactly the schema counts as none. */
57
+ export function parseDefects(text) {
58
+ const s = String(text ?? "")
59
+ const start = s.indexOf("{")
60
+ const end = s.lastIndexOf("}")
61
+ if (start === -1 || end <= start) return []
62
+ try {
63
+ const value = JSON.parse(s.slice(start, end + 1))
64
+ return validate(value) ? value.defects : []
65
+ } catch {
66
+ return []
67
+ }
68
+ }
69
+
70
+ /** The lines a polish builder gets about the defects. */
71
+ export function polishSection(defects) {
72
+ return [
73
+ "",
74
+ "This step already passes every check. A reviewer judged it against this role's standards and found these major defects:",
75
+ ...defects.map((d) => `- ${d.where}: ${d.fix}${d.id ? ` (${d.id})` : ""}`),
76
+ "Fix them without changing behaviour the checks cover. The harness keeps your change only if every check and gate still passes; otherwise it puts the files back as they were.",
77
+ ]
78
+ }