@evomap/evolver-cli 2.0.0-beta.6 → 2.0.0-beta.8
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/dist/autoexec.d.ts +2 -10
- package/dist/autoexec.js +17 -25
- package/dist/autoexecConfig.d.ts +10 -0
- package/dist/autoexecConfig.js +68 -0
- package/dist/cliContracts.js +22 -1
- package/dist/dashboard.d.ts +11 -1
- package/dist/dashboard.js +173 -12
- package/dist/dispatch.js +2 -0
- package/dist/distillPrimitives.d.ts +5 -1
- package/dist/distillPrimitives.js +1 -1
- package/dist/doctor.js +1 -1
- package/dist/index.js +21 -2
- package/dist/reuse.d.ts +3 -6
- package/dist/reuse.js +31 -6
- package/dist/workflow.d.ts +39 -0
- package/dist/workflow.js +386 -0
- package/dist/workflowRuntime.d.ts +66 -0
- package/dist/workflowRuntime.js +631 -0
- package/package.json +7 -7
package/dist/reuse.js
CHANGED
|
@@ -24,6 +24,8 @@ const REUSE_USAGE = [
|
|
|
24
24
|
// Flags that consume the following token as their value. firstPositional must skip those values so a flag value
|
|
25
25
|
// (e.g. the `reference` in `--mode reference`) is never mistaken for a bare positional asset id.
|
|
26
26
|
const VALUE_FLAGS = new Set(['--id', '--mode', '--run']);
|
|
27
|
+
// Keep this list limited to Hub-only fields. `confidence` is canonical Capsule content and must
|
|
28
|
+
// survive integrity verification even though delivery rows also use a field with that name.
|
|
27
29
|
const HUB_METADATA_KEYS = new Set([
|
|
28
30
|
'credit_cost',
|
|
29
31
|
'gdi_score',
|
|
@@ -89,7 +91,8 @@ export async function runReuseCommand(argv, deps = {}) {
|
|
|
89
91
|
const hub = deps.hub ?? createRecipeHubFromEnv(env, deps.connectHub ?? connectPublicHub);
|
|
90
92
|
// One-shot CLIs never heartbeat, so the hub may hold no env fingerprint for this node and its anti-abuse
|
|
91
93
|
// layer then 403s /a2a/fetch (`bulk_fetch_blocked: IP antibody`, #555). A fingerprinted hello
|
|
92
|
-
// (rotate:false
|
|
94
|
+
// (rotate:false + preserveCredentials:true) neither requests nor applies credential mutation while establishing
|
|
95
|
+
// trust. Best-effort by design:
|
|
93
96
|
// a hello failure must not block the fetch — the fetch's own error path classifies precisely.
|
|
94
97
|
await establishReuseTrust(hub);
|
|
95
98
|
const asset = await hub.fetchAssetById(opts.id);
|
|
@@ -164,18 +167,30 @@ export function parseReuseArgs(argv) {
|
|
|
164
167
|
const runId = flagValue(argv, '--run');
|
|
165
168
|
return { ok: true, value: { id, mode: modeRaw === 'direct' ? 'direct' : 'reference', ...(runId ? { runId } : {}) } };
|
|
166
169
|
}
|
|
170
|
+
// Integrity rejection is a first-class outcome, not an internal fault: the hub demonstrably rewrites
|
|
171
|
+
// delivered payloads (injected `validation`, wholesale `payload_backfill_reason` synthesis — #570), so the
|
|
172
|
+
// desktop adapter needs a typed reason to tell "this asset cannot be verified" apart from "the engine broke".
|
|
173
|
+
// Messages are fixed strings by construction (hard rule 2: nothing dynamic can reach a stream).
|
|
174
|
+
class ReuseIntegrityError extends Error {
|
|
175
|
+
}
|
|
176
|
+
const INTEGRITY_MISMATCH_MESSAGE = 'hub-delivered content does not match the asset content fingerprint';
|
|
177
|
+
const INTEGRITY_BACKFILLED_MESSAGE = 'hub delivered a synthesized payload for this asset; the original published content is unavailable for verification';
|
|
178
|
+
function integrityError(content) {
|
|
179
|
+
const backfilled = stringField(content, 'payload_backfill_reason') !== undefined;
|
|
180
|
+
return new ReuseIntegrityError(backfilled ? INTEGRITY_BACKFILLED_MESSAGE : INTEGRITY_MISMATCH_MESSAGE);
|
|
181
|
+
}
|
|
167
182
|
async function ingestHubAsset(store, deps, asset, requestedId) {
|
|
168
|
-
const cleaned = stripHubMetadata(asset);
|
|
183
|
+
const cleaned = stripHubMetadata(unwrapHubAssetContent(asset));
|
|
169
184
|
const actualAssetId = wire.computeAssetId(cleaned);
|
|
170
185
|
const contentAssetId = stringField(cleaned, 'asset_id');
|
|
171
186
|
if (!actualAssetId || !contentAssetId || actualAssetId !== contentAssetId) {
|
|
172
|
-
throw
|
|
187
|
+
throw integrityError(cleaned);
|
|
173
188
|
}
|
|
174
189
|
if (isContentAssetId(requestedId) && actualAssetId !== requestedId) {
|
|
175
|
-
throw
|
|
190
|
+
throw integrityError(cleaned);
|
|
176
191
|
}
|
|
177
192
|
if (!isContentAssetId(requestedId) && stringField(cleaned, 'id') !== requestedId) {
|
|
178
|
-
throw
|
|
193
|
+
throw integrityError(cleaned);
|
|
179
194
|
}
|
|
180
195
|
await assertNoLocalReuseIdConflict(cleaned, store);
|
|
181
196
|
const provenance = new assetstore.ProvenanceStore(storeBaseDir(store, deps));
|
|
@@ -209,6 +224,13 @@ async function assertNoLocalReuseIdConflict(asset, store) {
|
|
|
209
224
|
if (incomingAssetId !== localAssetId)
|
|
210
225
|
throw new Error('local asset id conflict');
|
|
211
226
|
}
|
|
227
|
+
function unwrapHubAssetContent(asset) {
|
|
228
|
+
const payload = asset.payload;
|
|
229
|
+
if (payload && typeof payload === 'object' && !Array.isArray(payload) && stringField(payload, 'asset_id')) {
|
|
230
|
+
return payload;
|
|
231
|
+
}
|
|
232
|
+
return asset;
|
|
233
|
+
}
|
|
212
234
|
function stripHubMetadata(asset) {
|
|
213
235
|
const out = {};
|
|
214
236
|
for (const [key, value] of Object.entries(asset))
|
|
@@ -242,7 +264,7 @@ async function establishReuseTrust(hub) {
|
|
|
242
264
|
if (typeof hub.hello !== 'function')
|
|
243
265
|
return;
|
|
244
266
|
try {
|
|
245
|
-
await hub.hello({ rotate: false, evolverVersion: getCliVersion() });
|
|
267
|
+
await hub.hello({ rotate: false, evolverVersion: getCliVersion(), preserveCredentials: true });
|
|
246
268
|
}
|
|
247
269
|
catch { /* fetch decides the outcome */ }
|
|
248
270
|
}
|
|
@@ -260,6 +282,9 @@ function hubErrorField(body) {
|
|
|
260
282
|
return typeof err === 'string' ? err : undefined;
|
|
261
283
|
}
|
|
262
284
|
function mapError(e) {
|
|
285
|
+
if (e instanceof ReuseIntegrityError) {
|
|
286
|
+
return { ok: false, status: 'integrity_failed', message: e.message };
|
|
287
|
+
}
|
|
263
288
|
if (e instanceof AuthError) {
|
|
264
289
|
// hubFetch raises AuthError for BOTH 401 and 403, so the hub's anti-abuse 403
|
|
265
290
|
// (`bulk_fetch_blocked: IP antibody active`) used to be misreported as "log in" — it is an
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { workflow } from '@evomap/evolver-core';
|
|
2
|
+
import { type ProductionWorkflowRuntimeOptions } from './workflowRuntime.js';
|
|
3
|
+
export declare const WORKFLOW_SUBCOMMANDS: readonly ["start", "submit", "list", "status", "history", "pause", "resume", "cancel", "approve", "reject"];
|
|
4
|
+
type OutputStream = Pick<NodeJS.WriteStream, 'write'>;
|
|
5
|
+
type RuntimeControlOptions = {
|
|
6
|
+
actor: string;
|
|
7
|
+
reason?: string;
|
|
8
|
+
};
|
|
9
|
+
type WorkflowRuntimeLike = {
|
|
10
|
+
start(spec: workflow.WorkflowSpec, options?: {
|
|
11
|
+
runId?: string;
|
|
12
|
+
}): Promise<unknown>;
|
|
13
|
+
pause?: (runId: string, options: RuntimeControlOptions) => Promise<unknown>;
|
|
14
|
+
resume?: (runId: string, options?: RuntimeControlOptions) => Promise<unknown>;
|
|
15
|
+
cancel?: (runId: string, options: RuntimeControlOptions) => Promise<unknown>;
|
|
16
|
+
approve?: (runId: string, gateId: string, options: RuntimeControlOptions) => Promise<unknown>;
|
|
17
|
+
reject?: (runId: string, gateId: string, options: RuntimeControlOptions) => Promise<unknown>;
|
|
18
|
+
};
|
|
19
|
+
type WorkflowStoreLike = {
|
|
20
|
+
read(runId: string): workflow.WorkflowRunState;
|
|
21
|
+
listRunIds(): string[];
|
|
22
|
+
history?: (runId: string) => unknown;
|
|
23
|
+
readHistory?: (runId: string) => unknown;
|
|
24
|
+
listHistory?: (runId: string) => unknown;
|
|
25
|
+
requestPause?: (runId: string, options: RuntimeControlOptions) => void;
|
|
26
|
+
requestCancel?: (runId: string, options: RuntimeControlOptions) => void;
|
|
27
|
+
approve?: (runId: string, gateId: string, options: RuntimeControlOptions) => void;
|
|
28
|
+
reject?: (runId: string, gateId: string, options: RuntimeControlOptions) => void;
|
|
29
|
+
};
|
|
30
|
+
export interface WorkflowCommandDeps {
|
|
31
|
+
stateDir?: string;
|
|
32
|
+
stdout?: OutputStream;
|
|
33
|
+
stderr?: OutputStream;
|
|
34
|
+
createStore?: (stateDir: string) => WorkflowStoreLike;
|
|
35
|
+
createRuntime?: (stateDir: string) => WorkflowRuntimeLike;
|
|
36
|
+
productionRuntimeOptions?: ProductionWorkflowRuntimeOptions;
|
|
37
|
+
}
|
|
38
|
+
export declare function runWorkflowCommand(argv: string[], deps?: WorkflowCommandDeps): Promise<number>;
|
|
39
|
+
export {};
|
package/dist/workflow.js
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { lstatSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { workflow } from '@evomap/evolver-core';
|
|
4
|
+
import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
|
|
5
|
+
import { createProductionWorkflowRuntime } from './workflowRuntime.js';
|
|
6
|
+
const MAX_SPEC_BYTES = 1_048_576;
|
|
7
|
+
const MAX_REASON_LENGTH = 500;
|
|
8
|
+
const DEFAULT_ACTOR = 'local-operator';
|
|
9
|
+
export const WORKFLOW_SUBCOMMANDS = [
|
|
10
|
+
'start', 'submit', 'list', 'status', 'history', 'pause', 'resume', 'cancel', 'approve', 'reject',
|
|
11
|
+
];
|
|
12
|
+
class WorkflowCliError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
constructor(code) {
|
|
15
|
+
super(code);
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.name = 'WorkflowCliError';
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function usage(stderr) {
|
|
21
|
+
stderr.write([
|
|
22
|
+
'usage:',
|
|
23
|
+
' evolver workflow start|submit <spec-file> [--run-id <id>] [--state-dir <path>] [--autoexec-home <path>] [--json]',
|
|
24
|
+
' evolver workflow list [--state-dir <path>] [--autoexec-home <path>] [--json]',
|
|
25
|
+
' evolver workflow status|history <run-id> [--state-dir <path>] [--autoexec-home <path>] [--json]',
|
|
26
|
+
' evolver workflow pause|resume|cancel <run-id> [--actor <id>] [--reason <text>] [--state-dir <path>] [--autoexec-home <path>] [--json]',
|
|
27
|
+
' evolver workflow approve|reject <run-id> <gate-id> [--actor <id>] [--reason <text>] [--state-dir <path>] [--autoexec-home <path>] [--json]',
|
|
28
|
+
].join('\n') + '\n');
|
|
29
|
+
return 1;
|
|
30
|
+
}
|
|
31
|
+
function isSubcommand(value) {
|
|
32
|
+
return WORKFLOW_SUBCOMMANDS.includes(value);
|
|
33
|
+
}
|
|
34
|
+
function allowedValueFlags(command) {
|
|
35
|
+
const flags = new Set(['--state-dir', '--autoexec-home']);
|
|
36
|
+
if (command === 'start' || command === 'submit')
|
|
37
|
+
flags.add('--run-id');
|
|
38
|
+
if (['pause', 'resume', 'cancel', 'approve', 'reject'].includes(command)) {
|
|
39
|
+
flags.add('--actor');
|
|
40
|
+
flags.add('--reason');
|
|
41
|
+
}
|
|
42
|
+
return flags;
|
|
43
|
+
}
|
|
44
|
+
function expectedPositionals(command) {
|
|
45
|
+
if (command === 'list')
|
|
46
|
+
return 0;
|
|
47
|
+
if (command === 'approve' || command === 'reject')
|
|
48
|
+
return 2;
|
|
49
|
+
return 1;
|
|
50
|
+
}
|
|
51
|
+
function parseArgs(argv) {
|
|
52
|
+
const command = argv[0];
|
|
53
|
+
if (!isSubcommand(command))
|
|
54
|
+
return null;
|
|
55
|
+
const valueFlags = allowedValueFlags(command);
|
|
56
|
+
const values = new Map();
|
|
57
|
+
const positionals = [];
|
|
58
|
+
let json = false;
|
|
59
|
+
for (let index = 1; index < argv.length; index += 1) {
|
|
60
|
+
const arg = argv[index];
|
|
61
|
+
if (arg === '--json') {
|
|
62
|
+
if (json)
|
|
63
|
+
return null;
|
|
64
|
+
json = true;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (arg?.startsWith('--')) {
|
|
68
|
+
if (!valueFlags.has(arg) || values.has(arg))
|
|
69
|
+
return null;
|
|
70
|
+
const value = argv[index + 1];
|
|
71
|
+
if (!value || value.startsWith('--'))
|
|
72
|
+
return null;
|
|
73
|
+
values.set(arg, value);
|
|
74
|
+
index += 1;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (!arg || arg.startsWith('-'))
|
|
78
|
+
return null;
|
|
79
|
+
positionals.push(arg);
|
|
80
|
+
}
|
|
81
|
+
if (positionals.length !== expectedPositionals(command))
|
|
82
|
+
return null;
|
|
83
|
+
return {
|
|
84
|
+
command,
|
|
85
|
+
positionals,
|
|
86
|
+
...(values.get('--state-dir') ? { stateDir: values.get('--state-dir') } : {}),
|
|
87
|
+
...(values.get('--autoexec-home') ? { autoExecHome: values.get('--autoexec-home') } : {}),
|
|
88
|
+
...(values.get('--run-id') ? { runId: values.get('--run-id') } : {}),
|
|
89
|
+
...(values.get('--actor') ? { actor: values.get('--actor') } : {}),
|
|
90
|
+
...(values.has('--reason') ? { reason: values.get('--reason') } : {}),
|
|
91
|
+
json,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function validateId(value, label) {
|
|
95
|
+
workflow.assertStableId(value, label);
|
|
96
|
+
return value;
|
|
97
|
+
}
|
|
98
|
+
function validateReason(reason) {
|
|
99
|
+
if (reason === undefined || reason.length === 0)
|
|
100
|
+
return undefined;
|
|
101
|
+
const hasControlCharacter = [...reason].some((character) => {
|
|
102
|
+
const code = character.charCodeAt(0);
|
|
103
|
+
return code <= 0x1f || code === 0x7f;
|
|
104
|
+
});
|
|
105
|
+
if (reason.length > MAX_REASON_LENGTH || hasControlCharacter || workflow.containsWorkflowSensitiveText(reason)) {
|
|
106
|
+
throw new WorkflowCliError('INVALID_REASON');
|
|
107
|
+
}
|
|
108
|
+
return reason;
|
|
109
|
+
}
|
|
110
|
+
function controlOptions(parsed) {
|
|
111
|
+
const actor = validateId(parsed.actor ?? DEFAULT_ACTOR, 'actor');
|
|
112
|
+
const reason = validateReason(parsed.reason);
|
|
113
|
+
return { actor, ...(reason ? { reason } : {}) };
|
|
114
|
+
}
|
|
115
|
+
function parseWorkflowSpec(path) {
|
|
116
|
+
const absolutePath = resolve(path);
|
|
117
|
+
let stat;
|
|
118
|
+
try {
|
|
119
|
+
stat = lstatSync(absolutePath);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
throw new WorkflowCliError('SPEC_NOT_FOUND');
|
|
123
|
+
}
|
|
124
|
+
if (stat.isSymbolicLink() || !stat.isFile())
|
|
125
|
+
throw new WorkflowCliError('INVALID_SPEC_PATH');
|
|
126
|
+
if (stat.size > MAX_SPEC_BYTES)
|
|
127
|
+
throw new WorkflowCliError('SPEC_TOO_LARGE');
|
|
128
|
+
let parsed;
|
|
129
|
+
try {
|
|
130
|
+
parsed = JSON.parse(readFileSync(absolutePath, 'utf8'));
|
|
131
|
+
}
|
|
132
|
+
catch {
|
|
133
|
+
throw new WorkflowCliError('INVALID_SPEC_JSON');
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
workflow.assertValidWorkflowSpec(parsed);
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
throw new WorkflowCliError('INVALID_WORKFLOW_SPEC');
|
|
140
|
+
}
|
|
141
|
+
return parsed;
|
|
142
|
+
}
|
|
143
|
+
function isRecord(value) {
|
|
144
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
145
|
+
}
|
|
146
|
+
function statusPayload(state) {
|
|
147
|
+
const candidate = state.currentStep ? state.steps[state.currentStep] : undefined;
|
|
148
|
+
const current = candidate?.status === 'succeeded' ? undefined : candidate;
|
|
149
|
+
return {
|
|
150
|
+
schemaVersion: state.schemaVersion,
|
|
151
|
+
workflowId: state.workflowId,
|
|
152
|
+
runId: state.runId,
|
|
153
|
+
workflowName: safeString(state.workflowName, 256),
|
|
154
|
+
status: state.status,
|
|
155
|
+
currentStep: current?.executionId ?? null,
|
|
156
|
+
currentStepId: current?.stepId ?? null,
|
|
157
|
+
attempts: current?.attempts ?? 0,
|
|
158
|
+
maxAttempts: current?.maxAttempts ?? 0,
|
|
159
|
+
lastErrorClass: safeMetadataToken(state.lastErrorClass),
|
|
160
|
+
createdAt: state.createdAt,
|
|
161
|
+
updatedAt: state.updatedAt,
|
|
162
|
+
completedAt: state.completedAt ?? null,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function safeString(value, maxLength = 500) {
|
|
166
|
+
if (typeof value !== 'string' || value.length > maxLength || workflow.containsWorkflowSensitiveText(value))
|
|
167
|
+
return null;
|
|
168
|
+
const hasControlCharacter = [...value].some((character) => {
|
|
169
|
+
const code = character.charCodeAt(0);
|
|
170
|
+
return code <= 0x1f || code === 0x7f;
|
|
171
|
+
});
|
|
172
|
+
return hasControlCharacter ? null : value;
|
|
173
|
+
}
|
|
174
|
+
function safeMetadataToken(value) {
|
|
175
|
+
const candidate = safeString(value, 64);
|
|
176
|
+
return candidate !== null && /^[A-Za-z0-9._-]+$/.test(candidate) ? candidate : null;
|
|
177
|
+
}
|
|
178
|
+
function historyPayload(entry) {
|
|
179
|
+
if (!isRecord(entry))
|
|
180
|
+
return { type: 'unknown' };
|
|
181
|
+
const output = {};
|
|
182
|
+
const numberFields = ['sequence', 'seq', 'attempt'];
|
|
183
|
+
for (const key of numberFields) {
|
|
184
|
+
if (typeof entry[key] === 'number' && Number.isFinite(entry[key]))
|
|
185
|
+
output[key] = entry[key];
|
|
186
|
+
}
|
|
187
|
+
const idFields = ['id', 'eventId', 'runId', 'workflowId', 'executionId', 'stepId', 'gateId'];
|
|
188
|
+
for (const key of idFields) {
|
|
189
|
+
const value = safeString(entry[key], 128);
|
|
190
|
+
if (value !== null)
|
|
191
|
+
output[key] = value;
|
|
192
|
+
}
|
|
193
|
+
const enumFields = ['type', 'event', 'operation', 'kind', 'action', 'status', 'previousStatus', 'nextStatus', 'errorClass'];
|
|
194
|
+
for (const key of enumFields) {
|
|
195
|
+
const value = safeString(entry[key], 64);
|
|
196
|
+
if (value !== null)
|
|
197
|
+
output[key] = value;
|
|
198
|
+
}
|
|
199
|
+
const actorRecord = isRecord(entry['actor']) ? entry['actor'] : null;
|
|
200
|
+
const actor = safeString(entry['actorId'], 128) ?? safeString(entry['actor'], 128) ?? safeString(actorRecord?.['id'], 128);
|
|
201
|
+
if (actor !== null)
|
|
202
|
+
output['actor'] = actor;
|
|
203
|
+
const reason = safeString(entry['reason'], MAX_REASON_LENGTH);
|
|
204
|
+
if (reason !== null)
|
|
205
|
+
output['reason'] = reason;
|
|
206
|
+
for (const key of ['timestamp', 'at', 'ts', 'createdAt']) {
|
|
207
|
+
const value = safeString(entry[key], 64);
|
|
208
|
+
if (value !== null)
|
|
209
|
+
output[key] = value;
|
|
210
|
+
}
|
|
211
|
+
return Object.keys(output).length > 0 ? output : { type: 'unknown' };
|
|
212
|
+
}
|
|
213
|
+
function historyRows(value) {
|
|
214
|
+
if (Array.isArray(value))
|
|
215
|
+
return value;
|
|
216
|
+
if (!isRecord(value))
|
|
217
|
+
return [];
|
|
218
|
+
if (Array.isArray(value['history']))
|
|
219
|
+
return value['history'];
|
|
220
|
+
if (Array.isArray(value['entries']))
|
|
221
|
+
return value['entries'];
|
|
222
|
+
return [];
|
|
223
|
+
}
|
|
224
|
+
function readHistory(store, runId) {
|
|
225
|
+
if (store.readHistory)
|
|
226
|
+
return historyRows(store.readHistory(runId));
|
|
227
|
+
if (store.listHistory)
|
|
228
|
+
return historyRows(store.listHistory(runId));
|
|
229
|
+
if (store.history)
|
|
230
|
+
return historyRows(store.history(runId));
|
|
231
|
+
const state = store.read(runId);
|
|
232
|
+
if (isRecord(state) && Array.isArray(state['history']))
|
|
233
|
+
return state['history'];
|
|
234
|
+
throw new WorkflowCliError('HISTORY_NOT_SUPPORTED');
|
|
235
|
+
}
|
|
236
|
+
function errorCode(error, command) {
|
|
237
|
+
if (error instanceof WorkflowCliError)
|
|
238
|
+
return error.code;
|
|
239
|
+
if (error instanceof workflow.WorkflowStateError || error instanceof workflow.WorkflowRuntimeError)
|
|
240
|
+
return error.code;
|
|
241
|
+
if (error instanceof workflow.WorkflowRunFailedError)
|
|
242
|
+
return 'RUN_FAILED';
|
|
243
|
+
return `WORKFLOW_${command.toUpperCase()}_FAILED`;
|
|
244
|
+
}
|
|
245
|
+
function createDefaultRuntime(stateDir, options = {}) {
|
|
246
|
+
return createProductionWorkflowRuntime({ ...options, stateDir });
|
|
247
|
+
}
|
|
248
|
+
function writeJson(stream, payload) {
|
|
249
|
+
stream.write(`${JSON.stringify(payload)}\n`);
|
|
250
|
+
}
|
|
251
|
+
function writeStatusText(stream, payload) {
|
|
252
|
+
stream.write([
|
|
253
|
+
`run=${String(payload['runId'])}`,
|
|
254
|
+
`workflow=${String(payload['workflowId'])}`,
|
|
255
|
+
`status=${String(payload['status'])}`,
|
|
256
|
+
`step=${String(payload['currentStepId'] ?? '-')}`,
|
|
257
|
+
`attempts=${String(payload['attempts'])}/${String(payload['maxAttempts'])}`,
|
|
258
|
+
`error=${String(payload['lastErrorClass'] ?? '-')}`,
|
|
259
|
+
].join(' ') + '\n');
|
|
260
|
+
}
|
|
261
|
+
async function invokeControl(runtime, store, parsed) {
|
|
262
|
+
const command = parsed.command;
|
|
263
|
+
const runId = validateId(parsed.positionals[0] ?? '', 'runId');
|
|
264
|
+
const options = controlOptions(parsed);
|
|
265
|
+
if (command === 'approve' || command === 'reject') {
|
|
266
|
+
const gateId = validateId(parsed.positionals[1] ?? '', 'gateId');
|
|
267
|
+
const runtimeMethod = runtime[command];
|
|
268
|
+
if (runtimeMethod) {
|
|
269
|
+
await runtimeMethod.call(runtime, runId, gateId, options);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
const storeMethod = store[command];
|
|
273
|
+
if (!storeMethod)
|
|
274
|
+
throw new WorkflowCliError('CONTROL_NOT_SUPPORTED');
|
|
275
|
+
storeMethod.call(store, runId, gateId, options);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
const runtimeMethod = runtime[command];
|
|
279
|
+
if (runtimeMethod) {
|
|
280
|
+
await runtimeMethod.call(runtime, runId, options);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
if (command === 'pause' && store.requestPause) {
|
|
284
|
+
store.requestPause(runId, options);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
if (command === 'cancel' && store.requestCancel) {
|
|
288
|
+
store.requestCancel(runId, options);
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
throw new WorkflowCliError('CONTROL_NOT_SUPPORTED');
|
|
292
|
+
}
|
|
293
|
+
export async function runWorkflowCommand(argv, deps = {}) {
|
|
294
|
+
const stdout = deps.stdout ?? process.stdout;
|
|
295
|
+
const stderr = deps.stderr ?? process.stderr;
|
|
296
|
+
const parsed = parseArgs(argv);
|
|
297
|
+
if (!parsed)
|
|
298
|
+
return usage(stderr);
|
|
299
|
+
const env = { ...(deps.productionRuntimeOptions?.env ?? process.env) };
|
|
300
|
+
const envFile = loadEnvFileFromEnv(env);
|
|
301
|
+
if (envFile.error) {
|
|
302
|
+
if (parsed.json)
|
|
303
|
+
writeJson(stdout, { ok: false, command: parsed.command, error: 'ENV_FILE_UNAVAILABLE' });
|
|
304
|
+
else
|
|
305
|
+
stderr.write(`workflow ${parsed.command} failed: ENV_FILE_UNAVAILABLE\n`);
|
|
306
|
+
return 1;
|
|
307
|
+
}
|
|
308
|
+
const configuredStateDir = env['EVOLVER_WORKFLOW_STATE_DIR']?.trim();
|
|
309
|
+
const stateDir = parsed.stateDir
|
|
310
|
+
?? deps.stateDir
|
|
311
|
+
?? (configuredStateDir || workflow.defaultWorkflowStateDir());
|
|
312
|
+
const runtimeOptions = {
|
|
313
|
+
...deps.productionRuntimeOptions,
|
|
314
|
+
env,
|
|
315
|
+
...(parsed.autoExecHome ? { autoExecHome: parsed.autoExecHome } : {}),
|
|
316
|
+
};
|
|
317
|
+
const createStore = deps.createStore ?? ((root) => new workflow.WorkflowStateStore(root));
|
|
318
|
+
const createRuntime = deps.createRuntime
|
|
319
|
+
?? ((root) => createDefaultRuntime(root, runtimeOptions));
|
|
320
|
+
let runId;
|
|
321
|
+
try {
|
|
322
|
+
if (parsed.command === 'start' || parsed.command === 'submit') {
|
|
323
|
+
const spec = parseWorkflowSpec(parsed.positionals[0] ?? '');
|
|
324
|
+
if (parsed.runId)
|
|
325
|
+
runId = validateId(parsed.runId, 'runId');
|
|
326
|
+
const result = await createRuntime(stateDir).start(spec, parsed.runId ? { runId: parsed.runId } : {});
|
|
327
|
+
if (!isRecord(result) || typeof result['runId'] !== 'string')
|
|
328
|
+
throw new WorkflowCliError('INVALID_RUNTIME_RESULT');
|
|
329
|
+
runId = validateId(result['runId'], 'runId');
|
|
330
|
+
const payload = {
|
|
331
|
+
ok: true,
|
|
332
|
+
runId,
|
|
333
|
+
workflowId: safeString(result['workflowId'], 128),
|
|
334
|
+
status: safeString(result['status'], 64),
|
|
335
|
+
};
|
|
336
|
+
if (parsed.json)
|
|
337
|
+
writeJson(stdout, payload);
|
|
338
|
+
else
|
|
339
|
+
stdout.write(`run=${runId} workflow=${String(payload.workflowId ?? '-')} status=${String(payload.status ?? '-')}\n`);
|
|
340
|
+
return 0;
|
|
341
|
+
}
|
|
342
|
+
const store = createStore(stateDir);
|
|
343
|
+
if (parsed.command === 'list') {
|
|
344
|
+
const runs = store.listRunIds().map((id) => statusPayload(store.read(validateId(id, 'runId'))));
|
|
345
|
+
if (parsed.json)
|
|
346
|
+
writeJson(stdout, { ok: true, runs });
|
|
347
|
+
else
|
|
348
|
+
for (const payload of runs)
|
|
349
|
+
writeStatusText(stdout, payload);
|
|
350
|
+
return 0;
|
|
351
|
+
}
|
|
352
|
+
runId = validateId(parsed.positionals[0] ?? '', 'runId');
|
|
353
|
+
if (parsed.command === 'status') {
|
|
354
|
+
const payload = statusPayload(store.read(runId));
|
|
355
|
+
if (parsed.json)
|
|
356
|
+
writeJson(stdout, { ok: true, ...payload });
|
|
357
|
+
else
|
|
358
|
+
writeStatusText(stdout, payload);
|
|
359
|
+
return 0;
|
|
360
|
+
}
|
|
361
|
+
if (parsed.command === 'history') {
|
|
362
|
+
const history = readHistory(store, runId).map(historyPayload);
|
|
363
|
+
if (parsed.json)
|
|
364
|
+
writeJson(stdout, { ok: true, runId, history });
|
|
365
|
+
else
|
|
366
|
+
for (const entry of history)
|
|
367
|
+
stdout.write(`${JSON.stringify(entry)}\n`);
|
|
368
|
+
return 0;
|
|
369
|
+
}
|
|
370
|
+
await invokeControl(createRuntime(stateDir), store, parsed);
|
|
371
|
+
const payload = statusPayload(store.read(runId));
|
|
372
|
+
if (parsed.json)
|
|
373
|
+
writeJson(stdout, { ok: true, operation: parsed.command, ...payload });
|
|
374
|
+
else
|
|
375
|
+
stdout.write(`run=${runId} operation=${parsed.command} status=${String(payload['status'])}\n`);
|
|
376
|
+
return 0;
|
|
377
|
+
}
|
|
378
|
+
catch (error) {
|
|
379
|
+
const code = errorCode(error, parsed.command);
|
|
380
|
+
if (parsed.json)
|
|
381
|
+
writeJson(stdout, { ok: false, command: parsed.command, ...(runId ? { runId } : {}), error: code });
|
|
382
|
+
else
|
|
383
|
+
stderr.write(`workflow ${parsed.command} failed: ${code}\n`);
|
|
384
|
+
return 1;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { assetstore, exec, verify, workflow } from '@evomap/evolver-core';
|
|
2
|
+
import { type AutoExecConfig } from './autoexecConfig.js';
|
|
3
|
+
declare const POLICY_CONTEXT_SCHEMA_VERSION = 2;
|
|
4
|
+
interface WorkflowPolicyContext {
|
|
5
|
+
schemaVersion: typeof POLICY_CONTEXT_SCHEMA_VERSION;
|
|
6
|
+
homeId: string;
|
|
7
|
+
policyId: string;
|
|
8
|
+
}
|
|
9
|
+
interface WorkflowPolicyExpectation extends WorkflowPolicyContext {
|
|
10
|
+
legacyPolicyId: string;
|
|
11
|
+
allowLegacyPolicyExact: boolean;
|
|
12
|
+
}
|
|
13
|
+
export interface ProductionWorkflowAgentDependencies {
|
|
14
|
+
store?: assetstore.AssetStoreProvider;
|
|
15
|
+
provenance?: assetstore.ProvenanceStore;
|
|
16
|
+
review?: assetstore.ReviewLedger;
|
|
17
|
+
agent?: exec.AgentRunner;
|
|
18
|
+
git?: exec.GitRunner;
|
|
19
|
+
runValidation?: typeof verify.runSandboxedValidation;
|
|
20
|
+
}
|
|
21
|
+
export interface ProductionWorkflowRuntimeOptions extends ProductionWorkflowAgentDependencies {
|
|
22
|
+
env?: Readonly<NodeJS.ProcessEnv>;
|
|
23
|
+
stateDir?: string;
|
|
24
|
+
maxQueuedRuns?: number;
|
|
25
|
+
assetsDir?: string;
|
|
26
|
+
autoExecHome?: string;
|
|
27
|
+
autoExecConfig?: AutoExecConfig;
|
|
28
|
+
writeDiagnostic?: (message: string) => void;
|
|
29
|
+
}
|
|
30
|
+
export interface WorkflowRecoveryRuntime {
|
|
31
|
+
recoverPending(): Promise<unknown>;
|
|
32
|
+
}
|
|
33
|
+
export interface WorkflowAgentExecutionSummary {
|
|
34
|
+
status: 'accepted';
|
|
35
|
+
score: number;
|
|
36
|
+
changedFiles: number;
|
|
37
|
+
changedLines: number;
|
|
38
|
+
validation: 'not_requested' | 'passed';
|
|
39
|
+
}
|
|
40
|
+
export declare function defaultWorkflowAutoExecHome(env?: Readonly<NodeJS.ProcessEnv>): string;
|
|
41
|
+
export declare function resolveWorkflowAutoExecHome(options?: Pick<ProductionWorkflowRuntimeOptions, 'autoExecHome' | 'env'>): string;
|
|
42
|
+
/**
|
|
43
|
+
* Compose the production workflow AgentBridge from the existing hardened execution primitive.
|
|
44
|
+
* The workflow may select only an operator-configured validation profile; raw validation commands are not accepted.
|
|
45
|
+
*/
|
|
46
|
+
export declare function createProductionWorkflowAgentBridge(config: AutoExecConfig, options?: ProductionWorkflowRuntimeOptions, expectedPolicyContext?: WorkflowPolicyExpectation): workflow.AgentBridge;
|
|
47
|
+
export declare function resolveWorkflowMaxConcurrentRuns(env?: Readonly<NodeJS.ProcessEnv>): number;
|
|
48
|
+
/** Create the shared production runtime used by CLI commands and daemon recovery. */
|
|
49
|
+
export declare function createProductionWorkflowRuntime(options?: ProductionWorkflowRuntimeOptions): workflow.DurableWorkflowRuntime;
|
|
50
|
+
/**
|
|
51
|
+
* Start recovery exactly once without awaiting it. A hung workflow may occupy a scheduler slot, but it cannot delay
|
|
52
|
+
* construction of the resident loop or daemon readiness.
|
|
53
|
+
*/
|
|
54
|
+
export declare function scheduleWorkflowStartupRecovery(runtime: WorkflowRecoveryRuntime, writeDiagnostic?: (message: string) => void): void;
|
|
55
|
+
interface WorkflowStartupRecoveryDependencies {
|
|
56
|
+
createRuntime?: (options: ProductionWorkflowRuntimeOptions) => WorkflowRecoveryRuntime;
|
|
57
|
+
scheduleRecovery?: (runtime: WorkflowRecoveryRuntime, writeDiagnostic: (message: string) => void) => void;
|
|
58
|
+
writeDiagnostic?: (message: string) => void;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Initialize daemon startup recovery without making workflow state availability a prerequisite for autoexec.
|
|
62
|
+
* Runtime construction can fail on corrupt state, insecure permissions, or concurrent access; those failures are
|
|
63
|
+
* reported as a bounded code while the independent task queue remains available.
|
|
64
|
+
*/
|
|
65
|
+
export declare function initializeWorkflowStartupRecovery(options: ProductionWorkflowRuntimeOptions, dependencies?: WorkflowStartupRecoveryDependencies): boolean;
|
|
66
|
+
export {};
|