@exaudeus/workrail 1.4.0 → 1.5.1

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 (168) hide show
  1. package/dist/manifest.json +464 -200
  2. package/dist/mcp/handlers/v2-advance-core/event-builders.d.ts +37 -0
  3. package/dist/mcp/handlers/v2-advance-core/event-builders.js +114 -0
  4. package/dist/mcp/handlers/v2-advance-core/index.d.ts +67 -0
  5. package/dist/mcp/handlers/v2-advance-core/index.js +100 -0
  6. package/dist/mcp/handlers/v2-advance-core/input-validation.d.ts +44 -0
  7. package/dist/mcp/handlers/v2-advance-core/input-validation.js +58 -0
  8. package/dist/mcp/handlers/v2-advance-core/outcome-blocked.d.ts +16 -0
  9. package/dist/mcp/handlers/v2-advance-core/outcome-blocked.js +64 -0
  10. package/dist/mcp/handlers/v2-advance-core/outcome-success.d.ts +15 -0
  11. package/dist/mcp/handlers/v2-advance-core/outcome-success.js +136 -0
  12. package/dist/mcp/handlers/v2-advance-core.d.ts +3 -45
  13. package/dist/mcp/handlers/v2-advance-core.js +3 -431
  14. package/dist/mcp/handlers/v2-advance-events.d.ts +61 -0
  15. package/dist/mcp/handlers/v2-advance-events.js +126 -0
  16. package/dist/mcp/handlers/v2-checkpoint.js +5 -4
  17. package/dist/mcp/handlers/v2-context-budget.js +2 -2
  18. package/dist/mcp/handlers/v2-execution/advance.d.ts +32 -0
  19. package/dist/mcp/handlers/v2-execution/advance.js +50 -0
  20. package/dist/mcp/handlers/v2-execution/continue-advance.d.ts +29 -0
  21. package/dist/mcp/handlers/v2-execution/continue-advance.js +170 -0
  22. package/dist/mcp/handlers/v2-execution/continue-rehydrate.d.ts +22 -0
  23. package/dist/mcp/handlers/v2-execution/continue-rehydrate.js +146 -0
  24. package/dist/mcp/handlers/v2-execution/index.d.ts +23 -0
  25. package/dist/mcp/handlers/v2-execution/index.js +113 -0
  26. package/dist/mcp/handlers/v2-execution/replay.d.ts +55 -0
  27. package/dist/mcp/handlers/v2-execution/replay.js +227 -0
  28. package/dist/mcp/handlers/v2-execution/start.d.ts +52 -0
  29. package/dist/mcp/handlers/v2-execution/start.js +350 -0
  30. package/dist/mcp/handlers/v2-execution-helpers.d.ts +23 -0
  31. package/dist/mcp/handlers/v2-execution-helpers.js +42 -1
  32. package/dist/mcp/handlers/v2-execution.d.ts +1 -23
  33. package/dist/mcp/handlers/v2-execution.js +5 -898
  34. package/dist/mcp/handlers/v2-resume.d.ts +8 -0
  35. package/dist/mcp/handlers/v2-resume.js +70 -0
  36. package/dist/mcp/handlers/v2-state-conversion.d.ts +0 -5
  37. package/dist/mcp/handlers/v2-state-conversion.js +2 -21
  38. package/dist/mcp/handlers/v2-token-ops.d.ts +1 -1
  39. package/dist/mcp/handlers/v2-workflow.js +76 -64
  40. package/dist/mcp/output-schemas.d.ts +40 -0
  41. package/dist/mcp/output-schemas.js +17 -1
  42. package/dist/mcp/server.js +12 -0
  43. package/dist/mcp/tool-descriptions.js +22 -0
  44. package/dist/mcp/tools.js +6 -0
  45. package/dist/mcp/types/tool-description-types.d.ts +1 -1
  46. package/dist/mcp/types/tool-description-types.js +1 -0
  47. package/dist/mcp/types/workflow-tool-edition.d.ts +1 -1
  48. package/dist/mcp/types.d.ts +6 -0
  49. package/dist/mcp/v2/tool-registry.js +8 -0
  50. package/dist/mcp/v2/tools.d.ts +15 -0
  51. package/dist/mcp/v2/tools.js +8 -1
  52. package/dist/v2/durable-core/constants.d.ts +60 -0
  53. package/dist/v2/durable-core/constants.js +55 -1
  54. package/dist/v2/durable-core/domain/ack-advance-append-plan.d.ts +23 -13
  55. package/dist/v2/durable-core/domain/ack-advance-append-plan.js +160 -113
  56. package/dist/v2/durable-core/domain/blocked-node-builder.js +8 -2
  57. package/dist/v2/durable-core/domain/blocking-decision.d.ts +2 -0
  58. package/dist/v2/durable-core/domain/blocking-decision.js +29 -12
  59. package/dist/v2/durable-core/domain/bundle-builder.d.ts +1 -0
  60. package/dist/v2/durable-core/domain/bundle-builder.js +1 -1
  61. package/dist/v2/durable-core/domain/bundle-validator.js +3 -2
  62. package/dist/v2/durable-core/domain/decision-trace-builder.js +7 -9
  63. package/dist/v2/durable-core/domain/function-definition-expander.js +1 -3
  64. package/dist/v2/durable-core/domain/gap-builder.js +2 -1
  65. package/dist/v2/durable-core/domain/observation-builder.js +2 -1
  66. package/dist/v2/durable-core/domain/outputs.d.ts +2 -1
  67. package/dist/v2/durable-core/domain/outputs.js +3 -2
  68. package/dist/v2/durable-core/domain/reason-model.d.ts +1 -1
  69. package/dist/v2/durable-core/domain/reason-model.js +4 -9
  70. package/dist/v2/durable-core/domain/validation-criteria-validator.js +2 -2
  71. package/dist/v2/durable-core/domain/validation-event-builder.js +4 -6
  72. package/dist/v2/durable-core/domain/validation-loader.js +2 -1
  73. package/dist/v2/durable-core/domain/validation-requirements-extractor.js +12 -18
  74. package/dist/v2/durable-core/encoding/base32-lower.d.ts +13 -1
  75. package/dist/v2/durable-core/encoding/base32-lower.js +13 -3
  76. package/dist/v2/durable-core/encoding/hex-to-bytes.d.ts +6 -0
  77. package/dist/v2/durable-core/encoding/hex-to-bytes.js +19 -0
  78. package/dist/v2/durable-core/ids/attempt-id-derivation.d.ts +6 -1
  79. package/dist/v2/durable-core/ids/attempt-id-derivation.js +9 -19
  80. package/dist/v2/durable-core/ids/event-ids.d.ts +9 -0
  81. package/dist/v2/durable-core/ids/event-ids.js +18 -0
  82. package/dist/v2/durable-core/ids/index.d.ts +13 -33
  83. package/dist/v2/durable-core/ids/index.js +22 -63
  84. package/dist/v2/durable-core/ids/session-ids.d.ts +9 -0
  85. package/dist/v2/durable-core/ids/session-ids.js +18 -0
  86. package/dist/v2/durable-core/ids/snapshot-ids.d.ts +6 -0
  87. package/dist/v2/durable-core/ids/snapshot-ids.js +10 -0
  88. package/dist/v2/durable-core/ids/token-ids.d.ts +3 -0
  89. package/dist/v2/durable-core/ids/token-ids.js +6 -0
  90. package/dist/v2/durable-core/ids/workflow-hash-ref.d.ts +3 -0
  91. package/dist/v2/durable-core/ids/workflow-hash-ref.js +5 -4
  92. package/dist/v2/durable-core/ids/workflow-ids.d.ts +11 -0
  93. package/dist/v2/durable-core/ids/workflow-ids.js +21 -0
  94. package/dist/v2/durable-core/lib/utf8-byte-length.d.ts +1 -0
  95. package/dist/v2/durable-core/lib/utf8-byte-length.js +6 -0
  96. package/dist/v2/durable-core/schemas/artifacts/loop-control.js +2 -1
  97. package/dist/v2/durable-core/schemas/execution-snapshot/blocked-snapshot.d.ts +24 -24
  98. package/dist/v2/durable-core/schemas/execution-snapshot/blocked-snapshot.js +5 -7
  99. package/dist/v2/durable-core/schemas/execution-snapshot/execution-snapshot.v1.d.ts +180 -180
  100. package/dist/v2/durable-core/schemas/export-bundle/index.d.ts +282 -287
  101. package/dist/v2/durable-core/schemas/export-bundle/index.js +0 -8
  102. package/dist/v2/durable-core/schemas/lib/dedupe-key.d.ts +9 -1
  103. package/dist/v2/durable-core/schemas/lib/dedupe-key.js +4 -3
  104. package/dist/v2/durable-core/schemas/lib/utf8-byte-length.d.ts +1 -0
  105. package/dist/v2/durable-core/schemas/lib/utf8-byte-length.js +6 -0
  106. package/dist/v2/durable-core/schemas/session/blockers.d.ts +305 -0
  107. package/dist/v2/durable-core/schemas/session/blockers.js +80 -0
  108. package/dist/v2/durable-core/schemas/session/dag-topology.d.ts +77 -0
  109. package/dist/v2/durable-core/schemas/session/dag-topology.js +45 -0
  110. package/dist/v2/durable-core/schemas/session/events.d.ts +36 -36
  111. package/dist/v2/durable-core/schemas/session/events.js +11 -182
  112. package/dist/v2/durable-core/schemas/session/gaps.d.ts +211 -0
  113. package/dist/v2/durable-core/schemas/session/gaps.js +37 -0
  114. package/dist/v2/durable-core/schemas/session/outputs.d.ts +148 -0
  115. package/dist/v2/durable-core/schemas/session/outputs.js +44 -0
  116. package/dist/v2/durable-core/schemas/session/validation-event.js +5 -7
  117. package/dist/v2/durable-core/tokens/token-codec.d.ts +1 -18
  118. package/dist/v2/durable-core/tokens/token-codec.js +0 -67
  119. package/dist/v2/durable-core/tokens/token-signer.d.ts +1 -8
  120. package/dist/v2/durable-core/tokens/token-signer.js +0 -43
  121. package/dist/v2/infra/local/base32/index.js +1 -23
  122. package/dist/v2/infra/local/bech32m/index.js +1 -1
  123. package/dist/v2/infra/local/data-dir/index.d.ts +7 -6
  124. package/dist/v2/infra/local/data-dir/index.js +3 -3
  125. package/dist/v2/infra/local/directory-listing/index.d.ts +8 -0
  126. package/dist/v2/infra/local/directory-listing/index.js +18 -0
  127. package/dist/v2/infra/local/fs/index.d.ts +1 -0
  128. package/dist/v2/infra/local/fs/index.js +3 -0
  129. package/dist/v2/infra/local/session-store/index.js +198 -182
  130. package/dist/v2/infra/local/session-summary-provider/index.d.ts +18 -0
  131. package/dist/v2/infra/local/session-summary-provider/index.js +144 -0
  132. package/dist/v2/infra/local/snapshot-store/index.js +2 -2
  133. package/dist/v2/ports/data-dir.port.d.ts +7 -6
  134. package/dist/v2/ports/directory-listing.port.d.ts +5 -0
  135. package/dist/v2/ports/directory-listing.port.js +2 -0
  136. package/dist/v2/ports/fs.port.d.ts +19 -7
  137. package/dist/v2/ports/session-event-log-store.port.d.ts +5 -2
  138. package/dist/v2/ports/session-summary-provider.port.d.ts +9 -0
  139. package/dist/v2/ports/session-summary-provider.port.js +2 -0
  140. package/dist/v2/projections/advance-outcomes.d.ts +1 -7
  141. package/dist/v2/projections/advance-outcomes.js +2 -1
  142. package/dist/v2/projections/artifacts.js +3 -2
  143. package/dist/v2/projections/capabilities.d.ts +1 -7
  144. package/dist/v2/projections/capabilities.js +2 -1
  145. package/dist/v2/projections/gaps.d.ts +1 -7
  146. package/dist/v2/projections/gaps.js +2 -1
  147. package/dist/v2/projections/node-outputs.d.ts +1 -7
  148. package/dist/v2/projections/node-outputs.js +4 -3
  149. package/dist/v2/projections/preferences.d.ts +1 -7
  150. package/dist/v2/projections/preferences.js +2 -1
  151. package/dist/v2/projections/projection-error.d.ts +7 -0
  152. package/dist/v2/projections/projection-error.js +2 -0
  153. package/dist/v2/projections/resume-ranking.d.ts +62 -0
  154. package/dist/v2/projections/resume-ranking.js +105 -0
  155. package/dist/v2/projections/run-context.d.ts +1 -7
  156. package/dist/v2/projections/run-context.js +4 -2
  157. package/dist/v2/projections/run-dag.d.ts +9 -9
  158. package/dist/v2/projections/run-dag.js +88 -65
  159. package/dist/v2/projections/run-status-signals.d.ts +1 -7
  160. package/dist/v2/projections/run-status-signals.js +3 -2
  161. package/dist/v2/usecases/enumerate-sessions.d.ts +9 -0
  162. package/dist/v2/usecases/enumerate-sessions.js +13 -0
  163. package/dist/v2/usecases/execution-session-gate.js +2 -5
  164. package/dist/v2/usecases/export-session.js +4 -2
  165. package/dist/v2/usecases/import-session.d.ts +3 -3
  166. package/dist/v2/usecases/resume-session.d.ts +4 -0
  167. package/dist/v2/usecases/resume-session.js +9 -0
  168. package/package.json +1 -1
@@ -0,0 +1,37 @@
1
+ import { ResultAsync as RA, type Result } from 'neverthrow';
2
+ import type { DomainEventV1 } from '../../../v2/durable-core/schemas/session/index.js';
3
+ import type { SessionId, RunId, NodeId, WorkflowHash } from '../../../v2/durable-core/ids/index.js';
4
+ import type { AttemptId } from '../../../v2/durable-core/tokens/index.js';
5
+ import type { LoadedSessionTruthV2 } from '../../../v2/ports/session-event-log-store.port.js';
6
+ import type { SessionEventLogStoreError } from '../../../v2/ports/session-event-log-store.port.js';
7
+ import type { WithHealthySessionLock } from '../../../v2/durable-core/ids/with-healthy-session-lock.js';
8
+ import type { Sha256PortV2 } from '../../../v2/ports/sha256.port.js';
9
+ import type { V2ContinueWorkflowInput } from '../../v2/tools.js';
10
+ import { type OutputToAppend } from '../../../v2/durable-core/domain/outputs.js';
11
+ import type { InternalError } from '../v2-error-mapping.js';
12
+ import type { AdvanceCorePorts } from './index.js';
13
+ type BuildAppendPlanArgs = {
14
+ readonly truth: LoadedSessionTruthV2;
15
+ readonly sessionId: SessionId;
16
+ readonly runId: RunId;
17
+ readonly currentNodeId: NodeId;
18
+ readonly attemptId: AttemptId;
19
+ readonly workflowHash: WorkflowHash;
20
+ readonly extraEventsToAppend: readonly Omit<DomainEventV1, 'eventIndex' | 'sessionId'>[];
21
+ readonly sessionStore: import('../../../v2/ports/session-event-log-store.port.js').SessionEventLogAppendStorePortV2;
22
+ readonly idFactory: AdvanceCorePorts['idFactory'];
23
+ readonly lock: WithHealthySessionLock;
24
+ } & ({
25
+ readonly kind: 'blocked';
26
+ readonly blockers: import('../../../v2/durable-core/domain/reason-model.js').BlockerReportV1;
27
+ readonly snapshotRef: import('../../../v2/durable-core/ids/index.js').SnapshotRef;
28
+ } | {
29
+ readonly kind: 'advanced';
30
+ readonly toNodeKind: 'step' | 'blocked_attempt' | undefined;
31
+ readonly snapshotRef: import('../../../v2/durable-core/ids/index.js').SnapshotRef;
32
+ readonly outputsToAppend: readonly OutputToAppend[];
33
+ });
34
+ export declare function buildAndAppendPlan(args: BuildAppendPlanArgs): RA<void, InternalError | SessionEventLogStoreError>;
35
+ export declare function buildNotesOutputs(allowNotesAppend: boolean, attemptId: AttemptId, inputOutput: V2ContinueWorkflowInput['output']): readonly OutputToAppend[];
36
+ export declare function buildArtifactOutputs(inputArtifacts: readonly unknown[], attemptId: AttemptId, sha256: Sha256PortV2): Result<readonly OutputToAppend[], InternalError>;
37
+ export {};
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildAndAppendPlan = buildAndAppendPlan;
4
+ exports.buildNotesOutputs = buildNotesOutputs;
5
+ exports.buildArtifactOutputs = buildArtifactOutputs;
6
+ const neverthrow_1 = require("neverthrow");
7
+ const index_js_1 = require("../../../v2/durable-core/tokens/index.js");
8
+ const jcs_js_1 = require("../../../v2/durable-core/canonical/jcs.js");
9
+ const notes_markdown_js_1 = require("../../../v2/durable-core/domain/notes-markdown.js");
10
+ const outputs_js_1 = require("../../../v2/durable-core/domain/outputs.js");
11
+ const ack_advance_append_plan_js_1 = require("../../../v2/durable-core/domain/ack-advance-append-plan.js");
12
+ const constants_js_1 = require("../../../v2/durable-core/constants.js");
13
+ function buildAndAppendPlan(args) {
14
+ const { truth, sessionId, runId, currentNodeId, attemptId, workflowHash, extraEventsToAppend, sessionStore, idFactory, lock } = args;
15
+ const nextEventIndex = truth.events.length === 0 ? 0 : truth.events[truth.events.length - 1].eventIndex + 1;
16
+ const evtAdvanceRecorded = idFactory.mintEventId();
17
+ if (args.kind === 'blocked') {
18
+ const toNodeId = String(idFactory.mintNodeId());
19
+ const evtNodeCreated = idFactory.mintEventId();
20
+ const evtEdgeCreated = idFactory.mintEventId();
21
+ const hasChildren = truth.events.some((e) => e.kind === constants_js_1.EVENT_KIND.EDGE_CREATED && e.data.fromNodeId === String(currentNodeId));
22
+ const causeKind = hasChildren ? constants_js_1.EDGE_CAUSE.NON_TIP_ADVANCE : constants_js_1.EDGE_CAUSE.INTENTIONAL_FORK;
23
+ const planRes = (0, ack_advance_append_plan_js_1.buildAckAdvanceAppendPlanV1)({
24
+ sessionId: String(sessionId),
25
+ runId: String(runId),
26
+ fromNodeId: String(currentNodeId),
27
+ workflowHash,
28
+ attemptId: String(attemptId),
29
+ nextEventIndex,
30
+ extraEventsToAppend,
31
+ outcome: { kind: 'advanced', toNodeId },
32
+ toNodeKind: 'blocked_attempt',
33
+ toNodeId,
34
+ snapshotRef: args.snapshotRef,
35
+ causeKind,
36
+ minted: {
37
+ advanceRecordedEventId: evtAdvanceRecorded,
38
+ nodeCreatedEventId: evtNodeCreated,
39
+ edgeCreatedEventId: evtEdgeCreated,
40
+ outputEventIds: [],
41
+ },
42
+ outputsToAppend: [],
43
+ });
44
+ if (planRes.isErr())
45
+ return (0, neverthrow_1.errAsync)({ kind: 'invariant_violation', message: planRes.error.message });
46
+ return sessionStore.append(lock, planRes.value);
47
+ }
48
+ const toNodeId = String(idFactory.mintNodeId());
49
+ const evtNodeCreated = idFactory.mintEventId();
50
+ const evtEdgeCreated = idFactory.mintEventId();
51
+ const hasChildren = truth.events.some((e) => e.kind === constants_js_1.EVENT_KIND.EDGE_CREATED && e.data.fromNodeId === String(currentNodeId));
52
+ const causeKind = hasChildren ? constants_js_1.EDGE_CAUSE.NON_TIP_ADVANCE : constants_js_1.EDGE_CAUSE.INTENTIONAL_FORK;
53
+ const normalizedOutputs = (0, outputs_js_1.normalizeOutputsForAppend)(args.outputsToAppend);
54
+ const outputEventIds = normalizedOutputs.map(() => idFactory.mintEventId());
55
+ const planRes = (0, ack_advance_append_plan_js_1.buildAckAdvanceAppendPlanV1)({
56
+ sessionId: String(sessionId),
57
+ runId: String(runId),
58
+ fromNodeId: String(currentNodeId),
59
+ workflowHash,
60
+ attemptId: String(attemptId),
61
+ nextEventIndex,
62
+ extraEventsToAppend,
63
+ outcome: { kind: 'advanced', toNodeId },
64
+ toNodeKind: args.toNodeKind ?? 'step',
65
+ toNodeId,
66
+ snapshotRef: args.snapshotRef,
67
+ causeKind,
68
+ minted: {
69
+ advanceRecordedEventId: evtAdvanceRecorded,
70
+ nodeCreatedEventId: evtNodeCreated,
71
+ edgeCreatedEventId: evtEdgeCreated,
72
+ outputEventIds,
73
+ },
74
+ outputsToAppend: [...args.outputsToAppend],
75
+ });
76
+ if (planRes.isErr())
77
+ return (0, neverthrow_1.errAsync)({ kind: 'invariant_violation', message: planRes.error.message });
78
+ return sessionStore.append(lock, planRes.value);
79
+ }
80
+ function buildNotesOutputs(allowNotesAppend, attemptId, inputOutput) {
81
+ if (!allowNotesAppend || !inputOutput?.notesMarkdown)
82
+ return [];
83
+ return [{
84
+ outputId: String((0, index_js_1.asOutputId)(`out_recap_${String(attemptId)}`)),
85
+ outputChannel: constants_js_1.OUTPUT_CHANNEL.RECAP,
86
+ payload: {
87
+ payloadKind: 'notes',
88
+ notesMarkdown: (0, notes_markdown_js_1.toNotesMarkdownV1)(inputOutput.notesMarkdown),
89
+ },
90
+ }];
91
+ }
92
+ function buildArtifactOutputs(inputArtifacts, attemptId, sha256) {
93
+ const outputs = [];
94
+ for (let idx = 0; idx < inputArtifacts.length; idx++) {
95
+ const artifact = inputArtifacts[idx];
96
+ const canonicalBytesRes = (0, jcs_js_1.toCanonicalBytes)(artifact);
97
+ if (canonicalBytesRes.isErr()) {
98
+ return (0, neverthrow_1.err)({ kind: 'invariant_violation', message: `Artifact canonicalization failed at index ${idx}: ${canonicalBytesRes.error.message}` });
99
+ }
100
+ const canonicalBytes = canonicalBytesRes.value;
101
+ outputs.push({
102
+ outputId: (0, index_js_1.asOutputId)(`out_artifact_${String(attemptId)}_${idx}`),
103
+ outputChannel: constants_js_1.OUTPUT_CHANNEL.ARTIFACT,
104
+ payload: {
105
+ payloadKind: 'artifact_ref',
106
+ sha256: sha256.sha256(canonicalBytes),
107
+ contentType: 'application/json',
108
+ byteLength: canonicalBytes.length,
109
+ content: artifact,
110
+ },
111
+ });
112
+ }
113
+ return (0, neverthrow_1.ok)(outputs);
114
+ }
@@ -0,0 +1,67 @@
1
+ import { ResultAsync as RA } from 'neverthrow';
2
+ import type { ExecutionSnapshotFileV1, EngineStateV1 } from '../../../v2/durable-core/schemas/execution-snapshot/index.js';
3
+ import type { SessionId, RunId, NodeId, WorkflowHash } from '../../../v2/durable-core/ids/index.js';
4
+ import type { AttemptId } from '../../../v2/durable-core/tokens/index.js';
5
+ import type { LoadedSessionTruthV2 } from '../../../v2/ports/session-event-log-store.port.js';
6
+ import type { SessionEventLogStoreError } from '../../../v2/ports/session-event-log-store.port.js';
7
+ import type { SnapshotStoreError } from '../../../v2/ports/snapshot-store.port.js';
8
+ import type { WithHealthySessionLock } from '../../../v2/durable-core/ids/with-healthy-session-lock.js';
9
+ import type { Sha256PortV2 } from '../../../v2/ports/sha256.port.js';
10
+ import type { JsonValue } from '../../../v2/durable-core/canonical/json-types.js';
11
+ import type { V2ContinueWorkflowInput } from '../../v2/tools.js';
12
+ import type { ValidationResult } from '../../../types/validation.js';
13
+ import { createWorkflow } from '../../../types/workflow.js';
14
+ import { type ReasonV1 } from '../../../v2/durable-core/domain/reason-model.js';
15
+ import { getOutputRequirementStatusWithArtifactsV1 } from '../../../v2/durable-core/domain/validation-criteria-validator.js';
16
+ import type { InternalError } from '../v2-error-mapping.js';
17
+ import { type ValidatedAdvanceInputs } from './input-validation.js';
18
+ export type AdvanceMode = {
19
+ readonly kind: 'fresh';
20
+ readonly sourceNodeId: NodeId;
21
+ readonly snapshot: ExecutionSnapshotFileV1;
22
+ } | {
23
+ readonly kind: 'retry';
24
+ readonly blockedNodeId: NodeId;
25
+ readonly blockedSnapshot: ExecutionSnapshotFileV1;
26
+ };
27
+ export interface AdvanceCorePorts {
28
+ readonly snapshotStore: import('../../../v2/ports/snapshot-store.port.js').SnapshotStorePortV2;
29
+ readonly sessionStore: import('../../../v2/ports/session-event-log-store.port.js').SessionEventLogAppendStorePortV2;
30
+ readonly sha256: Sha256PortV2;
31
+ readonly idFactory: {
32
+ readonly mintNodeId: () => NodeId;
33
+ readonly mintEventId: () => string;
34
+ };
35
+ }
36
+ export interface AdvanceContext {
37
+ readonly truth: LoadedSessionTruthV2;
38
+ readonly sessionId: SessionId;
39
+ readonly runId: RunId;
40
+ readonly currentNodeId: NodeId;
41
+ readonly attemptId: AttemptId;
42
+ readonly workflowHash: WorkflowHash;
43
+ readonly inputOutput: V2ContinueWorkflowInput['output'];
44
+ readonly pinnedWorkflow: ReturnType<typeof createWorkflow>;
45
+ readonly engineState: EngineStateV1;
46
+ readonly pendingStep: ValidatedAdvanceInputs['pendingStep'];
47
+ }
48
+ export interface ComputedAdvanceResults {
49
+ readonly reasons: readonly ReasonV1[];
50
+ readonly effectiveReasons: readonly ReasonV1[];
51
+ readonly outputRequirement: ReturnType<typeof getOutputRequirementStatusWithArtifactsV1>;
52
+ readonly validation: ValidationResult | undefined;
53
+ }
54
+ export declare function executeAdvanceCore(args: {
55
+ readonly mode: AdvanceMode;
56
+ readonly truth: LoadedSessionTruthV2;
57
+ readonly sessionId: SessionId;
58
+ readonly runId: RunId;
59
+ readonly attemptId: AttemptId;
60
+ readonly workflowHash: WorkflowHash;
61
+ readonly dedupeKey: string;
62
+ readonly inputContext: JsonValue | undefined;
63
+ readonly inputOutput: V2ContinueWorkflowInput['output'];
64
+ readonly lock: WithHealthySessionLock;
65
+ readonly pinnedWorkflow: ReturnType<typeof createWorkflow>;
66
+ readonly ports: AdvanceCorePorts;
67
+ }): RA<void, InternalError | SessionEventLogStoreError | SnapshotStoreError>;
@@ -0,0 +1,100 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.executeAdvanceCore = executeAdvanceCore;
4
+ const neverthrow_1 = require("neverthrow");
5
+ const snapshot_state_js_1 = require("../../../v2/durable-core/projections/snapshot-state.js");
6
+ const reason_model_js_1 = require("../../../v2/durable-core/domain/reason-model.js");
7
+ const risk_policy_guardrails_js_1 = require("../../../v2/durable-core/domain/risk-policy-guardrails.js");
8
+ const blocking_decision_js_1 = require("../../../v2/durable-core/domain/blocking-decision.js");
9
+ const validation_criteria_validator_js_1 = require("../../../v2/durable-core/domain/validation-criteria-validator.js");
10
+ const validation_engine_js_1 = require("../../../application/services/validation-engine.js");
11
+ const enhanced_loop_validator_js_1 = require("../../../application/services/enhanced-loop-validator.js");
12
+ const v2_state_conversion_js_1 = require("../v2-state-conversion.js");
13
+ const with_timeout_js_1 = require("../shared/with-timeout.js");
14
+ const input_validation_js_1 = require("./input-validation.js");
15
+ const outcome_blocked_js_1 = require("./outcome-blocked.js");
16
+ const outcome_success_js_1 = require("./outcome-success.js");
17
+ function nodeIdOf(mode) {
18
+ switch (mode.kind) {
19
+ case 'fresh': return mode.sourceNodeId;
20
+ case 'retry': return mode.blockedNodeId;
21
+ }
22
+ }
23
+ function snapshotOf(mode) {
24
+ switch (mode.kind) {
25
+ case 'fresh': return mode.snapshot;
26
+ case 'retry': return mode.blockedSnapshot;
27
+ }
28
+ }
29
+ function executeAdvanceCore(args) {
30
+ const { mode, truth, sessionId, runId, attemptId, workflowHash, inputContext, inputOutput, lock, pinnedWorkflow, ports } = args;
31
+ const { snapshotStore, sessionStore, sha256, idFactory } = ports;
32
+ const currentNodeId = nodeIdOf(mode);
33
+ const snap = snapshotOf(mode);
34
+ const engineState = snap.enginePayload.engineState;
35
+ const pendingStep = derivePendingStepForMode(mode, engineState);
36
+ if (!pendingStep) {
37
+ return errAsync({ kind: 'no_pending_step' });
38
+ }
39
+ const validatedRes = (0, input_validation_js_1.validateAdvanceInputs)({
40
+ truth, runId, currentNodeId, inputContext, inputOutput, pinnedWorkflow, pendingStep,
41
+ });
42
+ if (validatedRes.isErr())
43
+ return errAsync(validatedRes.error);
44
+ const v = validatedRes.value;
45
+ const validator = v.validationCriteria ? new validation_engine_js_1.ValidationEngine(new enhanced_loop_validator_js_1.EnhancedLoopValidator()) : null;
46
+ const validationRes = validator && v.notesMarkdown
47
+ ? neverthrow_1.ResultAsync.fromPromise((0, with_timeout_js_1.withTimeout)(validator.validate(v.notesMarkdown, v.validationCriteria, v.mergedContext), 30000, 'ValidationEngine.validate'), (cause) => ({ kind: 'advance_apply_failed', message: String(cause) })).andThen((res) => {
48
+ if (res.isErr()) {
49
+ return (0, neverthrow_1.errAsync)({
50
+ kind: 'advance_apply_failed',
51
+ message: `ValidationEngineError: ${res.error.kind} (${res.error.message})`,
52
+ });
53
+ }
54
+ return (0, neverthrow_1.okAsync)(res.value);
55
+ })
56
+ : (0, neverthrow_1.okAsync)(undefined);
57
+ return validationRes.andThen((validation) => {
58
+ const outputRequirement = (0, validation_criteria_validator_js_1.getOutputRequirementStatusWithArtifactsV1)({
59
+ outputContract: v.outputContract,
60
+ artifacts: v.artifacts,
61
+ validationCriteria: v.validationCriteria,
62
+ notesMarkdown: v.notesMarkdown,
63
+ validation,
64
+ });
65
+ const reasonsRes = (0, blocking_decision_js_1.detectBlockingReasonsV1)({ outputRequirement });
66
+ if (reasonsRes.isErr()) {
67
+ return errAsync({ kind: 'invariant_violation', message: reasonsRes.error.message });
68
+ }
69
+ const reasons = reasonsRes.value;
70
+ const { blocking: effectiveReasons } = (0, risk_policy_guardrails_js_1.applyGuardrails)(v.riskPolicy, reasons);
71
+ const shouldBlockNow = effectiveReasons.length > 0 && (0, reason_model_js_1.shouldBlock)(v.autonomy, effectiveReasons);
72
+ const ctx = { truth, sessionId, runId, currentNodeId, attemptId, workflowHash, inputOutput, pinnedWorkflow, engineState, pendingStep };
73
+ const computed = { reasons, effectiveReasons, outputRequirement, validation };
74
+ const ports = { snapshotStore, sessionStore, sha256, idFactory };
75
+ if (shouldBlockNow) {
76
+ return (0, outcome_blocked_js_1.buildBlockedOutcome)({ mode, snap, ctx, computed, lock, ports });
77
+ }
78
+ return (0, outcome_success_js_1.buildSuccessOutcome)({ mode, ctx, computed, v, lock, ports });
79
+ });
80
+ }
81
+ function derivePendingStepForMode(mode, engineState) {
82
+ switch (mode.kind) {
83
+ case 'fresh': {
84
+ const currentState = (0, v2_state_conversion_js_1.toV1ExecutionState)(engineState);
85
+ return (currentState.kind === 'running' && currentState.pendingStep) ? currentState.pendingStep : null;
86
+ }
87
+ case 'retry': {
88
+ if (engineState.kind !== 'blocked')
89
+ return null;
90
+ const pending = (0, snapshot_state_js_1.derivePendingStep)(engineState);
91
+ return pending ? {
92
+ stepId: String(pending.stepId),
93
+ loopPath: pending.loopPath.map(f => ({ loopId: String(f.loopId), iteration: f.iteration })),
94
+ } : null;
95
+ }
96
+ }
97
+ }
98
+ function errAsync(e) {
99
+ return (0, neverthrow_1.errAsync)(e);
100
+ }
@@ -0,0 +1,44 @@
1
+ import { type Result } from 'neverthrow';
2
+ import type { RunId, NodeId } from '../../../v2/durable-core/ids/index.js';
3
+ import type { LoadedSessionTruthV2 } from '../../../v2/ports/session-event-log-store.port.js';
4
+ import type { JsonValue, JsonObject } from '../../../v2/durable-core/canonical/json-types.js';
5
+ import type { V2ContinueWorkflowInput } from '../../v2/tools.js';
6
+ import type { OutputContract } from '../../../types/workflow-definition.js';
7
+ import type { ValidationCriteria } from '../../../types/validation.js';
8
+ import type { InternalError } from '../v2-error-mapping.js';
9
+ export interface ValidatedAdvanceInputs {
10
+ readonly pendingStep: {
11
+ readonly stepId: string;
12
+ readonly loopPath: readonly {
13
+ readonly loopId: string;
14
+ readonly iteration: number;
15
+ }[];
16
+ };
17
+ readonly mergedContext: Record<string, unknown>;
18
+ readonly inputContextObj: JsonObject | undefined;
19
+ readonly validationCriteria: ValidationCriteria | undefined;
20
+ readonly outputContract: OutputContract | undefined;
21
+ readonly notesMarkdown: string | undefined;
22
+ readonly artifacts: readonly unknown[];
23
+ readonly autonomy: 'guided' | 'full_auto_stop_on_user_deps' | 'full_auto_never_stop';
24
+ readonly riskPolicy: 'conservative' | 'balanced' | 'aggressive';
25
+ readonly effectivePrefs: {
26
+ readonly autonomy: string;
27
+ readonly riskPolicy: string;
28
+ } | undefined;
29
+ }
30
+ export declare function validateAdvanceInputs(args: {
31
+ readonly truth: LoadedSessionTruthV2;
32
+ readonly runId: RunId;
33
+ readonly currentNodeId: NodeId;
34
+ readonly inputContext: JsonValue | undefined;
35
+ readonly inputOutput: V2ContinueWorkflowInput['output'];
36
+ readonly pinnedWorkflow: ReturnType<typeof import('../../../types/workflow.js').createWorkflow>;
37
+ readonly pendingStep: {
38
+ readonly stepId: string;
39
+ readonly loopPath: readonly {
40
+ readonly loopId: string;
41
+ readonly iteration: number;
42
+ }[];
43
+ };
44
+ }): Result<ValidatedAdvanceInputs, InternalError>;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateAdvanceInputs = validateAdvanceInputs;
4
+ const neverthrow_1 = require("neverthrow");
5
+ const workflow_js_1 = require("../../../types/workflow.js");
6
+ const run_context_js_1 = require("../../../v2/projections/run-context.js");
7
+ const preferences_js_1 = require("../../../v2/projections/preferences.js");
8
+ const context_merge_js_1 = require("../../../v2/durable-core/domain/context-merge.js");
9
+ const constants_js_1 = require("../../../v2/durable-core/constants.js");
10
+ function validateAdvanceInputs(args) {
11
+ const { truth, runId, currentNodeId, inputContext, inputOutput, pinnedWorkflow, pendingStep } = args;
12
+ const storedContextRes = (0, run_context_js_1.projectRunContextV2)(truth.events);
13
+ const storedContext = storedContextRes.isOk() ? storedContextRes.value.byRunId[String(runId)]?.context : undefined;
14
+ const inputContextObj = inputContext && typeof inputContext === 'object' && inputContext !== null && !Array.isArray(inputContext)
15
+ ? inputContext
16
+ : undefined;
17
+ const mergedContextRes = (0, context_merge_js_1.mergeContext)(storedContext, inputContextObj);
18
+ if (mergedContextRes.isErr()) {
19
+ return (0, neverthrow_1.err)({ kind: 'invariant_violation', message: `Context merge failed: ${mergedContextRes.error.message}` });
20
+ }
21
+ const step = (0, workflow_js_1.getStepById)(pinnedWorkflow, pendingStep.stepId);
22
+ const validationCriteria = step?.validationCriteria;
23
+ const outputContract = step?.outputContract;
24
+ const parentByNodeId = {};
25
+ for (const e of truth.events) {
26
+ if (e.kind !== constants_js_1.EVENT_KIND.NODE_CREATED)
27
+ continue;
28
+ if (e.scope?.runId !== String(runId))
29
+ continue;
30
+ parentByNodeId[String(e.scope.nodeId)] = e.data.parentNodeId;
31
+ }
32
+ const prefs = (0, preferences_js_1.projectPreferencesV2)(truth.events, parentByNodeId);
33
+ const effectivePrefs = prefs.isOk() ? prefs.value.byNodeId[String(currentNodeId)]?.effective : undefined;
34
+ const rawAutonomy = effectivePrefs?.autonomy ?? 'guided';
35
+ const rawRiskPolicy = effectivePrefs?.riskPolicy ?? 'conservative';
36
+ const VALID_AUTONOMY = ['guided', 'full_auto_stop_on_user_deps', 'full_auto_never_stop'];
37
+ const VALID_RISK_POLICY = ['conservative', 'balanced', 'aggressive'];
38
+ if (!VALID_AUTONOMY.includes(rawAutonomy)) {
39
+ return (0, neverthrow_1.err)({ kind: 'invariant_violation', message: `Unknown autonomy mode: ${rawAutonomy}` });
40
+ }
41
+ if (!VALID_RISK_POLICY.includes(rawRiskPolicy)) {
42
+ return (0, neverthrow_1.err)({ kind: 'invariant_violation', message: `Unknown risk policy: ${rawRiskPolicy}` });
43
+ }
44
+ const autonomy = rawAutonomy;
45
+ const riskPolicy = rawRiskPolicy;
46
+ return (0, neverthrow_1.ok)({
47
+ pendingStep,
48
+ mergedContext: mergedContextRes.value,
49
+ inputContextObj,
50
+ validationCriteria,
51
+ outputContract,
52
+ notesMarkdown: inputOutput?.notesMarkdown,
53
+ artifacts: inputOutput?.artifacts ?? [],
54
+ autonomy,
55
+ riskPolicy,
56
+ effectivePrefs,
57
+ });
58
+ }
@@ -0,0 +1,16 @@
1
+ import { ResultAsync as RA } from 'neverthrow';
2
+ import type { ExecutionSnapshotFileV1 } from '../../../v2/durable-core/schemas/execution-snapshot/index.js';
3
+ import type { SessionEventLogStoreError } from '../../../v2/ports/session-event-log-store.port.js';
4
+ import type { SnapshotStoreError } from '../../../v2/ports/snapshot-store.port.js';
5
+ import type { WithHealthySessionLock } from '../../../v2/durable-core/ids/with-healthy-session-lock.js';
6
+ import type { InternalError } from '../v2-error-mapping.js';
7
+ import type { AdvanceMode } from './index.js';
8
+ import type { AdvanceContext, ComputedAdvanceResults, AdvanceCorePorts } from './index.js';
9
+ export declare function buildBlockedOutcome(args: {
10
+ readonly mode: AdvanceMode;
11
+ readonly snap: ExecutionSnapshotFileV1;
12
+ readonly ctx: AdvanceContext;
13
+ readonly computed: ComputedAdvanceResults;
14
+ readonly lock: WithHealthySessionLock;
15
+ readonly ports: AdvanceCorePorts;
16
+ }): RA<void, InternalError | SessionEventLogStoreError | SnapshotStoreError>;
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildBlockedOutcome = buildBlockedOutcome;
4
+ const neverthrow_1 = require("neverthrow");
5
+ const reason_model_js_1 = require("../../../v2/durable-core/domain/reason-model.js");
6
+ const validation_event_builder_js_1 = require("../../../v2/durable-core/domain/validation-event-builder.js");
7
+ const blocked_node_builder_js_1 = require("../../../v2/durable-core/domain/blocked-node-builder.js");
8
+ const event_builders_js_1 = require("./event-builders.js");
9
+ function buildBlockedOutcome(args) {
10
+ const { mode, snap, lock, ports } = args;
11
+ const { truth, sessionId, runId, currentNodeId, attemptId, workflowHash } = args.ctx;
12
+ const { reasons, effectiveReasons, outputRequirement, validation } = args.computed;
13
+ const { snapshotStore, sessionStore, sha256, idFactory } = ports;
14
+ const blockersRes = (0, reason_model_js_1.buildBlockerReport)(effectiveReasons);
15
+ if (blockersRes.isErr()) {
16
+ return errAsync({ kind: 'invariant_violation', message: blockersRes.error.message });
17
+ }
18
+ const validationEventId = idFactory.mintEventId();
19
+ const validationId = `validation_${String(attemptId)}`;
20
+ const contractRefForEvent = (outputRequirement.kind !== 'not_required' && outputRequirement.kind !== 'satisfied') ? outputRequirement.contractRef : 'none';
21
+ const validationForEvent = validation ??
22
+ (outputRequirement.kind === 'missing'
23
+ ? { valid: false, issues: [`Missing required output for contractRef=${contractRefForEvent}`], suggestions: [], warnings: undefined }
24
+ : { valid: false, issues: ['Validation result missing'], suggestions: [], warnings: undefined });
25
+ const validationEventRes = (0, validation_event_builder_js_1.buildValidationPerformedEvent)({
26
+ sessionId: String(sessionId),
27
+ validationId,
28
+ attemptId: String(attemptId),
29
+ contractRef: contractRefForEvent,
30
+ scope: { runId: String(runId), nodeId: String(currentNodeId) },
31
+ minted: { eventId: validationEventId },
32
+ result: validationForEvent,
33
+ });
34
+ if (validationEventRes.isErr()) {
35
+ return errAsync({ kind: 'invariant_violation', message: validationEventRes.error.message });
36
+ }
37
+ const extraEventsToAppend = [validationEventRes.value];
38
+ const primaryReason = reasons[0];
39
+ if (!primaryReason) {
40
+ return errAsync({ kind: 'invariant_violation', message: 'shouldBlockNow=true requires at least one reason' });
41
+ }
42
+ const blockedSnapshotRes = (0, blocked_node_builder_js_1.buildBlockedNodeSnapshot)({
43
+ priorSnapshot: snap,
44
+ primaryReason,
45
+ attemptId,
46
+ validationRef: validationId,
47
+ blockers: blockersRes.value,
48
+ sha256,
49
+ });
50
+ if (blockedSnapshotRes.isErr()) {
51
+ return errAsync({ kind: 'invariant_violation', message: blockedSnapshotRes.error.message });
52
+ }
53
+ return snapshotStore.putExecutionSnapshotV1(blockedSnapshotRes.value).andThen((blockedSnapshotRef) => {
54
+ return (0, event_builders_js_1.buildAndAppendPlan)({
55
+ kind: 'blocked',
56
+ truth, sessionId, runId, currentNodeId, attemptId, workflowHash,
57
+ extraEventsToAppend, blockers: blockersRes.value, snapshotRef: blockedSnapshotRef,
58
+ sessionStore, idFactory, lock,
59
+ });
60
+ });
61
+ }
62
+ function errAsync(e) {
63
+ return (0, neverthrow_1.errAsync)(e);
64
+ }
@@ -0,0 +1,15 @@
1
+ import { ResultAsync as RA } from 'neverthrow';
2
+ import type { SessionEventLogStoreError } from '../../../v2/ports/session-event-log-store.port.js';
3
+ import type { SnapshotStoreError } from '../../../v2/ports/snapshot-store.port.js';
4
+ import type { WithHealthySessionLock } from '../../../v2/durable-core/ids/with-healthy-session-lock.js';
5
+ import type { InternalError } from '../v2-error-mapping.js';
6
+ import type { AdvanceMode, AdvanceContext, ComputedAdvanceResults, AdvanceCorePorts } from './index.js';
7
+ import type { ValidatedAdvanceInputs } from './input-validation.js';
8
+ export declare function buildSuccessOutcome(args: {
9
+ readonly mode: AdvanceMode;
10
+ readonly ctx: AdvanceContext;
11
+ readonly computed: ComputedAdvanceResults;
12
+ readonly v: ValidatedAdvanceInputs;
13
+ readonly lock: WithHealthySessionLock;
14
+ readonly ports: AdvanceCorePorts;
15
+ }): RA<void, InternalError | SessionEventLogStoreError | SnapshotStoreError>;
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildSuccessOutcome = buildSuccessOutcome;
4
+ const neverthrow_1 = require("neverthrow");
5
+ const workflow_compiler_js_1 = require("../../../application/services/workflow-compiler.js");
6
+ const workflow_interpreter_js_1 = require("../../../application/services/workflow-interpreter.js");
7
+ const recommendation_warnings_js_1 = require("../../../v2/durable-core/domain/recommendation-warnings.js");
8
+ const v2_state_conversion_js_1 = require("../v2-state-conversion.js");
9
+ const v2_context_budget_js_1 = require("../v2-context-budget.js");
10
+ const v2_advance_events_js_1 = require("../v2-advance-events.js");
11
+ const event_builders_js_1 = require("./event-builders.js");
12
+ function successNodeKind(mode) {
13
+ switch (mode.kind) {
14
+ case 'fresh': return undefined;
15
+ case 'retry': return 'step';
16
+ }
17
+ }
18
+ function buildSuccessOutcome(args) {
19
+ const { mode, v, lock, ports } = args;
20
+ const { truth, sessionId, runId, currentNodeId, attemptId, workflowHash, inputOutput, pinnedWorkflow, engineState, pendingStep } = args.ctx;
21
+ const { effectiveReasons, outputRequirement, validation } = args.computed;
22
+ const { snapshotStore, sessionStore, sha256, idFactory } = ports;
23
+ const compiler = new workflow_compiler_js_1.WorkflowCompiler();
24
+ const interpreter = new workflow_interpreter_js_1.WorkflowInterpreter();
25
+ const compiledWf = compiler.compile(pinnedWorkflow);
26
+ if (compiledWf.isErr()) {
27
+ return errAsync({ kind: 'advance_apply_failed', message: compiledWf.error.message });
28
+ }
29
+ const currentState = (0, v2_state_conversion_js_1.toV1ExecutionState)(engineState);
30
+ const event = {
31
+ kind: 'step_completed',
32
+ stepInstanceId: {
33
+ stepId: pendingStep.stepId,
34
+ loopPath: pendingStep.loopPath.map(f => ({ loopId: f.loopId, iteration: f.iteration })),
35
+ },
36
+ };
37
+ const advanced = interpreter.applyEvent(currentState, event);
38
+ if (advanced.isErr()) {
39
+ return errAsync({ kind: 'advance_apply_failed', message: advanced.error.message });
40
+ }
41
+ const artifactsForEval = (0, v2_context_budget_js_1.collectArtifactsForEvaluation)({
42
+ truthEvents: truth.events,
43
+ inputArtifacts: inputOutput?.artifacts ?? [],
44
+ });
45
+ const nextRes = interpreter.next(compiledWf.value, advanced.value, v.mergedContext, artifactsForEval);
46
+ if (nextRes.isErr()) {
47
+ return errAsync({ kind: 'advance_next_failed', message: nextRes.error.message });
48
+ }
49
+ const out = nextRes.value;
50
+ const extraEventsToAppend = [];
51
+ if (v.autonomy === 'full_auto_never_stop' && effectiveReasons.length > 0) {
52
+ extraEventsToAppend.push(...(0, v2_advance_events_js_1.buildGapEvents)({
53
+ gaps: effectiveReasons,
54
+ sessionId: String(sessionId),
55
+ runId,
56
+ nodeId: currentNodeId,
57
+ attemptId,
58
+ idFactory,
59
+ }));
60
+ }
61
+ const workflowRecommendations = pinnedWorkflow.definition.recommendedPreferences;
62
+ if (workflowRecommendations && v.effectivePrefs) {
63
+ const warnings = (0, recommendation_warnings_js_1.checkRecommendationExceedance)({ autonomy: v.autonomy, riskPolicy: v.riskPolicy }, workflowRecommendations);
64
+ extraEventsToAppend.push(...(0, v2_advance_events_js_1.buildRecommendationWarningEvents)({
65
+ recommendations: warnings,
66
+ sessionId: String(sessionId),
67
+ runId,
68
+ nodeId: currentNodeId,
69
+ idFactory,
70
+ }));
71
+ }
72
+ if (v.inputContextObj) {
73
+ const contextEvent = (0, v2_advance_events_js_1.buildContextSetEvent)({
74
+ mergedContext: v.mergedContext,
75
+ sessionId: String(sessionId),
76
+ runId,
77
+ idFactory,
78
+ });
79
+ if (contextEvent) {
80
+ extraEventsToAppend.push(contextEvent);
81
+ }
82
+ }
83
+ const validationEvent = (0, v2_advance_events_js_1.buildSuccessValidationEvent)({
84
+ mode,
85
+ outputRequirement,
86
+ validation,
87
+ attemptId,
88
+ sessionId: String(sessionId),
89
+ runId,
90
+ nodeId: currentNodeId,
91
+ idFactory,
92
+ });
93
+ if (validationEvent) {
94
+ extraEventsToAppend.push(validationEvent);
95
+ }
96
+ const traceEventRes = (0, v2_advance_events_js_1.buildDecisionTraceEvent)({
97
+ decisions: out.trace,
98
+ sessionId: String(sessionId),
99
+ runId,
100
+ nodeId: currentNodeId,
101
+ idFactory,
102
+ });
103
+ if (traceEventRes.isErr()) {
104
+ return errAsync(traceEventRes.error);
105
+ }
106
+ if (traceEventRes.value) {
107
+ extraEventsToAppend.push(traceEventRes.value);
108
+ }
109
+ const newEngineState = (0, v2_state_conversion_js_1.fromV1ExecutionState)(out.state);
110
+ const snapshotFile = {
111
+ v: 1,
112
+ kind: 'execution_snapshot',
113
+ enginePayload: { v: 1, engineState: newEngineState },
114
+ };
115
+ return snapshotStore.putExecutionSnapshotV1(snapshotFile).andThen((newSnapshotRef) => {
116
+ const allowNotesAppend = v.validationCriteria
117
+ ? Boolean(v.notesMarkdown && validation && validation.valid)
118
+ : Boolean(v.notesMarkdown);
119
+ const notesOutputs = (0, event_builders_js_1.buildNotesOutputs)(allowNotesAppend, attemptId, inputOutput);
120
+ const artifactOutputsRes = (0, event_builders_js_1.buildArtifactOutputs)(inputOutput?.artifacts ?? [], attemptId, sha256);
121
+ if (artifactOutputsRes.isErr()) {
122
+ return errAsync(artifactOutputsRes.error);
123
+ }
124
+ const outputsToAppend = [...notesOutputs, ...artifactOutputsRes.value];
125
+ return (0, event_builders_js_1.buildAndAppendPlan)({
126
+ kind: 'advanced',
127
+ truth, sessionId, runId, currentNodeId, attemptId, workflowHash,
128
+ extraEventsToAppend, toNodeKind: successNodeKind(mode),
129
+ snapshotRef: newSnapshotRef, outputsToAppend,
130
+ sessionStore, idFactory, lock,
131
+ });
132
+ });
133
+ }
134
+ function errAsync(e) {
135
+ return (0, neverthrow_1.errAsync)(e);
136
+ }