@abelxiaoxing/cadence 1.8.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +324 -111
  2. package/THIRD_PARTY_NOTICES.md +15 -0
  3. package/agents/design-explorer.md +14 -26
  4. package/agents/diagnosis-worker.md +14 -25
  5. package/agents/implementation-worker.md +16 -35
  6. package/config/.env.example +2 -5
  7. package/config/workflow-task.example.json +7 -0
  8. package/docs/remote-access.md +60 -0
  9. package/docs/reuse-and-distribution.md +44 -0
  10. package/docs/service-management.md +108 -0
  11. package/licenses/bundled-web.txt +6245 -0
  12. package/licenses/pi-web-ui-MIT.txt +21 -0
  13. package/licenses/pi-web-ui-reuse.md +22 -0
  14. package/package.json +94 -21
  15. package/src/index.ts +22 -1807
  16. package/src/native-build.ts +6 -0
  17. package/src/native-client.ts +103 -0
  18. package/src/native-export.ts +58 -0
  19. package/src/native-history.ts +359 -0
  20. package/src/operator-cli.mjs +453 -1937
  21. package/src/plan-proposal.ts +87 -0
  22. package/src/sdk-worker.mjs +549 -0
  23. package/src/service/contracts/active.ts +82 -0
  24. package/src/service/contracts/budget.ts +148 -0
  25. package/src/service/contracts/build.ts +67 -0
  26. package/src/service/contracts/capture.ts +48 -0
  27. package/src/service/contracts/core.ts +33 -0
  28. package/src/service/contracts/current.ts +261 -0
  29. package/src/service/contracts/domain.ts +68 -0
  30. package/src/service/contracts/history.ts +2245 -0
  31. package/src/service/contracts/models.ts +139 -0
  32. package/src/service/coordination.ts +862 -0
  33. package/src/service/private-files.ts +204 -0
  34. package/src/service-cli.mjs +5592 -0
  35. package/src/service-client.ts +747 -0
  36. package/src/service-contract.ts +245 -0
  37. package/src/service-host.mjs +22382 -0
  38. package/src/service-http-client.ts +425 -0
  39. package/src/service-wire.ts +372 -0
  40. package/src/task-shell.ts +1045 -0
  41. package/src/task-store.ts +479 -0
  42. package/src/task-types.ts +184 -0
  43. package/src/verification-diagnostics.ts +29 -72
  44. package/src/worker-capture.mjs +1197 -0
  45. package/src/worker-public.mjs +1753 -0
  46. package/src/worker-redaction.mjs +608 -0
  47. package/src/worker-tools.mjs +202 -0
  48. package/web/dist/assets/KaTeX_AMS-Regular.ttf +0 -0
  49. package/web/dist/assets/KaTeX_AMS-Regular.woff +0 -0
  50. package/web/dist/assets/KaTeX_AMS-Regular.woff2 +0 -0
  51. package/web/dist/assets/KaTeX_Caligraphic-Bold.ttf +0 -0
  52. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff +0 -0
  53. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff2 +0 -0
  54. package/web/dist/assets/KaTeX_Caligraphic-Regular.ttf +0 -0
  55. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff +0 -0
  56. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff2 +0 -0
  57. package/web/dist/assets/KaTeX_Fraktur-Bold.ttf +0 -0
  58. package/web/dist/assets/KaTeX_Fraktur-Bold.woff +0 -0
  59. package/web/dist/assets/KaTeX_Fraktur-Bold.woff2 +0 -0
  60. package/web/dist/assets/KaTeX_Fraktur-Regular.ttf +0 -0
  61. package/web/dist/assets/KaTeX_Fraktur-Regular.woff +0 -0
  62. package/web/dist/assets/KaTeX_Fraktur-Regular.woff2 +0 -0
  63. package/web/dist/assets/KaTeX_Main-Bold.ttf +0 -0
  64. package/web/dist/assets/KaTeX_Main-Bold.woff +0 -0
  65. package/web/dist/assets/KaTeX_Main-Bold.woff2 +0 -0
  66. package/web/dist/assets/KaTeX_Main-BoldItalic.ttf +0 -0
  67. package/web/dist/assets/KaTeX_Main-BoldItalic.woff +0 -0
  68. package/web/dist/assets/KaTeX_Main-BoldItalic.woff2 +0 -0
  69. package/web/dist/assets/KaTeX_Main-Italic.ttf +0 -0
  70. package/web/dist/assets/KaTeX_Main-Italic.woff +0 -0
  71. package/web/dist/assets/KaTeX_Main-Italic.woff2 +0 -0
  72. package/web/dist/assets/KaTeX_Main-Regular.ttf +0 -0
  73. package/web/dist/assets/KaTeX_Main-Regular.woff +0 -0
  74. package/web/dist/assets/KaTeX_Main-Regular.woff2 +0 -0
  75. package/web/dist/assets/KaTeX_Math-BoldItalic.ttf +0 -0
  76. package/web/dist/assets/KaTeX_Math-BoldItalic.woff +0 -0
  77. package/web/dist/assets/KaTeX_Math-BoldItalic.woff2 +0 -0
  78. package/web/dist/assets/KaTeX_Math-Italic.ttf +0 -0
  79. package/web/dist/assets/KaTeX_Math-Italic.woff +0 -0
  80. package/web/dist/assets/KaTeX_Math-Italic.woff2 +0 -0
  81. package/web/dist/assets/KaTeX_SansSerif-Bold.ttf +0 -0
  82. package/web/dist/assets/KaTeX_SansSerif-Bold.woff +0 -0
  83. package/web/dist/assets/KaTeX_SansSerif-Bold.woff2 +0 -0
  84. package/web/dist/assets/KaTeX_SansSerif-Italic.ttf +0 -0
  85. package/web/dist/assets/KaTeX_SansSerif-Italic.woff +0 -0
  86. package/web/dist/assets/KaTeX_SansSerif-Italic.woff2 +0 -0
  87. package/web/dist/assets/KaTeX_SansSerif-Regular.ttf +0 -0
  88. package/web/dist/assets/KaTeX_SansSerif-Regular.woff +0 -0
  89. package/web/dist/assets/KaTeX_SansSerif-Regular.woff2 +0 -0
  90. package/web/dist/assets/KaTeX_Script-Regular.ttf +0 -0
  91. package/web/dist/assets/KaTeX_Script-Regular.woff +0 -0
  92. package/web/dist/assets/KaTeX_Script-Regular.woff2 +0 -0
  93. package/web/dist/assets/KaTeX_Size1-Regular.ttf +0 -0
  94. package/web/dist/assets/KaTeX_Size1-Regular.woff +0 -0
  95. package/web/dist/assets/KaTeX_Size1-Regular.woff2 +0 -0
  96. package/web/dist/assets/KaTeX_Size2-Regular.ttf +0 -0
  97. package/web/dist/assets/KaTeX_Size2-Regular.woff +0 -0
  98. package/web/dist/assets/KaTeX_Size2-Regular.woff2 +0 -0
  99. package/web/dist/assets/KaTeX_Size3-Regular.ttf +0 -0
  100. package/web/dist/assets/KaTeX_Size3-Regular.woff +0 -0
  101. package/web/dist/assets/KaTeX_Size3-Regular.woff2 +0 -0
  102. package/web/dist/assets/KaTeX_Size4-Regular.ttf +0 -0
  103. package/web/dist/assets/KaTeX_Size4-Regular.woff +0 -0
  104. package/web/dist/assets/KaTeX_Size4-Regular.woff2 +0 -0
  105. package/web/dist/assets/KaTeX_Typewriter-Regular.ttf +0 -0
  106. package/web/dist/assets/KaTeX_Typewriter-Regular.woff +0 -0
  107. package/web/dist/assets/KaTeX_Typewriter-Regular.woff2 +0 -0
  108. package/web/dist/assets/cadence.css +2 -0
  109. package/web/dist/assets/cadence.js +7 -0
  110. package/web/dist/assets/markdown.js +296 -0
  111. package/web/dist/assets/react.js +9 -0
  112. package/web/dist/assets/rolldown-runtime.js +1 -0
  113. package/web/dist/assets/timeline-client.js +41 -0
  114. package/web/dist/assets/vis-timeline.css +1274 -0
  115. package/web/dist/assets/vis-timeline.js +32 -0
  116. package/web/dist/index.html +18 -0
  117. package/web/dist/manifest.json +505 -0
  118. package/config/plan-draft.example.json +0 -125
  119. package/config/plan-draft.multiple-tasks.example.json +0 -375
  120. package/config/plan-draft.quick.example.json +0 -78
  121. package/config/routes.example.json +0 -39
  122. package/prompts/abel-design.md +0 -382
  123. package/prompts/abel-diagnose.md +0 -71
  124. package/prompts/abel-implement.md +0 -284
  125. package/prompts/abel-init.md +0 -52
  126. package/src/activation.ts +0 -44
  127. package/src/activity-contracts.ts +0 -82
  128. package/src/agent-registry.ts +0 -53
  129. package/src/apply-transaction.ts +0 -1437
  130. package/src/artifact-store.ts +0 -213
  131. package/src/build-windows-job.mjs +0 -95
  132. package/src/candidate-artifact.ts +0 -143
  133. package/src/candidate-patch.ts +0 -271
  134. package/src/candidate-workspace.ts +0 -80
  135. package/src/canonical.ts +0 -16
  136. package/src/change-contract-schema.ts +0 -191
  137. package/src/change-contract.ts +0 -324
  138. package/src/change-verification.ts +0 -1617
  139. package/src/child-budget.ts +0 -58
  140. package/src/child-model.ts +0 -142
  141. package/src/child-session.ts +0 -640
  142. package/src/contracts.ts +0 -2476
  143. package/src/control-contracts.ts +0 -382
  144. package/src/delivery-compiler.ts +0 -1805
  145. package/src/delivery-revision.ts +0 -42
  146. package/src/design-control.ts +0 -1299
  147. package/src/design-diagnostics.ts +0 -181
  148. package/src/design-journal.ts +0 -1773
  149. package/src/directory-sync.ts +0 -36
  150. package/src/durable-contracts.ts +0 -231
  151. package/src/durable-workflow.ts +0 -978
  152. package/src/evidence-draft.ts +0 -122
  153. package/src/execution-profile.ts +0 -64
  154. package/src/execution-retention.ts +0 -77
  155. package/src/file-snapshot.ts +0 -163
  156. package/src/implement-continuation.ts +0 -559
  157. package/src/implement-graph.ts +0 -690
  158. package/src/implement-plan.ts +0 -72
  159. package/src/install-config.d.mts +0 -6
  160. package/src/isolation-backend.ts +0 -353
  161. package/src/model-source.ts +0 -22
  162. package/src/openspec-cli.ts +0 -494
  163. package/src/operator-cli-entry.mjs +0 -24
  164. package/src/operator-tools.ts +0 -309
  165. package/src/package-candidate.ts +0 -227
  166. package/src/package-delivery.ts +0 -486
  167. package/src/package-state.ts +0 -320
  168. package/src/package-verification.ts +0 -635
  169. package/src/package-workflow.ts +0 -342
  170. package/src/packet-runtime.ts +0 -570
  171. package/src/parent-provider.ts +0 -375
  172. package/src/phase-execution.ts +0 -2259
  173. package/src/pi-adapter.ts +0 -19
  174. package/src/plan-draft-summary.ts +0 -527
  175. package/src/plan-draft.ts +0 -502
  176. package/src/remove-path.ts +0 -32
  177. package/src/route-policy.ts +0 -545
  178. package/src/run-state.ts +0 -420
  179. package/src/run-store.ts +0 -1179
  180. package/src/safe-path.ts +0 -77
  181. package/src/scoped-grep-worker.mjs +0 -23
  182. package/src/scoped-tools.ts +0 -775
  183. package/src/single-task-draft.ts +0 -142
  184. package/src/sqlite-schema.ts +0 -171
  185. package/src/state-root.ts +0 -215
  186. package/src/storage-schema.ts +0 -360
  187. package/src/subagent-activity.ts +0 -1417
  188. package/src/submit-tool.ts +0 -950
  189. package/src/task-ledger.ts +0 -1338
  190. package/src/transport-budget.ts +0 -52
  191. package/src/verification-capability.ts +0 -1191
  192. package/src/verification-environment-io.ts +0 -389
  193. package/src/verification-environment.ts +0 -162
  194. package/src/verification-identity.ts +0 -77
  195. package/src/verification-scan.ts +0 -64
  196. package/src/windows-job-backend.ts +0 -419
  197. package/src/windows-job.c +0 -149
  198. package/src/worker-broker.ts +0 -806
  199. package/src/workflow-engine.ts +0 -28
  200. package/src/workflow-policy.ts +0 -1679
  201. package/src/workflow-recovery-policy.ts +0 -97
  202. package/src/workflow-scheduling.ts +0 -105
  203. package/src/workflow-state-machine.ts +0 -4355
  204. package/src/workflow-status.ts +0 -576
  205. package/src/workspace-io-entry.mjs +0 -76
  206. package/src/workspace-io-worker.mjs +0 -1312
  207. package/src/workspace-io.ts +0 -89
  208. package/src/workspace-store.ts +0 -634
@@ -1,978 +0,0 @@
1
- import { ChangeVerification, sha256Bytes } from "./change-verification.ts";
2
- import type {
3
- DurableExecutionResources,
4
- DurablePhaseFact,
5
- DurableResourceInput,
6
- DurableWorkflowEngineOptions,
7
- } from "./durable-contracts.ts";
8
- import { assertExecutionsSettled } from "./execution-retention.ts";
9
- import { PhaseExecution } from "./phase-execution.ts";
10
- import { removePathSync } from "./remove-path.ts";
11
-
12
- export type {
13
- DurableChangeVerificationResult,
14
- DurablePhaseVerificationResult,
15
- DurableWorkflowEngineOptions,
16
- } from "./durable-contracts.ts";
17
-
18
- interface DurableRunResources extends DurableExecutionResources {
19
- transactions: ApplyTransaction;
20
- closed: boolean;
21
- }
22
-
23
- import { lstatSync, mkdirSync, readFileSync } from "node:fs";
24
- import path from "node:path";
25
- import { DatabaseSync } from "node:sqlite";
26
- import { ApplyTransaction } from "./apply-transaction.ts";
27
- import { ArtifactStore } from "./artifact-store.ts";
28
- import { compareCanonicalStrings } from "./canonical.ts";
29
- import type { ImplementPlan, PlanTaskDraft } from "./delivery-compiler.ts";
30
- import type { RoutePolicy } from "./route-policy.ts";
31
- import { observeSafePath } from "./safe-path.ts";
32
- import { configureSqlite, ensureSqliteSchema } from "./sqlite-schema.ts";
33
- import { ROUTE_HEALTH_SCHEMA } from "./storage-schema.ts";
34
- import { TaskLedger } from "./task-ledger.ts";
35
- import { type RouteHealthStore, RunWorkerBroker } from "./worker-broker.ts";
36
- import {
37
- deliveryBoundPaths,
38
- deliveryTrackingPath,
39
- hash,
40
- hasVerificationLifecycle,
41
- IDENTIFIER,
42
- implementationRouteRequirements,
43
- isRecord,
44
- SHA256,
45
- type WorkflowApplication,
46
- type WorkflowApplicationContext,
47
- type WorkflowChangeVerifier,
48
- type WorkflowRunLifecycle,
49
- type WorkflowWorker,
50
- workspaceEntryEqual,
51
- } from "./workflow-policy.ts";
52
- import { WorkflowEngine } from "./workflow-state-machine.ts";
53
- import { type WorkspaceRevision, WorkspaceStore } from "./workspace-store.ts";
54
-
55
- type DurableRouteHealth = Parameters<RouteHealthStore["set"]>[1];
56
-
57
- class DurableRouteHealthStore implements RouteHealthStore {
58
- readonly #databasePath: string;
59
- #database?: DatabaseSync;
60
- #closed = false;
61
-
62
- constructor(databasePath: string) {
63
- this.#databasePath = databasePath;
64
- }
65
-
66
- #open(): DatabaseSync {
67
- if (this.#closed) throw new Error("route-health-store-closed");
68
- if (this.#database) return this.#database;
69
- const database = new DatabaseSync(this.#databasePath);
70
- try {
71
- configureSqlite(database);
72
- ensureSqliteSchema(database, ROUTE_HEALTH_SCHEMA);
73
- } catch (error) {
74
- database.close();
75
- throw error;
76
- }
77
-
78
- this.#database = database;
79
- return database;
80
- }
81
-
82
- get(fingerprint: string): DurableRouteHealth | undefined {
83
- if (!SHA256.test(fingerprint)) return undefined;
84
- const row = this.#open()
85
- .prepare(
86
- `SELECT state, next_half_open_at, projection_json
87
- FROM route_health WHERE route_fingerprint = ?`,
88
- )
89
- .get(fingerprint) as
90
- | {
91
- state: string;
92
- next_half_open_at: number | null;
93
- projection_json: string;
94
- }
95
- | undefined;
96
- if (!row || !["healthy", "open", "half-open"].includes(row.state)) {
97
- return undefined;
98
- }
99
- let projection: unknown;
100
- try {
101
- projection = JSON.parse(row.projection_json);
102
- } catch {
103
- return undefined;
104
- }
105
- if (!isRecord(projection) || projection.state !== row.state) {
106
- return undefined;
107
- }
108
- const retryAt = row.next_half_open_at ?? undefined;
109
- const lastCode =
110
- typeof projection.lastCode === "string" &&
111
- projection.lastCode.length > 0 &&
112
- projection.lastCode.length <= 128
113
- ? projection.lastCode
114
- : undefined;
115
- const probeExpiresAt =
116
- Number.isSafeInteger(projection.probeExpiresAt) &&
117
- (projection.probeExpiresAt as number) >= 0
118
- ? (projection.probeExpiresAt as number)
119
- : undefined;
120
- return {
121
- state: row.state as DurableRouteHealth["state"],
122
- ...(retryAt === undefined ? {} : { retryAt }),
123
- ...(projection.probeInFlight === true ? { probeInFlight: true } : {}),
124
- ...(probeExpiresAt === undefined ? {} : { probeExpiresAt }),
125
- ...(lastCode === undefined ? {} : { lastCode }),
126
- };
127
- }
128
-
129
- set(fingerprint: string, health: DurableRouteHealth): void {
130
- if (
131
- !SHA256.test(fingerprint) ||
132
- !["healthy", "open", "half-open"].includes(health.state) ||
133
- (health.retryAt !== undefined &&
134
- (!Number.isSafeInteger(health.retryAt) || health.retryAt < 0)) ||
135
- (health.probeExpiresAt !== undefined &&
136
- (!Number.isSafeInteger(health.probeExpiresAt) ||
137
- health.probeExpiresAt < 0))
138
- ) {
139
- throw new Error("route-health-fact-invalid");
140
- }
141
- const projection = {
142
- state: health.state,
143
- ...(health.probeInFlight ? { probeInFlight: true } : {}),
144
- ...(health.probeExpiresAt === undefined
145
- ? {}
146
- : { probeExpiresAt: health.probeExpiresAt }),
147
- ...(health.lastCode ? { lastCode: health.lastCode.slice(0, 128) } : {}),
148
- };
149
- this.#open()
150
- .prepare(
151
- `INSERT INTO route_health(
152
- route_fingerprint, state, next_half_open_at, projection_json
153
- ) VALUES (?, ?, ?, ?)
154
- ON CONFLICT(route_fingerprint) DO UPDATE SET
155
- state = excluded.state,
156
- next_half_open_at = excluded.next_half_open_at,
157
- projection_json = excluded.projection_json`,
158
- )
159
- .run(
160
- fingerprint,
161
- health.state,
162
- health.retryAt ?? null,
163
- JSON.stringify(projection),
164
- );
165
- }
166
-
167
- close(): void {
168
- if (this.#closed) return;
169
- this.#database?.close();
170
- this.#closed = true;
171
- }
172
- }
173
-
174
- function ensurePrivateRunDirectory(directory: string): void {
175
- const existing = lstatSync(directory, { throwIfNoEntry: false });
176
- if (existing) {
177
- if (existing.isSymbolicLink() || !existing.isDirectory()) {
178
- throw new Error("workflow-run-data-unsafe");
179
- }
180
- return;
181
- }
182
- mkdirSync(directory, { recursive: true, mode: 0o700 });
183
- const created = lstatSync(directory);
184
- if (created.isSymbolicLink() || !created.isDirectory()) {
185
- throw new Error("workflow-run-data-unsafe");
186
- }
187
- }
188
-
189
- class DurableWorkflowComposition
190
- implements
191
- WorkflowWorker,
192
- WorkflowChangeVerifier,
193
- WorkflowApplication,
194
- WorkflowRunLifecycle
195
- {
196
- readonly #phase: PhaseExecution;
197
- readonly #verification: ChangeVerification;
198
- readonly #options: DurableWorkflowEngineOptions;
199
- readonly #routeHealth: DurableRouteHealthStore;
200
- #broker: RunWorkerBroker;
201
- readonly #runs = new Map<string, DurableRunResources>();
202
-
203
- constructor(options: DurableWorkflowEngineOptions) {
204
- this.#options = options;
205
- this.#routeHealth = new DurableRouteHealthStore(
206
- options.stateRoot.databasePath,
207
- );
208
- this.#broker = new RunWorkerBroker(options.routePolicy, {
209
- ...(options.now ? { now: options.now } : {}),
210
- healthStore: this.#routeHealth,
211
- });
212
- this.#verification = new ChangeVerification(options, {
213
- prepareResources: (input, signal) =>
214
- this.#prepareResources(input, signal),
215
- ledger: (resources, revision) => this.#ledger(resources, revision),
216
- run: (runId) => this.#runs.get(runId),
217
- revalidatePhasePolicy: (...args) =>
218
- this.#phase.revalidatePhasePolicy(...args),
219
- });
220
- this.#phase = new PhaseExecution(options, this.#broker, {
221
- prepareResources: (input, signal) =>
222
- this.#prepareResources(input, signal),
223
- ledger: (resources, revision) => this.#ledger(resources, revision),
224
- ensureVerificationBaseline: (input) =>
225
- this.#verification.ensureVerificationBaseline(input),
226
- verifyTaskAffected: (input) =>
227
- this.#verification.verifyTaskAffected(input),
228
- verifyPhase: (input) => this.#verification.verifyPhase(input),
229
- });
230
- }
231
-
232
- updateRoutePolicy(policy: RoutePolicy): void {
233
- this.#broker.updatePolicy(policy);
234
- }
235
-
236
- routePolicyStatus(): Record<string, unknown> {
237
- return this.#broker.status();
238
- }
239
-
240
- #runRoot(runId: string): string {
241
- if (!IDENTIFIER.test(runId)) throw new Error("workflow-run-id-invalid");
242
- const dataRoot = path.join(this.#options.stateRoot.rootDir, "run-data");
243
- const root = path.join(dataRoot, runId);
244
- const relative = path.relative(dataRoot, root);
245
- if (relative.startsWith("..") || path.isAbsolute(relative)) {
246
- throw new Error("workflow-run-data-unsafe");
247
- }
248
- return root;
249
- }
250
-
251
- #captureBaseline(
252
- workspaces: WorkspaceStore,
253
- plan: ImplementPlan,
254
- signal: AbortSignal,
255
- ) {
256
- const candidates = new Set<string>();
257
- const absent = new Set<string>();
258
- for (const relative of deliveryBoundPaths(plan)) {
259
- const observation = observeSafePath(this.#options.consumerRoot, relative);
260
- if (observation.kind === "file") candidates.add(relative);
261
- else if (observation.kind === "absent") absent.add(relative);
262
- else throw new Error("workflow-baseline-path-unsafe");
263
- }
264
- return workspaces.captureBaselineAsync(
265
- {
266
- consumerRoot: this.#options.consumerRoot,
267
- approvedUntracked: [...candidates].sort(),
268
- absent: [...absent].sort(),
269
- },
270
- signal,
271
- );
272
- }
273
-
274
- readonly #initializing = new Map<string, Promise<DurableRunResources>>();
275
-
276
- async #prepareResources(
277
- input: DurableResourceInput,
278
- signal: AbortSignal,
279
- ): Promise<DurableRunResources> {
280
- signal.throwIfAborted();
281
- assertExecutionsSettled(this.#options.stateRoot.rootDir);
282
- const pending = this.#initializing.get(input.runId);
283
- if (pending) return pending;
284
- if (
285
- this.#runs.has(input.runId) ||
286
- (input.baselineRevisionId && input.currentWorkspaceRevisionId)
287
- )
288
- return this.#resources(input);
289
- const initialize = async () => {
290
- if (
291
- !input.plan ||
292
- input.baselineRevisionId ||
293
- input.currentWorkspaceRevisionId
294
- )
295
- throw new Error("workflow-workspace-revision-unavailable");
296
- const root = this.#runRoot(input.runId);
297
- ensurePrivateRunDirectory(root);
298
- const artifacts = new ArtifactStore(path.join(root, "artifacts"));
299
- const workspaces = new WorkspaceStore(
300
- path.join(root, "workspaces"),
301
- artifacts,
302
- );
303
- const baseline = await this.#captureBaseline(
304
- workspaces,
305
- input.plan,
306
- signal,
307
- );
308
- signal.throwIfAborted();
309
- return this.#resources({
310
- ...input,
311
- baselineRevisionId: baseline.revisionId,
312
- currentWorkspaceRevisionId: baseline.revisionId,
313
- });
314
- };
315
- const promise = initialize();
316
- this.#initializing.set(input.runId, promise);
317
- try {
318
- return await promise;
319
- } finally {
320
- this.#initializing.delete(input.runId);
321
- }
322
- }
323
-
324
- #resources(input: {
325
- runId: string;
326
- deliveryRevision: number;
327
- plan?: ImplementPlan;
328
- baselineRevisionId?: string;
329
- currentWorkspaceRevisionId?: string;
330
- }): DurableRunResources {
331
- assertExecutionsSettled(this.#options.stateRoot.rootDir);
332
- const existing = this.#runs.get(input.runId);
333
- if (existing) {
334
- if (
335
- input.baselineRevisionId &&
336
- existing.baselineRevisionId !== input.baselineRevisionId
337
- ) {
338
- throw new Error("workflow-baseline-revision-conflict");
339
- }
340
- if (input.plan) {
341
- existing.plan = structuredClone(input.plan);
342
- existing.deliveryRevision = input.deliveryRevision;
343
- }
344
- return existing;
345
- }
346
- if (!input.plan) {
347
- throw new Error("workflow-plan-unavailable");
348
- }
349
- const root = this.#runRoot(input.runId);
350
- ensurePrivateRunDirectory(root);
351
- const artifacts = new ArtifactStore(path.join(root, "artifacts"));
352
- const workspaces = new WorkspaceStore(
353
- path.join(root, "workspaces"),
354
- artifacts,
355
- );
356
- const baselineRevisionId = input.baselineRevisionId;
357
- const currentRevisionId = input.currentWorkspaceRevisionId;
358
- if (!baselineRevisionId || !currentRevisionId)
359
- throw new Error("workflow-workspace-revision-unavailable");
360
- let originalBaseline = workspaces.getRevision(baselineRevisionId);
361
- const ancestors = new Set<string>();
362
- while (originalBaseline.parentRevisionId !== null) {
363
- if (ancestors.has(originalBaseline.revisionId))
364
- throw new Error("workflow-baseline-revision-conflict");
365
- ancestors.add(originalBaseline.revisionId);
366
- originalBaseline = workspaces.getRevision(
367
- originalBaseline.parentRevisionId,
368
- );
369
- }
370
- workspaces.getRevision(currentRevisionId);
371
- let resources!: DurableRunResources;
372
- const transactions = new ApplyTransaction({
373
- root: path.join(root, "transactions"),
374
- artifacts,
375
- workspaces,
376
- hooks: {
377
- awaitPostApplySettlement: this.#options.awaitPostApplySettlement,
378
- postApply: ({ transactionId, root: verificationRoot, signal }) =>
379
- this.#verification.verifyPostApply(
380
- resources,
381
- verificationRoot,
382
- signal,
383
- transactionId,
384
- ),
385
- },
386
- });
387
- resources = {
388
- runId: input.runId,
389
- root,
390
- plan: structuredClone(input.plan),
391
- deliveryRevision: input.deliveryRevision,
392
- artifacts,
393
- workspaces,
394
- ledgers: new Map(),
395
- transactions,
396
- baselineRevisionId,
397
- originalBaselineRevisionId: originalBaseline.revisionId,
398
- currentRevisionId,
399
- mergeTail: Promise.resolve(),
400
- baselinePromises: new Map(),
401
- closed: false,
402
- };
403
- resources.baselineLedger = this.#ledger(resources, 1);
404
- this.#runs.set(input.runId, resources);
405
- return resources;
406
- }
407
-
408
- #closeResources(resources: DurableRunResources): void {
409
- if (resources.closed) return;
410
- for (const ledger of resources.ledgers.values()) ledger.close();
411
- resources.ledgers.clear();
412
- resources.transactions.close();
413
- resources.closed = true;
414
- }
415
-
416
- #ledger(
417
- resources: DurableExecutionResources,
418
- deliveryRevision: number,
419
- ): TaskLedger {
420
- const existing = resources.ledgers.get(deliveryRevision);
421
- if (existing) return existing;
422
- const ledger = new TaskLedger({
423
- root: path.join(
424
- resources.root,
425
- "ledgers",
426
- `revision-${deliveryRevision}`,
427
- ),
428
- artifacts: resources.artifacts,
429
- });
430
- resources.ledgers.set(deliveryRevision, ledger);
431
- return ledger;
432
- }
433
-
434
- #expandedBaseline(
435
- resources: DurableRunResources,
436
- plan: ImplementPlan,
437
- ): WorkspaceRevision {
438
- const baseline = resources.workspaces.getRevision(
439
- resources.baselineRevisionId,
440
- );
441
- const candidates = new Map<string, boolean>(
442
- deliveryBoundPaths(plan).map((relative) => [relative, false]),
443
- );
444
- for (const task of plan.tasks) {
445
- for (const phase of Object.values(task.phases)) {
446
- for (const relative of phase.read) candidates.set(relative, false);
447
- for (const relative of [...phase.write, ...phase.delete]) {
448
- candidates.set(relative, true);
449
- }
450
- }
451
- }
452
- for (const output of plan.outputs) candidates.set(output.path, true);
453
- for (const task of plan.tasks) {
454
- if (task.agents.impact === "none" || !task.agents.target) continue;
455
- candidates.set(task.agents.target, task.agents.impact === "create-index");
456
- }
457
- const trackingPath = deliveryTrackingPath(plan);
458
- if (
459
- trackingPath &&
460
- (Object.hasOwn(baseline.entries, trackingPath) ||
461
- observeSafePath(this.#options.consumerRoot, trackingPath).kind ===
462
- "file")
463
- ) {
464
- candidates.set(trackingPath, false);
465
- }
466
- const changes: Record<
467
- string,
468
- { kind: "absent" } | { kind: "file"; bytes: Uint8Array; mode: number }
469
- > = {};
470
- for (const [relative, mayBeAbsent] of [...candidates].sort(
471
- ([left], [right]) => compareCanonicalStrings(left, right),
472
- )) {
473
- if (relative === ".") continue;
474
- const observation = observeSafePath(this.#options.consumerRoot, relative);
475
- if (observation.kind === "absent") {
476
- if (baseline.entries[relative]?.kind === "absent") continue;
477
- if (!mayBeAbsent)
478
- throw new Error("workflow-baseline-input-unavailable");
479
- changes[relative] = { kind: "absent" };
480
- continue;
481
- }
482
- if (observation.kind !== "file") {
483
- throw new Error("workflow-baseline-path-unsafe");
484
- }
485
- const target = path.join(
486
- this.#options.consumerRoot,
487
- ...relative.split("/"),
488
- );
489
- const stat = lstatSync(target);
490
- const bytes = readFileSync(target);
491
- const mode = stat.mode & 0o777;
492
- const prior = baseline.entries[relative];
493
- if (
494
- prior?.kind === "file" &&
495
- prior.hash === sha256Bytes(bytes) &&
496
- prior.bytes === bytes.byteLength &&
497
- prior.mode === mode
498
- ) {
499
- continue;
500
- }
501
- changes[relative] = {
502
- kind: "file",
503
- bytes,
504
- mode,
505
- };
506
- }
507
- return Object.keys(changes).length === 0
508
- ? baseline
509
- : resources.workspaces.createRevision({
510
- parentRevisionId: baseline.revisionId,
511
- changes,
512
- });
513
- }
514
-
515
- #orderedTasks(plan: ImplementPlan): PlanTaskDraft[] {
516
- const remaining = new Map(plan.tasks.map((task) => [task.taskId, task]));
517
- const ordered: PlanTaskDraft[] = [];
518
- const admitted = new Set<string>();
519
- while (remaining.size > 0) {
520
- let progressed = false;
521
- for (const task of plan.tasks) {
522
- if (
523
- !remaining.has(task.taskId) ||
524
- task.dependsOn.some((dependency) => !admitted.has(dependency))
525
- ) {
526
- continue;
527
- }
528
- remaining.delete(task.taskId);
529
- admitted.add(task.taskId);
530
- ordered.push(task);
531
- progressed = true;
532
- }
533
- if (!progressed) throw new Error("workflow-plan-dependency-cycle");
534
- }
535
- return ordered;
536
- }
537
-
538
- #phaseFacts(
539
- resources: DurableRunResources,
540
- task: {
541
- taskId: string;
542
- deliveryRevision: number;
543
- phase: "red" | "green" | "refactor";
544
- },
545
- ): DurablePhaseFact[] {
546
- let projection: unknown;
547
- try {
548
- projection = this.#ledger(resources, task.deliveryRevision).projection({
549
- runId: resources.runId,
550
- taskId: task.taskId,
551
- nextPhase: task.phase,
552
- });
553
- } catch (error) {
554
- if (
555
- error instanceof Error &&
556
- error.message === "ledger-task-unavailable"
557
- ) {
558
- return [];
559
- }
560
- throw error;
561
- }
562
- if (!isRecord(projection) || !Array.isArray(projection.history)) {
563
- throw new Error("workflow-ledger-projection-invalid");
564
- }
565
- return projection.history.flatMap((event): DurablePhaseFact[] => {
566
- if (
567
- !isRecord(event) ||
568
- (event.kind !== "phase-verified" && event.kind !== "repair-verified")
569
- ) {
570
- return [];
571
- }
572
- if (
573
- !["red", "green", "refactor"].includes(String(event.phase)) ||
574
- typeof event.isolatedRevisionId !== "string" ||
575
- !SHA256.test(event.isolatedRevisionId) ||
576
- !Array.isArray(event.outputFacts)
577
- ) {
578
- throw new Error("workflow-ledger-phase-invalid");
579
- }
580
- const outputFacts = event.outputFacts.map((fact) => {
581
- if (
582
- !isRecord(fact) ||
583
- typeof fact.path !== "string" ||
584
- (fact.kind !== "absent" && fact.kind !== "file")
585
- ) {
586
- throw new Error("workflow-ledger-phase-invalid");
587
- }
588
- if (fact.kind === "absent") {
589
- return { path: fact.path, kind: "absent" as const };
590
- }
591
- if (
592
- typeof fact.hash !== "string" ||
593
- !SHA256.test(fact.hash) ||
594
- !Number.isSafeInteger(fact.bytes) ||
595
- (fact.bytes as number) < 0
596
- ) {
597
- throw new Error("workflow-ledger-phase-invalid");
598
- }
599
- return {
600
- path: fact.path,
601
- kind: "file" as const,
602
- hash: fact.hash,
603
- bytes: fact.bytes as number,
604
- };
605
- });
606
- return [
607
- {
608
- kind: event.kind,
609
- phase: event.phase as DurablePhaseFact["phase"],
610
- isolatedRevisionId: event.isolatedRevisionId,
611
- outputFacts,
612
- },
613
- ];
614
- });
615
- }
616
-
617
- revalidateDelivery(
618
- input: Parameters<NonNullable<WorkflowWorker["revalidateDelivery"]>>[0],
619
- ): ReturnType<NonNullable<WorkflowWorker["revalidateDelivery"]>> {
620
- const resources = this.#resources({
621
- runId: input.runId,
622
- deliveryRevision: input.deliveryRevision,
623
- plan: input.plan,
624
- baselineRevisionId: input.baselineRevisionId,
625
- currentWorkspaceRevisionId: input.currentWorkspaceRevisionId,
626
- });
627
- const expandedBaseline = this.#expandedBaseline(resources, input.plan);
628
- const rows = new Map(input.tasks.map((task) => [task.taskId, task]));
629
- const facts = new Map(
630
- input.tasks.map((task) => [
631
- task.taskId,
632
- this.#phaseFacts(resources, task),
633
- ]),
634
- );
635
- const invalidated = new Set(input.invalidatedTaskIds);
636
- const ordered = this.#orderedTasks(input.plan);
637
- let rebuilt = expandedBaseline;
638
- for (;;) {
639
- let grew = false;
640
- rebuilt = expandedBaseline;
641
- for (const task of ordered) {
642
- const row = rows.get(task.taskId);
643
- if (!row || invalidated.has(task.taskId)) continue;
644
- if (task.dependsOn.some((dependency) => invalidated.has(dependency))) {
645
- invalidated.add(task.taskId);
646
- grew = true;
647
- continue;
648
- }
649
- for (const fact of facts.get(task.taskId) ?? []) {
650
- const phase = task.phases[fact.phase];
651
- if (!phase) {
652
- invalidated.add(task.taskId);
653
- grew = true;
654
- break;
655
- }
656
- const original = resources.workspaces.getRevision(
657
- fact.isolatedRevisionId,
658
- );
659
- if (!original.parentRevisionId) {
660
- throw new Error("workflow-ledger-revision-base-invalid");
661
- }
662
- const originalBase = resources.workspaces.getRevision(
663
- original.parentRevisionId,
664
- );
665
- const current = resources.workspaces.getRevision(rebuilt.revisionId);
666
- const boundaries =
667
- fact.kind === "repair-verified"
668
- ? Object.values(task.phases)
669
- : [phase];
670
- const boundPaths = [
671
- ...new Set(
672
- boundaries.flatMap((boundary) => [
673
- ...(row.contextReadPaths ?? []),
674
- ...boundary.read,
675
- ...boundary.write,
676
- ...boundary.delete,
677
- ...boundary.verificationInputs.flatMap((binding) =>
678
- binding.kind === "workspace" ? [binding.path] : [],
679
- ),
680
- ]),
681
- ),
682
- ];
683
- if (
684
- boundPaths.some(
685
- (relative) =>
686
- !workspaceEntryEqual(
687
- originalBase.entries[relative],
688
- current.entries[relative],
689
- ),
690
- )
691
- ) {
692
- invalidated.add(task.taskId);
693
- grew = true;
694
- break;
695
- }
696
- const changes: Record<
697
- string,
698
- | { kind: "absent" }
699
- | { kind: "file"; bytes: Uint8Array; mode: number }
700
- > = {};
701
- for (const output of fact.outputFacts) {
702
- const entry = original.entries[output.path];
703
- if (
704
- output.kind === "absent"
705
- ? entry?.kind !== "absent"
706
- : entry?.kind !== "file" ||
707
- entry.hash !== output.hash ||
708
- entry.bytes !== output.bytes
709
- ) {
710
- throw new Error("workflow-ledger-output-integrity-invalid");
711
- }
712
- changes[output.path] =
713
- entry.kind === "absent"
714
- ? { kind: "absent" }
715
- : {
716
- kind: "file",
717
- bytes: resources.artifacts.read(entry.hash),
718
- mode: entry.mode,
719
- };
720
- }
721
- rebuilt = resources.workspaces.createRevision({
722
- parentRevisionId: rebuilt.revisionId,
723
- changes,
724
- });
725
- }
726
- }
727
- for (const output of input.plan.outputs) {
728
- if (invalidated.has(output.producer.taskId)) continue;
729
- const produced = (facts.get(output.producer.taskId) ?? []).some(
730
- (fact) => fact.phase === output.producer.phase,
731
- );
732
- if (
733
- produced &&
734
- rebuilt.entries[output.path]?.kind !== "file" &&
735
- !invalidated.has(output.producer.taskId)
736
- ) {
737
- invalidated.add(output.producer.taskId);
738
- grew = true;
739
- }
740
- }
741
- if (!grew) break;
742
- }
743
- // Boundary expansion changes candidate/apply inputs, never the root capture
744
- // or its verification observations. Their contract-bound caches revalidate
745
- // only the obligations changed by this delivery.
746
- resources.baselinePromises.clear();
747
- resources.baselineRevisionId = expandedBaseline.revisionId;
748
- resources.currentRevisionId = rebuilt.revisionId;
749
- if (hasVerificationLifecycle(input.plan)) {
750
- for (const task of input.tasks) {
751
- if (task.state === "verified" && !invalidated.has(task.taskId)) {
752
- this.#phase.completeTracking(resources, task.taskId);
753
- }
754
- }
755
- }
756
- return {
757
- invalidatedTaskIds: [...invalidated].sort(),
758
- baselineRevisionId: resources.baselineRevisionId,
759
- currentWorkspaceRevisionId: resources.currentRevisionId,
760
- };
761
- }
762
-
763
- isContextReadAvailable(
764
- input: Parameters<NonNullable<WorkflowWorker["isContextReadAvailable"]>>[0],
765
- ): boolean {
766
- const resources = this.#resources(input);
767
- const revision = resources.workspaces.getRevision(
768
- input.currentWorkspaceRevisionId,
769
- );
770
- return revision.entries[input.path]?.kind === "file";
771
- }
772
-
773
- rebind(input: Parameters<WorkflowWorker["rebind"]>[0]) {
774
- const rebound = this.#broker.rebind({
775
- runId: input.runId,
776
- taskId: input.taskId,
777
- role: input.role,
778
- routeId: input.routeId,
779
- requirements: implementationRouteRequirements({ task: input.task }),
780
- });
781
- return rebound.ok
782
- ? {
783
- ok: true as const,
784
- routeId: rebound.route.id,
785
- routeFingerprint: rebound.route.fingerprint,
786
- }
787
- : { ok: false as const, code: rebound.code };
788
- }
789
-
790
- async prepare(
791
- input: Parameters<WorkflowApplication["begin"]>[0],
792
- ): Promise<Record<string, unknown>> {
793
- if (!input.baselineRevisionId || !input.currentWorkspaceRevisionId) {
794
- return { state: "paused", code: "workspace-revision-unavailable" };
795
- }
796
- const resources = await this.#prepareResources(
797
- {
798
- runId: input.runId,
799
- deliveryRevision: input.deliveryRevision,
800
- plan: input.plan,
801
- baselineRevisionId: input.baselineRevisionId,
802
- currentWorkspaceRevisionId: input.currentWorkspaceRevisionId,
803
- },
804
- input.signal,
805
- );
806
- if (!resources.verificationFact) {
807
- return { state: "paused", code: "verification-fact-unavailable" };
808
- }
809
- if (this.#options.verificationEnvironment) {
810
- if (!resources.environmentIdentity)
811
- return {
812
- state: "paused",
813
- code: "verification-environment-unavailable",
814
- };
815
- this.#ledger(resources, resources.deliveryRevision).putDurableFact(
816
- `apply-environment-${hash(input.transactionId).slice(0, 40)}`,
817
- { identity: resources.environmentIdentity },
818
- );
819
- }
820
- const prepared = await resources.transactions.prepare({
821
- transactionId: input.transactionId,
822
- consumerRoot: input.consumerRoot,
823
- baselineRevisionId: resources.baselineRevisionId,
824
- finalRevisionId: resources.currentRevisionId,
825
- boundPaths: [
826
- ...new Set([
827
- ...deliveryBoundPaths(input.plan),
828
- ...(input.contextReadPaths ?? []),
829
- ]),
830
- ].sort(),
831
- verificationFact: resources.verificationFact,
832
- });
833
- return prepared;
834
- }
835
-
836
- async applyPrepared(
837
- input: Parameters<WorkflowApplication["begin"]>[0],
838
- ): Promise<Record<string, unknown>> {
839
- const resources = await this.#prepareResources(
840
- {
841
- runId: input.runId,
842
- deliveryRevision: input.deliveryRevision,
843
- plan: input.plan,
844
- ...(input.baselineRevisionId
845
- ? { baselineRevisionId: input.baselineRevisionId }
846
- : {}),
847
- ...(input.currentWorkspaceRevisionId
848
- ? { currentWorkspaceRevisionId: input.currentWorkspaceRevisionId }
849
- : {}),
850
- },
851
- input.signal,
852
- );
853
- return resources.transactions.apply(input.transactionId, input.signal);
854
- }
855
-
856
- async begin(
857
- input: Parameters<WorkflowApplication["begin"]>[0],
858
- ): Promise<Record<string, unknown>> {
859
- const prepared = await this.prepare(input);
860
- return prepared.state === "prepared" ? this.applyPrepared(input) : prepared;
861
- }
862
-
863
- #resourcesForApplication(
864
- context: WorkflowApplicationContext | undefined,
865
- ): DurableRunResources {
866
- if (!context) throw new Error("workflow-application-context-unavailable");
867
- return this.#resources({
868
- runId: context.runId,
869
- deliveryRevision: context.deliveryRevision,
870
- plan: context.plan,
871
- ...(context.baselineRevisionId
872
- ? { baselineRevisionId: context.baselineRevisionId }
873
- : {}),
874
- ...(context.currentWorkspaceRevisionId
875
- ? { currentWorkspaceRevisionId: context.currentWorkspaceRevisionId }
876
- : {}),
877
- });
878
- }
879
-
880
- requestControl(
881
- transactionId: string,
882
- intent: "cancel" | "discard",
883
- context?: WorkflowApplicationContext,
884
- ): Record<string, unknown> {
885
- return this.#resourcesForApplication(context).transactions.requestControl(
886
- transactionId,
887
- intent,
888
- );
889
- }
890
-
891
- recover(
892
- transactionId: string,
893
- context?: WorkflowApplicationContext,
894
- ): Promise<Record<string, unknown>> {
895
- return this.#resourcesForApplication(context).transactions.recover(
896
- transactionId,
897
- );
898
- }
899
-
900
- cleanup(runId: string): void {
901
- assertExecutionsSettled(this.#options.stateRoot.rootDir, true);
902
- const resources = this.#runs.get(runId);
903
- if (resources) {
904
- this.#closeResources(resources);
905
- this.#runs.delete(runId);
906
- }
907
- removePathSync(this.#runRoot(runId), { recursive: true, force: true });
908
- }
909
-
910
- close(): void {
911
- for (const resources of this.#runs.values()) {
912
- this.#closeResources(resources);
913
- }
914
- this.#runs.clear();
915
- this.#routeHealth.close();
916
- }
917
- runAttempt(input: Parameters<WorkflowWorker["runAttempt"]>[0]) {
918
- return this.#phase.runAttempt(input);
919
- }
920
-
921
- async prepareTask(input: Parameters<WorkflowWorker["runAttempt"]>[0]) {
922
- const resources = await this.#prepareResources(input, input.signal);
923
- const workspace = {
924
- baselineRevisionId: resources.baselineRevisionId,
925
- currentWorkspaceRevisionId: resources.currentRevisionId,
926
- };
927
- if (hasVerificationLifecycle(input.plan)) {
928
- const captured = await this.#verification.ensureVerificationBaseline({
929
- resources,
930
- ledger: this.#ledger(resources, input.deliveryRevision),
931
- taskId: input.taskId,
932
- signal: input.signal,
933
- });
934
- if (!captured.ok)
935
- return {
936
- ...captured.outcome,
937
- ...workspace,
938
- ...(captured.outcome.kind === "paused"
939
- ? {
940
- verification: {
941
- scope: "baseline" as const,
942
- attribution: "environment" as const,
943
- },
944
- }
945
- : {}),
946
- };
947
- }
948
- return { kind: "prepared" as const, ...workspace };
949
- }
950
- hasPendingVerification(input: Parameters<WorkflowWorker["runAttempt"]>[0]) {
951
- return this.#phase.hasPendingVerification(input);
952
- }
953
- verify(input: Parameters<WorkflowChangeVerifier["verify"]>[0]) {
954
- return this.#verification.verify(input);
955
- }
956
- }
957
-
958
- export function openDurableWorkflowEngine(
959
- options: DurableWorkflowEngineOptions,
960
- ): WorkflowEngine {
961
- const composition = new DurableWorkflowComposition(options);
962
- return WorkflowEngine.open({
963
- consumerRoot: options.consumerRoot,
964
- stateRoot: options.stateRoot,
965
- deliverySource: options.deliverySource,
966
- worker: composition,
967
- ...(options.workHardLimit !== undefined
968
- ? { workHardLimit: options.workHardLimit }
969
- : {}),
970
- changeVerifier: composition,
971
- application: composition,
972
- lifecycle: composition,
973
- ...(options.now ? { now: options.now } : {}),
974
- ...(options.leaseTtlMs !== undefined
975
- ? { leaseTtlMs: options.leaseTtlMs }
976
- : {}),
977
- });
978
- }