@kriya-ai/harness 0.0.0-stage → 0.2.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 (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,92 @@
1
+ import { existsSync, lstatSync, mkdirSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
2
+ import { dirname, join, resolve } from "node:path"
3
+
4
+ import { kriyaHome, PACKAGE_ROOT } from "./paths.js"
5
+ import { ensureHome } from "./store.js"
6
+
7
+ // The Kriya profiles under the Kriya home (DSH_HOME). Each is a DSH profile
8
+ // directory: package.json naming its bundles in order, and a link from its
9
+ // node_modules to this package, which DSH then resolves as the "kriya"
10
+ // bundle (bundle/cordis.patch.yml). The person's own cordis.patch.yml in a
11
+ // profile is never touched, so DSH's settings pages keep working.
12
+
13
+ export const PROFILES = {
14
+ // `kriya`: DSH's local Web UI
15
+ kriya: ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-web-app", "@kriya-ai/harness"],
16
+ // `kriya run "…"`: one job, final answer printed
17
+ "kriya-run": ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-headless", "@kriya-ai/harness"],
18
+ // `kriya acp`: DSH's ACP server over stdio, for editors (HD-13)
19
+ "kriya-acp": ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-acp-app", "@kriya-ai/harness"],
20
+ }
21
+
22
+ function manifest(name, bundles) {
23
+ return (
24
+ JSON.stringify(
25
+ { name: `${name}-profile`, private: true, dsh: { profile: { bundles } } },
26
+ null,
27
+ 2
28
+ ) + "\n"
29
+ )
30
+ }
31
+
32
+ // Packages of this repository a profile resolves by name: the bundle itself
33
+ // and the plugins the bundle mounts (the Web UI brand, approvals from the
34
+ // phone, the session mirror, Kriya skills and memory, the Skills page, the Changes tab)
35
+ export const LINKED = {
36
+ "@kriya-ai/harness": PACKAGE_ROOT,
37
+ "@kriya-ai/harness-brand": join(PACKAGE_ROOT, "plugins", "brand"),
38
+ "@kriya-ai/harness-approvals": join(PACKAGE_ROOT, "plugins", "approvals"),
39
+ "@kriya-ai/harness-mirror": join(PACKAGE_ROOT, "plugins", "mirror"),
40
+ "@kriya-ai/harness-tools": join(PACKAGE_ROOT, "plugins", "kriya-tools"),
41
+ "@kriya-ai/harness-skills": join(PACKAGE_ROOT, "plugins", "skills"),
42
+ "@kriya-ai/harness-changes": join(PACKAGE_ROOT, "plugins", "changes"),
43
+ "@kriya-ai/harness-overview": join(PACKAGE_ROOT, "plugins", "overview"),
44
+ "@kriya-ai/harness-progress": join(PACKAGE_ROOT, "plugins", "progress"),
45
+ "@kriya-ai/harness-preview": join(PACKAGE_ROOT, "plugins", "preview"),
46
+ "@kriya-ai/harness-graph": join(PACKAGE_ROOT, "plugins", "graph"),
47
+ "@kriya-ai/harness-browser": join(PACKAGE_ROOT, "plugins", "browser"),
48
+ "@kriya-ai/harness-remote": join(PACKAGE_ROOT, "plugins", "remote"),
49
+ "@kriya-ai/harness-sessions": join(PACKAGE_ROOT, "plugins", "sessions"),
50
+ "@kriya-ai/harness-rea": join(PACKAGE_ROOT, "plugins", "rea"),
51
+ "@kriya-ai/harness-router": join(PACKAGE_ROOT, "plugins", "router"),
52
+ "@kriya-ai/harness-projects": join(PACKAGE_ROOT, "plugins", "projects"),
53
+ "@kriya-ai/harness-fs-freshness": join(PACKAGE_ROOT, "plugins", "fs-freshness"),
54
+ "@kriya-ai/harness-loop": join(PACKAGE_ROOT, "plugins", "loop"),
55
+ "@kriya-ai/harness-budget": join(PACKAGE_ROOT, "plugins", "budget"),
56
+ "@kriya-ai/harness-anchor": join(PACKAGE_ROOT, "plugins", "anchor"),
57
+ "@kriya-ai/harness-edit": join(PACKAGE_ROOT, "plugins", "edit"),
58
+ }
59
+
60
+ function link(dir, name, target) {
61
+ const path = join(dir, "node_modules", ...name.split("/"))
62
+ mkdirSync(dirname(path), { recursive: true })
63
+ let current = null
64
+ try {
65
+ current = lstatSync(path).isSymbolicLink() ? resolve(dirname(path), readlinkSync(path)) : "not-a-link"
66
+ } catch {
67
+ // Missing: created below
68
+ }
69
+ if (current === resolve(target)) return
70
+ // Only ever our own link (or a stale one from an older install) is replaced
71
+ if (current !== null) rmSync(path, { force: true, recursive: current === "not-a-link" })
72
+ symlinkSync(target, path, process.platform === "win32" ? "junction" : "dir")
73
+ }
74
+
75
+ /** Creates or repairs one profile; returns its directory. Idempotent. */
76
+ export function ensureProfile(name) {
77
+ const bundles = PROFILES[name]
78
+ if (!bundles) throw new Error(`Unknown Kriya profile ${name}`)
79
+ ensureHome()
80
+ const dir = join(kriyaHome(), "profiles", name)
81
+ mkdirSync(dir, { recursive: true })
82
+ // Rewritten each time: the bundle list is this package's, not the person's
83
+ writeFileSync(join(dir, "package.json"), manifest(name, bundles))
84
+ for (const [packageName, target] of Object.entries(LINKED)) link(dir, packageName, target)
85
+ return dir
86
+ }
87
+
88
+ export function ensureProfiles() {
89
+ return Object.keys(PROFILES).map(ensureProfile)
90
+ }
91
+
92
+ export const hasProfile = (name) => existsSync(join(kriyaHome(), "profiles", name, "package.json"))
@@ -0,0 +1,104 @@
1
+ import { existsSync, readdirSync, realpathSync, statSync } from "node:fs"
2
+ import { homedir } from "node:os"
3
+ import { delimiter, join, resolve, sep } from "node:path"
4
+
5
+ // The Projects page (plugins/projects): folders on this computer that look
6
+ // like projects, so the person opens one as a workspace in a click, as
7
+ // Claude's desktop app lists its folders. Read-only: names, paths and
8
+ // times; nothing inside a project is read beyond the markers below.
9
+ //
10
+ // Where it looks: the usual folders under home, one level deep, and one
11
+ // more level for group folders (~/Developer/<org>/<repo>). macOS asks the
12
+ // person before an app reads Desktop, Documents or Downloads, so those are
13
+ // only searched when named in KRIYA_PROJECT_ROOTS (paths, separated like
14
+ // PATH), which also adds any other folder.
15
+
16
+ export const ROOTS = ["Developer", "Projects", "projects", "Code", "code", "src", "dev", "repos", "Repos", "workspace", "Workspace", "GitHub", "git", "Sites", "work"]
17
+
18
+ // A folder with one of these is a project
19
+ export const MARKERS = [
20
+ ".git",
21
+ "package.json",
22
+ "pyproject.toml",
23
+ "requirements.txt",
24
+ "Cargo.toml",
25
+ "go.mod",
26
+ "pom.xml",
27
+ "build.gradle",
28
+ "build.gradle.kts",
29
+ "Gemfile",
30
+ "composer.json",
31
+ "Package.swift",
32
+ "pubspec.yaml",
33
+ "deno.json",
34
+ "CMakeLists.txt",
35
+ "Makefile",
36
+ ]
37
+
38
+ const SKIP = new Set(["node_modules", "Library", "Applications", "vendor", "target", "dist", "build"])
39
+ export const LIMIT = 500
40
+ // Directory listings per scan: keeps a huge home from stalling the page
41
+ const BUDGET = 4000
42
+
43
+ const isProject = (dir) => MARKERS.some((marker) => existsSync(join(dir, marker)))
44
+
45
+ function children(dir, budget) {
46
+ if (budget.left-- <= 0) return []
47
+ try {
48
+ return readdirSync(dir, { withFileTypes: true })
49
+ .filter((entry) => (entry.isDirectory() || entry.isSymbolicLink()) && !entry.name.startsWith(".") && !SKIP.has(entry.name))
50
+ .map((entry) => join(dir, entry.name))
51
+ } catch {
52
+ // Unreadable (permissions, vanished): not a place to look
53
+ return []
54
+ }
55
+ }
56
+
57
+ function describe(path, root, home) {
58
+ try {
59
+ const real = realpathSync(path)
60
+ const stat = statSync(real)
61
+ if (!stat.isDirectory()) return undefined
62
+ return {
63
+ name: real.split(sep).pop(),
64
+ path: real,
65
+ shown: real === home ? "~" : real.startsWith(home + sep) ? "~" + real.slice(home.length) : real,
66
+ root,
67
+ git: existsSync(join(real, ".git")),
68
+ modifiedAt: stat.mtime.toISOString(),
69
+ }
70
+ } catch {
71
+ return undefined
72
+ }
73
+ }
74
+
75
+ /**
76
+ * The project folders, most recently changed first.
77
+ * @param {{ home?: string, cwd?: string, extra?: string }} [where] extra: KRIYA_PROJECT_ROOTS
78
+ * @returns {{ projects: Array<{ name: string, path: string, shown: string, root: string, git: boolean, modifiedAt: string, here?: boolean }>, roots: string[], truncated: boolean }}
79
+ */
80
+ export function findProjects({ home = homedir(), cwd = process.cwd(), extra = process.env.KRIYA_PROJECT_ROOTS ?? "" } = {}) {
81
+ const roots = [
82
+ ...extra.split(delimiter).filter(Boolean).map((path) => resolve(home, path.replace(/^~(?=$|\/)/, home))),
83
+ ...ROOTS.map((name) => join(home, name)),
84
+ ].filter((dir, i, all) => all.indexOf(dir) === i && existsSync(dir))
85
+ const budget = { left: BUDGET }
86
+ const found = new Map()
87
+ const add = (path, root) => {
88
+ const project = describe(path, root, home)
89
+ if (project && !found.has(project.path)) found.set(project.path, project)
90
+ }
91
+ for (const root of roots) {
92
+ const label = root.startsWith(home + sep) ? "~" + root.slice(home.length) : root
93
+ for (const dir of children(root, budget)) {
94
+ if (found.size >= LIMIT) break
95
+ if (isProject(dir)) add(dir, label)
96
+ else for (const inner of children(dir, budget)) if (isProject(inner)) add(inner, label)
97
+ }
98
+ }
99
+ // The folder Kriya Harness was started in, project or not
100
+ const here = describe(cwd, "Started here", home)
101
+ if (here) found.set(here.path, { ...(found.get(here.path) ?? here), here: true })
102
+ const projects = [...found.values()].sort((a, b) => Number(Boolean(b.here)) - Number(Boolean(a.here)) || b.modifiedAt.localeCompare(a.modifiedAt))
103
+ return { projects: projects.slice(0, LIMIT), roots, truncated: projects.length > LIMIT || budget.left <= 0 }
104
+ }
package/src/recon.js ADDED
@@ -0,0 +1,244 @@
1
+ import { execFileSync } from "node:child_process"
2
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
3
+ import { dirname, extname, join, normalize, relative, resolve, sep } from "node:path"
4
+
5
+ // Code reconnaissance (KRIYA_RECON=on, `--recon`): look before reading. The
6
+ // outline lists a file's symbols with their line numbers; impact lists the
7
+ // files that import a file. shortcut: both read source with fixed patterns,
8
+ // not a parser, so a symbol built at run time or an import through an alias
9
+ // is missed; a real parser would need a dependency, worth it only if real
10
+ // runs show these misses matter.
11
+
12
+ export const MAX_READ_LINES = 400
13
+ const MAX_SYMBOLS = 200
14
+ const MAX_FILES = 3000
15
+ const MAX_BYTES = 1_000_000
16
+ const SKIP = new Set(["node_modules", ".git", "dist", "build", "out", "target", "coverage", "vendor", "venv", ".venv", "__pycache__", ".next"])
17
+
18
+ const PATTERNS = {
19
+ js: [
20
+ [/^\s*(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s*\*?\s*([\w$]+)/, "function"],
21
+ [/^\s*(?:export\s+(?:default\s+)?)?(?:abstract\s+)?class\s+([\w$]+)/, "class"],
22
+ [/^\s*(?:export\s+)?interface\s+([\w$]+)/, "interface"],
23
+ [/^\s*(?:export\s+)?type\s+([\w$]+)\s*[=<]/, "type"],
24
+ [/^\s*(?:export\s+)?enum\s+([\w$]+)/, "enum"],
25
+ [/^(?:export\s+)?(?:const|let|var)\s+([\w$]+)/, "const"],
26
+ [/^\s{2,4}(?:public\s+|private\s+|protected\s+|static\s+|async\s+)*(?!if\b|for\b|while\b|switch\b|return\b|catch\b)([\w$]+)\s*\([^)]*\)\s*(?::[^={]+)?\{\s*$/, "method"],
27
+ ],
28
+ py: [
29
+ [/^\s*(?:async\s+)?def\s+(\w+)/, "function"],
30
+ [/^\s*class\s+(\w+)/, "class"],
31
+ ],
32
+ go: [
33
+ [/^func\s+(?:\([^)]*\)\s*)?(\w+)/, "function"],
34
+ [/^type\s+(\w+)/, "type"],
35
+ ],
36
+ rs: [
37
+ [/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+(\w+)/, "function"],
38
+ [/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:struct|enum|trait)\s+(\w+)/, "type"],
39
+ ],
40
+ }
41
+ const FAMILY = { ".js": "js", ".mjs": "js", ".cjs": "js", ".jsx": "js", ".ts": "js", ".tsx": "js", ".mts": "js", ".py": "py", ".go": "go", ".rs": "rs" }
42
+
43
+ export class ReconError extends Error {}
44
+
45
+ /** A path the agent gave, inside the session's folder */
46
+ export function insideFolder(cwd, path) {
47
+ const file = resolve(cwd, String(path ?? ""))
48
+ if (file !== cwd && !file.startsWith(cwd + sep)) throw new ReconError("That path is outside this session's folder.")
49
+ return file
50
+ }
51
+
52
+ /** The symbols of source text, in order: { line, kind, name } */
53
+ export function outlineText(text, extension) {
54
+ const patterns = PATTERNS[FAMILY[extension]]
55
+ if (!patterns) return []
56
+ const out = []
57
+ text.split("\n").forEach((line, i) => {
58
+ for (const [re, kind] of patterns) {
59
+ const match = re.exec(line)
60
+ if (match) {
61
+ out.push({ line: i + 1, kind, name: match[1] })
62
+ break
63
+ }
64
+ }
65
+ })
66
+ return out
67
+ }
68
+
69
+ /** One file's size and symbols, so the agent can read only the lines it needs */
70
+ export function outline(cwd, path) {
71
+ const file = insideFolder(cwd, path)
72
+ if (!existsSync(file) || !statSync(file).isFile()) throw new ReconError(`No file ${path}.`)
73
+ if (statSync(file).size > MAX_BYTES) throw new ReconError(`${path} is over 1 MB; use grep.`)
74
+ const text = readFileSync(file, "utf8")
75
+ const symbols = outlineText(text, extname(file))
76
+ return { path: relative(cwd, file), lines: text.split("\n").length, symbols: symbols.slice(0, MAX_SYMBOLS), ...(symbols.length > MAX_SYMBOLS && { cut: symbols.length - MAX_SYMBOLS }) }
77
+ }
78
+
79
+ function sourceFiles(root) {
80
+ try {
81
+ const listed = execFileSync("git", ["ls-files", "-co", "--exclude-standard"], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 })
82
+ return listed.split("\n").filter((f) => FAMILY[extname(f)]).slice(0, MAX_FILES)
83
+ } catch {
84
+ const out = []
85
+ const walk = (dir) => {
86
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
87
+ if (out.length >= MAX_FILES || entry.name.startsWith(".") || SKIP.has(entry.name)) continue
88
+ const path = join(dir, entry.name)
89
+ if (entry.isDirectory()) walk(path)
90
+ else if (FAMILY[extname(entry.name)]) out.push(relative(root, path))
91
+ }
92
+ }
93
+ walk(root)
94
+ return out
95
+ }
96
+ }
97
+
98
+ const SPECIFIER = /(?:from\s+|import\s+|require\(\s*|import\(\s*|vi\.mock\(\s*)["']([^"']+)["']/g
99
+ const PY_IMPORT = /^\s*(?:from\s+([\w.]+)\s+import|import\s+([\w.]+))/gm
100
+ const stem = (rel) => rel.replace(/\.[^./]+$/, "").replace(/\/index$/, "")
101
+
102
+ // tsconfig's `paths` ("@/*": ["./*"]): how most TypeScript projects import across folders
103
+ function pathAliases(root) {
104
+ try {
105
+ const text = readFileSync(join(root, "tsconfig.json"), "utf8").replace(/^\s*\/\/.*$/gm, "")
106
+ const paths = JSON.parse(text).compilerOptions?.paths ?? {}
107
+ return Object.entries(paths).flatMap(([from, [to]]) => (from.endsWith("/*") && to?.endsWith("/*") ? [{ from: from.slice(0, -1), to: normalize(to.slice(0, -1)) }] : []))
108
+ } catch {
109
+ return []
110
+ }
111
+ }
112
+
113
+ /**
114
+ * The project's import graph, read once: who imports whom, by what each
115
+ * import statement resolves to (relative paths, tsconfig aliases, Python's
116
+ * dotted modules). `text` hands out what was read.
117
+ * @returns {{ root: string, files: string[], importedBy: Map<string, Set<string>>, importsOf: Map<string, Set<string>>, text: (rel: string) => string }}
118
+ */
119
+ export function importGraph(root) {
120
+ const files = sourceFiles(root)
121
+ const stems = new Map(files.map((rel) => [stem(normalize(rel)), rel]))
122
+ const aliases = pathAliases(root)
123
+ const texts = new Map()
124
+ const importedBy = new Map()
125
+ const importsOf = new Map()
126
+ const edge = (from, to) => {
127
+ if (!to || to === from) return
128
+ if (!importsOf.has(from)) importsOf.set(from, new Set())
129
+ if (!importedBy.has(to)) importedBy.set(to, new Set())
130
+ importsOf.get(from).add(to)
131
+ importedBy.get(to).add(from)
132
+ }
133
+ for (const rel of files) {
134
+ let text = ""
135
+ try {
136
+ const file = join(root, rel)
137
+ if (statSync(file).size <= MAX_BYTES) text = readFileSync(file, "utf8")
138
+ } catch {
139
+ // Listed but gone: nothing to read
140
+ }
141
+ texts.set(rel, text)
142
+ for (const [, spec] of text.matchAll(SPECIFIER)) {
143
+ if (spec.startsWith(".")) edge(rel, stems.get(stem(normalize(join(dirname(rel), spec)))))
144
+ else {
145
+ const alias = aliases.find((a) => spec.startsWith(a.from))
146
+ if (alias) edge(rel, stems.get(stem(normalize(join(alias.to, spec.slice(alias.from.length))))))
147
+ }
148
+ }
149
+ if (rel.endsWith(".py"))
150
+ for (const [, a, b] of text.matchAll(PY_IMPORT)) {
151
+ const dotted = (a ?? b).replaceAll(".", sep)
152
+ edge(rel, stems.get(dotted) ?? [...stems.keys()].filter((k) => k.endsWith(`${sep}${dotted}`)).map((k) => stems.get(k))[0])
153
+ }
154
+ }
155
+ return { root, files, importedBy, importsOf, text: (rel) => texts.get(rel) ?? "" }
156
+ }
157
+
158
+ /** Project files that import `target`, by what their import statements resolve to */
159
+ export function importers(root, target, graph = importGraph(root)) {
160
+ return [...(graph.importedBy.get(normalize(target)) ?? [])]
161
+ }
162
+
163
+ const TEST = /(^|\/)(tests?|__tests__|spec|specs)\/|\.(test|spec)\.[^/]+$|(^|\/)test_[^/]+\.py$|_test\.py$/
164
+
165
+ /** Test files a change touches: changed ones and the ones importing a changed file */
166
+ export function affectedTests(root, changed) {
167
+ const tests = new Set(changed.filter((rel) => TEST.test(rel) && existsSync(join(root, rel))))
168
+ for (const rel of changed.filter((f) => FAMILY[extname(f)] && !TEST.test(f)).slice(0, 20)) for (const by of importers(root, rel)) if (TEST.test(by)) tests.add(by)
169
+ return [...tests].sort()
170
+ }
171
+
172
+ // A file that defines shared data: everything naming its tables is in reach, imported or not
173
+ const SCHEMA = /(^|\/)(schema\.(ts|js|prisma|py|rb)|models?\.(py|ts|js))$|(^|\/)migrations?\//
174
+ const ROUTE = /(^|\/)(app\/api\/(.+)\/route\.[jt]sx?|pages\/api\/(.+)\.[jt]sx?)$/
175
+ const MAX_SYMBOLS_TRACED = 30
176
+ const MAX_TESTS = 40
177
+
178
+ /** The names a change touches: symbols whose definition line is new or gone */
179
+ export function changedSymbols(before, after, extension) {
180
+ const lines = (text) => new Set(String(text ?? "").split("\n"))
181
+ const [was, now] = [lines(before), lines(after)]
182
+ const named = (text, other) => {
183
+ const rows = String(text ?? "").split("\n")
184
+ return outlineText(text ?? "", extension).filter((s) => s.kind !== "method" && !other.has(rows[s.line - 1])).map((s) => s.name)
185
+ }
186
+ return [...new Set([...named(before, now), ...named(after, was)])]
187
+ }
188
+
189
+ const word = (name) => new RegExp(`(^|[^\\w$])${name.replace(/[$]/g, "\\$")}([^\\w$]|$)`)
190
+
191
+ /**
192
+ * What a change can reach: files that import it (near, then through them),
193
+ * files naming a changed schema table or exported symbol, callers of a
194
+ * changed API route, and the test suites of all of those, nearest first.
195
+ * @param {{ rel: string, before: string | null, after: string | null }[]} diffs
196
+ * @returns {{ direct: string[], transitive: string[], symbols: string[], callers: string[], tests: string[], cut: number }}
197
+ */
198
+ export function blastRadius(graph, diffs, { depth = 3 } = {}) {
199
+ const changed = new Set(diffs.map((d) => d.rel))
200
+ const seen = new Map([...changed].map((rel) => [rel, 0]))
201
+ let frontier = [...changed]
202
+ for (let level = 1; level <= depth && frontier.length; level++) {
203
+ const next = []
204
+ for (const rel of frontier) for (const by of graph.importedBy.get(rel) ?? []) if (!seen.has(by)) (seen.set(by, level), next.push(by))
205
+ frontier = next
206
+ }
207
+ const symbols = [...new Set(diffs.flatMap((d) => changedSymbols(d.before, d.after, extname(d.rel))))].slice(0, MAX_SYMBOLS_TRACED)
208
+ const shared = diffs.filter((d) => SCHEMA.test(d.rel)).flatMap((d) => changedSymbols(d.before, d.after, extname(d.rel)))
209
+ const named = (names) => {
210
+ const res = names.filter((n) => n.length > 3).map(word)
211
+ return res.length ? graph.files.filter((rel) => !changed.has(rel) && res.some((re) => re.test(graph.text(rel)))) : []
212
+ }
213
+ // A table is shared by whoever names it; an ordinary symbol, only tests are looked for by name
214
+ const schemaUsers = named(shared)
215
+ for (const rel of schemaUsers) if (!seen.has(rel)) seen.set(rel, depth)
216
+ const urls = diffs.flatMap((d) => {
217
+ const m = ROUTE.exec(d.rel)
218
+ const path = m && (m[3] ?? m[4])
219
+ return path ? [`/api/${path.replace(/\[[^\]]+\]/g, "").replace(/\/$/, "")}`] : []
220
+ })
221
+ const callers = graph.files.filter((rel) => !changed.has(rel) && urls.some((url) => graph.text(rel).includes(url)))
222
+ for (const rel of callers) if (!seen.has(rel)) seen.set(rel, 1)
223
+ const byName = named(symbols).filter((rel) => TEST.test(rel))
224
+ for (const rel of byName) if (!seen.has(rel)) seen.set(rel, depth)
225
+ const rows = [...seen.entries()].sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0]))
226
+ const tests = rows.filter(([rel]) => TEST.test(rel) && existsSync(join(graph.root, rel))).map(([rel]) => rel)
227
+ return {
228
+ direct: rows.filter(([rel, d]) => d === 1 && !TEST.test(rel)).map(([rel]) => rel),
229
+ transitive: rows.filter(([rel, d]) => d > 1 && !TEST.test(rel)).map(([rel]) => rel),
230
+ symbols,
231
+ callers,
232
+ tests: tests.slice(0, MAX_TESTS),
233
+ cut: Math.max(0, tests.length - MAX_TESTS),
234
+ }
235
+ }
236
+
237
+ /** A long read's first page, in the read tool's own format, saying what's left; undefined when it fits */
238
+ export function readPage({ path, offset, lines, totalLines }) {
239
+ if (!(lines?.length > MAX_READ_LINES)) return undefined
240
+ const page = lines.slice(0, MAX_READ_LINES)
241
+ const end = page.at(-1).number
242
+ const body = page.map((line) => `${line.number}: ${line.text}`).join("\n")
243
+ return `<path>${path}</path>\n<type>file</type>\n<content>\n${body}\n\n(Showing lines ${offset}-${end} of ${totalLines}. Use offset=${end + 1} to continue, or code_outline to find the part you need.)\n</content>`
244
+ }
package/src/rules.js ADDED
@@ -0,0 +1,139 @@
1
+ import { createHash } from "node:crypto"
2
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"
3
+ import { dirname, join } from "node:path"
4
+
5
+ import { signature } from "./failure.js"
6
+ import { kriyaHome } from "./paths.js"
7
+ import { projectRoot } from "./skill-switches.js"
8
+
9
+ // Kriya loop v2, R_{n+1} = R_n ⊕ rule(fail) (KRIYA_LOOP_V2.md): the same
10
+ // failure (command, class, first named line) seen twice becomes a proposed
11
+ // rule. Code writes the proposal from a fixed template; it reaches the
12
+ // agent only after the person confirms it (`kriya rules confirm`), and may
13
+ // be reworded then. Kept in ~/.kriya/rules/, never in the project, so the
14
+ // agent can't write a "confirmed" rule with its file tools and Read only
15
+ // stays read-only.
16
+
17
+ export const SEEN_TWICE = 2
18
+ const KEEP_SEEN = 200
19
+ const RULE = 300
20
+ export const PROMPT_LIMIT = 2000
21
+
22
+ export class RulesError extends Error {}
23
+
24
+ const fileFor = (root) => join(kriyaHome(), "rules", `${createHash("sha256").update(root).digest("hex").slice(0, 16)}.json`)
25
+
26
+ function load(root) {
27
+ try {
28
+ const value = JSON.parse(readFileSync(fileFor(root), "utf8"))
29
+ if (value && Array.isArray(value.proposed) && Array.isArray(value.confirmed)) return { seen: {}, dismissed: [], ...value }
30
+ } catch {
31
+ // None yet
32
+ }
33
+ return { version: 1, root, seen: {}, proposed: [], confirmed: [], dismissed: [] }
34
+ }
35
+
36
+ function store(root, value) {
37
+ const file = fileFor(root)
38
+ mkdirSync(dirname(file), { recursive: true })
39
+ const temp = `${file}.${process.pid}.tmp`
40
+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 })
41
+ renameSync(temp, file)
42
+ }
43
+
44
+ const ADVICE = {
45
+ syntax: "Code in this project has failed to parse; re-read each edited file for syntax before finishing a step.",
46
+ type: "Check types, names and call signatures against their definitions before finishing a step.",
47
+ assertion: "Read the failing test's expectation before changing code, and fix the code, not the test.",
48
+ "tests changed": "Never change existing tests or the check's configuration to make the check pass; fix the code.",
49
+ environment: "The check needs something the machine lacks; stop and tell the person instead of retrying.",
50
+ timeout: "The check has timed out; keep changes small and look for loops that never end.",
51
+ unknown: "Read the check's whole output before changing code.",
52
+ }
53
+
54
+ /** The proposed rule's text: a fixed sentence for the class, and the evidence */
55
+ export function ruleText(command, failure) {
56
+ const line = signature(command, failure).split("\0")[2]
57
+ return `${ADVICE[failure.kind] ?? ADVICE.unknown} (\`${command}\` failed twice this way${line ? `: ${line}` : ""})`.slice(0, RULE)
58
+ }
59
+
60
+ /**
61
+ * Notes one failed check. On the SEEN_TWICE-th time a signature is seen, a
62
+ * rule is proposed, once (not again after it's confirmed or dismissed).
63
+ * @returns {undefined | { text: string }} the new proposal, if this made one
64
+ */
65
+ export function noteFailure(root, command, failure, now = () => new Date()) {
66
+ const value = load(root)
67
+ const sig = signature(command, failure)
68
+ const count = (value.seen[sig]?.count ?? 0) + 1
69
+ value.seen[sig] = { count, at: now().toISOString() }
70
+ const entries = Object.entries(value.seen)
71
+ if (entries.length > KEEP_SEEN) value.seen = Object.fromEntries(entries.sort((a, b) => b[1].at.localeCompare(a[1].at)).slice(0, KEEP_SEEN))
72
+ const known = [...value.proposed, ...value.confirmed].some((r) => r.sig === sig) || value.dismissed.includes(sig)
73
+ let made
74
+ if (count >= SEEN_TWICE && !known) {
75
+ made = { sig, kind: failure.kind, text: ruleText(command, failure), at: now().toISOString() }
76
+ value.proposed.push(made)
77
+ }
78
+ store(root, value)
79
+ return made && { text: made.text }
80
+ }
81
+
82
+ /** The project's proposed and confirmed rules */
83
+ export function listRules(cwd) {
84
+ const { proposed, confirmed } = load(projectRoot(cwd))
85
+ return { proposed: proposed.map((r) => r.text), confirmed: confirmed.map((r) => r.text) }
86
+ }
87
+
88
+ function pick(value, n) {
89
+ const at = Number(n) - 1
90
+ if (!Number.isInteger(at) || at < 0 || at >= value.proposed.length) throw new RulesError(`There's no proposed rule ${n}; kriya rules lists them.`)
91
+ return at
92
+ }
93
+
94
+ /** The person confirms proposal n (CLI only; no tool calls this), optionally in their own words */
95
+ export function confirmRule(cwd, n, text, now = () => new Date()) {
96
+ const root = projectRoot(cwd)
97
+ const value = load(root)
98
+ const at = pick(value, n)
99
+ const [rule] = value.proposed.splice(at, 1)
100
+ const words = typeof text === "string" ? text.replace(/\s+/g, " ").trim() : ""
101
+ if (words.length > RULE) throw new RulesError(`A rule is at most ${RULE} characters.`)
102
+ value.confirmed.push({ ...rule, text: words || rule.text, confirmedAt: now().toISOString() })
103
+ store(root, value)
104
+ return words || rule.text
105
+ }
106
+
107
+ /** The person dismisses proposal n: that failure is never proposed again */
108
+ export function dismissRule(cwd, n) {
109
+ const root = projectRoot(cwd)
110
+ const value = load(root)
111
+ const [rule] = value.proposed.splice(pick(value, n), 1)
112
+ value.dismissed.push(rule.sig)
113
+ store(root, value)
114
+ return rule.text
115
+ }
116
+
117
+ /** The person removes confirmed rule n */
118
+ export function forgetRule(cwd, n) {
119
+ const root = projectRoot(cwd)
120
+ const value = load(root)
121
+ const at = Number(n) - 1
122
+ if (!Number.isInteger(at) || at < 0 || at >= value.confirmed.length) throw new RulesError(`There's no confirmed rule ${n}; kriya rules lists them.`)
123
+ const [rule] = value.confirmed.splice(at, 1)
124
+ value.dismissed.push(rule.sig)
125
+ store(root, value)
126
+ return rule.text
127
+ }
128
+
129
+ /** The confirmed rules as prompt lines, newest kept when they don't all fit */
130
+ export function confirmedRules(cwd) {
131
+ const lines = []
132
+ let size = 0
133
+ for (const { text } of load(projectRoot(cwd)).confirmed.toReversed()) {
134
+ if (size + text.length > PROMPT_LIMIT) break
135
+ lines.unshift(`- ${text}`)
136
+ size += text.length
137
+ }
138
+ return lines
139
+ }