@kriya-ai/harness 0.2.5 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/RELEASE_NOTES.md +121 -0
  2. package/SAFETY.md +181 -0
  3. package/THIRD_PARTY_NOTICES.md +113 -0
  4. package/bin/kriya.js +188 -2
  5. package/bundle/cordis.patch.yml +60 -5
  6. package/contract/SOURCE.md +3 -3
  7. package/contract/contract.json +498 -3
  8. package/contract/schemas/api.json +64 -0
  9. package/contract/schemas/auth_matrix.json +44 -0
  10. package/contract/schemas/component_states.json +33 -0
  11. package/contract/schemas/design_tokens.json +34 -0
  12. package/contract/schemas/scene_direction.json +82 -0
  13. package/contract/schemas/threat_model.json +44 -0
  14. package/package.json +2 -1
  15. package/plugins/changes/client.js +5 -3
  16. package/plugins/deploy/index.js +215 -0
  17. package/plugins/deploy/package.json +13 -0
  18. package/plugins/grounding/index.js +81 -0
  19. package/plugins/grounding/lookup.js +373 -0
  20. package/plugins/grounding/package.json +13 -0
  21. package/plugins/kriya-tools/index.js +2 -1
  22. package/plugins/loop/index.js +381 -10
  23. package/plugins/mcp/index.js +79 -0
  24. package/plugins/mcp/package.json +13 -0
  25. package/plugins/mirror/index.js +17 -0
  26. package/plugins/overview/client.js +5 -2
  27. package/plugins/preview/client.js +12 -6
  28. package/plugins/progress/client.js +7 -4
  29. package/plugins/repo/index.js +230 -0
  30. package/plugins/repo/package.json +13 -0
  31. package/plugins/repo/repo.js +348 -0
  32. package/plugins/runstrip/client.js +436 -0
  33. package/plugins/runstrip/index.js +312 -0
  34. package/plugins/runstrip/package.json +23 -0
  35. package/src/cartridges.js +133 -0
  36. package/src/contracts.js +130 -0
  37. package/src/critic.js +78 -0
  38. package/src/daemon.js +7 -1
  39. package/src/doctor.js +67 -0
  40. package/src/edit/core/effects.js +185 -0
  41. package/src/edit/core/ffmpeg.js +65 -6
  42. package/src/edit/core/layout.js +46 -1
  43. package/src/edit/core/ops.js +169 -2
  44. package/src/edit/core/plan.js +65 -9
  45. package/src/edit/core/project.d.ts +24 -0
  46. package/src/edit/core/project.js +64 -0
  47. package/src/edit/core/solver.js +34 -6
  48. package/src/edit/core/style-brief.js +211 -0
  49. package/src/edit/core/style-packs.js +57 -0
  50. package/src/edit/core/type-kit.js +173 -0
  51. package/src/edit/director/ask.js +37 -3
  52. package/src/edit/director/assembly.js +829 -0
  53. package/src/edit/director/continuity.js +9 -1
  54. package/src/edit/director/custom-motion.js +88 -0
  55. package/src/edit/director/graphics.js +44 -10
  56. package/src/edit/director/intent.js +125 -0
  57. package/src/edit/director/mentions.js +52 -0
  58. package/src/edit/director/plan.js +43 -11
  59. package/src/edit/director/revise.js +132 -9
  60. package/src/edit/director/viewer.js +136 -0
  61. package/src/edit/director/watch-fix.js +119 -0
  62. package/src/edit/engine/captions.js +110 -5
  63. package/src/edit/engine/confine.js +81 -4
  64. package/src/edit/engine/custom.js +243 -0
  65. package/src/edit/engine/dna2.js +893 -0
  66. package/src/edit/engine/fonts.js +218 -0
  67. package/src/edit/engine/graphics.js +271 -10
  68. package/src/edit/engine/index.js +14 -5
  69. package/src/edit/engine/motion.js +148 -13
  70. package/src/edit/engine/music-bed.js +59 -1
  71. package/src/edit/engine/packs.js +11 -0
  72. package/src/edit/engine/reference2.js +26 -0
  73. package/src/edit/engine/sfx.js +56 -1
  74. package/src/edit/engine/tool.js +21 -5
  75. package/src/edit/gates/assembly.js +194 -0
  76. package/src/edit/gates/copy.js +7 -4
  77. package/src/edit/gates/index.js +72 -7
  78. package/src/edit/gates/reference.js +115 -0
  79. package/src/edit/gates/tile.js +96 -0
  80. package/src/edit/host/client.js +8 -3
  81. package/src/edit/host/clips.js +33 -0
  82. package/src/edit/host/jobs.js +9 -3
  83. package/src/edit/host/layers.js +134 -0
  84. package/src/edit/host/main.js +10 -3
  85. package/src/edit/host/paths.js +21 -3
  86. package/src/edit/host/preview.js +108 -0
  87. package/src/edit/host/projects.js +443 -34
  88. package/src/edit/host/server.js +235 -20
  89. package/src/edit/host/tavi.js +77 -0
  90. package/src/edit/index/index.js +3 -2
  91. package/src/edit/loop/make.js +28 -3
  92. package/src/edit/recipes/assembly.js +352 -0
  93. package/src/edit/recipes/graphic-clips.js +4 -2
  94. package/src/edit/recipes/openings.js +36 -0
  95. package/src/edit/recipes/reel.js +104 -14
  96. package/src/edit/recipes/reference-look.js +29 -0
  97. package/src/edit/recipes/short-from-long.js +3 -3
  98. package/src/edit/recipes/sound.js +71 -0
  99. package/src/edit/runtime/cli.js +26 -5
  100. package/src/edit/runtime/fetch.js +4 -4
  101. package/src/edit/runtime/licences.js +7 -1
  102. package/src/explore.js +103 -0
  103. package/src/failure.js +1 -1
  104. package/src/gate-commands.js +114 -0
  105. package/src/gates/api.js +127 -0
  106. package/src/gates/commands.js +111 -0
  107. package/src/gates/detectors.js +370 -0
  108. package/src/gates/http.js +62 -0
  109. package/src/gates/index.js +196 -0
  110. package/src/gates/page.js +264 -0
  111. package/src/gates/sast.js +64 -0
  112. package/src/gates/stack.js +110 -0
  113. package/src/gates/tenant.js +162 -0
  114. package/src/gates/three.js +431 -0
  115. package/src/gates/ui.js +111 -0
  116. package/src/gateway-proxy.js +20 -2
  117. package/src/launch.js +39 -5
  118. package/src/loop.js +199 -7
  119. package/src/mcp.js +126 -0
  120. package/src/milestones.js +188 -0
  121. package/src/modes.js +67 -0
  122. package/src/orchestra.js +50 -0
  123. package/src/outcomes.js +88 -0
  124. package/src/profiles.js +5 -0
  125. package/src/receipts.js +238 -0
  126. package/src/release.js +356 -0
  127. package/src/runstrip.js +122 -0
  128. package/src/stack.js +120 -0
  129. package/src/verify.js +67 -20
  130. package/studio/dist/fonts/fraunces.woff2 +0 -0
  131. package/studio/dist/fonts/geist.woff2 +0 -0
  132. package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
  133. package/studio/dist/studio.css +449 -1
  134. package/studio/dist/studio.js +3 -3
@@ -0,0 +1,29 @@
1
+ // A reference's look on a cut (TP6, CRAFT_UPGRADE §4.2), only when the make's own brief carries it:
2
+ // grain, darker corners and bars as adjustments over the whole film, each a row of the effects
3
+ // registry (TP5). Each hangs on the cut's first clip, so the next make finds it and takes it out
4
+ // with that clip (audit §6 rule 6). One that doesn't fit (restraint, a missing filter, the effects
5
+ // switch off) is left out with a note and never fails the make (rule 7).
6
+
7
+ import { EFFECTS } from "../core/effects.js"
8
+ import { apply } from "../core/ops.js"
9
+ import { solve } from "../core/solver.js"
10
+
11
+ /**
12
+ * @param {{ project: object, all: object[], step: { project: object }, fx: { effect: string, params?: object }[], index: object, notes: string[] }} input `all` gains the operations that were taken
13
+ * @returns {{ project: object, applied: true }} the step to go on from
14
+ */
15
+ export function referenceLook({ project, all, step, fx, index, notes }) {
16
+ const timeline = solve(step.project, index)
17
+ const first = timeline.picture.find((p) => !p.hold)
18
+ if (!first) return step
19
+ for (const { effect, params } of fx) {
20
+ if (!Object.hasOwn(EFFECTS, effect)) continue
21
+ const op = { op: "add_adjustment", at: { clip: first.clip, edge: "start" }, duration: timeline.duration, effect, ...(params ? { params } : {}) }
22
+ const tried = apply(project, [...all, op], { index, author: "agent" })
23
+ if (tried.applied) {
24
+ all.push(op)
25
+ step = tried
26
+ } else notes.push(`The reference's ${EFFECTS[effect].label.toLowerCase()} was left out: ${tried.diagnostics[0]?.message ?? "it doesn't fit this cut"}.`)
27
+ }
28
+ return step
29
+ }
@@ -7,7 +7,7 @@
7
7
 
8
8
  import { apply } from "../core/ops.js"
9
9
  import { compile } from "../core/plan.js"
10
- import { LOOKS, pages } from "../engine/captions.js"
10
+ import { ALL_LOOKS, pageLimits, pages } from "../engine/captions.js"
11
11
  import { candidateLines, fitLines, runsOf } from "./reel.js"
12
12
 
13
13
  const FLICKS = 705_600_000
@@ -29,7 +29,7 @@ export const SHORT_FROM_LONG = {
29
29
  /** With captions asked for, they burn in and the text gates run, as for the reel (ED8). */
30
30
  export function deliverableFor(brief = {}) {
31
31
  const base = SHORT_FROM_LONG.deliverable
32
- return LOOKS[brief.captions] ? { ...base, burnCaptions: true, gates: [...base.gates, "QG-08", "QG-09", "QG-10"].sort() } : base
32
+ return ALL_LOOKS[brief.captions] ? { ...base, burnCaptions: true, gates: [...base.gates, "QG-08", "QG-09", "QG-10"].sort() } : base
33
33
  }
34
34
 
35
35
  // Openers that lean on something said before: a short that starts here starts mid-thought
@@ -229,7 +229,7 @@ export function planShort({ project, index, asset, brief = {}, variant = {} }) {
229
229
  if (!subject) notes.push("No face track for this recording, so the frame holds the centre.")
230
230
  const clips = step.project.sequences.find((q) => q.id === step.project.active).clips.filter((c) => base.has(c.track))
231
231
  const framing = clips.map((c) => (subject ? { op: "reframe", clip: c.id, mode: "subject" } : { op: "reframe", clip: c.id, mode: "fixed", x: Math.max(0, Math.round((facts.width - cropWidth) / 2)) }))
232
- const captions = LOOKS[brief.captions] ? best.lines.flatMap((l) => runsOf(l, recipe.joinGap)).flatMap((run) => pages(run)).map((ids) => ({ op: "caption_style", look: brief.captions, words: ids })) : []
232
+ const captions = ALL_LOOKS[brief.captions] ? best.lines.flatMap((l) => runsOf(l, recipe.joinGap)).flatMap((run) => pages(run, pageLimits(brief.captions))).map((ids) => ({ op: "caption_style", look: brief.captions, words: ids })) : []
233
233
  const all = [...ops, ...framing, ...captions]
234
234
  const done = apply(project, all, { index, author: "agent" })
235
235
  if (!done.applied) throw new Error(`The short was refused: ${done.diagnostics[0].message}`)
@@ -0,0 +1,71 @@
1
+ // The make's sound, arranged to the cut (TP10, CRAFT_UPGRADE §8, EDD-69), behind editing.craft and only
2
+ // when the make's own brief asks (audit rule 4). Every sound is still one Kriya wrote. Code knows where
3
+ // every join is, so an accent in the bed's key lands on each; a quiet bed comes from the take's own
4
+ // silence; J and L cuts let a voice lead or trail its picture only through silence, never into a word;
5
+ // and B-roll lands on the music's beat, which moves no word, since the picture under it doesn't move.
6
+
7
+ const FLICKS = 705_600_000
8
+ export const SPLIT_MAX = Math.round(0.15 * FLICKS) // how far a J or L cut leads or trails
9
+ const MARGIN = Math.round(0.04 * FLICKS) // kept clear of a word on either side
10
+ const QUIET_MIN = Math.round(1.2 * FLICKS) // the shortest gap between words that can be a room tone
11
+ const BEAT_REACH = Math.round(0.25 * FLICKS) // how far a B-roll may move to meet a beat, later only
12
+
13
+ /** The take's quietest stretch: its longest gap between words, less a margin at each end; null if none is long enough. */
14
+ export function quietStretch(words, asset, length) {
15
+ const own = words.filter((w) => w.asset === asset).sort((a, b) => a.start - b.start)
16
+ const gaps = []
17
+ let from = 0
18
+ for (const w of own) {
19
+ gaps.push({ from, to: w.start })
20
+ from = Math.max(from, w.end)
21
+ }
22
+ if (length !== undefined) gaps.push({ from, to: length })
23
+ const best = gaps.filter((g) => g.to - g.from >= QUIET_MIN).sort((a, b) => b.to - b.from - (a.to - a.from) || a.from - b.from)[0]
24
+ return best ? { from: best.from + Math.round(0.2 * FLICKS), to: best.to - Math.round(0.2 * FLICKS) } : null
25
+ }
26
+
27
+ /**
28
+ * J and L cuts at the story's joins: the incoming clip's voice leads its picture (J) where the take is silent
29
+ * before its first word, else the outgoing one trails (L) where it is silent after its last. Never more than
30
+ * the silence less a margin, never more than SPLIT_MAX, so the extra sound is room, not speech.
31
+ * @param {{ clip: string, asset: string, in: number, out: number }[]} played the story's clips as they play, in order
32
+ */
33
+ export function splitOps(played, words) {
34
+ const ops = []
35
+ const sorted = [...words].sort((a, b) => a.start - b.start)
36
+ for (let i = 1; i < played.length; i++) {
37
+ const [a, b] = [played[i - 1], played[i]]
38
+ // J: the incoming voice starts this much before its picture, through the silence before b's cut point
39
+ const before = sorted.filter((w) => w.asset === b.asset && w.end <= b.in).at(-1)
40
+ const lead = Math.min(SPLIT_MAX, b.in - (before?.end ?? 0) - MARGIN)
41
+ if (lead >= MARGIN) {
42
+ ops.push({ op: "trim", clip: b.clip, audioLead: Math.round(lead) })
43
+ continue
44
+ }
45
+ // L: the outgoing voice trails its picture, through the silence after a's cut point
46
+ const after = sorted.find((w) => w.asset === a.asset && w.start >= a.out)
47
+ const lag = after ? Math.min(SPLIT_MAX, after.start - a.out - MARGIN) : 0
48
+ if (lag >= MARGIN) ops.push({ op: "trim", clip: a.clip, audioLag: Math.round(lag) })
49
+ }
50
+ return ops
51
+ }
52
+
53
+ /** The music's beats where they play on the timeline, through a fitted bed's pieces and their crossfades. */
54
+ export function timelineBeats(item, beats) {
55
+ if (!item) return []
56
+ const own = beats.filter((b) => b.asset === item.asset).map((b) => b.t)
57
+ const pieces = item.fit?.segments?.length ? item.fit.segments : [{ in: item.in, out: item.out }]
58
+ const out = []
59
+ let start = item.at
60
+ for (const [i, piece] of pieces.entries()) {
61
+ for (const t of own) if (t >= piece.in && t < piece.out) out.push(start + (t - piece.in))
62
+ start += piece.out - piece.in - (i < pieces.length - 1 ? (item.fit?.crossfade ?? 0) : 0)
63
+ }
64
+ return out.filter((t) => t >= item.at && t < item.end).sort((x, y) => x - y)
65
+ }
66
+
67
+ /** A B-roll start moved later onto the nearest beat within reach, inside its host clip; unchanged otherwise. */
68
+ export function onBeat(start, hostEnd, length, beats) {
69
+ const beat = beats.find((t) => t >= start && t - start <= BEAT_REACH)
70
+ return beat !== undefined && beat + length <= hostEnd ? beat : start
71
+ }
@@ -1,5 +1,7 @@
1
1
  // `kriya edit setup` and `kriya edit doctor`, loaded only with the switch on.
2
2
 
3
+ import { spawn } from "node:child_process"
4
+
3
5
  import { KriyaError } from "../../api.js"
4
6
  import { kriyaHome } from "../../paths.js"
5
7
  import { readDevice } from "../../store.js"
@@ -9,7 +11,7 @@ import { RuntimeError } from "./manifest.js"
9
11
  import { install, installPack, removePack, rollback } from "./setup.js"
10
12
 
11
13
  const USAGE = `Usage:
12
- kriya edit start the Edit Host and print the Studio's link
14
+ kriya edit [--no-open] open the Editing Studio in your browser (--no-open: only print its link)
13
15
  kriya edit setup [--rollback] install the Media Runtime, or go back to the last one
14
16
  kriya edit setup --pack <name> add a capability pack (color, voice-clean, depth)
15
17
  kriya edit setup --remove-pack <name>
@@ -22,12 +24,31 @@ const USAGE = `Usage:
22
24
  with no folder, list them. Nothing runs until you tap the card
23
25
  kriya edit unwatch <folder> stop`
24
26
 
25
- export async function editCommand([action, ...rest], { say = (line) => process.stdout.write(`${line}\n`) } = {}) {
27
+ /** The Studio's one-time link in the person's own browser, as `kriya login` opens its page. No browser: the printed link is enough. */
28
+ export function openInBrowser(url, { platform = process.platform, run = spawn } = {}) {
29
+ const [command, args] = platform === "darwin" ? ["open", [url]] : platform === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]]
26
30
  try {
27
- if (action === undefined) {
28
- const { ensureHost, hostCall } = await import("../host/client.js")
31
+ run(command, args, { stdio: "ignore", detached: true }).on("error", () => {}).unref()
32
+ return true
33
+ } catch {
34
+ return false
35
+ }
36
+ }
37
+
38
+ export async function editCommand([action, ...rest], { say = (line) => process.stdout.write(`${line}\n`), open = openInBrowser, interactive = process.stdout.isTTY === true, host = () => import("../host/client.js") } = {}) {
39
+ try {
40
+ // Typed in a terminal, `kriya edit` opens the Studio itself, never the harness's Web UI. Piped (a script)
41
+ // or with --no-open, it prints only the link, as it always did
42
+ if (action === undefined || (action === "--no-open" && rest.length === 0)) {
43
+ const { ensureHost, hostCall } = await host()
29
44
  await ensureHost()
30
- say((await hostCall(kriyaHome(), "POST", "/internal/launch")).url)
45
+ const { url } = await hostCall(kriyaHome(), "POST", "/internal/launch")
46
+ if (action === "--no-open" || !interactive) {
47
+ say(url)
48
+ return 0
49
+ }
50
+ say(`Opening the Kriya Editing Studio in your browser. If it didn't open, this link works once, for a short while:\n${url}`)
51
+ open(url)
31
52
  return 0
32
53
  }
33
54
  if ((action === "watch" && rest.length <= 1) || (action === "unwatch" && rest.length === 1)) {
@@ -7,15 +7,15 @@ import { openManifest, RuntimeError, TRUSTED_KEYS } from "./manifest.js"
7
7
  /**
8
8
  * What this Kriya has switched on for editing (EH-01). Any failure, a server with no such
9
9
  * route among them, means off: the server ships first, and a client never assumes (track E rule 17).
10
- * @returns {Promise<{ visuals: boolean, playbooks: boolean, mediaSearch: boolean, motion: boolean, customMotion: boolean }>}
10
+ * @returns {Promise<{ visuals: boolean, playbooks: boolean, mediaSearch: boolean, motion: boolean, customMotion: boolean, assembly: boolean }>}
11
11
  */
12
12
  export async function fetchFeatures(device) {
13
13
  try {
14
14
  const found = await call(device.url, "GET", "/editing/features", { token: device.token })
15
- // motion, customMotion: a server from before them says nothing, which is off
16
- return { visuals: found?.visuals === true, playbooks: found?.playbooks === true, mediaSearch: found?.mediaSearch === true, motion: found?.motion === true, customMotion: found?.customMotion === true }
15
+ // motion, customMotion, assembly, livePreview, intent, craft, typeKit, referenceIntent, directorLoop, taviOrder: a server from before them says nothing, which is off
16
+ return { visuals: found?.visuals === true, playbooks: found?.playbooks === true, mediaSearch: found?.mediaSearch === true, motion: found?.motion === true, customMotion: found?.customMotion === true, assembly: found?.assembly === true, livePreview: found?.livePreview === true, intent: found?.intent === true, craft: found?.craft === true, typeKit: found?.typeKit === true, referenceIntent: found?.referenceIntent === true, directorLoop: found?.directorLoop === true, taviOrder: found?.taviOrder === true }
17
17
  } catch {
18
- return { visuals: false, playbooks: false, mediaSearch: false, motion: false, customMotion: false }
18
+ return { visuals: false, playbooks: false, mediaSearch: false, motion: false, customMotion: false, assembly: false, livePreview: false, intent: false, craft: false, typeKit: false, referenceIntent: false, directorLoop: false, taviOrder: false }
19
19
  }
20
20
  }
21
21
 
@@ -65,7 +65,13 @@ export function manifestLicenceProblems(data) {
65
65
  for (const [platform, spec] of Object.entries(data?.platforms ?? {})) {
66
66
  for (const artifact of spec.artifacts ?? []) check(`${platform}/${artifact.id}`, artifact.licence, "runtime")
67
67
  for (const pkg of spec.python?.packages ?? []) check(`${platform}/python/${pkg.name}`, pkg.licence, "runtime")
68
- for (const [pack, offered] of Object.entries(spec.packs ?? {})) for (const artifact of offered.artifacts ?? []) check(`${platform}/${pack}/${artifact.id}`, artifact.licence, "weight")
68
+ for (const [pack, offered] of Object.entries(spec.packs ?? {})) {
69
+ for (const artifact of offered.artifacts ?? []) {
70
+ check(`${platform}/${pack}/${artifact.id}`, artifact.licence, "weight")
71
+ // The table allows OFL-1.1 for fonts only (TP7): anywhere but the font pack it isn't a font
72
+ if (pack !== "pack-fonts" && /\bOFL-/.test(artifact.licence ?? "")) problems.push({ item: `${platform}/${pack}/${artifact.id}`, problem: "OFL-1.1 is allowed for fonts only, and this isn't the font pack" })
73
+ }
74
+ }
69
75
  }
70
76
  return problems
71
77
  }
package/src/explore.js ADDED
@@ -0,0 +1,103 @@
1
+ import { createHash } from "node:crypto"
2
+ import { readFileSync } from "node:fs"
3
+ import { join } from "node:path"
4
+
5
+ import { CONTRACTS_DIR } from "./contracts.js"
6
+
7
+ // Harness 2.0 W14 (WD-18): Explore (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
8
+ // THREE_D_AND_CREATIVE.md §5). A creative step marked `explore: 2 | 3` builds
9
+ // that many takes one after another in the same folder (a builder can't get
10
+ // its own directory), each from the step's starting files and each in a
11
+ // different direction chosen here, by code, so diversity isn't left to
12
+ // sampling. Only gates decide pass; the person (or, with no UI, the critic)
13
+ // picks among passing takes. Pure helpers; src/loop.js runs the takes.
14
+
15
+ export const EXPLORE_ROLES = Object.freeze(["frontend", "designer", "graphics"])
16
+ export const MIN_TAKES = 2
17
+ export const MAX_TAKES = 3
18
+ export const RELOAD_MS = 20_000
19
+
20
+ /** THREE_D_AND_CREATIVE §3's lighting recipes, in table order (graphics). */
21
+ export const SCENE_DIRECTIONS = Object.freeze([
22
+ ["studio-product", "Studio product: an HDR studio environment with a soft key and a rim light, a contact shadow, filmic tone mapping (AgX or ACES)."],
23
+ ["daylight-exterior", "Daylight exterior: a sky environment and one directional sun with a single shadow, filmic tone mapping."],
24
+ ["night-neon", "Night and neon: a dark environment, emissive materials, restrained bloom, neutral tone mapping."],
25
+ ["soft-clay", "Soft clay, illustrative: an ambient environment and one soft key, no hard shadows, neutral tone mapping."],
26
+ ["data-abstract", "Data and abstract: unlit or minimal light, instanced points and lines, no or neutral tone mapping."],
27
+ ])
28
+ /** Visual directions for interface steps (frontend, designer), in table order. */
29
+ export const UI_DIRECTIONS = Object.freeze([
30
+ ["editorial", "Editorial: generous whitespace, one strong typeface in two weights, restrained colour, content first."],
31
+ ["precise", "Dense and precise: compact spacing on a strict grid, tabular figures, quiet colour, information first."],
32
+ ["warm", "Warm and soft: rounded shapes, gentle tinted surfaces, friendly copy, generous touch targets."],
33
+ ["bold", "Bold: high contrast, large display type, one confident accent colour, strong hierarchy."],
34
+ ])
35
+
36
+ const readJson = (root, file) => {
37
+ try {
38
+ return JSON.parse(readFileSync(join(root, CONTRACTS_DIR, file), "utf8"))
39
+ } catch {
40
+ return undefined
41
+ }
42
+ }
43
+
44
+ /**
45
+ * The takes' direction hints, by code: the first is the contract's own
46
+ * direction (scene_direction.json `lighting` for graphics, design_tokens.json
47
+ * `direction` for interface steps), the others its two neighbours in the table.
48
+ * @returns {Array<{ id: string, text: string }>}
49
+ */
50
+ export function directionHints(role, takes, root) {
51
+ const table = role === "graphics" ? SCENE_DIRECTIONS : UI_DIRECTIONS
52
+ const named = role === "graphics" ? readJson(root, "scene_direction.json")?.lighting : readJson(root, "design_tokens.json")?.direction
53
+ const at = Math.max(0, table.findIndex(([id]) => id === named))
54
+ const order = [at, (at + 1) % table.length, (at - 1 + table.length) % table.length]
55
+ return order.slice(0, takes).map((i) => ({ id: table[i][0], text: table[i][1] }))
56
+ }
57
+
58
+ /** The section a take's builder gets after its normal prompt. */
59
+ export const takeSection = (take, of, hint) =>
60
+ [
61
+ `## This is take ${take} of ${of}`,
62
+ "",
63
+ `The person will compare ${of} takes of this step side by side and keep one. Build the whole step, fully working, in this direction:`,
64
+ "",
65
+ hint.text,
66
+ "",
67
+ "Commit to it: a half-way take loses the comparison. The checks still decide pass or fail; the direction never excuses a failing check.",
68
+ ].join("\n")
69
+
70
+ /** What a served route looks like now: its ETag or Last-Modified, else a hash of its body. */
71
+ export async function fingerprint(url, fetchImpl = fetch) {
72
+ const r = await fetchImpl(url, { cache: "no-store", redirect: "manual" })
73
+ const tag = r.headers.get("etag") ?? r.headers.get("last-modified")
74
+ return tag ? `h:${tag}` : `b:${createHash("sha256").update(Buffer.from(await r.arrayBuffer())).digest("hex")}`
75
+ }
76
+
77
+ /**
78
+ * Waits until the dev server serves something other than `before` (its file
79
+ * watcher reloaded the take), up to RELOAD_MS.
80
+ * shortcut: fingerprints the route itself, not its main module; upgrade if a dev server serves an unchanged HTML shell for changed modules.
81
+ * @returns {Promise<{ ok: true } | { ok: false, reason: string }>}
82
+ */
83
+ export async function waitForReload(url, before, { timeoutMs = RELOAD_MS, everyMs = 250, fetchImpl = fetch, now = Date.now, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
84
+ const until = now() + timeoutMs
85
+ for (;;) {
86
+ try {
87
+ if ((await fingerprint(url, fetchImpl)) !== before) return { ok: true }
88
+ } catch {
89
+ // Reloading: try again
90
+ }
91
+ if (now() >= until) return { ok: false, reason: "dev server didn't reload" }
92
+ await sleep(everyMs)
93
+ }
94
+ }
95
+
96
+ /** The person's choice among passing takes: one option per take, in take order. */
97
+ export const takeQuestion = (survivors, stepTitle) => ({
98
+ id: "kriya-explore",
99
+ header: "Explore",
100
+ question: `Which take of "${stepTitle}" do you want to keep?`,
101
+ detail: "Every take shown passed the project's check and its gates. The others stay in kriya undo --list.",
102
+ options: survivors.map((t) => ({ label: `Take ${t.v}`, description: t.hint.text })),
103
+ })
package/src/failure.js CHANGED
@@ -20,7 +20,7 @@ export const CLASSES = [
20
20
  ]
21
21
 
22
22
  // The order a fix can move through: lower is further from passing
23
- export const RANK = { timeout: 0, environment: 0, syntax: 1, type: 2, unknown: 2, assertion: 3, "tests changed": 3, silenced: 3, "invariant broken": 3, acceptance: 3, "no reproduction": 3, "invariant violated": 3, "regression hazard": 3, "no negative test": 3, "premortem open": 3, pass: 4 }
23
+ export const RANK = { timeout: 0, environment: 0, syntax: 1, type: 2, unknown: 2, assertion: 3, "tests changed": 3, silenced: 3, "invariant broken": 3, acceptance: 3, "no reproduction": 3, "invariant violated": 3, "regression hazard": 3, "no negative test": 3, "premortem open": 3, gate: 3, "contract changed": 3, flaky: 3, "not checked": 0, pass: 4 }
24
24
 
25
25
  const EXCERPT = 2500
26
26
 
@@ -0,0 +1,114 @@
1
+ import { createHash } from "node:crypto"
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
3
+ import { dirname, join } from "node:path"
4
+
5
+ import { kriyaHome } from "./paths.js"
6
+ import { projectRoot } from "./skill-switches.js"
7
+
8
+ // Harness 2.0 W6: the commands the command-running gates use (Kriya-Tavi
9
+ // docs/kriya-harness/upgrade_2.0/GATES.md §3: G-DATA, G-EVAL, G-SAN, G-IAC,
10
+ // G-SIM, G-SIM-HEADLESS). A model never writes a gate's command (WD-04): the
11
+ // person confirms each one per project with `kriya gates use`, the same trust
12
+ // as `kriya verify use`. Kept in ~/.kriya/gates.json, outside the project; the
13
+ // G-EVAL baseline beside it, in ~/.kriya/evidence, so a builder can't move it.
14
+
15
+ export class GateCommandError extends Error {}
16
+
17
+ export const COMMAND_GATES = {
18
+ data: { id: "G-DATA", what: "runs the data pipeline on its dirty fixture", options: ["output"] },
19
+ eval: { id: "G-EVAL", what: "runs the evaluation and writes a metrics JSON file", options: ["metrics", "metric", "direction", "margin"] },
20
+ san: { id: "G-SAN", what: "builds and tests with warnings as errors and sanitizers on", options: [] },
21
+ iac: { id: "G-IAC", what: "validates and policy-checks the infrastructure offline (no apply)", options: [] },
22
+ sim: { id: "G-SIM", what: "builds and launches the app on a simulator or emulator", options: [] },
23
+ "sim-headless": { id: "G-SIM-HEADLESS", what: "runs the game's seeded headless simulation and prints STATE-HASH:", options: ["frameBudgetMs"] },
24
+ }
25
+ const LIMIT = 500
26
+
27
+ export const gatesFile = () => join(kriyaHome(), "gates.json")
28
+
29
+ function read() {
30
+ try {
31
+ const v = JSON.parse(readFileSync(gatesFile(), "utf8"))
32
+ return v && typeof v.projects === "object" ? v.projects : {}
33
+ } catch {
34
+ return {}
35
+ }
36
+ }
37
+
38
+ function write(file, value) {
39
+ mkdirSync(dirname(file), { recursive: true })
40
+ const temp = `${file}.${process.pid}.tmp`
41
+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
42
+ renameSync(temp, file)
43
+ }
44
+
45
+ const relative = (value) => {
46
+ const v = String(value ?? "").trim()
47
+ if (!v || v.startsWith("/") || v.split(/[\\/]/).includes("..")) throw new GateCommandError("Paths are relative to the project and stay inside it.")
48
+ return v
49
+ }
50
+
51
+ /** Confirms one gate's command (and its options) for this project. */
52
+ export function useGateCommand(cwd, gate, command, options = {}, now = () => new Date()) {
53
+ const spec = COMMAND_GATES[gate]
54
+ if (!spec) throw new GateCommandError(`The gates that run a command are: ${Object.keys(COMMAND_GATES).join(", ")}.`)
55
+ const text = typeof command === "string" ? command.trim() : ""
56
+ if (!text || text.length > LIMIT || /[\r\n]/.test(text)) throw new GateCommandError(`A gate command is one line of at most ${LIMIT} characters.`)
57
+ const entry = { command: text, confirmedAt: now().toISOString() }
58
+ if (gate === "data") {
59
+ if (!options.output) throw new GateCommandError("G-DATA needs --output <file or folder the pipeline writes>, to compare two runs.")
60
+ entry.output = relative(options.output)
61
+ }
62
+ if (gate === "eval") {
63
+ if (!options.metrics || !options.metric) throw new GateCommandError("G-EVAL needs --metrics <file.json> and --metric <name>, e.g. --metrics eval/metrics.json --metric f1.")
64
+ entry.metrics = relative(options.metrics)
65
+ entry.metric = String(options.metric).slice(0, 80)
66
+ entry.direction = options.direction === "lower" ? "lower" : "higher"
67
+ const margin = Number(options.margin ?? 0)
68
+ if (!Number.isFinite(margin) || margin < 0) throw new GateCommandError("--margin is a number ≥ 0.")
69
+ entry.margin = margin
70
+ }
71
+ if (gate === "sim-headless" && options.frameBudgetMs !== undefined) {
72
+ const ms = Number(options.frameBudgetMs)
73
+ if (!Number.isFinite(ms) || ms <= 0) throw new GateCommandError("--frame-budget-ms is a number above 0.")
74
+ entry.frameBudgetMs = ms
75
+ }
76
+ const root = projectRoot(cwd)
77
+ const projects = read()
78
+ projects[root] = { ...(projects[root] ?? {}), [gate]: entry }
79
+ write(gatesFile(), { version: 1, projects })
80
+ return { root, gate, ...entry }
81
+ }
82
+
83
+ export function forgetGateCommand(cwd, gate) {
84
+ const root = projectRoot(cwd)
85
+ const projects = read()
86
+ const had = Boolean(projects[root]?.[gate])
87
+ if (projects[root]) delete projects[root][gate]
88
+ write(gatesFile(), { version: 1, projects })
89
+ return had
90
+ }
91
+
92
+ /** This project's confirmed gate commands: { data?: {...}, eval?: {...}, … } */
93
+ export const gateCommands = (cwd) => read()[projectRoot(cwd)] ?? {}
94
+
95
+ const baselineFile = (root) => join(kriyaHome(), "evidence", createHash("sha256").update(root).digest("hex").slice(0, 16), "eval-baseline.json")
96
+ const candidateFile = (root) => baselineFile(root).replace(/baseline\.json$/, "candidate.json")
97
+
98
+ export function readBaseline(root) {
99
+ try {
100
+ return JSON.parse(readFileSync(baselineFile(root), "utf8"))
101
+ } catch {
102
+ return null
103
+ }
104
+ }
105
+ export const writeCandidate = (root, value) => write(candidateFile(root), value)
106
+
107
+ /** `kriya eval baseline confirm`: the last recorded first run becomes the baseline; only the person does this. */
108
+ export function confirmBaseline(cwd) {
109
+ const root = projectRoot(cwd)
110
+ if (!existsSync(candidateFile(root))) throw new GateCommandError("There's no recorded run to confirm yet: run the work with --gates once, then confirm.")
111
+ const candidate = JSON.parse(readFileSync(candidateFile(root), "utf8"))
112
+ write(baselineFile(root), { ...candidate, confirmedAt: new Date().toISOString() })
113
+ return candidate
114
+ }
@@ -0,0 +1,127 @@
1
+ import { randomUUID } 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 { CONTRACTS_DIR, resolvePointer } from "../contracts.js"
8
+ import { readStack } from "../stack.js"
9
+ import { Budget, fill, local, median, p95 } from "./http.js"
10
+ import { signIn, tenantConfig } from "./tenant.js"
11
+
12
+ // Harness 2.0 W5: G-API (Kriya-Tavi docs/kriya-harness/upgrade_2.0/GATES.md
13
+ // §3). Against the app the person confirmed (`kriya stack use --app`), for
14
+ // each operation of .kriya/contracts/api.openapi.json that carries an
15
+ // `x-kriya-example`: the example answers the contract's status with a body
16
+ // its schema accepts; seeded bad inputs get a 4xx, never a 5xx or a 2xx; an
17
+ // operation marked `x-kriya-idempotent` has one effect for ten concurrent
18
+ // requests with one Idempotency-Key. Latency is reported, never gated.
19
+ // These requests reach the person's local app, writes included; never anything else.
20
+
21
+ export const MAX_OPERATIONS = 10
22
+ const METHODS = ["get", "post", "put", "patch", "delete"]
23
+ const esc = (s) => String(s).replace(/~/g, "~0").replace(/\//g, "~1")
24
+
25
+ /** Bad request bodies made from the request schema, deterministic: [why, body] */
26
+ export function badBodies(schema, example) {
27
+ const out = []
28
+ const props = schema?.properties ?? {}
29
+ const base = example && typeof example === "object" && !Array.isArray(example) ? example : {}
30
+ for (const field of (schema?.required ?? []).slice(0, 3)) {
31
+ const { [field]: _gone, ...rest } = base
32
+ void _gone
33
+ out.push([`without required "${field}"`, rest])
34
+ }
35
+ const WRONG = { string: 12345, integer: "not a number", number: "not a number", boolean: "not a boolean", array: { not: "an array" }, object: "not an object" }
36
+ for (const [field, p] of Object.entries(props).slice(0, 3)) if (WRONG[p?.type] !== undefined) out.push([`"${field}" of the wrong type`, { ...base, [field]: WRONG[p.type] }])
37
+ for (const [field, p] of Object.entries(props)) {
38
+ if (p?.type === "string" && Number.isInteger(p.maxLength)) {
39
+ out.push([`"${field}" longer than its maxLength ${p.maxLength}`, { ...base, [field]: "x".repeat(p.maxLength + 1) }])
40
+ break
41
+ }
42
+ }
43
+ out.push(["a body that isn't JSON", "{"])
44
+ return out
45
+ }
46
+
47
+ const countOf = (r) => (Array.isArray(r.json) ? r.json.length : Number.isFinite(r.json?.count) ? r.json.count : Number.isFinite(r.json?.total) ? r.json.total : undefined)
48
+
49
+ /**
50
+ * @param {{ root: string, request?: typeof fetch }} input
51
+ * @returns {Promise<{ id: string, status: string, kind?: string, excerpt?: string, reason?: string, optional?: boolean, note?: string }>}
52
+ */
53
+ export async function apiGate({ root, request }) {
54
+ const id = "G-API"
55
+ const file = join(root, CONTRACTS_DIR, "api.openapi.json")
56
+ if (!existsSync(file)) return { id, status: "pass", note: "no API contract in this project" }
57
+ const { app } = readStack(root)
58
+ if (!app) return { id, status: "not_checked", optional: true, reason: "no app is confirmed for this project (kriya stack use --app http://localhost:<port>)" }
59
+ let doc
60
+ try {
61
+ doc = JSON.parse(readFileSync(file, "utf8"))
62
+ } catch {
63
+ return { id, status: "not_checked", reason: "api.openapi.json isn't valid JSON (G-CONTRACT reports it)" }
64
+ }
65
+ const ops = Object.entries(doc.paths ?? {})
66
+ .flatMap(([path, item]) => METHODS.filter((m) => item?.[m]?.["x-kriya-example"]).map((method) => ({ path, method, op: item[method] })))
67
+ .slice(0, MAX_OPERATIONS)
68
+ if (!ops.length) return { id, status: "not_checked", reason: 'no operation in api.openapi.json has an "x-kriya-example" to call' }
69
+ const ajv = new Ajv2020({ strict: false, allErrors: true, validateFormats: false })
70
+ ajv.addSchema(doc, "kriya-api")
71
+ const budget = new Budget()
72
+ const problems = []
73
+ const times = []
74
+ const tenants = tenantConfig(root)
75
+ const auth = {}
76
+ const headersFor = async (who) => {
77
+ if (!who) return {}
78
+ if (!tenants.config) throw new Error(`the example signs in as ${who}, but .kriya/gates/tenants.json is missing`)
79
+ auth[who] ??= await signIn(app, tenants.config, who, budget, request)
80
+ return auth[who].headers
81
+ }
82
+ try {
83
+ for (const { path, method, op } of ops) {
84
+ const ex = op["x-kriya-example"]
85
+ const label = `${method.toUpperCase()} ${path}`
86
+ const url = fill(ex.path ?? path, ex.params)
87
+ const headers = await headersFor(ex.auth)
88
+ const res = await local(app, url, { method: method.toUpperCase(), body: ex.body, headers, budget, request })
89
+ times.push(res.ms)
90
+ const wanted = ex.status ?? Number(Object.keys(op.responses ?? {}).find((s) => /^2\d\d$/.test(s)))
91
+ if (res.status === 0) {
92
+ problems.push(`${label}: no answer (${res.error})`)
93
+ continue
94
+ }
95
+ if (res.status !== wanted) problems.push(`${label}: answered ${res.status}, the contract's example expects ${wanted}${res.status >= 500 ? " (a server error)" : ""}`)
96
+ const pointer = `/paths/${esc(path)}/${method}/responses/${res.status}/content/application~1json/schema`
97
+ if (resolvePointer(doc, pointer) !== undefined) {
98
+ const validate = ajv.compile({ $ref: `kriya-api#${pointer}` })
99
+ if (!validate(res.json)) problems.push(`${label}: the ${res.status} body doesn't match the contract: ${validate.errors.slice(0, 3).map((e) => `${e.instancePath || "/"} ${e.message}`).join("; ")}`)
100
+ }
101
+ const reqPointer = `/paths/${esc(path)}/${method}/requestBody/content/application~1json/schema`
102
+ let schema = resolvePointer(doc, reqPointer)
103
+ if (schema?.$ref?.startsWith("#/")) schema = resolvePointer(doc, schema.$ref.slice(1))
104
+ if (schema && ["post", "put", "patch"].includes(method))
105
+ for (const [why, body] of badBodies(schema, ex.body)) {
106
+ const bad = await local(app, url, { method: method.toUpperCase(), body, headers, budget, request })
107
+ if (bad.status < 400 || bad.status >= 500) problems.push(`${label} ${why}: answered ${bad.status || bad.error}, expected a 4xx`)
108
+ }
109
+ const idem = op["x-kriya-idempotent"]
110
+ if (idem?.count) {
111
+ const before = countOf(await local(app, idem.count, { headers, budget, request }))
112
+ const key = randomUUID()
113
+ const replies = await Promise.all(Array.from({ length: 10 }, () => local(app, url, { method: method.toUpperCase(), body: ex.body, headers: { ...headers, "Idempotency-Key": key }, budget, request })))
114
+ const after = countOf(await local(app, idem.count, { headers, budget, request }))
115
+ const statuses = [...new Set(replies.map((r) => r.status))]
116
+ if (before === undefined || after === undefined) problems.push(`${label}: ${idem.count} doesn't return a list or { count }, so the effect can't be counted`)
117
+ else if (after - before !== 1) problems.push(`${label}: ten requests with one Idempotency-Key made ${after - before} effects, expected 1`)
118
+ if (statuses.some((s) => s < 200 || s >= 300)) problems.push(`${label}: with one Idempotency-Key, answers were ${statuses.join(", ")}`)
119
+ }
120
+ }
121
+ } catch (error) {
122
+ return { id, status: "fail", kind: "gate", excerpt: `G-API: ${String(error?.message ?? error).slice(0, 300)}` }
123
+ }
124
+ const note = `${ops.length} operation(s); latency p50 ${Math.round(median(times) ?? 0)} ms, p95 ${Math.round(p95(times) ?? 0)} ms (reported, not gated)`
125
+ if (problems.length) return { id, status: "fail", kind: "gate", excerpt: `G-API (against ${app}):\n${problems.slice(0, 15).map((p) => `- ${p}`).join("\n")}`, note }
126
+ return { id, status: "pass", note }
127
+ }