@abelxiaoxing/cadence 1.5.2 → 1.6.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.
@@ -14,6 +14,7 @@ import type { PackageContext } from "./model-source.ts";
14
14
  import { inspectOpenSpecDelivery } from "./openspec-cli.ts";
15
15
  import { proposePackageCandidate } from "./package-candidate.ts";
16
16
  import { packageDeliverySource } from "./package-delivery.ts";
17
+ import { acquirePackageState } from "./package-state.ts";
17
18
  import {
18
19
  changeVerificationResult,
19
20
  executePackageVerification,
@@ -79,6 +80,42 @@ function affectedVerification(
79
80
 
80
81
  export function openPackageWorkflowService(
81
82
  initialContext: PackageContext,
83
+ ): PackageWorkflowService {
84
+ const state = acquirePackageState(
85
+ resolveStateRoot({
86
+ consumerRoot: path.resolve(initialContext.cwd),
87
+ xdgStateHome: process.env.XDG_STATE_HOME,
88
+ }),
89
+ );
90
+ try {
91
+ const service = openPreparedPackageWorkflowService(initialContext);
92
+ const notice = (result: Record<string, unknown>) =>
93
+ state.notice ? { ...result, packageStateReset: state.notice } : result;
94
+ return {
95
+ ...service,
96
+ async execute(...args) {
97
+ return notice(await service.execute(...args));
98
+ },
99
+ async executeDesign(...args) {
100
+ return notice(await service.executeDesign(...args));
101
+ },
102
+ async executeAmendment(...args) {
103
+ return notice(await service.executeAmendment(...args));
104
+ },
105
+ async close() {
106
+ // Never release ownership while an executor or storage connection may survive.
107
+ await service.close();
108
+ state.close();
109
+ },
110
+ };
111
+ } catch (error) {
112
+ state.close();
113
+ throw error;
114
+ }
115
+ }
116
+
117
+ function openPreparedPackageWorkflowService(
118
+ initialContext: PackageContext,
82
119
  ): PackageWorkflowService {
83
120
  const consumerRoot = path.resolve(initialContext.cwd);
84
121
  const routeResolution = loadRoutePolicy({
@@ -102,180 +139,188 @@ export function openPackageWorkflowService(
102
139
  stateRoot,
103
140
  inspectOpenSpec: inspectOpenSpecDelivery,
104
141
  });
105
- const implementationAgent = loadAgentDefinitions().find(
106
- (agent) => agent.role === "implementation-worker",
107
- );
108
- if (!implementationAgent) {
109
- throw new Error("implementation-worker-agent-unavailable");
110
- }
111
- const hostLimit = (name: string, fallback: number): number => {
112
- const value =
113
- process.env[name] === undefined ? fallback : Number(process.env[name]);
114
- if (!Number.isSafeInteger(value) || value < 1)
115
- throw new Error("verification-host-limit-invalid");
116
- return value;
117
- };
118
- const maxReportBytes = hostLimit(
119
- "ABEL_VERIFICATION_MAX_REPORT_BYTES",
120
- 64 * 1024 * 1024,
121
- );
122
- const workHardLimit = hostLimit("ABEL_WORK_MAX_UNITS", 512);
123
- const engine = openDurableWorkflowEngine({
124
- workHardLimit,
125
- verificationPolicy: `report-file-v5:${JSON.stringify(executionProfile())}`,
126
- verificationEnvironment: coalesceVerificationScans(
127
- (plan: import("./implement-plan.ts").ImplementPlan, signal) =>
128
- captureVerificationEnvironmentIdentity(
129
- consumerRoot,
130
- [
131
- ...plan.tasks.flatMap((task) => [
132
- ...Object.values(task.phases).map((phase) => phase.verification),
133
- task.affectedVerification,
134
- task.repairVerification,
135
- ]),
136
- plan.verification.baseline.fullSuite,
137
- plan.verification.change.fullSuite,
138
- plan.verification.change.postApply,
139
- ...(plan.verification.agentsCheckpoint.verification
140
- ? [plan.verification.agentsCheckpoint.verification]
141
- : []),
142
- ],
143
- signal,
144
- ),
145
- ),
146
- consumerRoot,
147
- stateRoot,
148
- deliverySource: packageDeliverySource(consumerRoot, {
149
- verifyGateProof: (input) => design.verifyGateProof(input),
150
- verifyFinalizedDelivery: (input) => design.verifyFinalizedDelivery(input),
151
- }),
152
- routePolicy: routeResolution.ok
153
- ? routeResolution.policy
154
- : unavailableRoutePolicy(),
155
- proposeCandidate: (input) =>
156
- proposePackageCandidate(
157
- input,
158
- contexts.getStore(),
159
- implementationAgent,
160
- feedback.getStore()?.current(),
161
- ),
162
- verifyPhase: async (input) =>
163
- phaseVerificationResult(
164
- await verify({
165
- maxReportBytes,
166
- executionWritePaths: input.executionWritePaths,
167
- root: input.root,
168
- dependencyOwner: consumerRoot,
169
- verification: input.verification,
170
- signal: input.signal,
171
- }),
172
- ),
173
- verifyChange: async (input) => {
174
- const verifications = input.verification
175
- ? [input.verification]
176
- : input.plan.tasks.map((task) => affectedVerification(task));
177
- let failure: ReturnType<typeof changeVerificationResult> | undefined;
178
- for (const verification of verifications) {
179
- const result = await verify({
180
- maxReportBytes,
181
- executionWritePaths: input.plan.tasks.flatMap((task) =>
182
- Object.values(task.phases).flatMap((phase) => [
183
- ...phase.write,
184
- ...phase.delete,
185
- ]),
142
+ try {
143
+ const implementationAgent = loadAgentDefinitions().find(
144
+ (agent) => agent.role === "implementation-worker",
145
+ );
146
+ if (!implementationAgent) {
147
+ throw new Error("implementation-worker-agent-unavailable");
148
+ }
149
+ const hostLimit = (name: string, fallback: number): number => {
150
+ const value =
151
+ process.env[name] === undefined ? fallback : Number(process.env[name]);
152
+ if (!Number.isSafeInteger(value) || value < 1)
153
+ throw new Error("verification-host-limit-invalid");
154
+ return value;
155
+ };
156
+ const maxReportBytes = hostLimit(
157
+ "ABEL_VERIFICATION_MAX_REPORT_BYTES",
158
+ 64 * 1024 * 1024,
159
+ );
160
+ const workHardLimit = hostLimit("ABEL_WORK_MAX_UNITS", 512);
161
+ const engine = openDurableWorkflowEngine({
162
+ workHardLimit,
163
+ verificationPolicy: `report-file-v5:${JSON.stringify(executionProfile())}`,
164
+ verificationEnvironment: coalesceVerificationScans(
165
+ (plan: import("./implement-plan.ts").ImplementPlan, signal) =>
166
+ captureVerificationEnvironmentIdentity(
167
+ consumerRoot,
168
+ [
169
+ ...plan.tasks.flatMap((task) => [
170
+ ...Object.values(task.phases).map(
171
+ (phase) => phase.verification,
172
+ ),
173
+ task.affectedVerification,
174
+ task.repairVerification,
175
+ ]),
176
+ plan.verification.baseline.fullSuite,
177
+ plan.verification.change.fullSuite,
178
+ plan.verification.change.postApply,
179
+ ...(plan.verification.agentsCheckpoint.verification
180
+ ? [plan.verification.agentsCheckpoint.verification]
181
+ : []),
182
+ ],
183
+ signal,
186
184
  ),
187
- root: input.root,
188
- dependencyOwner: consumerRoot,
189
- verification,
190
- signal: input.signal,
191
- });
192
- const observed = changeVerificationResult(result);
193
- if (!observed.ok) {
194
- if (observed.kind !== "verification") return observed;
195
- if (failure && !failure.ok && failure.kind === "verification") {
196
- failure.failureIdentities = [
197
- ...new Set([
198
- ...(failure.failureIdentities ?? []),
199
- ...(observed.failureIdentities ?? []),
185
+ ),
186
+ consumerRoot,
187
+ stateRoot,
188
+ deliverySource: packageDeliverySource(consumerRoot, {
189
+ verifyGateProof: (input) => design.verifyGateProof(input),
190
+ verifyFinalizedDelivery: (input) =>
191
+ design.verifyFinalizedDelivery(input),
192
+ }),
193
+ routePolicy: routeResolution.ok
194
+ ? routeResolution.policy
195
+ : unavailableRoutePolicy(),
196
+ proposeCandidate: (input) =>
197
+ proposePackageCandidate(
198
+ input,
199
+ contexts.getStore(),
200
+ implementationAgent,
201
+ feedback.getStore()?.current(),
202
+ ),
203
+ verifyPhase: async (input) =>
204
+ phaseVerificationResult(
205
+ await verify({
206
+ maxReportBytes,
207
+ executionWritePaths: input.executionWritePaths,
208
+ root: input.root,
209
+ dependencyOwner: consumerRoot,
210
+ verification: input.verification,
211
+ signal: input.signal,
212
+ }),
213
+ ),
214
+ verifyChange: async (input) => {
215
+ const verifications = input.verification
216
+ ? [input.verification]
217
+ : input.plan.tasks.map((task) => affectedVerification(task));
218
+ let failure: ReturnType<typeof changeVerificationResult> | undefined;
219
+ for (const verification of verifications) {
220
+ const result = await verify({
221
+ maxReportBytes,
222
+ executionWritePaths: input.plan.tasks.flatMap((task) =>
223
+ Object.values(task.phases).flatMap((phase) => [
224
+ ...phase.write,
225
+ ...phase.delete,
200
226
  ]),
201
- ];
202
- failure.attributionReliable =
203
- failure.attributionReliable !== false &&
204
- observed.attributionReliable !== false;
205
- } else failure = observed;
227
+ ),
228
+ root: input.root,
229
+ dependencyOwner: consumerRoot,
230
+ verification,
231
+ signal: input.signal,
232
+ });
233
+ const observed = changeVerificationResult(result);
234
+ if (!observed.ok) {
235
+ if (observed.kind !== "verification") return observed;
236
+ if (failure && !failure.ok && failure.kind === "verification") {
237
+ failure.failureIdentities = [
238
+ ...new Set([
239
+ ...(failure.failureIdentities ?? []),
240
+ ...(observed.failureIdentities ?? []),
241
+ ]),
242
+ ];
243
+ failure.attributionReliable =
244
+ failure.attributionReliable !== false &&
245
+ observed.attributionReliable !== false;
246
+ } else failure = observed;
247
+ }
206
248
  }
207
- }
208
- if (failure) return failure;
209
- return {
210
- ok: true,
211
- exitCode: 0,
212
- classification: "expected-green",
213
- };
214
- },
215
- });
216
- return {
217
- async execute(
218
- command: unknown,
219
- context = initialContext,
220
- signal,
221
- onActivity,
222
- ) {
223
- const operationRouteResolution = loadRoutePolicy({
224
- cwd: consumerRoot,
225
- home: homedir(),
226
- ...(context.model ? { parentModel: context.model } : {}),
227
- });
228
- engine.updateRoutePolicy(
229
- operationRouteResolution.ok
230
- ? operationRouteResolution.policy
231
- : unavailableRoutePolicy(),
232
- );
233
- const validation = validateControlCommand(command);
234
- if (!validation.ok) {
235
- const error = new Error(validation.code);
236
- error.name = "ControlCommandError";
237
- throw error;
238
- }
239
- return feedback.run(new VerificationFeedback(), () =>
240
- contexts.run(context, async () => {
241
- const outcome = await engine.execute(
242
- validation.value,
243
- signal,
244
- onActivity,
245
- );
246
- const routePolicy = visibleRoutePolicyStatus(
247
- operationRouteResolution,
248
- engine.routePolicyStatus(),
249
- );
250
- return {
251
- ...outcome,
252
- routePolicy,
253
- verificationDiagnostics: feedback.getStore()?.current() ?? [],
254
- };
255
- }),
256
- );
257
- },
258
- executeDesign(request: unknown) {
259
- return design.execute(request);
260
- },
261
- executeAmendment(change: string, batchId: string, request: unknown) {
262
- return engine.amend(change, batchId, request, (assertAuthority) =>
263
- design.executeWithAuthority(request, assertAuthority),
264
- );
265
- },
266
- assertDesignRun(runId: string) {
267
- design.assertDesignRun(runId);
268
- },
269
- recordDesignEvidence(input) {
270
- return design.recordEvidence(input);
271
- },
272
- async close() {
273
- contexts.disable();
274
- await engine.close();
275
- feedback.disable();
276
- design.close();
277
- },
278
- };
249
+ if (failure) return failure;
250
+ return {
251
+ ok: true,
252
+ exitCode: 0,
253
+ classification: "expected-green",
254
+ };
255
+ },
256
+ });
257
+ return {
258
+ async execute(
259
+ command: unknown,
260
+ context = initialContext,
261
+ signal,
262
+ onActivity,
263
+ ) {
264
+ const operationRouteResolution = loadRoutePolicy({
265
+ cwd: consumerRoot,
266
+ home: homedir(),
267
+ ...(context.model ? { parentModel: context.model } : {}),
268
+ });
269
+ engine.updateRoutePolicy(
270
+ operationRouteResolution.ok
271
+ ? operationRouteResolution.policy
272
+ : unavailableRoutePolicy(),
273
+ );
274
+ const validation = validateControlCommand(command);
275
+ if (!validation.ok) {
276
+ const error = new Error(validation.code);
277
+ error.name = "ControlCommandError";
278
+ throw error;
279
+ }
280
+ return feedback.run(new VerificationFeedback(), () =>
281
+ contexts.run(context, async () => {
282
+ const outcome = await engine.execute(
283
+ validation.value,
284
+ signal,
285
+ onActivity,
286
+ );
287
+ const routePolicy = visibleRoutePolicyStatus(
288
+ operationRouteResolution,
289
+ engine.routePolicyStatus(),
290
+ );
291
+ return {
292
+ ...outcome,
293
+ routePolicy,
294
+ verificationDiagnostics: feedback.getStore()?.current() ?? [],
295
+ };
296
+ }),
297
+ );
298
+ },
299
+ executeDesign(request: unknown) {
300
+ return design.execute(request);
301
+ },
302
+ executeAmendment(change: string, batchId: string, request: unknown) {
303
+ return engine.amend(change, batchId, request, (assertAuthority) =>
304
+ design.executeWithAuthority(request, assertAuthority),
305
+ );
306
+ },
307
+ assertDesignRun(runId: string) {
308
+ design.assertDesignRun(runId);
309
+ },
310
+ recordDesignEvidence(input) {
311
+ return design.recordEvidence(input);
312
+ },
313
+ async close() {
314
+ contexts.disable();
315
+ await engine.close();
316
+ feedback.disable();
317
+ design.close();
318
+ },
319
+ };
320
+ } catch (error) {
321
+ design.close();
322
+ throw error;
323
+ }
279
324
  }
280
325
 
281
326
  function visibleRoutePolicyStatus(
package/src/run-store.ts CHANGED
@@ -17,7 +17,10 @@ import {
17
17
  type ResolvedStateRoot,
18
18
  StateRootError,
19
19
  } from "./state-root.ts";
20
- import { RUN_SCHEMA as SCHEMA } from "./storage-schema.ts";
20
+ import {
21
+ LEGACY_RUN_SCHEMA_V2,
22
+ RUN_SCHEMA as SCHEMA,
23
+ } from "./storage-schema.ts";
21
24
 
22
25
  export class RunStoreFormatError extends Error {
23
26
  readonly code = "run-store-reset-required" as const;
@@ -115,7 +118,10 @@ function requireIdentifier(value: string, label: string): void {
115
118
  if (!IDENTIFIER.test(value)) throw new Error(`invalid-${label}`);
116
119
  }
117
120
 
118
- const LEGACY_SCHEMA_VERSION = 4;
121
+ const LEGACY_SCHEMA_VERSIONS = new Map([
122
+ [2, LEGACY_RUN_SCHEMA_V2],
123
+ [4, SCHEMA],
124
+ ]);
119
125
 
120
126
  function applicationTables(database: DatabaseSync): string[] {
121
127
  return (
@@ -153,25 +159,35 @@ function hasCurrentSchema(
153
159
  );
154
160
  }
155
161
 
156
- function isSupportedLegacySchema(
162
+ function supportedLegacyVersion(
157
163
  database: DatabaseSync,
158
164
  tables: readonly string[],
159
- ): boolean {
165
+ ): number | undefined {
160
166
  if (
161
167
  !tables.includes("schema_meta") ||
162
- !hasRequiredCoreSchema(database, tables) ||
163
168
  tableColumns(database, "schema_meta").join("\0") !== "version"
164
169
  ) {
165
- return false;
170
+ return undefined;
166
171
  }
167
172
  const rows = database
168
173
  .prepare("SELECT version FROM schema_meta")
169
174
  .all() as unknown as Array<{
170
175
  version: number;
171
176
  }>;
172
- return (
173
- rows.length === 1 && Number(rows[0]?.version) === LEGACY_SCHEMA_VERSION
174
- );
177
+ if (rows.length !== 1) return undefined;
178
+ const version = rows[0]?.version;
179
+ const schema = LEGACY_SCHEMA_VERSIONS.get(version);
180
+ if (!schema || !matchesSqliteSchema(database, schema)) return undefined;
181
+ // A v2 database cannot already contain any proof fields. Do not repair a
182
+ // partial/ambiguous upgrade or reinterpret malformed fields as authority.
183
+ if (
184
+ version === 2 &&
185
+ tableColumns(database, "delivery_bindings").some((column) =>
186
+ ["approval_revision", "contract_hash", "record_hash"].includes(column),
187
+ )
188
+ )
189
+ return undefined;
190
+ return version;
175
191
  }
176
192
 
177
193
  function isSqliteLocked(error: unknown): boolean {
@@ -210,7 +226,7 @@ function ensureCurrentSchema(
210
226
  const initialTables = applicationTables(database);
211
227
  if (hasCurrentSchema(database, initialTables)) return;
212
228
  let transactionStarted = false;
213
- let migrating = false;
229
+ let migrating: number | undefined;
214
230
  try {
215
231
  database.exec("BEGIN IMMEDIATE");
216
232
  transactionStarted = true;
@@ -219,11 +235,19 @@ function ensureCurrentSchema(
219
235
  database.exec(SCHEMA);
220
236
  } else if (hasCurrentSchema(database, tables)) {
221
237
  // Another opener may already have completed the same migration.
222
- } else if (isSupportedLegacySchema(database, tables)) {
223
- migrating = true;
224
- database.exec("DROP TABLE schema_meta");
225
238
  } else {
226
- throw new RunStoreFormatError(databasePath);
239
+ migrating = supportedLegacyVersion(database, tables);
240
+ if (migrating === undefined) throw new RunStoreFormatError(databasePath);
241
+ if (migrating === 2) {
242
+ database.exec(`
243
+ ALTER TABLE delivery_bindings ADD COLUMN approval_revision INTEGER;
244
+ ALTER TABLE delivery_bindings ADD COLUMN contract_hash TEXT;
245
+ ALTER TABLE delivery_bindings ADD COLUMN record_hash TEXT;
246
+ `);
247
+ }
248
+ if (!hasRequiredCoreSchema(database, tables))
249
+ throw new RunStoreFormatError(databasePath);
250
+ database.exec("DROP TABLE schema_meta");
227
251
  }
228
252
  database.exec("COMMIT");
229
253
  } catch (error) {
@@ -242,7 +266,7 @@ function ensureCurrentSchema(
242
266
  throw error;
243
267
  }
244
268
  if (migrating) {
245
- throw new RunStoreMigrationError(LEGACY_SCHEMA_VERSION, error);
269
+ throw new RunStoreMigrationError(migrating, error);
246
270
  }
247
271
  throw error;
248
272
  }
@@ -7,8 +7,14 @@ export const ROUTE_HEALTH_SCHEMA = `
7
7
  ) STRICT;
8
8
  `;
9
9
 
10
- /** Owner-private storage contracts. Migrations run atomically before use. */
11
- export const RUN_SCHEMA = `
10
+ /** v2 predates proof-bound delivery receipts; migration must not invent proof. */
11
+ const DELIVERY_PROOF_COLUMNS = `
12
+ approval_revision INTEGER,
13
+ contract_hash TEXT,
14
+ record_hash TEXT,`;
15
+
16
+ function runSchema(withDeliveryProof: boolean): string {
17
+ return `
12
18
  CREATE TABLE IF NOT EXISTS runs (
13
19
  run_id TEXT PRIMARY KEY,
14
20
  root_hash TEXT NOT NULL,
@@ -29,10 +35,7 @@ export const RUN_SCHEMA = `
29
35
  run_id TEXT NOT NULL REFERENCES runs(run_id) ON DELETE CASCADE,
30
36
  gate TEXT NOT NULL,
31
37
  revision INTEGER NOT NULL,
32
- receipt_hash TEXT NOT NULL,
33
- approval_revision INTEGER,
34
- contract_hash TEXT,
35
- record_hash TEXT,
38
+ receipt_hash TEXT NOT NULL,${withDeliveryProof ? DELIVERY_PROOF_COLUMNS : ""}
36
39
  operation_id TEXT NOT NULL,
37
40
  PRIMARY KEY (run_id, gate, revision),
38
41
  UNIQUE (run_id, operation_id)
@@ -102,6 +105,11 @@ ${ROUTE_HEALTH_SCHEMA}
102
105
  facts_json TEXT NOT NULL
103
106
  ) STRICT;
104
107
  `;
108
+ }
109
+
110
+ /** Owner-private storage contracts. Migrations run atomically before use. */
111
+ export const RUN_SCHEMA = runSchema(true);
112
+ export const LEGACY_RUN_SCHEMA_V2 = runSchema(false);
105
113
 
106
114
  export const DESIGN_SCHEMA = `
107
115
  CREATE TABLE IF NOT EXISTS design_facts (