@nones/agentflow-strategy-workflow 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,648 @@
1
+ import { readFileSync } from "node:fs";
2
+ import type { ArtifactDeclaration } from "@nones/agentflow-core";
3
+ import {
4
+ assertJsonValue,
5
+ assertOnlyKeys,
6
+ expectId,
7
+ expectRecord,
8
+ expectString,
9
+ fail,
10
+ isRecord,
11
+ normalizeArtifacts,
12
+ } from "./internal";
13
+ import type { WorkflowExpansion } from "./expansion";
14
+ import { expandWorkflow, sha256Digest } from "./expansion";
15
+
16
+ /**
17
+ * Typed, reusable workflow template registry and plan preview.
18
+ *
19
+ * Templates are plain JSON data. The registry never imports, evaluates or
20
+ * re-reads executable configuration, never starts agents and never touches
21
+ * shared run state. Parameters are validated against a declared JSON Schema
22
+ * subset before a template is expanded.
23
+ */
24
+ export const WORKFLOW_TEMPLATE_VERSION = 1;
25
+
26
+ export interface WorkflowTemplate {
27
+ name: string;
28
+ title?: string;
29
+ description?: string;
30
+ /** Bumped by the template author whenever parameters or phases change. */
31
+ revision: number;
32
+ /** Declared parameter schema; `properties` are object-typed values. */
33
+ parameters?: Record<string, unknown>;
34
+ /** Phase/round document accepted by `expandWorkflow`. */
35
+ phases: unknown[];
36
+ profile?: string;
37
+ artifacts?: ArtifactDeclaration[];
38
+ sealed?: boolean;
39
+ /** Where the template was discovered. */
40
+ source: "project" | "global" | "inline";
41
+ }
42
+
43
+ export interface ParsedWorkflowTemplate {
44
+ template: WorkflowTemplate;
45
+ /** SHA-256 over the normalized template, including its source. */
46
+ digest: string;
47
+ }
48
+
49
+ export interface WorkflowTemplatePreview {
50
+ name: string;
51
+ title?: string;
52
+ description?: string;
53
+ revision: number;
54
+ templateDigest: string;
55
+ /** Digest of the expanded plan, used to scope approval. */
56
+ planDigest: string;
57
+ source: WorkflowTemplate["source"];
58
+ profile?: string;
59
+ sealed: boolean;
60
+ /** Validated parameters after applying schema defaults. */
61
+ parameters: Record<string, unknown>;
62
+ phases: {
63
+ id: string;
64
+ rounds: {
65
+ id: string;
66
+ wave: string;
67
+ mode: string;
68
+ steps: { key: string; kind: string; handler?: string }[];
69
+ }[];
70
+ }[];
71
+ models: Record<string, string[]>;
72
+ profiles: string[];
73
+ artifacts: ArtifactDeclaration[];
74
+ /** Bundled with the preview for `agentflow workflow plan` output. */
75
+ expansion: WorkflowExpansion;
76
+ }
77
+
78
+ export class WorkflowTemplateError extends Error {
79
+ readonly code:
80
+ | "template_invalid"
81
+ | "template_not_found"
82
+ | "template_ambiguous"
83
+ | "template_input_invalid";
84
+
85
+ constructor(code: WorkflowTemplateError["code"], message: string) {
86
+ super(message);
87
+ this.name = "WorkflowTemplateError";
88
+ this.code = code;
89
+ }
90
+ }
91
+
92
+ const TEMPLATE_FIELDS = [
93
+ "name",
94
+ "title",
95
+ "description",
96
+ "revision",
97
+ "parameters",
98
+ "phases",
99
+ "profile",
100
+ "artifacts",
101
+ "sealed",
102
+ ] as const;
103
+
104
+ /**
105
+ * Validate and normalize one untrusted template document. Nothing here is
106
+ * executed: `phases` is kept as data and checked structurally.
107
+ */
108
+ export function parseWorkflowTemplate(
109
+ value: unknown,
110
+ source: WorkflowTemplate["source"] = "inline",
111
+ path = "workflow template",
112
+ ): ParsedWorkflowTemplate {
113
+ const record = expectRecord(value, path);
114
+ assertOnlyKeys(record, TEMPLATE_FIELDS, path);
115
+
116
+ const template: WorkflowTemplate = {
117
+ name: expectId(record.name, `${path}.name`),
118
+ revision:
119
+ record.revision === undefined
120
+ ? 1
121
+ : expectRevision(record.revision, `${path}.revision`),
122
+ phases: expectPhaseList(record.phases, `${path}.phases`),
123
+ source,
124
+ };
125
+
126
+ for (const field of ["title", "description"] as const) {
127
+ const text = record[field];
128
+ if (text !== undefined) {
129
+ template[field] = expectString(text, `${path}.${field}`);
130
+ }
131
+ }
132
+
133
+ if (record.parameters !== undefined) {
134
+ const parameters = expectRecord(record.parameters, `${path}.parameters`);
135
+ assertJsonValue(parameters, `${path}.parameters`);
136
+ template.parameters = JSON.parse(JSON.stringify(parameters)) as Record<
137
+ string,
138
+ unknown
139
+ >;
140
+ }
141
+
142
+ if (record.profile !== undefined) {
143
+ template.profile = expectString(record.profile, `${path}.profile`);
144
+ }
145
+ if (record.artifacts !== undefined) {
146
+ template.artifacts = normalizeArtifacts(
147
+ record.artifacts,
148
+ `${path}.artifacts`,
149
+ );
150
+ }
151
+ if (record.sealed !== undefined) {
152
+ if (typeof record.sealed !== "boolean") {
153
+ fail(`${path}.sealed`, "must be a boolean");
154
+ }
155
+ template.sealed = record.sealed;
156
+ }
157
+
158
+ return { template, digest: workflowTemplateDigest(template) };
159
+ }
160
+
161
+ function expectRevision(value: unknown, path: string): number {
162
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
163
+ fail(path, "must be a positive integer");
164
+ }
165
+ return value;
166
+ }
167
+
168
+ function expectPhaseList(value: unknown, path: string): unknown[] {
169
+ if (!Array.isArray(value)) {
170
+ return fail(path, "must be an array of phases");
171
+ }
172
+ assertJsonValue(value, path);
173
+ return JSON.parse(JSON.stringify(value)) as unknown[];
174
+ }
175
+
176
+ /** JSON Schema subset used for template parameters. */
177
+ export function validateTemplateParameters(
178
+ schema: Record<string, unknown> | undefined,
179
+ input: unknown,
180
+ ): Record<string, unknown> {
181
+ if (input === undefined) {
182
+ input = {};
183
+ }
184
+ const record = expectRecord(input, "workflow input");
185
+ assertJsonValue(record, "workflow input");
186
+
187
+ const properties: Record<string, unknown> = isRecord(schema?.properties)
188
+ ? schema.properties
189
+ : {};
190
+ const required = Array.isArray(schema?.required) ? schema.required : [];
191
+ const output: Record<string, unknown> = {};
192
+
193
+ for (const name of required) {
194
+ if (typeof name === "string" && !(name in record)) {
195
+ throw new WorkflowTemplateError(
196
+ "template_input_invalid",
197
+ `workflow input.${name}: is required`,
198
+ );
199
+ }
200
+ }
201
+ for (const [name, propertySchema] of Object.entries(properties)) {
202
+ if (name in record) {
203
+ output[name] = JSON.parse(JSON.stringify(record[name]));
204
+ } else if (
205
+ isRecord(propertySchema) &&
206
+ propertySchema.default !== undefined
207
+ ) {
208
+ output[name] = JSON.parse(JSON.stringify(propertySchema.default));
209
+ }
210
+ }
211
+ if (schema?.additionalProperties === false) {
212
+ for (const name of Object.keys(record)) {
213
+ if (!(name in properties)) {
214
+ throw new WorkflowTemplateError(
215
+ "template_input_invalid",
216
+ `workflow input.${name}: is not allowed`,
217
+ );
218
+ }
219
+ }
220
+ } else {
221
+ for (const [name, value] of Object.entries(record)) {
222
+ if (!(name in properties)) {
223
+ output[name] = JSON.parse(JSON.stringify(value));
224
+ }
225
+ }
226
+ }
227
+
228
+ if (schema !== undefined) {
229
+ const errors = checkParameters(output, schema, "workflow input");
230
+ if (errors.length > 0) {
231
+ throw new WorkflowTemplateError(
232
+ "template_input_invalid",
233
+ errors.join("; "),
234
+ );
235
+ }
236
+ }
237
+ return output;
238
+ }
239
+
240
+ /**
241
+ * A small, dependency-free structural check. It intentionally validates only
242
+ * the keywords the registry can guarantee without evaluating user code.
243
+ */
244
+ function checkParameters(
245
+ value: unknown,
246
+ schema: Record<string, unknown>,
247
+ path: string,
248
+ ): string[] {
249
+ const errors: string[] = [];
250
+ if (typeof schema.type === "string" || Array.isArray(schema.type)) {
251
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type];
252
+ if (!types.some((type) => matchesType(value, type))) {
253
+ errors.push(`${path}: expected ${types.join(" or ")}`);
254
+ return errors;
255
+ }
256
+ }
257
+ if (
258
+ "const" in schema &&
259
+ JSON.stringify(value) !== JSON.stringify(schema.const)
260
+ ) {
261
+ errors.push(`${path}: must equal the declared const`);
262
+ }
263
+ if (Array.isArray(schema.enum)) {
264
+ if (
265
+ !schema.enum.some(
266
+ (entry) => JSON.stringify(entry) === JSON.stringify(value),
267
+ )
268
+ ) {
269
+ errors.push(`${path}: must be one of the declared enum values`);
270
+ }
271
+ }
272
+ if (typeof value === "string") {
273
+ if (
274
+ typeof schema.minLength === "number" &&
275
+ value.length < schema.minLength
276
+ ) {
277
+ errors.push(`${path}: must have at least ${schema.minLength} characters`);
278
+ }
279
+ if (
280
+ typeof schema.maxLength === "number" &&
281
+ value.length > schema.maxLength
282
+ ) {
283
+ errors.push(`${path}: must have at most ${schema.maxLength} characters`);
284
+ }
285
+ if (typeof schema.pattern === "string") {
286
+ try {
287
+ if (!new RegExp(schema.pattern).test(value)) {
288
+ errors.push(`${path}: does not match pattern ${schema.pattern}`);
289
+ }
290
+ } catch {
291
+ errors.push(`${path}: schema has an invalid pattern`);
292
+ }
293
+ }
294
+ }
295
+ if (typeof value === "number") {
296
+ if (typeof schema.minimum === "number" && value < schema.minimum) {
297
+ errors.push(`${path}: must be >= ${schema.minimum}`);
298
+ }
299
+ if (typeof schema.maximum === "number" && value > schema.maximum) {
300
+ errors.push(`${path}: must be <= ${schema.maximum}`);
301
+ }
302
+ }
303
+ if (Array.isArray(value)) {
304
+ if (typeof schema.minItems === "number" && value.length < schema.minItems) {
305
+ errors.push(`${path}: must have at least ${schema.minItems} items`);
306
+ }
307
+ if (typeof schema.maxItems === "number" && value.length > schema.maxItems) {
308
+ errors.push(`${path}: must have at most ${schema.maxItems} items`);
309
+ }
310
+ if (schema.items !== undefined && isRecord(schema.items)) {
311
+ const items = schema.items;
312
+ value.forEach((entry, index) => {
313
+ errors.push(...checkParameters(entry, items, `${path}[${index}]`));
314
+ });
315
+ }
316
+ }
317
+ if (isRecord(value) && isRecord(schema.properties)) {
318
+ const properties = schema.properties;
319
+ for (const [name, propertySchema] of Object.entries(properties)) {
320
+ if (isRecord(propertySchema) && name in value) {
321
+ errors.push(
322
+ ...checkParameters(value[name], propertySchema, `${path}.${name}`),
323
+ );
324
+ }
325
+ }
326
+ }
327
+ return errors;
328
+ }
329
+
330
+ function matchesType(value: unknown, type: unknown): boolean {
331
+ switch (type) {
332
+ case "object":
333
+ return isRecord(value);
334
+ case "array":
335
+ return Array.isArray(value);
336
+ case "string":
337
+ return typeof value === "string";
338
+ case "number":
339
+ return typeof value === "number" && Number.isFinite(value);
340
+ case "integer":
341
+ return typeof value === "number" && Number.isInteger(value);
342
+ case "boolean":
343
+ return typeof value === "boolean";
344
+ case "null":
345
+ return value === null;
346
+ default:
347
+ return true;
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Parameter validation as seen from a plan preview: every failure, including
353
+ * the plain `TypeError` path errors, surfaces as a `WorkflowTemplateError`.
354
+ */
355
+ function validatePreviewParameters(
356
+ schema: Record<string, unknown> | undefined,
357
+ input: unknown,
358
+ ): Record<string, unknown> {
359
+ try {
360
+ return validateTemplateParameters(schema, input);
361
+ } catch (error) {
362
+ if (error instanceof WorkflowTemplateError) {
363
+ throw error;
364
+ }
365
+ throw new WorkflowTemplateError(
366
+ "template_invalid",
367
+ (error as Error).message,
368
+ );
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Deterministic `{{name}}` / `{{name.path}}` substitution using only validated
374
+ * parameters. There is no expression evaluation: an unknown placeholder or a
375
+ * non-scalar value is an error, so a template can never smuggle logic in.
376
+ */
377
+ export function interpolateTemplateParameters(
378
+ value: unknown,
379
+ parameters: Record<string, unknown>,
380
+ path = "template value",
381
+ ): unknown {
382
+ if (typeof value === "string") {
383
+ return interpolateString(value, parameters, path);
384
+ }
385
+ if (Array.isArray(value)) {
386
+ return value.map((entry, index) =>
387
+ interpolateTemplateParameters(entry, parameters, `${path}[${index}]`),
388
+ );
389
+ }
390
+ if (isRecord(value)) {
391
+ const output: Record<string, unknown> = {};
392
+ for (const [key, entry] of Object.entries(value)) {
393
+ output[key] = interpolateTemplateParameters(
394
+ entry,
395
+ parameters,
396
+ `${path}.${key}`,
397
+ );
398
+ }
399
+ return output;
400
+ }
401
+ return value;
402
+ }
403
+
404
+ const PLACEHOLDER =
405
+ /\{\{\s*([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)*)\s*\}\}/g;
406
+
407
+ function interpolateString(
408
+ text: string,
409
+ parameters: Record<string, unknown>,
410
+ path: string,
411
+ ): string {
412
+ return text.replace(PLACEHOLDER, (_match, reference: string) => {
413
+ const resolved = resolveReference(reference, parameters);
414
+ if (resolved === undefined) {
415
+ throw new WorkflowTemplateError(
416
+ "template_invalid",
417
+ `${path}: unknown parameter "${reference}"`,
418
+ );
419
+ }
420
+ if (
421
+ typeof resolved === "string" ||
422
+ typeof resolved === "number" ||
423
+ typeof resolved === "boolean"
424
+ ) {
425
+ return String(resolved);
426
+ }
427
+ throw new WorkflowTemplateError(
428
+ "template_invalid",
429
+ `${path}: parameter "${reference}" must be a string, number or boolean`,
430
+ );
431
+ });
432
+ }
433
+
434
+ function resolveReference(
435
+ reference: string,
436
+ parameters: Record<string, unknown>,
437
+ ): unknown {
438
+ let current: unknown = parameters;
439
+ for (const segment of reference.split(".")) {
440
+ if (!isRecord(current) || !(segment in current)) {
441
+ return undefined;
442
+ }
443
+ current = current[segment];
444
+ }
445
+ return current;
446
+ }
447
+
448
+ /**
449
+ * Expand one validated template with validated parameters. The returned
450
+ * preview is deterministic for equivalent inputs and never admits work.
451
+ */
452
+ export function previewWorkflowTemplate(
453
+ template: WorkflowTemplate,
454
+ input: unknown = {},
455
+ ): WorkflowTemplatePreview {
456
+ const parameters = validatePreviewParameters(template.parameters, input);
457
+
458
+ const phases = interpolateTemplateParameters(
459
+ template.phases,
460
+ parameters,
461
+ `template ${template.name}.phases`,
462
+ );
463
+
464
+ let expansion: WorkflowExpansion;
465
+ try {
466
+ expansion = expandWorkflow({
467
+ phases,
468
+ profile: template.profile,
469
+ artifacts: template.artifacts,
470
+ sealed: template.sealed,
471
+ });
472
+ } catch (error) {
473
+ throw new WorkflowTemplateError(
474
+ "template_invalid",
475
+ `template ${template.name} produced an invalid plan: ${(error as Error).message}`,
476
+ );
477
+ }
478
+
479
+ const templateDigest = workflowTemplateDigest(template);
480
+
481
+ const models: Record<string, string[]> = {};
482
+ const profiles = new Set<string>();
483
+ for (const wave of expansion.waves) {
484
+ for (const agent of wave.agents) {
485
+ const model = agent.model ?? "(default)";
486
+ models[model] ??= [];
487
+ if (!models[model].includes(agent.id)) models[model].push(agent.id);
488
+ if (agent.profile !== undefined) profiles.add(agent.profile);
489
+ }
490
+ }
491
+ if (template.profile !== undefined) profiles.add(template.profile);
492
+
493
+ return {
494
+ name: template.name,
495
+ ...(template.title === undefined ? {} : { title: template.title }),
496
+ ...(template.description === undefined
497
+ ? {}
498
+ : { description: template.description }),
499
+ revision: template.revision,
500
+ templateDigest,
501
+ planDigest: expansion.digest,
502
+ source: template.source,
503
+ ...(template.profile === undefined ? {} : { profile: template.profile }),
504
+ sealed: template.sealed === true,
505
+ parameters,
506
+ phases: expansion.phases.map((phase) => ({
507
+ id: phase.id,
508
+ rounds: phase.rounds.map((round) => ({
509
+ id: round.id,
510
+ wave: round.wave,
511
+ mode: round.mode,
512
+ steps: round.steps.map((step) => ({
513
+ key: step.key,
514
+ kind: step.kind,
515
+ ...(step.handler === undefined ? {} : { handler: step.handler }),
516
+ })),
517
+ })),
518
+ })),
519
+ models,
520
+ profiles: [...profiles].sort(),
521
+ artifacts: template.artifacts ?? [],
522
+ expansion,
523
+ };
524
+ }
525
+
526
+ export interface WorkflowTemplateRegistry {
527
+ /** Replace the registry contents with parsed project and global sources. */
528
+ add(template: ParsedWorkflowTemplate | WorkflowTemplate): void;
529
+ /**
530
+ * Resolve one template by name. Project templates override global ones;
531
+ * two definitions at the same tier fail as ambiguous.
532
+ */
533
+ get(name: string): ParsedWorkflowTemplate;
534
+ /** List every contained template without exposing duplicate resolution. */
535
+ list(): ParsedWorkflowTemplate[];
536
+ }
537
+
538
+ function isParsedTemplate(
539
+ value: ParsedWorkflowTemplate | WorkflowTemplate,
540
+ ): value is ParsedWorkflowTemplate {
541
+ return (
542
+ isRecord(value) &&
543
+ typeof value.digest === "string" &&
544
+ isRecord(value.template)
545
+ );
546
+ }
547
+
548
+ export function createWorkflowTemplateRegistry(
549
+ templates: (ParsedWorkflowTemplate | WorkflowTemplate)[] = [],
550
+ ): WorkflowTemplateRegistry {
551
+ let entries: ParsedWorkflowTemplate[] = [];
552
+
553
+ const add = (template: ParsedWorkflowTemplate | WorkflowTemplate): void => {
554
+ let parsed: ParsedWorkflowTemplate;
555
+ if (isParsedTemplate(template)) {
556
+ parsed = template;
557
+ } else {
558
+ const { source, ...rest } = template;
559
+ parsed = parseWorkflowTemplate(rest, source ?? "inline");
560
+ }
561
+ entries = [...entries, parsed].sort((left, right) =>
562
+ left.template.name.localeCompare(right.template.name),
563
+ );
564
+ };
565
+
566
+ for (const template of templates) {
567
+ add(template);
568
+ }
569
+
570
+ return {
571
+ add,
572
+ get(name) {
573
+ const matches = entries.filter((entry) => entry.template.name === name);
574
+ if (matches.length === 0) {
575
+ throw new WorkflowTemplateError(
576
+ "template_not_found",
577
+ `no workflow template named "${name}"`,
578
+ );
579
+ }
580
+ const projects = matches.filter(
581
+ (entry) => entry.template.source === "project",
582
+ );
583
+ if (projects.length > 1) {
584
+ throw new WorkflowTemplateError(
585
+ "template_ambiguous",
586
+ `template "${name}" is defined twice as a project template`,
587
+ );
588
+ }
589
+ const chosen = projects[0] ?? matches[0]!;
590
+ return chosen;
591
+ },
592
+ list() {
593
+ return entries.slice();
594
+ },
595
+ };
596
+ }
597
+
598
+ export function parseWorkflowTemplateJson(
599
+ text: string,
600
+ source: WorkflowTemplate["source"] = "inline",
601
+ path = "workflow template",
602
+ ): ParsedWorkflowTemplate {
603
+ let value: unknown;
604
+ try {
605
+ value = JSON.parse(text);
606
+ } catch {
607
+ fail(path, "must be valid JSON");
608
+ }
609
+ return parseWorkflowTemplate(value, source, path);
610
+ }
611
+
612
+ export function workflowTemplateDigest(template: WorkflowTemplate): string {
613
+ return sha256Digest({
614
+ name: template.name,
615
+ revision: template.revision,
616
+ parameters: template.parameters,
617
+ phases: template.phases,
618
+ profile: template.profile,
619
+ artifacts: template.artifacts,
620
+ sealed: template.sealed,
621
+ source: template.source,
622
+ });
623
+ }
624
+
625
+ /**
626
+ * Read a JSON template file as pure data. The file is never imported as a
627
+ * module, so no top-level source can run during discovery or planning.
628
+ */
629
+ export function readWorkflowTemplateFile(
630
+ path: string,
631
+ source: WorkflowTemplate["source"] = "project",
632
+ ): ParsedWorkflowTemplate {
633
+ try {
634
+ return parseWorkflowTemplateJson(
635
+ readFileSync(path, "utf8"),
636
+ source,
637
+ `workflow template ${path}`,
638
+ );
639
+ } catch (error) {
640
+ if (error instanceof WorkflowTemplateError) {
641
+ throw error;
642
+ }
643
+ throw new WorkflowTemplateError(
644
+ "template_not_found",
645
+ `cannot read workflow template ${path}`,
646
+ );
647
+ }
648
+ }