@abelxiaoxing/cadence 1.0.14 → 1.1.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 (48) hide show
  1. package/README.md +39 -13
  2. package/agents/contract-reviewer.md +2 -2
  3. package/agents/design-explorer.md +1 -1
  4. package/agents/diagnosis-worker.md +6 -3
  5. package/agents/implementation-worker.md +14 -9
  6. package/config/.env.example +5 -17
  7. package/config/routes.example.json +42 -0
  8. package/package.json +3 -3
  9. package/prompts/abel-design.md +206 -228
  10. package/prompts/abel-diagnose.md +39 -18
  11. package/prompts/abel-implement.md +122 -178
  12. package/prompts/abel-init.md +36 -33
  13. package/skills/abel-workflow/SKILL.md +190 -168
  14. package/src/apply-transaction.ts +1427 -0
  15. package/src/artifact-store.ts +204 -0
  16. package/src/child-session.ts +136 -17
  17. package/src/contracts.ts +121 -696
  18. package/src/control-contracts.ts +246 -0
  19. package/src/delivery-compiler.ts +1118 -0
  20. package/src/design-control.ts +846 -0
  21. package/src/design-journal.ts +1569 -0
  22. package/src/file-snapshot.ts +5 -0
  23. package/src/implement-graph.ts +11 -4
  24. package/src/index.ts +1833 -118
  25. package/src/isolation-backend.ts +269 -0
  26. package/src/packet-runtime.ts +533 -0
  27. package/src/parent-provider.ts +23 -4
  28. package/src/route-policy.ts +483 -0
  29. package/src/run-state.ts +430 -0
  30. package/src/run-store.ts +990 -0
  31. package/src/safe-path.ts +11 -0
  32. package/src/scoped-tools.ts +36 -0
  33. package/src/state-root.ts +215 -0
  34. package/src/subagent-activity.ts +526 -27
  35. package/src/submit-tool.ts +274 -0
  36. package/src/task-ledger.ts +1380 -0
  37. package/src/verification-capability.ts +560 -45
  38. package/src/worker-broker.ts +703 -0
  39. package/src/workflow-engine.ts +7706 -0
  40. package/src/workspace-store.ts +544 -0
  41. package/src/candidate-preflight.ts +0 -1618
  42. package/src/drain.ts +0 -20
  43. package/src/patch.ts +0 -505
  44. package/src/result-store.ts +0 -312
  45. package/src/runtime.ts +0 -2436
  46. package/src/scheduler.ts +0 -384
  47. package/src/subagent-endpoint.ts +0 -158
  48. package/src/worker.ts +0 -204
@@ -0,0 +1,544 @@
1
+ import { 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
+
18
+ import type { ArtifactStore } from "./artifact-store.ts";
19
+ import { isValidRelativePath } from "./contracts.ts";
20
+ import { observeSafePath } from "./safe-path.ts";
21
+
22
+ const SHA256 = /^[a-f0-9]{64}$/u;
23
+ const REVISION_VERSION = 2 as const;
24
+
25
+ export interface WorkspaceFileEntry {
26
+ kind: "file";
27
+ hash: string;
28
+ bytes: number;
29
+ mode: number;
30
+ }
31
+
32
+ export interface WorkspaceAbsentEntry {
33
+ kind: "absent";
34
+ }
35
+
36
+ export type WorkspaceEntry = WorkspaceFileEntry | WorkspaceAbsentEntry;
37
+ export type WorkspaceEntries = Record<string, WorkspaceEntry>;
38
+
39
+ export interface WorkspaceRevision {
40
+ version: typeof REVISION_VERSION;
41
+ revisionId: string;
42
+ parentRevisionId: string | null;
43
+ manifestHash: string;
44
+ entries: WorkspaceEntries;
45
+ }
46
+
47
+ export interface CaptureBaselineInput {
48
+ consumerRoot: string;
49
+ approvedUntracked?: string[];
50
+ absent?: string[];
51
+ excludedPaths?: string[];
52
+ }
53
+
54
+ export type WorkspaceChange =
55
+ | Uint8Array
56
+ | null
57
+ | { kind: "absent" }
58
+ | { kind: "file"; bytes: Uint8Array; mode?: number };
59
+
60
+ export interface CreateRevisionInput {
61
+ parentRevisionId: string;
62
+ changes: Record<string, WorkspaceChange>;
63
+ }
64
+
65
+ export interface MergeRevisionInput {
66
+ baseRevisionId: string;
67
+ currentRevisionId: string;
68
+ candidateRevisionId: string;
69
+ boundPaths: string[];
70
+ }
71
+
72
+ function hash(...values: Array<string | Uint8Array>): string {
73
+ const digest = createHash("sha256");
74
+ for (const value of values) {
75
+ const bytes = typeof value === "string" ? Buffer.from(value) : value;
76
+ digest.update(`${bytes.byteLength}:`);
77
+ digest.update(bytes);
78
+ }
79
+ return digest.digest("hex");
80
+ }
81
+
82
+ function stableEntries(entries: WorkspaceEntries): WorkspaceEntries {
83
+ return Object.fromEntries(
84
+ Object.entries(entries)
85
+ .sort(([left], [right]) => left.localeCompare(right))
86
+ .map(([relative, entry]) => [relative, { ...entry }]),
87
+ );
88
+ }
89
+
90
+ function manifestHash(entries: WorkspaceEntries): string {
91
+ return hash(
92
+ "cadence-workspace-manifest-v2",
93
+ JSON.stringify(stableEntries(entries)),
94
+ );
95
+ }
96
+
97
+ function revisionId(parentRevisionId: string | null, manifest: string): string {
98
+ return hash(
99
+ "cadence-workspace-revision-v2",
100
+ parentRevisionId ?? "",
101
+ manifest,
102
+ );
103
+ }
104
+
105
+ function ensureDirectory(directory: string): void {
106
+ const stat = lstatSync(directory, { throwIfNoEntry: false });
107
+ if (stat) {
108
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
109
+ throw new Error("unsafe-workspace-path");
110
+ }
111
+ chmodSync(directory, 0o700);
112
+ return;
113
+ }
114
+ let cursor = path.dirname(directory);
115
+ while (cursor !== path.dirname(cursor)) {
116
+ const ancestor = lstatSync(cursor, { throwIfNoEntry: false });
117
+ if (ancestor) {
118
+ if (ancestor.isSymbolicLink() || !ancestor.isDirectory()) {
119
+ throw new Error("unsafe-workspace-path");
120
+ }
121
+ break;
122
+ }
123
+ cursor = path.dirname(cursor);
124
+ }
125
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
126
+ const created = lstatSync(directory);
127
+ if (created.isSymbolicLink() || !created.isDirectory()) {
128
+ throw new Error("unsafe-workspace-path");
129
+ }
130
+ chmodSync(directory, 0o700);
131
+ }
132
+
133
+ function syncDirectory(directory: string): void {
134
+ const descriptor = openSync(directory, constants.O_RDONLY);
135
+ try {
136
+ fsyncSync(descriptor);
137
+ } finally {
138
+ closeSync(descriptor);
139
+ }
140
+ }
141
+
142
+ function writeAtomic(target: string, bytes: Uint8Array): void {
143
+ const directory = path.dirname(target);
144
+ ensureDirectory(directory);
145
+ const temporary = path.join(
146
+ directory,
147
+ `.${path.basename(target)}.${process.pid}.${randomUUID()}.tmp`,
148
+ );
149
+ const descriptor = openSync(
150
+ temporary,
151
+ constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,
152
+ 0o600,
153
+ );
154
+ try {
155
+ writeFileSync(descriptor, bytes);
156
+ fsyncSync(descriptor);
157
+ } finally {
158
+ closeSync(descriptor);
159
+ }
160
+ try {
161
+ renameSync(temporary, target);
162
+ chmodSync(target, 0o600);
163
+ syncDirectory(directory);
164
+ } catch (error) {
165
+ try {
166
+ unlinkSync(temporary);
167
+ } catch {
168
+ // The rename may already have consumed the temporary file.
169
+ }
170
+ throw error;
171
+ }
172
+ }
173
+
174
+ function requireSafeRelative(relative: string): void {
175
+ if (!isValidRelativePath(relative) || relative === ".") {
176
+ throw new Error("unsafe-workspace-path");
177
+ }
178
+ }
179
+
180
+ function isExcluded(relative: string, excluded: readonly string[]): boolean {
181
+ return excluded.some(
182
+ (entry) => relative === entry || relative.startsWith(`${entry}/`),
183
+ );
184
+ }
185
+
186
+ function parseNullSeparated(bytes: Buffer): string[] {
187
+ const decoded = bytes.toString("utf8");
188
+ if (!Buffer.from(decoded, "utf8").equals(bytes)) {
189
+ throw new Error("unsafe-workspace-path");
190
+ }
191
+ return decoded.split("\0").filter((entry) => entry.length > 0);
192
+ }
193
+
194
+ function sameEntry(
195
+ left: WorkspaceEntry | undefined,
196
+ right: WorkspaceEntry | undefined,
197
+ ): boolean {
198
+ if (!left || !right) return left === right;
199
+ if (left.kind !== right.kind) return false;
200
+ return (
201
+ left.kind === "absent" ||
202
+ (right.kind === "file" &&
203
+ left.hash === right.hash &&
204
+ left.bytes === right.bytes &&
205
+ left.mode === right.mode)
206
+ );
207
+ }
208
+
209
+ function requireMode(mode: number): number {
210
+ if (!Number.isInteger(mode) || mode < 0 || mode > 0o777) {
211
+ throw new Error("workspace-file-mode-invalid");
212
+ }
213
+ return mode;
214
+ }
215
+
216
+ function requireRevisionShape(value: unknown): WorkspaceRevision {
217
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
218
+ throw new Error("workspace-revision-invalid");
219
+ }
220
+ const candidate = value as Partial<WorkspaceRevision>;
221
+ if (
222
+ candidate.version !== REVISION_VERSION ||
223
+ typeof candidate.revisionId !== "string" ||
224
+ !SHA256.test(candidate.revisionId) ||
225
+ (candidate.parentRevisionId !== null &&
226
+ (typeof candidate.parentRevisionId !== "string" ||
227
+ !SHA256.test(candidate.parentRevisionId))) ||
228
+ typeof candidate.manifestHash !== "string" ||
229
+ !SHA256.test(candidate.manifestHash) ||
230
+ !candidate.entries ||
231
+ typeof candidate.entries !== "object" ||
232
+ Array.isArray(candidate.entries)
233
+ ) {
234
+ throw new Error("workspace-revision-invalid");
235
+ }
236
+ for (const [relative, entry] of Object.entries(candidate.entries)) {
237
+ requireSafeRelative(relative);
238
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
239
+ throw new Error("workspace-revision-invalid");
240
+ }
241
+ if ((entry as WorkspaceEntry).kind === "absent") {
242
+ if (Object.keys(entry).length !== 1) {
243
+ throw new Error("workspace-revision-invalid");
244
+ }
245
+ continue;
246
+ }
247
+ const file = entry as WorkspaceFileEntry;
248
+ if (
249
+ file.kind !== "file" ||
250
+ !SHA256.test(file.hash) ||
251
+ !Number.isSafeInteger(file.bytes) ||
252
+ file.bytes < 0 ||
253
+ Object.keys(file).length !== 4
254
+ ) {
255
+ throw new Error("workspace-revision-invalid");
256
+ }
257
+ requireMode(file.mode);
258
+ }
259
+ return candidate as WorkspaceRevision;
260
+ }
261
+
262
+ /** Immutable manifests over private content-addressed workspace bytes. */
263
+ export class WorkspaceStore {
264
+ readonly root: string;
265
+ readonly #revisions: string;
266
+ readonly #artifacts: ArtifactStore;
267
+
268
+ constructor(root: string, artifacts: ArtifactStore) {
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
+ version: REVISION_VERSION,
291
+ revisionId: id,
292
+ parentRevisionId,
293
+ manifestHash: manifest,
294
+ entries,
295
+ };
296
+ const target = this.#revisionPath(id);
297
+ const existing = lstatSync(target, { throwIfNoEntry: false });
298
+ if (existing) {
299
+ const stored = this.getRevision(id);
300
+ if (JSON.stringify(stored) !== JSON.stringify(revision)) {
301
+ throw new Error("workspace-revision-conflict");
302
+ }
303
+ return stored;
304
+ }
305
+
306
+ writeAtomic(target, Buffer.from(`${JSON.stringify(revision)}\n`));
307
+ for (const entry of Object.values(entries)) {
308
+ if (entry.kind === "file") this.#artifacts.retain(entry.hash);
309
+ }
310
+ return structuredClone(revision);
311
+ }
312
+
313
+ #isAncestor(ancestorId: string, revision: WorkspaceRevision): boolean {
314
+ let cursor: WorkspaceRevision | null = revision;
315
+ const visited = new Set<string>();
316
+ while (cursor) {
317
+ if (cursor.revisionId === ancestorId) return true;
318
+ if (visited.has(cursor.revisionId)) {
319
+ throw new Error("workspace-revision-cycle");
320
+ }
321
+ visited.add(cursor.revisionId);
322
+ cursor = cursor.parentRevisionId
323
+ ? this.getRevision(cursor.parentRevisionId)
324
+ : null;
325
+ }
326
+ return false;
327
+ }
328
+
329
+ captureBaseline(input: CaptureBaselineInput): WorkspaceRevision {
330
+ const consumerRoot = path.resolve(input.consumerRoot);
331
+ const rootStat = lstatSync(consumerRoot, { throwIfNoEntry: false });
332
+ if (!rootStat?.isDirectory() || rootStat.isSymbolicLink()) {
333
+ throw new Error("unsafe-workspace-path");
334
+ }
335
+ const excluded = [".git", "node_modules", ...(input.excludedPaths ?? [])];
336
+ for (const relative of excluded) requireSafeRelative(relative);
337
+
338
+ let tracked: string[];
339
+ try {
340
+ tracked = parseNullSeparated(
341
+ execFileSync("git", ["ls-files", "-z", "--cached"], {
342
+ cwd: consumerRoot,
343
+ maxBuffer: 32 * 1024 * 1024,
344
+ }),
345
+ );
346
+ } catch (error) {
347
+ if (error instanceof Error && error.message === "unsafe-workspace-path") {
348
+ throw error;
349
+ }
350
+ throw new Error("workspace-git-baseline-unavailable");
351
+ }
352
+
353
+ const approved = input.approvedUntracked ?? [];
354
+ const absent = input.absent ?? [];
355
+ const selected = [...new Set([...tracked, ...approved])].sort();
356
+ const entries: WorkspaceEntries = {};
357
+ for (const relative of selected) {
358
+ requireSafeRelative(relative);
359
+ if (isExcluded(relative, excluded)) continue;
360
+ const observation = observeSafePath(consumerRoot, relative);
361
+ if (observation.kind === "absent") {
362
+ entries[relative] = { kind: "absent" };
363
+ continue;
364
+ }
365
+ if (observation.kind !== "file") throw new Error("unsafe-workspace-path");
366
+ const absolute = path.join(consumerRoot, ...relative.split("/"));
367
+ const bytes = readFileSync(absolute);
368
+ const artifact = this.#artifacts.put(bytes);
369
+ const stat = lstatSync(absolute);
370
+ entries[relative] = {
371
+ kind: "file",
372
+ hash: artifact.hash,
373
+ bytes: artifact.bytes,
374
+ mode: requireMode(stat.mode & 0o777),
375
+ };
376
+ }
377
+ for (const relative of [...new Set(absent)].sort()) {
378
+ requireSafeRelative(relative);
379
+ if (isExcluded(relative, excluded))
380
+ throw new Error("unsafe-workspace-path");
381
+ if (observeSafePath(consumerRoot, relative).kind !== "absent") {
382
+ throw new Error("workspace-path-not-absent");
383
+ }
384
+ entries[relative] = { kind: "absent" };
385
+ }
386
+ return this.#storeRevision(null, entries);
387
+ }
388
+
389
+ getRevision(id: string): WorkspaceRevision {
390
+ const target = this.#revisionPath(id);
391
+ const stat = lstatSync(target, { throwIfNoEntry: false });
392
+ if (!stat?.isFile() || stat.isSymbolicLink()) {
393
+ throw new Error("workspace-revision-unavailable");
394
+ }
395
+ let parsed: unknown;
396
+ try {
397
+ parsed = JSON.parse(readFileSync(target, "utf8"));
398
+ } catch {
399
+ throw new Error("workspace-revision-invalid");
400
+ }
401
+ const revision = requireRevisionShape(parsed);
402
+ if (
403
+ revision.revisionId !== id ||
404
+ manifestHash(revision.entries) !== revision.manifestHash ||
405
+ revisionId(revision.parentRevisionId, revision.manifestHash) !== id
406
+ ) {
407
+ throw new Error("workspace-revision-integrity-invalid");
408
+ }
409
+ for (const entry of Object.values(revision.entries)) {
410
+ if (entry.kind !== "file") continue;
411
+ const bytes = this.#artifacts.read(entry.hash);
412
+ if (bytes.byteLength !== entry.bytes) {
413
+ throw new Error("workspace-revision-integrity-invalid");
414
+ }
415
+ }
416
+ return structuredClone(revision);
417
+ }
418
+
419
+ createRevision(input: CreateRevisionInput): WorkspaceRevision {
420
+ const parent = this.getRevision(input.parentRevisionId);
421
+ const entries = stableEntries(parent.entries);
422
+ for (const [relative, change] of Object.entries(input.changes).sort(
423
+ ([left], [right]) => left.localeCompare(right),
424
+ )) {
425
+ requireSafeRelative(relative);
426
+ if (
427
+ change === null ||
428
+ (typeof change === "object" &&
429
+ "kind" in change &&
430
+ change.kind === "absent")
431
+ ) {
432
+ entries[relative] = { kind: "absent" };
433
+ continue;
434
+ }
435
+ const descriptor =
436
+ change instanceof Uint8Array
437
+ ? {
438
+ kind: "file" as const,
439
+ bytes: change,
440
+ mode:
441
+ entries[relative]?.kind === "file"
442
+ ? entries[relative].mode
443
+ : 0o644,
444
+ }
445
+ : change;
446
+ if (
447
+ descriptor?.kind !== "file" ||
448
+ !(descriptor.bytes instanceof Uint8Array)
449
+ ) {
450
+ throw new Error("workspace-change-invalid");
451
+ }
452
+ const artifact = this.#artifacts.put(descriptor.bytes);
453
+ entries[relative] = {
454
+ kind: "file",
455
+ hash: artifact.hash,
456
+ bytes: artifact.bytes,
457
+ mode: requireMode(descriptor.mode ?? 0o644),
458
+ };
459
+ }
460
+ return this.#storeRevision(parent.revisionId, entries);
461
+ }
462
+
463
+ mergeRevision(input: MergeRevisionInput): WorkspaceRevision {
464
+ const base = this.getRevision(input.baseRevisionId);
465
+ const current = this.getRevision(input.currentRevisionId);
466
+ const candidate = this.getRevision(input.candidateRevisionId);
467
+ if (
468
+ candidate.parentRevisionId !== base.revisionId ||
469
+ !this.#isAncestor(base.revisionId, current)
470
+ ) {
471
+ throw new Error("workspace-revision-base-invalid");
472
+ }
473
+ const boundPaths = [...new Set(input.boundPaths)];
474
+ for (const relative of boundPaths) {
475
+ requireSafeRelative(relative);
476
+ if (!sameEntry(base.entries[relative], current.entries[relative])) {
477
+ throw new Error("workspace-revision-stale");
478
+ }
479
+ }
480
+
481
+ const allPaths = new Set([
482
+ ...Object.keys(base.entries),
483
+ ...Object.keys(candidate.entries),
484
+ ]);
485
+ const delta = [...allPaths].filter(
486
+ (relative) =>
487
+ !sameEntry(base.entries[relative], candidate.entries[relative]),
488
+ );
489
+ for (const relative of delta) {
490
+ if (!sameEntry(base.entries[relative], current.entries[relative])) {
491
+ throw new Error("workspace-revision-stale");
492
+ }
493
+ }
494
+
495
+ const merged = stableEntries(current.entries);
496
+ for (const relative of delta.sort()) {
497
+ const entry = candidate.entries[relative];
498
+ if (entry) merged[relative] = { ...entry };
499
+ else delete merged[relative];
500
+ }
501
+ return this.#storeRevision(current.revisionId, merged);
502
+ }
503
+
504
+ materialize(revisionIdValue: string, destination: string): void {
505
+ const revision = this.getRevision(revisionIdValue);
506
+ const root = path.resolve(destination);
507
+ ensureDirectory(root);
508
+ for (const [relative, entry] of Object.entries(revision.entries)) {
509
+ requireSafeRelative(relative);
510
+ const observation = observeSafePath(root, relative);
511
+ if (entry.kind === "absent") {
512
+ const segments = relative.split("/");
513
+ const supersededByFileAncestor = segments
514
+ .slice(0, -1)
515
+ .some(
516
+ (_segment, index) =>
517
+ revision.entries[segments.slice(0, index + 1).join("/")]?.kind ===
518
+ "file",
519
+ );
520
+ if (supersededByFileAncestor) continue;
521
+ if (observation.kind !== "absent") {
522
+ throw new Error("workspace-materialize-conflict");
523
+ }
524
+ continue;
525
+ }
526
+ const segments = relative.split("/");
527
+ let parent = root;
528
+ for (const segment of segments.slice(0, -1)) {
529
+ parent = path.join(parent, segment);
530
+ ensureDirectory(parent);
531
+ }
532
+ const target = path.join(root, ...segments);
533
+ if (observation.kind !== "absent") {
534
+ throw new Error("workspace-materialize-conflict");
535
+ }
536
+ const bytes = this.#artifacts.read(entry.hash);
537
+ if (bytes.byteLength !== entry.bytes) {
538
+ throw new Error("workspace-revision-integrity-invalid");
539
+ }
540
+ writeFileSync(target, bytes, { flag: "wx", mode: entry.mode });
541
+ chmodSync(target, entry.mode);
542
+ }
543
+ }
544
+ }