@kriya-ai/harness 0.0.0-stage → 0.2.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 (185) hide show
  1. package/README.md +379 -2
  2. package/SAFETY.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +7911 -0
  4. package/bin/kriya.js +577 -0
  5. package/bundle/cordis.patch.yml +397 -0
  6. package/contract/SOURCE.md +15 -0
  7. package/contract/contract.json +1355 -0
  8. package/package.json +57 -4
  9. package/plugins/anchor/index.js +56 -0
  10. package/plugins/anchor/package.json +13 -0
  11. package/plugins/approvals/index.js +183 -0
  12. package/plugins/approvals/package.json +13 -0
  13. package/plugins/brand/DESIGN.md +112 -0
  14. package/plugins/brand/client.js +826 -0
  15. package/plugins/brand/index.js +15 -0
  16. package/plugins/brand/package.json +25 -0
  17. package/plugins/brand/src/client.js +823 -0
  18. package/plugins/browser/index.js +218 -0
  19. package/plugins/browser/package.json +13 -0
  20. package/plugins/budget/index.js +108 -0
  21. package/plugins/budget/package.json +13 -0
  22. package/plugins/changes/client.js +245 -0
  23. package/plugins/changes/index.js +75 -0
  24. package/plugins/changes/package.json +22 -0
  25. package/plugins/edit/client.js +113 -0
  26. package/plugins/edit/index.js +58 -0
  27. package/plugins/edit/package.json +23 -0
  28. package/plugins/fs-freshness/index.js +28 -0
  29. package/plugins/fs-freshness/package.json +13 -0
  30. package/plugins/graph/client.js +178 -0
  31. package/plugins/graph/index.js +4 -0
  32. package/plugins/graph/package.json +22 -0
  33. package/plugins/kriya-handoff/index.js +194 -0
  34. package/plugins/kriya-handoff/package.json +13 -0
  35. package/plugins/kriya-tools/index.js +189 -0
  36. package/plugins/kriya-tools/package.json +13 -0
  37. package/plugins/loop/index.js +743 -0
  38. package/plugins/loop/package.json +13 -0
  39. package/plugins/mirror/index.js +235 -0
  40. package/plugins/mirror/package.json +13 -0
  41. package/plugins/overview/client.js +276 -0
  42. package/plugins/overview/index.js +95 -0
  43. package/plugins/overview/package.json +22 -0
  44. package/plugins/preview/client.js +337 -0
  45. package/plugins/preview/index.js +4 -0
  46. package/plugins/preview/package.json +22 -0
  47. package/plugins/progress/client.js +290 -0
  48. package/plugins/progress/index.js +100 -0
  49. package/plugins/progress/package.json +22 -0
  50. package/plugins/projects/client.js +249 -0
  51. package/plugins/projects/index.js +30 -0
  52. package/plugins/projects/package.json +24 -0
  53. package/plugins/rea/index.js +256 -0
  54. package/plugins/rea/package.json +10 -0
  55. package/plugins/rea/skill/LICENSE +21 -0
  56. package/plugins/rea/skill/SKILL.md +360 -0
  57. package/plugins/rea/skill/references/android-applications.md +36 -0
  58. package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
  59. package/plugins/rea/skill/references/evidence-workflows.md +71 -0
  60. package/plugins/rea/skill/references/javascript-applications.md +218 -0
  61. package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
  62. package/plugins/rea/skill/references/runtime-observation.md +78 -0
  63. package/plugins/remote/index.js +297 -0
  64. package/plugins/remote/package.json +10 -0
  65. package/plugins/router/index.js +84 -0
  66. package/plugins/router/package.json +13 -0
  67. package/plugins/sessions/client.js +68 -0
  68. package/plugins/sessions/index.js +79 -0
  69. package/plugins/sessions/package.json +20 -0
  70. package/plugins/skills/client.js +504 -0
  71. package/plugins/skills/index.js +166 -0
  72. package/plugins/skills/package.json +23 -0
  73. package/src/api.js +97 -0
  74. package/src/browser.js +286 -0
  75. package/src/changes.js +191 -0
  76. package/src/checkpoints.js +313 -0
  77. package/src/daemon.js +503 -0
  78. package/src/doctor.js +137 -0
  79. package/src/edit/core/anchors.js +102 -0
  80. package/src/edit/core/audio.js +158 -0
  81. package/src/edit/core/faces.js +99 -0
  82. package/src/edit/core/ffmpeg.js +258 -0
  83. package/src/edit/core/handoff.js +220 -0
  84. package/src/edit/core/history.js +90 -0
  85. package/src/edit/core/layout.js +92 -0
  86. package/src/edit/core/mix.js +115 -0
  87. package/src/edit/core/ops.js +602 -0
  88. package/src/edit/core/plan.js +266 -0
  89. package/src/edit/core/project.d.ts +134 -0
  90. package/src/edit/core/project.js +307 -0
  91. package/src/edit/core/reframe.js +125 -0
  92. package/src/edit/core/solver.js +416 -0
  93. package/src/edit/core/time.js +110 -0
  94. package/src/edit/core/tonemap.js +57 -0
  95. package/src/edit/director/ask.js +120 -0
  96. package/src/edit/director/gateway.js +16 -0
  97. package/src/edit/director/revise.js +186 -0
  98. package/src/edit/engine/capabilities.js +33 -0
  99. package/src/edit/engine/captions.js +154 -0
  100. package/src/edit/engine/color.js +269 -0
  101. package/src/edit/engine/confine.js +67 -0
  102. package/src/edit/engine/dna.js +148 -0
  103. package/src/edit/engine/index.js +473 -0
  104. package/src/edit/engine/loudness.js +43 -0
  105. package/src/edit/engine/media.js +57 -0
  106. package/src/edit/engine/motion.js +281 -0
  107. package/src/edit/engine/packs.js +87 -0
  108. package/src/edit/engine/probe.js +101 -0
  109. package/src/edit/engine/receipt.js +123 -0
  110. package/src/edit/engine/tool.js +101 -0
  111. package/src/edit/gates/copy.js +113 -0
  112. package/src/edit/gates/index.js +430 -0
  113. package/src/edit/gates/picture.js +130 -0
  114. package/src/edit/gates/sound.js +58 -0
  115. package/src/edit/gates/speech.js +127 -0
  116. package/src/edit/gates/text.js +196 -0
  117. package/src/edit/gates/text.swift +22 -0
  118. package/src/edit/graph/index.js +139 -0
  119. package/src/edit/graph/journal.js +69 -0
  120. package/src/edit/graph/scheduler.js +79 -0
  121. package/src/edit/host/client.js +58 -0
  122. package/src/edit/host/deliver.js +119 -0
  123. package/src/edit/host/jobs.js +84 -0
  124. package/src/edit/host/main.js +135 -0
  125. package/src/edit/host/paths.js +11 -0
  126. package/src/edit/host/projects.js +415 -0
  127. package/src/edit/host/server.js +391 -0
  128. package/src/edit/host/taste.js +135 -0
  129. package/src/edit/host/tavi.js +417 -0
  130. package/src/edit/host/watch.js +141 -0
  131. package/src/edit/index/db.js +109 -0
  132. package/src/edit/index/index.js +236 -0
  133. package/src/edit/index/layers/faces.js +78 -0
  134. package/src/edit/index/layers/faces.swift +18 -0
  135. package/src/edit/index/layers/meta.js +35 -0
  136. package/src/edit/index/layers/music.js +146 -0
  137. package/src/edit/index/layers/quality.js +120 -0
  138. package/src/edit/index/layers/retakes.js +132 -0
  139. package/src/edit/index/layers/screen.js +99 -0
  140. package/src/edit/index/layers/shots.js +29 -0
  141. package/src/edit/index/layers/sound.js +42 -0
  142. package/src/edit/index/layers/words.js +64 -0
  143. package/src/edit/index/story.js +248 -0
  144. package/src/edit/index/views.js +71 -0
  145. package/src/edit/loop/governor.js +112 -0
  146. package/src/edit/loop/loop.js +69 -0
  147. package/src/edit/loop/make.js +115 -0
  148. package/src/edit/loop/repair.js +97 -0
  149. package/src/edit/loop/replay.js +32 -0
  150. package/src/edit/recipes/multicam.js +461 -0
  151. package/src/edit/recipes/reel.js +202 -0
  152. package/src/edit/recipes/short-from-long.js +237 -0
  153. package/src/edit/recipes/tutorial.js +137 -0
  154. package/src/edit/recipes/youtube.js +155 -0
  155. package/src/edit/runtime/cli.js +126 -0
  156. package/src/edit/runtime/doctor.js +122 -0
  157. package/src/edit/runtime/fetch.js +15 -0
  158. package/src/edit/runtime/licences.js +88 -0
  159. package/src/edit/runtime/manifest.js +73 -0
  160. package/src/edit/runtime/setup.js +252 -0
  161. package/src/failure.js +69 -0
  162. package/src/gateway-proxy.js +213 -0
  163. package/src/intent.js +130 -0
  164. package/src/launch.js +315 -0
  165. package/src/live.js +81 -0
  166. package/src/local-skills.js +284 -0
  167. package/src/login.js +82 -0
  168. package/src/loop.js +428 -0
  169. package/src/modes.js +128 -0
  170. package/src/overview.js +71 -0
  171. package/src/paths.js +30 -0
  172. package/src/profiles.js +92 -0
  173. package/src/projects.js +104 -0
  174. package/src/recon.js +244 -0
  175. package/src/rules.js +139 -0
  176. package/src/runner.bundle.js +21172 -0
  177. package/src/sentinel.js +248 -0
  178. package/src/skill-switches.js +130 -0
  179. package/src/store.js +58 -0
  180. package/src/strict.js +124 -0
  181. package/src/verify.js +659 -0
  182. package/src/world.js +268 -0
  183. package/studio/dist/index.html +14 -0
  184. package/studio/dist/studio.css +163 -0
  185. package/studio/dist/studio.js +1 -0
@@ -0,0 +1,248 @@
1
+ // The defensive engine's code half (KRIYA_DEFENSIVE=on, `--defensive`;
2
+ // KRIYA_DEFENSIVE_ENGINE_REPORT.md in the Kriya repository). Everything here
3
+ // is a fixed rule over a diff, with no model: a model reviewing its own work
4
+ // is the weakest check there is (R-63), so a finding is a line in a file a
5
+ // person can read. shortcut: rules read source lines, not a syntax tree, so
6
+ // they miss what's split across lines; a parser is a dependency worth adding
7
+ // only if real runs show the misses matter.
8
+
9
+ const COMMENT = /^\s*(\/\/|#|\*|\/\*)/
10
+ const TEST = /(^|\/)(tests?|__tests__|spec|specs)\/|\.(test|spec)\.[^/]+$|(^|\/)test_[^/]+\.py$|_test\.py$/
11
+ const CODE = /\.(m?[jt]sx?|cjs|py)$/
12
+ export const isTest = (rel) => TEST.test(rel)
13
+
14
+ /** Lines of `after` that `before` doesn't have, as many times as they're new, with their numbers */
15
+ export function addedLines(before, after) {
16
+ const left = new Map()
17
+ for (const line of String(before ?? "").split("\n")) left.set(line, (left.get(line) ?? 0) + 1)
18
+ const out = []
19
+ String(after ?? "").split("\n").forEach((text, i) => {
20
+ const n = left.get(text) ?? 0
21
+ if (n > 0) left.set(text, n - 1)
22
+ else if (text.trim()) out.push({ line: i + 1, text })
23
+ })
24
+ return out
25
+ }
26
+
27
+ const SERVER = /(^|\/)(app\/api|pages\/api|actions|routes|controllers|handlers|server|api)\//
28
+ const UI = /(^|\/)components\/|\.tsx$|\.jsx$/
29
+ const DATA_PATH = /(^|\/)(actions|queries|app)\//
30
+ const MONEY = /\b\w*(amount|price|paise|rupee|inr|usd|cost|fee|tax|gst|charge|balance|total|salary)\w*\b/i
31
+ // Not toFixed: replayed on real commits it was only ever display
32
+ const FLOAT_MATH = /\bparseFloat\(|\bfloat\(|[*/]\s*\d+\.\d+|\b\d+\.\d+\s*\*/
33
+ const IDENTITY = "userId|user_id|ownerId|owner_id|tenantId|tenant_id|role|isAdmin|is_admin|plan|price"
34
+ const UNTRUSTED = "body|json\\(\\)|searchParams|formData|query|params|headers"
35
+
36
+ const RULES = [
37
+ {
38
+ rule: "tenant isolation",
39
+ applies: (rel, facts) => facts.tenancy && DATA_PATH.test(rel),
40
+ match: /\bprivileged\(|\bdb\.(select|insert|update|delete|execute)\(/,
41
+ why: "runs outside withUser, so Row Level Security doesn't apply; go through withUser(userId, …)",
42
+ },
43
+ {
44
+ rule: "sql injection",
45
+ applies: () => true,
46
+ match: /\.(query|execute|raw|unsafe)\(\s*`[^`]*\$\{|\.(query|execute|raw|unsafe)\(\s*["'][^"']*["']\s*\+|\.(execute|query)\(\s*f["']/,
47
+ why: "builds SQL from a string; bind the value as a parameter",
48
+ },
49
+ {
50
+ rule: "financial precision",
51
+ applies: (rel) => !UI.test(rel),
52
+ match: (text) => MONEY.test(text) && FLOAT_MATH.test(text),
53
+ why: "does money math in floats; keep integers (paise, micros) and use the project's money helpers",
54
+ },
55
+ {
56
+ rule: "session identity",
57
+ applies: (rel) => SERVER.test(rel),
58
+ match: new RegExp(`\\b(${IDENTITY})\\b[^=\\n]*=[^=>][^;\\n]*\\b(${UNTRUSTED})\\b|\\{[^}]*\\b(${IDENTITY})\\b[^}]*\\}\\s*=\\s*(await\\s+)?[\\w.]*\\b(${UNTRUSTED})`),
59
+ why: "takes identity or price from the request; derive it from the session on the server",
60
+ },
61
+ {
62
+ rule: "secret in code",
63
+ applies: () => true,
64
+ match: /\bsk-[A-Za-z0-9_-]{20,}|\bAKIA[0-9A-Z]{16}\b|-----BEGIN [A-Z ]*PRIVATE KEY|\bghp_[A-Za-z0-9]{30,}/,
65
+ why: "puts a secret in source; read it from the environment",
66
+ },
67
+ ]
68
+
69
+ /**
70
+ * The invariant sentinel: added source lines against the rules.
71
+ * @param {{ rel: string, before: string | null, after: string | null }[]} diffs
72
+ * @param {{ tenancy?: boolean }} facts tenancy: the project scopes data through withUser
73
+ * @returns {{ file: string, line: number, rule: string, why: string }[]}
74
+ */
75
+ export function sentinel(diffs, facts = {}) {
76
+ const found = []
77
+ for (const { rel, before, after } of diffs) {
78
+ if (after === null || isTest(rel) || !CODE.test(rel)) continue
79
+ for (const { line, text } of addedLines(before, after)) {
80
+ if (COMMENT.test(text)) continue
81
+ for (const r of RULES) {
82
+ if (!r.applies(rel, facts)) continue
83
+ if (typeof r.match === "function" ? r.match(text) : r.match.test(text)) found.push({ file: rel, line, rule: r.rule, why: r.why })
84
+ }
85
+ }
86
+ }
87
+ return found
88
+ }
89
+
90
+ function splitParams(text) {
91
+ const out = []
92
+ let depth = 0
93
+ let part = ""
94
+ for (const ch of text) {
95
+ if ("([{<".includes(ch)) depth++
96
+ if (")]}>".includes(ch)) depth--
97
+ if (ch === "," && depth === 0) (out.push(part.trim()), (part = ""))
98
+ else part += ch
99
+ }
100
+ if (part.trim()) out.push(part.trim())
101
+ return out
102
+ }
103
+
104
+ const param = (text) => {
105
+ const [head, value] = text.split(/=(?!>)/, 2).map((t) => t.trim())
106
+ const name = head.replace(/^\.\.\./, "").replace(/[?:].*$/, "").trim()
107
+ return { name, required: value === undefined && !/\?\s*:/.test(head) && !head.startsWith("..."), default: value }
108
+ }
109
+
110
+ const FUNCTION = /^\s*export\s+(?:default\s+)?(async\s+)?function\s*\*?\s*([\w$]+)\s*(?:<[^>]*>)?\s*\(([^)]*)\)|^\s*export\s+const\s+([\w$]+)\s*(?::[^=]+)?=\s*(async\s+)?\(([^)]*)\)\s*(?::[^=]+)?=>|^\s*(async\s+)?def\s+(\w+)\s*\(([^)]*)\)/gm
111
+
112
+ /** A file's exported functions: name → whether async, and their parameters */
113
+ export function exportedFunctions(text) {
114
+ const out = new Map()
115
+ for (const m of String(text ?? "").matchAll(FUNCTION)) {
116
+ const name = m[2] ?? m[4] ?? m[8]
117
+ if (name.startsWith("_")) continue
118
+ out.set(name, { async: Boolean(m[1] ?? m[5] ?? m[7]), params: splitParams(m[3] ?? m[6] ?? m[9] ?? "").map(param).filter((p) => p.name && p.name !== "self") })
119
+ }
120
+ return out
121
+ }
122
+ const REEXPORT = /^\s*export\s*\{([^}]*)\}/gm
123
+ const reexported = (text, name) => [...String(text ?? "").matchAll(REEXPORT)].some(([, list]) => list.split(",").some((n) => n.trim().split(/\s+as\s+/).at(-1) === name))
124
+
125
+ const calls = (text, name) => new RegExp(`(^|[^\\w$.])${name.replace(/\$/g, "\\$")}\\s*\\(`).test(text)
126
+ const names = (text, name) => new RegExp(`(^|[^\\w$])${name.replace(/\$/g, "\\$")}([^\\w$]|$)`).test(text)
127
+
128
+ const GENERATED = /(\.bundle\.|\.min\.|(^|\/)dist\/)/
129
+
130
+ /** `const x = call()` with x awaited later is deliberate: the work starts now, and is waited for */
131
+ function heldForLater(text, file) {
132
+ const held = /(?:const|let|var)\s+([\w$]+)\s*=/.exec(text)?.[1]
133
+ return Boolean(held) && new RegExp(`\\bawait\\s+${held}\\b|\\b${held}\\.(then|catch|finally)\\(|Promise\\.\\w+\\([^)]*\\b${held}\\b`).test(file)
134
+ }
135
+
136
+ /**
137
+ * The adversarial diff review: what this change does to code it didn't touch.
138
+ * A hazard is unhandled only while a caller outside the change still relies on
139
+ * the old shape: a change that updates its callers is handled.
140
+ * @returns {{ file: string, line?: number, hazard: string, why: string }[]}
141
+ */
142
+ export function reviewDiff(graph, diffs) {
143
+ const found = []
144
+ const changed = new Set(diffs.map((d) => d.rel))
145
+ const outside = (rel) => [...(graph.importedBy.get(rel) ?? [])].filter((by) => !changed.has(by) && !isTest(by))
146
+ for (const { rel, before, after } of diffs) {
147
+ if (isTest(rel) || !CODE.test(rel) || GENERATED.test(rel)) continue
148
+ const was = exportedFunctions(before)
149
+ const now = exportedFunctions(after)
150
+ for (const [name, old] of was) {
151
+ const users = outside(rel).filter((by) => names(graph.text(by), name))
152
+ if (!users.length) continue
153
+ const next = now.get(name)
154
+ if (!next) {
155
+ if (!reexported(after, name) && !new RegExp(`\\b${name}\\b`).test(String(after ?? ""))) found.push({ file: rel, hazard: "removed export", why: `${name} is gone but ${users[0]} still uses it` })
156
+ continue
157
+ }
158
+ const callers = users.filter((by) => calls(graph.text(by), name))
159
+ if (!callers.length) continue
160
+ const required = (f) => f.params.filter((p) => p.required).length
161
+ if (required(next) > required(old)) found.push({ file: rel, hazard: "broken signature", why: `${name} now needs ${required(next)} arguments; ${callers[0]} still passes the old ones` })
162
+ else if (next.params.length < old.params.length) found.push({ file: rel, hazard: "broken signature", why: `${name} lost a parameter; ${callers[0]} still calls it` })
163
+ else if (!old.async && next.async) {
164
+ const blind = callers.find((by) => graph.text(by).split("\n").some((line) => calls(line, name) && !/\b(await|return)\b|\.then\(/.test(line)))
165
+ if (blind) found.push({ file: rel, hazard: "now async", why: `${name} now returns a promise; ${blind} isn't changed to await it` })
166
+ }
167
+ for (const p of old.params) {
168
+ const q = next.params.find((x) => x.name === p.name)
169
+ if (q && p.default !== undefined && q.default !== undefined && p.default !== q.default) found.push({ file: rel, hazard: "altered default", why: `${name}'s ${p.name} default went from ${p.default} to ${q.default}; ${callers[0]} relies on it` })
170
+ }
171
+ }
172
+ if (after === null) continue
173
+ // What this file can call that returns a promise: its own, and what it imports
174
+ const pending = new Set([...now, ...[...String(after).matchAll(/\basync\s+function\s+([\w$]+)|(?:const|let)\s+([\w$]+)\s*=\s*async\b/g)].map((m) => [m[1] ?? m[2], { async: true }])].filter(([, f]) => f.async).map(([n]) => n))
175
+ for (const dep of graph.importsOf.get(rel) ?? []) for (const [n, f] of exportedFunctions(graph.text(dep))) if (f.async && names(after, n)) pending.add(n)
176
+ const added = addedLines(before, after)
177
+ const lines = String(after).split("\n")
178
+ // A call ending in a comma is an element of something, usually Promise.all
179
+ const element = (text) => /,\s*$/.test(text)
180
+ for (const { line, text } of added) {
181
+ if (COMMENT.test(text)) continue
182
+ for (const n of pending) {
183
+ const floating = new RegExp(`^\\s*${n.replace(/\$/g, "\\$")}\\s*\\(|=\\s*${n.replace(/\$/g, "\\$")}\\s*\\(`).test(text)
184
+ if (floating && !element(text) && !/=>\s*$/.test(lines[line - 2] ?? "") && !heldForLater(text, after) && !/\b(await|return|void|yield)\b|\.then\(|\.catch\(|Promise\.(all|race|allSettled)|=>\s*$/.test(text) && !/^\s*(async\s+)?(function|def)\b|^\s*export\b/.test(text)) found.push({ file: rel, line, hazard: "missing await", why: `${n}() returns a promise and nothing waits for it` })
185
+ }
186
+ if (/\.forEach\(\s*async\b/.test(text)) found.push({ file: rel, line, hazard: "race", why: "forEach doesn't wait for async callbacks, so these run unordered and errors are lost; use for…of or Promise.all" })
187
+ if (/\.map\(\s*async\b/.test(text) && !/Promise\.(all|allSettled)/.test(lines.slice(Math.max(0, line - 4), line).join(" "))) found.push({ file: rel, line, hazard: "race", why: "these promises are never awaited together; wrap in Promise.all" })
188
+ }
189
+ for (const { text } of addedLines(after, before)) {
190
+ const m = /\bawait\s+([\w$.]+)\s*\(/.exec(text)
191
+ // The same line with only the await gone
192
+ if (m && added.some((a) => a.text === text.replace(/\bawait\s+/, ""))) found.push({ file: rel, hazard: "missing await", why: `the change dropped the await on ${m[1]}()` })
193
+ }
194
+ }
195
+ return found
196
+ }
197
+
198
+ // A file that adds a way in from outside
199
+ const NEW_API = /(^|\/)(app\/api\/.+\/route\.[jt]sx?|pages\/api\/.+\.[jt]sx?|routes\/.+\.[jt]sx?)$|(^|\/)actions\/[^/]+\.[jt]sx?$/
200
+ const BOUNDARY = /\b(toThrow|rejects|assert\.(throws|rejects)|pytest\.raises|assertRaises|ValueError|TypeError|RangeError)\b|\b(40[0-9]|41[0-9]|42[0-9])\b|\b(null|undefined|None|NaN|Infinity)\b|\b(empty|invalid|missing|malformed|unauthori[sz]ed|forbidden|boundary|negative|overflow|too (long|large|big)|zero)\b|\(\s*(""|''|\[\]|\{\})\s*[,)]/i
201
+
202
+ /** Whether this change adds something a caller can reach: a route, an action, or a new exported function */
203
+ export function newSurface(diffs) {
204
+ const out = []
205
+ for (const { rel, before, after } of diffs) {
206
+ if (after === null || isTest(rel) || !CODE.test(rel)) continue
207
+ if (before === null && NEW_API.test(rel)) out.push(rel)
208
+ else {
209
+ const was = exportedFunctions(before)
210
+ if ([...exportedFunctions(after).keys()].some((n) => !was.has(n))) out.push(rel)
211
+ }
212
+ }
213
+ return out
214
+ }
215
+
216
+ /** Whether this change's test lines try a bad input: an error, an empty value, a boundary */
217
+ export function hasBoundaryTest(diffs) {
218
+ return diffs.some(({ rel, before, after }) => isTest(rel) && addedLines(before, after).some(({ text }) => !COMMENT.test(text) && BOUNDARY.test(text)))
219
+ }
220
+
221
+ const BLANK = /^(none|n\/?a|tbd|todo|nothing|no|unknown|-+)\.?$/i
222
+ const MIN_TEXT = 12
223
+ const clean = (value) => (typeof value === "string" ? value.replace(/\s+/g, " ").trim().slice(0, 300) : "")
224
+ const said = (value) => clean(value).length >= MIN_TEXT && !BLANK.test(clean(value))
225
+ export const MIN_FAILURES = 2
226
+
227
+ /**
228
+ * The pre-mortem a plan must carry: how this could fail and what will prove it
229
+ * doesn't, what else shares this surface, and which bad inputs were thought
230
+ * through. `covered_by` turns a hypothesis into an obligation: the file must
231
+ * exist before the plan can read verified. Code can't judge the thinking, so
232
+ * it refuses blanks and makes each claim cost a test.
233
+ * @returns {{ premortem?: object, problem?: string }}
234
+ */
235
+ export function checkPremortem(input, steps) {
236
+ if (!input && steps < 2) return {}
237
+ const name = (what) => ({ problem: `This plan needs a pre-mortem before anything is built: premortem.${what}.` })
238
+ const failures = (Array.isArray(input?.failures) ? input.failures : []).filter((f) => said(f?.what)).map((f) => ({ what: clean(f.what), coveredBy: clean(f.covered_by ?? f.coveredBy) }))
239
+ const distinct = new Set(failures.map((f) => f.what.toLowerCase()))
240
+ if (distinct.size < MIN_FAILURES) return name(`failures: at least ${MIN_FAILURES} different ways this could crash or misbehave, each with covered_by, the test file that will prove it can't`)
241
+ const open = failures.find((f) => !f.coveredBy)
242
+ if (open) return name(`failures: "${open.what}" needs covered_by, the test file that will prove it can't happen`)
243
+ const radius = (Array.isArray(input?.blast_radius) ? input.blast_radius : []).filter(said).map(clean)
244
+ if (!radius.length) return name("blast_radius: the other features, tables or routes that share this surface")
245
+ const negatives = (Array.isArray(input?.negatives) ? input.negatives : []).filter(said).map(clean)
246
+ if (!negatives.length) return name("negatives: the bad inputs to handle (nulls, empty states, boundary values, timeouts)")
247
+ return { premortem: { failures: failures.slice(0, 6), blastRadius: radius.slice(0, 12), negatives: negatives.slice(0, 12) } }
248
+ }
@@ -0,0 +1,130 @@
1
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, unwatchFile, watchFile, writeFileSync } from "node:fs"
2
+ import { dirname, join, resolve } from "node:path"
3
+
4
+ import { kriyaHome } from "./paths.js"
5
+
6
+ // Skills turned off, per project or everywhere, so their catalog entries stop
7
+ // costing tokens on every request. Nothing is moved or edited: a provider at
8
+ // rank 0 (below every root DSH scans, 100+, and Kriya's own, 100) reports each
9
+ // turned-off name with both invocation surfaces off, so it wins the duplicate
10
+ // name under the registry's own rules and the catalog, the `skill` tool and
11
+ // `/name` all leave it out. Turning it back on removes that entry.
12
+
13
+ /** A skill name as DSH accepts it: kebab-case. */
14
+ const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
15
+
16
+ export const switchesFile = () => join(kriyaHome(), "skill-switches.json")
17
+
18
+ /** The folder a project is keyed by: the nearest ancestor with .git (DSH's own rule), else the folder. */
19
+ export function projectRoot(cwd) {
20
+ const start = resolve(cwd)
21
+ for (let dir = start; ; dir = dirname(dir)) {
22
+ if (existsSync(join(dir, ".git"))) return safeRealpath(dir)
23
+ if (dirname(dir) === dir) return safeRealpath(start)
24
+ }
25
+ }
26
+
27
+ function safeRealpath(path) {
28
+ try {
29
+ return realpathSync(path)
30
+ } catch {
31
+ return path
32
+ }
33
+ }
34
+
35
+ const names = (value) => (Array.isArray(value) ? value.filter((n) => typeof n === "string" && SKILL_NAME.test(n)) : [])
36
+
37
+ /** The saved switches; a missing or unreadable file means every skill is on. */
38
+ export function readSwitches() {
39
+ try {
40
+ const raw = JSON.parse(readFileSync(switchesFile(), "utf8"))
41
+ const projects = {}
42
+ for (const [root, list] of Object.entries(raw?.projects ?? {})) if (names(list).length) projects[root] = names(list)
43
+ return { everywhere: names(raw?.everywhere), projects }
44
+ } catch {
45
+ return { everywhere: [], projects: {} }
46
+ }
47
+ }
48
+
49
+ function writeSwitches(switches) {
50
+ const file = switchesFile()
51
+ mkdirSync(dirname(file), { recursive: true })
52
+ const temp = `${file}.${process.pid}.tmp`
53
+ writeFileSync(temp, `${JSON.stringify({ version: 1, ...switches }, null, 2)}\n`, { mode: 0o600 })
54
+ renameSync(temp, file)
55
+ }
56
+
57
+ /** Each turned-off name for `cwd`: "here" (this project) or "everywhere". */
58
+ export function offFor(cwd) {
59
+ const switches = readSwitches()
60
+ const off = new Map()
61
+ for (const name of switches.projects[projectRoot(cwd)] ?? []) off.set(name, "here")
62
+ for (const name of switches.everywhere) off.set(name, "everywhere")
63
+ return off
64
+ }
65
+
66
+ // Invalidators of the providers registered in this process (kriya-tools), so
67
+ // a switch from the Skills page reaches the agent's next step at once
68
+ const listeners = new Set()
69
+
70
+ export class SwitchError extends Error {}
71
+
72
+ /**
73
+ * Sets one skill's switch for the project `cwd` is in.
74
+ * @param {string} cwd
75
+ * @param {string} name
76
+ * @param {"on" | "off-here" | "off-everywhere"} state "on" clears both
77
+ */
78
+ export function setSkillSwitch(cwd, name, state) {
79
+ if (typeof name !== "string" || !SKILL_NAME.test(name)) throw new SwitchError("That isn't a skill name.")
80
+ if (!["on", "off-here", "off-everywhere"].includes(state)) throw new SwitchError("Say on, off-here or off-everywhere.")
81
+ const root = projectRoot(cwd)
82
+ const switches = readSwitches()
83
+ const here = new Set(switches.projects[root] ?? [])
84
+ const everywhere = new Set(switches.everywhere)
85
+ here.delete(name)
86
+ everywhere.delete(name)
87
+ if (state === "off-here") here.add(name)
88
+ if (state === "off-everywhere") everywhere.add(name)
89
+ if (here.size) switches.projects[root] = [...here].sort()
90
+ else delete switches.projects[root]
91
+ writeSwitches({ everywhere: [...everywhere].sort(), projects: switches.projects })
92
+ for (const invalidate of listeners) invalidate()
93
+ return { name, state, project: root }
94
+ }
95
+
96
+ /**
97
+ * The DSH skill provider (registered by plugins/kriya-tools): one rank-0
98
+ * entry per turned-off name, invisible to the model and to `/name`.
99
+ * @param {{ signal?: AbortSignal, invalidate?: () => void }} [control]
100
+ */
101
+ export function switchProvider(control = {}) {
102
+ if (control.invalidate) {
103
+ const invalidate = control.invalidate
104
+ listeners.add(invalidate)
105
+ // `kriya skills off` in a terminal is another process: polled
106
+ const file = switchesFile()
107
+ watchFile(file, { interval: 2000, persistent: false }, invalidate)
108
+ control.signal?.addEventListener("abort", () => {
109
+ listeners.delete(invalidate)
110
+ unwatchFile(file, invalidate)
111
+ })
112
+ }
113
+ return {
114
+ name: "kriya-switches",
115
+ async list({ cwd } = {}) {
116
+ return [...offFor(cwd ?? process.cwd())].map(([name, where]) => ({
117
+ name,
118
+ description: where === "here" ? "Turned off for this project in Kriya Harness." : "Turned off in Kriya Harness.",
119
+ invocation: { modelInvocable: false, userInvocable: false },
120
+ source: "custom",
121
+ provider: "kriya-switches",
122
+ rank: 0,
123
+ locator: null,
124
+ }))
125
+ },
126
+ async get() {
127
+ return undefined
128
+ },
129
+ }
130
+ }
package/src/store.js ADDED
@@ -0,0 +1,58 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
2
+ import { join } from "node:path"
3
+
4
+ import { kriyaHome } from "./paths.js"
5
+
6
+ // The device sign-in, kept on this machine only: one JSON file readable by
7
+ // the same OS user (0600 in a 0700 directory), the property DSH's own
8
+ // credentials-local store gives (DSH_DISTRIBUTION §3, P-AUTH). The server
9
+ // keeps only the token's sha256.
10
+
11
+ const FILE = "device.json"
12
+
13
+ const path = () => join(kriyaHome(), FILE)
14
+
15
+ export function ensureHome() {
16
+ const home = kriyaHome()
17
+ mkdirSync(home, { recursive: true, mode: 0o700 })
18
+ if (process.platform !== "win32") chmodSync(home, 0o700)
19
+ return home
20
+ }
21
+
22
+ /** @returns {{ url: string, token: string, deviceId: string } | null} */
23
+ export function readDevice() {
24
+ if (!existsSync(path())) return null
25
+ try {
26
+ const value = JSON.parse(readFileSync(path(), "utf8"))
27
+ if (typeof value?.url === "string" && typeof value?.token === "string") return value
28
+ } catch {
29
+ // A broken file is the same as no sign-in; `kriya login` rewrites it
30
+ }
31
+ return null
32
+ }
33
+
34
+ /** @param {{ url: string, token: string, deviceId: string }} device */
35
+ export function writeDevice(device) {
36
+ ensureHome()
37
+ writeFileSync(path(), JSON.stringify(device, null, 2) + "\n", { mode: 0o600 })
38
+ if (process.platform !== "win32") chmodSync(path(), 0o600)
39
+ }
40
+
41
+ export function deleteDevice() {
42
+ rmSync(path(), { force: true })
43
+ }
44
+
45
+ /** Normalises the Kriya address the person gives: https only (http for localhost), no path. */
46
+ export function kriyaUrl(raw) {
47
+ let url
48
+ try {
49
+ url = new URL(String(raw))
50
+ } catch {
51
+ throw new Error(`Not a web address: ${raw}`)
52
+ }
53
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)
54
+ if (url.protocol !== "https:" && !(local && url.protocol === "http:")) {
55
+ throw new Error("Use the https:// address of your Kriya account.")
56
+ }
57
+ return url.origin
58
+ }
package/src/strict.js ADDED
@@ -0,0 +1,124 @@
1
+ import { existsSync, readFileSync } from "node:fs"
2
+ import { join } from "node:path"
3
+
4
+ // The strict loop (KRIYA_STRICT_LOOP=on, `--strict-loop`; Kriya repository,
5
+ // docs/kriya-harness/harness_upgradation/KRIYA_CODING_HARNESS_REPORT.md): the
6
+ // pure half. Task kinds and their planning bounds, what counts as weakening a
7
+ // test or silencing the compiler, and the fast rungs that run before the
8
+ // person's check. Every rung can only fail a step early: "passing" still
9
+ // means the person's confirmed check exited 0.
10
+
11
+ export const TASK_KINDS = ["surgical_bugfix", "feature_dag", "deep_research", "refactoring_migration"]
12
+ // The most plan steps a kind may have: a one-line fix doesn't need a graph
13
+ export const PLAN_LIMITS = { surgical_bugfix: 2, deep_research: 3, feature_dag: 7, refactoring_migration: 7 }
14
+
15
+ /** A task's kind from the words of its goal, when the plan names none. Fixed patterns, no model. */
16
+ export function taskKind(text) {
17
+ const t = String(text ?? "").toLowerCase()
18
+ if (/\b(research|investigate|compare|survey)\b/.test(t)) return "deep_research"
19
+ if (/\b(refactor|migrat\w*|rename|restructure|extract|upgrade)\b/.test(t)) return "refactoring_migration"
20
+ if (/\b(fix|bug|crash\w*|regression|broken|fail\w*|error)\b/.test(t)) return "surgical_bugfix"
21
+ return "feature_dag"
22
+ }
23
+
24
+ const COMMENT = /^\s*(\/\/|#|\*|\/\*)/
25
+ const ASSERTION = /\b(assert\w*|expect|should|t\.(is|not|deepEqual|true|false|throws)|self\.assert\w*|require\.\w+)\s*[.(]/g
26
+ const SKIPPED = /\b(it|test|describe)\.(skip|todo|only)\b|\bx(it|describe)\(|@pytest\.mark\.(skip|xfail)|\bt\.Skip\(|#\[ignore\]/g
27
+ const count = (text, re) => (text.match(re) ?? []).length
28
+ const live = (text) => text.split("\n").filter((line) => !COMMENT.test(line)).join("\n")
29
+
30
+ /**
31
+ * Why a test file's new text is weaker than its old text, or undefined.
32
+ * Adding tests is fine (the owner's "grade on originals" ruling, HU-F-20): only
33
+ * fewer live assertions, more skips, or a deleted file count.
34
+ * @param {string} before @param {string | null} after null when the file is gone
35
+ */
36
+ export function weakenedTest(before, after) {
37
+ if (after === null) return "deleted"
38
+ const [was, now] = [live(before), live(after)]
39
+ if (count(now, ASSERTION) < count(was, ASSERTION)) return `fewer assertions (${count(was, ASSERTION)} to ${count(now, ASSERTION)})`
40
+ if (count(now, SKIPPED) > count(was, SKIPPED)) return "tests skipped"
41
+ return undefined
42
+ }
43
+
44
+ const SILENCERS = [
45
+ ["`any`", /(:\s*any\b|\bas any\b|<any>)/g],
46
+ ["a compiler suppression", /@ts-(ignore|nocheck|expect-error)|eslint-disable|#\s*type:\s*ignore|#\s*noqa/g],
47
+ ["an empty catch", /catch\s*(\([^)]*\))?\s*\{\s*\}|except[^\n]*:\s*\n?\s*pass\b/g],
48
+ ]
49
+ const SOURCE = /\.(m?[jt]sx?|cjs|py)$/
50
+
51
+ /** What this change adds to quiet the compiler or swallow an error, as words; empty when nothing */
52
+ export function silencers(before, after) {
53
+ return SILENCERS.filter(([, re]) => count(after, re) > count(before ?? "", re)).map(([name]) => name)
54
+ }
55
+ export const isSource = (rel) => SOURCE.test(rel)
56
+
57
+ const quote = (text) => `'${text.replace(/'/g, `'\\''`)}'`
58
+ const MAX_FILES = 40
59
+ const read = (file) => {
60
+ try {
61
+ return readFileSync(file, "utf8")
62
+ } catch {
63
+ return undefined
64
+ }
65
+ }
66
+
67
+ /** The command that parses these files without running them, or undefined; `node --check` and Python's ast only read */
68
+ export function syntaxCommand(paths) {
69
+ const js = paths.filter((p) => /\.(m?js|cjs)$/.test(p)).slice(0, MAX_FILES)
70
+ const py = paths.filter((p) => p.endsWith(".py")).slice(0, MAX_FILES)
71
+ const json = paths.filter((p) => p.endsWith(".json")).slice(0, MAX_FILES)
72
+ const parts = [
73
+ ...js.map((p) => `node --check ${quote(p)}`),
74
+ ...py.map((p) => `python3 -c 'import ast,sys; ast.parse(open(sys.argv[1]).read(), sys.argv[1])' ${quote(p)}`),
75
+ ...json.map((p) => `node -e 'JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"))' ${quote(p)}`),
76
+ ]
77
+ return parts.length ? parts.join(" && ") : undefined
78
+ }
79
+
80
+ /** How this project runs named test files, or undefined when it can't be told */
81
+ function testCommand(root, tests) {
82
+ const scripts = (() => {
83
+ try {
84
+ return JSON.stringify(JSON.parse(read(join(root, "package.json")) ?? "{}").scripts ?? {})
85
+ } catch {
86
+ return "{}"
87
+ }
88
+ })()
89
+ const files = tests.map(quote).join(" ")
90
+ if (/vitest/.test(scripts)) return `npx --no-install vitest run ${files}`
91
+ if (/jest/.test(scripts)) return `npx --no-install jest ${files}`
92
+ if (/node --test/.test(scripts)) return `node --test ${files}`
93
+ if (tests.every((t) => t.endsWith(".py"))) return `python3 -m pytest -q ${files}`
94
+ return undefined
95
+ }
96
+
97
+ /**
98
+ * The rungs under the person's check, cheapest first, for the files that
99
+ * changed. `names` keeps a rung to this work: a type error elsewhere in the
100
+ * project is older than this change and isn't the builder's to fix.
101
+ * @param {string} root the repository's top folder
102
+ * @param {string[]} changed paths relative to it
103
+ * @param {string[]} [tests] test files the change affects (src/recon.js)
104
+ * @param {string[]} [neighbours] the blast radius's other test files (defensive)
105
+ * @returns {Array<{ level: number, name: string, command: string, kind?: string, names?: string[] }>}
106
+ */
107
+ export function ladder(root, changed, tests = [], neighbours = []) {
108
+ const present = changed.filter((rel) => existsSync(join(root, rel)))
109
+ const rungs = []
110
+ const syntax = syntaxCommand(present)
111
+ if (syntax) rungs.push({ level: 1, name: "syntax", command: syntax, kind: "syntax" })
112
+ if (present.some((rel) => /\.tsx?$/.test(rel)) && existsSync(join(root, "tsconfig.json")) && existsSync(join(root, "node_modules", ".bin", "tsc")))
113
+ rungs.push({ level: 2, name: "types", command: "npx --no-install tsc --noEmit", kind: "type", names: present })
114
+ if (tests.length) {
115
+ const command = testCommand(root, tests.slice(0, 10))
116
+ if (command) rungs.push({ level: 3, name: "affected tests", command })
117
+ }
118
+ // Slower, so after the tests of the code itself: a failure there costs seconds, not minutes
119
+ if (neighbours.length) {
120
+ const command = testCommand(root, neighbours)
121
+ if (command) rungs.push({ level: 3, name: "neighbouring tests", command })
122
+ }
123
+ return rungs
124
+ }