@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,313 @@
1
+ import { execFile } from "node:child_process"
2
+ import { createHash } from "node:crypto"
3
+ import { existsSync, mkdirSync, realpathSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs"
4
+ import { homedir } from "node:os"
5
+ import { dirname, join, parse, relative, resolve, sep } from "node:path"
6
+
7
+ import { kriyaHome } from "./paths.js"
8
+
9
+ // Step checkpoints and undo (H14b, K3; KRIYA_LOOP.md in the Kriya
10
+ // repository). Before the agent changes files, the working tree (tracked
11
+ // and untracked files, never ignored ones) is saved as a commit on Kriya's
12
+ // own ref, refs/kriya/checkpoints/<session>/<n>. `kriya undo` puts the
13
+ // working tree back one step. What's never touched: the person's branches,
14
+ // tags, stash, HEAD and index (every git call that stages uses a separate
15
+ // index file), ignored files, and anything under .git but Kriya's refs and
16
+ // git's object store. Before an undo changes a file, the state it replaces
17
+ // is saved too (refs/kriya/undone/<n>), so an undo can be undone.
18
+
19
+ export const REF_ROOT = "refs/kriya"
20
+ export const KEEP = 100 // checkpoints kept per session; older refs are dropped
21
+ const MB = 1024 * 1024
22
+ const SESSION = /^[A-Za-z0-9_-]{1,128}$/
23
+ // Neutral identity, so a checkpoint never depends on (or pretends to be) the person's git config
24
+ const IDENTITY = {
25
+ GIT_AUTHOR_NAME: "Kriya Harness",
26
+ GIT_AUTHOR_EMAIL: "harness@kriya.invalid",
27
+ GIT_COMMITTER_NAME: "Kriya Harness",
28
+ GIT_COMMITTER_EMAIL: "harness@kriya.invalid",
29
+ }
30
+
31
+ export class CheckpointError extends Error {}
32
+
33
+ // Folders that aren't git repositories (2026-11-04, owner: "it created the
34
+ // files … why it was not showing at all"): checkpoints, undo and the Changes
35
+ // tab use a private git store in ~/.kriya/shadow/<folder hash>.git whose
36
+ // work tree is the folder. Nothing is written into the folder itself (no
37
+ // .git); dependency, build and cache folders are left out; the home folder
38
+ // and filesystem roots are never tracked. A real repository always wins.
39
+ const shadows = new Map() // folder → its store's git dir
40
+ export const SHADOW_EXCLUDES = [
41
+ "node_modules/", ".npm-cache/", ".npm/", ".pnpm-store/", ".yarn/", "bower_components/",
42
+ "dist/", "build/", "out/", ".next/", ".nuxt/", ".svelte-kit/", ".turbo/", ".cache/", ".parcel-cache/", ".vite/",
43
+ "coverage/", "target/", ".venv/", "venv/", "__pycache__/", "*.pyc", ".gradle/", ".idea/", ".vscode/",
44
+ ".DS_Store", "Thumbs.db", "*.log", "playwright-report/", "test-results/", ".playwright/", ".git/",
45
+ ]
46
+ // The first snapshot of a big folder reads every file; later ones only what changed
47
+ const SHADOW_TIMEOUT_MS = 60_000
48
+
49
+ function git(cwd, args, { env, input, timeout, raw = false } = {}) {
50
+ // raw: git as the folder itself sees it, never through Kriya's store
51
+ const store = raw ? undefined : shadows.get(cwd)
52
+ const full = store ? ["--git-dir", store, ...args] : args
53
+ return new Promise((done, fail) => {
54
+ const child = execFile("git", full, { cwd, env: { ...process.env, ...env }, encoding: "buffer", maxBuffer: 256 * MB, ...(timeout && { timeout }) }, (error, stdout, stderr) => {
55
+ if (error) fail(new CheckpointError(stderr.toString().trim().split("\n")[0] || error.message))
56
+ else done(stdout)
57
+ })
58
+ if (input !== undefined) child.stdin.end(input)
59
+ })
60
+ }
61
+ const text = async (cwd, args, options) => (await git(cwd, args, options)).toString().trim()
62
+
63
+ /** The repository's top folder, or undefined when `cwd` isn't in one. */
64
+ export async function repoRoot(cwd) {
65
+ try {
66
+ return await text(cwd, ["rev-parse", "--show-toplevel"], { raw: true })
67
+ } catch {
68
+ return undefined
69
+ }
70
+ }
71
+
72
+ /** Whether a folder is too broad to track: the home folder or a filesystem root */
73
+ export function tooBroad(folder, home = homedir()) {
74
+ const real = resolve(folder)
75
+ return real === resolve(home) || real === parse(real).root
76
+ }
77
+
78
+ /** The private store's git dir for a folder that isn't a repository */
79
+ export const shadowDir = (folder) => join(kriyaHome(), "shadow", `${createHash("sha256").update(folder).digest("hex").slice(0, 16)}.git`)
80
+
81
+ /**
82
+ * Where checkpoints for `cwd` live: its repository's top folder, or, for a
83
+ * folder in no repository, the folder itself with its private store set up
84
+ * (undefined for the home folder or a filesystem root, or without git).
85
+ * @returns {Promise<{ root: string, shadow: boolean } | undefined>}
86
+ */
87
+ export async function trackedRoot(cwd) {
88
+ const repo = await repoRoot(cwd)
89
+ if (repo) {
90
+ // A folder that became a repository (git init) is the repository's again
91
+ shadows.delete(repo)
92
+ return { root: repo, shadow: false }
93
+ }
94
+ let folder
95
+ try {
96
+ folder = realpathSync(cwd)
97
+ } catch {
98
+ return undefined
99
+ }
100
+ if (tooBroad(folder)) return undefined
101
+ const store = shadowDir(folder)
102
+ try {
103
+ if (!existsSync(join(store, "HEAD"))) {
104
+ mkdirSync(dirname(store), { recursive: true })
105
+ await git(dirname(store), ["init", "-q", "--bare", store])
106
+ await git(dirname(store), ["--git-dir", store, "config", "core.bare", "false"])
107
+ await git(dirname(store), ["--git-dir", store, "config", "core.worktree", folder])
108
+ // Kriya's store keeps no reflogs or hooks of its own
109
+ await git(dirname(store), ["--git-dir", store, "config", "core.logAllRefUpdates", "false"])
110
+ mkdirSync(join(store, "info"), { recursive: true })
111
+ writeFileSync(join(store, "info", "exclude"), `# Kriya Harness: never tracked in this folder\n${SHADOW_EXCLUDES.join("\n")}\n`)
112
+ }
113
+ } catch {
114
+ return undefined
115
+ }
116
+ shadows.set(folder, store)
117
+ return { root: folder, shadow: true }
118
+ }
119
+
120
+ // Kriya's own index per repository, kept between snapshots so `add -A` only
121
+ // rereads what changed; outside the repository, so .git gains nothing else
122
+ const indexFile = (root) => join(kriyaHome(), "checkpoint-index", `${createHash("sha256").update(root).digest("hex").slice(0, 16)}.index`)
123
+
124
+ /** The working tree as a tree object: tracked and untracked files, not ignored ones. */
125
+ export async function snapshot(root) {
126
+ const index = indexFile(root)
127
+ mkdirSync(dirname(index), { recursive: true })
128
+ const env = { GIT_INDEX_FILE: index }
129
+ await git(root, ["add", "-A", "--", "."], { env, ...(shadows.has(root) && { timeout: SHADOW_TIMEOUT_MS }) })
130
+ return text(root, ["write-tree"], { env })
131
+ }
132
+
133
+ const seq = (ref) => Number(ref.split("/").pop())
134
+
135
+ /** Kriya's checkpoints, newest first: { ref, commit, tree, at, label, session, kind } */
136
+ export async function listCheckpoints(root) {
137
+ const out = await text(root, ["for-each-ref", "--format=%(refname)%09%(objectname)%09%(tree)%09%(creatordate:iso-strict)%09%(contents:subject)", REF_ROOT])
138
+ if (!out) return []
139
+ return out
140
+ .split("\n")
141
+ .map((line) => {
142
+ const [ref, commit, tree, at, label] = line.split("\t")
143
+ const parts = ref.split("/")
144
+ const kind = parts[2] === "undone" ? "undone" : "checkpoint"
145
+ return { ref, commit, tree, at, label, kind, session: kind === "checkpoint" ? parts[3] : undefined, n: seq(ref) }
146
+ })
147
+ .sort((a, b) => b.at.localeCompare(a.at) || b.n - a.n)
148
+ }
149
+
150
+ async function save(root, prefix, tree, label, now) {
151
+ const existing = (await listCheckpoints(root)).filter((c) => c.ref.startsWith(`${prefix}/`))
152
+ const n = existing.reduce((max, c) => Math.max(max, c.n), 0) + 1
153
+ const date = now().toISOString()
154
+ const commit = await text(root, ["commit-tree", tree, "-m", label], {
155
+ env: { ...IDENTITY, GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date },
156
+ })
157
+ const ref = `${prefix}/${String(n).padStart(6, "0")}`
158
+ await git(root, ["update-ref", ref, commit])
159
+ // Keep the newest KEEP; dropping a ref leaves its objects to git's own gc
160
+ for (const old of existing.sort((a, b) => b.n - a.n).slice(KEEP - 1)) await git(root, ["update-ref", "-d", old.ref])
161
+ return { ref, commit, tree, at: date, label }
162
+ }
163
+
164
+ /**
165
+ * Saves the working tree before a change, unless it's the same as the
166
+ * session's last checkpoint.
167
+ * @returns {Promise<undefined | { ref: string, commit: string, tree: string, created: boolean }>} undefined where nothing can be tracked
168
+ */
169
+ export async function checkpoint(cwd, sessionId, label, now = () => new Date()) {
170
+ if (!SESSION.test(sessionId)) throw new CheckpointError("That session id can't name a checkpoint.")
171
+ const root = (await trackedRoot(cwd))?.root
172
+ if (!root) return undefined
173
+ const tree = await snapshot(root)
174
+ const prefix = `${REF_ROOT}/checkpoints/${sessionId}`
175
+ const last = (await listCheckpoints(root)).find((c) => c.ref.startsWith(`${prefix}/`))
176
+ if (last?.tree === tree) return { ...last, created: false }
177
+ return { ...(await save(root, prefix, tree, String(label).replace(/\s+/g, " ").slice(0, 200), now)), created: true }
178
+ }
179
+
180
+ /** The files that differ between two trees, by what restoring `to` does to each. */
181
+ async function differences(root, from, to) {
182
+ const out = (await git(root, ["diff-tree", "-r", "-z", "--no-renames", "--name-status", from, to])).toString()
183
+ const fields = out.split("\0").filter(Boolean)
184
+ const write = []
185
+ const remove = []
186
+ for (let i = 0; i + 1 < fields.length; i += 2) (fields[i] === "D" ? remove : write).push(fields[i + 1])
187
+ return { write, remove }
188
+ }
189
+
190
+ /**
191
+ * One step back from the files as they are: if they match a checkpoint
192
+ * (a previous undo landed there), the newest older one that differs;
193
+ * otherwise (new work since) the newest that differs. Never forward.
194
+ * @param {Array<{ tree: string }>} checkpoints newest first
195
+ */
196
+ export function stepBack(checkpoints, current) {
197
+ const here = checkpoints.findIndex((c) => c.tree === current)
198
+ return checkpoints.slice(here + 1).find((c) => c.tree !== current)
199
+ }
200
+
201
+ /**
202
+ * Puts the working tree back to a checkpoint. With no `target`, one step
203
+ * back (stepBack).
204
+ * @param {string} cwd
205
+ * @param {{ target?: number, now?: () => Date }} [options] target: a number from `kriya undo --list`
206
+ */
207
+ export async function undo(cwd, { target, now = () => new Date() } = {}) {
208
+ const root = (await trackedRoot(cwd))?.root
209
+ if (!root) throw new CheckpointError("Kriya doesn't track this folder (your home folder or a drive root), so there are no checkpoints to go back to.")
210
+ const all = await listCheckpoints(root)
211
+ const current = await snapshot(root)
212
+ const chosen = target === undefined ? stepBack(all.filter((c) => c.kind === "checkpoint"), current) : all[target - 1]
213
+ if (!chosen) throw new CheckpointError(target === undefined ? "Nothing to undo: no checkpoint differs from the files as they are." : `There's no checkpoint ${target}; kriya undo --list shows them.`)
214
+ if (chosen.tree === current) return { root, restored: chosen, changed: 0, saved: undefined }
215
+ return { root, restored: chosen, ...(await restore(root, current, chosen.tree, `before undo to ${chosen.label}`, now)) }
216
+ }
217
+
218
+ /**
219
+ * Loop v2: puts the working tree back to `tree` (a checkpoint's), the way
220
+ * undo does, keeping what it replaces on refs/kriya/undone first.
221
+ * @returns {Promise<undefined | { changed: number, saved?: object }>} undefined where nothing can be tracked
222
+ */
223
+ export async function restoreTree(cwd, tree, label, now = () => new Date()) {
224
+ const root = (await trackedRoot(cwd))?.root
225
+ if (!root) return undefined
226
+ const current = await snapshot(root)
227
+ return current === tree ? { changed: 0, saved: undefined } : restore(root, current, tree, String(label).replace(/\s+/g, " ").slice(0, 200), now)
228
+ }
229
+
230
+ async function restore(root, current, tree, label, now) {
231
+ const { write, remove } = await differences(root, current, tree)
232
+ // What this replaces is kept first: nothing is lost
233
+ const saved = await save(root, `${REF_ROOT}/undone`, current, label, now)
234
+
235
+ if (write.length) {
236
+ const index = join(dirname(indexFile(root)), `${createHash("sha256").update(root).digest("hex").slice(0, 16)}.restore.index`)
237
+ const env = { GIT_INDEX_FILE: index }
238
+ await git(root, ["read-tree", tree], { env })
239
+ await git(root, ["checkout-index", "-f", "-z", "--stdin"], { env, input: `${write.join("\0")}\0` })
240
+ try {
241
+ unlinkSync(index)
242
+ } catch {
243
+ // Already gone
244
+ }
245
+ }
246
+ for (const path of remove) {
247
+ const file = resolve(root, path)
248
+ if (relative(root, file).startsWith("..")) continue
249
+ try {
250
+ unlinkSync(file)
251
+ } catch {
252
+ continue
253
+ }
254
+ // Folders the undo emptied go too, never the root
255
+ for (let dir = dirname(file); dir !== root && dir.startsWith(root + sep); dir = dirname(dir)) {
256
+ try {
257
+ rmdirSync(dir)
258
+ } catch {
259
+ break
260
+ }
261
+ }
262
+ }
263
+ // Kriya's index now matches the restored files
264
+ await snapshot(root)
265
+ return { changed: write.length + remove.length, saved }
266
+ }
267
+
268
+ /* ───────── the Changes tab in a folder with no repository (src/changes.js) ───────── */
269
+
270
+ /**
271
+ * The files before the session's first change: the oldest checkpoint that
272
+ * is the session's own or was taken in the folder after the session began
273
+ * (`since`, ms). A step's builder is a child agent whose checkpoints carry
274
+ * its own id, so time is what ties them to the session that started it.
275
+ */
276
+ export async function sessionBase(root, sessionId, since) {
277
+ if (!SESSION.test(sessionId)) return undefined
278
+ const started = Number.isFinite(since) ? since : undefined
279
+ const mine = (await listCheckpoints(root)).filter((c) => c.kind === "checkpoint" && (c.session === sessionId || (started !== undefined && Date.parse(c.at) >= started)))
280
+ return mine.sort((a, b) => a.at.localeCompare(b.at) || a.n - b.n)[0]?.tree
281
+ }
282
+
283
+ /** Files that differ between two trees: { path, status, from?, added?, deleted?, binary? } */
284
+ export async function treeChanges(root, from, to) {
285
+ const names = (await git(root, ["diff-tree", "-r", "-z", "-M", "--name-status", from, to])).toString().split("\0").filter(Boolean)
286
+ const counts = new Map()
287
+ const numstat = (await git(root, ["diff-tree", "-r", "-z", "-M", "--numstat", from, to])).toString().split("\0")
288
+ for (let i = 0; i < numstat.length; i++) {
289
+ const m = /^(-|\d+)\t(-|\d+)\t(.*)$/s.exec(numstat[i])
290
+ if (!m) continue
291
+ let path = m[3]
292
+ if (path === "") {
293
+ i++
294
+ path = numstat[++i]
295
+ }
296
+ counts.set(path, m[1] === "-" ? { binary: true } : { added: Number(m[1]), deleted: Number(m[2]) })
297
+ }
298
+ const files = []
299
+ for (let i = 0; i < names.length; ) {
300
+ const code = names[i++]
301
+ const renamed = code[0] === "R" || code[0] === "C"
302
+ const fromPath = renamed ? names[i++] : undefined
303
+ const path = names[i++]
304
+ const status = code[0] === "A" ? "added" : code[0] === "D" ? "deleted" : renamed ? "renamed" : "modified"
305
+ files.push({ path, status, ...(fromPath && { from: fromPath }), ...(counts.get(path) ?? {}) })
306
+ }
307
+ return files
308
+ }
309
+
310
+ /** One file's unified diff between two trees */
311
+ export async function treeFileDiff(root, from, to, path, fromPath) {
312
+ return (await git(root, ["diff", "--no-color", "-M", from, to, "--", ...(fromPath ? [fromPath] : []), path])).toString()
313
+ }