@picassohq/cli 0.0.0-stage → 1.0.2

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 (232) hide show
  1. package/agents/browser_agent.yaml +53 -0
  2. package/agents/code_reviewer.yaml +49 -0
  3. package/agents/codebase_investigator.yaml +70 -0
  4. package/agents/design_auditor.yaml +50 -0
  5. package/agents/devex_auditor.yaml +50 -0
  6. package/agents/doc_writer.yaml +54 -0
  7. package/agents/engineering_architect.yaml +51 -0
  8. package/agents/generalist.yaml +55 -0
  9. package/agents/migration_planner.yaml +51 -0
  10. package/agents/product_reviewer.yaml +48 -0
  11. package/agents/qa_operator.yaml +52 -0
  12. package/agents/release_engineer.yaml +50 -0
  13. package/agents/security_auditor.yaml +62 -0
  14. package/agents/test_writer.yaml +52 -0
  15. package/assets/first-light-lockup.png +0 -0
  16. package/assets/first-light-tagline.png +0 -0
  17. package/assets/house/README.md +26 -0
  18. package/assets/house/auraone-banner.png +0 -0
  19. package/assets/house/auraone-logo.png +0 -0
  20. package/assets/house/kiro-prism-banner.png +0 -0
  21. package/assets/house/kiro-prism-logo.png +0 -0
  22. package/assets/house/picasso-banner.png +0 -0
  23. package/assets/house/picasso-logo.png +0 -0
  24. package/assets/wordmark-app.png +0 -0
  25. package/assets/wordmark-tight.png +0 -0
  26. package/assets/wordmark.png +0 -0
  27. package/design/styles.css +1042 -0
  28. package/dist/build-info.json +37 -0
  29. package/dist/index.js +3062 -0
  30. package/goals/cli-hardening.yaml +40 -0
  31. package/goals/repo-maintenance.yaml +40 -0
  32. package/package.json +49 -4
  33. package/runtime/dsh/picasso-ecosystem.community.amendments.yml +24 -0
  34. package/runtime/dsh/picasso-ecosystem.community.json +185 -0
  35. package/runtime/dsh/picasso-ecosystem.community.patch.yml +40 -0
  36. package/runtime/dsh/picasso-ecosystem.cordis.patch.yml +143 -0
  37. package/runtime/dsh/picasso-isolation.patch.yml +25 -0
  38. package/runtime/dsh/picasso-providers.patch.yml +373 -0
  39. package/runtime/dsh/picasso-runtime.cordis.yml +738 -0
  40. package/runtime/dsh/picasso-sdk.patch.yml +204 -0
  41. package/runtime/engine-manifest.json +215 -0
  42. package/runtime/package.json +6 -0
  43. package/runtime/packages/picasso-cache-probe/cordis.patch.yml +5 -0
  44. package/runtime/packages/picasso-cache-probe/index.js +477 -0
  45. package/runtime/packages/picasso-cache-probe/package.json +38 -0
  46. package/runtime/packages/picasso-commands/cordis.patch.yml +4 -0
  47. package/runtime/packages/picasso-commands/fresh-review.js +573 -0
  48. package/runtime/packages/picasso-commands/index.js +497 -0
  49. package/runtime/packages/picasso-commands/package.json +28 -0
  50. package/runtime/packages/picasso-instructions/conflicts.js +115 -0
  51. package/runtime/packages/picasso-instructions/formats.js +145 -0
  52. package/runtime/packages/picasso-instructions/frontmatter.js +175 -0
  53. package/runtime/packages/picasso-instructions/glob.js +114 -0
  54. package/runtime/packages/picasso-instructions/globals.js +90 -0
  55. package/runtime/packages/picasso-instructions/imports.js +123 -0
  56. package/runtime/packages/picasso-instructions/index.js +326 -0
  57. package/runtime/packages/picasso-instructions/modes.js +64 -0
  58. package/runtime/packages/picasso-instructions/package.json +30 -0
  59. package/runtime/packages/picasso-instructions/parse.js +134 -0
  60. package/runtime/packages/picasso-instructions/report.js +161 -0
  61. package/runtime/packages/picasso-instructions/resolve.js +939 -0
  62. package/runtime/packages/picasso-instructions/scan.js +181 -0
  63. package/runtime/packages/picasso-instructions/settings.js +150 -0
  64. package/runtime/packages/picasso-instructions/skills.js +345 -0
  65. package/runtime/packages/picasso-lean-context/cordis.patch.yml +13 -0
  66. package/runtime/packages/picasso-lean-context/index.js +6280 -0
  67. package/runtime/packages/picasso-lean-context/package.json +26 -0
  68. package/runtime/packages/picasso-lean-context/read-image-recovery.js +306 -0
  69. package/runtime/packages/picasso-lean-context/timeline.js +418 -0
  70. package/runtime/packages/picasso-librarian/classify.js +146 -0
  71. package/runtime/packages/picasso-librarian/cordis.patch.yml +10 -0
  72. package/runtime/packages/picasso-librarian/index.js +878 -0
  73. package/runtime/packages/picasso-librarian/notes.js +159 -0
  74. package/runtime/packages/picasso-librarian/package.json +34 -0
  75. package/runtime/packages/picasso-librarian/state.js +478 -0
  76. package/runtime/packages/picasso-memory/index.js +1184 -0
  77. package/runtime/packages/picasso-memory/package.json +21 -0
  78. package/runtime/packages/picasso-model-router/connections.js +912 -0
  79. package/runtime/packages/picasso-model-router/cordis.patch.yml +17 -0
  80. package/runtime/packages/picasso-model-router/index.js +1083 -0
  81. package/runtime/packages/picasso-model-router/package.json +30 -0
  82. package/runtime/packages/picasso-options/cordis.patch.yml +4 -0
  83. package/runtime/packages/picasso-options/index.js +263 -0
  84. package/runtime/packages/picasso-options/package.json +28 -0
  85. package/runtime/packages/picasso-progress-reports/cordis.patch.yml +10 -0
  86. package/runtime/packages/picasso-progress-reports/index.js +267 -0
  87. package/runtime/packages/picasso-progress-reports/package.json +30 -0
  88. package/runtime/packages/picasso-progress-reports/report.js +235 -0
  89. package/runtime/packages/picasso-sdk-server/aside.js +142 -0
  90. package/runtime/packages/picasso-sdk-server/connections.js +38 -0
  91. package/runtime/packages/picasso-sdk-server/context-timeline.js +27 -0
  92. package/runtime/packages/picasso-sdk-server/egress-gate.js +520 -0
  93. package/runtime/packages/picasso-sdk-server/failure-policy.js +246 -0
  94. package/runtime/packages/picasso-sdk-server/file-input.js +169 -0
  95. package/runtime/packages/picasso-sdk-server/goal.js +131 -0
  96. package/runtime/packages/picasso-sdk-server/ignore-file.js +458 -0
  97. package/runtime/packages/picasso-sdk-server/ignore-plugin.js +12 -0
  98. package/runtime/packages/picasso-sdk-server/ignore-sandbox.js +122 -0
  99. package/runtime/packages/picasso-sdk-server/ignore-snapshot.js +131 -0
  100. package/runtime/packages/picasso-sdk-server/image-input.js +44 -0
  101. package/runtime/packages/picasso-sdk-server/index.js +891 -0
  102. package/runtime/packages/picasso-sdk-server/instructions.js +34 -0
  103. package/runtime/packages/picasso-sdk-server/jobs.js +113 -0
  104. package/runtime/packages/picasso-sdk-server/mcp-gate.js +51 -0
  105. package/runtime/packages/picasso-sdk-server/model-selection.js +162 -0
  106. package/runtime/packages/picasso-sdk-server/package.json +50 -0
  107. package/runtime/packages/picasso-sdk-server/picasso-records.js +50 -0
  108. package/runtime/packages/picasso-sdk-server/provider-reload.js +84 -0
  109. package/runtime/packages/picasso-sdk-server/queue.js +322 -0
  110. package/runtime/packages/picasso-sdk-server/requester.js +43 -0
  111. package/runtime/packages/picasso-sdk-server/rewind.js +108 -0
  112. package/runtime/packages/picasso-sdk-server/schedule.js +187 -0
  113. package/runtime/packages/picasso-sdk-server/session-grants.js +35 -0
  114. package/runtime/packages/picasso-sdk-server/session-state.js +118 -0
  115. package/runtime/packages/picasso-sdk-server/shell-paths.js +869 -0
  116. package/runtime/packages/picasso-sdk-server/stream-deltas.js +211 -0
  117. package/runtime/packages/picasso-sdk-server/team-tasks.js +451 -0
  118. package/runtime/packages/picasso-sdk-server/tool-output.js +128 -0
  119. package/runtime/packages/picasso-sdk-server/tools-list.js +51 -0
  120. package/runtime/packages/picasso-sdk-server/wave2-hooks.js +612 -0
  121. package/runtime/packages/picasso-sdk-server/workspace-archive.js +170 -0
  122. package/runtime/packages/picasso-sdk-server/workspace-restore.js +180 -0
  123. package/runtime/packages/picasso-web-search/backends.js +412 -0
  124. package/runtime/packages/picasso-web-search/config.js +121 -0
  125. package/runtime/packages/picasso-web-search/cordis.patch.yml +7 -0
  126. package/runtime/packages/picasso-web-search/failure.js +116 -0
  127. package/runtime/packages/picasso-web-search/format.js +42 -0
  128. package/runtime/packages/picasso-web-search/index.js +71 -0
  129. package/runtime/packages/picasso-web-search/package.json +38 -0
  130. package/runtime/packages/picasso-web-search/router.js +156 -0
  131. package/runtime/packages/picasso-x-reader/circle.js +324 -0
  132. package/runtime/packages/picasso-x-reader/command.js +169 -0
  133. package/runtime/packages/picasso-x-reader/cordis.patch.yml +8 -0
  134. package/runtime/packages/picasso-x-reader/index.js +170 -0
  135. package/runtime/packages/picasso-x-reader/package.json +39 -0
  136. package/runtime/packages/picasso-x-reader/read.js +370 -0
  137. package/runtime/packages/picasso-x-reader/rewrite.js +38 -0
  138. package/runtime/packages/picasso-x-reader/settings.js +131 -0
  139. package/runtime/packages/picasso-x-reader/urls.js +154 -0
  140. package/runtime/packages/picasso-x-reader/xmd.js +512 -0
  141. package/runtime/plugins/picasso-auth-bridge/index.js +380 -0
  142. package/runtime/plugins/picasso-auth-bridge/package.json +28 -0
  143. package/runtime/plugins/picasso-auto-approve/index.js +1003 -0
  144. package/runtime/plugins/picasso-auto-approve/package.json +28 -0
  145. package/runtime/plugins/picasso-browser/index.js +424 -0
  146. package/runtime/plugins/picasso-browser/package.json +28 -0
  147. package/runtime/plugins/picasso-checkpoints/evidence.js +210 -0
  148. package/runtime/plugins/picasso-checkpoints/index.js +885 -0
  149. package/runtime/plugins/picasso-checkpoints/package.json +29 -0
  150. package/runtime/plugins/picasso-commands/fresh-review.js +573 -0
  151. package/runtime/plugins/picasso-commands/index.js +497 -0
  152. package/runtime/plugins/picasso-commands/package.json +28 -0
  153. package/runtime/plugins/picasso-instructions/conflicts.js +115 -0
  154. package/runtime/plugins/picasso-instructions/formats.js +145 -0
  155. package/runtime/plugins/picasso-instructions/frontmatter.js +175 -0
  156. package/runtime/plugins/picasso-instructions/glob.js +114 -0
  157. package/runtime/plugins/picasso-instructions/globals.js +90 -0
  158. package/runtime/plugins/picasso-instructions/imports.js +123 -0
  159. package/runtime/plugins/picasso-instructions/index.js +326 -0
  160. package/runtime/plugins/picasso-instructions/modes.js +64 -0
  161. package/runtime/plugins/picasso-instructions/package.json +30 -0
  162. package/runtime/plugins/picasso-instructions/parse.js +134 -0
  163. package/runtime/plugins/picasso-instructions/report.js +161 -0
  164. package/runtime/plugins/picasso-instructions/resolve.js +939 -0
  165. package/runtime/plugins/picasso-instructions/scan.js +181 -0
  166. package/runtime/plugins/picasso-instructions/settings.js +150 -0
  167. package/runtime/plugins/picasso-instructions/skills.js +345 -0
  168. package/runtime/plugins/picasso-lean-context/index.js +6280 -0
  169. package/runtime/plugins/picasso-lean-context/package.json +26 -0
  170. package/runtime/plugins/picasso-lean-context/read-image-recovery.js +306 -0
  171. package/runtime/plugins/picasso-lean-context/timeline.js +418 -0
  172. package/runtime/plugins/picasso-librarian/classify.js +146 -0
  173. package/runtime/plugins/picasso-librarian/index.js +878 -0
  174. package/runtime/plugins/picasso-librarian/notes.js +159 -0
  175. package/runtime/plugins/picasso-librarian/package.json +34 -0
  176. package/runtime/plugins/picasso-librarian/state.js +478 -0
  177. package/runtime/plugins/picasso-lifecycle-hooks/index.js +186 -0
  178. package/runtime/plugins/picasso-lifecycle-hooks/package.json +25 -0
  179. package/runtime/plugins/picasso-mail/inbox.js +207 -0
  180. package/runtime/plugins/picasso-mail/index.js +293 -0
  181. package/runtime/plugins/picasso-mail/package.json +22 -0
  182. package/runtime/plugins/picasso-memory/index.js +1184 -0
  183. package/runtime/plugins/picasso-memory/package.json +21 -0
  184. package/runtime/plugins/picasso-model-router/connections.js +912 -0
  185. package/runtime/plugins/picasso-model-router/index.js +1083 -0
  186. package/runtime/plugins/picasso-model-router/package.json +30 -0
  187. package/runtime/plugins/picasso-options/index.js +263 -0
  188. package/runtime/plugins/picasso-options/package.json +28 -0
  189. package/runtime/plugins/picasso-progress-reports/index.js +267 -0
  190. package/runtime/plugins/picasso-progress-reports/package.json +30 -0
  191. package/runtime/plugins/picasso-progress-reports/report.js +235 -0
  192. package/runtime/plugins/picasso-provider-models/index.js +436 -0
  193. package/runtime/plugins/picasso-provider-models/package.json +28 -0
  194. package/runtime/plugins/picasso-repo-index/index.js +1850 -0
  195. package/runtime/plugins/picasso-repo-index/package.json +28 -0
  196. package/runtime/plugins/picasso-schedule-pause/index.js +344 -0
  197. package/runtime/plugins/picasso-schedule-pause/package.json +28 -0
  198. package/runtime/plugins/picasso-session-lifecycle/index.js +796 -0
  199. package/runtime/plugins/picasso-session-lifecycle/package.json +28 -0
  200. package/runtime/plugins/picasso-trackers/index.js +895 -0
  201. package/runtime/plugins/picasso-trackers/package.json +28 -0
  202. package/runtime/plugins/picasso-web-search/backends.js +412 -0
  203. package/runtime/plugins/picasso-web-search/config.js +121 -0
  204. package/runtime/plugins/picasso-web-search/failure.js +116 -0
  205. package/runtime/plugins/picasso-web-search/format.js +42 -0
  206. package/runtime/plugins/picasso-web-search/index.js +71 -0
  207. package/runtime/plugins/picasso-web-search/package.json +38 -0
  208. package/runtime/plugins/picasso-web-search/router.js +156 -0
  209. package/runtime/plugins/picasso-x-reader/circle.js +324 -0
  210. package/runtime/plugins/picasso-x-reader/command.js +169 -0
  211. package/runtime/plugins/picasso-x-reader/index.js +170 -0
  212. package/runtime/plugins/picasso-x-reader/package.json +39 -0
  213. package/runtime/plugins/picasso-x-reader/read.js +370 -0
  214. package/runtime/plugins/picasso-x-reader/rewrite.js +38 -0
  215. package/runtime/plugins/picasso-x-reader/settings.js +131 -0
  216. package/runtime/plugins/picasso-x-reader/urls.js +154 -0
  217. package/runtime/plugins/picasso-x-reader/xmd.js +512 -0
  218. package/runtime/relay/attachment-text.mjs +737 -0
  219. package/runtime/relay/companion/companion.css +126 -0
  220. package/runtime/relay/companion/companion.js +648 -0
  221. package/runtime/relay/companion/icon.svg +5 -0
  222. package/runtime/relay/companion/index.html +25 -0
  223. package/runtime/relay/companion/manifest.json +13 -0
  224. package/runtime/relay/companion/sw.js +41 -0
  225. package/runtime/relay/main.mjs +38580 -0
  226. package/runtime/relay/model-listing.mjs +614 -0
  227. package/runtime/relay/versions-routes.mjs +1400 -0
  228. package/runtime/verify-plugins.mjs +205 -0
  229. package/runtime-lock/package-lock.json +10779 -0
  230. package/runtime-lock/package.json +7 -0
  231. package/scripts/install-runtime.mjs +400 -0
  232. package/README.md +0 -3
@@ -0,0 +1,170 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { execFile } from 'node:child_process';
3
+ import { existsSync } from 'node:fs';
4
+ import { cp, mkdir, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
5
+ import { delimiter, isAbsolute, join, relative, resolve } from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { storeSnapshotWithoutIgnored } from './ignore-snapshot.js';
8
+
9
+ const execFileAsync = promisify(execFile);
10
+
11
+ export function workspaceRestorePaths(summaries, root) {
12
+ const paths = new Set();
13
+ for (const summary of summaries) {
14
+ if (summary.total > summary.files.length) throw new Error('workspace summary is truncated; refusing an incomplete restore');
15
+ for (const file of summary.files) {
16
+ const path = relative(root, resolve(summary.cwd, file.path));
17
+ if (path === '' || path === '..' || path.startsWith('../') || isAbsolute(path)) {
18
+ throw new Error(`cannot restore a path outside the snapshot repository: ${file.path}`);
19
+ }
20
+ paths.add(path);
21
+ }
22
+ }
23
+ return [...paths];
24
+ }
25
+
26
+ const TREE = /^[a-f0-9]{40,64}$/u;
27
+ const HUNK_HEADER = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/u;
28
+
29
+ /** Hunks of one file's unified patch in dsh's `WorkspaceFileDiff` shape (`git diff-tree -p` output). */
30
+ export function parseUnifiedHunks(patch) {
31
+ const hunks = [];
32
+ let current;
33
+ for (const line of patch.split('\n')) {
34
+ const header = HUNK_HEADER.exec(line);
35
+ if (header !== null) {
36
+ current = {
37
+ oldStart: Number(header[1]),
38
+ oldLines: header[2] === undefined ? 1 : Number(header[2]),
39
+ newStart: Number(header[3]),
40
+ newLines: header[4] === undefined ? 1 : Number(header[4]),
41
+ lines: [],
42
+ };
43
+ hunks.push(current);
44
+ } else if (line.startsWith('diff --git ')) {
45
+ current = undefined;
46
+ } else if (current !== undefined && (line.startsWith(' ') || line.startsWith('+') || line.startsWith('-'))) {
47
+ current.lines.push(line);
48
+ }
49
+ }
50
+ return hunks;
51
+ }
52
+
53
+ /** The old path of a renamed or copied entry, from `git diff-tree -r -M --name-status -z`. */
54
+ function sourcePathOf(nameStatus, path) {
55
+ const fields = nameStatus.split('\0');
56
+ for (let index = 0; index < fields.length;) {
57
+ const status = fields[index];
58
+ if (status === '') break;
59
+ if (/^[RC]/u.test(status)) {
60
+ if (fields[index + 2] === path) return fields[index + 1];
61
+ index += 3;
62
+ } else {
63
+ index += 2;
64
+ }
65
+ }
66
+ return path;
67
+ }
68
+
69
+ export function createWorkspaceArchive(root, findObjects) {
70
+ const sessionDir = (sessionId) => join(root, createHash('sha256').update(sessionId).digest('hex'));
71
+ const objectsDir = (sessionId) => join(sessionDir(sessionId), 'objects');
72
+ const summaryPath = (sessionId, seq) => {
73
+ if (!Number.isSafeInteger(seq) || seq < 0) throw new TypeError('workspace seq must be a non-negative integer');
74
+ return join(sessionDir(sessionId), `${seq}.json`);
75
+ };
76
+ return {
77
+ objectsDir,
78
+ async save(sessionId, seq, input, { isIgnored } = {}) {
79
+ const path = summaryPath(sessionId, seq);
80
+ await mkdir(objectsDir(sessionId), { recursive: true, mode: 0o700 });
81
+ const filtered = typeof isIgnored === 'function';
82
+ const summary = filtered ? await storeSnapshotWithoutIgnored({ summary: input, objects: objectsDir(sessionId), findObjects, isIgnored }) : input;
83
+ if (!filtered && summary.snapshot !== undefined) {
84
+ const copied = new Set();
85
+ for (const tree of new Set(Object.values(summary.snapshot))) {
86
+ if (typeof tree !== 'string' || !/^[a-f0-9]{40,64}$/u.test(tree)) throw new Error('invalid workspace snapshot tree');
87
+ const source = findObjects(tree);
88
+ if (source === undefined) {
89
+ if (typeof summary.cwd !== 'string') throw new Error('workspace snapshot objects are unavailable');
90
+ await execFileAsync('git', ['-C', summary.cwd, 'cat-file', '-e', `${tree}^{tree}`], { timeout: 30000 });
91
+ } else if (!copied.has(source)) {
92
+ await cp(source, objectsDir(sessionId), { recursive: true, force: false, errorOnExist: false });
93
+ copied.add(source);
94
+ }
95
+ }
96
+ }
97
+ const pending = `${path}.${randomUUID()}.tmp`;
98
+ await writeFile(pending, JSON.stringify(summary), { mode: 0o600 });
99
+ await rename(pending, path);
100
+ },
101
+ async read(sessionId, seq) {
102
+ try {
103
+ return JSON.parse(await readFile(summaryPath(sessionId, seq), 'utf8'));
104
+ } catch (error) {
105
+ if (error.code === 'ENOENT') return undefined;
106
+ throw error;
107
+ }
108
+ },
109
+ /**
110
+ * One listed file's turn diff served from the archived summary and snapshot
111
+ * objects, for turns dsh's in-memory recorder no longer holds (a restarted
112
+ * runtime or a forked session). Same shape as `workspaceChanges.diff`:
113
+ * `{ kind: 'text', path, display, before, after, hunks, coarse }`, or
114
+ * `{ kind: 'binary' | 'oversized', path, display }`. Undefined when the seq
115
+ * or index is unknown or the summary has no git snapshot.
116
+ */
117
+ async diff(sessionId, seq, index, liveObjectsFor = findObjects) {
118
+ const summary = await this.read(sessionId, seq);
119
+ const file = summary?.files?.[index];
120
+ if (file === undefined || typeof file.path !== 'string') return undefined;
121
+ const { path, display } = file;
122
+ if (file.oversized === true) return { kind: 'oversized', path, display };
123
+ if (file.binary === true) return { kind: 'binary', path, display };
124
+ const snapshot = summary.snapshot;
125
+ if (snapshot === undefined || typeof summary.cwd !== 'string') return undefined;
126
+ if (!TREE.test(snapshot.before) || !TREE.test(snapshot.after)) throw new Error('invalid workspace snapshot tree');
127
+ const cwd = await realpath(summary.cwd);
128
+ const git = (args, env, at = cwd) => execFileAsync('git', ['-C', at, ...args], {
129
+ env: { ...process.env, ...env },
130
+ timeout: 30000,
131
+ maxBuffer: 16 * 1024 * 1024,
132
+ });
133
+ const { stdout: top } = await git(['rev-parse', '--show-toplevel', '--git-path', 'objects']);
134
+ const [repoRoot, repoObjects] = top.trimEnd().split('\n');
135
+ const durable = objectsDir(sessionId);
136
+ const live = liveObjectsFor(snapshot.before) ?? liveObjectsFor(snapshot.after);
137
+ const objects = existsSync(durable) ? durable : (live ?? resolve(cwd, repoObjects));
138
+ const alternates = new Set([resolve(cwd, repoObjects), ...(live === undefined ? [] : [live])]);
139
+ alternates.delete(objects);
140
+ const env = { GIT_OBJECT_DIRECTORY: objects, GIT_ALTERNATE_OBJECT_DIRECTORIES: [...alternates].join(delimiter) };
141
+ const rel = relative(repoRoot, resolve(cwd, path)).split('\\').join('/');
142
+ if (rel === '' || rel === '..' || rel.startsWith('../') || isAbsolute(rel)) return undefined;
143
+ const { stdout: nameStatus } = await git(['diff-tree', '-r', '-M', '--name-status', '-z', snapshot.before, snapshot.after], env);
144
+ const oldPath = sourcePathOf(nameStatus, rel);
145
+ const exists = (tree, entry) => git(['cat-file', '-e', `${tree}:${entry}`], env, repoRoot).then(() => true, () => false);
146
+ const [before, after] = await Promise.all([exists(snapshot.before, oldPath), exists(snapshot.after, rel)]);
147
+ const { stdout: patch } = await git([
148
+ 'diff-tree', '-p', '-M', '-U3', '--no-color', '--no-ext-diff', snapshot.before, snapshot.after,
149
+ '--', `:(literal)${oldPath}`, ...(oldPath === rel ? [] : [`:(literal)${rel}`]),
150
+ ], env, repoRoot);
151
+ if (/^Binary files .* differ$/mu.test(patch) || /^GIT binary patch$/mu.test(patch)) return { kind: 'binary', path, display };
152
+ return { kind: 'text', path, display, before, after, hunks: parseUnifiedHunks(patch), coarse: false };
153
+ },
154
+ async fork(sourceId, targetId, seqs) {
155
+ for (const seq of seqs) {
156
+ const summary = await this.read(sourceId, seq);
157
+ if (summary === undefined) continue;
158
+ await mkdir(sessionDir(targetId), { recursive: true, mode: 0o700 });
159
+ if (summary.snapshot !== undefined && Object.keys(summary.snapshot).length > 0) {
160
+ await cp(objectsDir(sourceId), objectsDir(targetId), { recursive: true, force: false, errorOnExist: false });
161
+ }
162
+ await writeFile(summaryPath(targetId, seq), JSON.stringify(summary), { mode: 0o600 });
163
+ }
164
+ },
165
+ /** Delete a session's archived summaries and snapshot objects (a discarded aside). */
166
+ async remove(sessionId) {
167
+ await rm(sessionDir(sessionId), { recursive: true, force: true });
168
+ },
169
+ };
170
+ }
@@ -0,0 +1,180 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { chmod, lstat, mkdir, readFile, readlink, realpath, rm, symlink, writeFile } from 'node:fs/promises';
4
+ import { delimiter, dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { workspaceRestorePaths } from './workspace-archive.js';
7
+
8
+ const execFileAsync = promisify(execFile);
9
+
10
+ /**
11
+ * Validate a `workspace/restore` `paths` filter: undefined (restore every
12
+ * path) or a non-empty array of workspace-relative paths that stay inside
13
+ * the workspace. Returns them normalized (`/`-separated, no trailing `/`).
14
+ */
15
+ export function restorePathFilter(paths) {
16
+ if (paths === undefined || paths === null) return undefined;
17
+ if (!Array.isArray(paths) || paths.length === 0) throw new TypeError('paths must be a non-empty array of workspace-relative paths');
18
+ return paths.map((path) => {
19
+ if (typeof path !== 'string' || path.length === 0 || path.includes('\0')) throw new TypeError('paths must be non-empty strings');
20
+ if (isAbsolute(path)) throw new TypeError(`paths must be workspace-relative: ${path}`);
21
+ const normalized = normalize(path).split(sep).join('/').replace(/\/+$/u, '');
22
+ if (normalized === '..' || normalized.startsWith('../') || normalized === '.' || normalized === '') {
23
+ throw new TypeError(`paths must name files inside the workspace: ${path}`);
24
+ }
25
+ return normalized;
26
+ });
27
+ }
28
+
29
+ export async function planWorkspaceRestore({ sessionId, seq, side, summaryFor, changeSeqs, archive, findObjects, isIgnored, only }) {
30
+ const filter = restorePathFilter(only);
31
+ const summary = await summaryFor(sessionId, seq);
32
+ const tree = summary?.snapshot?.[side === 'after' ? 'after' : 'before'];
33
+ if (summary === undefined || tree === undefined) throw new Error('snapshot unavailable for that turn');
34
+ if (!/^[a-f0-9]{40,64}$/u.test(tree)) throw new Error('invalid workspace snapshot tree');
35
+ const git = (args, env, cwd = summary.cwd) => execFileAsync('git', ['-C', cwd, ...args], {
36
+ env: { ...process.env, ...env },
37
+ timeout: 30000,
38
+ maxBuffer: 8 * 1024 * 1024,
39
+ });
40
+ const { stdout: top } = await git(['rev-parse', '--show-toplevel', '--git-path', 'objects']);
41
+ const [root, repoObjects] = top.trimEnd().split('\n');
42
+ const durableObjects = archive.objectsDir(sessionId);
43
+ const liveObjects = findObjects(tree) ?? findObjects(summary.snapshot.after) ?? findObjects(summary.snapshot.before);
44
+ const persisted = await archive.read(sessionId, seq);
45
+ const objectsDir = persisted !== undefined && existsSync(durableObjects)
46
+ ? durableObjects
47
+ : (liveObjects ?? resolve(summary.cwd, repoObjects));
48
+ const alternates = new Set([resolve(summary.cwd, repoObjects)]);
49
+ if (existsSync(durableObjects)) alternates.add(durableObjects);
50
+ if (liveObjects !== undefined) alternates.add(liveObjects);
51
+ alternates.delete(objectsDir);
52
+ const env = { GIT_OBJECT_DIRECTORY: objectsDir, GIT_ALTERNATE_OBJECT_DIRECTORIES: [...alternates].join(delimiter) };
53
+ await git(['cat-file', '-e', `${tree}^{tree}`], env);
54
+ const summaries = [summary];
55
+ for (const entry of changeSeqs.get(sessionId) ?? []) {
56
+ if (entry.seq <= seq) continue;
57
+ const next = await summaryFor(sessionId, entry.seq);
58
+ if (next === undefined) throw new Error('a later workspace snapshot is unavailable; refusing an incomplete restore');
59
+ summaries.push(next);
60
+ }
61
+ const paths = new Set(workspaceRestorePaths(summaries, root));
62
+ for (const item of summaries) {
63
+ if (item.snapshot === undefined) throw new Error('a later turn has no git snapshot; refusing an incomplete restore');
64
+ if (Object.values(item.snapshot).some((snapshot) => !/^[a-f0-9]{40,64}$/u.test(snapshot))) throw new Error('invalid workspace snapshot tree');
65
+ const { stdout: changedPaths } = await git(['diff-tree', '-r', '--no-renames', '--name-only', '-z', item.snapshot.before, item.snapshot.after], env);
66
+ for (const path of changedPaths.split('\0').filter(Boolean)) paths.add(path);
67
+ }
68
+ if (typeof isIgnored === 'function') {
69
+ for (const path of [...paths]) if (isIgnored(summary.cwd, join(root, path))) paths.delete(path);
70
+ }
71
+ if (filter !== undefined) {
72
+ // Workspace-relative (the session cwd, which may sit below the repository root) to repository-relative.
73
+ const base = relative(root, await realpath(summary.cwd)).split(sep).join('/');
74
+ const wanted = filter.map((path) => (base === '' ? path : `${base}/${path}`));
75
+ const matches = (path, want) => path === want || path.startsWith(`${want}/`);
76
+ for (const want of wanted) {
77
+ if (![...paths].some((path) => matches(path, want))) throw new Error(`not changed by that turn or a later one: ${want.slice(base === '' ? 0 : base.length + 1)}`);
78
+ }
79
+ for (const path of [...paths]) if (!wanted.some((want) => matches(path, want))) paths.delete(path);
80
+ }
81
+ const targets = new Map();
82
+ for (const path of paths) {
83
+ let parent = dirname(join(root, path));
84
+ for (;;) {
85
+ try {
86
+ parent = await realpath(parent);
87
+ break;
88
+ } catch (error) {
89
+ if (error.code !== 'ENOENT') throw error;
90
+ const next = dirname(parent);
91
+ if (next === parent) throw error;
92
+ parent = next;
93
+ }
94
+ }
95
+ const rel = relative(root, parent);
96
+ if (rel === '..' || rel.startsWith('../') || isAbsolute(rel)) throw new Error(`restore path traverses outside the repository: ${path}`);
97
+ let covered = false;
98
+ for (const item of summaries) {
99
+ for (const snapshot of Object.values(item.snapshot)) {
100
+ covered = await git(['cat-file', '-e', `${snapshot}:${path}`], env).then(() => true, () => false);
101
+ if (covered) break;
102
+ }
103
+ if (covered) break;
104
+ }
105
+ if (!covered) throw new Error(`file is not covered by a git snapshot: ${path}`);
106
+ const { stdout: entry } = await git(['ls-tree', '--full-tree', '-z', tree, '--', `:(literal)${path}`], env, root);
107
+ if (/^(040000|160000) /u.test(entry)) throw new Error(`cannot restore a directory or submodule as a file: ${path}`);
108
+ const inTree = entry.length > 0;
109
+ if (inTree) await git(['cat-file', '-e', `${tree}:${path}`], env);
110
+ targets.set(path, inTree);
111
+ }
112
+ return { root, tree, env, git, paths: [...paths], targets };
113
+ }
114
+
115
+ /** Write a planned restore into the work tree (every object and path was checked by the plan). */
116
+ export async function applyWorkspaceRestore({ root, tree, env, git, paths, targets }) {
117
+ const restored = [];
118
+ for (const path of paths) {
119
+ if (targets.get(path)) await git(['restore', `--source=${tree}`, '--worktree', '--', `:(literal)${path}`], env, root);
120
+ else await rm(join(root, path), { force: true });
121
+ restored.push(path);
122
+ }
123
+ return { restored, snapshot: tree };
124
+ }
125
+
126
+ export async function restoreWorkspace(options) {
127
+ return applyWorkspaceRestore(await planWorkspaceRestore(options));
128
+ }
129
+
130
+ /**
131
+ * Copy the current state of `paths` (repository-relative under `root`) so a
132
+ * failed rewind can put the work tree back exactly: regular files keep their
133
+ * bytes and mode, symlinks their target, absent paths remember the first
134
+ * missing ancestor so directories the restore creates are removed again.
135
+ * A path that is currently a directory refuses before anything is written.
136
+ */
137
+ export async function snapshotWorktree(root, paths) {
138
+ const entries = [];
139
+ for (const path of paths) {
140
+ const absolute = join(root, path);
141
+ let stat;
142
+ try {
143
+ stat = await lstat(absolute);
144
+ } catch (error) {
145
+ if (error.code !== 'ENOENT') throw error;
146
+ let missing = absolute;
147
+ for (let parent = dirname(missing); parent !== missing && !existsSync(parent); parent = dirname(parent)) missing = parent;
148
+ entries.push({ path, kind: 'absent', missing });
149
+ continue;
150
+ }
151
+ if (stat.isSymbolicLink()) entries.push({ path, kind: 'symlink', target: await readlink(absolute) });
152
+ else if (stat.isFile()) entries.push({ path, kind: 'file', data: await readFile(absolute), mode: stat.mode & 0o7777 });
153
+ else throw new Error(`cannot rewind over a non-file path: ${path}`);
154
+ }
155
+ return { root, entries };
156
+ }
157
+
158
+ /** Put every snapshotted path back; reports the paths that could not be rolled back. */
159
+ export async function rollbackWorktree({ root, entries }) {
160
+ const failed = [];
161
+ for (const entry of entries) {
162
+ const absolute = join(root, entry.path);
163
+ try {
164
+ if (entry.kind === 'absent') {
165
+ await rm(entry.missing, { recursive: true, force: true });
166
+ continue;
167
+ }
168
+ await mkdir(dirname(absolute), { recursive: true });
169
+ await rm(absolute, { force: true });
170
+ if (entry.kind === 'symlink') await symlink(entry.target, absolute);
171
+ else {
172
+ await writeFile(absolute, entry.data, { mode: entry.mode });
173
+ await chmod(absolute, entry.mode);
174
+ }
175
+ } catch {
176
+ failed.push(entry.path);
177
+ }
178
+ }
179
+ return { failed };
180
+ }