@abelxiaoxing/cadence 2.1.2 → 2.1.4

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.
@@ -1,6 +1,7 @@
1
1
  /** Conversation workflow DTOs. Plans are data; only fresh user confirmation admits execution. */
2
2
  import {
3
3
  bool,
4
+ ContractError,
4
5
  canonicalJson,
5
6
  closed,
6
7
  decodeHash,
@@ -10,6 +11,7 @@ import {
10
11
  nullable,
11
12
  oneOf,
12
13
  text,
14
+ utf8Bytes,
13
15
  } from "./core.ts";
14
16
  import {
15
17
  type ChoiceVersion,
@@ -24,10 +26,16 @@ export const WORKFLOW_LIMITS = {
24
26
  * and those they superseded. */
25
27
  route: 48,
26
28
  /** Questions one research run may carry. How many run at once is the
27
- * owner's execution limit (`parallelLimit`), not a property of the plan. */
28
- questions: 8,
29
+ * owner's execution limit (`parallelLimit`), not a property of the plan;
30
+ * the tool schema states no count, so only this bound refuses one. */
31
+ questions: 32,
29
32
  checks: 16,
30
33
  bytes: 256 * 1024,
34
+ /** Goal, route, decisions, assumptions and acceptance together: every
35
+ * worker of the delivery is given them, inside its 32KiB context. */
36
+ context: 32768,
37
+ /** Why a worker should read something first. */
38
+ reason: 1024,
31
39
  // Read budgets, never a lifetime cap on retained runs.
32
40
  historyScanEntries: 200,
33
41
  historyPage: 20,
@@ -39,6 +47,11 @@ export interface WorkflowCheck {
39
47
  command: string;
40
48
  timeoutMs?: number;
41
49
  }
50
+ /** Setup placement is part of approval. Missing only in retained agreements,
51
+ * where the original meaning (every worktree) is preserved. */
52
+ export interface WorkflowSetup extends WorkflowCheck {
53
+ placement?: "target" | "candidate" | "worktree";
54
+ }
42
55
  /** Something a worker should read before it starts: a project document (and
43
56
  * optionally one section of it) or a recorded investigation, with the reason. */
44
57
  export type WorkflowReading =
@@ -81,7 +94,7 @@ export interface WorkflowPlan {
81
94
  projectContext?: string;
82
95
  tasks: WorkflowTask[];
83
96
  checks: WorkflowCheck[];
84
- setup: WorkflowCheck[];
97
+ setup: WorkflowSetup[];
85
98
  baselineChecks: WorkflowCheck[];
86
99
  /** Retained v1 evidence only. New plans have no repair quota. */
87
100
  repairAttempts?: number;
@@ -203,6 +216,8 @@ export interface WorkflowStep {
203
216
  | "running"
204
217
  | "completed"
205
218
  | "rejected"
219
+ | "partial"
220
+ | "blocked"
206
221
  | "failed"
207
222
  | "canceled"
208
223
  | "timeout"
@@ -304,6 +319,94 @@ export type WorkflowResponse =
304
319
  }
305
320
  | { type: "run"; run: WorkflowRun };
306
321
 
322
+ /** A plan or an investigation request that its author can correct: the message
323
+ * names the field, what it holds and what is accepted there. */
324
+ export class WorkflowInputError extends Error {}
325
+ function issue(path: string, problem: string): never {
326
+ throw new WorkflowInputError(`${path}: ${problem}`);
327
+ }
328
+ const quoted = (value: string) => JSON.stringify(clipUnits(value, 80));
329
+ /** Reads one field; whatever refuses it is reported under the field's name. */
330
+ function at<T>(path: string, read: () => T): T {
331
+ try {
332
+ return read();
333
+ } catch (error) {
334
+ if (error instanceof WorkflowInputError) throw error;
335
+ return issue(
336
+ path,
337
+ error instanceof ContractError
338
+ ? error.code === "oversize"
339
+ ? "is too long"
340
+ : "is not valid"
341
+ : error instanceof Error
342
+ ? error.message
343
+ : "is not valid",
344
+ );
345
+ }
346
+ }
347
+ function words(
348
+ path: string,
349
+ v: unknown,
350
+ maximum: number,
351
+ nonempty = false,
352
+ ): string {
353
+ if (v === undefined) return issue(path, "is missing");
354
+ if (typeof v !== "string") return issue(path, "must be text");
355
+ if (nonempty && !v.trim()) return issue(path, "must not be empty");
356
+ const bytes = utf8Bytes(v);
357
+ if (bytes > maximum)
358
+ return issue(path, `is ${bytes} bytes; at most ${maximum}`);
359
+ return at(path, () => text(v, maximum, nonempty));
360
+ }
361
+ function entries<T>(
362
+ path: string,
363
+ v: unknown,
364
+ maximum: number,
365
+ read: (entry: unknown, path: string) => T,
366
+ ): T[] {
367
+ if (v === undefined) return issue(path, "is missing");
368
+ if (!Array.isArray(v)) return issue(path, "must be a list");
369
+ if (v.length > maximum)
370
+ return issue(path, `has ${v.length} entries; at most ${maximum}`);
371
+ return at(path, () => list(v, maximum, (entry) => entry)).map((entry, i) =>
372
+ read(entry, `${path}[${i}]`),
373
+ );
374
+ }
375
+ /** A closed object: every required field present, nothing unknown. */
376
+ function fields(
377
+ path: string,
378
+ v: unknown,
379
+ required: readonly string[],
380
+ optional: readonly string[] = [],
381
+ ): Record<string, unknown> {
382
+ if (v === undefined) return issue(path, "is missing");
383
+ if (v === null || typeof v !== "object" || Array.isArray(v))
384
+ return issue(path, "must be an object");
385
+ const names = Object.keys(v);
386
+ const known = [...required, ...optional];
387
+ const unknown = names.filter((name) => !known.includes(name));
388
+ if (unknown.length)
389
+ return issue(
390
+ path,
391
+ `has no field ${unknown.map(quoted).join(", ")}; its fields are ${known.join(", ")}`,
392
+ );
393
+ const missing = required.filter((name) => !names.includes(name));
394
+ if (missing.length) return issue(path, `is missing ${missing.join(", ")}`);
395
+ return at(path, () =>
396
+ closed(
397
+ v,
398
+ known.filter((name) => names.includes(name)),
399
+ ),
400
+ );
401
+ }
402
+ const INVESTIGATION =
403
+ /^(?:research-[0-9]{1,4}-)?([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$/u;
404
+ /** The record a reading names: a research step's `investigation` value, or the
405
+ * step's own id (`research-<n>-<uuid>`), under whose uuid the same record is
406
+ * kept. Null when the text is neither. */
407
+ export function investigationId(reference: string): string | null {
408
+ return INVESTIGATION.exec(reference)?.[1] ?? null;
409
+ }
307
410
  /** Clip by UTF-16 units without leaving a lone surrogate (unencodable on the wire). */
308
411
  export function clipUnits(value: string, units: number): string {
309
412
  if (value.length <= units) return value;
@@ -337,7 +440,9 @@ export function workflowPath(v: unknown, strict = false): string {
337
440
  ) ||
338
441
  /(^|\/)\.env(?:\.|$)/iu.test(p)
339
442
  )
340
- throw new Error("Invalid workflow file path");
443
+ throw new Error(
444
+ "is not a plain path inside the repository (relative, forward slashes, no . or .. segment, no colon, not .git or .env)",
445
+ );
341
446
  return p;
342
447
  }
343
448
  // Task IDs are worker assignment IDs and worktree names. New plans use the
@@ -345,35 +450,46 @@ export function workflowPath(v: unknown, strict = false): string {
345
450
  const taskId = (v: unknown, strict = false) => {
346
451
  const s = text(v, 64, true);
347
452
  if (!/^[a-z][a-z0-9-]*$/u.test(s) || (strict && s.length > 48))
348
- throw new Error("Invalid task id");
453
+ throw new Error(
454
+ "is not an assignment id (lowercase letters, digits and hyphens, starting with a letter, at most 48 characters)",
455
+ );
349
456
  return s;
350
457
  };
351
458
  /** The identity a new assignment may take. */
352
459
  export const workflowTaskId = (v: unknown) => taskId(v, true);
353
- export function decodeWorkflowCheck(v: unknown): WorkflowCheck {
354
- const o = closed(v, [
355
- "name",
356
- "command",
357
- ...(Object.hasOwn(v ?? {}, "timeoutMs") ? ["timeoutMs"] : []),
358
- ]);
460
+ export function decodeWorkflowCheck(v: unknown, path = "check"): WorkflowCheck {
461
+ const o = fields(path, v, ["name", "command"], ["timeoutMs"]);
359
462
  return {
360
- name: text(o.name, 128, true),
361
- command: text(o.command, 4096, true),
463
+ name: words(`${path}.name`, o.name, 128, true),
464
+ command: words(`${path}.command`, o.command, 4096, true),
362
465
  ...(o.timeoutMs === undefined
363
466
  ? {}
364
- : { timeoutMs: integer(o.timeoutMs, 100, 2_147_483_647) }),
467
+ : {
468
+ timeoutMs: at(`${path}.timeoutMs`, () => {
469
+ try {
470
+ return integer(o.timeoutMs, 100, 2_147_483_647);
471
+ } catch {
472
+ throw new Error(
473
+ "is a whole number of milliseconds from 100 to 2147483647, or left out for no timeout",
474
+ );
475
+ }
476
+ }),
477
+ }),
365
478
  };
366
479
  }
367
480
  export function workflowOrder(tasks: WorkflowTask[]): WorkflowTask[] {
368
481
  const done = new Set<string>(),
369
482
  ordered: WorkflowTask[] = [];
370
483
  if (new Set(tasks.map((t) => t.id)).size !== tasks.length)
371
- throw new Error("Duplicate task id");
484
+ throw new Error("an assignment id is used twice");
372
485
  while (ordered.length < tasks.length) {
373
486
  const next = tasks.find(
374
487
  (t) => !done.has(t.id) && t.after.every((id) => done.has(id)),
375
488
  );
376
- if (!next) throw new Error("Missing dependency or cyclic plan");
489
+ if (!next)
490
+ throw new Error(
491
+ "the after lists name a missing assignment or form a cycle",
492
+ );
377
493
  ordered.push(next);
378
494
  done.add(next.id);
379
495
  }
@@ -397,7 +513,9 @@ export function workflowAncestors(
397
513
  return workflowOrder(tasks).filter((t) => needed.has(t.id));
398
514
  }
399
515
  /** Retained plans decode with the rules they were accepted under; `strict` is
400
- * for validating a new plan before publication or execution. */
516
+ * for validating a new plan before publication or execution. Every refusal
517
+ * names the field (`WorkflowInputError`), so its author can correct that field
518
+ * and publish the same plan again. */
401
519
  export function decodeWorkflowPlan(
402
520
  v: unknown,
403
521
  options: { strict?: boolean } = {},
@@ -408,7 +526,16 @@ export function decodeWorkflowPlan(
408
526
  throw new Error(
409
527
  "Publish a new delivery agreement; retained fixed-pipeline plans are readonly",
410
528
  );
411
- canonicalJson(v, WORKFLOW_LIMITS.bytes);
529
+ try {
530
+ canonicalJson(v, WORKFLOW_LIMITS.bytes);
531
+ } catch (error) {
532
+ issue(
533
+ "plan",
534
+ error instanceof ContractError && error.code === "oversize"
535
+ ? `is larger than ${WORKFLOW_LIMITS.bytes} bytes as a whole`
536
+ : "is not plain JSON data",
537
+ );
538
+ }
412
539
  const version = modern ? (v as { version?: unknown }).version : undefined;
413
540
  if (modern && version !== 2 && version !== 3)
414
541
  throw new Error("Unsupported delivery agreement version");
@@ -417,7 +544,7 @@ export function decodeWorkflowPlan(
417
544
  throw new Error(
418
545
  "Publish a new delivery agreement; earlier agreements are readonly",
419
546
  );
420
- const o = closed(v, [
547
+ const o = fields("plan", v, [
421
548
  "goal",
422
549
  "design",
423
550
  "decisions",
@@ -433,44 +560,70 @@ export function decodeWorkflowPlan(
433
560
  "baselineChecks",
434
561
  "delivery",
435
562
  ]);
436
- const documentation = (value: unknown) =>
437
- list(value, 16, (entry) => {
438
- const path = workflowPath(entry, strict);
439
- if (!path.endsWith(".md"))
440
- throw new Error("Documentation targets must be Markdown files");
441
- return path;
442
- });
443
- const tasks = list(o.tasks, WORKFLOW_LIMITS.tasks, (value) => {
444
- const t = closed(value, [
445
- "id",
446
- "title",
447
- "instructions",
448
- "writes",
449
- "after",
450
- ...(current ? ["reads"] : []),
451
- ]);
452
- return {
453
- id: taskId(t.id, strict),
454
- title: text(t.title, 256, true),
455
- instructions: text(t.instructions, 8192, true),
456
- writes: list(t.writes, 128, (p: unknown) => workflowPath(p, strict)),
457
- after: list(t.after, WORKFLOW_LIMITS.tasks, (id: unknown) =>
458
- taskId(id, strict),
459
- ),
460
- ...(current ? { reads: decodeWorkflowReadings(t.reads, strict) } : {}),
461
- };
462
- });
463
- if (
464
- !tasks.length ||
465
- tasks.some(
466
- (t) =>
467
- !t.writes.length ||
468
- new Set(t.writes).size !== t.writes.length ||
469
- new Set(t.after).size !== t.after.length,
470
- )
471
- )
472
- throw new Error("Empty or duplicate task scope");
473
- workflowOrder(tasks);
563
+ const documentation = (value: unknown, name: string) =>
564
+ entries(name, value, 16, (entry, path) =>
565
+ at(path, () => {
566
+ const document = workflowPath(entry, strict);
567
+ if (!document.endsWith(".md"))
568
+ throw new Error("must be a Markdown file (.md)");
569
+ return document;
570
+ }),
571
+ );
572
+ const tasks = entries(
573
+ "tasks",
574
+ o.tasks,
575
+ WORKFLOW_LIMITS.tasks,
576
+ (value, path) => {
577
+ const t = fields(path, value, [
578
+ "id",
579
+ "title",
580
+ "instructions",
581
+ "writes",
582
+ "after",
583
+ ...(current ? ["reads"] : []),
584
+ ]);
585
+ return {
586
+ id: at(`${path}.id`, () => taskId(t.id, strict)),
587
+ title: words(`${path}.title`, t.title, 256, true),
588
+ instructions: words(`${path}.instructions`, t.instructions, 8192, true),
589
+ writes: entries(`${path}.writes`, t.writes, 128, (p, entry) =>
590
+ at(entry, () => workflowPath(p, strict)),
591
+ ),
592
+ after: entries(
593
+ `${path}.after`,
594
+ t.after,
595
+ WORKFLOW_LIMITS.tasks,
596
+ (id, entry) => at(entry, () => taskId(id, strict)),
597
+ ),
598
+ ...(current
599
+ ? { reads: decodeWorkflowReadings(t.reads, strict, `${path}.reads`) }
600
+ : {}),
601
+ };
602
+ },
603
+ );
604
+ if (!tasks.length) issue("tasks", "needs at least one assignment");
605
+ const ids = tasks.map((t) => t.id);
606
+ for (const [i, t] of tasks.entries()) {
607
+ const path = `tasks[${i}]`;
608
+ if (ids.indexOf(t.id) !== i)
609
+ issue(
610
+ `${path}.id`,
611
+ `${quoted(t.id)} is already the id of tasks[${ids.indexOf(t.id)}]`,
612
+ );
613
+ if (!t.writes.length)
614
+ issue(`${path}.writes`, "needs at least one path this assignment writes");
615
+ if (new Set(t.writes).size !== t.writes.length)
616
+ issue(`${path}.writes`, "lists a path twice");
617
+ if (new Set(t.after).size !== t.after.length)
618
+ issue(`${path}.after`, "lists an assignment twice");
619
+ const unknown = t.after.find((id) => !ids.includes(id));
620
+ if (unknown !== undefined)
621
+ issue(
622
+ `${path}.after`,
623
+ `names ${quoted(unknown)}, which is not the id of an assignment in tasks`,
624
+ );
625
+ }
626
+ at("tasks", () => workflowOrder(tasks));
474
627
  // Retained parallel plans keep their original validation. New delivery uses
475
628
  // a stable sequential candidate, so adjacent assignments may share files.
476
629
  for (const a of modern ? [] : tasks)
@@ -489,69 +642,215 @@ export function decodeWorkflowPlan(
489
642
  "Independent tasks share write paths; assign an owner and dependency",
490
643
  );
491
644
  }
492
- const checks = list(o.checks, WORKFLOW_LIMITS.checks, decodeWorkflowCheck);
645
+ const commands = (value: unknown, name: string, maximum: number) =>
646
+ entries(name, value, maximum, decodeWorkflowCheck);
647
+ const checks = commands(o.checks, "checks", WORKFLOW_LIMITS.checks);
493
648
  if (!checks.length)
494
- throw new Error("At least one real verification command is required");
649
+ issue("checks", "needs at least one real verification command");
495
650
  const result: WorkflowPlan = {
496
- goal: text(o.goal, 8192, true),
497
- design: text(o.design, 32768, true),
498
- decisions: text(o.decisions, 16384),
499
- acceptance: text(o.acceptance, 16384, true),
651
+ goal: words("goal", o.goal, 8192, true),
652
+ design: words("design", o.design, 32768, true),
653
+ decisions: words("decisions", o.decisions, 16384),
654
+ acceptance: words("acceptance", o.acceptance, 16384, true),
500
655
  ...(current
501
656
  ? {
502
657
  version: 3 as const,
503
- assumptions: text(o.assumptions, 16384),
504
- documents: documentation(o.documents),
505
- reviewReads: decodeWorkflowReadings(o.reviewReads, strict),
658
+ assumptions: words("assumptions", o.assumptions, 16384),
659
+ documents: documentation(o.documents, "documents"),
660
+ reviewReads: decodeWorkflowReadings(
661
+ o.reviewReads,
662
+ strict,
663
+ "reviewReads",
664
+ ),
506
665
  policy: {
507
- installs: bool(closed(o.policy, ["installs"]).installs),
666
+ installs: at("policy.installs", () => {
667
+ try {
668
+ return bool(fields("policy", o.policy, ["installs"]).installs);
669
+ } catch (error) {
670
+ if (error instanceof WorkflowInputError) throw error;
671
+ throw new Error("must be true or false");
672
+ }
673
+ }),
508
674
  },
509
675
  }
510
676
  : modern
511
- ? { version: 2 as const, knowledge: documentation(o.knowledge) }
677
+ ? {
678
+ version: 2 as const,
679
+ knowledge: documentation(o.knowledge, "knowledge"),
680
+ }
512
681
  : {
513
- projectContext: text(o.projectContext, 16384),
514
- repairAttempts: integer(o.repairAttempts, 0, 2),
682
+ projectContext: words("projectContext", o.projectContext, 16384),
683
+ repairAttempts: at("repairAttempts", () =>
684
+ integer(o.repairAttempts, 0, 2),
685
+ ),
515
686
  }),
516
687
  tasks,
517
688
  checks,
518
- setup: list(o.setup, 4, decodeWorkflowCheck),
519
- baselineChecks: list(
689
+ setup: entries("setup", o.setup, 4, (value, path): WorkflowSetup => {
690
+ const entry = fields(
691
+ path,
692
+ value,
693
+ ["name", "command", ...(strict ? ["placement"] : [])],
694
+ ["timeoutMs", ...(!strict ? ["placement"] : [])],
695
+ );
696
+ const { placement, ...check } = entry;
697
+ return {
698
+ ...decodeWorkflowCheck(check, path),
699
+ ...(placement === undefined
700
+ ? {}
701
+ : {
702
+ placement: at(`${path}.placement`, () =>
703
+ oneOf(placement, ["target", "candidate", "worktree"]),
704
+ ),
705
+ }),
706
+ };
707
+ }),
708
+ baselineChecks: commands(
520
709
  o.baselineChecks,
710
+ "baselineChecks",
521
711
  WORKFLOW_LIMITS.checks,
522
- decodeWorkflowCheck,
523
712
  ),
524
- delivery: oneOf(o.delivery, ["local-merge", "working-copy"]),
713
+ delivery: at("delivery", () => {
714
+ try {
715
+ return oneOf(o.delivery, ["local-merge", "working-copy"]);
716
+ } catch {
717
+ throw new Error("is local-merge or working-copy");
718
+ }
719
+ }),
525
720
  };
526
- workflowContext(result);
527
- text(workflowWrites(result).join(", "), 16384);
528
- for (const value of [
529
- result.goal,
530
- result.design,
531
- result.decisions,
532
- result.acceptance,
533
- result.assumptions ?? "",
534
- result.projectContext ?? "",
535
- ...[
536
- ...(result.reviewReads ?? []),
537
- ...result.tasks.flatMap((t) => t.reads ?? []),
538
- ].flatMap((r) => [r.reason, "section" in r ? (r.section ?? "") : ""]),
539
- ...result.tasks.flatMap((t) => [t.title, t.instructions]),
540
- ...[...result.checks, ...result.setup, ...result.baselineChecks].flatMap(
541
- (c) => [c.name, c.command],
721
+ // Every worker of the delivery is given these five together.
722
+ const agreement = utf8Bytes(agreementText(result));
723
+ if (agreement > WORKFLOW_LIMITS.context)
724
+ issue(
725
+ "plan",
726
+ `goal, design, decisions, assumptions and acceptance are ${agreement} bytes together (${(
727
+ ["goal", "design", "decisions", "assumptions", "acceptance"] as const
728
+ )
729
+ .map((name) => `${name} ${utf8Bytes(result[name] ?? "")}`)
730
+ .join(", ")}); together at most ${WORKFLOW_LIMITS.context}`,
731
+ );
732
+ const scope = utf8Bytes(workflowWrites(result).join(", "));
733
+ if (scope > 16384)
734
+ issue(
735
+ "tasks",
736
+ `the write paths of all assignments and documents are ${scope} bytes together; at most 16384`,
737
+ );
738
+ const readings = (list: WorkflowReading[] | undefined, name: string) =>
739
+ (list ?? []).flatMap((r, i): [string, string][] => [
740
+ [`${name}[${i}].reason`, r.reason],
741
+ [`${name}[${i}].section`, "section" in r ? (r.section ?? "") : ""],
742
+ ]);
743
+ for (const [path, value] of [
744
+ ["goal", result.goal],
745
+ ["design", result.design],
746
+ ["decisions", result.decisions],
747
+ ["acceptance", result.acceptance],
748
+ ["assumptions", result.assumptions ?? ""],
749
+ ["projectContext", result.projectContext ?? ""],
750
+ ...readings(result.reviewReads, "reviewReads"),
751
+ ...result.tasks.flatMap((t, i): [string, string][] => [
752
+ [`tasks[${i}].title`, t.title],
753
+ [`tasks[${i}].instructions`, t.instructions],
754
+ ...readings(t.reads, `tasks[${i}].reads`),
755
+ ]),
756
+ ...(["checks", "setup", "baselineChecks"] as const).flatMap((name) =>
757
+ result[name].flatMap((c, i): [string, string][] => [
758
+ [`${name}[${i}].name`, c.name],
759
+ [`${name}[${i}].command`, c.command],
760
+ ]),
542
761
  ),
543
- ])
762
+ ] as [string, string][])
544
763
  if (
545
764
  [...value].some(
546
765
  (c) =>
547
766
  (c.charCodeAt(0) < 32 && c !== "\n" && c !== "\t") ||
548
767
  c.charCodeAt(0) === 127 ||
549
- /[\u202a-\u202e\u2066-\u2069]/u.test(c),
768
+ /[‪-‮⁦-⁩]/u.test(c),
550
769
  )
551
770
  )
552
- throw new Error("Plan contains invisible terminal controls");
771
+ issue(
772
+ path,
773
+ "contains an invisible control character (only newline and tab are accepted)",
774
+ );
553
775
  return result;
554
776
  }
777
+ /** A plan as the coordinator gave it, made complete: a field that may be empty
778
+ * takes its empty value when left out, and the agreement is the current
779
+ * version. The result is decoded as a new agreement, so everything that cannot
780
+ * be accepted, an unknown field included, is refused by name. */
781
+ export function workflowPlanInput(v: unknown): WorkflowPlan {
782
+ if (v === null || typeof v !== "object" || Array.isArray(v))
783
+ return issue("plan", "must be an object");
784
+ const completed = (
785
+ source: object,
786
+ defaults: Record<string, unknown>,
787
+ ): Record<string, unknown> => {
788
+ const result: Record<string, unknown> = { ...defaults };
789
+ // A model sends null for a field it means to leave out.
790
+ for (const [key, value] of Object.entries(source))
791
+ if (value !== null && value !== undefined) result[key] = value;
792
+ return result;
793
+ };
794
+ const plan = completed(v, {
795
+ version: 3,
796
+ decisions: "",
797
+ assumptions: "",
798
+ documents: [],
799
+ reviewReads: [],
800
+ policy: {},
801
+ setup: [],
802
+ baselineChecks: [],
803
+ });
804
+ if (plan.policy && typeof plan.policy === "object")
805
+ plan.policy = completed(plan.policy, { installs: false });
806
+ if (Array.isArray(plan.tasks))
807
+ plan.tasks = plan.tasks.map((task: unknown) =>
808
+ task && typeof task === "object" && !Array.isArray(task)
809
+ ? completed(task, { after: [], reads: [] })
810
+ : task,
811
+ );
812
+ return decodeWorkflowPlan(plan, { strict: true });
813
+ }
814
+ /** An investigation request as the coordinator gave it: questions trimmed,
815
+ * empty and repeated ones dropped, fields this contract does not know ignored.
816
+ * What is left is refused by name when it cannot be asked. */
817
+ export function researchInput(v: unknown): {
818
+ goal: string;
819
+ questions: string[];
820
+ roots?: string[];
821
+ } {
822
+ if (v === null || typeof v !== "object" || Array.isArray(v))
823
+ return issue("request", "must be an object with a goal and questions");
824
+ const given = (key: string): unknown =>
825
+ Object.getOwnPropertyDescriptor(v, key)?.value ?? undefined;
826
+ const distinct = (name: string, value: unknown, maximum: number) => [
827
+ ...new Set(
828
+ entries(
829
+ name,
830
+ typeof value === "string" ? [value] : value,
831
+ Number.MAX_SAFE_INTEGER,
832
+ (entry, path) => words(path, entry, maximum).trim(),
833
+ ).filter(Boolean),
834
+ ),
835
+ ];
836
+ const questions = distinct("questions", given("questions"), 8192);
837
+ if (!questions.length)
838
+ issue("questions", "needs at least one question that is not empty");
839
+ if (questions.length > WORKFLOW_LIMITS.questions)
840
+ issue(
841
+ "questions",
842
+ `has ${questions.length} questions; one investigation takes at most ${WORKFLOW_LIMITS.questions}, so ask the others in a further call`,
843
+ );
844
+ const roots =
845
+ given("roots") === undefined ? [] : distinct("roots", given("roots"), 4096);
846
+ if (roots.length > 8)
847
+ issue("roots", `has ${roots.length} directories; at most 8`);
848
+ return {
849
+ goal: words("goal", given("goal"), 8192, true),
850
+ questions,
851
+ ...(roots.length ? { roots } : {}),
852
+ };
853
+ }
555
854
  /** Existing project documents the agreement allows this delivery to update. */
556
855
  export function workflowDocuments(p: WorkflowPlan): string[] {
557
856
  return p.documents ?? p.knowledge ?? [];
@@ -584,35 +883,38 @@ export function workflowBoundary(path: string): boolean {
584
883
  function decodeWorkflowReadings(
585
884
  value: unknown,
586
885
  strict: boolean,
886
+ name: string,
587
887
  ): WorkflowReading[] {
588
- return list(value, 16, (entry): WorkflowReading => {
888
+ return entries(name, value, 16, (entry, path): WorkflowReading => {
589
889
  if (Object.hasOwn((entry ?? {}) as object, "research")) {
590
- const r = closed(entry, ["research", "reason"]);
890
+ const r = fields(path, entry, ["research", "reason"]);
891
+ // Either spelling of the record; the plan keeps its uuid.
892
+ const id =
893
+ typeof r.research === "string" ? investigationId(r.research) : null;
894
+ if (id === null)
895
+ issue(
896
+ `${path}.research`,
897
+ `${typeof r.research === "string" ? `${quoted(r.research)} ` : ""}is not an investigation; give the "investigation" value of a completed research step`,
898
+ );
591
899
  return {
592
- research: decodeId(r.research),
593
- reason: text(r.reason, 512, true),
900
+ research: id as string,
901
+ reason: words(`${path}.reason`, r.reason, WORKFLOW_LIMITS.reason, true),
594
902
  };
595
903
  }
596
- const r = closed(entry, [
597
- "path",
598
- ...(Object.hasOwn((entry ?? {}) as object, "section") ? ["section"] : []),
599
- "reason",
600
- ]);
904
+ const r = fields(path, entry, ["path", "reason"], ["section"]);
601
905
  return {
602
- path: workflowPath(r.path, strict),
906
+ path: at(`${path}.path`, () => workflowPath(r.path, strict)),
603
907
  ...(r.section === undefined
604
908
  ? {}
605
- : { section: text(r.section, 256, true) }),
606
- reason: text(r.reason, 512, true),
909
+ : { section: words(`${path}.section`, r.section, 256, true) }),
910
+ reason: words(`${path}.reason`, r.reason, WORKFLOW_LIMITS.reason, true),
607
911
  };
608
912
  });
609
913
  }
914
+ const agreementText = (p: WorkflowPlan) =>
915
+ `# ${p.goal}\n\nInitial route (${p.version === 3 ? "the owner may revise it" : "adapt within the approved boundary"}): ${p.design}\n\nExplicit decisions and non-goals: ${p.decisions}${p.assumptions ? `\n\nAssumptions confirmed with the agreement: ${p.assumptions}` : ""}\n\nAcceptance: ${p.acceptance}`;
610
916
  export function workflowContext(p: WorkflowPlan): string {
611
- return text(
612
- `# ${p.goal}\n\nInitial route (${p.version === 3 ? "the owner may revise it" : "adapt within the approved boundary"}): ${p.design}\n\nExplicit decisions and non-goals: ${p.decisions}${p.assumptions ? `\n\nAssumptions confirmed with the agreement: ${p.assumptions}` : ""}\n\nAcceptance: ${p.acceptance}`,
613
- 32768,
614
- true,
615
- );
917
+ return text(agreementText(p), WORKFLOW_LIMITS.context, true);
616
918
  }
617
919
  export function gitOid(value: unknown): string {
618
920
  const oid = text(value, 64, true);
@@ -1068,7 +1370,10 @@ export function decodeWorkflowRun(v: unknown): WorkflowRun {
1068
1370
  status:
1069
1371
  s.kind === "review" && s.status === "rejected"
1070
1372
  ? "rejected"
1071
- : status(s.status),
1373
+ : ["implementation", "knowledge"].includes(s.kind as string) &&
1374
+ ["partial", "blocked"].includes(s.status as string)
1375
+ ? oneOf(s.status, ["partial", "blocked"])
1376
+ : status(s.status),
1072
1377
  text: text(s.text, 65536),
1073
1378
  exitCode: nullable(s.exitCode, (n) =>
1074
1379
  integer(n, -2147483648, 2147483647),
@@ -1123,7 +1428,7 @@ export function readableWorkflowPlan(p: WorkflowPlan): string {
1123
1428
  )
1124
1429
  .join(
1125
1430
  "\n\n",
1126
- )}\n\n## Setup (explicitly authorized commands)\n${p.setup.map(readableCheck).join("\n") || "None; no dependency installation or copying."}\n\n## Baseline verification\n${p.baselineChecks.map(readableCheck).join("\n") || "No separate baseline checks declared."}\n\n## Verification\n${p.checks.map(readableCheck).join("\n")}${
1431
+ )}\n\n## Setup (explicitly authorized commands)\nExecution order: target once before worktree creation, candidate once, then worktree in the candidate and every detached child; listed order within each stage. Each command is a separate process; exports do not persist.\n${p.setup.map((c) => `[${c.placement ?? "worktree"}] ${readableCheck(c)}`).join("\n") || "None; no dependency installation or copying."}\n\n## Baseline verification\n${p.baselineChecks.map(readableCheck).join("\n") || "No separate baseline checks declared."}\n\n## Verification\n${p.checks.map(readableCheck).join("\n")}${
1127
1432
  p.reviewReads?.length
1128
1433
  ? `\n\n## Review reads first\n${p.reviewReads.map(readableReading).join("\n")}`
1129
1434
  : ""