@abelxiaoxing/cadence 2.0.37 → 2.0.40

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.de.md +2 -2
  2. package/README.es.md +2 -2
  3. package/README.fr.md +2 -2
  4. package/README.ja.md +2 -2
  5. package/README.ko.md +2 -2
  6. package/README.md +9 -7
  7. package/README.pt-BR.md +2 -2
  8. package/README.ru.md +2 -2
  9. package/README.zh-CN.md +10 -8
  10. package/agents/design-explorer.md +4 -2
  11. package/agents/diagnosis-worker.md +5 -2
  12. package/agents/implementation-worker.md +19 -12
  13. package/docs/conversation-mode.md +73 -16
  14. package/docs/reuse-and-distribution.md +78 -0
  15. package/package.json +7 -2
  16. package/src/activity.ts +147 -0
  17. package/src/agent-browser/session-navigator.ts +33 -6
  18. package/src/agent-browser/source.ts +23 -19
  19. package/src/agent-panel-cadence.ts +147 -628
  20. package/src/agent-panel-model.ts +30 -19
  21. package/src/agent-panel.ts +12 -16
  22. package/src/cadence-instructions.ts +8 -7
  23. package/src/cadence-mode.ts +30 -9
  24. package/src/change-tools.mjs +268 -0
  25. package/src/coordinator-tools.mjs +2 -2
  26. package/src/git-environment.d.mts +2 -0
  27. package/src/git-environment.mjs +24 -0
  28. package/src/index.ts +3 -1
  29. package/src/native-build.ts +1 -1
  30. package/src/native-workflow-history.ts +20 -3
  31. package/src/operator-cli.mjs +22 -12
  32. package/src/research-scan.mjs +111 -31
  33. package/src/research-tools.mjs +75 -16
  34. package/src/sdk-worker.mjs +6 -1
  35. package/src/service/activity-files.ts +190 -0
  36. package/src/service/contracts/workbench.ts +11 -3
  37. package/src/service/contracts/workflow.ts +283 -16
  38. package/src/service/coordination.ts +13 -3
  39. package/src/service-cli.mjs +392 -93
  40. package/src/service-host.mjs +7635 -5682
  41. package/src/worker-capture.mjs +24 -1
  42. package/src/worker-public.mjs +18 -0
  43. package/src/worker-redaction.mjs +11 -0
  44. package/src/worker-toolkit.mjs +55 -2
  45. package/src/workspace.ts +62 -25
  46. package/web/dist/assets/cadence.css +1 -1
  47. package/web/dist/assets/cadence.js +19 -18
  48. package/web/dist/manifest.json +7 -7
@@ -0,0 +1,190 @@
1
+ /** Short-lived, single-writer Pi activity metadata. Readers never repair or delete. */
2
+ import { randomUUID } from "node:crypto";
3
+ import { opendirSync, renameSync } from "node:fs";
4
+ import { hostname } from "node:os";
5
+ import { join } from "node:path";
6
+ import { canonicalAmbientRoot, defaultStateHome } from "../workspace.ts";
7
+ import {
8
+ closed,
9
+ decodeHash,
10
+ decodeId,
11
+ integer,
12
+ literal,
13
+ text,
14
+ } from "./contracts/core.ts";
15
+ import { decodeSessionId } from "./contracts/models.ts";
16
+ import { holderState, type ProcessMark } from "./liveness.ts";
17
+ import {
18
+ encoded,
19
+ type FileSnapshot,
20
+ hash,
21
+ json,
22
+ PrivateFiles,
23
+ } from "./private-files.ts";
24
+
25
+ export const ACTIVITY_RENEW_MS = 5000;
26
+ export const ACTIVITY_FRESH_MS = 15000;
27
+ /** Lost observations leave the activity area after two minutes, never as success. */
28
+ export const ACTIVITY_RETAIN_MS = 120000;
29
+ /** Per configuration/host scan and response bound; overflow is explicitly partial. */
30
+ export const ACTIVITY_FILES = 256;
31
+ export interface NativeActivity {
32
+ schema: "cadence-pi-activity/1";
33
+ instance: string;
34
+ activity: string;
35
+ scope: string;
36
+ sessionScope: string;
37
+ process: ProcessMark;
38
+ cwd: string;
39
+ sessionId: string;
40
+ leaf: string | null;
41
+ startedAt: number;
42
+ renewedAt: number;
43
+ }
44
+ export function decodeNativeActivity(value: unknown): NativeActivity {
45
+ const o = closed(value, [
46
+ "schema",
47
+ "instance",
48
+ "activity",
49
+ "scope",
50
+ "sessionScope",
51
+ "process",
52
+ "cwd",
53
+ "sessionId",
54
+ "leaf",
55
+ "startedAt",
56
+ "renewedAt",
57
+ ]);
58
+ const p = closed(o.process, ["pid", "host", "boot", "started"]);
59
+ return {
60
+ schema: literal(o.schema, "cadence-pi-activity/1"),
61
+ instance: decodeId(o.instance),
62
+ activity: decodeId(o.activity),
63
+ scope: decodeHash(o.scope),
64
+ sessionScope: decodeHash(o.sessionScope),
65
+ process: {
66
+ pid: integer(p.pid, 1, 2147483647),
67
+ host: text(p.host, 255, true),
68
+ boot: p.boot === null ? null : text(p.boot, 128, true),
69
+ started: p.started === null ? null : text(p.started, 128, true),
70
+ },
71
+ cwd: text(o.cwd, 4096, true),
72
+ sessionId: decodeSessionId(o.sessionId),
73
+ leaf: o.leaf === null ? null : text(o.leaf, 128, true),
74
+ startedAt: integer(o.startedAt, 0),
75
+ renewedAt: integer(o.renewedAt, 0),
76
+ };
77
+ }
78
+ export const activityScope = (agentDir: string) =>
79
+ hash(canonicalAmbientRoot(agentDir));
80
+ /** Bind the existing reader's configuration without exposing any source path. */
81
+ export const activityReaderScope = (agentDir: string, sessionDir?: string) =>
82
+ hash(
83
+ encoded([
84
+ canonicalAmbientRoot(agentDir),
85
+ process.env.PI_CODING_AGENT_SESSION_DIR ?? null,
86
+ sessionDir ?? null,
87
+ ]),
88
+ );
89
+ export class ActivityFiles {
90
+ readonly files: PrivateFiles;
91
+ readonly directory: string;
92
+ readonly scope: string;
93
+ constructor(agentDir: string, stateHome = defaultStateHome()) {
94
+ this.files = new PrivateFiles(
95
+ join(canonicalAmbientRoot(stateHome), "cadence-assistant-v1"),
96
+ );
97
+ this.scope = activityScope(agentDir);
98
+ this.directory = join(
99
+ this.files.namespace,
100
+ "pi-activity-v1",
101
+ this.scope,
102
+ hash(hostname()),
103
+ );
104
+ }
105
+ scan(): { records: NativeActivity[]; unavailable: number } {
106
+ const records: NativeActivity[] = [];
107
+ let unavailable = 0;
108
+ if (!this.files.directory(this.directory)) return { records, unavailable };
109
+ const dir = opendirSync(this.directory);
110
+ try {
111
+ let count = 0;
112
+ for (let e = dir.readSync(); e; e = dir.readSync()) {
113
+ if (++count > ACTIVITY_FILES) {
114
+ unavailable++;
115
+ break;
116
+ }
117
+ try {
118
+ if (!e.isFile() || !/^[0-9a-f-]{36}\.json$/.test(e.name))
119
+ throw new Error();
120
+ const file = this.files.read(join(this.directory, e.name));
121
+ if (!file) continue; // A publisher settled between directory and file reads.
122
+ const record = decodeNativeActivity(json(file));
123
+ if (
124
+ `${record.instance}.json` !== e.name ||
125
+ record.scope !== this.scope ||
126
+ record.process.host !== hostname()
127
+ )
128
+ throw new Error();
129
+ records.push(record);
130
+ } catch {
131
+ unavailable++;
132
+ }
133
+ }
134
+ } finally {
135
+ dir.closeSync();
136
+ }
137
+ return { records, unavailable };
138
+ }
139
+ /** Only a writer starting real work retires provably dead reports. Unknown
140
+ * and corrupt bytes stay untouched. Archived metadata expires with the existing
141
+ * 30-day recovery archive; a readonly discovery never cleans consumer data. */
142
+ retireDead(now: number): void {
143
+ const { records } = this.scan();
144
+ for (const record of records) {
145
+ if (
146
+ now - record.renewedAt <= ACTIVITY_RETAIN_MS ||
147
+ holderState(record.process).state !== "dead"
148
+ )
149
+ continue;
150
+ const path = join(this.directory, `${record.instance}.json`);
151
+ const before = this.files.read(path);
152
+ if (
153
+ !before ||
154
+ encoded(decodeNativeActivity(json(before))) !== encoded(record)
155
+ )
156
+ continue;
157
+ const archive = join(
158
+ this.files.namespace,
159
+ "recovery-archive-v1",
160
+ `${Date.now()}-${randomUUID()}`,
161
+ );
162
+ this.files.directory(archive, true);
163
+ this.files.assert(path, before);
164
+ renameSync(path, join(archive, "pi-activity.json"));
165
+ }
166
+ }
167
+ publish(record: NativeActivity, previous?: FileSnapshot): FileSnapshot {
168
+ if (!previous) {
169
+ const scanned = this.scan();
170
+ if (scanned.records.length + scanned.unavailable >= ACTIVITY_FILES)
171
+ throw new Error("activity-capacity");
172
+ }
173
+ const path = join(this.directory, `${record.instance}.json`);
174
+ const bytes = encoded(decodeNativeActivity(record));
175
+ if (previous) return this.files.replace(path, previous, bytes);
176
+ // Publish the first report atomically too. A failed temporary is preserved,
177
+ // not interpreted as an idle terminal or silently deleted by a reader.
178
+ this.files.directory(this.directory, true);
179
+ const temporary = join(this.directory, `pending-${record.instance}.json`);
180
+ this.files.create(temporary, bytes);
181
+ this.files.assert(path, undefined);
182
+ renameSync(temporary, path);
183
+ const saved = this.files.read(path);
184
+ if (!saved) throw new Error("activity-unavailable");
185
+ return saved;
186
+ }
187
+ withdraw(instance: string, previous: FileSnapshot): void {
188
+ this.files.remove(join(this.directory, `${instance}.json`), previous);
189
+ }
190
+ }
@@ -107,7 +107,7 @@ export type WorkbenchRead =
107
107
  | { kind: "workflow-history"; after: string | null; scan?: string }
108
108
  | { kind: "workflow-detail"; id: string; stepId: string }
109
109
  | { kind: "workflow-transcript"; id: string; stepId: string }
110
- | { kind: "workflow"; id: string }
110
+ | { kind: "workflow"; id: string; before?: number }
111
111
  | { kind: "conversation-active" }
112
112
  | { kind: "conversations"; after?: ChatCursor | null }
113
113
  | {
@@ -610,8 +610,16 @@ export function decodeWorkbenchRead(v: unknown): WorkbenchRead {
610
610
  return { kind, id: decodeId(o.id), stepId: text(o.stepId, 160, true) };
611
611
  }
612
612
  case "workflow": {
613
- const o = closed(v, ["kind", "id"]);
614
- return { kind, id: decodeId(o.id) };
613
+ const o = closed(v, [
614
+ "kind",
615
+ "id",
616
+ ...(Object.hasOwn(v ?? {}, "before") ? ["before"] : []),
617
+ ]);
618
+ return {
619
+ kind,
620
+ id: decodeId(o.id),
621
+ ...(o.before === undefined ? {} : { before: integer(o.before, 1) }),
622
+ };
615
623
  }
616
624
  case "conversations": {
617
625
  const after = Object.hasOwn(v as object, "after");
@@ -22,14 +22,12 @@ export const WORKFLOW_LIMITS = {
22
22
  tasks: 16,
23
23
  parallel: 2,
24
24
  checks: 16,
25
- repairs: 2,
26
25
  bytes: 256 * 1024,
27
26
  // Read budgets, never a lifetime cap on retained runs.
28
27
  historyScanEntries: 200,
29
28
  historyPage: 20,
30
29
  historyScans: 16,
31
30
  historyIdleMs: 120000,
32
- durationMs: 90 * 60 * 1000,
33
31
  } as const;
34
32
  export interface WorkflowCheck {
35
33
  name: string;
@@ -44,19 +42,65 @@ export interface WorkflowTask {
44
42
  after: string[];
45
43
  }
46
44
  export interface WorkflowPlan {
45
+ /** Version 2 admits adaptive delivery; absent versions are retained, readonly plans. */
46
+ version?: 2;
47
+ knowledge?: string[];
47
48
  goal: string;
48
49
  design: string;
49
50
  decisions: string;
50
51
  acceptance: string;
51
- projectContext: string;
52
+ /** Retained v1 data only, never used to synthesize new project knowledge. */
53
+ projectContext?: string;
52
54
  tasks: WorkflowTask[];
53
55
  checks: WorkflowCheck[];
54
56
  setup: WorkflowCheck[];
55
57
  baselineChecks: WorkflowCheck[];
56
- repairAttempts: number;
58
+ /** Retained v1 evidence only. New plans have no repair quota. */
59
+ repairAttempts?: number;
57
60
  delivery: "local-merge" | "working-copy";
58
61
  }
62
+ /** Owner-selected Git placement, not a model's permission to pick refs. */
63
+ export interface DeliveryTarget {
64
+ checkoutRoot: string;
65
+ repository: string;
66
+ repositoryIdentity: string;
67
+ branch: string;
68
+ head: string;
69
+ }
70
+ export interface DeliveryBinding {
71
+ policy: "task-branch-v1";
72
+ target: DeliveryTarget;
73
+ }
74
+ export interface AcceptanceRecord {
75
+ candidate: string;
76
+ tree: string;
77
+ planDigest: string;
78
+ contextDigest: string;
79
+ checks: string[];
80
+ review: string;
81
+ }
82
+ export interface DeliveryObservation {
83
+ binding: DeliveryBinding;
84
+ taskBranch: string;
85
+ worktreeRoot: string;
86
+ preparation: "pending" | "ready" | "unknown";
87
+ workspace: {
88
+ head: string;
89
+ state: "preparing" | "ready" | "removed" | "retained";
90
+ } | null;
91
+ candidate: string | null;
92
+ acceptance: AcceptanceRecord | null;
93
+ integration: {
94
+ status: "pending" | "blocked" | "applying" | "applied" | "unknown";
95
+ before: string;
96
+ after: string | null;
97
+ reason: string;
98
+ };
99
+ postChecks: "not-run" | "passed" | "failed" | "unknown";
100
+ cleanup: { status: "pending" | "removed" | "retained"; reason: string };
101
+ }
59
102
  export interface WorkflowProposal {
103
+ delivery?: DeliveryBinding;
60
104
  id: string;
61
105
  epoch: string;
62
106
  digest: string;
@@ -96,10 +140,18 @@ export interface WorkflowStep {
96
140
  runtime?: { sdkVersion: string; workerHash: string };
97
141
  id: string;
98
142
  childRunId?: string;
99
- kind: "research" | "implementation" | "review" | "check" | "git";
143
+ kind:
144
+ | "research"
145
+ | "implementation"
146
+ | "diagnosis"
147
+ | "knowledge"
148
+ | "review"
149
+ | "check"
150
+ | "git";
100
151
  status:
101
152
  | "running"
102
153
  | "completed"
154
+ | "rejected"
103
155
  | "failed"
104
156
  | "canceled"
105
157
  | "timeout"
@@ -109,6 +161,11 @@ export interface WorkflowStep {
109
161
  truncated: boolean;
110
162
  }
111
163
  export interface WorkflowRun {
164
+ /** New runs retain older step pages separately; this is a view offset, not eviction. */
165
+ stepsBefore?: number;
166
+ revision?: number;
167
+ verification?: { id: string; source: string; steps: string[] };
168
+ delivery?: DeliveryObservation;
112
169
  execution?: ExecutionContext;
113
170
  diagnostics?: WorkflowDiagnostics;
114
171
  id: string;
@@ -127,6 +184,8 @@ export interface WorkflowRun {
127
184
  | "implementing"
128
185
  | "verifying"
129
186
  | "reviewing"
187
+ | "recovering"
188
+ | "learning"
130
189
  | "integrating"
131
190
  | "finished";
132
191
  steps: WorkflowStep[];
@@ -247,18 +306,26 @@ export function decodeWorkflowPlan(
247
306
  options: { strict?: boolean } = {},
248
307
  ): WorkflowPlan {
249
308
  const strict = options.strict === true;
309
+ const modern = Object.hasOwn(v ?? {}, "version");
310
+ if (strict && !modern)
311
+ throw new Error(
312
+ "Publish a new delivery agreement; retained fixed-pipeline plans are readonly",
313
+ );
250
314
  canonicalJson(v, WORKFLOW_LIMITS.bytes);
315
+ if (modern && (v as { version?: unknown }).version !== 2)
316
+ throw new Error("Unsupported delivery agreement version");
251
317
  const o = closed(v, [
252
318
  "goal",
253
319
  "design",
254
320
  "decisions",
255
321
  "acceptance",
256
- "projectContext",
322
+ ...(modern
323
+ ? ["version", "knowledge"]
324
+ : ["projectContext", "repairAttempts"]),
257
325
  "tasks",
258
326
  "checks",
259
327
  "setup",
260
328
  "baselineChecks",
261
- "repairAttempts",
262
329
  "delivery",
263
330
  ]);
264
331
  const tasks = list(o.tasks, WORKFLOW_LIMITS.tasks, (value) => {
@@ -284,7 +351,9 @@ export function decodeWorkflowPlan(
284
351
  )
285
352
  throw new Error("Empty or duplicate task scope");
286
353
  workflowOrder(tasks);
287
- for (const a of tasks)
354
+ // Retained parallel plans keep their original validation. New delivery uses
355
+ // a stable sequential candidate, so adjacent assignments may share files.
356
+ for (const a of modern ? [] : tasks)
288
357
  for (const b of tasks) {
289
358
  if (
290
359
  a.id >= b.id ||
@@ -308,7 +377,20 @@ export function decodeWorkflowPlan(
308
377
  design: text(o.design, 32768, true),
309
378
  decisions: text(o.decisions, 16384),
310
379
  acceptance: text(o.acceptance, 16384, true),
311
- projectContext: text(o.projectContext, 16384),
380
+ ...(modern
381
+ ? {
382
+ version: 2 as const,
383
+ knowledge: list(o.knowledge, 16, (v) => {
384
+ const path = workflowPath(v, strict);
385
+ if (!path.endsWith(".md"))
386
+ throw new Error("Knowledge targets must be Markdown files");
387
+ return path;
388
+ }),
389
+ }
390
+ : {
391
+ projectContext: text(o.projectContext, 16384),
392
+ repairAttempts: integer(o.repairAttempts, 0, 2),
393
+ }),
312
394
  tasks,
313
395
  checks,
314
396
  setup: list(o.setup, 4, decodeWorkflowCheck),
@@ -317,17 +399,16 @@ export function decodeWorkflowPlan(
317
399
  WORKFLOW_LIMITS.checks,
318
400
  decodeWorkflowCheck,
319
401
  ),
320
- repairAttempts: integer(o.repairAttempts, 0, WORKFLOW_LIMITS.repairs),
321
402
  delivery: oneOf(o.delivery, ["local-merge", "working-copy"]),
322
403
  };
323
404
  workflowContext(result);
324
- text(result.tasks.flatMap((t) => t.writes).join(", "), 16384);
405
+ text(workflowWrites(result).join(", "), 16384);
325
406
  for (const value of [
326
407
  result.goal,
327
408
  result.design,
328
409
  result.decisions,
329
410
  result.acceptance,
330
- result.projectContext,
411
+ result.projectContext ?? "",
331
412
  ...result.tasks.flatMap((t) => [t.title, t.instructions]),
332
413
  ...[...result.checks, ...result.setup, ...result.baselineChecks].flatMap(
333
414
  (c) => [c.name, c.command],
@@ -344,13 +425,165 @@ export function decodeWorkflowPlan(
344
425
  throw new Error("Plan contains invisible terminal controls");
345
426
  return result;
346
427
  }
428
+ /** The immutable permission/verification boundary, independent of internal route revisions. */
429
+ export function workflowWrites(p: WorkflowPlan): string[] {
430
+ return [
431
+ ...new Set([...p.tasks.flatMap((t) => t.writes), ...(p.knowledge ?? [])]),
432
+ ];
433
+ }
347
434
  export function workflowContext(p: WorkflowPlan): string {
348
435
  return text(
349
- `# ${p.goal}\n\n${p.design}\n\nDecisions: ${p.decisions}\n\nAcceptance: ${p.acceptance}`,
436
+ `# ${p.goal}\n\nInitial route (adapt within the approved boundary): ${p.design}\n\nExplicit decisions and non-goals: ${p.decisions}\n\nImmutable acceptance: ${p.acceptance}`,
350
437
  32768,
351
438
  true,
352
439
  );
353
440
  }
441
+ export function gitOid(value: unknown): string {
442
+ const oid = text(value, 64, true);
443
+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(oid))
444
+ throw new Error("Invalid Git object");
445
+ return oid;
446
+ }
447
+ function localRef(value: unknown): string {
448
+ const ref = text(value, 1024, true);
449
+ if (
450
+ !ref.startsWith("refs/heads/") ||
451
+ /[\s~^:?*[\\]/u.test(ref) ||
452
+ [...ref].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127) ||
453
+ ref.includes("..") ||
454
+ ref.includes("@{") ||
455
+ ref
456
+ .split("/")
457
+ .some(
458
+ (p) =>
459
+ !p || p.startsWith(".") || p.endsWith(".") || p.endsWith(".lock"),
460
+ )
461
+ )
462
+ throw new Error("Invalid local ref");
463
+ return ref;
464
+ }
465
+ function deliveryPath(value: unknown): string {
466
+ const path = text(value, 4096, true);
467
+ if (!/^(?:\/|[A-Za-z]:[\\/]|\\\\)/u.test(path) || path.includes("\0"))
468
+ throw new Error("Invalid delivery path");
469
+ return path;
470
+ }
471
+ export function decodeDeliveryBinding(value: unknown): DeliveryBinding {
472
+ const b = closed(value, ["policy", "target"]);
473
+ const t = closed(b.target, [
474
+ "checkoutRoot",
475
+ "repository",
476
+ "repositoryIdentity",
477
+ "branch",
478
+ "head",
479
+ ]);
480
+ return {
481
+ policy: oneOf(b.policy, ["task-branch-v1"]),
482
+ target: {
483
+ checkoutRoot: deliveryPath(t.checkoutRoot),
484
+ repository: deliveryPath(t.repository),
485
+ repositoryIdentity: decodeHash(t.repositoryIdentity),
486
+ branch: localRef(t.branch),
487
+ head: gitOid(t.head),
488
+ },
489
+ };
490
+ }
491
+ export function decodeDeliveryObservation(value: unknown): DeliveryObservation {
492
+ const d = closed(value, [
493
+ "binding",
494
+ "taskBranch",
495
+ "worktreeRoot",
496
+ "preparation",
497
+ "workspace",
498
+ "candidate",
499
+ "acceptance",
500
+ "integration",
501
+ "postChecks",
502
+ "cleanup",
503
+ ]);
504
+ const i = closed(d.integration, ["status", "before", "after", "reason"]);
505
+ const c = closed(d.cleanup, ["status", "reason"]);
506
+ const step = (x: unknown) => text(x, 160, true);
507
+ const acceptance = nullable(d.acceptance, (v) => {
508
+ const a = closed(v, [
509
+ "candidate",
510
+ "tree",
511
+ "planDigest",
512
+ "contextDigest",
513
+ "checks",
514
+ "review",
515
+ ]);
516
+ const checks = list(a.checks, WORKFLOW_LIMITS.checks, step);
517
+ if (!checks.length || new Set(checks).size !== checks.length)
518
+ throw new Error("Invalid acceptance checks");
519
+ return {
520
+ candidate: gitOid(a.candidate),
521
+ tree: gitOid(a.tree),
522
+ planDigest: decodeHash(a.planDigest),
523
+ contextDigest: decodeHash(a.contextDigest),
524
+ checks,
525
+ review: step(a.review),
526
+ };
527
+ });
528
+ const candidate = nullable(d.candidate, gitOid);
529
+ if (acceptance && acceptance.candidate !== candidate)
530
+ throw new Error("Stale candidate acceptance");
531
+ const workspace = nullable(d.workspace, (v) => {
532
+ const w = closed(v, ["head", "state"]);
533
+ return {
534
+ head: gitOid(w.head),
535
+ state: oneOf(w.state, [
536
+ "preparing",
537
+ "ready",
538
+ "removed",
539
+ "retained",
540
+ ] as const),
541
+ };
542
+ });
543
+ const binding = decodeDeliveryBinding(d.binding),
544
+ taskBranch = localRef(d.taskBranch);
545
+ if (
546
+ !taskBranch.startsWith("refs/heads/cadence/") ||
547
+ (i.status === "applied" && i.after === null)
548
+ )
549
+ throw new Error("Inconsistent delivery evidence");
550
+ return {
551
+ binding,
552
+ taskBranch,
553
+ worktreeRoot: deliveryPath(d.worktreeRoot),
554
+ preparation: oneOf(d.preparation, ["pending", "ready", "unknown"]),
555
+ workspace,
556
+ candidate,
557
+ acceptance,
558
+ integration: {
559
+ status: oneOf(i.status, [
560
+ "pending",
561
+ "blocked",
562
+ "applying",
563
+ "applied",
564
+ "unknown",
565
+ ]),
566
+ before: gitOid(i.before),
567
+ after: nullable(i.after, gitOid),
568
+ reason: text(i.reason, 2048),
569
+ },
570
+ postChecks: oneOf(d.postChecks, ["not-run", "passed", "failed", "unknown"]),
571
+ cleanup: {
572
+ status: oneOf(c.status, ["pending", "removed", "retained"]),
573
+ reason: text(c.reason, 2048),
574
+ },
575
+ };
576
+ }
577
+ /** Shared native/browser copy: placement is part of the visible approval. */
578
+ export function readableDelivery(binding?: DeliveryBinding): string {
579
+ if (!binding) return "";
580
+ const t = binding.target;
581
+ return `Target: ${t.branch} @ ${t.head}\nTarget checkout: ${t.checkoutRoot}\nExecution: new cadence/<goal>-<run-id> branch and one stable isolated worktree after approval.\nAcceptance: checks and automatic Agent review of the exact candidate.\nDelivery: fast-forward only into the bound target, unchanged since approval or this run's last confirmed merge. Keep the task branch; remove only owned worktrees without any residue, including ignored files. No source/profile/dependency copying, push or deployment.`;
582
+ }
583
+ export function readableDeliveryRun(d?: DeliveryObservation): string {
584
+ if (!d) return "";
585
+ return `Task branch: ${d.taskBranch}\nWorktree: ${d.worktreeRoot}\nTarget: ${d.binding.target.branch} @ ${d.binding.target.head}\nPreparation: ${d.preparation}\nCandidate: ${d.candidate ?? "not recorded"}\nAcceptance: ${d.acceptance ? `checks + automatic Agent review of ${d.acceptance.candidate}` : "not recorded"}\nIntegration: ${d.integration.status}${d.integration.after ? ` @ ${d.integration.after}` : ""}${d.integration.reason ? ` — ${d.integration.reason}` : ""}\nPost-merge checks: ${d.postChecks}\nWorktree cleanup: ${d.cleanup.status}${d.cleanup.reason ? ` — ${d.cleanup.reason}` : ""}\nPolicy: keep the task branch; no push or deployment.`;
586
+ }
354
587
  export function decodeWorkflowProposal(v: unknown): WorkflowProposal {
355
588
  const modern =
356
589
  v !== null && typeof v === "object" && Object.hasOwn(v, "display");
@@ -363,9 +596,13 @@ export function decodeWorkflowProposal(v: unknown): WorkflowProposal {
363
596
  "plan",
364
597
  "cwd",
365
598
  ...(Object.hasOwn(v ?? {}, "checkoutRoot") ? ["checkoutRoot"] : []),
599
+ ...(Object.hasOwn(v ?? {}, "delivery") ? ["delivery"] : []),
366
600
  ...(modern ? ["display"] : []),
367
601
  ]);
368
602
  return {
603
+ ...(o.delivery === undefined
604
+ ? {}
605
+ : { delivery: decodeDeliveryBinding(o.delivery) }),
369
606
  id: decodeId(o.id),
370
607
  epoch: decodeId(o.epoch),
371
608
  digest: decodeHash(o.digest),
@@ -455,8 +692,12 @@ export function decodeWorkflowRun(v: unknown): WorkflowRun {
455
692
  "notice",
456
693
  "mergedCommit",
457
694
  "humanReviewed",
695
+ ...(Object.hasOwn(v ?? {}, "stepsBefore") ? ["stepsBefore"] : []),
696
+ ...(Object.hasOwn(v ?? {}, "revision") ? ["revision"] : []),
697
+ ...(Object.hasOwn(v ?? {}, "verification") ? ["verification"] : []),
458
698
  ...(Object.hasOwn(v ?? {}, "diagnostics") ? ["diagnostics"] : []),
459
699
  ...(Object.hasOwn(v ?? {}, "execution") ? ["execution"] : []),
700
+ ...(Object.hasOwn(v ?? {}, "delivery") ? ["delivery"] : []),
460
701
  ]);
461
702
  const status = (x: unknown) =>
462
703
  oneOf(x, [
@@ -470,6 +711,25 @@ export function decodeWorkflowRun(v: unknown): WorkflowRun {
470
711
  if (o.humanReviewed !== false)
471
712
  throw new Error("Automatic execution is not human review");
472
713
  return {
714
+ ...(o.verification === undefined
715
+ ? {}
716
+ : {
717
+ verification: (() => {
718
+ const evidence = closed(o.verification, ["id", "source", "steps"]);
719
+ return {
720
+ id: decodeId(evidence.id),
721
+ source: decodeHash(evidence.source),
722
+ steps: list(evidence.steps, 32, (v) => text(v, 160, true)),
723
+ };
724
+ })(),
725
+ }),
726
+ ...(o.stepsBefore === undefined
727
+ ? {}
728
+ : { stepsBefore: integer(o.stepsBefore, 0) }),
729
+ ...(o.revision === undefined ? {} : { revision: integer(o.revision, 0) }),
730
+ ...(o.delivery === undefined
731
+ ? {}
732
+ : { delivery: decodeDeliveryObservation(o.delivery) }),
473
733
  ...(o.execution === undefined
474
734
  ? {}
475
735
  : { execution: decodeExecutionContext(o.execution) }),
@@ -485,6 +745,8 @@ export function decodeWorkflowRun(v: unknown): WorkflowRun {
485
745
  "implementing",
486
746
  "verifying",
487
747
  "reviewing",
748
+ "recovering",
749
+ "learning",
488
750
  "integrating",
489
751
  "finished",
490
752
  ]),
@@ -525,11 +787,16 @@ export function decodeWorkflowRun(v: unknown): WorkflowRun {
525
787
  kind: oneOf(s.kind, [
526
788
  "research",
527
789
  "implementation",
790
+ "diagnosis",
791
+ "knowledge",
528
792
  "review",
529
793
  "check",
530
794
  "git",
531
795
  ]),
532
- status: status(s.status),
796
+ status:
797
+ s.kind === "review" && s.status === "rejected"
798
+ ? "rejected"
799
+ : status(s.status),
533
800
  text: text(s.text, 65536),
534
801
  exitCode: nullable(s.exitCode, (n) =>
535
802
  integer(n, -2147483648, 2147483647),
@@ -558,7 +825,7 @@ export function decodeWorkflowResponse(v: unknown): WorkflowResponse {
558
825
  };
559
826
  }
560
827
  export function readableWorkflowPlan(p: WorkflowPlan): string {
561
- return `# ${p.goal}\n\n## Design\n${p.design}\n\n## Decisions\n${p.decisions}\n\n## Acceptance\n${p.acceptance}\n\n## Tasks\n${workflowOrder(
828
+ return `# ${p.goal}\n\n## Initial route (automatically adjustable)\n${p.design}\n\n## Decisions\n${p.decisions}\n\n## Acceptance\n${p.acceptance}\n\n## Tasks\n${workflowOrder(
562
829
  p.tasks,
563
830
  )
564
831
  .map(
@@ -567,7 +834,7 @@ export function readableWorkflowPlan(p: WorkflowPlan): string {
567
834
  )
568
835
  .join(
569
836
  "\n\n",
570
- )}\n\n## Setup (explicitly authorized commands)\n${p.setup.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join("\n") || "None; no dependency installation or copying."}\n\n## Baseline verification\n${p.baselineChecks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join("\n") || "No separate baseline checks declared."}\n\n## Verification\n${p.checks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join("\n")}\n\n## Automation boundary\nAt most ${p.repairAttempts} repair rounds. ${p.delivery === "local-merge" ? "Authorize isolated task worktrees, local task commits and fast-forward integration into the current branch." : "Direct working-copy edits; failures leave actual edits for inspection. No Git commit or merge."} No push, publication, deployment, unplanned installation or recursive delegation. Generated project context and workflow Markdown are included. Worktrees/tools are not a sandbox.\n\n## Project context\n${p.projectContext}\n`;
837
+ )}\n\n## Setup (explicitly authorized commands)\n${p.setup.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join("\n") || "None; no dependency installation or copying."}\n\n## Baseline verification\n${p.baselineChecks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join("\n") || "No separate baseline checks declared."}\n\n## Verification\n${p.checks.map((c) => `${c.name}: ${c.command} (${c.timeoutMs}ms)`).join("\n")}\n\n## Automation boundary\n${p.version === 2 ? "Authorize diagnosis, partial-work continuation, task splitting and alternative implementations within these goals, decisions, write paths and exact setup/check commands. No fixed repair-round or delivery-duration quota. Only actual verification and independent Agent review permit delivery." : `Historical fixed pipeline: at most ${p.repairAttempts} repair rounds.`} ${p.delivery === "local-merge" ? "Authorize one new named task branch and stable isolated worktree after approval, local commits and fast-forward delivery of the exact checked and Agent-reviewed candidate into the displayed target. Keep the task branch; retain any worktree with uncommitted, untracked or ignored residue." : "Direct working-copy edits; failures leave actual edits for inspection. No Git commit or merge."} No push, publication, deployment, unplanned installation or recursive delegation. Related project knowledge and workflow Markdown are included. Worktrees/tools are not a sandbox.\n\n## Project knowledge\n${p.version === 2 ? p.knowledge?.join("\n") || "No documentation edits authorized; existing knowledge is still read." : p.projectContext}\n`;
571
838
  }
572
839
 
573
840
  const timestamp = (v: unknown) => integer(v, 0, 8640000000000000);