@nathanstephenson/flow 0.1.10-beta.1 → 0.1.10-beta.2

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 (46) hide show
  1. package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-LO7O6NAM.mjs} +9 -7
  2. package/build/backend-worker-chunks/{claude-UXZDJKZQ.mjs → claude-COCNALN2.mjs} +36 -6
  3. package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-HJKTV2TH.mjs} +35 -3
  4. package/build/backend-worker.mjs +7 -3
  5. package/dist/backend/claude/index.js +35 -5
  6. package/dist/backend/fake/index.js +16 -1
  7. package/dist/backend/pi/index.js +33 -2
  8. package/dist/backend/pi/state.js +16 -1
  9. package/dist/backend/worker/claude-state.js +22 -0
  10. package/dist/backend/worker/entry.js +6 -1
  11. package/dist/backend/worker/index.js +9 -3
  12. package/dist/backend/worker/protocol.js +1 -1
  13. package/dist/backend/workflow-tools.js +9 -7
  14. package/dist/build-id +1 -1
  15. package/dist/cli/bootstrap.js +1 -1
  16. package/dist/client/reduce.js +20 -0
  17. package/dist/daemon/host.js +138 -5
  18. package/dist/daemon/runtime.js +8 -0
  19. package/dist/daemon/workflow-builder-guidance.js +1 -1
  20. package/dist/daemon/workflow-builder.js +36 -11
  21. package/dist/daemon/workflow-execution-routes.js +9 -6
  22. package/dist/daemon/workflow-executions.js +179 -84
  23. package/dist/daemon/workflow-routes.js +39 -0
  24. package/dist/protocol/events.js +2 -0
  25. package/dist/workflows/calls.js +50 -0
  26. package/dist/workflows/graph.js +78 -4
  27. package/dist/workflows/invocations.js +20 -0
  28. package/dist/workflows/records.js +118 -8
  29. package/dist/workflows/recovery.js +37 -1
  30. package/dist/workflows/scheduler.js +326 -78
  31. package/dist/workflows/schema.js +2 -0
  32. package/package.json +1 -1
  33. package/web/dist/assets/index-CLdr6AA0.js +40 -0
  34. package/web/dist/assets/index-DHAcGIoF.css +2 -0
  35. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-sebWClE0.js} +1 -1
  36. package/web/dist/assets/settings-workflows-BvArjkes.js +23 -0
  37. package/web/dist/assets/workflow-editors-Tztq_Opa.js +139 -0
  38. package/web/dist/assets/workflows-CdDynCfW.js +7 -0
  39. package/web/dist/assets/workflows-pane-DaqHEeXu.js +1 -0
  40. package/web/dist/index.html +3 -3
  41. package/web/dist/assets/index-DRfeO6GJ.js +0 -40
  42. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  43. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  44. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  45. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  46. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
@@ -4,7 +4,7 @@ import { z } from 'zod';
4
4
  import { validSecretName } from "../protocol/secrets.js";
5
5
  import { Decisions } from "./decisions.js";
6
6
  import { analyzeLoops } from "./loops.js";
7
- import { dictionaryKey, dictionaryRecord, declaredOutputSchema, partialSchema, schemaAssignable, schemaAt, unionSchema, validateSchema, valueAt, visualSchemaValidator } from "./schema.js";
7
+ import { dictionaryKey, dictionaryRecord, declaredOutputSchema, parseValue, partialSchema, schemaAssignable, schemaAt, unionSchema, validateSchema, valueAt, visualSchemaValidator } from "./schema.js";
8
8
  const reference = z.discriminatedUnion('source', [
9
9
  z.object({ source: z.literal('input'), path: z.array(z.string()) }).strict(),
10
10
  z.object({ source: z.literal('step'), stepId: z.string(), path: z.array(z.string()) }).strict(),
@@ -37,12 +37,19 @@ export const workflowDefinitionValidator = z.object({
37
37
  z.object({ ...base, kind: z.literal('typescript'), code: z.string(), outputSchema: visualSchemaValidator }).strict(),
38
38
  z.object({ ...base, kind: z.literal('branch'), condition }).strict(),
39
39
  z.object({ ...base, kind: z.literal('join') }).strict(),
40
+ z.object({ ...base, kind: z.literal('workflow'), workflowId: z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/), contract: z.object({ inputSchema: visualSchemaValidator.refine(schema => schema.type === 'object'), outputSchema: visualSchemaValidator }).strict() }).strict(),
40
41
  z.object({ ...base, kind: z.literal('mcp'), tool: z.object({ connectionId: z.string().min(1), connectionName: z.string(), identity: z.string().regex(/^[a-f0-9]{64}$/), serverIdentity: z.string().regex(/^[a-f0-9]{64}$/), toolName: z.string().min(1), inputSchema: originalSchema, outputSchema: originalSchema.optional() }).strict() }).strict(),
41
42
  ])).min(1),
42
43
  loopSettings: dictionaryRecord(z.object({ maxTries: z.number().int().min(1).max(100) }).strict()).optional(),
43
44
  edges: z.array(z.object({ id: z.string().min(1), from: z.string(), to: z.string(), outcome: z.enum(['success', 'failure', 'timeout', 'true', 'false']) }).strict()),
44
45
  }).strict();
45
46
  export function validateDefinition(value) {
47
+ return buildGraph(value);
48
+ }
49
+ export function mappingSourceGraph(value) {
50
+ return buildGraph(value, true);
51
+ }
52
+ function buildGraph(value, mappingSources = false) {
46
53
  const definition = workflowDefinitionValidator.parse(value);
47
54
  const skillStep = definition.steps.find(step => step.kind === 'agent' && leadingSkillInvocation(step.instructions));
48
55
  if (skillStep && !definition.projectId) {
@@ -167,7 +174,31 @@ export function validateDefinition(value) {
167
174
  node.items.forEach(inspect);
168
175
  };
169
176
  inspect(mapping.template);
170
- input = { type: 'json' };
177
+ const infer = (node) => {
178
+ if (node.kind === 'reference')
179
+ return referenceSchema(node.reference).schema;
180
+ if (node.kind === 'object')
181
+ return { type: 'object', fields: Object.fromEntries(Object.entries(node.fields).map(([key, value]) => [key, { schema: infer(value), required: true }])) };
182
+ if (node.kind === 'array')
183
+ return { type: 'array', items: node.items.length ? unionSchema(node.items.map(infer)) : { type: 'json' } };
184
+ const literal = (value) => {
185
+ if (value === null)
186
+ return { type: 'null' };
187
+ if (typeof value === 'string')
188
+ return { type: 'enum', values: [value] };
189
+ if (typeof value === 'number')
190
+ return { type: 'number', integer: Number.isInteger(value) };
191
+ if (typeof value === 'boolean')
192
+ return { type: 'boolean' };
193
+ if (Array.isArray(value))
194
+ return { type: 'array', items: value.length ? unionSchema(value.map(literal)) : { type: 'json' } };
195
+ return { type: 'object', fields: Object.fromEntries(Object.entries(value).map(([key, value]) => [key, { schema: literal(value), required: true }])) };
196
+ };
197
+ return literal(node.value);
198
+ };
199
+ input = step.kind === 'workflow' ? infer(mapping.template) : { type: 'json' };
200
+ if (step.kind === 'workflow' && !mappingSources && mapping.template.kind === 'literal')
201
+ parseValue(step.contract.inputSchema, mapping.template.value);
171
202
  }
172
203
  else if (mapping?.kind === 'reference') {
173
204
  const field = referenceSchema(mapping.reference);
@@ -198,9 +229,16 @@ export function validateDefinition(value) {
198
229
  }
199
230
  if (step.inputSchema) {
200
231
  validateSchema(step.inputSchema);
201
- if (!schemaAssignable(input, step.inputSchema))
232
+ if (!(mappingSources && step.kind === 'workflow') && !schemaAssignable(input, step.inputSchema))
202
233
  throw new Error('Input does not match the declared input schema');
203
234
  }
235
+ if (step.kind === 'workflow') {
236
+ validateSchema(step.contract.inputSchema);
237
+ validateSchema(step.contract.outputSchema);
238
+ if (!mappingSources && (!schemaAssignable(input, step.contract.inputSchema) || (step.inputSchema && !schemaAssignable(step.inputSchema, step.contract.inputSchema))))
239
+ throw new Error('Input does not match the Workflow call input contract');
240
+ return step.contract.inputSchema;
241
+ }
204
242
  return step.inputSchema ?? input;
205
243
  };
206
244
  const inputFor = (id) => {
@@ -235,7 +273,43 @@ export function validateDefinition(value) {
235
273
  }
236
274
  outputFor(step.id);
237
275
  }
238
- return graph;
276
+ const terminalConditions = order.map(step => decisions.and(completed.get(step.id), decisions.not(any(outgoing.get(step.id).map(edge => selectedEdges.get(edge.id))))));
277
+ let finished = 1;
278
+ for (const step of order) {
279
+ const handled = any(outgoing.get(step.id).filter(edge => edge.outcome === 'failure' || edge.outcome === 'timeout').map(edge => selectedEdges.get(edge.id)));
280
+ finished = decisions.and(finished, decisions.or(decisions.not(reaches.get(step.id)), decisions.or(completed.get(step.id), handled)));
281
+ if (loops.length)
282
+ finished = decisions.and(finished, decisions.not(any(outgoing.get(step.id).filter(edge => backIds.has(edge.id)).map(edge => selectedEdges.get(edge.id)))));
283
+ }
284
+ const candidates = order.map((step, index) => ({ step, condition: terminalConditions[index] })).filter(({ condition }) => decisions.and(finished, condition) !== 0);
285
+ const variants = [];
286
+ let none = 1;
287
+ let one = 0;
288
+ let many = 0;
289
+ for (const { condition } of candidates) {
290
+ many = decisions.or(many, decisions.and(one, condition));
291
+ one = decisions.or(decisions.and(one, decisions.not(condition)), decisions.and(none, condition));
292
+ none = decisions.and(none, decisions.not(condition));
293
+ }
294
+ if (loops.length || definition.edges.some(edge => edge.outcome === 'failure' || edge.outcome === 'timeout')) {
295
+ const possible = order.filter(step => step.kind === 'branch'
296
+ ? ['true', 'false'].some(outcome => !outgoing.get(step.id).some(edge => edge.outcome === outcome))
297
+ : !outgoing.get(step.id).some(edge => edge.outcome === 'success'));
298
+ variants.push(...possible.map(step => outputFor(step.id)));
299
+ if (possible.length > 1)
300
+ variants.push({ type: 'object', fields: Object.fromEntries(possible.map(step => [step.name, { schema: outputFor(step.id) }])) });
301
+ }
302
+ else {
303
+ for (const { step, condition } of candidates)
304
+ if (decisions.and(finished, decisions.and(one, condition)) !== 0)
305
+ variants.push(outputFor(step.id));
306
+ const multiple = decisions.and(finished, many);
307
+ if (multiple !== 0)
308
+ variants.push({ type: 'object', fields: Object.fromEntries(candidates.filter(({ condition }) => decisions.and(multiple, condition) !== 0).map(({ step, condition }) => [step.name, { schema: outputFor(step.id), required: decisions.implies(multiple, condition) }])) });
309
+ if (decisions.and(finished, none) !== 0)
310
+ variants.push({ type: 'object', fields: {} });
311
+ }
312
+ return { ...graph, resultSchema: variants.length ? unionSchema(variants) : { type: 'json' } };
239
313
  }
240
314
  export function recoverySchema(input, output) {
241
315
  return { type: 'object', fields: {
@@ -0,0 +1,20 @@
1
+ export function invocationExecution(root, invocationId) {
2
+ const invocation = root.invocations?.[invocationId];
3
+ if (!invocation)
4
+ throw new Error('Unknown workflow invocation');
5
+ const retained = root.retainedDefinitions?.[invocation.definitionId];
6
+ if (!retained)
7
+ throw new Error('Missing retained Workflow Definition');
8
+ const definition = structuredClone(retained);
9
+ for (const correction of invocation.definitionUpdates ?? []) {
10
+ const index = definition.steps.findIndex(step => step.id === correction.stepId);
11
+ if (index < 0)
12
+ throw new Error('Invalid invocation correction');
13
+ definition.steps[index] = structuredClone(correction.nextStep);
14
+ }
15
+ return { ...structuredClone(invocation), version: 1, sessionId: root.sessionId, scope: root.scope, definition };
16
+ }
17
+ export function invocationCheckpoint(record, ownership) {
18
+ const { version: _, sessionId: __, scope: ___, definition: ____, ...state } = record;
19
+ return { ...state, ...ownership };
20
+ }
@@ -1,6 +1,8 @@
1
1
  import { boundedMcpValue, validateMcpOutput } from "./mcp.js";
2
2
  import { z } from 'zod';
3
3
  import { isDeepStrictEqual } from 'node:util';
4
+ import { resolveWorkflowCalls } from "./calls.js";
5
+ import { dictionaryRecord } from "./schema.js";
4
6
  import { validateDefinition, workflowDefinitionValidator } from "./graph.js";
5
7
  import { validateCompatibleDefinition } from "./recovery.js";
6
8
  const errorValidator = z.object({ message: z.string(), kind: z.enum(['failure', 'timeout', 'interrupted']) }).strict();
@@ -12,25 +14,33 @@ const loopValidator = z.object({
12
14
  }).strict();
13
15
  const attemptValidator = z.object({
14
16
  loops: z.array(identityValidator).optional(),
15
- number: z.number().int().positive(), action: z.enum(['execute', 'retry', 'supply']), startedAt: z.number().nonnegative(), finishedAt: z.number().nonnegative().optional(),
17
+ number: z.number().int().positive(), action: z.enum(['execute', 'retry', 'supply']), startedAt: z.number().nonnegative(), deadlineAt: z.number().nonnegative().optional(), finishedAt: z.number().nonnegative().optional(),
16
18
  input: z.json(), output: z.json().optional(), partialOutput: z.json().optional(), error: errorValidator.optional(),
17
19
  }).strict();
18
- export const workflowExecutionValidator = z.object({
19
- version: z.literal(1), id: z.string().min(1), sessionId: z.string().min(1), scope: z.string(), definition: workflowDefinitionValidator,
20
+ const checkpointFields = {
20
21
  definitionUpdates: z.array(z.object({
21
22
  stepId: z.string().min(1), previousStep: workflowDefinitionValidator.shape.steps.element, nextStep: workflowDefinitionValidator.shape.steps.element,
22
23
  appliedAt: z.number().nonnegative(), attempt: z.number().int().min(2),
23
24
  }).strict()).optional(),
24
- input: z.json(), launchId: z.string().min(1).optional(), naming: z.enum(['pending', 'requested']).optional(), testStepId: z.string().optional(), status: z.enum(['running', 'recovery-required', 'completed', 'completed-with-recovery', 'cancelled']),
25
+ input: z.json(), status: z.enum(['running', 'recovery-required', 'completed', 'completed-with-recovery', 'cancelled']),
25
26
  startedAt: z.number().nonnegative(), finishedAt: z.number().nonnegative().optional(), result: z.json().optional(),
26
- loops: z.record(z.string(), loopValidator).optional(),
27
- steps: z.record(z.string(), z.object({
27
+ loops: dictionaryRecord(loopValidator).optional(),
28
+ steps: dictionaryRecord(z.object({
28
29
  status: z.enum(['pending', 'running', 'completed', 'failed', 'timed-out', 'interrupted', 'skipped', 'blocked', 'cancelled']), recovery: z.boolean().optional(),
29
30
  attempts: z.array(attemptValidator), output: z.json().optional(), outcome: z.enum(['success', 'failure', 'timeout', 'true', 'false']).optional(),
30
31
  }).strict()),
32
+ };
33
+ const invocationValidator = z.object({
34
+ ...checkpointFields, id: z.string().min(1), parentInvocationId: z.string().min(1).optional(),
35
+ callStepId: z.string().min(1), callAttempt: z.number().int().positive(), definitionId: z.string().min(1),
31
36
  }).strict();
32
- export function parseExecution(value) {
33
- const record = workflowExecutionValidator.parse(value);
37
+ export const workflowExecutionValidator = z.object({
38
+ ...checkpointFields, version: z.literal(1), id: z.string().min(1), sessionId: z.string().min(1), scope: z.string(), definition: workflowDefinitionValidator,
39
+ retainedDefinitions: z.preprocess(value => value && typeof value === 'object' && !Array.isArray(value) ? new Map(Object.entries(value)) : value, z.map(workflowDefinitionValidator.shape.id, workflowDefinitionValidator)).transform(entries => Object.fromEntries(entries)).optional(),
40
+ invocations: dictionaryRecord(invocationValidator).optional(),
41
+ launchId: z.string().min(1).optional(), naming: z.enum(['pending', 'requested']).optional(), testStepId: z.string().optional(),
42
+ }).strict();
43
+ function validateCheckpoint(record) {
34
44
  const graph = validateDefinition(record.definition);
35
45
  if (graph.order.length !== Object.keys(record.steps).length || graph.order.some(step => !Object.hasOwn(record.steps, step.id)))
36
46
  throw new Error('Execution steps do not match the definition');
@@ -53,6 +63,7 @@ export function parseExecution(value) {
53
63
  validateCompatibleDefinition(previous, definition, update.stepId);
54
64
  definition = previous;
55
65
  }
66
+ const original = definition;
56
67
  if (record.testStepId && !Object.hasOwn(record.steps, record.testStepId))
57
68
  throw new Error('Unknown test step');
58
69
  if (record.testStepId && record.naming)
@@ -100,6 +111,11 @@ export function parseExecution(value) {
100
111
  }
101
112
  const containing = loops.filter(loop => loop.memberIds.includes(id));
102
113
  for (const [index, attempt] of step.attempts.entries()) {
114
+ if (attempt.deadlineAt !== undefined) {
115
+ const configuration = stepConfiguration(record, original, id, attempt.number);
116
+ if (configuration?.kind !== 'workflow' || configuration.timeoutMs === undefined || attempt.deadlineAt !== attempt.startedAt + configuration.timeoutMs)
117
+ throw new Error('Invalid call attempt deadline');
118
+ }
103
119
  if ((attempt.loops ?? []).length !== containing.length || containing.some(loop => !attempt.loops?.some(identity => identity.headerId === loop.headerId)))
104
120
  throw new Error('Invalid attempt loop identities');
105
121
  if (containing.length && index === 0 && attempt.action !== 'execute')
@@ -133,5 +149,99 @@ export function parseExecution(value) {
133
149
  }
134
150
  if (['completed', 'completed-with-recovery'].includes(record.status) && Object.values(record.steps).some(step => ['pending', 'running', 'interrupted', 'blocked'].includes(step.status)))
135
151
  throw new Error('Completed execution contains unfinished work');
152
+ return original;
153
+ }
154
+ function stepConfiguration(record, original, stepId, attempt) {
155
+ let step = original.steps.find(step => step.id === stepId);
156
+ for (const update of record.definitionUpdates ?? [])
157
+ if (update.stepId === stepId && update.attempt <= attempt)
158
+ step = update.nextStep;
159
+ return step;
160
+ }
161
+ export function parseExecution(value) {
162
+ const record = workflowExecutionValidator.parse(value);
163
+ const original = validateCheckpoint(record);
164
+ const manifest = record.retainedDefinitions;
165
+ if (!manifest) {
166
+ if (record.invocations || record.definition.steps.some(step => step.kind === 'workflow'))
167
+ throw new Error('Missing retained Workflow Definitions');
168
+ return record;
169
+ }
170
+ for (const [id, definition] of Object.entries(manifest))
171
+ if (id !== definition.id)
172
+ throw new Error('Invalid retained definition identity');
173
+ if (!isDeepStrictEqual(manifest[original.id], original))
174
+ throw new Error('Retained root definition does not match the original checkpoint');
175
+ const resolved = resolveWorkflowCalls(original, id => {
176
+ if (!Object.hasOwn(manifest, id))
177
+ throw new Error('Missing retained definition');
178
+ return manifest[id];
179
+ }, record.testStepId);
180
+ if (!isDeepStrictEqual(resolved, manifest))
181
+ throw new Error('Retained definitions do not match the call manifest');
182
+ const locals = new Map();
183
+ const originals = new Map();
184
+ for (const [id, invocation] of Object.entries(record.invocations ?? {})) {
185
+ if (id !== invocation.id || id === record.id)
186
+ throw new Error('Invalid invocation identity');
187
+ const retained = manifest[invocation.definitionId];
188
+ if (!retained)
189
+ throw new Error('Missing invocation definition');
190
+ const definition = structuredClone(retained);
191
+ for (const update of invocation.definitionUpdates ?? []) {
192
+ const index = definition.steps.findIndex(step => step.id === update.stepId);
193
+ if (index < 0)
194
+ throw new Error('Unknown invocation correction step');
195
+ definition.steps[index] = structuredClone(update.nextStep);
196
+ }
197
+ const local = { ...invocation, version: 1, sessionId: record.sessionId, scope: record.scope, definition };
198
+ if (!isDeepStrictEqual(validateCheckpoint(local), retained))
199
+ throw new Error('Invocation corrections do not match the retained definition');
200
+ locals.set(id, local);
201
+ originals.set(id, retained);
202
+ }
203
+ const checked = new Set();
204
+ for (const id of locals.keys()) {
205
+ const path = new Set();
206
+ let current = id;
207
+ while (current !== undefined && !checked.has(current)) {
208
+ if (path.has(current))
209
+ throw new Error('Invocation parent cycle');
210
+ path.add(current);
211
+ const invocation = record.invocations[current];
212
+ if (!invocation)
213
+ throw new Error('Missing parent invocation');
214
+ current = invocation.parentInvocationId;
215
+ }
216
+ for (const ancestor of path)
217
+ checked.add(ancestor);
218
+ }
219
+ const owners = new Set();
220
+ for (const [id, invocation] of Object.entries(record.invocations ?? {})) {
221
+ const parentId = invocation.parentInvocationId;
222
+ const parent = parentId === undefined ? record : locals.get(parentId);
223
+ const parentOriginal = parentId === undefined ? original : originals.get(parentId);
224
+ const step = stepConfiguration(parent, parentOriginal, invocation.callStepId, invocation.callAttempt);
225
+ const state = parent.steps[invocation.callStepId];
226
+ const attempt = state?.attempts[invocation.callAttempt - 1];
227
+ if (step?.kind !== 'workflow' || step.workflowId !== invocation.definitionId || !attempt || attempt.action === 'supply' || (parent.testStepId !== undefined && parent.testStepId !== step.id))
228
+ throw new Error('Invalid invocation call ownership');
229
+ if (!isDeepStrictEqual(invocation.input, attempt.input))
230
+ throw new Error('Invocation input does not match the call attempt');
231
+ if (step.timeoutMs !== undefined && attempt.deadlineAt === undefined)
232
+ throw new Error('Missing call attempt deadline');
233
+ if (invocation.callAttempt < state.attempts.length && ['running', 'recovery-required'].includes(invocation.status))
234
+ throw new Error('Unfinished invocation belongs to an earlier call attempt');
235
+ const owner = JSON.stringify([parentId ?? null, invocation.callStepId, invocation.callAttempt]);
236
+ if (owners.has(owner))
237
+ throw new Error('Duplicate invocation call ownership');
238
+ owners.add(owner);
239
+ if (['completed', 'completed-with-recovery'].includes(invocation.status) && invocation.result === undefined)
240
+ throw new Error('Missing completed invocation result');
241
+ if (['completed', 'completed-with-recovery'].includes(record.status) && ['running', 'recovery-required'].includes(invocation.status))
242
+ throw new Error('Completed execution contains unfinished invocations');
243
+ if (!locals.has(id))
244
+ throw new Error('Missing invocation checkpoint');
245
+ }
136
246
  return record;
137
247
  }
@@ -1,6 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { isDeepStrictEqual } from 'node:util';
3
3
  import { validateDefinition } from "./graph.js";
4
+ import { invocationExecution } from "./invocations.js";
4
5
  // Object key order is not part of a saved definition's identity; array order is.
5
6
  function canonical(value) {
6
7
  if (Array.isArray(value))
@@ -48,17 +49,52 @@ export function validateCompatibleDefinition(previous, candidate, stepId) {
48
49
  }
49
50
  return graph;
50
51
  }
52
+ export function recoverySteps(root, action, replacement) {
53
+ const steps = [];
54
+ let invocationId = action.invocationId, selected = true;
55
+ for (;;) {
56
+ const current = invocationId === undefined ? root : invocationExecution(root, invocationId);
57
+ const graph = validateDefinition(selected && replacement ? replacement : current.definition);
58
+ const repeating = new Set(current.testStepId ? [] : graph.loops.filter(loop => ['active', 'repeating', 'limit'].includes(current.loops?.[loop.headerId]?.phase ?? 'inactive')).flatMap(loop => loop.memberIds));
59
+ const owned = new Set(Object.values(root.invocations ?? {}).filter(invocation => {
60
+ const call = current.steps[invocation.callStepId];
61
+ return invocation.parentInvocationId === invocationId && call?.status === 'running' && invocation.callAttempt === call.attempts.length;
62
+ }).map(invocation => invocation.callStepId));
63
+ for (const step of graph.order) {
64
+ if (current.testStepId && current.testStepId !== step.id)
65
+ continue;
66
+ if (!repeating.has(step.id)) {
67
+ const state = current.steps[step.id];
68
+ if (!current.testStepId && ['failed', 'timed-out'].includes(state.status) && !state.recovery && graph.outgoing.get(step.id).some(edge => edge.outcome === state.outcome))
69
+ continue;
70
+ if (state.status === 'completed' || owned.has(step.id))
71
+ continue;
72
+ if (selected && action.kind === 'supply' && action.stepId === step.id)
73
+ continue;
74
+ }
75
+ steps.push(step);
76
+ }
77
+ if (invocationId === undefined)
78
+ return steps;
79
+ invocationId = root.invocations[invocationId].parentInvocationId;
80
+ selected = false;
81
+ }
82
+ }
51
83
  /** State identity, not wall-clock time: repeated notifications cannot mint new authority. */
52
84
  export function recoveryRevision(record) {
53
85
  return createHash('sha256').update(JSON.stringify({ id: record.id, status: record.status,
54
86
  steps: Object.entries(record.steps).map(([id, step]) => [id, step.status, step.attempts.map(a => [a.number, a.action, a.finishedAt, a.error])]),
55
87
  loops: record.loops, definition: savedDefinitionRevision(record.definition), definitionUpdates: record.definitionUpdates,
88
+ invocations: record.invocations, retainedDefinitions: record.retainedDefinitions,
56
89
  })).digest('hex');
57
90
  }
58
91
  export function successfulProgress(record) {
59
- return Object.values(record.steps).reduce((count, step) => count + step.attempts.filter(a => a.finishedAt !== undefined && a.output !== undefined && !a.error && a.action !== 'supply').length, 0);
92
+ const local = (execution) => Object.entries(execution.steps).reduce((count, [id, step]) => count + (execution.definition.steps.find(step => step.id === id)?.kind === 'workflow' ? 0 : step.attempts.filter(a => a.finishedAt !== undefined && a.output !== undefined && !a.error && a.action !== 'supply').length), 0);
93
+ return local(record) + Object.keys(record.invocations ?? {}).reduce((count, id) => count + local(invocationExecution(record, id)), 0);
60
94
  }
61
95
  export function safeAutomaticRecovery(record, action) {
96
+ if (action.invocationId)
97
+ record = invocationExecution(record, action.invocationId);
62
98
  if (record.status !== 'recovery-required' || Object.values(record.loops ?? {}).some(loop => loop.phase === 'limit'))
63
99
  return false;
64
100
  if (action.kind === 'retry') {