@abelxiaoxing/cadence 1.8.4 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/README.md +324 -117
  2. package/THIRD_PARTY_NOTICES.md +15 -0
  3. package/agents/design-explorer.md +14 -18
  4. package/agents/diagnosis-worker.md +14 -14
  5. package/agents/implementation-worker.md +16 -17
  6. package/config/workflow-task.example.json +7 -0
  7. package/docs/remote-access.md +60 -0
  8. package/docs/reuse-and-distribution.md +44 -0
  9. package/docs/service-management.md +108 -0
  10. package/licenses/bundled-web.txt +6245 -0
  11. package/licenses/pi-web-ui-MIT.txt +21 -0
  12. package/licenses/pi-web-ui-reuse.md +22 -0
  13. package/package.json +92 -20
  14. package/src/index.ts +21 -1802
  15. package/src/native-build.ts +6 -0
  16. package/src/native-client.ts +103 -0
  17. package/src/native-export.ts +58 -0
  18. package/src/native-history.ts +359 -0
  19. package/src/operator-cli.mjs +453 -1937
  20. package/src/plan-proposal.ts +87 -0
  21. package/src/sdk-worker.mjs +549 -0
  22. package/src/service/contracts/active.ts +82 -0
  23. package/src/service/contracts/budget.ts +148 -0
  24. package/src/service/contracts/build.ts +67 -0
  25. package/src/service/contracts/capture.ts +48 -0
  26. package/src/service/contracts/core.ts +33 -0
  27. package/src/service/contracts/current.ts +261 -0
  28. package/src/service/contracts/domain.ts +68 -0
  29. package/src/service/contracts/history.ts +2245 -0
  30. package/src/service/contracts/models.ts +139 -0
  31. package/src/service/coordination.ts +862 -0
  32. package/src/service/private-files.ts +204 -0
  33. package/src/service-cli.mjs +5592 -0
  34. package/src/service-client.ts +747 -0
  35. package/src/service-contract.ts +245 -0
  36. package/src/service-host.mjs +22382 -0
  37. package/src/service-http-client.ts +425 -0
  38. package/src/service-wire.ts +372 -0
  39. package/src/task-shell.ts +1045 -0
  40. package/src/task-store.ts +479 -0
  41. package/src/task-types.ts +184 -0
  42. package/src/verification-diagnostics.ts +29 -72
  43. package/src/worker-capture.mjs +1197 -0
  44. package/src/worker-public.mjs +1753 -0
  45. package/src/worker-redaction.mjs +608 -0
  46. package/src/worker-tools.mjs +202 -0
  47. package/web/dist/assets/KaTeX_AMS-Regular.ttf +0 -0
  48. package/web/dist/assets/KaTeX_AMS-Regular.woff +0 -0
  49. package/web/dist/assets/KaTeX_AMS-Regular.woff2 +0 -0
  50. package/web/dist/assets/KaTeX_Caligraphic-Bold.ttf +0 -0
  51. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff +0 -0
  52. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff2 +0 -0
  53. package/web/dist/assets/KaTeX_Caligraphic-Regular.ttf +0 -0
  54. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff +0 -0
  55. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff2 +0 -0
  56. package/web/dist/assets/KaTeX_Fraktur-Bold.ttf +0 -0
  57. package/web/dist/assets/KaTeX_Fraktur-Bold.woff +0 -0
  58. package/web/dist/assets/KaTeX_Fraktur-Bold.woff2 +0 -0
  59. package/web/dist/assets/KaTeX_Fraktur-Regular.ttf +0 -0
  60. package/web/dist/assets/KaTeX_Fraktur-Regular.woff +0 -0
  61. package/web/dist/assets/KaTeX_Fraktur-Regular.woff2 +0 -0
  62. package/web/dist/assets/KaTeX_Main-Bold.ttf +0 -0
  63. package/web/dist/assets/KaTeX_Main-Bold.woff +0 -0
  64. package/web/dist/assets/KaTeX_Main-Bold.woff2 +0 -0
  65. package/web/dist/assets/KaTeX_Main-BoldItalic.ttf +0 -0
  66. package/web/dist/assets/KaTeX_Main-BoldItalic.woff +0 -0
  67. package/web/dist/assets/KaTeX_Main-BoldItalic.woff2 +0 -0
  68. package/web/dist/assets/KaTeX_Main-Italic.ttf +0 -0
  69. package/web/dist/assets/KaTeX_Main-Italic.woff +0 -0
  70. package/web/dist/assets/KaTeX_Main-Italic.woff2 +0 -0
  71. package/web/dist/assets/KaTeX_Main-Regular.ttf +0 -0
  72. package/web/dist/assets/KaTeX_Main-Regular.woff +0 -0
  73. package/web/dist/assets/KaTeX_Main-Regular.woff2 +0 -0
  74. package/web/dist/assets/KaTeX_Math-BoldItalic.ttf +0 -0
  75. package/web/dist/assets/KaTeX_Math-BoldItalic.woff +0 -0
  76. package/web/dist/assets/KaTeX_Math-BoldItalic.woff2 +0 -0
  77. package/web/dist/assets/KaTeX_Math-Italic.ttf +0 -0
  78. package/web/dist/assets/KaTeX_Math-Italic.woff +0 -0
  79. package/web/dist/assets/KaTeX_Math-Italic.woff2 +0 -0
  80. package/web/dist/assets/KaTeX_SansSerif-Bold.ttf +0 -0
  81. package/web/dist/assets/KaTeX_SansSerif-Bold.woff +0 -0
  82. package/web/dist/assets/KaTeX_SansSerif-Bold.woff2 +0 -0
  83. package/web/dist/assets/KaTeX_SansSerif-Italic.ttf +0 -0
  84. package/web/dist/assets/KaTeX_SansSerif-Italic.woff +0 -0
  85. package/web/dist/assets/KaTeX_SansSerif-Italic.woff2 +0 -0
  86. package/web/dist/assets/KaTeX_SansSerif-Regular.ttf +0 -0
  87. package/web/dist/assets/KaTeX_SansSerif-Regular.woff +0 -0
  88. package/web/dist/assets/KaTeX_SansSerif-Regular.woff2 +0 -0
  89. package/web/dist/assets/KaTeX_Script-Regular.ttf +0 -0
  90. package/web/dist/assets/KaTeX_Script-Regular.woff +0 -0
  91. package/web/dist/assets/KaTeX_Script-Regular.woff2 +0 -0
  92. package/web/dist/assets/KaTeX_Size1-Regular.ttf +0 -0
  93. package/web/dist/assets/KaTeX_Size1-Regular.woff +0 -0
  94. package/web/dist/assets/KaTeX_Size1-Regular.woff2 +0 -0
  95. package/web/dist/assets/KaTeX_Size2-Regular.ttf +0 -0
  96. package/web/dist/assets/KaTeX_Size2-Regular.woff +0 -0
  97. package/web/dist/assets/KaTeX_Size2-Regular.woff2 +0 -0
  98. package/web/dist/assets/KaTeX_Size3-Regular.ttf +0 -0
  99. package/web/dist/assets/KaTeX_Size3-Regular.woff +0 -0
  100. package/web/dist/assets/KaTeX_Size3-Regular.woff2 +0 -0
  101. package/web/dist/assets/KaTeX_Size4-Regular.ttf +0 -0
  102. package/web/dist/assets/KaTeX_Size4-Regular.woff +0 -0
  103. package/web/dist/assets/KaTeX_Size4-Regular.woff2 +0 -0
  104. package/web/dist/assets/KaTeX_Typewriter-Regular.ttf +0 -0
  105. package/web/dist/assets/KaTeX_Typewriter-Regular.woff +0 -0
  106. package/web/dist/assets/KaTeX_Typewriter-Regular.woff2 +0 -0
  107. package/web/dist/assets/cadence.css +2 -0
  108. package/web/dist/assets/cadence.js +7 -0
  109. package/web/dist/assets/markdown.js +296 -0
  110. package/web/dist/assets/react.js +9 -0
  111. package/web/dist/assets/rolldown-runtime.js +1 -0
  112. package/web/dist/assets/timeline-client.js +41 -0
  113. package/web/dist/assets/vis-timeline.css +1274 -0
  114. package/web/dist/assets/vis-timeline.js +32 -0
  115. package/web/dist/index.html +18 -0
  116. package/web/dist/manifest.json +505 -0
  117. package/config/plan-draft.example.json +0 -125
  118. package/config/plan-draft.multiple-tasks.example.json +0 -375
  119. package/config/plan-draft.quick.example.json +0 -78
  120. package/prompts/abel-design.md +0 -382
  121. package/prompts/abel-diagnose.md +0 -71
  122. package/prompts/abel-implement.md +0 -284
  123. package/prompts/abel-init.md +0 -52
  124. package/src/activation.ts +0 -44
  125. package/src/activity-contracts.ts +0 -82
  126. package/src/agent-registry.ts +0 -53
  127. package/src/apply-transaction.ts +0 -1437
  128. package/src/artifact-store.ts +0 -213
  129. package/src/build-windows-job.mjs +0 -95
  130. package/src/candidate-artifact.ts +0 -143
  131. package/src/candidate-context.ts +0 -289
  132. package/src/candidate-patch.ts +0 -271
  133. package/src/candidate-workspace.ts +0 -80
  134. package/src/canonical.ts +0 -16
  135. package/src/change-contract-schema.ts +0 -191
  136. package/src/change-contract.ts +0 -324
  137. package/src/change-verification.ts +0 -1617
  138. package/src/contracts.ts +0 -2466
  139. package/src/control-contracts.ts +0 -382
  140. package/src/delivery-compiler.ts +0 -1805
  141. package/src/delivery-revision.ts +0 -42
  142. package/src/design-control.ts +0 -1299
  143. package/src/design-diagnostics.ts +0 -181
  144. package/src/design-journal.ts +0 -1773
  145. package/src/directory-sync.ts +0 -36
  146. package/src/durable-contracts.ts +0 -227
  147. package/src/durable-workflow.ts +0 -822
  148. package/src/evidence-draft.ts +0 -122
  149. package/src/execution-profile.ts +0 -64
  150. package/src/execution-retention.ts +0 -77
  151. package/src/file-snapshot.ts +0 -163
  152. package/src/implement-continuation.ts +0 -559
  153. package/src/implement-graph.ts +0 -690
  154. package/src/implement-plan.ts +0 -72
  155. package/src/install-config.d.mts +0 -6
  156. package/src/isolation-backend.ts +0 -353
  157. package/src/model-source.ts +0 -22
  158. package/src/openspec-cli.ts +0 -494
  159. package/src/operator-cli-entry.mjs +0 -24
  160. package/src/operator-tools.ts +0 -309
  161. package/src/package-candidate-process.ts +0 -206
  162. package/src/package-candidate.ts +0 -24
  163. package/src/package-delivery.ts +0 -486
  164. package/src/package-state.ts +0 -320
  165. package/src/package-verification.ts +0 -635
  166. package/src/package-workflow.ts +0 -305
  167. package/src/packet-runtime.ts +0 -459
  168. package/src/phase-execution.ts +0 -2163
  169. package/src/pi-adapter.ts +0 -19
  170. package/src/plan-draft-summary.ts +0 -527
  171. package/src/plan-draft.ts +0 -502
  172. package/src/remove-path.ts +0 -32
  173. package/src/run-state.ts +0 -420
  174. package/src/run-store.ts +0 -1179
  175. package/src/safe-path.ts +0 -77
  176. package/src/scoped-grep-worker.mjs +0 -23
  177. package/src/scoped-tools.ts +0 -775
  178. package/src/single-task-draft.ts +0 -142
  179. package/src/sqlite-schema.ts +0 -171
  180. package/src/state-root.ts +0 -215
  181. package/src/storage-schema.ts +0 -360
  182. package/src/subagent-activity.ts +0 -1417
  183. package/src/subagent-process.ts +0 -476
  184. package/src/task-ledger.ts +0 -1338
  185. package/src/transport-budget.ts +0 -50
  186. package/src/verification-capability.ts +0 -1191
  187. package/src/verification-environment-io.ts +0 -389
  188. package/src/verification-environment.ts +0 -162
  189. package/src/verification-identity.ts +0 -77
  190. package/src/verification-scan.ts +0 -64
  191. package/src/windows-job-backend.ts +0 -419
  192. package/src/windows-job.c +0 -149
  193. package/src/workflow-engine.ts +0 -28
  194. package/src/workflow-policy.ts +0 -1670
  195. package/src/workflow-recovery-policy.ts +0 -97
  196. package/src/workflow-scheduling.ts +0 -105
  197. package/src/workflow-state-machine.ts +0 -4341
  198. package/src/workflow-status.ts +0 -576
  199. package/src/workspace-io-entry.mjs +0 -76
  200. package/src/workspace-io-worker.mjs +0 -1312
  201. package/src/workspace-io.ts +0 -89
  202. package/src/workspace-store.ts +0 -634
@@ -1,634 +0,0 @@
1
- import { execFile, execFileSync } from "node:child_process";
2
- import { createHash, randomUUID } from "node:crypto";
3
- import {
4
- chmodSync,
5
- closeSync,
6
- constants,
7
- fsyncSync,
8
- lstatSync,
9
- mkdirSync,
10
- openSync,
11
- readFileSync,
12
- renameSync,
13
- unlinkSync,
14
- writeFileSync,
15
- } from "node:fs";
16
- import path from "node:path";
17
- import { promisify } from "node:util";
18
- import type { ArtifactStore } from "./artifact-store.ts";
19
- import { compareCanonicalStrings } from "./canonical.ts";
20
- import { isValidRelativePath } from "./contracts.ts";
21
- import { syncDirectory } from "./directory-sync.ts";
22
- import { observeSafePath } from "./safe-path.ts";
23
- import { runWorkspaceIo, type WorkspaceIoMetrics } from "./workspace-io.ts";
24
-
25
- const SHA256 = /^[a-f0-9]{64}$/u;
26
-
27
- export interface WorkspaceFileEntry {
28
- kind: "file";
29
- hash: string;
30
- bytes: number;
31
- mode: number;
32
- }
33
-
34
- export interface WorkspaceAbsentEntry {
35
- kind: "absent";
36
- }
37
-
38
- export type WorkspaceEntry = WorkspaceFileEntry | WorkspaceAbsentEntry;
39
- export type WorkspaceEntries = Record<string, WorkspaceEntry>;
40
-
41
- export interface WorkspaceRevision {
42
- revisionId: string;
43
- parentRevisionId: string | null;
44
- manifestHash: string;
45
- entries: WorkspaceEntries;
46
- }
47
-
48
- export interface CaptureBaselineInput {
49
- gitTimeoutMs?: number;
50
- consumerRoot: string;
51
- approvedUntracked?: string[];
52
- absent?: string[];
53
- excludedPaths?: string[];
54
- }
55
-
56
- export type WorkspaceChange =
57
- | Uint8Array
58
- | null
59
- | { kind: "absent" }
60
- | { kind: "file"; bytes: Uint8Array; mode?: number };
61
-
62
- export interface CreateRevisionInput {
63
- parentRevisionId: string;
64
- changes: Record<string, WorkspaceChange>;
65
- }
66
-
67
- export interface MergeRevisionInput {
68
- baseRevisionId: string;
69
- currentRevisionId: string;
70
- candidateRevisionId: string;
71
- boundPaths: string[];
72
- }
73
-
74
- function hash(...values: Array<string | Uint8Array>): string {
75
- const digest = createHash("sha256");
76
- for (const value of values) {
77
- const bytes = typeof value === "string" ? Buffer.from(value) : value;
78
- digest.update(`${bytes.byteLength}:`);
79
- digest.update(bytes);
80
- }
81
- return digest.digest("hex");
82
- }
83
-
84
- function stableEntries(entries: WorkspaceEntries): WorkspaceEntries {
85
- return Object.fromEntries(
86
- Object.entries(entries)
87
- .sort(([left], [right]) => compareCanonicalStrings(left, right))
88
- .map(([relative, entry]) => [relative, { ...entry }]),
89
- );
90
- }
91
-
92
- function manifestHash(entries: WorkspaceEntries): string {
93
- return hash(
94
- "cadence-workspace-manifest",
95
- JSON.stringify(stableEntries(entries)),
96
- );
97
- }
98
-
99
- function revisionId(parentRevisionId: string | null, manifest: string): string {
100
- return hash("cadence-workspace-revision", parentRevisionId ?? "", manifest);
101
- }
102
-
103
- function ensureDirectory(directory: string): void {
104
- const stat = lstatSync(directory, { throwIfNoEntry: false });
105
- if (stat) {
106
- if (stat.isSymbolicLink() || !stat.isDirectory()) {
107
- throw new Error("unsafe-workspace-path");
108
- }
109
- chmodSync(directory, 0o700);
110
- return;
111
- }
112
- let cursor = path.dirname(directory);
113
- while (cursor !== path.dirname(cursor)) {
114
- const ancestor = lstatSync(cursor, { throwIfNoEntry: false });
115
- if (ancestor) {
116
- if (ancestor.isSymbolicLink() || !ancestor.isDirectory()) {
117
- throw new Error("unsafe-workspace-path");
118
- }
119
- break;
120
- }
121
- cursor = path.dirname(cursor);
122
- }
123
- mkdirSync(directory, { recursive: true, mode: 0o700 });
124
- const created = lstatSync(directory);
125
- if (created.isSymbolicLink() || !created.isDirectory()) {
126
- throw new Error("unsafe-workspace-path");
127
- }
128
- chmodSync(directory, 0o700);
129
- }
130
-
131
- function writeAtomic(target: string, bytes: Uint8Array): void {
132
- const directory = path.dirname(target);
133
- ensureDirectory(directory);
134
- const temporary = path.join(
135
- directory,
136
- `.${path.basename(target)}.${process.pid}.${randomUUID()}.tmp`,
137
- );
138
- const descriptor = openSync(
139
- temporary,
140
- constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,
141
- 0o600,
142
- );
143
- try {
144
- writeFileSync(descriptor, bytes);
145
- fsyncSync(descriptor);
146
- } finally {
147
- closeSync(descriptor);
148
- }
149
- try {
150
- renameSync(temporary, target);
151
- chmodSync(target, 0o600);
152
- syncDirectory(directory);
153
- } catch (error) {
154
- try {
155
- unlinkSync(temporary);
156
- } catch {
157
- // The rename may already have consumed the temporary file.
158
- }
159
- throw error;
160
- }
161
- }
162
-
163
- function requireSafeRelative(relative: string): void {
164
- if (!isValidRelativePath(relative) || relative === ".") {
165
- throw new Error("unsafe-workspace-path");
166
- }
167
- }
168
-
169
- function isExcluded(relative: string, excluded: readonly string[]): boolean {
170
- return excluded.some(
171
- (entry) => relative === entry || relative.startsWith(`${entry}/`),
172
- );
173
- }
174
-
175
- function parseNullSeparated(bytes: Buffer): string[] {
176
- const decoded = bytes.toString("utf8");
177
- if (!Buffer.from(decoded, "utf8").equals(bytes)) {
178
- throw new Error("unsafe-workspace-path");
179
- }
180
- return decoded.split("\0").filter((entry) => entry.length > 0);
181
- }
182
-
183
- function sameEntry(
184
- left: WorkspaceEntry | undefined,
185
- right: WorkspaceEntry | undefined,
186
- ): boolean {
187
- if (!left || !right) return left === right;
188
- if (left.kind !== right.kind) return false;
189
- return (
190
- left.kind === "absent" ||
191
- (right.kind === "file" &&
192
- left.hash === right.hash &&
193
- left.bytes === right.bytes &&
194
- left.mode === right.mode)
195
- );
196
- }
197
-
198
- function requireMode(mode: number): number {
199
- if (!Number.isInteger(mode) || mode < 0 || mode > 0o777) {
200
- throw new Error("workspace-file-mode-invalid");
201
- }
202
- return mode;
203
- }
204
-
205
- function requireRevisionShape(value: unknown): WorkspaceRevision {
206
- if (!value || typeof value !== "object" || Array.isArray(value)) {
207
- throw new Error("workspace-revision-invalid");
208
- }
209
- const candidate = value as Partial<WorkspaceRevision>;
210
- if (
211
- typeof candidate.revisionId !== "string" ||
212
- !SHA256.test(candidate.revisionId) ||
213
- (candidate.parentRevisionId !== null &&
214
- (typeof candidate.parentRevisionId !== "string" ||
215
- !SHA256.test(candidate.parentRevisionId))) ||
216
- typeof candidate.manifestHash !== "string" ||
217
- !SHA256.test(candidate.manifestHash) ||
218
- !candidate.entries ||
219
- typeof candidate.entries !== "object" ||
220
- Array.isArray(candidate.entries)
221
- ) {
222
- throw new Error("workspace-revision-invalid");
223
- }
224
- for (const [relative, entry] of Object.entries(candidate.entries)) {
225
- requireSafeRelative(relative);
226
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
227
- throw new Error("workspace-revision-invalid");
228
- }
229
- if ((entry as WorkspaceEntry).kind === "absent") {
230
- if (Object.keys(entry).length !== 1) {
231
- throw new Error("workspace-revision-invalid");
232
- }
233
- continue;
234
- }
235
- const file = entry as WorkspaceFileEntry;
236
- if (
237
- file.kind !== "file" ||
238
- !SHA256.test(file.hash) ||
239
- !Number.isSafeInteger(file.bytes) ||
240
- file.bytes < 0 ||
241
- Object.keys(file).length !== 4
242
- ) {
243
- throw new Error("workspace-revision-invalid");
244
- }
245
- requireMode(file.mode);
246
- }
247
- return candidate as WorkspaceRevision;
248
- }
249
-
250
- /** Immutable manifests over private content-addressed workspace bytes. */
251
- export class WorkspaceStore {
252
- readonly root: string;
253
- readonly #revisions: string;
254
- readonly #artifacts: ArtifactStore;
255
-
256
- readonly #checkCancelled: () => void;
257
- readonly #onMetrics?: (metrics: WorkspaceIoMetrics) => void;
258
-
259
- constructor(
260
- root: string,
261
- artifacts: ArtifactStore,
262
- options: {
263
- checkCancelled?: () => void;
264
- onMetrics?: (metrics: WorkspaceIoMetrics) => void;
265
- } = {},
266
- ) {
267
- this.#checkCancelled = options.checkCancelled ?? (() => {});
268
- this.#onMetrics = options.onMetrics;
269
- if (!path.isAbsolute(root)) throw new Error("workspace-store-root-invalid");
270
- this.root = path.resolve(root);
271
- this.#revisions = path.join(this.root, "revisions");
272
- this.#artifacts = artifacts;
273
- ensureDirectory(this.root);
274
- ensureDirectory(this.#revisions);
275
- }
276
-
277
- #revisionPath(id: string): string {
278
- if (!SHA256.test(id)) throw new Error("workspace-revision-id-invalid");
279
- return path.join(this.#revisions, id.slice(0, 2), `${id}.json`);
280
- }
281
-
282
- #storeRevision(
283
- parentRevisionId: string | null,
284
- rawEntries: WorkspaceEntries,
285
- ): WorkspaceRevision {
286
- const entries = stableEntries(rawEntries);
287
- const manifest = manifestHash(entries);
288
- const id = revisionId(parentRevisionId, manifest);
289
- const revision: WorkspaceRevision = {
290
- revisionId: id,
291
- parentRevisionId,
292
- manifestHash: manifest,
293
- entries,
294
- };
295
- const target = this.#revisionPath(id);
296
- const existing = lstatSync(target, { throwIfNoEntry: false });
297
- if (existing) {
298
- const stored = this.getRevision(id);
299
- if (JSON.stringify(stored) !== JSON.stringify(revision)) {
300
- throw new Error("workspace-revision-conflict");
301
- }
302
- return stored;
303
- }
304
-
305
- writeAtomic(target, Buffer.from(`${JSON.stringify(revision)}\n`));
306
- const inherited = parentRevisionId
307
- ? this.getRevision(parentRevisionId).entries
308
- : {};
309
- for (const [relative, entry] of Object.entries(entries)) {
310
- if (entry.kind === "file" && !sameEntry(entry, inherited[relative]))
311
- this.#artifacts.retain(entry.hash);
312
- }
313
- return structuredClone(revision);
314
- }
315
-
316
- #isAncestor(ancestorId: string, revision: WorkspaceRevision): boolean {
317
- let cursor: WorkspaceRevision | null = revision;
318
- const visited = new Set<string>();
319
- while (cursor) {
320
- if (cursor.revisionId === ancestorId) return true;
321
- if (visited.has(cursor.revisionId)) {
322
- throw new Error("workspace-revision-cycle");
323
- }
324
- visited.add(cursor.revisionId);
325
- cursor = cursor.parentRevisionId
326
- ? this.getRevision(cursor.parentRevisionId)
327
- : null;
328
- }
329
- return false;
330
- }
331
-
332
- captureBaseline(input: CaptureBaselineInput): WorkspaceRevision {
333
- const consumerRoot = path.resolve(input.consumerRoot);
334
- const rootStat = lstatSync(consumerRoot, { throwIfNoEntry: false });
335
- if (!rootStat?.isDirectory() || rootStat.isSymbolicLink()) {
336
- throw new Error("unsafe-workspace-path");
337
- }
338
- const excluded = [".git", "node_modules", ...(input.excludedPaths ?? [])];
339
- for (const relative of excluded) requireSafeRelative(relative);
340
-
341
- return this.#captureBaselineFiles(
342
- input,
343
- this.#trackedFiles(input),
344
- consumerRoot,
345
- excluded,
346
- );
347
- }
348
-
349
- #trackedFiles(input: CaptureBaselineInput): string[] {
350
- const timeout = input.gitTimeoutMs ?? 30_000;
351
- if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 30_000)
352
- throw new Error("workspace-git-timeout-invalid");
353
- const consumerRoot = path.resolve(input.consumerRoot);
354
- let tracked: string[];
355
- try {
356
- tracked = parseNullSeparated(
357
- execFileSync("git", ["ls-files", "-z", "--cached"], {
358
- cwd: consumerRoot,
359
- maxBuffer: 32 * 1024 * 1024,
360
- timeout,
361
- killSignal: "SIGKILL",
362
- }),
363
- );
364
- } catch (error) {
365
- if (error instanceof Error && error.message === "unsafe-workspace-path") {
366
- throw error;
367
- }
368
- throw new Error("workspace-git-baseline-unavailable");
369
- }
370
-
371
- return tracked;
372
- }
373
-
374
- #captureBaselineFiles(
375
- input: CaptureBaselineInput,
376
- tracked: string[],
377
- consumerRoot: string,
378
- excluded: string[],
379
- ): WorkspaceRevision {
380
- const approved = input.approvedUntracked ?? [];
381
- const absent = input.absent ?? [];
382
- const selected = [...new Set([...tracked, ...approved])].sort();
383
- const entries: WorkspaceEntries = {};
384
- for (const relative of selected) {
385
- this.#checkCancelled();
386
- requireSafeRelative(relative);
387
- if (isExcluded(relative, excluded)) continue;
388
- const observation = observeSafePath(consumerRoot, relative);
389
- if (observation.kind === "absent") {
390
- entries[relative] = { kind: "absent" };
391
- continue;
392
- }
393
- if (observation.kind !== "file") throw new Error("unsafe-workspace-path");
394
- const absolute = path.join(consumerRoot, ...relative.split("/"));
395
- const bytes = readFileSync(absolute);
396
- const artifact = this.#artifacts.put(bytes);
397
- const stat = lstatSync(absolute);
398
- entries[relative] = {
399
- kind: "file",
400
- hash: artifact.hash,
401
- bytes: artifact.bytes,
402
- mode: requireMode(stat.mode & 0o777),
403
- };
404
- }
405
- for (const relative of [...new Set(absent)].sort()) {
406
- requireSafeRelative(relative);
407
- if (isExcluded(relative, excluded))
408
- throw new Error("unsafe-workspace-path");
409
- if (observeSafePath(consumerRoot, relative).kind !== "absent") {
410
- throw new Error("workspace-path-not-absent");
411
- }
412
- entries[relative] = { kind: "absent" };
413
- }
414
- return this.#storeRevision(null, entries);
415
- }
416
-
417
- getRevision(id: string): WorkspaceRevision {
418
- const target = this.#revisionPath(id);
419
- const stat = lstatSync(target, { throwIfNoEntry: false });
420
- if (!stat?.isFile() || stat.isSymbolicLink()) {
421
- throw new Error("workspace-revision-unavailable");
422
- }
423
- let parsed: unknown;
424
- try {
425
- parsed = JSON.parse(readFileSync(target, "utf8"));
426
- } catch {
427
- throw new Error("workspace-revision-invalid");
428
- }
429
- const revision = requireRevisionShape(parsed);
430
- if (
431
- revision.revisionId !== id ||
432
- (manifestHash(revision.entries) !== revision.manifestHash &&
433
- hash("cadence-workspace-manifest", JSON.stringify(revision.entries)) !==
434
- revision.manifestHash) ||
435
- revisionId(revision.parentRevisionId, revision.manifestHash) !== id
436
- ) {
437
- throw new Error("workspace-revision-integrity-invalid");
438
- }
439
- return structuredClone(revision);
440
- }
441
-
442
- createRevision(input: CreateRevisionInput): WorkspaceRevision {
443
- const parent = this.getRevision(input.parentRevisionId);
444
- const entries = stableEntries(parent.entries);
445
- for (const [relative, change] of Object.entries(input.changes).sort(
446
- ([left], [right]) => compareCanonicalStrings(left, right),
447
- )) {
448
- requireSafeRelative(relative);
449
- if (
450
- change === null ||
451
- (typeof change === "object" &&
452
- "kind" in change &&
453
- change.kind === "absent")
454
- ) {
455
- entries[relative] = { kind: "absent" };
456
- continue;
457
- }
458
- const descriptor =
459
- change instanceof Uint8Array
460
- ? {
461
- kind: "file" as const,
462
- bytes: change,
463
- mode:
464
- entries[relative]?.kind === "file"
465
- ? entries[relative].mode
466
- : 0o644,
467
- }
468
- : change;
469
- if (
470
- descriptor?.kind !== "file" ||
471
- !(descriptor.bytes instanceof Uint8Array)
472
- ) {
473
- throw new Error("workspace-change-invalid");
474
- }
475
- const artifact = this.#artifacts.put(descriptor.bytes);
476
- entries[relative] = {
477
- kind: "file",
478
- hash: artifact.hash,
479
- bytes: artifact.bytes,
480
- mode: requireMode(descriptor.mode ?? 0o644),
481
- };
482
- }
483
- return this.#storeRevision(parent.revisionId, entries);
484
- }
485
-
486
- mergeRevision(input: MergeRevisionInput): WorkspaceRevision {
487
- const base = this.getRevision(input.baseRevisionId);
488
- const current = this.getRevision(input.currentRevisionId);
489
- const candidate = this.getRevision(input.candidateRevisionId);
490
- if (
491
- candidate.parentRevisionId !== base.revisionId ||
492
- !this.#isAncestor(base.revisionId, current)
493
- ) {
494
- throw new Error("workspace-revision-base-invalid");
495
- }
496
- const boundPaths = [...new Set(input.boundPaths)];
497
- for (const relative of boundPaths) {
498
- requireSafeRelative(relative);
499
- if (!sameEntry(base.entries[relative], current.entries[relative])) {
500
- throw new Error("workspace-revision-stale");
501
- }
502
- }
503
-
504
- const allPaths = new Set([
505
- ...Object.keys(base.entries),
506
- ...Object.keys(candidate.entries),
507
- ]);
508
- const delta = [...allPaths].filter(
509
- (relative) =>
510
- !sameEntry(base.entries[relative], candidate.entries[relative]),
511
- );
512
- for (const relative of delta) {
513
- if (!sameEntry(base.entries[relative], current.entries[relative])) {
514
- throw new Error("workspace-revision-stale");
515
- }
516
- }
517
-
518
- const merged = stableEntries(current.entries);
519
- for (const relative of delta.sort()) {
520
- const entry = candidate.entries[relative];
521
- if (entry) merged[relative] = { ...entry };
522
- else delete merged[relative];
523
- }
524
- return this.#storeRevision(current.revisionId, merged);
525
- }
526
-
527
- materialize(revisionIdValue: string, destination: string): void {
528
- const revision = this.getRevision(revisionIdValue);
529
- const root = path.resolve(destination);
530
- ensureDirectory(root);
531
- for (const [relative, entry] of Object.entries(revision.entries)) {
532
- this.#checkCancelled();
533
- requireSafeRelative(relative);
534
- const observation = observeSafePath(root, relative);
535
- if (entry.kind === "absent") {
536
- const segments = relative.split("/");
537
- const supersededByFileAncestor = segments
538
- .slice(0, -1)
539
- .some(
540
- (_segment, index) =>
541
- revision.entries[segments.slice(0, index + 1).join("/")]?.kind ===
542
- "file",
543
- );
544
- if (supersededByFileAncestor) continue;
545
- if (observation.kind !== "absent") {
546
- throw new Error("workspace-materialize-conflict");
547
- }
548
- continue;
549
- }
550
- const segments = relative.split("/");
551
- let parent = root;
552
- for (const segment of segments.slice(0, -1)) {
553
- parent = path.join(parent, segment);
554
- ensureDirectory(parent);
555
- }
556
- const target = path.join(root, ...segments);
557
- if (observation.kind !== "absent") {
558
- throw new Error("workspace-materialize-conflict");
559
- }
560
- const bytes = this.#artifacts.copyVerified(entry.hash, target);
561
- if (bytes !== entry.bytes)
562
- throw new Error("workspace-revision-integrity-invalid");
563
- chmodSync(target, entry.mode);
564
- }
565
- }
566
- /** Used by the trusted I/O worker; Git is bounded and cancellable. */
567
- async captureBaselineWithGit(
568
- input: CaptureBaselineInput,
569
- signal?: AbortSignal,
570
- ): Promise<WorkspaceRevision> {
571
- signal?.throwIfAborted();
572
- const consumerRoot = path.resolve(input.consumerRoot);
573
- const stat = lstatSync(consumerRoot, { throwIfNoEntry: false });
574
- if (!stat?.isDirectory() || stat.isSymbolicLink())
575
- throw new Error("unsafe-workspace-path");
576
- const excluded = [".git", "node_modules", ...(input.excludedPaths ?? [])];
577
- for (const relative of excluded) requireSafeRelative(relative);
578
- const timeout = input.gitTimeoutMs ?? 30_000;
579
- if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 30_000)
580
- throw new Error("workspace-git-timeout-invalid");
581
- let tracked: string[];
582
- try {
583
- const { stdout } = await promisify(execFile)(
584
- "git",
585
- ["ls-files", "-z", "--cached"],
586
- {
587
- cwd: consumerRoot,
588
- encoding: "buffer",
589
- maxBuffer: 32 * 1024 * 1024,
590
- timeout,
591
- killSignal: "SIGKILL",
592
- signal,
593
- },
594
- );
595
- tracked = parseNullSeparated(stdout);
596
- } catch (error) {
597
- signal?.throwIfAborted();
598
- if (error instanceof Error && error.message === "unsafe-workspace-path")
599
- throw error;
600
- throw new Error("workspace-git-baseline-unavailable");
601
- }
602
- this.#checkCancelled();
603
- return this.#captureBaselineFiles(input, tracked, consumerRoot, excluded);
604
- }
605
-
606
- captureBaselineAsync(
607
- input: CaptureBaselineInput,
608
- signal?: AbortSignal,
609
- ): Promise<WorkspaceRevision> {
610
- return runWorkspaceIo({
611
- root: this.root,
612
- artifactRoot: this.#artifacts.root,
613
- operation: "captureBaseline",
614
- args: [input],
615
- signal,
616
- onMetrics: this.#onMetrics,
617
- });
618
- }
619
-
620
- materializeAsync(
621
- revisionId: string,
622
- destination: string,
623
- signal?: AbortSignal,
624
- ): Promise<void> {
625
- return runWorkspaceIo({
626
- root: this.root,
627
- artifactRoot: this.#artifacts.root,
628
- operation: "materialize",
629
- args: [revisionId, destination],
630
- signal,
631
- onMetrics: this.#onMetrics,
632
- });
633
- }
634
- }