create-safest-tools 0.6.0 → 0.7.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.
- package/README.md +3 -3
- package/package.json +2 -2
- package/src/config.mjs +2 -2
- package/src/update.mjs +10 -1
- package/template/README.md +2 -2
- package/template/console/README.md +2 -2
- package/template/console/analytics/AnalyticsWorkspace.tsx +49 -36
- package/template/console/analytics/controller.ts +10 -2
- package/template/console/analytics/types.ts +7 -0
- package/template/console/appeals/AppealFollowup.tsx +171 -0
- package/template/console/appeals/AppealWorkspace.tsx +33 -4
- package/template/console/appeals/RecordAppealDialog.tsx +42 -0
- package/template/console/appeals/appeal-corrections.css +29 -0
- package/template/console/appeals/controller.ts +40 -14
- package/template/console/appeals/events.ts +1 -0
- package/template/console/appeals/types.ts +6 -0
- package/template/console/appeals/useAppealDraftGuard.ts +12 -0
- package/template/console/assistant/AssistantWorkspace.tsx +28 -5
- package/template/console/command/CommandCentre.tsx +101 -64
- package/template/console/command/controller.ts +80 -70
- package/template/console/command/events.ts +1 -2
- package/template/console/command/presentation.ts +29 -0
- package/template/console/command/store.ts +4 -4
- package/template/console/command/types.ts +26 -21
- package/template/console/configuration/ConfigurationBuilders.tsx +101 -0
- package/template/console/configuration/ConfigurationDialog.tsx +28 -13
- package/template/console/configuration/ConfigurationWorkspace.tsx +21 -8
- package/template/console/configuration/types.ts +1 -1
- package/template/console/lib/priority.ts +13 -0
- package/template/console/operations/CaseEscalations.tsx +142 -0
- package/template/console/operations/OperationsWorkspace.tsx +2 -0
- package/template/console/operations/case-escalations.css +20 -0
- package/template/console/people/PeopleWorkspace.tsx +8 -4
- package/template/console/people/PersonAccessDialog.tsx +40 -0
- package/template/console/people/types.ts +1 -0
- package/template/console/profile/ProfileWorkspace.tsx +1 -1
- package/template/console/registry/IntegrationSetup.tsx +41 -0
- package/template/console/registry/IntegrationVerification.tsx +54 -0
- package/template/console/registry/RegistryDetailsDialog.tsx +2 -2
- package/template/console/registry/RegistryDialog.tsx +56 -27
- package/template/console/registry/RegistryWorkspace.tsx +10 -5
- package/template/console/registry/integration-verification.css +25 -0
- package/template/console/reports/CaseActions.tsx +81 -0
- package/template/console/reports/CaseContinuity.tsx +27 -0
- package/template/console/reports/CaseNotices.tsx +48 -0
- package/template/console/reports/CaseOwnership.tsx +78 -0
- package/template/console/reports/CaseReviewTasks.tsx +148 -0
- package/template/console/reports/EnrichmentFindings.tsx +148 -0
- package/template/console/reports/InvestigationBrief.tsx +29 -0
- package/template/console/reports/ReportDrawer.tsx +122 -67
- package/template/console/reports/ReportWorkspace.tsx +112 -23
- package/template/console/reports/controller.ts +125 -60
- package/template/console/reports/events.ts +9 -2
- package/template/console/reports/load-inbox.ts +17 -0
- package/template/console/reports/presence-presentation.ts +52 -0
- package/template/console/reports/private-drafts.ts +32 -0
- package/template/console/reports/store.ts +2 -2
- package/template/console/reports/types.ts +50 -2
- package/template/console/reports/use-editing-access.ts +13 -0
- package/template/console/settings/SettingsWorkspace.tsx +1 -1
- package/template/console/shell/WorkspaceShell.tsx +55 -29
- package/template/console/shell/WorkspaceUpdateNotice.tsx +48 -0
- package/template/console/shell/controller.ts +23 -16
- package/template/console/shell/navigation.ts +30 -39
- package/template/console/workflows/CreatePlaybookDialog.tsx +73 -0
- package/template/console/workflows/PlaybookExamples.tsx +160 -0
- package/template/console/workflows/PlaybookFields.tsx +109 -0
- package/template/console/workflows/PlaybookGuideEditor.tsx +125 -0
- package/template/console/workflows/PlaybookHistory.tsx +106 -0
- package/template/console/workflows/WorkflowDialogs.tsx +2 -1
- package/template/console/workflows/WorkflowStudio.tsx +108 -39
- package/template/console/workflows/WorkflowWorkspace.tsx +9 -7
- package/template/console/workflows/templates.ts +3 -3
- package/template/console/workflows/types.ts +11 -0
- package/template/migrations/0001_safest_resolve_baseline.sql +0 -1
- package/template/migrations/0002_playbook_publication_evidence.sql +36 -0
- package/template/migrations/0003_action_confirmation.sql +24 -0
- package/template/migrations/0004_notice_recovery.sql +22 -0
- package/template/migrations/0005_appeal_continuity.sql +17 -0
- package/template/migrations/0006_case_ownership.sql +23 -0
- package/template/migrations/0007_integration_verification.sql +21 -0
- package/template/migrations/0008_case_escalations.sql +135 -0
- package/template/migrations/0009_participant_continuation.sql +61 -0
- package/template/migrations/0010_appeal_corrections.sql +41 -0
- package/template/npm-shrinkwrap.json +8036 -0
- package/template/package.json +31 -22
- package/template/public/_headers +16 -1
- package/template/public/console/auth-shell.js +22151 -14847
- package/template/public/console/release.json +1 -0
- package/template/public/console/workspace-features.css +2 -0
- package/template/public/embed/embed.css +3 -0
- package/template/public/embed/embed.js +19 -1
- package/template/public/embed/index.html +2 -0
- package/template/public/index.html +9 -6
- package/template/public/participant.css +2 -0
- package/template/public/participant.html +13 -0
- package/template/public/participant.js +111 -0
- package/template/public/public-report.js +21 -1
- package/template/public/report/index.html +1 -1
- package/template/public/styles.css +599 -83
- package/template/public/workspace.css +124 -0
- package/template/scripts/reports-plan.mjs +1 -1
- package/template/shared/case-escalations.ts +31 -0
- package/template/shared/integration-progress.ts +27 -0
- package/template/shared/notice-inputs.ts +3 -0
- package/template/shared/playbook-resources.ts +14 -0
- package/template/shared/playbooks.ts +249 -0
- package/template/src/agent-executor.ts +25 -8
- package/template/src/ai-observability.ts +14 -13
- package/template/src/ai-registry-validation.ts +1 -1
- package/template/src/appeal-continuity.ts +75 -0
- package/template/src/appeal-correction-state.ts +46 -0
- package/template/src/appeal-corrections.ts +112 -0
- package/template/src/appeal-decisions.ts +85 -0
- package/template/src/assistant.ts +3 -4
- package/template/src/case-escalations.ts +223 -0
- package/template/src/case-investigator.ts +179 -0
- package/template/src/component-executor.ts +5 -4
- package/template/src/configuration-registry.ts +4 -1
- package/template/src/connection-oauth.ts +12 -3
- package/template/src/database-readiness.ts +14 -0
- package/template/src/human-tasks.ts +152 -55
- package/template/src/index.ts +191 -29
- package/template/src/installation-admin.ts +2 -1
- package/template/src/integration-progress.ts +45 -0
- package/template/src/integration-verification.ts +249 -0
- package/template/src/investigation-evidence.ts +95 -0
- package/template/src/investigator-fixture.ts +30 -0
- package/template/src/notice-delivery.ts +19 -0
- package/template/src/notice-recovery.ts +81 -0
- package/template/src/operator-scope.ts +31 -0
- package/template/src/participant-access.ts +163 -0
- package/template/src/participant-case.ts +87 -0
- package/template/src/participant-customer-access.ts +93 -0
- package/template/src/participant-recovery.ts +43 -0
- package/template/src/participant-routes.ts +67 -0
- package/template/src/platform-registry-validation.ts +25 -2
- package/template/src/platform-registry.ts +10 -7
- package/template/src/playbook-resources.ts +58 -0
- package/template/src/report-admin.ts +9 -2
- package/template/src/report-auth.ts +1 -28
- package/template/src/report-better-auth.ts +18 -6
- package/template/src/report-delivery.ts +149 -148
- package/template/src/report-email-inbound.ts +33 -22
- package/template/src/report-email-template.ts +5 -2
- package/template/src/report-email.ts +7 -30
- package/template/src/report-governance.ts +42 -45
- package/template/src/report-http.ts +37 -2
- package/template/src/report-operations.ts +30 -67
- package/template/src/report-operator-accounts.ts +7 -6
- package/template/src/report-ownership.ts +64 -0
- package/template/src/report-presence.ts +15 -9
- package/template/src/report-repository.ts +16 -7
- package/template/src/report-turnstile.ts +7 -3
- package/template/src/report-types.ts +1 -0
- package/template/src/report-workflow.ts +183 -249
- package/template/src/workflow-actions.ts +248 -156
- package/template/src/workflow-compiler.ts +63 -12
- package/template/src/workflow-dynamic-runtime.ts +20 -9
- package/template/src/workflow-effects.ts +117 -39
- package/template/src/workflow-event-transport.ts +16 -0
- package/template/src/workflow-expressions.ts +30 -0
- package/template/src/workflow-loader-code.ts +21 -0
- package/template/src/workflow-platform-types.ts +3 -0
- package/template/src/workflow-platform-validation.ts +23 -1
- package/template/src/workflow-repository.ts +131 -28
- package/template/src/workflow-runs.ts +61 -13
- package/template/src/workflow-simulator.ts +7 -4
- package/template/src/workspace-governance.ts +6 -4
- package/template/tsconfig.json +1 -0
- package/template/vite.console.config.ts +30 -2
- package/template/worker-configuration.d.ts +3 -2
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
validateWorkflowGraph,
|
|
13
13
|
} from "./workflow-platform-validation";
|
|
14
14
|
|
|
15
|
-
export const WORKFLOW_COMPILER_VERSION = "safest-workflow-compiler-
|
|
15
|
+
export const WORKFLOW_COMPILER_VERSION = "safest-workflow-compiler-v5";
|
|
16
16
|
|
|
17
17
|
function dynamicWorkerSource(graph: WorkflowGraphV1, authorityMode: WorkflowAuthorityMode): string {
|
|
18
18
|
const graphJson = canonicalJson(graphForStorage(graph));
|
|
@@ -26,6 +26,11 @@ const OUTGOING = new Map();
|
|
|
26
26
|
for (const node of GRAPH.nodes) OUTGOING.set(node.id, []);
|
|
27
27
|
for (const edge of GRAPH.edges) OUTGOING.get(edge.from.node_id).push(edge);
|
|
28
28
|
|
|
29
|
+
async function transportEventType(logicalType) {
|
|
30
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(logicalType));
|
|
31
|
+
return "ev_" + Array.from(new Uint8Array(digest), value => value.toString(16).padStart(2, "0")).join("");
|
|
32
|
+
}
|
|
33
|
+
|
|
29
34
|
function nextNode(node, result) {
|
|
30
35
|
const edges = OUTGOING.get(node.id) || [];
|
|
31
36
|
if (!edges.length) return null;
|
|
@@ -85,7 +90,7 @@ export class TenantWorkflow extends WorkflowEntrypoint {
|
|
|
85
90
|
let eventResult;
|
|
86
91
|
try {
|
|
87
92
|
const received = await step.waitForEvent("node:" + node.id + ":wait", {
|
|
88
|
-
type: prepared.eventType,
|
|
93
|
+
type: await transportEventType(prepared.eventType),
|
|
89
94
|
timeout: prepared.timeoutMs,
|
|
90
95
|
});
|
|
91
96
|
eventResult = { status: "received", event: received.payload };
|
|
@@ -101,14 +106,14 @@ export class TenantWorkflow extends WorkflowEntrypoint {
|
|
|
101
106
|
if (node.kind === "action") {
|
|
102
107
|
try {
|
|
103
108
|
const prepared = await step.do("node:" + node.id + ":prepare", stepConfig(node), async () => this.env.RUNTIME.prepareAction({
|
|
104
|
-
runId, nodeId: node.id, nodeKind: node.kind, branchKey, authorityMode: AUTHORITY_MODE,
|
|
109
|
+
runId, nodeId: node.id, nodeKind: node.kind, branchKey, authorityMode: AUTHORITY_MODE, awaitRecovery: Boolean(GRAPH.playbook),
|
|
105
110
|
}));
|
|
106
111
|
let actionResult = prepared;
|
|
107
112
|
if (prepared.status === "approval_required") {
|
|
108
113
|
let eventResult;
|
|
109
114
|
try {
|
|
110
115
|
const received = await step.waitForEvent("node:" + node.id + ":approval", {
|
|
111
|
-
type: prepared.eventType,
|
|
116
|
+
type: await transportEventType(prepared.eventType),
|
|
112
117
|
timeout: prepared.timeoutMs,
|
|
113
118
|
});
|
|
114
119
|
eventResult = { status: "received", event: received.payload };
|
|
@@ -117,27 +122,27 @@ export class TenantWorkflow extends WorkflowEntrypoint {
|
|
|
117
122
|
}
|
|
118
123
|
actionResult = await step.do("node:" + node.id + ":approval-complete", stepConfig(node), async () => this.env.RUNTIME.completeAction({
|
|
119
124
|
runId, nodeId: node.id, nodeKind: node.kind, branchKey,
|
|
120
|
-
authorityMode: AUTHORITY_MODE, proposalId: prepared.proposalId, eventResult,
|
|
125
|
+
authorityMode: AUTHORITY_MODE, proposalId: prepared.proposalId, eventResult, awaitRecovery: Boolean(GRAPH.playbook),
|
|
121
126
|
}));
|
|
122
127
|
}
|
|
123
|
-
|
|
128
|
+
for (let delivery = 0; actionResult.status === "delivery_pending" && delivery < 16; delivery++) {
|
|
124
129
|
let deliveryResult;
|
|
125
130
|
try {
|
|
126
|
-
const received = await step.waitForEvent("node:" + node.id + ":delivery", {
|
|
127
|
-
type: actionResult.eventType,
|
|
131
|
+
const received = await step.waitForEvent("node:" + node.id + ":delivery:" + delivery, {
|
|
132
|
+
type: await transportEventType(actionResult.eventType),
|
|
128
133
|
timeout: actionResult.timeoutMs,
|
|
129
134
|
});
|
|
130
135
|
deliveryResult = { status: "received", event: received.payload };
|
|
131
136
|
} catch (error) {
|
|
132
137
|
deliveryResult = { status: "timed_out" };
|
|
133
138
|
}
|
|
134
|
-
|
|
139
|
+
actionResult = await step.do("node:" + node.id + ":delivery-complete:" + delivery, async () => this.env.RUNTIME.completeAction({
|
|
135
140
|
runId, nodeId: node.id, nodeKind: node.kind, branchKey,
|
|
136
|
-
authorityMode: AUTHORITY_MODE, proposalId: actionResult.proposalId, eventResult: deliveryResult,
|
|
141
|
+
authorityMode: AUTHORITY_MODE, proposalId: actionResult.proposalId, eventResult: deliveryResult, awaitRecovery: Boolean(GRAPH.playbook),
|
|
137
142
|
}));
|
|
138
|
-
} else {
|
|
139
|
-
last = actionResult;
|
|
140
143
|
}
|
|
144
|
+
if (actionResult.status === "delivery_pending") throw new Error("action_recovery_limit");
|
|
145
|
+
last = actionResult;
|
|
141
146
|
} catch (error) {
|
|
142
147
|
last = await step.do("node:" + node.id + ":failure", async () => this.env.RUNTIME.failNode({
|
|
143
148
|
runId, nodeId: node.id, nodeKind: node.kind, branchKey,
|
|
@@ -147,6 +152,30 @@ export class TenantWorkflow extends WorkflowEntrypoint {
|
|
|
147
152
|
nodeId = nextNode(node, last);
|
|
148
153
|
continue;
|
|
149
154
|
}
|
|
155
|
+
if (node.kind === "send_message" && GRAPH.playbook && AUTHORITY_MODE !== "shadow") {
|
|
156
|
+
try {
|
|
157
|
+
for (let delivery = 0; delivery <= 96; delivery++) {
|
|
158
|
+
last = await step.do("node:" + node.id + ":notice:" + delivery, stepConfig(node), async () => this.env.RUNTIME.executeNode({
|
|
159
|
+
runId, nodeId: node.id, nodeKind: node.kind, branchKey, authorityMode: AUTHORITY_MODE, input: { notice_delivery: true },
|
|
160
|
+
}));
|
|
161
|
+
if (!last.pending) break;
|
|
162
|
+
if (delivery === 96) throw new Error("notice_recovery_limit");
|
|
163
|
+
try {
|
|
164
|
+
await step.waitForEvent("node:" + node.id + ":notice-wait:" + delivery, {
|
|
165
|
+
type: await transportEventType(last.eventType), timeout: last.timeoutMs,
|
|
166
|
+
});
|
|
167
|
+
} catch (error) {
|
|
168
|
+
// Re-read the saved delivery receipt; an event is only a wake-up.
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
} catch (error) {
|
|
172
|
+
last = await step.do("node:" + node.id + ":notice-failure", async () => this.env.RUNTIME.failNode({
|
|
173
|
+
runId, nodeId: node.id, nodeKind: node.kind, branchKey, authorityMode: AUTHORITY_MODE, errorCode: "notice_delivery_incomplete",
|
|
174
|
+
}));
|
|
175
|
+
}
|
|
176
|
+
nodeId = nextNode(node, last);
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
150
179
|
if (node.kind === "delay") {
|
|
151
180
|
await step.sleep("node:" + node.id + ":delay", node.config.duration_seconds * 1000);
|
|
152
181
|
last = await step.do("node:" + node.id + ":complete", async () => this.env.RUNTIME.executeNode({
|
|
@@ -169,6 +198,24 @@ export class TenantWorkflow extends WorkflowEntrypoint {
|
|
|
169
198
|
nodeId = nextNode(node, last);
|
|
170
199
|
continue;
|
|
171
200
|
}
|
|
201
|
+
if (node.kind === "ai_proposal" && node.config.investigator === true) {
|
|
202
|
+
try {
|
|
203
|
+
for (let poll = 0; poll < 40; poll++) {
|
|
204
|
+
last = await step.do("node:" + node.id + ":investigation:" + poll, stepConfig(node), async () => this.env.RUNTIME.executeNode({
|
|
205
|
+
runId, nodeId: node.id, nodeKind: node.kind, branchKey, authorityMode: AUTHORITY_MODE, input: { investigation_poll: true },
|
|
206
|
+
}));
|
|
207
|
+
if (!last.pending) break;
|
|
208
|
+
await step.sleep("node:" + node.id + ":investigation-wait:" + poll, 5000);
|
|
209
|
+
}
|
|
210
|
+
if (last.pending) throw new Error("investigation_time_limit");
|
|
211
|
+
} catch (error) {
|
|
212
|
+
last = await step.do("node:" + node.id + ":investigation-failure", async () => this.env.RUNTIME.failNode({
|
|
213
|
+
runId, nodeId: node.id, nodeKind: node.kind, branchKey, authorityMode: AUTHORITY_MODE, errorCode: "investigation_incomplete",
|
|
214
|
+
}));
|
|
215
|
+
}
|
|
216
|
+
nodeId = nextNode(node, last);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
172
219
|
try {
|
|
173
220
|
last = await step.do("node:" + node.id, stepConfig(node), async () => this.env.RUNTIME.executeNode({
|
|
174
221
|
runId, nodeId: node.id, nodeKind: node.kind, branchKey, authorityMode: AUTHORITY_MODE,
|
|
@@ -210,6 +257,10 @@ export async function compileWorkflowGraph(
|
|
|
210
257
|
warnings: validation.warnings,
|
|
211
258
|
});
|
|
212
259
|
}
|
|
260
|
+
const maximumSteps = graph.nodes.length * 3 + graph.nodes.filter(node => node.kind === "action").length * 36
|
|
261
|
+
+ graph.nodes.filter(node => node.kind === "ai_proposal" && node.config.investigator === true).length * 42
|
|
262
|
+
+ (graph.playbook ? graph.nodes.filter(node => node.kind === "send_message").length * 194 : 0);
|
|
263
|
+
if (maximumSteps > 950) throw new ApiError(400, "workflow_step_budget_exceeded", "This playbook needs more recovery steps than the configured runtime supports. Split it into smaller playbooks.");
|
|
213
264
|
const source = dynamicWorkerSource(graph, authorityMode);
|
|
214
265
|
const graphDigest = `sha256:${await sha256(canonicalWorkflowGraph(graph))}`;
|
|
215
266
|
const sourceDigest = `sha256:${await sha256(source)}`;
|
|
@@ -17,11 +17,13 @@ import { evaluateInputMapping, evaluateWorkflowExpression } from "./workflow-exp
|
|
|
17
17
|
import {
|
|
18
18
|
handoffWorkflowReport,
|
|
19
19
|
recordWorkflowDecision,
|
|
20
|
+
completePlaybookOutcome,
|
|
20
21
|
sendWorkflowMessage,
|
|
21
22
|
WorkflowEffectError,
|
|
22
23
|
} from "./workflow-effects";
|
|
23
24
|
import { completeWorkflowAction, prepareWorkflowAction } from "./workflow-actions";
|
|
24
25
|
import { createLinkedWorkflowRun } from "./workflow-runs";
|
|
26
|
+
import { dynamicWorkflowWorkerModule } from "./workflow-loader-code";
|
|
25
27
|
import { parseWorkflowGraph } from "./workflow-platform-validation";
|
|
26
28
|
import type { JsonObject, JsonValue, WorkflowAuthorityMode, WorkflowGraphV1, WorkflowNodeV1 } from "./workflow-platform-types";
|
|
27
29
|
|
|
@@ -58,10 +60,12 @@ interface RuntimeCompleteWaitRequest {
|
|
|
58
60
|
}
|
|
59
61
|
|
|
60
62
|
interface RuntimeActionRequest extends RuntimeNodeRequest {
|
|
63
|
+
awaitRecovery?: boolean;
|
|
61
64
|
nodeKind: "action";
|
|
62
65
|
}
|
|
63
66
|
|
|
64
67
|
interface RuntimeCompleteActionRequest extends RuntimeActionRequest {
|
|
68
|
+
awaitRecovery?: boolean;
|
|
65
69
|
proposalId: string;
|
|
66
70
|
eventResult: { status: "received"; event: unknown } | { status: "timed_out" };
|
|
67
71
|
}
|
|
@@ -127,8 +131,7 @@ async function loadCompiledWorkflow(env: Env, ctx: ExecutionContext, metadata: R
|
|
|
127
131
|
const artifact = await artifactRow(env, metadata.artifactId, metadata.workflowVersionId);
|
|
128
132
|
const stub = env.LOADER.get(`workflow-version:${metadata.workflowVersionId}`, async () => ({
|
|
129
133
|
compatibilityDate: artifact.compatibilityDate,
|
|
130
|
-
|
|
131
|
-
modules: { "workflow.mjs": await artifactSource(env, artifact) },
|
|
134
|
+
...dynamicWorkflowWorkerModule(await artifactSource(env, artifact)),
|
|
132
135
|
env: {
|
|
133
136
|
WORKFLOWS: wrapWorkflowBinding({
|
|
134
137
|
artifactId: metadata.artifactId,
|
|
@@ -316,9 +319,10 @@ async function recordDelayPreparation(
|
|
|
316
319
|
INSERT OR IGNORE INTO audit_events (
|
|
317
320
|
id, idempotency_key, action, actor_type, actor_id,
|
|
318
321
|
target_type, target_id, details_json, created_at
|
|
319
|
-
) VALUES (?1, ?2,
|
|
322
|
+
) VALUES (?1, ?2, ?6, 'system', 'workflow-runtime',
|
|
320
323
|
'workflow_run', ?3, ?4, ?5)
|
|
321
|
-
`).bind(crypto.randomUUID(), `workflow-
|
|
324
|
+
`).bind(crypto.randomUUID(), `workflow-wait:${id}`, run.id, canonicalJson({ nodeId: node.id, resumeAt: timestamp }), updatedAt,
|
|
325
|
+
node.kind === "send_message" ? "workflow.notice_delivery_waiting" : "workflow.delay_scheduled"),
|
|
322
326
|
]);
|
|
323
327
|
}
|
|
324
328
|
|
|
@@ -341,12 +345,13 @@ export class WorkflowRuntimeCapability extends WorkerEntrypoint<Env, RuntimeProp
|
|
|
341
345
|
});
|
|
342
346
|
} else if (node.kind === "ai_proposal") {
|
|
343
347
|
const executionInput = {
|
|
344
|
-
runId: run.id, node, branchKey,
|
|
348
|
+
runId: run.id, node, branchKey, investigationPoll: input.input?.investigation_poll === true,
|
|
345
349
|
stepRunId: stepRunId(run.id, node.id, branchKey),
|
|
346
350
|
};
|
|
347
351
|
const executed = typeof node.config.component_version_id === "string"
|
|
348
352
|
? await executeReadOnlyComponent(this.env, executionInput)
|
|
349
353
|
: await executeAgentProposal(this.env, executionInput);
|
|
354
|
+
if (executed.pending === true) return executed;
|
|
350
355
|
const data = executed.data && typeof executed.data === "object" && !Array.isArray(executed.data)
|
|
351
356
|
? executed.data as Record<string, unknown> : {};
|
|
352
357
|
const resultCode = [data.result_code, data.outcome, data.conclusion, data.classification]
|
|
@@ -358,7 +363,11 @@ export class WorkflowRuntimeCapability extends WorkerEntrypoint<Env, RuntimeProp
|
|
|
358
363
|
} else if (node.kind === "condition") {
|
|
359
364
|
output = await executeCondition(this.env, run, node, branchKey);
|
|
360
365
|
} else if (node.kind === "send_message") {
|
|
361
|
-
output = await sendWorkflowMessage(this.env, { runId: run.id, node, branchKey });
|
|
366
|
+
output = await sendWorkflowMessage(this.env, { runId: run.id, node, branchKey, awaitDelivery: input.input?.notice_delivery === true });
|
|
367
|
+
if (output.pending === true) {
|
|
368
|
+
await recordDelayPreparation(this.env, run, node, branchKey, new Date(Date.now() + Number(output.timeoutMs)).toISOString());
|
|
369
|
+
return output;
|
|
370
|
+
}
|
|
362
371
|
} else if (node.kind === "decision") {
|
|
363
372
|
output = await recordWorkflowDecision(this.env, { runId: run.id, node, branchKey });
|
|
364
373
|
} else if (node.kind === "handoff") {
|
|
@@ -397,6 +406,7 @@ export class WorkflowRuntimeCapability extends WorkerEntrypoint<Env, RuntimeProp
|
|
|
397
406
|
throw error;
|
|
398
407
|
}
|
|
399
408
|
}
|
|
409
|
+
if (node.kind === "end" && run.graph.playbook && node.config.terminal_code === "resolved") await completePlaybookOutcome(this.env, run.id);
|
|
400
410
|
await recordSuccessfulStep(this.env, run, node, branchKey, output);
|
|
401
411
|
if (node.kind === "end") {
|
|
402
412
|
const timestamp = now();
|
|
@@ -457,8 +467,8 @@ export class WorkflowRuntimeCapability extends WorkerEntrypoint<Env, RuntimeProp
|
|
|
457
467
|
`).bind(
|
|
458
468
|
taskId, id, String(node.config.task_type ?? "review"),
|
|
459
469
|
typeof node.config.queue_id === "string" && node.config.queue_id !== "run-queue" ? node.config.queue_id : null,
|
|
460
|
-
canonicalJson({ nodeId: node.id, inputMapping: node.inputMapping }),
|
|
461
|
-
`sha256:${await sha256(canonicalJson({ nodeId: node.id, inputMapping: node.inputMapping }))}`,
|
|
470
|
+
canonicalJson({ nodeId: node.id, title: node.name, instructions: typeof node.config.instructions === "string" ? node.config.instructions : "", inputMapping: node.inputMapping }),
|
|
471
|
+
`sha256:${await sha256(canonicalJson({ nodeId: node.id, title: node.name, instructions: typeof node.config.instructions === "string" ? node.config.instructions : "", inputMapping: node.inputMapping }))}`,
|
|
462
472
|
canonicalJson(node.config.response_schema ?? { type: "object" }), deadlineAt, timestamp, run.id,
|
|
463
473
|
));
|
|
464
474
|
}
|
|
@@ -494,6 +504,7 @@ export class WorkflowRuntimeCapability extends WorkerEntrypoint<Env, RuntimeProp
|
|
|
494
504
|
branchKey,
|
|
495
505
|
stepRunId: id,
|
|
496
506
|
authorityMode: run.authorityMode,
|
|
507
|
+
awaitRecovery: input.awaitRecovery === true,
|
|
497
508
|
});
|
|
498
509
|
if (result.status === "approval_required" || result.status === "delivery_pending") {
|
|
499
510
|
await this.env.DB.batch([
|
|
@@ -513,7 +524,7 @@ export class WorkflowRuntimeCapability extends WorkerEntrypoint<Env, RuntimeProp
|
|
|
513
524
|
const branchKey = input.branchKey ? cleanIdentifier(input.branchKey, "branch_key", 100) : "";
|
|
514
525
|
const expectedProposalId = `${stepRunId(run.id, node.id, branchKey)}:proposal`;
|
|
515
526
|
if (cleanIdentifier(input.proposalId, "proposal_id", 500) !== expectedProposalId) throw new Error("action_proposal_denied");
|
|
516
|
-
const result = await completeWorkflowAction(this.env, { proposalId: expectedProposalId, eventResult: input.eventResult });
|
|
527
|
+
const result = await completeWorkflowAction(this.env, { proposalId: expectedProposalId, eventResult: input.eventResult, awaitRecovery: input.awaitRecovery === true });
|
|
517
528
|
if (result.status === "delivery_pending") {
|
|
518
529
|
const timestamp = now();
|
|
519
530
|
await this.env.DB.batch([
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { parsePlaybook } from "../shared/playbooks";
|
|
1
2
|
import { canonicalJson } from "./audit";
|
|
2
3
|
import { loadWorkflowExecutionContext } from "./component-executor";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
4
|
+
import { sha256 } from "./report-crypto";
|
|
5
|
+
import { reporterEmailConfigured, selectParticipantDelivery } from "./report-email";
|
|
5
6
|
import type { DeliveryJob } from "./report-types";
|
|
6
7
|
import { evaluateInputMapping } from "./workflow-expressions";
|
|
7
8
|
import type { JsonObject, JsonValue, WorkflowNodeV1 } from "./workflow-platform-types";
|
|
@@ -18,6 +19,9 @@ interface EffectRunRow {
|
|
|
18
19
|
reportState: string;
|
|
19
20
|
policyVersionId: string | null;
|
|
20
21
|
locale: string;
|
|
22
|
+
playbookJson: string | null;
|
|
23
|
+
runKind: string;
|
|
24
|
+
compilerVersion: string;
|
|
21
25
|
}
|
|
22
26
|
|
|
23
27
|
export class WorkflowEffectError extends Error {
|
|
@@ -34,11 +38,12 @@ function now(): string {
|
|
|
34
38
|
async function effectRun(db: D1Database, runId: string): Promise<EffectRunRow> {
|
|
35
39
|
const row = await db.prepare(`
|
|
36
40
|
SELECT wr.id, wr.installation_id AS installationId, wr.report_id AS reportId,
|
|
37
|
-
wr.workflow_version_id AS workflowVersionId, wr.authority_mode AS authorityMode,
|
|
41
|
+
wr.workflow_version_id AS workflowVersionId, wr.authority_mode AS authorityMode, wr.run_kind AS runKind,
|
|
38
42
|
wr.queue_id AS queueId, wr.queue_version_id AS queueVersionId,
|
|
39
43
|
r.public_reference AS publicReference, r.state AS reportState,
|
|
40
|
-
r.policy_version_id AS policyVersionId, r.locale
|
|
41
|
-
FROM workflow_runs wr JOIN reports r ON r.id = wr.report_id
|
|
44
|
+
r.policy_version_id AS policyVersionId, r.locale, json_extract(wv.graph_json, '$.playbook') AS playbookJson, wv.compiler_version AS compilerVersion
|
|
45
|
+
FROM workflow_runs wr JOIN reports r ON r.id = wr.report_id
|
|
46
|
+
JOIN workflow_versions wv ON wv.id = wr.workflow_version_id WHERE wr.id = ?1 LIMIT 1
|
|
42
47
|
`).bind(runId).first<EffectRunRow>();
|
|
43
48
|
if (!row) throw new WorkflowEffectError("workflow_effect_context_missing");
|
|
44
49
|
return row;
|
|
@@ -64,7 +69,7 @@ function renderTemplate(template: string, variables: JsonObject): string {
|
|
|
64
69
|
|
|
65
70
|
export async function sendWorkflowMessage(
|
|
66
71
|
env: Env,
|
|
67
|
-
input: { runId: string; node: WorkflowNodeV1; branchKey: string },
|
|
72
|
+
input: { runId: string; node: WorkflowNodeV1; branchKey: string; awaitDelivery?: boolean },
|
|
68
73
|
): Promise<Record<string, unknown>> {
|
|
69
74
|
const run = await effectRun(env.DB, input.runId);
|
|
70
75
|
if (run.authorityMode === "shadow") throw new WorkflowEffectError("shadow_effect_prohibited");
|
|
@@ -72,9 +77,15 @@ export async function sendWorkflowMessage(
|
|
|
72
77
|
const templateVersionId = typeof input.node.config.template_version_id === "string" ? input.node.config.template_version_id : null;
|
|
73
78
|
if (!audience || !["reporter", "affected_user", "internal"].includes(audience) || !templateVersionId) throw new WorkflowEffectError("workflow_message_configuration_invalid");
|
|
74
79
|
const operationKey = `workflow-message:${run.id}:${input.node.id}:${input.branchKey || "main"}`;
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
80
|
+
const result = (messageId: string, deliveryState: string, createdAt: string, idempotentReplay: boolean) => {
|
|
81
|
+
if (!input.awaitDelivery || ["delivered", "not_required"].includes(deliveryState)) return { port: "sent", messageId, deliveryState, idempotentReplay };
|
|
82
|
+
const remaining = Date.parse(createdAt) + 86_400_000 - Date.now();
|
|
83
|
+
if (remaining <= 0) return { port: "error", messageId, deliveryState, errorCode: "notice_delivery_unconfirmed" };
|
|
84
|
+
return { pending: true, messageId, deliveryState, eventType: `notice.${messageId}.updated`, timeoutMs: Math.max(1000, Math.min(900_000, remaining)), recoveryRequired: ["failed", "suppressed"].includes(deliveryState) };
|
|
85
|
+
};
|
|
86
|
+
const existing = await env.DB.prepare(`SELECT id, delivery_state AS deliveryState, created_at AS createdAt FROM case_messages WHERE report_id = ?1 AND idempotency_key = ?2 LIMIT 1`)
|
|
87
|
+
.bind(run.reportId, operationKey).first<{ id: string; deliveryState: string; createdAt: string }>();
|
|
88
|
+
if (existing) return result(existing.id, existing.deliveryState, existing.createdAt, true);
|
|
78
89
|
const context = await loadWorkflowExecutionContext(env, run.id, input.branchKey);
|
|
79
90
|
const variables = evaluateInputMapping(input.node.inputMapping, context.context);
|
|
80
91
|
let body: string;
|
|
@@ -97,21 +108,22 @@ export async function sendWorkflowMessage(
|
|
|
97
108
|
const deliveryChannels = Array.isArray(input.node.config.delivery_channels)
|
|
98
109
|
? input.node.config.delivery_channels.filter((entry): entry is string => typeof entry === "string")
|
|
99
110
|
: audience === "internal" ? [] : ["customer_webhook", "email"];
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
111
|
+
const delivery = audience !== "internal" && participant
|
|
112
|
+
? await selectParticipantDelivery({
|
|
113
|
+
reportId: run.reportId,
|
|
114
|
+
audience: audience as "reporter" | "affected_user",
|
|
115
|
+
contactMode: participant.contactMode,
|
|
116
|
+
contactCiphertext: participant.contactCiphertext,
|
|
117
|
+
reference: participant.reference,
|
|
118
|
+
emailEnabled: deliveryChannels.includes("email") && reporterEmailConfigured(env),
|
|
119
|
+
notificationEnabled: deliveryChannels.includes("customer_webhook") && Boolean(
|
|
120
|
+
env.NOTIFICATION_WEBHOOK_URL?.trim() && env.NOTIFICATION_WEBHOOK_SECRET?.trim(),
|
|
121
|
+
),
|
|
122
|
+
contactEncryptionKey: env.CREDENTIAL_ENCRYPTION_KEY,
|
|
123
|
+
recipientHashPepper: env.RATE_LIMIT_PEPPER,
|
|
124
|
+
})
|
|
125
|
+
: { channel: null, state: "suppressed" } as const;
|
|
126
|
+
const externalDeliveryEnabled = delivery.state === "queued";
|
|
115
127
|
const messageId = crypto.randomUUID();
|
|
116
128
|
const conversationId = `conversation:${audience}:${run.reportId}`;
|
|
117
129
|
const timestamp = now();
|
|
@@ -136,17 +148,20 @@ export async function sendWorkflowMessage(
|
|
|
136
148
|
];
|
|
137
149
|
let job: DeliveryJob | null = null;
|
|
138
150
|
if (audience !== "internal") {
|
|
151
|
+
const decision = await env.DB.prepare(`SELECT id FROM decisions WHERE report_id = ?1 AND substr(idempotency_key, 1, length(?2)) = ?2 ORDER BY created_at DESC, rowid DESC LIMIT 1`)
|
|
152
|
+
.bind(run.reportId, `workflow-decision:${run.id}:`).first<{ id: string }>();
|
|
153
|
+
if (input.awaitDelivery && run.playbookJson && !decision) throw new WorkflowEffectError("notice_decision_missing");
|
|
139
154
|
const noticeId = crypto.randomUUID();
|
|
140
155
|
statements.push(env.DB.prepare(`
|
|
141
156
|
INSERT INTO notices (
|
|
142
157
|
id, report_id, audience, template_version_id, rendered_body,
|
|
143
|
-
delivery_state, created_at, updated_at, idempotency_key, message_id
|
|
144
|
-
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7, ?8, ?9)
|
|
158
|
+
delivery_state, created_at, updated_at, idempotency_key, message_id, decision_id
|
|
159
|
+
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7, ?8, ?9, ?10)
|
|
145
160
|
`).bind(
|
|
146
161
|
noticeId, run.reportId, audience, templateVersionId, body,
|
|
147
|
-
externalDeliveryEnabled ? "queued" : "suppressed", timestamp, operationKey, messageId,
|
|
162
|
+
externalDeliveryEnabled ? "queued" : "suppressed", timestamp, operationKey, messageId, decision?.id ?? null,
|
|
148
163
|
));
|
|
149
|
-
if (
|
|
164
|
+
if (delivery.channel === "email" && delivery.recipientHash) {
|
|
150
165
|
const emailDeliveryId = crypto.randomUUID();
|
|
151
166
|
statements.push(env.DB.prepare(`
|
|
152
167
|
INSERT INTO email_deliveries (
|
|
@@ -155,11 +170,11 @@ export async function sendWorkflowMessage(
|
|
|
155
170
|
) VALUES (?1, ?2, ?3, ?4, ?5, 'cloudflare_email_service', 'pending', 0, ?6, ?6, ?6)
|
|
156
171
|
`).bind(
|
|
157
172
|
emailDeliveryId, run.installationId, messageId, audience,
|
|
158
|
-
|
|
173
|
+
delivery.recipientHash,
|
|
159
174
|
timestamp,
|
|
160
175
|
));
|
|
161
176
|
job = { version: 1, jobId: `email:${emailDeliveryId}`, type: "deliver_email", outboxId: emailDeliveryId };
|
|
162
|
-
} else if (
|
|
177
|
+
} else if (delivery.channel === "customer_webhook" && participant) {
|
|
163
178
|
const notificationId = crypto.randomUUID();
|
|
164
179
|
statements.push(env.DB.prepare(`
|
|
165
180
|
INSERT INTO notification_outbox (
|
|
@@ -172,6 +187,7 @@ export async function sendWorkflowMessage(
|
|
|
172
187
|
notification_id: notificationId,
|
|
173
188
|
report_reference: run.publicReference,
|
|
174
189
|
...(participant.reference ? { recipient_reference: participant.reference } : {}),
|
|
190
|
+
recipient_contact_fingerprint: participant.contactCiphertext ? await sha256(participant.contactCiphertext) : null,
|
|
175
191
|
audience,
|
|
176
192
|
message: body,
|
|
177
193
|
}), timestamp));
|
|
@@ -185,11 +201,11 @@ export async function sendWorkflowMessage(
|
|
|
185
201
|
) VALUES (?1, ?2, 'workflow.message_created', 'system', ?3, 'message', ?4, ?5, ?6)
|
|
186
202
|
`).bind(crypto.randomUUID(), operationKey, run.id, messageId, canonicalJson({
|
|
187
203
|
reportId: run.reportId, audience, templateVersionId,
|
|
188
|
-
deliveryChannels,
|
|
204
|
+
deliveryChannels, deliveryChannel: delivery.channel, deliveryState: delivery.state,
|
|
189
205
|
}), timestamp));
|
|
190
206
|
await env.DB.batch(statements);
|
|
191
207
|
if (job) await env.DELIVERY_JOBS.send(job, { contentType: "json" }).catch(() => {});
|
|
192
|
-
return
|
|
208
|
+
return result(messageId, audience === "internal" ? "not_required" : externalDeliveryEnabled ? "queued" : "suppressed", timestamp, false);
|
|
193
209
|
}
|
|
194
210
|
|
|
195
211
|
function stringList(value: JsonValue | undefined, code: string): string[] {
|
|
@@ -209,7 +225,8 @@ export async function recordWorkflowDecision(
|
|
|
209
225
|
if (existing) return { port: "recorded", decisionId: existing.id, decisionCode: existing.decisionCode, idempotentReplay: true };
|
|
210
226
|
const policyVersionId = typeof input.node.config.policy_version_id === "string" ? input.node.config.policy_version_id : null;
|
|
211
227
|
if (!policyVersionId || policyVersionId !== run.policyVersionId) throw new WorkflowEffectError("workflow_decision_policy_mismatch");
|
|
212
|
-
|
|
228
|
+
const policy = await env.DB.prepare(`SELECT id, rules_json AS rulesJson FROM policy_versions WHERE id = ?1 AND published_at IS NOT NULL`).bind(policyVersionId).first<{ id: string; rulesJson: string }>();
|
|
229
|
+
if (!policy) {
|
|
213
230
|
throw new WorkflowEffectError("workflow_decision_policy_unavailable");
|
|
214
231
|
}
|
|
215
232
|
const context = await loadWorkflowExecutionContext(env, run.id, input.branchKey);
|
|
@@ -231,10 +248,35 @@ export async function recordWorkflowDecision(
|
|
|
231
248
|
if (evidenceReferences.some((entry) => !evidenceSet.has(entry)) || findingIds.some((entry) => !findingSet.has(entry))) {
|
|
232
249
|
throw new WorkflowEffectError("workflow_decision_evidence_not_visible");
|
|
233
250
|
}
|
|
251
|
+
let makerType = "ai";
|
|
252
|
+
let makerId = `workflow:${run.id}`;
|
|
253
|
+
if (run.playbookJson) {
|
|
254
|
+
const guide = parsePlaybook(JSON.parse(run.playbookJson));
|
|
255
|
+
const rules = JSON.parse(policy.rulesJson) as { code?: string }[];
|
|
256
|
+
if ((guide.editing_mode === "guided" && !guide.outcomes.decision_codes.includes(decisionCode)) || !Array.isArray(rules) || !rules.some(rule => rule.code === policyCode)) throw new WorkflowEffectError("playbook_decision_policy_invalid");
|
|
257
|
+
const steps = context.context.steps as JsonObject | undefined;
|
|
258
|
+
const review = steps?.review as JsonObject | undefined;
|
|
259
|
+
const event = review?.event as JsonObject | undefined;
|
|
260
|
+
const responseId = mapped.review_response_id ?? event?.response_id;
|
|
261
|
+
const saved = typeof responseId === "string" ? await env.DB.prepare(`
|
|
262
|
+
SELECT response.operator_id AS operatorId, response.response_json AS responseJson
|
|
263
|
+
FROM human_task_responses response JOIN human_tasks task ON task.id = response.task_id
|
|
264
|
+
JOIN workflow_step_runs step ON step.id = task.step_run_id
|
|
265
|
+
WHERE response.id = ?1 AND task.run_id = ?2 AND task.report_id = ?3
|
|
266
|
+
AND task.state = 'completed' AND task.action_proposal_id IS NULL
|
|
267
|
+
AND (?5 = 0 OR step.node_id = 'review') AND step.branch_key = ?4 LIMIT 1
|
|
268
|
+
`).bind(responseId, run.id, run.reportId, input.branchKey, guide.editing_mode === "guided" ? 1 : 0).first<{ operatorId: string; responseJson: string }>() : null;
|
|
269
|
+
if (!saved) throw new WorkflowEffectError("playbook_verified_review_required");
|
|
270
|
+
const response = JSON.parse(saved.responseJson) as JsonObject;
|
|
271
|
+
if (response.decision_code !== decisionCode || String(response.rationale ?? "").trim() !== rationale
|
|
272
|
+
|| canonicalJson(response.evidence_references ?? []) !== canonicalJson(evidenceReferences)
|
|
273
|
+
|| canonicalJson(response.finding_ids ?? []) !== canonicalJson(findingIds)) throw new WorkflowEffectError("playbook_review_response_mismatch");
|
|
274
|
+
makerType = "human"; makerId = saved.operatorId;
|
|
275
|
+
}
|
|
234
276
|
const decisionId = crypto.randomUUID();
|
|
235
277
|
const timestamp = now();
|
|
236
278
|
const nextState = typeof input.node.config.report_state === "string" ? input.node.config.report_state : null;
|
|
237
|
-
const allowedStates = ["human_review", "awaiting_reporter", "resolved_by_ai", "human_review_requested", "closed"];
|
|
279
|
+
const allowedStates = ["human_review", "awaiting_reporter", "resolved_by_ai", "resolved_by_human", "human_review_requested", "closed"];
|
|
238
280
|
if (nextState && !allowedStates.includes(nextState)) throw new WorkflowEffectError("workflow_decision_state_invalid");
|
|
239
281
|
const statements: D1PreparedStatement[] = [
|
|
240
282
|
env.DB.prepare(`
|
|
@@ -242,13 +284,13 @@ export async function recordWorkflowDecision(
|
|
|
242
284
|
id, report_id, decision_code, policy_version_id, policy_code, rationale,
|
|
243
285
|
evidence_references_json, maker_type, maker_id, queue_version_id,
|
|
244
286
|
proposed_action_code, created_at, idempotency_key
|
|
245
|
-
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7,
|
|
287
|
+
) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?13, ?8, ?9, ?10, ?11, ?12)
|
|
246
288
|
`).bind(
|
|
247
289
|
decisionId, run.reportId, decisionCode, policyVersionId, policyCode,
|
|
248
290
|
rationale, canonicalJson([...evidenceReferences, ...findingIds.map((id) => `finding:${id}`)]),
|
|
249
|
-
|
|
291
|
+
makerId, run.queueVersionId,
|
|
250
292
|
typeof mapped.proposed_action_code === "string" ? mapped.proposed_action_code : null,
|
|
251
|
-
timestamp, operationKey,
|
|
293
|
+
timestamp, operationKey, makerType,
|
|
252
294
|
),
|
|
253
295
|
env.DB.prepare(`
|
|
254
296
|
INSERT OR IGNORE INTO audit_events (
|
|
@@ -257,12 +299,12 @@ export async function recordWorkflowDecision(
|
|
|
257
299
|
) VALUES (?1, ?2, 'workflow.decision_recorded', 'system', ?3, 'decision', ?4, ?5, ?6)
|
|
258
300
|
`).bind(crypto.randomUUID(), operationKey, run.id, decisionId, canonicalJson({
|
|
259
301
|
reportId: run.reportId, decisionCode, policyVersionId, policyCode,
|
|
260
|
-
evidenceReferences, findingIds, authorityMode: run.authorityMode,
|
|
302
|
+
evidenceReferences, findingIds, authorityMode: run.authorityMode, makerType, makerId,
|
|
261
303
|
}), timestamp),
|
|
262
304
|
];
|
|
263
305
|
if (nextState && nextState !== run.reportState) {
|
|
264
306
|
statements.push(
|
|
265
|
-
env.DB.prepare(`UPDATE reports SET state = ?2, resolved_at = CASE WHEN ?2 IN ('resolved_by_ai','closed') THEN ?3 ELSE resolved_at END, updated_at = ?3 WHERE id = ?1`)
|
|
307
|
+
env.DB.prepare(`UPDATE reports SET state = ?2, resolved_at = CASE WHEN ?2 IN ('resolved_by_ai','resolved_by_human','closed') THEN ?3 ELSE resolved_at END, updated_at = ?3 WHERE id = ?1`)
|
|
266
308
|
.bind(run.reportId, nextState, timestamp),
|
|
267
309
|
env.DB.prepare(`
|
|
268
310
|
INSERT INTO report_state_history (
|
|
@@ -275,6 +317,42 @@ export async function recordWorkflowDecision(
|
|
|
275
317
|
return { port: "recorded", decisionId, decisionCode, idempotentReplay: false };
|
|
276
318
|
}
|
|
277
319
|
|
|
320
|
+
// A completed process is not proof that a customer outcome happened. Resolve
|
|
321
|
+
// the case only after a decision exists and every proposed action is confirmed.
|
|
322
|
+
export async function completePlaybookOutcome(env: Env, runId: string): Promise<void> {
|
|
323
|
+
const run = await effectRun(env.DB, runId);
|
|
324
|
+
if (!run.playbookJson || run.runKind !== "primary" || run.authorityMode === "shadow") return;
|
|
325
|
+
const prefix = `workflow-decision:${run.id}:`;
|
|
326
|
+
const decision = await env.DB.prepare(`SELECT id, maker_type AS makerType, maker_id AS makerId, decision_code AS decisionCode
|
|
327
|
+
FROM decisions WHERE report_id = ?1 AND substr(idempotency_key, 1, length(?2)) = ?2 ORDER BY created_at DESC, rowid DESC LIMIT 1`)
|
|
328
|
+
.bind(run.reportId, prefix).first<{ id: string; makerType: string; makerId: string; decisionCode: string }>();
|
|
329
|
+
if (!decision) throw new WorkflowEffectError("playbook_outcome_decision_missing");
|
|
330
|
+
const nextState = decision.makerType === "human" ? "resolved_by_human" : "resolved_by_ai";
|
|
331
|
+
if (run.reportState === nextState) return;
|
|
332
|
+
if (!["human_review", "human_review_requested", "ai_review", "awaiting_reporter"].includes(run.reportState)) throw new WorkflowEffectError("playbook_outcome_case_changed");
|
|
333
|
+
const timestamp = now();
|
|
334
|
+
const id = `playbook-outcome:${run.id}`;
|
|
335
|
+
const written = await env.DB.batch([
|
|
336
|
+
env.DB.prepare(`UPDATE reports SET state = ?2, resolved_at = ?3, updated_at = ?3
|
|
337
|
+
WHERE id = ?1 AND state = ?4
|
|
338
|
+
AND NOT EXISTS (SELECT 1 FROM action_proposals WHERE run_id = ?5 AND state <> 'applied')
|
|
339
|
+
AND NOT EXISTS (SELECT 1 FROM human_tasks WHERE run_id = ?5 AND state IN ('open','claimed'))
|
|
340
|
+
AND (?6 = 0 OR (NOT EXISTS (SELECT 1 FROM case_messages WHERE workflow_run_id = ?5 AND audience <> 'internal' AND delivery_state <> 'delivered')
|
|
341
|
+
AND NOT EXISTS (SELECT 1 FROM json_each(?7, '$.outcomes.notices') required
|
|
342
|
+
WHERE json_extract(?7, '$.editing_mode') = 'guided' AND NOT EXISTS (
|
|
343
|
+
SELECT 1 FROM notices n JOIN case_messages m ON m.id = n.message_id
|
|
344
|
+
WHERE m.workflow_run_id = ?5 AND n.decision_id = ?8 AND n.audience = json_extract(required.value, '$.audience')
|
|
345
|
+
AND n.template_version_id = json_extract(required.value, '$.template_version_id') AND n.delivery_state = 'delivered'))))`)
|
|
346
|
+
.bind(run.reportId, nextState, timestamp, run.reportState, run.id, Number(/^safest-workflow-compiler-v(\d+)$/u.exec(run.compilerVersion)?.[1] ?? 0) >= 5 ? 1 : 0, run.playbookJson, decision.id),
|
|
347
|
+
env.DB.prepare(`INSERT INTO report_state_history (id, report_id, from_state, to_state, reason_code, actor_type, actor_id, created_at)
|
|
348
|
+
SELECT ?1, ?2, ?3, ?4, ?5, 'system', ?6, ?7 WHERE changes() = 1`)
|
|
349
|
+
.bind(id, run.reportId, run.reportState, nextState, decision.decisionCode, run.id, timestamp),
|
|
350
|
+
env.DB.prepare(`DELETE FROM review_claims WHERE report_id = ?1 AND EXISTS (SELECT 1 FROM report_state_history WHERE id = ?2)`)
|
|
351
|
+
.bind(run.reportId, id),
|
|
352
|
+
]);
|
|
353
|
+
if (written[0]?.meta.changes !== 1) throw new WorkflowEffectError("playbook_outcome_not_confirmed");
|
|
354
|
+
}
|
|
355
|
+
|
|
278
356
|
export async function handoffWorkflowReport(
|
|
279
357
|
env: Env,
|
|
280
358
|
input: { runId: string; node: WorkflowNodeV1; branchKey: string },
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { sha256 } from "./report-crypto";
|
|
2
|
+
|
|
3
|
+
/** Logical names stay in the audit/inbox; only the platform transport is encoded. */
|
|
4
|
+
export async function workflowEventTransportType(logicalType: string, compilerVersion: string): Promise<string> {
|
|
5
|
+
const revision = /^safest-workflow-compiler-v(\d+)$/u.exec(compilerVersion);
|
|
6
|
+
return revision && Number(revision[1]) >= 4 ? `ev_${await sha256(logicalType)}` : logicalType;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export async function workflowRunEventType(db: D1Database, runId: string, logicalType: string): Promise<string> {
|
|
10
|
+
const version = await db.prepare(`
|
|
11
|
+
SELECT v.compiler_version AS compilerVersion FROM workflow_runs r
|
|
12
|
+
JOIN workflow_versions v ON v.id = r.workflow_version_id WHERE r.id = ?1
|
|
13
|
+
`).bind(runId).first<{ compilerVersion: string }>();
|
|
14
|
+
if (!version) throw new Error("workflow_event_run_missing");
|
|
15
|
+
return workflowEventTransportType(logicalType, version.compilerVersion);
|
|
16
|
+
}
|
|
@@ -142,6 +142,36 @@ export function evaluateInputMapping(
|
|
|
142
142
|
return output;
|
|
143
143
|
}
|
|
144
144
|
|
|
145
|
+
function mappedPath(expression: JsonValue): string | null {
|
|
146
|
+
if (typeof expression === "string" && pathPattern.test(expression)) return expression;
|
|
147
|
+
if (!expression || typeof expression !== "object" || Array.isArray(expression)) return null;
|
|
148
|
+
const operation = operatorObject(expression);
|
|
149
|
+
return operation?.[0] === "$path" && typeof operation[1] === "string" && pathPattern.test(operation[1])
|
|
150
|
+
? operation[1]
|
|
151
|
+
: null;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function evaluateSchemaInputMapping(
|
|
155
|
+
mapping: Record<string, JsonValue>,
|
|
156
|
+
context: JsonObject,
|
|
157
|
+
schema: JsonObject,
|
|
158
|
+
): JsonObject {
|
|
159
|
+
const required = new Set(Array.isArray(schema.required)
|
|
160
|
+
? schema.required.filter((entry): entry is string => typeof entry === "string")
|
|
161
|
+
: []);
|
|
162
|
+
const properties = schema.properties && typeof schema.properties === "object" && !Array.isArray(schema.properties)
|
|
163
|
+
? schema.properties as JsonObject
|
|
164
|
+
: {};
|
|
165
|
+
const output: JsonObject = {};
|
|
166
|
+
for (const [key, expression] of Object.entries(mapping)) {
|
|
167
|
+
const propertySchema = properties[key];
|
|
168
|
+
const path = mappedPath(expression);
|
|
169
|
+
if (path && !required.has(key) && propertySchema && directPath(context, path) === undefined) continue;
|
|
170
|
+
output[key] = evaluateWorkflowExpression(expression, context);
|
|
171
|
+
}
|
|
172
|
+
return output;
|
|
173
|
+
}
|
|
174
|
+
|
|
145
175
|
export function validateJsonSchemaValue(
|
|
146
176
|
value: JsonValue,
|
|
147
177
|
schema: JsonObject,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export const DYNAMIC_WORKFLOW_MAIN_MODULE = "workflow.js";
|
|
2
|
+
|
|
3
|
+
export function dynamicWorkflowWorkerModule(source: string): {
|
|
4
|
+
mainModule: string;
|
|
5
|
+
modules: Record<string, { js: string }>;
|
|
6
|
+
} {
|
|
7
|
+
return {
|
|
8
|
+
mainModule: DYNAMIC_WORKFLOW_MAIN_MODULE,
|
|
9
|
+
modules: { [DYNAMIC_WORKFLOW_MAIN_MODULE]: { js: source } },
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function canRequeueUnavailableWorkflowDispatch(input: {
|
|
14
|
+
state: string;
|
|
15
|
+
errorCode: string | null;
|
|
16
|
+
stepCount: number;
|
|
17
|
+
}): boolean {
|
|
18
|
+
return input.state === "repair_required"
|
|
19
|
+
&& ["workflow_dispatch_exhausted", "workflow_dispatch_queue_retries_exhausted"].includes(input.errorCode ?? "")
|
|
20
|
+
&& Number(input.stepCount) === 0;
|
|
21
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { PlaybookGuide } from "../shared/playbooks";
|
|
2
|
+
|
|
1
3
|
export type WorkflowPurpose = "report" | "appeal" | "quality" | "operations";
|
|
2
4
|
export type WorkflowAuthorityMode = "off" | "shadow" | "assist" | "bounded_auto";
|
|
3
5
|
export type WorkflowNodeKind =
|
|
@@ -43,6 +45,7 @@ export interface WorkflowEdgeV1 {
|
|
|
43
45
|
}
|
|
44
46
|
|
|
45
47
|
export interface WorkflowGraphV1 {
|
|
48
|
+
playbook?: PlaybookGuide;
|
|
46
49
|
schemaVersion: "1";
|
|
47
50
|
purpose: WorkflowPurpose;
|
|
48
51
|
entryNodeId: string;
|