@abelxiaoxing/cadence 1.2.4 → 1.4.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 (46) hide show
  1. package/README.md +155 -10
  2. package/package.json +5 -3
  3. package/prompts/abel-design.md +71 -17
  4. package/prompts/abel-diagnose.md +10 -1
  5. package/prompts/abel-implement.md +118 -20
  6. package/prompts/abel-init.md +9 -2
  7. package/src/apply-transaction.ts +16 -14
  8. package/src/artifact-store.ts +17 -0
  9. package/src/candidate-patch.ts +2 -1
  10. package/src/canonical.ts +16 -0
  11. package/src/change-contract.ts +268 -0
  12. package/src/child-session.ts +4 -3
  13. package/src/contracts.ts +141 -33
  14. package/src/control-contracts.ts +51 -1
  15. package/src/delivery-compiler.ts +148 -31
  16. package/src/design-control.ts +83 -15
  17. package/src/design-journal.ts +216 -72
  18. package/src/durable-workflow.ts +4385 -0
  19. package/src/implement-graph.ts +11 -16
  20. package/src/index.ts +399 -1079
  21. package/src/isolation-backend.ts +84 -23
  22. package/src/openspec-cli.ts +494 -0
  23. package/src/package-delivery.ts +486 -0
  24. package/src/package-verification.ts +509 -0
  25. package/src/route-policy.ts +1 -11
  26. package/src/run-state.ts +4 -16
  27. package/src/run-store.ts +5 -144
  28. package/src/scoped-grep-worker.mjs +23 -0
  29. package/src/scoped-tools.ts +312 -116
  30. package/src/sqlite-schema.ts +171 -0
  31. package/src/storage-schema.ts +352 -0
  32. package/src/subagent-activity.ts +14 -1
  33. package/src/submit-tool.ts +20 -2
  34. package/src/task-ledger.ts +14 -55
  35. package/src/verification-capability.ts +298 -102
  36. package/src/verification-environment.ts +213 -0
  37. package/src/verification-identity.ts +77 -0
  38. package/src/worker-broker.ts +97 -34
  39. package/src/workflow-engine.ts +28 -8285
  40. package/src/workflow-policy.ts +1427 -0
  41. package/src/workflow-state-machine.ts +4478 -0
  42. package/src/workspace-io-entry.mjs +58 -0
  43. package/src/workspace-io-worker.mjs +984 -0
  44. package/src/workspace-io.ts +84 -0
  45. package/src/workspace-store.ts +125 -19
  46. package/skills/abel-workflow/SKILL.md +0 -205
@@ -15,6 +15,7 @@ export interface IsolationRunInput {
15
15
  mounts?: IsolationMount[];
16
16
  environment?: Record<string, string>;
17
17
  signal?: AbortSignal;
18
+ outputWitness?: string;
18
19
  }
19
20
 
20
21
  export type IsolationRunResult =
@@ -24,6 +25,11 @@ export type IsolationRunResult =
24
25
  exitCode: number;
25
26
  stdout: string;
26
27
  stderr: string;
28
+ outputWitnessMatched?: boolean;
29
+ logs: {
30
+ stdout: { bytes: number; truncated: boolean };
31
+ stderr: { bytes: number; truncated: boolean };
32
+ };
27
33
  }
28
34
  | {
29
35
  ok: false;
@@ -31,14 +37,13 @@ export type IsolationRunResult =
31
37
  code:
32
38
  | "isolation-backend-unavailable"
33
39
  | "isolation-backend-launch-failed"
34
- | "isolation-execution-timeout"
35
- | "isolation-output-limit-exceeded";
40
+ | "isolation-execution-timeout";
36
41
  }
37
42
  | { ok: false; state: "cancelled"; code: "cancelled" };
38
43
 
39
44
  export const ISOLATION_RUN_LIMITS = Object.freeze({
40
45
  timeoutMs: 10 * 60_000,
41
- maxOutputBytes: 1024 * 1024,
46
+ maxOutputBytes: 256 * 1024,
42
47
  terminateGraceMs: 1_000,
43
48
  });
44
49
 
@@ -64,6 +69,59 @@ function validEnvironmentName(name: string): boolean {
64
69
  return /^[A-Za-z_][A-Za-z0-9_]*$/u.test(name);
65
70
  }
66
71
 
72
+ /** Retains independent head/tail copies; discarded chunks never stay referenced. */
73
+ class BoundedLog {
74
+ bytes = 0;
75
+ #head = Buffer.alloc(0);
76
+ #tail = Buffer.alloc(0);
77
+ readonly limit: number;
78
+ readonly #witness?: Buffer;
79
+ #witnessTail = Buffer.alloc(0);
80
+ witnessMatched = false;
81
+ constructor(limit: number, witness?: string) {
82
+ this.limit = limit;
83
+ if (witness) this.#witness = Buffer.from(witness);
84
+ }
85
+ append(chunk: Buffer | string): void {
86
+ const input = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
87
+ this.bytes += input.byteLength;
88
+ if (this.#witness && !this.witnessMatched) {
89
+ const searchable = Buffer.concat([this.#witnessTail, input]);
90
+ this.witnessMatched = searchable.includes(this.#witness);
91
+ this.#witnessTail = this.witnessMatched
92
+ ? Buffer.alloc(0)
93
+ : Buffer.from(
94
+ searchable.subarray(
95
+ Math.max(0, searchable.length - this.#witness.length + 1),
96
+ ),
97
+ );
98
+ }
99
+ const headLimit = Math.ceil(this.limit / 2);
100
+ const take = Math.min(input.length, headLimit - this.#head.length);
101
+ if (take > 0)
102
+ this.#head = Buffer.concat([this.#head, input.subarray(0, take)]);
103
+ const rest = input.subarray(take);
104
+ const tailLimit = this.limit - headLimit;
105
+ if (rest.length && tailLimit) {
106
+ this.#tail =
107
+ rest.length >= tailLimit
108
+ ? Buffer.from(rest.subarray(-tailLimit))
109
+ : Buffer.concat([
110
+ this.#tail.subarray(
111
+ Math.max(0, this.#tail.length + rest.length - tailLimit),
112
+ ),
113
+ rest,
114
+ ]);
115
+ }
116
+ }
117
+ text(): string {
118
+ return Buffer.concat([this.#head, this.#tail]).toString("utf8");
119
+ }
120
+ metadata() {
121
+ return { bytes: this.bytes, truncated: this.bytes > this.limit };
122
+ }
123
+ }
124
+
67
125
  /** Linux isolation capability. Lack of Bubblewrap is a pause, never a fallback. */
68
126
  export class BubblewrapIsolationBackend {
69
127
  readonly #bwrapPath: string;
@@ -103,6 +161,13 @@ export class BubblewrapIsolationBackend {
103
161
  }
104
162
 
105
163
  async run(input: IsolationRunInput): Promise<IsolationRunResult> {
164
+ if (
165
+ input.outputWitness !== undefined &&
166
+ (typeof input.outputWitness !== "string" ||
167
+ input.outputWitness.length < 1 ||
168
+ input.outputWitness.length > 512)
169
+ )
170
+ throw new Error("isolation-output-witness-invalid");
106
171
  if (!(await this.available())) {
107
172
  return {
108
173
  ok: false,
@@ -165,9 +230,8 @@ export class BubblewrapIsolationBackend {
165
230
 
166
231
  return new Promise((resolve) => {
167
232
  let settled = false;
168
- const stdout: Buffer[] = [];
169
- const stderr: Buffer[] = [];
170
- let capturedBytes = 0;
233
+ const stdout = new BoundedLog(this.#maxOutputBytes, input.outputWitness);
234
+ const stderr = new BoundedLog(this.#maxOutputBytes, input.outputWitness);
171
235
  let child: ReturnType<typeof spawn>;
172
236
  let executionTimer: ReturnType<typeof setTimeout> | undefined;
173
237
  let killTimer: ReturnType<typeof setTimeout> | undefined;
@@ -207,21 +271,11 @@ export class BubblewrapIsolationBackend {
207
271
  });
208
272
  return;
209
273
  }
210
- const capture = (destination: Buffer[], chunk: Buffer | string): void => {
211
- if (settled || terminationResult) return;
212
- const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
213
- const remaining = this.#maxOutputBytes - capturedBytes;
214
- if (remaining > 0) destination.push(bytes.subarray(0, remaining));
215
- if (bytes.byteLength > remaining) {
216
- capturedBytes = this.#maxOutputBytes;
217
- terminate({
218
- ok: false,
219
- state: "paused",
220
- code: "isolation-output-limit-exceeded",
221
- });
222
- return;
223
- }
224
- capturedBytes += bytes.byteLength;
274
+ const capture = (
275
+ destination: BoundedLog,
276
+ chunk: Buffer | string,
277
+ ): void => {
278
+ if (!settled && !terminationResult) destination.append(chunk);
225
279
  };
226
280
  child.stdout?.on("data", (chunk: Buffer | string) => {
227
281
  capture(stdout, chunk);
@@ -244,8 +298,15 @@ export class BubblewrapIsolationBackend {
244
298
  ok: true,
245
299
  state: "completed",
246
300
  exitCode: code ?? 1,
247
- stdout: Buffer.concat(stdout).toString("utf8"),
248
- stderr: Buffer.concat(stderr).toString("utf8"),
301
+ stdout: stdout.text(),
302
+ stderr: stderr.text(),
303
+ logs: { stdout: stdout.metadata(), stderr: stderr.metadata() },
304
+ ...(input.outputWitness
305
+ ? {
306
+ outputWitnessMatched:
307
+ stdout.witnessMatched || stderr.witnessMatched,
308
+ }
309
+ : {}),
249
310
  },
250
311
  );
251
312
  });
@@ -0,0 +1,494 @@
1
+ import { execFile } from "node:child_process";
2
+ import { lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ const PACKAGE_NAME = "@fission-ai/openspec";
6
+ export const OPENSPEC_LIMITS = Object.freeze({
7
+ timeoutMs: 30_000,
8
+ maxBuffer: 4 * 1024 * 1024,
9
+ });
10
+
11
+ type Command = "resolve" | "status" | "validate";
12
+ type Phase = "resolution" | "spawn" | "execution" | "protocol";
13
+ type Reason =
14
+ | "installation-not-found"
15
+ | "installation-invalid"
16
+ | "runtime-unavailable"
17
+ | "cwd-unavailable"
18
+ | "terminated"
19
+ | "unsafe-installation"
20
+ | "launch-failed"
21
+ | "timeout"
22
+ | "cancelled"
23
+ | "output-limit"
24
+ | "exit-nonzero"
25
+ | "json-invalid"
26
+ | "schema-invalid"
27
+ | "change-invalid";
28
+
29
+ /** Only code-owned, non-secret fields may cross the Design failure boundary. */
30
+ export interface OpenSpecDiagnostic {
31
+ code: "design-openspec-unavailable";
32
+ command: Command;
33
+ phase: Phase;
34
+ reason: Reason;
35
+ systemCode?: string;
36
+ exitCode?: string;
37
+ }
38
+
39
+ export class OpenSpecCliError extends Error {
40
+ readonly diagnostic: Readonly<OpenSpecDiagnostic>;
41
+
42
+ constructor(
43
+ command: Command,
44
+ phase: Phase,
45
+ reason: Reason,
46
+ detail: { systemCode?: string; exitCode?: number } = {},
47
+ ) {
48
+ super("design-openspec-unavailable");
49
+ this.name = "OpenSpecCliError";
50
+ this.diagnostic = Object.freeze({
51
+ code: "design-openspec-unavailable",
52
+ command,
53
+ phase,
54
+ reason,
55
+ ...(["ENOENT", "EINVAL", "EACCES", "EPERM", "ENOEXEC", "E2BIG"].includes(
56
+ detail.systemCode ?? "",
57
+ )
58
+ ? { systemCode: detail.systemCode }
59
+ : {}),
60
+ ...(Number.isSafeInteger(detail.exitCode) && (detail.exitCode ?? -1) >= 0
61
+ ? { exitCode: String(detail.exitCode) }
62
+ : {}),
63
+ });
64
+ }
65
+ }
66
+
67
+ export interface OpenSpecCliOptions {
68
+ /** Trusted operator configuration, never a Worker-supplied command string. */
69
+ environment?: NodeJS.ProcessEnv;
70
+ signal?: AbortSignal;
71
+ timeoutMs?: number;
72
+ maxBuffer?: number;
73
+ }
74
+
75
+ export interface OpenSpecInvocation {
76
+ executable: string;
77
+ entry: string;
78
+ }
79
+
80
+ function record(value: unknown): Record<string, unknown> | undefined {
81
+ return value !== null && typeof value === "object" && !Array.isArray(value)
82
+ ? (value as Record<string, unknown>)
83
+ : undefined;
84
+ }
85
+
86
+ function inside(root: string, target: string): boolean {
87
+ const relative = path.relative(root, target);
88
+ return (
89
+ relative === "" ||
90
+ (relative !== ".." &&
91
+ !relative.startsWith(`..${path.sep}`) &&
92
+ !path.isAbsolute(relative))
93
+ );
94
+ }
95
+
96
+ function envValue(
97
+ environment: NodeJS.ProcessEnv,
98
+ name: string,
99
+ ): string | undefined {
100
+ // Match Node's lexicographic, case-insensitive environment selection on Windows.
101
+ const key = Object.keys(environment)
102
+ .sort()
103
+ .find((candidate) =>
104
+ process.platform === "win32"
105
+ ? candidate.toUpperCase() === name.toUpperCase()
106
+ : candidate === name,
107
+ );
108
+ return key === undefined ? undefined : environment[key];
109
+ }
110
+
111
+ function packageEntry(root: string): string {
112
+ const canonicalRoot = realpathSync(root);
113
+ const manifestPath = realpathSync(path.join(canonicalRoot, "package.json"));
114
+ const manifestStat = lstatSync(manifestPath);
115
+ if (
116
+ !inside(canonicalRoot, manifestPath) ||
117
+ !manifestStat.isFile() ||
118
+ manifestStat.size > 1024 * 1024
119
+ )
120
+ throw new Error("manifest-limit");
121
+ const manifest = record(JSON.parse(readFileSync(manifestPath, "utf8")));
122
+ const bin =
123
+ typeof manifest?.bin === "string"
124
+ ? manifest.bin
125
+ : record(manifest?.bin)?.openspec;
126
+ if (
127
+ manifest?.name !== PACKAGE_NAME ||
128
+ typeof bin !== "string" ||
129
+ path.isAbsolute(bin)
130
+ )
131
+ throw new Error("manifest-invalid");
132
+ const entry = realpathSync(path.resolve(canonicalRoot, bin));
133
+ if (
134
+ !inside(canonicalRoot, entry) ||
135
+ !/\.(?:cjs|mjs|js)$/iu.test(entry) ||
136
+ !lstatSync(entry).isFile()
137
+ )
138
+ throw new Error("entry-invalid");
139
+ return entry;
140
+ }
141
+
142
+ function canonicalConsumerRoot(consumerRoot: string): string {
143
+ try {
144
+ const root = realpathSync(consumerRoot);
145
+ if (!lstatSync(root).isDirectory()) throw new Error("cwd-invalid");
146
+ return root;
147
+ } catch (error) {
148
+ throw new OpenSpecCliError("resolve", "resolution", "cwd-unavailable", {
149
+ systemCode: (error as NodeJS.ErrnoException).code,
150
+ });
151
+ }
152
+ }
153
+
154
+ function commandIn(directory: string): string | undefined {
155
+ const names =
156
+ process.platform === "win32"
157
+ ? ["openspec.exe", "openspec.cmd", "openspec"]
158
+ : ["openspec"];
159
+ // Windows filesystems are usually case-insensitive; reject ambiguous names.
160
+ const entries = process.platform === "win32" ? readdirSync(directory) : names;
161
+ for (const name of names) {
162
+ const matches = entries.filter((entry) => entry.toLowerCase() === name);
163
+ if (matches.length > 1) throw new Error("ambiguous-command");
164
+ if (matches.length === 1) {
165
+ const candidate = path.join(directory, matches[0]);
166
+ if (lstatSync(candidate, { throwIfNoEntry: false })) return candidate;
167
+ }
168
+ }
169
+ return undefined;
170
+ }
171
+
172
+ /** Resolve once per inspection. Never execute or parse a shell shim. */
173
+ export function resolveOpenSpecInvocation(
174
+ consumerRoot: string,
175
+ environment: NodeJS.ProcessEnv = process.env,
176
+ ): OpenSpecInvocation {
177
+ const configuredRoot = envValue(environment, "ABEL_OPENSPEC_PACKAGE_ROOT");
178
+ const configuredNode = envValue(environment, "ABEL_OPENSPEC_NODE");
179
+ const node =
180
+ configuredNode ??
181
+ (process.release.name === "node" && !process.versions.bun
182
+ ? process.execPath
183
+ : undefined);
184
+ let executable: string;
185
+ try {
186
+ if (!node || !path.isAbsolute(node) || /\.(?:cmd|bat|ps1)$/iu.test(node)) {
187
+ throw new Error("runtime-invalid");
188
+ }
189
+ executable = realpathSync(node);
190
+ if (!lstatSync(executable).isFile()) throw new Error("runtime-invalid");
191
+ } catch {
192
+ throw new OpenSpecCliError("resolve", "resolution", "runtime-unavailable");
193
+ }
194
+ if (configuredRoot !== undefined) {
195
+ try {
196
+ if (!path.isAbsolute(configuredRoot)) throw new Error("root-invalid");
197
+ return { executable, entry: packageEntry(configuredRoot) };
198
+ } catch {
199
+ throw new OpenSpecCliError(
200
+ "resolve",
201
+ "resolution",
202
+ "installation-invalid",
203
+ );
204
+ }
205
+ }
206
+
207
+ const consumer = canonicalConsumerRoot(consumerRoot);
208
+ const directories = (envValue(environment, "PATH") ?? "").split(
209
+ path.delimiter,
210
+ );
211
+ for (const directory of directories) {
212
+ // Do not introduce implicit cwd search or automatically trust repository CLIs.
213
+ if (!path.isAbsolute(directory)) continue;
214
+ let command: string | undefined;
215
+ let canonicalDirectory: string;
216
+ try {
217
+ canonicalDirectory = realpathSync(directory);
218
+ if (inside(consumer, canonicalDirectory)) continue;
219
+ command = commandIn(canonicalDirectory);
220
+ } catch {
221
+ continue;
222
+ }
223
+ if (!command) continue;
224
+ try {
225
+ const target = realpathSync(command);
226
+ if (inside(consumer, target)) {
227
+ throw new OpenSpecCliError(
228
+ "resolve",
229
+ "resolution",
230
+ "unsafe-installation",
231
+ );
232
+ }
233
+ // npm Windows/custom prefix and Unix global layouts. Symlinked npm/Bun
234
+ // entries are also discovered by walking their real target's ancestors.
235
+ const layoutRoots = [
236
+ path.join(canonicalDirectory, "node_modules", PACKAGE_NAME),
237
+ path.resolve(canonicalDirectory, "../lib/node_modules", PACKAGE_NAME),
238
+ ];
239
+ const roots: string[] = [];
240
+ let ancestor = path.dirname(target);
241
+ for (let depth = 0; depth < 8; depth++) {
242
+ roots.push(ancestor);
243
+ const parent = path.dirname(ancestor);
244
+ if (parent === ancestor) break;
245
+ ancestor = parent;
246
+ }
247
+ // A real symlink target identifies the selected version more precisely
248
+ // than an adjacent global installation.
249
+ const linked = lstatSync(command).isSymbolicLink();
250
+ const candidates = linked ? roots : layoutRoots;
251
+ for (const root of candidates) {
252
+ let entry: string;
253
+ try {
254
+ entry = packageEntry(root);
255
+ if (linked && entry !== target) continue;
256
+ } catch {
257
+ continue;
258
+ }
259
+ if (inside(consumer, entry)) {
260
+ throw new OpenSpecCliError(
261
+ "resolve",
262
+ "resolution",
263
+ "unsafe-installation",
264
+ );
265
+ }
266
+ return { executable, entry };
267
+ }
268
+ } catch (error) {
269
+ if (error instanceof OpenSpecCliError) throw error;
270
+ }
271
+ // A broken/shadowing installation must not silently select another version.
272
+ throw new OpenSpecCliError("resolve", "resolution", "installation-invalid");
273
+ }
274
+ throw new OpenSpecCliError("resolve", "resolution", "installation-not-found");
275
+ }
276
+
277
+ interface CommandResult {
278
+ stdout: string;
279
+ exitCode: number;
280
+ }
281
+
282
+ function execute(
283
+ invocation: OpenSpecInvocation,
284
+ command: "status" | "validate",
285
+ args: string[],
286
+ consumerRoot: string,
287
+ options: OpenSpecCliOptions,
288
+ ): Promise<CommandResult> {
289
+ return new Promise((resolve, reject) => {
290
+ let child: ReturnType<typeof execFile> | undefined;
291
+ const abort = () => child?.kill("SIGKILL");
292
+ const failLaunch = (error: unknown) => {
293
+ const code = (error as NodeJS.ErrnoException)?.code;
294
+ reject(
295
+ new OpenSpecCliError(command, "spawn", "launch-failed", {
296
+ systemCode: typeof code === "string" ? code : undefined,
297
+ }),
298
+ );
299
+ };
300
+ try {
301
+ child = execFile(
302
+ invocation.executable,
303
+ [invocation.entry, ...args],
304
+ {
305
+ cwd: consumerRoot,
306
+ env: {
307
+ ...(options.environment ?? process.env),
308
+ OPENSPEC_TELEMETRY: "0",
309
+ },
310
+ encoding: "utf8",
311
+ shell: false,
312
+ windowsHide: true,
313
+ timeout: options.timeoutMs ?? OPENSPEC_LIMITS.timeoutMs,
314
+ maxBuffer: options.maxBuffer ?? OPENSPEC_LIMITS.maxBuffer,
315
+ // This adapter launches a single Node CLI, not a shell/process tree.
316
+ killSignal: "SIGKILL",
317
+ },
318
+ (error, stdout) => {
319
+ options.signal?.removeEventListener("abort", abort);
320
+ if (options.signal?.aborted) {
321
+ return reject(
322
+ new OpenSpecCliError(command, "execution", "cancelled"),
323
+ );
324
+ }
325
+ if (!error) return resolve({ stdout, exitCode: 0 });
326
+ const code = error.code;
327
+ if (code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
328
+ return reject(
329
+ new OpenSpecCliError(command, "execution", "output-limit"),
330
+ );
331
+ }
332
+ if (error.killed) {
333
+ return reject(
334
+ new OpenSpecCliError(command, "execution", "timeout"),
335
+ );
336
+ }
337
+ if (error.signal) {
338
+ return reject(
339
+ new OpenSpecCliError(command, "execution", "terminated"),
340
+ );
341
+ }
342
+ if (typeof code === "number")
343
+ return resolve({ stdout, exitCode: code });
344
+ reject(
345
+ new OpenSpecCliError(command, "spawn", "launch-failed", {
346
+ systemCode: typeof code === "string" ? code : undefined,
347
+ }),
348
+ );
349
+ },
350
+ );
351
+ child.stdin?.end();
352
+ options.signal?.addEventListener("abort", abort, { once: true });
353
+ if (options.signal?.aborted) abort();
354
+ } catch (error) {
355
+ options.signal?.removeEventListener("abort", abort);
356
+ failLaunch(error);
357
+ }
358
+ });
359
+ }
360
+
361
+ function parseJson(result: CommandResult, command: "status" | "validate") {
362
+ if (
363
+ result.exitCode !== 0 &&
364
+ !(command === "validate" && result.exitCode === 1)
365
+ ) {
366
+ throw new OpenSpecCliError(command, "execution", "exit-nonzero", result);
367
+ }
368
+ try {
369
+ const parsed = record(JSON.parse(result.stdout));
370
+ if (!parsed) throw new Error("not-object");
371
+ return parsed;
372
+ } catch {
373
+ throw new OpenSpecCliError(command, "protocol", "json-invalid", result);
374
+ }
375
+ }
376
+
377
+ export interface OpenSpecDeliveryInspection {
378
+ change: string;
379
+ schema: string;
380
+ planningComplete: boolean;
381
+ strictValid: boolean;
382
+ artifactPaths: string[];
383
+ }
384
+
385
+ export async function inspectOpenSpecDelivery(
386
+ consumerRoot: string,
387
+ change: string,
388
+ options: OpenSpecCliOptions = {},
389
+ ): Promise<OpenSpecDeliveryInspection> {
390
+ if (!/^[a-z0-9](?:[a-z0-9-]{0,126}[a-z0-9])?$/u.test(change)) {
391
+ throw new OpenSpecCliError("resolve", "resolution", "change-invalid");
392
+ }
393
+ for (const limit of [options.timeoutMs, options.maxBuffer]) {
394
+ if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) {
395
+ throw new Error("openspec-limit-invalid");
396
+ }
397
+ }
398
+ if (options.signal?.aborted) {
399
+ throw new OpenSpecCliError("resolve", "execution", "cancelled");
400
+ }
401
+ consumerRoot = canonicalConsumerRoot(consumerRoot);
402
+ options = {
403
+ ...options,
404
+ environment: { ...(options.environment ?? process.env) },
405
+ };
406
+ const invocation = resolveOpenSpecInvocation(
407
+ consumerRoot,
408
+ options.environment,
409
+ );
410
+ // allSettled ensures neither child outlives a failed inspection. Both have
411
+ // bounded time/output; deterministic status-first diagnostics avoid races.
412
+ const results = await Promise.allSettled([
413
+ execute(
414
+ invocation,
415
+ "status",
416
+ ["status", "--change", change, "--json"],
417
+ consumerRoot,
418
+ options,
419
+ ),
420
+ execute(
421
+ invocation,
422
+ "validate",
423
+ ["validate", change, "--strict", "--json", "--no-interactive"],
424
+ consumerRoot,
425
+ options,
426
+ ),
427
+ ]);
428
+ const executions = results.map((result) => {
429
+ if (result.status === "rejected") throw result.reason;
430
+ return result.value;
431
+ });
432
+ const status = parseJson(executions[0], "status");
433
+ const validation = parseJson(executions[1], "validate");
434
+ const changeRoot = path.resolve(consumerRoot, "openspec", "changes", change);
435
+ const paths = record(status.artifactPaths);
436
+ const artifactPaths: string[] = [];
437
+ let invalidPaths = !paths;
438
+ for (const entry of Object.values(paths ?? {})) {
439
+ const outputs = record(entry)?.existingOutputPaths;
440
+ if (!Array.isArray(outputs)) {
441
+ invalidPaths = true;
442
+ continue;
443
+ }
444
+ for (const candidate of outputs) {
445
+ if (typeof candidate !== "string" || candidate.includes("\0")) {
446
+ invalidPaths = true;
447
+ continue;
448
+ }
449
+ // Relative CLI output is relative to its cwd, not the extension process.
450
+ const resolved = path.resolve(consumerRoot, candidate);
451
+ const relative = path.relative(changeRoot, resolved);
452
+ if (!relative || !inside(changeRoot, resolved)) {
453
+ invalidPaths = true;
454
+ continue;
455
+ }
456
+ artifactPaths.push(relative.split(path.sep).join("/"));
457
+ }
458
+ }
459
+ if (
460
+ status.changeName !== change ||
461
+ typeof status.schemaName !== "string" ||
462
+ !status.schemaName ||
463
+ ("isPlanningComplete" in status &&
464
+ typeof status.isPlanningComplete !== "boolean") ||
465
+ typeof status.isComplete !== "boolean" ||
466
+ invalidPaths ||
467
+ artifactPaths.length === 0
468
+ )
469
+ throw new OpenSpecCliError("status", "protocol", "schema-invalid");
470
+ const items = Array.isArray(validation.items) ? validation.items : [];
471
+ const item = record(items[0]);
472
+ if (
473
+ items.length !== 1 ||
474
+ item?.id !== change ||
475
+ typeof item.valid !== "boolean" ||
476
+ (executions[1].exitCode !== 0 && item.valid)
477
+ ) {
478
+ throw new OpenSpecCliError(
479
+ "validate",
480
+ "protocol",
481
+ "schema-invalid",
482
+ executions[1],
483
+ );
484
+ }
485
+ return {
486
+ change,
487
+ schema: status.schemaName,
488
+ // OpenSpec 1.5.0 reports artifact completion only as isComplete.
489
+ // When a separate planning flag is present, both flags must be true.
490
+ planningComplete: status.isComplete && status.isPlanningComplete !== false,
491
+ strictValid: item.valid,
492
+ artifactPaths: [...new Set(artifactPaths)].sort(),
493
+ };
494
+ }