@abelxiaoxing/cadence 2.1.1 → 2.1.3

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,
@@ -304,6 +312,94 @@ export type WorkflowResponse =
304
312
  }
305
313
  | { type: "run"; run: WorkflowRun };
306
314
 
315
+ /** A plan or an investigation request that its author can correct: the message
316
+ * names the field, what it holds and what is accepted there. */
317
+ export class WorkflowInputError extends Error {}
318
+ function issue(path: string, problem: string): never {
319
+ throw new WorkflowInputError(`${path}: ${problem}`);
320
+ }
321
+ const quoted = (value: string) => JSON.stringify(clipUnits(value, 80));
322
+ /** Reads one field; whatever refuses it is reported under the field's name. */
323
+ function at<T>(path: string, read: () => T): T {
324
+ try {
325
+ return read();
326
+ } catch (error) {
327
+ if (error instanceof WorkflowInputError) throw error;
328
+ return issue(
329
+ path,
330
+ error instanceof ContractError
331
+ ? error.code === "oversize"
332
+ ? "is too long"
333
+ : "is not valid"
334
+ : error instanceof Error
335
+ ? error.message
336
+ : "is not valid",
337
+ );
338
+ }
339
+ }
340
+ function words(
341
+ path: string,
342
+ v: unknown,
343
+ maximum: number,
344
+ nonempty = false,
345
+ ): string {
346
+ if (v === undefined) return issue(path, "is missing");
347
+ if (typeof v !== "string") return issue(path, "must be text");
348
+ if (nonempty && !v.trim()) return issue(path, "must not be empty");
349
+ const bytes = utf8Bytes(v);
350
+ if (bytes > maximum)
351
+ return issue(path, `is ${bytes} bytes; at most ${maximum}`);
352
+ return at(path, () => text(v, maximum, nonempty));
353
+ }
354
+ function entries<T>(
355
+ path: string,
356
+ v: unknown,
357
+ maximum: number,
358
+ read: (entry: unknown, path: string) => T,
359
+ ): T[] {
360
+ if (v === undefined) return issue(path, "is missing");
361
+ if (!Array.isArray(v)) return issue(path, "must be a list");
362
+ if (v.length > maximum)
363
+ return issue(path, `has ${v.length} entries; at most ${maximum}`);
364
+ return at(path, () => list(v, maximum, (entry) => entry)).map((entry, i) =>
365
+ read(entry, `${path}[${i}]`),
366
+ );
367
+ }
368
+ /** A closed object: every required field present, nothing unknown. */
369
+ function fields(
370
+ path: string,
371
+ v: unknown,
372
+ required: readonly string[],
373
+ optional: readonly string[] = [],
374
+ ): Record<string, unknown> {
375
+ if (v === undefined) return issue(path, "is missing");
376
+ if (v === null || typeof v !== "object" || Array.isArray(v))
377
+ return issue(path, "must be an object");
378
+ const names = Object.keys(v);
379
+ const known = [...required, ...optional];
380
+ const unknown = names.filter((name) => !known.includes(name));
381
+ if (unknown.length)
382
+ return issue(
383
+ path,
384
+ `has no field ${unknown.map(quoted).join(", ")}; its fields are ${known.join(", ")}`,
385
+ );
386
+ const missing = required.filter((name) => !names.includes(name));
387
+ if (missing.length) return issue(path, `is missing ${missing.join(", ")}`);
388
+ return at(path, () =>
389
+ closed(
390
+ v,
391
+ known.filter((name) => names.includes(name)),
392
+ ),
393
+ );
394
+ }
395
+ const INVESTIGATION =
396
+ /^(?: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;
397
+ /** The record a reading names: a research step's `investigation` value, or the
398
+ * step's own id (`research-<n>-<uuid>`), under whose uuid the same record is
399
+ * kept. Null when the text is neither. */
400
+ export function investigationId(reference: string): string | null {
401
+ return INVESTIGATION.exec(reference)?.[1] ?? null;
402
+ }
307
403
  /** Clip by UTF-16 units without leaving a lone surrogate (unencodable on the wire). */
308
404
  export function clipUnits(value: string, units: number): string {
309
405
  if (value.length <= units) return value;
@@ -337,7 +433,9 @@ export function workflowPath(v: unknown, strict = false): string {
337
433
  ) ||
338
434
  /(^|\/)\.env(?:\.|$)/iu.test(p)
339
435
  )
340
- throw new Error("Invalid workflow file path");
436
+ throw new Error(
437
+ "is not a plain path inside the repository (relative, forward slashes, no . or .. segment, no colon, not .git or .env)",
438
+ );
341
439
  return p;
342
440
  }
343
441
  // Task IDs are worker assignment IDs and worktree names. New plans use the
@@ -345,35 +443,46 @@ export function workflowPath(v: unknown, strict = false): string {
345
443
  const taskId = (v: unknown, strict = false) => {
346
444
  const s = text(v, 64, true);
347
445
  if (!/^[a-z][a-z0-9-]*$/u.test(s) || (strict && s.length > 48))
348
- throw new Error("Invalid task id");
446
+ throw new Error(
447
+ "is not an assignment id (lowercase letters, digits and hyphens, starting with a letter, at most 48 characters)",
448
+ );
349
449
  return s;
350
450
  };
351
451
  /** The identity a new assignment may take. */
352
452
  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
- ]);
453
+ export function decodeWorkflowCheck(v: unknown, path = "check"): WorkflowCheck {
454
+ const o = fields(path, v, ["name", "command"], ["timeoutMs"]);
359
455
  return {
360
- name: text(o.name, 128, true),
361
- command: text(o.command, 4096, true),
456
+ name: words(`${path}.name`, o.name, 128, true),
457
+ command: words(`${path}.command`, o.command, 4096, true),
362
458
  ...(o.timeoutMs === undefined
363
459
  ? {}
364
- : { timeoutMs: integer(o.timeoutMs, 100, 2_147_483_647) }),
460
+ : {
461
+ timeoutMs: at(`${path}.timeoutMs`, () => {
462
+ try {
463
+ return integer(o.timeoutMs, 100, 2_147_483_647);
464
+ } catch {
465
+ throw new Error(
466
+ "is a whole number of milliseconds from 100 to 2147483647, or left out for no timeout",
467
+ );
468
+ }
469
+ }),
470
+ }),
365
471
  };
366
472
  }
367
473
  export function workflowOrder(tasks: WorkflowTask[]): WorkflowTask[] {
368
474
  const done = new Set<string>(),
369
475
  ordered: WorkflowTask[] = [];
370
476
  if (new Set(tasks.map((t) => t.id)).size !== tasks.length)
371
- throw new Error("Duplicate task id");
477
+ throw new Error("an assignment id is used twice");
372
478
  while (ordered.length < tasks.length) {
373
479
  const next = tasks.find(
374
480
  (t) => !done.has(t.id) && t.after.every((id) => done.has(id)),
375
481
  );
376
- if (!next) throw new Error("Missing dependency or cyclic plan");
482
+ if (!next)
483
+ throw new Error(
484
+ "the after lists name a missing assignment or form a cycle",
485
+ );
377
486
  ordered.push(next);
378
487
  done.add(next.id);
379
488
  }
@@ -397,7 +506,9 @@ export function workflowAncestors(
397
506
  return workflowOrder(tasks).filter((t) => needed.has(t.id));
398
507
  }
399
508
  /** Retained plans decode with the rules they were accepted under; `strict` is
400
- * for validating a new plan before publication or execution. */
509
+ * for validating a new plan before publication or execution. Every refusal
510
+ * names the field (`WorkflowInputError`), so its author can correct that field
511
+ * and publish the same plan again. */
401
512
  export function decodeWorkflowPlan(
402
513
  v: unknown,
403
514
  options: { strict?: boolean } = {},
@@ -408,7 +519,16 @@ export function decodeWorkflowPlan(
408
519
  throw new Error(
409
520
  "Publish a new delivery agreement; retained fixed-pipeline plans are readonly",
410
521
  );
411
- canonicalJson(v, WORKFLOW_LIMITS.bytes);
522
+ try {
523
+ canonicalJson(v, WORKFLOW_LIMITS.bytes);
524
+ } catch (error) {
525
+ issue(
526
+ "plan",
527
+ error instanceof ContractError && error.code === "oversize"
528
+ ? `is larger than ${WORKFLOW_LIMITS.bytes} bytes as a whole`
529
+ : "is not plain JSON data",
530
+ );
531
+ }
412
532
  const version = modern ? (v as { version?: unknown }).version : undefined;
413
533
  if (modern && version !== 2 && version !== 3)
414
534
  throw new Error("Unsupported delivery agreement version");
@@ -417,7 +537,7 @@ export function decodeWorkflowPlan(
417
537
  throw new Error(
418
538
  "Publish a new delivery agreement; earlier agreements are readonly",
419
539
  );
420
- const o = closed(v, [
540
+ const o = fields("plan", v, [
421
541
  "goal",
422
542
  "design",
423
543
  "decisions",
@@ -433,44 +553,70 @@ export function decodeWorkflowPlan(
433
553
  "baselineChecks",
434
554
  "delivery",
435
555
  ]);
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);
556
+ const documentation = (value: unknown, name: string) =>
557
+ entries(name, value, 16, (entry, path) =>
558
+ at(path, () => {
559
+ const document = workflowPath(entry, strict);
560
+ if (!document.endsWith(".md"))
561
+ throw new Error("must be a Markdown file (.md)");
562
+ return document;
563
+ }),
564
+ );
565
+ const tasks = entries(
566
+ "tasks",
567
+ o.tasks,
568
+ WORKFLOW_LIMITS.tasks,
569
+ (value, path) => {
570
+ const t = fields(path, value, [
571
+ "id",
572
+ "title",
573
+ "instructions",
574
+ "writes",
575
+ "after",
576
+ ...(current ? ["reads"] : []),
577
+ ]);
578
+ return {
579
+ id: at(`${path}.id`, () => taskId(t.id, strict)),
580
+ title: words(`${path}.title`, t.title, 256, true),
581
+ instructions: words(`${path}.instructions`, t.instructions, 8192, true),
582
+ writes: entries(`${path}.writes`, t.writes, 128, (p, entry) =>
583
+ at(entry, () => workflowPath(p, strict)),
584
+ ),
585
+ after: entries(
586
+ `${path}.after`,
587
+ t.after,
588
+ WORKFLOW_LIMITS.tasks,
589
+ (id, entry) => at(entry, () => taskId(id, strict)),
590
+ ),
591
+ ...(current
592
+ ? { reads: decodeWorkflowReadings(t.reads, strict, `${path}.reads`) }
593
+ : {}),
594
+ };
595
+ },
596
+ );
597
+ if (!tasks.length) issue("tasks", "needs at least one assignment");
598
+ const ids = tasks.map((t) => t.id);
599
+ for (const [i, t] of tasks.entries()) {
600
+ const path = `tasks[${i}]`;
601
+ if (ids.indexOf(t.id) !== i)
602
+ issue(
603
+ `${path}.id`,
604
+ `${quoted(t.id)} is already the id of tasks[${ids.indexOf(t.id)}]`,
605
+ );
606
+ if (!t.writes.length)
607
+ issue(`${path}.writes`, "needs at least one path this assignment writes");
608
+ if (new Set(t.writes).size !== t.writes.length)
609
+ issue(`${path}.writes`, "lists a path twice");
610
+ if (new Set(t.after).size !== t.after.length)
611
+ issue(`${path}.after`, "lists an assignment twice");
612
+ const unknown = t.after.find((id) => !ids.includes(id));
613
+ if (unknown !== undefined)
614
+ issue(
615
+ `${path}.after`,
616
+ `names ${quoted(unknown)}, which is not the id of an assignment in tasks`,
617
+ );
618
+ }
619
+ at("tasks", () => workflowOrder(tasks));
474
620
  // Retained parallel plans keep their original validation. New delivery uses
475
621
  // a stable sequential candidate, so adjacent assignments may share files.
476
622
  for (const a of modern ? [] : tasks)
@@ -489,69 +635,197 @@ export function decodeWorkflowPlan(
489
635
  "Independent tasks share write paths; assign an owner and dependency",
490
636
  );
491
637
  }
492
- const checks = list(o.checks, WORKFLOW_LIMITS.checks, decodeWorkflowCheck);
638
+ const commands = (value: unknown, name: string, maximum: number) =>
639
+ entries(name, value, maximum, decodeWorkflowCheck);
640
+ const checks = commands(o.checks, "checks", WORKFLOW_LIMITS.checks);
493
641
  if (!checks.length)
494
- throw new Error("At least one real verification command is required");
642
+ issue("checks", "needs at least one real verification command");
495
643
  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),
644
+ goal: words("goal", o.goal, 8192, true),
645
+ design: words("design", o.design, 32768, true),
646
+ decisions: words("decisions", o.decisions, 16384),
647
+ acceptance: words("acceptance", o.acceptance, 16384, true),
500
648
  ...(current
501
649
  ? {
502
650
  version: 3 as const,
503
- assumptions: text(o.assumptions, 16384),
504
- documents: documentation(o.documents),
505
- reviewReads: decodeWorkflowReadings(o.reviewReads, strict),
651
+ assumptions: words("assumptions", o.assumptions, 16384),
652
+ documents: documentation(o.documents, "documents"),
653
+ reviewReads: decodeWorkflowReadings(
654
+ o.reviewReads,
655
+ strict,
656
+ "reviewReads",
657
+ ),
506
658
  policy: {
507
- installs: bool(closed(o.policy, ["installs"]).installs),
659
+ installs: at("policy.installs", () => {
660
+ try {
661
+ return bool(fields("policy", o.policy, ["installs"]).installs);
662
+ } catch (error) {
663
+ if (error instanceof WorkflowInputError) throw error;
664
+ throw new Error("must be true or false");
665
+ }
666
+ }),
508
667
  },
509
668
  }
510
669
  : modern
511
- ? { version: 2 as const, knowledge: documentation(o.knowledge) }
670
+ ? {
671
+ version: 2 as const,
672
+ knowledge: documentation(o.knowledge, "knowledge"),
673
+ }
512
674
  : {
513
- projectContext: text(o.projectContext, 16384),
514
- repairAttempts: integer(o.repairAttempts, 0, 2),
675
+ projectContext: words("projectContext", o.projectContext, 16384),
676
+ repairAttempts: at("repairAttempts", () =>
677
+ integer(o.repairAttempts, 0, 2),
678
+ ),
515
679
  }),
516
680
  tasks,
517
681
  checks,
518
- setup: list(o.setup, 4, decodeWorkflowCheck),
519
- baselineChecks: list(
682
+ setup: commands(o.setup, "setup", 4),
683
+ baselineChecks: commands(
520
684
  o.baselineChecks,
685
+ "baselineChecks",
521
686
  WORKFLOW_LIMITS.checks,
522
- decodeWorkflowCheck,
523
687
  ),
524
- delivery: oneOf(o.delivery, ["local-merge", "working-copy"]),
688
+ delivery: at("delivery", () => {
689
+ try {
690
+ return oneOf(o.delivery, ["local-merge", "working-copy"]);
691
+ } catch {
692
+ throw new Error("is local-merge or working-copy");
693
+ }
694
+ }),
525
695
  };
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],
696
+ // Every worker of the delivery is given these five together.
697
+ const agreement = utf8Bytes(agreementText(result));
698
+ if (agreement > WORKFLOW_LIMITS.context)
699
+ issue(
700
+ "plan",
701
+ `goal, design, decisions, assumptions and acceptance are ${agreement} bytes together (${(
702
+ ["goal", "design", "decisions", "assumptions", "acceptance"] as const
703
+ )
704
+ .map((name) => `${name} ${utf8Bytes(result[name] ?? "")}`)
705
+ .join(", ")}); together at most ${WORKFLOW_LIMITS.context}`,
706
+ );
707
+ const scope = utf8Bytes(workflowWrites(result).join(", "));
708
+ if (scope > 16384)
709
+ issue(
710
+ "tasks",
711
+ `the write paths of all assignments and documents are ${scope} bytes together; at most 16384`,
712
+ );
713
+ const readings = (list: WorkflowReading[] | undefined, name: string) =>
714
+ (list ?? []).flatMap((r, i): [string, string][] => [
715
+ [`${name}[${i}].reason`, r.reason],
716
+ [`${name}[${i}].section`, "section" in r ? (r.section ?? "") : ""],
717
+ ]);
718
+ for (const [path, value] of [
719
+ ["goal", result.goal],
720
+ ["design", result.design],
721
+ ["decisions", result.decisions],
722
+ ["acceptance", result.acceptance],
723
+ ["assumptions", result.assumptions ?? ""],
724
+ ["projectContext", result.projectContext ?? ""],
725
+ ...readings(result.reviewReads, "reviewReads"),
726
+ ...result.tasks.flatMap((t, i): [string, string][] => [
727
+ [`tasks[${i}].title`, t.title],
728
+ [`tasks[${i}].instructions`, t.instructions],
729
+ ...readings(t.reads, `tasks[${i}].reads`),
730
+ ]),
731
+ ...(["checks", "setup", "baselineChecks"] as const).flatMap((name) =>
732
+ result[name].flatMap((c, i): [string, string][] => [
733
+ [`${name}[${i}].name`, c.name],
734
+ [`${name}[${i}].command`, c.command],
735
+ ]),
542
736
  ),
543
- ])
737
+ ] as [string, string][])
544
738
  if (
545
739
  [...value].some(
546
740
  (c) =>
547
741
  (c.charCodeAt(0) < 32 && c !== "\n" && c !== "\t") ||
548
742
  c.charCodeAt(0) === 127 ||
549
- /[\u202a-\u202e\u2066-\u2069]/u.test(c),
743
+ /[‪-‮⁦-⁩]/u.test(c),
550
744
  )
551
745
  )
552
- throw new Error("Plan contains invisible terminal controls");
746
+ issue(
747
+ path,
748
+ "contains an invisible control character (only newline and tab are accepted)",
749
+ );
553
750
  return result;
554
751
  }
752
+ /** A plan as the coordinator gave it, made complete: a field that may be empty
753
+ * takes its empty value when left out, and the agreement is the current
754
+ * version. The result is decoded as a new agreement, so everything that cannot
755
+ * be accepted, an unknown field included, is refused by name. */
756
+ export function workflowPlanInput(v: unknown): WorkflowPlan {
757
+ if (v === null || typeof v !== "object" || Array.isArray(v))
758
+ return issue("plan", "must be an object");
759
+ const completed = (
760
+ source: object,
761
+ defaults: Record<string, unknown>,
762
+ ): Record<string, unknown> => {
763
+ const result: Record<string, unknown> = { ...defaults };
764
+ // A model sends null for a field it means to leave out.
765
+ for (const [key, value] of Object.entries(source))
766
+ if (value !== null && value !== undefined) result[key] = value;
767
+ return result;
768
+ };
769
+ const plan = completed(v, {
770
+ version: 3,
771
+ decisions: "",
772
+ assumptions: "",
773
+ documents: [],
774
+ reviewReads: [],
775
+ policy: {},
776
+ setup: [],
777
+ baselineChecks: [],
778
+ });
779
+ if (plan.policy && typeof plan.policy === "object")
780
+ plan.policy = completed(plan.policy, { installs: false });
781
+ if (Array.isArray(plan.tasks))
782
+ plan.tasks = plan.tasks.map((task: unknown) =>
783
+ task && typeof task === "object" && !Array.isArray(task)
784
+ ? completed(task, { after: [], reads: [] })
785
+ : task,
786
+ );
787
+ return decodeWorkflowPlan(plan, { strict: true });
788
+ }
789
+ /** An investigation request as the coordinator gave it: questions trimmed,
790
+ * empty and repeated ones dropped, fields this contract does not know ignored.
791
+ * What is left is refused by name when it cannot be asked. */
792
+ export function researchInput(v: unknown): {
793
+ goal: string;
794
+ questions: string[];
795
+ roots?: string[];
796
+ } {
797
+ if (v === null || typeof v !== "object" || Array.isArray(v))
798
+ return issue("request", "must be an object with a goal and questions");
799
+ const given = (key: string): unknown =>
800
+ Object.getOwnPropertyDescriptor(v, key)?.value ?? undefined;
801
+ const distinct = (name: string, value: unknown, maximum: number) => [
802
+ ...new Set(
803
+ entries(
804
+ name,
805
+ typeof value === "string" ? [value] : value,
806
+ Number.MAX_SAFE_INTEGER,
807
+ (entry, path) => words(path, entry, maximum).trim(),
808
+ ).filter(Boolean),
809
+ ),
810
+ ];
811
+ const questions = distinct("questions", given("questions"), 8192);
812
+ if (!questions.length)
813
+ issue("questions", "needs at least one question that is not empty");
814
+ if (questions.length > WORKFLOW_LIMITS.questions)
815
+ issue(
816
+ "questions",
817
+ `has ${questions.length} questions; one investigation takes at most ${WORKFLOW_LIMITS.questions}, so ask the others in a further call`,
818
+ );
819
+ const roots =
820
+ given("roots") === undefined ? [] : distinct("roots", given("roots"), 4096);
821
+ if (roots.length > 8)
822
+ issue("roots", `has ${roots.length} directories; at most 8`);
823
+ return {
824
+ goal: words("goal", given("goal"), 8192, true),
825
+ questions,
826
+ ...(roots.length ? { roots } : {}),
827
+ };
828
+ }
555
829
  /** Existing project documents the agreement allows this delivery to update. */
556
830
  export function workflowDocuments(p: WorkflowPlan): string[] {
557
831
  return p.documents ?? p.knowledge ?? [];
@@ -584,35 +858,38 @@ export function workflowBoundary(path: string): boolean {
584
858
  function decodeWorkflowReadings(
585
859
  value: unknown,
586
860
  strict: boolean,
861
+ name: string,
587
862
  ): WorkflowReading[] {
588
- return list(value, 16, (entry): WorkflowReading => {
863
+ return entries(name, value, 16, (entry, path): WorkflowReading => {
589
864
  if (Object.hasOwn((entry ?? {}) as object, "research")) {
590
- const r = closed(entry, ["research", "reason"]);
865
+ const r = fields(path, entry, ["research", "reason"]);
866
+ // Either spelling of the record; the plan keeps its uuid.
867
+ const id =
868
+ typeof r.research === "string" ? investigationId(r.research) : null;
869
+ if (id === null)
870
+ issue(
871
+ `${path}.research`,
872
+ `${typeof r.research === "string" ? `${quoted(r.research)} ` : ""}is not an investigation; give the "investigation" value of a completed research step`,
873
+ );
591
874
  return {
592
- research: decodeId(r.research),
593
- reason: text(r.reason, 512, true),
875
+ research: id as string,
876
+ reason: words(`${path}.reason`, r.reason, WORKFLOW_LIMITS.reason, true),
594
877
  };
595
878
  }
596
- const r = closed(entry, [
597
- "path",
598
- ...(Object.hasOwn((entry ?? {}) as object, "section") ? ["section"] : []),
599
- "reason",
600
- ]);
879
+ const r = fields(path, entry, ["path", "reason"], ["section"]);
601
880
  return {
602
- path: workflowPath(r.path, strict),
881
+ path: at(`${path}.path`, () => workflowPath(r.path, strict)),
603
882
  ...(r.section === undefined
604
883
  ? {}
605
- : { section: text(r.section, 256, true) }),
606
- reason: text(r.reason, 512, true),
884
+ : { section: words(`${path}.section`, r.section, 256, true) }),
885
+ reason: words(`${path}.reason`, r.reason, WORKFLOW_LIMITS.reason, true),
607
886
  };
608
887
  });
609
888
  }
889
+ const agreementText = (p: WorkflowPlan) =>
890
+ `# ${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
891
  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
- );
892
+ return text(agreementText(p), WORKFLOW_LIMITS.context, true);
616
893
  }
617
894
  export function gitOid(value: unknown): string {
618
895
  const oid = text(value, 64, true);
@@ -205,6 +205,7 @@ var LIMITS = Object.freeze({
205
205
  predecessorBytes: 16 * 1024,
206
206
  handoffBytes: 32 * 1024,
207
207
  frameBytes: 64 * 1024,
208
+ coordinatorBytes: 384 * 1024,
208
209
  chunkBytes: 8 * 1024,
209
210
  detailBytes: 32 * 1024 * 1024,
210
211
  dataFrames: 1e5,
@@ -885,14 +886,22 @@ function sourceId(v) {
885
886
  invalid();
886
887
  return s;
887
888
  }
889
+ var MODEL_FAILURE_BYTES = 256;
888
890
  function decodeModelRetry(v) {
889
- const o = closed(v, ["phase", "attempt", "maxAttempts", "delayMs"]);
891
+ const o = closed(v, [
892
+ "phase",
893
+ "attempt",
894
+ "maxAttempts",
895
+ "delayMs",
896
+ ...Object.hasOwn(v ?? {}, "reason") ? ["reason"] : []
897
+ ]);
890
898
  const maxAttempts = integer(o.maxAttempts, 1);
891
899
  const progress = {
892
900
  phase: oneOf(o.phase, ["waiting", "requesting"]),
893
901
  attempt: integer(o.attempt, 1, maxAttempts),
894
902
  maxAttempts,
895
- delayMs: integer(o.delayMs, 0, 2147483647)
903
+ delayMs: integer(o.delayMs, 0, 2147483647),
904
+ ...o.reason === undefined ? {} : { reason: text(o.reason, MODEL_FAILURE_BYTES, true) }
896
905
  };
897
906
  if (progress.phase === "requesting" && progress.delayMs !== 0)
898
907
  throw new ContractError("invalid");