@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
package/src/mcp.js ADDED
@@ -0,0 +1,126 @@
1
+ import { createHash } from "node:crypto"
2
+
3
+ import { CLIENT_VERSION } from "./paths.js"
4
+
5
+ // Harness 2.0 W16, MCP P3a (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
6
+ // GROUNDING_AND_CONNECTORS.md §4): servers from the owner's registry that need
7
+ // no sign-in, each tool used only if its full definition still hashes to what
8
+ // the owner pinned. The hash is Kriya's own (lib/mcp/tools.ts definitionHash
9
+ // over lib/agent/episodes.ts canonical), so a device and Kriya agree on drift.
10
+ // A minimal Streamable HTTP client: https only (http only to this machine),
11
+ // no redirects followed, and no credential of any kind sent: no
12
+ // Authorization, no cookie, never the device's Kriya token.
13
+
14
+ const PINNED = ["name", "title", "description", "inputSchema", "outputSchema", "annotations"]
15
+
16
+ /** Kriya's canonical JSON: keys sorted, undefined dropped (lib/agent/episodes.ts). */
17
+ export const canonical = (value) => {
18
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`
19
+ if (value && typeof value === "object") {
20
+ const entries = Object.entries(value).filter(([, v]) => v !== undefined)
21
+ return `{${entries
22
+ .sort(([a], [b]) => (a < b ? -1 : 1))
23
+ .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)
24
+ .join(",")}}`
25
+ }
26
+ return JSON.stringify(value)
27
+ }
28
+
29
+ /** The pinned parts of a tool definition, hashed as Kriya hashes them. */
30
+ export function definitionHash(definition) {
31
+ const pinned = Object.fromEntries(PINNED.filter((k) => definition?.[k] !== undefined).map((k) => [k, definition[k]]))
32
+ return createHash("sha256").update(canonical(pinned)).digest("hex")
33
+ }
34
+
35
+ /**
36
+ * The tools a server lists that the owner pinned, unchanged: `{ tool, pin }`.
37
+ * A listed tool with no pin, or whose definition drifted, is left out.
38
+ */
39
+ export function pinnedTools(listed, pins) {
40
+ const out = []
41
+ const dropped = []
42
+ for (const tool of listed ?? []) {
43
+ const pin = (pins ?? []).find((p) => p.name === tool?.name)
44
+ if (!pin) continue
45
+ if (definitionHash(tool) !== pin.definitionHash) dropped.push(tool.name)
46
+ else out.push({ tool, pin })
47
+ }
48
+ return { tools: out, drifted: dropped }
49
+ }
50
+
51
+ export class McpError extends Error {}
52
+
53
+ /** https, or http only to this machine; no credentials in the address. */
54
+ export function serverUrl(text) {
55
+ let url
56
+ try {
57
+ url = new URL(text)
58
+ } catch {
59
+ throw new McpError("That isn't a server address.")
60
+ }
61
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)
62
+ if (url.username || url.password) throw new McpError("A server address carries no credentials.")
63
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) throw new McpError("Registry servers are https.")
64
+ return url
65
+ }
66
+
67
+ const PROTOCOL = "2025-06-18"
68
+
69
+ /** One server's session: initialize, list, call. `fetchImpl` for tests. */
70
+ export function mcpSession(address, { fetchImpl = fetch, timeoutMs = 30_000 } = {}) {
71
+ const url = serverUrl(address)
72
+ let session
73
+ let id = 0
74
+ const post = async (body, signal) => {
75
+ const headers = { "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-protocol-version": PROTOCOL }
76
+ if (session) headers["mcp-session-id"] = session
77
+ const response = await fetchImpl(url, { method: "POST", headers, body: JSON.stringify(body), redirect: "error", signal: signal ?? AbortSignal.timeout(timeoutMs) })
78
+ const next = response.headers.get("mcp-session-id")
79
+ if (next) session = next
80
+ return response
81
+ }
82
+ async function request(method, params, signal) {
83
+ const want = ++id
84
+ const response = await post({ jsonrpc: "2.0", id: want, method, params }, signal)
85
+ if (!response.ok) throw new McpError(`The server answered ${response.status}.`)
86
+ const type = response.headers.get("content-type") ?? ""
87
+ let message
88
+ if (type.includes("text/event-stream")) {
89
+ const text = await response.text()
90
+ for (const line of text.split("\n")) {
91
+ if (!line.startsWith("data:")) continue
92
+ try {
93
+ const m = JSON.parse(line.slice(5))
94
+ if (m?.id === want) message = m
95
+ } catch {
96
+ // Not a message
97
+ }
98
+ }
99
+ } else message = await response.json()
100
+ if (!message) throw new McpError("The server sent no answer.")
101
+ if (message.error) throw new McpError(`The server refused: ${String(message.error.message ?? "error").slice(0, 300)}`)
102
+ return message.result
103
+ }
104
+ return {
105
+ async open() {
106
+ await request("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "kriya-harness", version: CLIENT_VERSION } })
107
+ await post({ jsonrpc: "2.0", method: "notifications/initialized" })
108
+ },
109
+ async tools() {
110
+ const all = []
111
+ let cursor
112
+ for (let page = 0; page < 10; page++) {
113
+ const result = await request("tools/list", cursor ? { cursor } : {})
114
+ all.push(...(result?.tools ?? []))
115
+ cursor = result?.nextCursor
116
+ if (!cursor) break
117
+ }
118
+ return all
119
+ },
120
+ call: (name, args, signal) => request("tools/call", { name, arguments: args ?? {} }, signal),
121
+ }
122
+ }
123
+
124
+ /** A model-facing name: mcp__<server>__<tool>, within DeepSeek's function-name rules. */
125
+ export const toolName = (serverId, name) =>
126
+ `mcp__${serverId}__${name}`.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64)
@@ -0,0 +1,188 @@
1
+ import { createHash } from "node:crypto"
2
+ import { closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
3
+ import { dirname, join } from "node:path"
4
+
5
+ import { planStatus } from "./loop.js"
6
+ import { projectRoot } from "./skill-switches.js"
7
+ import { progressFiles, readProgress, VerifyError } from "./verify.js"
8
+
9
+ // Harness 2.0 milestones (Kriya-Tavi docs/kriya-harness/upgrade_2.0/
10
+ // ORCHESTRA.md §4, WD-12): long work as a ledger of at most 12 milestones,
11
+ // each one bounded plan (MAX_STEPS and MAX_ATTEMPTS unchanged). The ledger
12
+ // lives in ~/.kriya/progress/<project>/milestones.json, outside the project,
13
+ // written only by this code: a milestone is done only when its plan's every
14
+ // step passed the person's check, never because the model says so. The head
15
+ // plans milestone i+1 only after milestone i is done; a blocked one stops the
16
+ // work for the person. Off unless kriya was started with --milestones.
17
+
18
+ export const MAX_MILESTONES = 12
19
+ export const LOCK_STALE_MS = 10_000
20
+ const LOCK_WAIT_MS = 2_000
21
+
22
+ /** The ledger's file: beside the project's progress records. */
23
+ export function milestonesFile(root) {
24
+ return join(dirname(progressFiles(root, "ledger").json), "milestones.json")
25
+ }
26
+
27
+ /** The ledger, or undefined. */
28
+ export function readMilestones(root) {
29
+ try {
30
+ return JSON.parse(readFileSync(milestonesFile(root), "utf8"))
31
+ } catch {
32
+ return undefined
33
+ }
34
+ }
35
+
36
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
37
+
38
+ /**
39
+ * Runs `change(ledger)` under the ledger's lock and writes its result
40
+ * atomically (temp file + rename). Two sessions in one project may run at
41
+ * once: a second writer waits briefly, then is told; a lock older than
42
+ * LOCK_STALE_MS (a crashed session) is taken over.
43
+ */
44
+ export async function updateMilestones(root, change, { now = Date.now, waitMs = LOCK_WAIT_MS } = {}) {
45
+ const file = milestonesFile(root)
46
+ const lock = `${file}.lock`
47
+ mkdirSync(dirname(file), { recursive: true })
48
+ const started = now()
49
+ for (;;) {
50
+ try {
51
+ closeSync(openSync(lock, "wx", 0o600))
52
+ break
53
+ } catch (error) {
54
+ if (error.code !== "EEXIST") throw error
55
+ let age = 0
56
+ try {
57
+ age = now() - statSync(lock).mtimeMs
58
+ } catch {
59
+ continue
60
+ }
61
+ if (age > LOCK_STALE_MS) {
62
+ rmSync(lock, { force: true })
63
+ continue
64
+ }
65
+ if (now() - started >= waitMs) throw new VerifyError("Another session is updating milestones; try again in a moment.")
66
+ await sleep(50)
67
+ }
68
+ }
69
+ try {
70
+ const next = change(readMilestones(root))
71
+ if (next !== undefined) {
72
+ const temp = `${file}.${process.pid}.tmp`
73
+ writeFileSync(temp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 })
74
+ renameSync(temp, file)
75
+ }
76
+ return next
77
+ } finally {
78
+ rmSync(lock, { force: true })
79
+ }
80
+ }
81
+
82
+ const text = (v, max) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim().slice(0, max) : "")
83
+
84
+ /** 1 to 12 milestones, each a title and a done-when, roles checked against `roles` when given. */
85
+ export function validateMilestones(input, roles) {
86
+ const list = Array.isArray(input) ? input : []
87
+ if (!list.length) throw new VerifyError("Milestones need at least one milestone.")
88
+ if (list.length > MAX_MILESTONES) throw new VerifyError(`At most ${MAX_MILESTONES} milestones; split the work differently.`)
89
+ const out = list.map((m, i) => {
90
+ const title = text(m?.title, 200)
91
+ const doneWhen = text(m?.done_when ?? m?.doneWhen, 500)
92
+ if (!title || !doneWhen) throw new VerifyError(`Milestone ${i + 1} needs a title and done_when.`)
93
+ const asked = Array.isArray(m?.roles) ? [...new Set(m.roles.filter((r) => typeof r === "string"))] : []
94
+ if (roles && asked.some((r) => !roles.includes(r))) throw new VerifyError(`Milestone ${i + 1} names a role Kriya doesn't have.`)
95
+ return { title, doneWhen, roles: roles ? asked : [], status: "todo" }
96
+ })
97
+ if (new Set(out.map((m) => m.title.toLowerCase())).size !== out.length) throw new VerifyError("Two milestones have the same title.")
98
+ return out
99
+ }
100
+
101
+ const open = (ledger) => ledger?.milestones?.some((m) => m.status !== "done")
102
+
103
+ /**
104
+ * Records the milestones. While some are still open, a new list is refused
105
+ * unless `replan` (the person chose to replace them, asked by the harness).
106
+ */
107
+ export async function saveMilestones(root, input, { roles, replan = false, now = () => new Date().toISOString() } = {}) {
108
+ const milestones = validateMilestones(input, roles)
109
+ return updateMilestones(root, (ledger) => {
110
+ if (open(ledger) && !replan) throw new VerifyError("This project already has milestones in progress. Work through them with kriya_plan, one milestone at a time; only the person can replace them.")
111
+ return { version: 1, createdAt: now(), milestones, ...(ledger && { replaced: (ledger.replaced ?? 0) + 1 }) }
112
+ })
113
+ }
114
+
115
+ const planHash = (plan) => createHash("sha256").update(JSON.stringify(plan)).digest("hex").slice(0, 16)
116
+
117
+ /** The first milestone not done: the only one a plan may be for. */
118
+ export const currentMilestone = (ledger) => ledger?.milestones?.findIndex((m) => m.status !== "done") ?? -1
119
+
120
+ /** Before a plan is recorded: refused when every milestone is done or the current one is blocked. */
121
+ export function checkPlanAllowed(root) {
122
+ const ledger = readMilestones(root)
123
+ if (!ledger) return
124
+ const i = currentMilestone(ledger)
125
+ if (i === -1) throw new VerifyError("Every milestone is done. Tell the person; they can set new milestones.")
126
+ if (ledger.milestones[i].status === "blocked")
127
+ throw new VerifyError(`Milestone ${i + 1} (${ledger.milestones[i].title}) is blocked. Stop and tell the person what failed.`)
128
+ }
129
+
130
+ /** After a plan is recorded: it belongs to the current milestone, which becomes active. */
131
+ export function bindPlan(root, sessionId, { now = () => new Date().toISOString() } = {}) {
132
+ const plan = readProgress(root, sessionId).plan
133
+ if (!plan) return Promise.resolve(undefined)
134
+ return updateMilestones(root, (ledger) => {
135
+ if (!ledger) return undefined
136
+ const i = currentMilestone(ledger)
137
+ if (i === -1) return undefined
138
+ const m = ledger.milestones[i]
139
+ ledger.milestones[i] = { ...m, status: "active", startedAt: m.startedAt ?? now(), plan: { sessionId, hash: planHash(plan) }, verdicts: [] }
140
+ return ledger
141
+ })
142
+ }
143
+
144
+ /**
145
+ * After a step: the active milestone's status from its plan's records, by
146
+ * code. Done only when every step passed; blocked when a step is blocked.
147
+ */
148
+ export function syncMilestones(cwd, sessionId, { now = () => new Date().toISOString() } = {}) {
149
+ const root = projectRoot(cwd)
150
+ const ledger = readMilestones(root)
151
+ const i = currentMilestone(ledger)
152
+ if (i === -1 || ledger.milestones[i].plan?.sessionId !== sessionId) return Promise.resolve(ledger)
153
+ const rows = planStatus(cwd, sessionId)
154
+ if (!rows) return Promise.resolve(ledger)
155
+ const hash = planHash(readProgress(root, sessionId).plan)
156
+ return updateMilestones(root, (current) => {
157
+ const m = current?.milestones?.[i]
158
+ if (!m || m.plan?.sessionId !== sessionId || m.plan.hash !== hash) return undefined
159
+ const verdicts = rows.map((r) => ({ n: r.n, title: r.title, status: r.status }))
160
+ const status = rows.every((r) => r.status === "pass") ? "done" : rows.some((r) => r.status === "blocked") ? "blocked" : "active"
161
+ current.milestones[i] = { ...m, status, verdicts, ...(status === "done" && { doneAt: now() }) }
162
+ return current
163
+ })
164
+ }
165
+
166
+ /** The late system-prompt section: where the long work stands, for a new or resumed session. Empty without milestones. */
167
+ export function milestonesText(root) {
168
+ const ledger = readMilestones(root)
169
+ if (!ledger?.milestones?.length) return ""
170
+ const i = currentMilestone(ledger)
171
+ const lines = ["# Milestones (from Kriya's ledger; only passing checks complete one)", ""]
172
+ ledger.milestones.forEach((m, n) => lines.push(`${n + 1}. ${m.title}: ${m.status}`))
173
+ lines.push("")
174
+ if (i === -1) lines.push("Every milestone is done.")
175
+ else {
176
+ const m = ledger.milestones[i]
177
+ lines.push(`Current: milestone ${i + 1}, ${m.title}. Done when: ${m.doneWhen}.${m.roles.length ? ` Roles: ${m.roles.join(", ")}.` : ""}`)
178
+ if (m.verdicts?.length) lines.push(`Last verdicts: ${m.verdicts.map((v) => `${v.n}. ${v.title}: ${v.status}`).join("; ")}.`)
179
+ lines.push(
180
+ m.status === "blocked"
181
+ ? "It is blocked: stop and tell the person what failed."
182
+ : m.plan
183
+ ? "Run its plan's remaining steps with kriya_step; the next milestone is planned only after this one is done."
184
+ : "Plan it with kriya_plan (one plan for this milestone only)."
185
+ )
186
+ }
187
+ return lines.join("\n")
188
+ }
package/src/modes.js CHANGED
@@ -107,22 +107,89 @@ 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],
113
145
  ]
114
146
 
147
+ /** The launch variable naming the switches the person set themself (a flag, or the variable in their shell) */
148
+ export const SET_BY_PERSON = "KRIYA_SWITCHES_SET"
149
+
115
150
  /** Takes the switch flags out of `args` and sets each switch to "on" or "off" in `env`. */
116
151
  export function switchEnv(args, env = process.env) {
152
+ const chosen = new Set((env[SET_BY_PERSON] ?? "").split(",").filter(Boolean))
117
153
  for (const [flag, name, byDefault] of SWITCHES) {
154
+ if (env[name] === "on" || env[name] === "off") chosen.add(flag)
118
155
  let value = env[name] === "on" ? true : env[name] === "off" ? false : byDefault
119
156
  for (const [form, on] of [[`--${flag}`, true], [`--no-${flag}`, false]]) {
120
157
  const at = args.indexOf(form)
121
158
  if (at === -1) continue
122
159
  args.splice(at, 1)
123
160
  value = on
161
+ chosen.add(flag)
124
162
  }
125
163
  env[name] = value ? "on" : "off"
126
164
  }
165
+ // Recorded once, from the first call: later calls see the defaults written above, not the person's choice
166
+ env[SET_BY_PERSON] ??= [...chosen].join(",")
167
+ }
168
+
169
+ /**
170
+ * Harness 2.0 switches the owner turns on for every device with Kriya's
171
+ * harness.workforce (GET /models `workforce: 1`). Each still yields to the
172
+ * person's own flag or variable (`kriya --no-gates`). Repository tools and
173
+ * deploys act on the person's own GitHub and hosting logins, so they stay the
174
+ * person's to turn on per device (`kriya --repo-tools --deploy`); the Editing
175
+ * Studio has its own owner switch.
176
+ */
177
+ export const WORKFORCE_SWITCHES = Object.freeze(["cartridges", "orchestra", "gates", "critic", "milestones", "grounding", "explore", "runstrip", "mcp"])
178
+
179
+ /**
180
+ * Turns on the owner's Harness 2.0 switches the person didn't set, when Kriya
181
+ * advertises them. Without the advertisement nothing changes (HT-REG).
182
+ * @returns {string[]} the switches this turned on
183
+ */
184
+ export function applyWorkforce(env = process.env, advertised = false) {
185
+ if (!advertised) return []
186
+ const chosen = new Set((env[SET_BY_PERSON] ?? "").split(",").filter(Boolean))
187
+ const turned = []
188
+ for (const [flag, name] of SWITCHES) {
189
+ if (!WORKFORCE_SWITCHES.includes(flag) || chosen.has(flag) || env[name] === "on") continue
190
+ env[name] = "on"
191
+ turned.push(flag)
192
+ }
193
+ return turned
127
194
  }
128
195
 
@@ -0,0 +1,50 @@
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
+ }
44
+
45
+ /**
46
+ * Harness 2.0: whether a session runs split (head and worker). With the
47
+ * picker's Orchestration choice offered (`pick`), only a session whose model
48
+ * is that choice; without it, every session (the earlier behaviour).
49
+ */
50
+ export const sessionOrchestrated = (levels, pick, model) => Boolean(levels) && (!pick || model === pick)
@@ -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
  }