devworkspace 0.5.0 → 0.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.
- package/CHANGELOG.md +16 -0
- package/dist/intelligence/orchestration/engine.d.ts +9 -0
- package/dist/intelligence/orchestration/engine.js +190 -30
- package/dist/intelligence/orchestration/engine.js.map +1 -1
- package/dist/intelligence/orchestration/types.d.ts +13 -2
- package/dist/intelligence/orchestration/types.js +2 -2
- package/dist/intelligence/orchestration/types.js.map +1 -1
- package/dist/intelligence/runtime/adk/adapter.js +21 -32
- package/dist/intelligence/runtime/adk/adapter.js.map +1 -1
- package/dist/intelligence/runtime/boundary.d.ts +30 -0
- package/dist/intelligence/runtime/boundary.js +163 -0
- package/dist/intelligence/runtime/boundary.js.map +1 -0
- package/dist/intelligence/runtime/external.js +32 -58
- package/dist/intelligence/runtime/external.js.map +1 -1
- package/dist/intelligence/runtime/native.js +23 -55
- package/dist/intelligence/runtime/native.js.map +1 -1
- package/dist/intelligence/runtime/types.d.ts +29 -1
- package/dist/intelligence/runtime/types.js +11 -1
- package/dist/intelligence/runtime/types.js.map +1 -1
- package/dist/intelligence/verification/engine.d.ts +21 -7
- package/dist/intelligence/verification/engine.js +78 -17
- package/dist/intelligence/verification/engine.js.map +1 -1
- package/dist/intelligence/verification/types.d.ts +11 -0
- package/dist/intelligence/verification/types.js.map +1 -1
- package/dist/standards/distribution/cache.d.ts +1 -0
- package/dist/standards/distribution/cache.js +199 -185
- package/dist/standards/distribution/cache.js.map +1 -1
- package/dist/standards/distribution/package.js +6 -0
- package/dist/standards/distribution/package.js.map +1 -1
- package/dist/standards/distribution/sync.d.ts +7 -2
- package/dist/standards/distribution/sync.js +41 -8
- package/dist/standards/distribution/sync.js.map +1 -1
- package/dist/utils/proc.d.ts +4 -0
- package/dist/utils/proc.js +58 -4
- package/dist/utils/proc.js.map +1 -1
- package/docs/agents.md +15 -0
- package/docs/contributing.md +4 -5
- package/docs/mcp.md +13 -0
- package/docs/security.md +8 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes are documented here. This project follows [Semantic Versioning](https://semver.org/). Workspace schema changes are called out under **Breaking**.
|
|
4
4
|
|
|
5
|
+
## [0.5.1] - 2026-12-01
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- **Truthful Runtime Contracts & Execution Separation (`src/intelligence/runtime/`)**:
|
|
9
|
+
- Added unified 9-state `RuntimeExecutionStatus` (`PREPARED`, `RUNNING`, `SUCCEEDED`, `FAILED`, `BLOCKED`, `NOT_EXECUTED`, `TIMED_OUT`, `CANCELLED`, `UNSUPPORTED`) and separated `verificationStatus` from execution `ok`.
|
|
10
|
+
- Prevented `NativeRuntimeAdapter`, `ExternalAgentAdapter`, and `GoogleAdkAdapter` from returning `ok: true` for planning summaries, prepared CLI instructions, or unwired invocations.
|
|
11
|
+
- **Mandatory Bound Verification & Stale Receipt Invalidation (`src/intelligence/orchestration/`, `src/intelligence/verification/`)**:
|
|
12
|
+
- Enforced real `IndependentVerificationEngine` verification before `COMPLETED` / `verified: true` can be recorded; missing, errored, timed-out, skipped, or mismatched verifiers halt cleanly instead of defaulting to verified.
|
|
13
|
+
- Bound `ExecutionReceipt` records to `executionId`, `stageId`, `verifierId`/`verifierVersion`, `workspaceFingerprint`, and actual workspace file contents, with `invalidateStaleReceipts()` invalidating receipts when files change after verification.
|
|
14
|
+
- **Process Boundary & Non-Sandbox Disclosure (`src/intelligence/runtime/boundary.ts`, `src/utils/proc.ts`)**:
|
|
15
|
+
- Added pre-spawn shell blocking, `cwd` containment/symlink checks, `replaceEnv: true` with minimal environment allowlisting (`createMinimalExecutionEnv`), OS process-tree cleanup on timeout/abort (`killProcessTree`), and explicit `sandboxed: false` (`unavailable-cwd-only`) capability reporting.
|
|
16
|
+
- **Knowledge Distribution Hardening (`src/standards/distribution/`)**:
|
|
17
|
+
- Rejected duplicate or case-conflicting paths in `manifest.files`, serialized concurrent cache mutations with `withLock`, enforced HTTPS for remote HTTP sync URLs, rejected HTTP redirects (`redirect: 'manual'`), wrapped TLS errors, and capped response payload size.
|
|
18
|
+
- **Automated Release Trigger (`.github/workflows/release.yml`)**:
|
|
19
|
+
- Triggered Release automatically on `package.json` version bumps on `main` (auto-tagging `vX.Y.Z` after `release:check` passes) or semver tag pushes, skipping cleanly when the version is already published on npm.
|
|
20
|
+
|
|
5
21
|
## [0.5.0] - 2026-12-01
|
|
6
22
|
|
|
7
23
|
### Added
|
|
@@ -25,6 +25,15 @@ export declare class OrchestrationEngine {
|
|
|
25
25
|
private store;
|
|
26
26
|
private lockManager;
|
|
27
27
|
constructor(router: IntelligentRouter, store: OrchestrationStore);
|
|
28
|
+
/** Compute a workspace + modified-file SHA-256 fingerprint to bind verification receipts to exact workspace state. */
|
|
29
|
+
computeWorkspaceFingerprint(workspaceRoot: string | undefined, filePaths: string[]): Promise<string>;
|
|
30
|
+
/** Safely load bounded contents of modified files for independent verification without leaking secrets. */
|
|
31
|
+
private loadModifiedFileContents;
|
|
32
|
+
/** Reject and invalidate any stage verification receipt whose workspace files changed since verification. */
|
|
33
|
+
invalidateStaleReceipts(runId: string, workspaceRoot?: string): Promise<{
|
|
34
|
+
run: OrchestrationRun;
|
|
35
|
+
invalidatedStages: string[];
|
|
36
|
+
}>;
|
|
28
37
|
/**
|
|
29
38
|
* Detects potentially destructive operations in stage inputs or prompt.
|
|
30
39
|
*/
|
|
@@ -1,8 +1,14 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
1
2
|
import { StageLockManager } from './lock-manager.js';
|
|
2
3
|
import { NativeRuntimeAdapter } from '../runtime/native.js';
|
|
4
|
+
import { createExecutionId } from '../runtime/boundary.js';
|
|
3
5
|
import { isValidStateTransition } from './types.js';
|
|
4
6
|
import { DevWorkspaceError } from '../../errors/index.js';
|
|
5
7
|
import { redact } from '../../security/redact.js';
|
|
8
|
+
import { isSensitiveFile } from '../../security/files.js';
|
|
9
|
+
import { readTextBounded } from '../../utils/fs.js';
|
|
10
|
+
import { resolveInside } from '../../utils/paths.js';
|
|
11
|
+
import { run as runProc } from '../../utils/proc.js';
|
|
6
12
|
export class OrchestrationEngine {
|
|
7
13
|
router;
|
|
8
14
|
store;
|
|
@@ -12,6 +18,88 @@ export class OrchestrationEngine {
|
|
|
12
18
|
this.store = store;
|
|
13
19
|
this.lockManager = new StageLockManager();
|
|
14
20
|
}
|
|
21
|
+
/** Compute a workspace + modified-file SHA-256 fingerprint to bind verification receipts to exact workspace state. */
|
|
22
|
+
async computeWorkspaceFingerprint(workspaceRoot, filePaths) {
|
|
23
|
+
const hash = crypto.createHash('sha256');
|
|
24
|
+
if (workspaceRoot) {
|
|
25
|
+
try {
|
|
26
|
+
const gitRes = await runProc('git', ['rev-parse', 'HEAD'], { cwd: workspaceRoot, timeoutMs: 2_000 });
|
|
27
|
+
hash.update(`head:${gitRes.ok ? gitRes.stdout.trim() : 'nogit'}\n`);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
hash.update('head:nogit\n');
|
|
31
|
+
}
|
|
32
|
+
for (const rel of [...filePaths].sort()) {
|
|
33
|
+
hash.update(`file:${rel}:`);
|
|
34
|
+
try {
|
|
35
|
+
const full = resolveInside(workspaceRoot, rel);
|
|
36
|
+
const content = await readTextBounded(full, 256 * 1024);
|
|
37
|
+
hash.update(content ?? 'binary-or-large');
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
hash.update('missing-or-unsafe');
|
|
41
|
+
}
|
|
42
|
+
hash.update('\n');
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
hash.update(`files:${[...filePaths].sort().join(',')}`);
|
|
47
|
+
}
|
|
48
|
+
return hash.digest('hex');
|
|
49
|
+
}
|
|
50
|
+
/** Safely load bounded contents of modified files for independent verification without leaking secrets. */
|
|
51
|
+
async loadModifiedFileContents(workspaceRoot, filePaths) {
|
|
52
|
+
const out = [];
|
|
53
|
+
for (const rel of filePaths) {
|
|
54
|
+
if (!workspaceRoot || isSensitiveFile(rel)) {
|
|
55
|
+
out.push({ path: rel, content: '' });
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const full = resolveInside(workspaceRoot, rel);
|
|
60
|
+
const content = await readTextBounded(full, 256 * 1024);
|
|
61
|
+
out.push({ path: rel, content: content ?? '' });
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
out.push({ path: rel, content: '' });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
/** Reject and invalidate any stage verification receipt whose workspace files changed since verification. */
|
|
70
|
+
async invalidateStaleReceipts(runId, workspaceRoot) {
|
|
71
|
+
const loaded = await this.store.getRun(runId);
|
|
72
|
+
if (!loaded) {
|
|
73
|
+
throw new DevWorkspaceError('NOT_FOUND', `Orchestration run "${runId}" not found.`);
|
|
74
|
+
}
|
|
75
|
+
const invalidatedStages = [];
|
|
76
|
+
for (const stage of loaded.stages) {
|
|
77
|
+
if (!stage.receipt || !stage.receipt.verified)
|
|
78
|
+
continue;
|
|
79
|
+
const root = workspaceRoot ?? stage.receipt.cwd;
|
|
80
|
+
const currentFp = await this.computeWorkspaceFingerprint(root, stage.receipt.filesModified);
|
|
81
|
+
if (stage.receipt.workspaceFingerprint && currentFp !== stage.receipt.workspaceFingerprint) {
|
|
82
|
+
stage.receipt.verified = false;
|
|
83
|
+
stage.receipt.stale = true;
|
|
84
|
+
stage.receipt.verificationStatus = 'NOT_TESTED';
|
|
85
|
+
stage.status = 'VERIFYING';
|
|
86
|
+
stage.outputs = { ...(stage.outputs ?? {}), verified: false, stale: true, receipt: stage.receipt };
|
|
87
|
+
invalidatedStages.push(stage.id);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (invalidatedStages.length > 0) {
|
|
91
|
+
if (loaded.state === 'COMPLETED' || loaded.state === 'SUCCEEDED') {
|
|
92
|
+
loaded.state = 'VERIFYING';
|
|
93
|
+
}
|
|
94
|
+
loaded.checkpoints.push({
|
|
95
|
+
at: new Date().toISOString(),
|
|
96
|
+
state: loaded.state,
|
|
97
|
+
note: `Invalidated stale verification receipt(s) due to workspace changes: ${invalidatedStages.join(', ')}.`,
|
|
98
|
+
});
|
|
99
|
+
await this.store.saveRun(loaded);
|
|
100
|
+
}
|
|
101
|
+
return { run: loaded, invalidatedStages };
|
|
102
|
+
}
|
|
15
103
|
/**
|
|
16
104
|
* Detects potentially destructive operations in stage inputs or prompt.
|
|
17
105
|
*/
|
|
@@ -287,6 +375,7 @@ export class OrchestrationEngine {
|
|
|
287
375
|
let stageSuccess = false;
|
|
288
376
|
let lastError;
|
|
289
377
|
let receipt;
|
|
378
|
+
let haltState = null;
|
|
290
379
|
while (!stageSuccess && stage.retryCount <= run.maxRetries) {
|
|
291
380
|
try {
|
|
292
381
|
const execRes = await adapter.execute({
|
|
@@ -299,36 +388,94 @@ export class OrchestrationEngine {
|
|
|
299
388
|
signal: options.signal,
|
|
300
389
|
command: stage.inputs.command,
|
|
301
390
|
cwd: options.workspaceRoot,
|
|
391
|
+
workspaceRoot: options.workspaceRoot,
|
|
392
|
+
explicitApproval: Boolean(run.approvedBy || options.explicitApproval),
|
|
302
393
|
});
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
cwd: options.workspaceRoot,
|
|
321
|
-
exitCode: execRes.exitCode ?? 0,
|
|
394
|
+
const execId = execRes.executionId ?? createExecutionId('exec');
|
|
395
|
+
const execStatus = execRes.status ?? (execRes.ok ? 'SUCCEEDED' : 'FAILED');
|
|
396
|
+
const execFiles = execRes.filesModified ?? [];
|
|
397
|
+
const baseReceipt = (verified, verificationStatus, fp, report) => ({
|
|
398
|
+
executionId: execId,
|
|
399
|
+
stageId: stage.id,
|
|
400
|
+
executionStatus: execStatus,
|
|
401
|
+
verificationStatus,
|
|
402
|
+
verifierId: report?.verifierId,
|
|
403
|
+
verifierVersion: report?.verifierVersion,
|
|
404
|
+
workspaceFingerprint: fp,
|
|
405
|
+
verifiedAt: report?.verifiedAt,
|
|
406
|
+
checksPerformed: report?.checksPerformed ?? [],
|
|
407
|
+
evidenceRefs: report?.evidenceRefs ?? execFiles,
|
|
408
|
+
command: execRes.command ?? stage.inputs.command,
|
|
409
|
+
cwd: execRes.cwd ?? options.workspaceRoot,
|
|
410
|
+
exitCode: execRes.exitCode,
|
|
322
411
|
durationMs: execRes.durationMs,
|
|
323
412
|
stdout: execRes.stdout,
|
|
324
413
|
stderr: execRes.stderr,
|
|
325
414
|
timedOut: execRes.timedOut,
|
|
326
415
|
aborted: execRes.aborted,
|
|
327
|
-
filesModified:
|
|
328
|
-
executedAt: new Date().toISOString(),
|
|
329
|
-
verified
|
|
330
|
-
verificationReport,
|
|
331
|
-
};
|
|
416
|
+
filesModified: execFiles,
|
|
417
|
+
executedAt: execRes.endedAt ?? new Date().toISOString(),
|
|
418
|
+
verified,
|
|
419
|
+
verificationReport: report,
|
|
420
|
+
});
|
|
421
|
+
if (execRes.isPlaceholder) {
|
|
422
|
+
throw new Error(execRes.error || 'Placeholder runtime cannot execute stages.');
|
|
423
|
+
}
|
|
424
|
+
if (execStatus === 'TIMED_OUT' || execRes.timedOut || (timeoutMs > 0 && Date.now() - startTs > timeoutMs)) {
|
|
425
|
+
stage.receipt = baseReceipt(false, 'NOT_TESTED');
|
|
426
|
+
lastError = execRes.error || `Stage execution timed out${timeoutMs > 0 ? ` after ${timeoutMs}ms` : ''}.`;
|
|
427
|
+
haltState = 'TIMED_OUT';
|
|
428
|
+
break;
|
|
429
|
+
}
|
|
430
|
+
if (execStatus === 'CANCELLED' || execRes.aborted) {
|
|
431
|
+
stage.receipt = baseReceipt(false, 'NOT_TESTED');
|
|
432
|
+
lastError = execRes.error || 'Stage execution cancelled.';
|
|
433
|
+
haltState = 'CANCELLED';
|
|
434
|
+
break;
|
|
435
|
+
}
|
|
436
|
+
if (execStatus === 'PREPARED' || execStatus === 'NOT_EXECUTED' || execStatus === 'UNSUPPORTED' || execStatus === 'BLOCKED') {
|
|
437
|
+
stage.receipt = baseReceipt(false, 'NOT_TESTED');
|
|
438
|
+
lastError = execRes.reason || execRes.error || `Stage did not execute (${execStatus}).`;
|
|
439
|
+
haltState = 'BLOCKED';
|
|
440
|
+
break;
|
|
441
|
+
}
|
|
442
|
+
if (execStatus !== 'SUCCEEDED' || !execRes.ok) {
|
|
443
|
+
throw new Error(execRes.error || 'Stage execution failed in runtime adapter.');
|
|
444
|
+
}
|
|
445
|
+
// Mandatory independent verification gate: never default to verified without a real verifier run.
|
|
446
|
+
const rootForVerify = options.workspaceRoot ?? execRes.cwd;
|
|
447
|
+
const preVerifyFingerprint = await this.computeWorkspaceFingerprint(rootForVerify, execFiles);
|
|
448
|
+
if (!options.verificationEngine) {
|
|
449
|
+
const unverifiedReceipt = baseReceipt(false, 'NOT_TESTED', preVerifyFingerprint);
|
|
450
|
+
stage.receipt = unverifiedReceipt;
|
|
451
|
+
stage.outputs = { outcome: 'unverified', verified: false, receipt: unverifiedReceipt };
|
|
452
|
+
lastError = 'Independent verification engine is required before verified completion; execution finished unverified.';
|
|
453
|
+
haltState = 'BLOCKED';
|
|
454
|
+
break;
|
|
455
|
+
}
|
|
456
|
+
this.transitionState(run, 'VERIFYING', `Running independent verification for stage "${stage.name}".`, stage.id);
|
|
457
|
+
const checks = stage.inputs.contractChecks ?? [];
|
|
458
|
+
const modified = await this.loadModifiedFileContents(rootForVerify, execFiles);
|
|
459
|
+
const verificationReport = await options.verificationEngine.verify(checks, modified, [], stage.retryCount, run.maxRetries, {
|
|
460
|
+
executionId: execId,
|
|
461
|
+
stageId: stage.id,
|
|
462
|
+
workspaceFingerprint: preVerifyFingerprint,
|
|
463
|
+
evidenceRefs: execFiles,
|
|
464
|
+
});
|
|
465
|
+
if (verificationReport.executionId && verificationReport.executionId !== execId) {
|
|
466
|
+
throw new Error(`Stale verification receipt rejected: bound to "${verificationReport.executionId}", expected "${execId}".`);
|
|
467
|
+
}
|
|
468
|
+
if (verificationReport.workspaceFingerprint && verificationReport.workspaceFingerprint !== preVerifyFingerprint) {
|
|
469
|
+
throw new Error('Stale verification receipt rejected: workspace fingerprint mismatch.');
|
|
470
|
+
}
|
|
471
|
+
const postVerifyFingerprint = await this.computeWorkspaceFingerprint(rootForVerify, execFiles);
|
|
472
|
+
if (postVerifyFingerprint !== preVerifyFingerprint) {
|
|
473
|
+
throw new Error('Verification invalidated: workspace files changed during verification.');
|
|
474
|
+
}
|
|
475
|
+
if (!verificationReport.canComplete || !verificationReport.mandatoryGatesPassed || verificationReport.verificationStatus !== 'PASS') {
|
|
476
|
+
throw new Error(`Verification failed (${verificationReport.verificationStatus}): ${verificationReport.summary}`);
|
|
477
|
+
}
|
|
478
|
+
receipt = baseReceipt(true, 'PASS', preVerifyFingerprint, verificationReport);
|
|
332
479
|
stage.status = 'COMPLETED';
|
|
333
480
|
stage.completedAt = new Date().toISOString();
|
|
334
481
|
stage.outputs = { outcome: 'success', verified: true, receipt };
|
|
@@ -350,6 +497,14 @@ export class OrchestrationEngine {
|
|
|
350
497
|
}
|
|
351
498
|
}
|
|
352
499
|
this.lockManager.releaseAllForStage(stage.id);
|
|
500
|
+
if (haltState) {
|
|
501
|
+
stage.status = haltState;
|
|
502
|
+
stage.error = redact(lastError ?? `Execution halted (${haltState}).`);
|
|
503
|
+
run.error = stage.error;
|
|
504
|
+
this.transitionState(run, haltState, stage.error, stage.id);
|
|
505
|
+
await this.store.saveRun(run);
|
|
506
|
+
return run;
|
|
507
|
+
}
|
|
353
508
|
if (timeoutMs > 0 && Date.now() - startTs > timeoutMs) {
|
|
354
509
|
stage.status = 'TIMED_OUT';
|
|
355
510
|
this.transitionState(run, 'TIMED_OUT', `Execution timed out after ${timeoutMs}ms.`, stage.id);
|
|
@@ -361,14 +516,19 @@ export class OrchestrationEngine {
|
|
|
361
516
|
stage.error = lastError;
|
|
362
517
|
throw new Error(lastError || `Stage "${stage.name}" failed after ${run.maxRetries} retries.`);
|
|
363
518
|
}
|
|
364
|
-
this.transitionState(run, 'RUNNING', `Stage "${stage.name}" completed successfully.`, stage.id);
|
|
519
|
+
this.transitionState(run, 'RUNNING', `Stage "${stage.name}" completed and verified successfully.`, stage.id);
|
|
365
520
|
await this.store.saveRun(run);
|
|
366
521
|
}
|
|
367
|
-
//
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
522
|
+
// Final Completion: only reachable when every stage executed and passed independent verification
|
|
523
|
+
const allStagesVerified = run.stages.every((s) => s.status === 'COMPLETED' && s.receipt?.verified === true && s.receipt.verificationStatus === 'PASS');
|
|
524
|
+
if (!allStagesVerified) {
|
|
525
|
+
this.transitionState(run, 'BLOCKED', 'Run cannot complete because one or more stages lack verified completion.');
|
|
526
|
+
run.error = 'One or more stages lack verified completion.';
|
|
527
|
+
run.metrics.durationMs = Date.now() - startTs;
|
|
528
|
+
await this.store.saveRun(run);
|
|
529
|
+
return run;
|
|
530
|
+
}
|
|
531
|
+
this.transitionState(run, 'COMPLETED', 'Workflow executed and independently verified.');
|
|
372
532
|
run.metrics.durationMs = Date.now() - startTs;
|
|
373
533
|
await this.store.saveRun(run);
|
|
374
534
|
return run;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.js","sourceRoot":"","sources":["../../../src/intelligence/orchestration/engine.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAS5D,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE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O;YACV,KAAK;SACN,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,KAAa,EAAE,MAAM,GAAG,wBAAwB;QAC3D,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAC3C,IAAI,CAAC,GAAG,EAAE,CAAC;YACT,MAAM,IAAI,iBAAiB,CAAC,WAAW,EAAE,sBAAsB,KAAK,cAAc,CAAC,CAAC;QACtF,CAAC;QAED,IAAI,CAAC,WAAW,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;YACvF,MAAM,IAAI,iBAAiB,CAAC,OAAO,EAAE,sBAAsB,KAAK,wBAAwB,GAAG,CAAC,KAAK,IAAI,CAAC,CAAC;QACzG,CAAC;QAED,2BAA2B;QAC3B,KAAK,MAAM,KAAK,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;YAC/B,IAAI,CAAC,WAAW,CAAC,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAChD,CAAC;QAED,GAAG,CAAC,KAAK,GAAG,MAAM,CAAC;QACnB,GAAG,CAAC,kBAAkB,GAAG,MAAM,CAAC;QAChC,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC;QAC/C,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC9B,OAAO,GAAG,CAAC;IACb,CAAC;CACF","sourcesContent":["import { IntelligentRouter } from '../routing/router.js';\nimport { OrchestrationStore } from './store.js';\nimport { StageLockManager } from './lock-manager.js';\nimport { NativeRuntimeAdapter } from '../runtime/native.js';\nimport type {\n ExecutionReceipt,\n ExecutionStage,\n OrchestrationRun,\n OrchestrationState,\n PlanOptions,\n RunOptions,\n} from './types.js';\nimport { isValidStateTransition } from './types.js';\nimport { DevWorkspaceError } from '../../errors/index.js';\nimport { redact } from '../../security/redact.js';\n\nexport interface DryRunPlanSummary {\n runId: string;\n state: OrchestrationState;\n request: string;\n strategy: string;\n totalStages: number;\n requiresApproval: boolean;\n stages: Array<{\n id: string;\n name: string;\n agentId: string;\n claimedFiles: string[];\n isDestructive: boolean;\n requiresApproval: boolean;\n dependsOn: string[];\n }>;\n estimatedDurationMs: number;\n estimatedTokens: number;\n}\n\nexport class OrchestrationEngine {\n private router: IntelligentRouter;\n private store: OrchestrationStore;\n private lockManager: StageLockManager;\n\n constructor(router: IntelligentRouter, store: OrchestrationStore) {\n this.router = router;\n this.store = store;\n this.lockManager = new StageLockManager();\n }\n\n /**\n * Detects potentially destructive operations in stage inputs or prompt.\n */\n private detectDestructiveOperation(text: string, inputs: Record<string, unknown> = {}): { isDestructive: boolean; reasons: string[] } {\n const reasons: string[] = [];\n const fullText = [text, JSON.stringify(inputs)].join(' ');\n\n // 1. Destructive SQL operations\n const sqlRegex = /\\b(DROP\\s+TABLE|DROP\\s+DATABASE|TRUNCATE\\s+TABLE|ALTER\\s+TABLE\\s+.*\\s+DROP|DELETE\\s+FROM\\s+\\w+\\s*(?:;|$))\\b/i;\n if (sqlRegex.test(fullText)) {\n reasons.push('Contains destructive SQL statement (DROP / TRUNCATE / ALTER DROP / unqualified DELETE)');\n }\n\n // 2. Destructive filesystem operations\n const fsRegex = /\\b(?:rm\\s+-[a-zA-Z]*[rf][a-zA-Z]*|format\\s+[A-Z]:|mkfs|dropdb|prisma\\s+migrate\\s+reset)\\b/i;\n if (fsRegex.test(fullText)) {\n reasons.push('Contains destructive filesystem or database reset command');\n }\n\n // 3. Destructive deploy / credential rotation\n const deployRegex = /\\b(deploy\\s+--prod|publish\\s+--force|rotate-all-keys)\\b/i;\n if (deployRegex.test(fullText)) {\n reasons.push('Contains production deployment or credential rotation command');\n }\n\n return {\n isDestructive: reasons.length > 0,\n reasons,\n };\n }\n\n /**\n * Safely transitions run state, verifying valid transition rules.\n */\n private transitionState(run: OrchestrationRun, newState: OrchestrationState, note: string, stageId?: string): void {\n if (!isValidStateTransition(run.state, newState)) {\n throw new DevWorkspaceError('USAGE', `Invalid state transition from \"${run.state}\" to \"${newState}\".`);\n }\n\n run.state = newState;\n run.updatedAt = new Date().toISOString();\n run.checkpoints.push({\n at: run.updatedAt,\n state: newState,\n stageId,\n note: redact(note),\n });\n }\n\n async plan(options: PlanOptions): Promise<OrchestrationRun> {\n const req = (options.request || options.prompt || options.title || '').trim();\n\n // Idempotency check: if a run with this idempotency key already exists, return it\n if (options.idempotencyKey) {\n const existing = await this.store.getRunByIdempotencyKey(options.idempotencyKey);\n if (existing) {\n return existing;\n }\n }\n\n const routing = await this.router.route({\n workspaceRoot: options.workspaceRoot || '',\n request: req,\n taskType: undefined,\n });\n\n const runId = this.store.generateRunId();\n const stages: ExecutionStage[] = [];\n\n // Stage 1: Analysis & Requirements Formulation\n const analysisAgent = routing.selectedAgents.find((a) => a.agentId === 'planner' || a.agentId === 'research') || routing.selectedAgents[0];\n const stage1Destructive = this.detectDestructiveOperation(req, { taskType: routing.taskType });\n stages.push({\n id: 'stage-1-analysis',\n name: 'Task Decomposition & Architecture Context',\n agentId: analysisAgent?.agentId || 'research',\n skillIds: routing.selectedSkills.map((s) => s.skillId),\n status: 'PENDING',\n dependsOn: [],\n claimedFiles: [],\n inputs: { request: req, taskType: routing.taskType },\n modifiedFiles: [],\n retryCount: 0,\n isDestructive: stage1Destructive.isDestructive,\n requiresApproval: stage1Destructive.isDestructive,\n });\n\n // Stage 2: Implementation (if not read-only)\n const devAgent = routing.selectedAgents.find((a) => a.agentId === 'developer' || a.agentId === 'database-specialist' || a.agentId === 'debugger');\n if (devAgent) {\n const stage2Destructive = this.detectDestructiveOperation(req, { strategy: routing.strategy });\n stages.push({\n id: 'stage-2-implementation',\n name: `Implementation by ${devAgent.role}`,\n agentId: devAgent.agentId,\n skillIds: routing.selectedSkills.map((s) => s.skillId),\n status: 'PENDING',\n dependsOn: ['stage-1-analysis'],\n claimedFiles: routing.relevantFiles,\n inputs: { strategy: routing.strategy },\n modifiedFiles: [],\n retryCount: 0,\n isDestructive: stage2Destructive.isDestructive,\n requiresApproval: stage2Destructive.isDestructive,\n });\n }\n\n // Stage 3: Independent Review & Verification\n const reviewerAgent = routing.selectedAgents.find((a) => a.agentId === 'code-reviewer' || a.agentId === 'security-auditor' || a.agentId === 'testing');\n if (reviewerAgent) {\n stages.push({\n id: 'stage-3-verification',\n name: `Independent Verification by ${reviewerAgent.role}`,\n agentId: reviewerAgent.agentId,\n skillIds: ['code-review', 'security-audit'],\n status: 'PENDING',\n dependsOn: devAgent ? ['stage-2-implementation'] : ['stage-1-analysis'],\n claimedFiles: [],\n inputs: { verificationContract: 'standard' },\n modifiedFiles: [],\n retryCount: 0,\n isDestructive: false,\n requiresApproval: false,\n });\n }\n\n const hasDestructive = stages.some((s) => s.isDestructive);\n const requiresApproval = (routing.requiredApprovals.length > 0 || routing.complexity === 'CRITICAL' || hasDestructive) && !options.autoApprove;\n const initialState: OrchestrationState = requiresApproval ? 'AWAITING_APPROVAL' : 'READY';\n\n const now = new Date().toISOString();\n const run: OrchestrationRun = {\n runId,\n taskId: options.taskId,\n idempotencyKey: options.idempotencyKey,\n request: req,\n state: initialState,\n routing,\n stages,\n currentStageIndex: 0,\n checkpoints: [\n {\n at: now,\n state: 'CREATED',\n note: `Plan generated with ${stages.length} stage(s) under strategy ${routing.strategy}.`,\n },\n {\n at: now,\n state: initialState,\n note: requiresApproval ? 'Plan requires developer approval before execution.' : 'Plan validated and ready for execution.',\n },\n ],\n retryCount: 0,\n maxRetries: options.maxRetries ?? 3,\n metrics: {\n durationMs: 0,\n tokensEstimate: routing.estimatedResources.tokensEstimate,\n filesModifiedCount: 0,\n stagesCompleted: 0,\n correctionsCount: 0,\n },\n createdAt: now,\n updatedAt: now,\n isDryRun: options.dryRun,\n };\n\n await this.store.saveRun(run);\n return run;\n }\n\n async approve(runId: string, approvedBy = 'user'): Promise<OrchestrationRun> {\n const run = await this.store.getRun(runId);\n if (!run) {\n throw new DevWorkspaceError('NOT_FOUND', `Orchestration run \"${runId}\" not found.`);\n }\n\n if (run.state !== 'AWAITING_APPROVAL' && run.state !== 'WAITING_APPROVAL') {\n throw new DevWorkspaceError('USAGE', `Run \"${runId}\" is in state \"${run.state}\", not AWAITING_APPROVAL.`);\n }\n\n run.approvedBy = approvedBy;\n run.approvedAt = new Date().toISOString();\n this.transitionState(run, 'READY', `Plan approved by ${approvedBy}. Ready for execution.`);\n\n await this.store.saveRun(run);\n return run;\n }\n\n async dryRun(runId: string): Promise<DryRunPlanSummary> {\n const run = await this.store.getRun(runId);\n if (!run) {\n throw new DevWorkspaceError('NOT_FOUND', `Orchestration run \"${runId}\" not found.`);\n }\n\n return {\n runId: run.runId,\n state: run.state,\n request: run.request,\n strategy: run.routing?.strategy ?? 'STANDARD',\n totalStages: run.stages.length,\n requiresApproval: run.state === 'AWAITING_APPROVAL' || run.state === 'WAITING_APPROVAL',\n stages: run.stages.map((s) => ({\n id: s.id,\n name: s.name,\n agentId: s.agentId,\n claimedFiles: s.claimedFiles,\n isDestructive: Boolean(s.isDestructive),\n requiresApproval: Boolean(s.requiresApproval),\n dependsOn: s.dependsOn,\n })),\n estimatedDurationMs: run.metrics.durationMs,\n estimatedTokens: run.metrics.tokensEstimate,\n };\n }\n\n async run(options: RunOptions): Promise<OrchestrationRun> {\n const run = await this.store.getRun(options.runId);\n if (!run) {\n throw new DevWorkspaceError('NOT_FOUND', `Orchestration run \"${options.runId}\" not found.`);\n }\n\n // Duplicate execution protection: do not re-run an already completed or running run\n if (run.state === 'COMPLETED' || run.state === 'SUCCEEDED') {\n return run;\n }\n if (run.state === 'RUNNING') {\n throw new DevWorkspaceError('USAGE', `Run \"${run.runId}\" is already running.`);\n }\n if (run.state === 'CANCELLED' || run.state === 'TIMED_OUT') {\n throw new DevWorkspaceError('USAGE', `Cannot run \"${run.runId}\" in terminal state \"${run.state}\".`);\n }\n\n // Approval gating: check if approval is required\n if (run.state === 'AWAITING_APPROVAL' || run.state === 'WAITING_APPROVAL') {\n if (options.explicitApproval) {\n run.approvedBy = run.approvedBy ?? 'explicit-opt-in';\n run.approvedAt = new Date().toISOString();\n this.transitionState(run, 'READY', 'Execution explicitly approved by developer option.');\n } else {\n throw new DevWorkspaceError('USAGE', `Run \"${run.runId}\" requires developer approval before execution.`);\n }\n }\n\n if (run.state !== 'READY' && run.state !== 'PAUSED' && run.state !== 'BLOCKED') {\n throw new DevWorkspaceError('USAGE', `Run \"${run.runId}\" is in state \"${run.state}\"; only READY, PAUSED or unblocked runs can be executed.`);\n }\n\n // Certify runtime adapter: placeholder runtimes MUST NEVER return successful execution\n const adapter = options.runtimeAdapter ?? new NativeRuntimeAdapter();\n if (adapter.isPlaceholder) {\n this.transitionState(run, 'FAILED', 'Placeholder runtime cannot return a successful execution.');\n run.error = 'No placeholder runtime can return a successful execution.';\n await this.store.saveRun(run);\n return run;\n }\n\n const startTs = Date.now();\n const timeoutMs = (options.timeoutSeconds ? options.timeoutSeconds * 1000 : options.timeoutMs) ?? 0;\n\n this.transitionState(run, 'RUNNING', 'Execution started.');\n await this.store.saveRun(run);\n\n try {\n for (let i = run.currentStageIndex; i < run.stages.length; i++) {\n const stage = run.stages[i]!;\n run.currentStageIndex = i;\n\n // Check cancellation\n if (options.signal?.aborted) {\n this.transitionState(run, 'CANCELLED', 'Run cancelled by user request.', stage.id);\n await this.store.saveRun(run);\n return run;\n }\n\n // Check timeout\n if (timeoutMs > 0 && Date.now() - startTs > timeoutMs) {\n stage.status = 'TIMED_OUT';\n this.transitionState(run, 'TIMED_OUT', `Execution timed out after ${timeoutMs}ms.`, stage.id);\n this.lockManager.releaseAllForStage(stage.id);\n await this.store.saveRun(run);\n return run;\n }\n\n // Destructive operations safety gate\n if (stage.isDestructive && !run.approvedBy && !options.explicitApproval) {\n stage.status = 'WAITING_APPROVAL';\n this.transitionState(run, 'WAITING_APPROVAL', `Execution halted: stage \"${stage.name}\" requires explicit approval for destructive operations.`, stage.id);\n await this.store.saveRun(run);\n return run;\n }\n\n // Single-writer lock acquisition for claimed files\n if (stage.claimedFiles.length > 0) {\n const lockResult = await this.lockManager.acquire(stage.id, stage.agentId, stage.claimedFiles, 'write');\n if (!lockResult.acquired) {\n stage.status = 'BLOCKED';\n this.transitionState(run, 'BLOCKED', `Execution blocked: file lock conflict on ${lockResult.conflictingFiles?.join(', ')}.`, stage.id);\n await this.store.saveRun(run);\n return run;\n }\n }\n\n stage.status = 'RUNNING';\n stage.startedAt = new Date().toISOString();\n await this.store.saveRun(run);\n\n // Execute stage work with runtime adapter\n let stageSuccess = false;\n let lastError: string | undefined;\n let receipt: ExecutionReceipt | undefined;\n\n while (!stageSuccess && stage.retryCount <= run.maxRetries) {\n try {\n const execRes = await adapter.execute({\n agentId: stage.agentId,\n role: stage.name,\n prompt: run.request,\n skills: stage.skillIds,\n contextFiles: stage.claimedFiles,\n timeoutMs: timeoutMs > 0 ? Math.max(1000, timeoutMs - (Date.now() - startTs)) : undefined,\n signal: options.signal,\n command: (stage.inputs.command as string[] | undefined),\n cwd: options.workspaceRoot,\n });\n\n if (execRes.isPlaceholder || !execRes.ok) {\n throw new Error(execRes.error || 'Stage execution failed in runtime adapter.');\n }\n\n // Independent verification gate\n let verificationReport: any = undefined;\n if (options.verificationEngine) {\n this.transitionState(run, 'VERIFYING', `Running independent verification for stage \"${stage.name}\".`, stage.id);\n const checks = (stage.inputs.contractChecks as any) ?? [];\n const modified = (execRes.filesModified ?? []).map((f) => ({ path: f, content: '' }));\n verificationReport = await options.verificationEngine.verify(checks, modified);\n\n if (!verificationReport.canComplete) {\n throw new Error(`Verification failed: ${verificationReport.summary}`);\n }\n }\n\n // Execution receipt\n receipt = {\n command: (stage.inputs.command as string[] | undefined),\n cwd: options.workspaceRoot,\n exitCode: execRes.exitCode ?? 0,\n durationMs: execRes.durationMs,\n stdout: execRes.stdout,\n stderr: execRes.stderr,\n timedOut: execRes.timedOut,\n aborted: execRes.aborted,\n filesModified: execRes.filesModified,\n executedAt: new Date().toISOString(),\n verified: true,\n verificationReport,\n };\n\n stage.status = 'COMPLETED';\n stage.completedAt = new Date().toISOString();\n stage.outputs = { outcome: 'success', verified: true, receipt };\n stage.receipt = receipt;\n run.metrics.stagesCompleted += 1;\n stageSuccess = true;\n } catch (err: any) {\n lastError = err.message;\n if (stage.retryCount < run.maxRetries) {\n stage.retryCount += 1;\n run.metrics.correctionsCount += 1;\n this.transitionState(run, 'CORRECTING', `Retrying stage \"${stage.name}\" (attempt ${stage.retryCount}/${run.maxRetries}): ${redact(err.message)}`, stage.id);\n await this.store.saveRun(run);\n } else {\n break;\n }\n }\n }\n\n this.lockManager.releaseAllForStage(stage.id);\n\n if (timeoutMs > 0 && Date.now() - startTs > timeoutMs) {\n stage.status = 'TIMED_OUT';\n this.transitionState(run, 'TIMED_OUT', `Execution timed out after ${timeoutMs}ms.`, stage.id);\n await this.store.saveRun(run);\n return run;\n }\n\n if (!stageSuccess) {\n stage.status = 'FAILED';\n stage.error = lastError;\n throw new Error(lastError || `Stage \"${stage.name}\" failed after ${run.maxRetries} retries.`);\n }\n\n this.transitionState(run, 'RUNNING', `Stage \"${stage.name}\" completed successfully.`, stage.id);\n await this.store.saveRun(run);\n }\n\n // Verification transition\n this.transitionState(run, 'VERIFYING', 'All stages finished. Running independent verification gates.');\n await this.store.saveRun(run);\n\n // Final Completion\n this.transitionState(run, 'COMPLETED', 'Workflow successfully verified and completed.');\n run.metrics.durationMs = Date.now() - startTs;\n await this.store.saveRun(run);\n return run;\n } catch (err: any) {\n this.transitionState(run, 'FAILED', `Execution failed: ${err.message}`);\n run.error = err.message;\n run.metrics.durationMs = Date.now() - startTs;\n await this.store.saveRun(run);\n return run;\n }\n }\n\n async resume(runId: string, options?: Omit<RunOptions, 'runId'>): Promise<OrchestrationRun> {\n const run = await this.store.getRun(runId);\n if (!run) {\n throw new DevWorkspaceError('NOT_FOUND', `Orchestration run \"${runId}\" not found.`);\n }\n\n if (run.state !== 'PAUSED' && run.state !== 'BLOCKED' && run.state !== 'WAITING_APPROVAL' && run.state !== 'AWAITING_APPROVAL') {\n throw new DevWorkspaceError('USAGE', `Run \"${runId}\" is in state \"${run.state}\"; only PAUSED, BLOCKED, or approved runs can be resumed.`);\n }\n\n this.transitionState(run, 'READY', 'Run resumed by developer request.');\n await this.store.saveRun(run);\n\n return this.run({\n ...options,\n runId,\n });\n }\n\n async cancel(runId: string, reason = 'Cancelled by developer'): Promise<OrchestrationRun> {\n const run = await this.store.getRun(runId);\n if (!run) {\n throw new DevWorkspaceError('NOT_FOUND', `Orchestration run \"${runId}\" not found.`);\n }\n\n if (['COMPLETED', 'SUCCEEDED', 'FAILED', 'CANCELLED', 'TIMED_OUT'].includes(run.state)) {\n throw new DevWorkspaceError('USAGE', `Cannot cancel run \"${runId}\" in terminal state \"${run.state}\".`);\n }\n\n // Release any active locks\n for (const stage of run.stages) {\n this.lockManager.releaseAllForStage(stage.id);\n }\n\n run.error = reason;\n run.cancellationReason = reason;\n this.transitionState(run, 'CANCELLED', reason);\n await this.store.saveRun(run);\n return run;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"engine.js","sourceRoot":"","sources":["../../../src/intelligence/orchestration/engine.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AAGjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAS3D,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAClD,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CA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AW,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;YACvF,MAAM,IAAI,iBAAiB,CAAC,OAAO,EAAE,sBAAsB,KAAK,wBAAwB,GAAG,CAAC,KAAK,IAAI,CAAC,CAAC;QACzG,CAAC;QAED,2BAA2B;QAC3B,KAAK,MAAM,KAAK,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;YAC/B,IAAI,CAAC,WAAW,CAAC,kBAAkB,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAChD,CAAC;QAED,GAAG,CAAC,KAAK,GAAG,MAAM,CAAC;QACnB,GAAG,CAAC,kBAAkB,GAAG,MAAM,CAAC;QAChC,IAAI,CAAC,eAAe,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC;QAC/C,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;QAC9B,OAAO,GAAG,CAAC;IACb,CAAC;CACF","sourcesContent":["import crypto from 'node:crypto';\nimport { IntelligentRouter } from '../routing/router.js';\nimport { OrchestrationStore } from './store.js';\nimport { StageLockManager } from './lock-manager.js';\nimport { NativeRuntimeAdapter } from '../runtime/native.js';\nimport { createExecutionId } from '../runtime/boundary.js';\nimport type {\n ExecutionReceipt,\n ExecutionStage,\n OrchestrationRun,\n OrchestrationState,\n PlanOptions,\n RunOptions,\n} from './types.js';\nimport { isValidStateTransition } from './types.js';\nimport { DevWorkspaceError } from '../../errors/index.js';\nimport { redact } from '../../security/redact.js';\nimport { isSensitiveFile } from '../../security/files.js';\nimport { readTextBounded } from '../../utils/fs.js';\nimport { resolveInside } from '../../utils/paths.js';\nimport { run as runProc } from '../../utils/proc.js';\n\nexport interface DryRunPlanSummary {\n runId: string;\n state: OrchestrationState;\n request: string;\n strategy: string;\n totalStages: number;\n requiresApproval: boolean;\n stages: Array<{\n id: string;\n name: string;\n agentId: string;\n claimedFiles: string[];\n isDestructive: boolean;\n requiresApproval: boolean;\n dependsOn: string[];\n }>;\n estimatedDurationMs: number;\n estimatedTokens: number;\n}\n\nexport class OrchestrationEngine {\n private router: IntelligentRouter;\n private store: OrchestrationStore;\n private lockManager: StageLockManager;\n\n constructor(router: IntelligentRouter, store: OrchestrationStore) {\n this.router = router;\n this.store = store;\n this.lockManager = new StageLockManager();\n }\n\n /** Compute a workspace + modified-file SHA-256 fingerprint to bind verification receipts to exact workspace state. */\n async computeWorkspaceFingerprint(workspaceRoot: string | undefined, filePaths: string[]): Promise<string> {\n const hash = crypto.createHash('sha256');\n if (workspaceRoot) {\n try {\n const gitRes = await runProc('git', ['rev-parse', 'HEAD'], { cwd: workspaceRoot, timeoutMs: 2_000 });\n hash.update(`head:${gitRes.ok ? gitRes.stdout.trim() : 'nogit'}\\n`);\n } catch {\n hash.update('head:nogit\\n');\n }\n for (const rel of [...filePaths].sort()) {\n hash.update(`file:${rel}:`);\n try {\n const full = resolveInside(workspaceRoot, rel);\n const content = await readTextBounded(full, 256 * 1024);\n hash.update(content ?? 'binary-or-large');\n } catch {\n hash.update('missing-or-unsafe');\n }\n hash.update('\\n');\n }\n } else {\n hash.update(`files:${[...filePaths].sort().join(',')}`);\n }\n return hash.digest('hex');\n }\n\n /** Safely load bounded contents of modified files for independent verification without leaking secrets. */\n private async loadModifiedFileContents(workspaceRoot: string | undefined, filePaths: string[]): Promise<Array<{ path: string; content: string }>> {\n const out: Array<{ path: string; content: string }> = [];\n for (const rel of filePaths) {\n if (!workspaceRoot || isSensitiveFile(rel)) {\n out.push({ path: rel, content: '' });\n continue;\n }\n try {\n const full = resolveInside(workspaceRoot, rel);\n const content = await readTextBounded(full, 256 * 1024);\n out.push({ path: rel, content: content ?? '' });\n } catch {\n out.push({ path: rel, content: '' });\n }\n }\n return out;\n }\n\n /** Reject and invalidate any stage verification receipt whose workspace files changed since verification. */\n async invalidateStaleReceipts(runId: string, workspaceRoot?: string): Promise<{ run: OrchestrationRun; invalidatedStages: string[] }> {\n const loaded = await this.store.getRun(runId);\n if (!loaded) {\n throw new DevWorkspaceError('NOT_FOUND', `Orchestration run \"${runId}\" not found.`);\n }\n const invalidatedStages: string[] = [];\n for (const stage of loaded.stages) {\n if (!stage.receipt || !stage.receipt.verified) continue;\n const root = workspaceRoot ?? stage.receipt.cwd;\n const currentFp = await this.computeWorkspaceFingerprint(root, stage.receipt.filesModified);\n if (stage.receipt.workspaceFingerprint && currentFp !== stage.receipt.workspaceFingerprint) {\n stage.receipt.verified = false;\n stage.receipt.stale = true;\n stage.receipt.verificationStatus = 'NOT_TESTED';\n stage.status = 'VERIFYING';\n stage.outputs = { ...(stage.outputs ?? {}), verified: false, stale: true, receipt: stage.receipt };\n invalidatedStages.push(stage.id);\n }\n }\n if (invalidatedStages.length > 0) {\n if (loaded.state === 'COMPLETED' || loaded.state === 'SUCCEEDED') {\n loaded.state = 'VERIFYING';\n }\n loaded.checkpoints.push({\n at: new Date().toISOString(),\n state: loaded.state,\n note: `Invalidated stale verification receipt(s) due to workspace changes: ${invalidatedStages.join(', ')}.`,\n });\n await this.store.saveRun(loaded);\n }\n return { run: loaded, invalidatedStages };\n }\n\n /**\n * Detects potentially destructive operations in stage inputs or prompt.\n */\n private detectDestructiveOperation(text: string, inputs: Record<string, unknown> = {}): { isDestructive: boolean; reasons: string[] } {\n const reasons: string[] = [];\n const fullText = [text, JSON.stringify(inputs)].join(' ');\n\n // 1. Destructive SQL operations\n const sqlRegex = /\\b(DROP\\s+TABLE|DROP\\s+DATABASE|TRUNCATE\\s+TABLE|ALTER\\s+TABLE\\s+.*\\s+DROP|DELETE\\s+FROM\\s+\\w+\\s*(?:;|$))\\b/i;\n if (sqlRegex.test(fullText)) {\n reasons.push('Contains destructive SQL statement (DROP / TRUNCATE / ALTER DROP / unqualified DELETE)');\n }\n\n // 2. Destructive filesystem operations\n const fsRegex = /\\b(?:rm\\s+-[a-zA-Z]*[rf][a-zA-Z]*|format\\s+[A-Z]:|mkfs|dropdb|prisma\\s+migrate\\s+reset)\\b/i;\n if (fsRegex.test(fullText)) {\n reasons.push('Contains destructive filesystem or database reset command');\n }\n\n // 3. Destructive deploy / credential rotation\n const deployRegex = /\\b(deploy\\s+--prod|publish\\s+--force|rotate-all-keys)\\b/i;\n if (deployRegex.test(fullText)) {\n reasons.push('Contains production deployment or credential rotation command');\n }\n\n return {\n isDestructive: reasons.length > 0,\n reasons,\n };\n }\n\n /**\n * Safely transitions run state, verifying valid transition rules.\n */\n private transitionState(run: OrchestrationRun, newState: OrchestrationState, note: string, stageId?: string): void {\n if (!isValidStateTransition(run.state, newState)) {\n throw new DevWorkspaceError('USAGE', `Invalid state transition from \"${run.state}\" to \"${newState}\".`);\n }\n\n run.state = newState;\n run.updatedAt = new Date().toISOString();\n run.checkpoints.push({\n at: run.updatedAt,\n state: newState,\n stageId,\n note: redact(note),\n });\n }\n\n async plan(options: PlanOptions): Promise<OrchestrationRun> {\n const req = (options.request || options.prompt || options.title || '').trim();\n\n // Idempotency check: if a run with this idempotency key already exists, return it\n if (options.idempotencyKey) {\n const existing = await this.store.getRunByIdempotencyKey(options.idempotencyKey);\n if (existing) {\n return existing;\n }\n }\n\n const routing = await this.router.route({\n workspaceRoot: options.workspaceRoot || '',\n request: req,\n taskType: undefined,\n });\n\n const runId = this.store.generateRunId();\n const stages: ExecutionStage[] = [];\n\n // Stage 1: Analysis & Requirements Formulation\n const analysisAgent = routing.selectedAgents.find((a) => a.agentId === 'planner' || a.agentId === 'research') || routing.selectedAgents[0];\n const stage1Destructive = this.detectDestructiveOperation(req, { taskType: routing.taskType });\n stages.push({\n id: 'stage-1-analysis',\n name: 'Task Decomposition & Architecture Context',\n agentId: analysisAgent?.agentId || 'research',\n skillIds: routing.selectedSkills.map((s) => s.skillId),\n status: 'PENDING',\n dependsOn: [],\n claimedFiles: [],\n inputs: { request: req, taskType: routing.taskType },\n modifiedFiles: [],\n retryCount: 0,\n isDestructive: stage1Destructive.isDestructive,\n requiresApproval: stage1Destructive.isDestructive,\n });\n\n // Stage 2: Implementation (if not read-only)\n const devAgent = routing.selectedAgents.find((a) => a.agentId === 'developer' || a.agentId === 'database-specialist' || a.agentId === 'debugger');\n if (devAgent) {\n const stage2Destructive = this.detectDestructiveOperation(req, { strategy: routing.strategy });\n stages.push({\n id: 'stage-2-implementation',\n name: `Implementation by ${devAgent.role}`,\n agentId: devAgent.agentId,\n skillIds: routing.selectedSkills.map((s) => s.skillId),\n status: 'PENDING',\n dependsOn: ['stage-1-analysis'],\n claimedFiles: routing.relevantFiles,\n inputs: { strategy: routing.strategy },\n modifiedFiles: [],\n retryCount: 0,\n isDestructive: stage2Destructive.isDestructive,\n requiresApproval: stage2Destructive.isDestructive,\n });\n }\n\n // Stage 3: Independent Review & Verification\n const reviewerAgent = routing.selectedAgents.find((a) => a.agentId === 'code-reviewer' || a.agentId === 'security-auditor' || a.agentId === 'testing');\n if (reviewerAgent) {\n stages.push({\n id: 'stage-3-verification',\n name: `Independent Verification by ${reviewerAgent.role}`,\n agentId: reviewerAgent.agentId,\n skillIds: ['code-review', 'security-audit'],\n status: 'PENDING',\n dependsOn: devAgent ? ['stage-2-implementation'] : ['stage-1-analysis'],\n claimedFiles: [],\n inputs: { verificationContract: 'standard' },\n modifiedFiles: [],\n retryCount: 0,\n isDestructive: false,\n requiresApproval: false,\n });\n }\n\n const hasDestructive = stages.some((s) => s.isDestructive);\n const requiresApproval = (routing.requiredApprovals.length > 0 || routing.complexity === 'CRITICAL' || hasDestructive) && !options.autoApprove;\n const initialState: OrchestrationState = requiresApproval ? 'AWAITING_APPROVAL' : 'READY';\n\n const now = new Date().toISOString();\n const run: OrchestrationRun = {\n runId,\n taskId: options.taskId,\n idempotencyKey: options.idempotencyKey,\n request: req,\n state: initialState,\n routing,\n stages,\n currentStageIndex: 0,\n checkpoints: [\n {\n at: now,\n state: 'CREATED',\n note: `Plan generated with ${stages.length} stage(s) under strategy ${routing.strategy}.`,\n },\n {\n at: now,\n state: initialState,\n note: requiresApproval ? 'Plan requires developer approval before execution.' : 'Plan validated and ready for execution.',\n },\n ],\n retryCount: 0,\n maxRetries: options.maxRetries ?? 3,\n metrics: {\n durationMs: 0,\n tokensEstimate: routing.estimatedResources.tokensEstimate,\n filesModifiedCount: 0,\n stagesCompleted: 0,\n correctionsCount: 0,\n },\n createdAt: now,\n updatedAt: now,\n isDryRun: options.dryRun,\n };\n\n await this.store.saveRun(run);\n return run;\n }\n\n async approve(runId: string, approvedBy = 'user'): Promise<OrchestrationRun> {\n const run = await this.store.getRun(runId);\n if (!run) {\n throw new DevWorkspaceError('NOT_FOUND', `Orchestration run \"${runId}\" not found.`);\n }\n\n if (run.state !== 'AWAITING_APPROVAL' && run.state !== 'WAITING_APPROVAL') {\n throw new DevWorkspaceError('USAGE', `Run \"${runId}\" is in state \"${run.state}\", not AWAITING_APPROVAL.`);\n }\n\n run.approvedBy = approvedBy;\n run.approvedAt = new Date().toISOString();\n this.transitionState(run, 'READY', `Plan approved by ${approvedBy}. Ready for execution.`);\n\n await this.store.saveRun(run);\n return run;\n }\n\n async dryRun(runId: string): Promise<DryRunPlanSummary> {\n const run = await this.store.getRun(runId);\n if (!run) {\n throw new DevWorkspaceError('NOT_FOUND', `Orchestration run \"${runId}\" not found.`);\n }\n\n return {\n runId: run.runId,\n state: run.state,\n request: run.request,\n strategy: run.routing?.strategy ?? 'STANDARD',\n totalStages: run.stages.length,\n requiresApproval: run.state === 'AWAITING_APPROVAL' || run.state === 'WAITING_APPROVAL',\n stages: run.stages.map((s) => ({\n id: s.id,\n name: s.name,\n agentId: s.agentId,\n claimedFiles: s.claimedFiles,\n isDestructive: Boolean(s.isDestructive),\n requiresApproval: Boolean(s.requiresApproval),\n dependsOn: s.dependsOn,\n })),\n estimatedDurationMs: run.metrics.durationMs,\n estimatedTokens: run.metrics.tokensEstimate,\n };\n }\n\n async run(options: RunOptions): Promise<OrchestrationRun> {\n const run = await this.store.getRun(options.runId);\n if (!run) {\n throw new DevWorkspaceError('NOT_FOUND', `Orchestration run \"${options.runId}\" not found.`);\n }\n\n // Duplicate execution protection: do not re-run an already completed or running run\n if (run.state === 'COMPLETED' || run.state === 'SUCCEEDED') {\n return run;\n }\n if (run.state === 'RUNNING') {\n throw new DevWorkspaceError('USAGE', `Run \"${run.runId}\" is already running.`);\n }\n if (run.state === 'CANCELLED' || run.state === 'TIMED_OUT') {\n throw new DevWorkspaceError('USAGE', `Cannot run \"${run.runId}\" in terminal state \"${run.state}\".`);\n }\n\n // Approval gating: check if approval is required\n if (run.state === 'AWAITING_APPROVAL' || run.state === 'WAITING_APPROVAL') {\n if (options.explicitApproval) {\n run.approvedBy = run.approvedBy ?? 'explicit-opt-in';\n run.approvedAt = new Date().toISOString();\n this.transitionState(run, 'READY', 'Execution explicitly approved by developer option.');\n } else {\n throw new DevWorkspaceError('USAGE', `Run \"${run.runId}\" requires developer approval before execution.`);\n }\n }\n\n if (run.state !== 'READY' && run.state !== 'PAUSED' && run.state !== 'BLOCKED') {\n throw new DevWorkspaceError('USAGE', `Run \"${run.runId}\" is in state \"${run.state}\"; only READY, PAUSED or unblocked runs can be executed.`);\n }\n\n // Certify runtime adapter: placeholder runtimes MUST NEVER return successful execution\n const adapter = options.runtimeAdapter ?? new NativeRuntimeAdapter();\n if (adapter.isPlaceholder) {\n this.transitionState(run, 'FAILED', 'Placeholder runtime cannot return a successful execution.');\n run.error = 'No placeholder runtime can return a successful execution.';\n await this.store.saveRun(run);\n return run;\n }\n\n const startTs = Date.now();\n const timeoutMs = (options.timeoutSeconds ? options.timeoutSeconds * 1000 : options.timeoutMs) ?? 0;\n\n this.transitionState(run, 'RUNNING', 'Execution started.');\n await this.store.saveRun(run);\n\n try {\n for (let i = run.currentStageIndex; i < run.stages.length; i++) {\n const stage = run.stages[i]!;\n run.currentStageIndex = i;\n\n // Check cancellation\n if (options.signal?.aborted) {\n this.transitionState(run, 'CANCELLED', 'Run cancelled by user request.', stage.id);\n await this.store.saveRun(run);\n return run;\n }\n\n // Check timeout\n if (timeoutMs > 0 && Date.now() - startTs > timeoutMs) {\n stage.status = 'TIMED_OUT';\n this.transitionState(run, 'TIMED_OUT', `Execution timed out after ${timeoutMs}ms.`, stage.id);\n this.lockManager.releaseAllForStage(stage.id);\n await this.store.saveRun(run);\n return run;\n }\n\n // Destructive operations safety gate\n if (stage.isDestructive && !run.approvedBy && !options.explicitApproval) {\n stage.status = 'WAITING_APPROVAL';\n this.transitionState(run, 'WAITING_APPROVAL', `Execution halted: stage \"${stage.name}\" requires explicit approval for destructive operations.`, stage.id);\n await this.store.saveRun(run);\n return run;\n }\n\n // Single-writer lock acquisition for claimed files\n if (stage.claimedFiles.length > 0) {\n const lockResult = await this.lockManager.acquire(stage.id, stage.agentId, stage.claimedFiles, 'write');\n if (!lockResult.acquired) {\n stage.status = 'BLOCKED';\n this.transitionState(run, 'BLOCKED', `Execution blocked: file lock conflict on ${lockResult.conflictingFiles?.join(', ')}.`, stage.id);\n await this.store.saveRun(run);\n return run;\n }\n }\n\n stage.status = 'RUNNING';\n stage.startedAt = new Date().toISOString();\n await this.store.saveRun(run);\n\n // Execute stage work with runtime adapter\n let stageSuccess = false;\n let lastError: string | undefined;\n let receipt: ExecutionReceipt | undefined;\n let haltState: 'BLOCKED' | 'TIMED_OUT' | 'CANCELLED' | null = null;\n\n while (!stageSuccess && stage.retryCount <= run.maxRetries) {\n try {\n const execRes = await adapter.execute({\n agentId: stage.agentId,\n role: stage.name,\n prompt: run.request,\n skills: stage.skillIds,\n contextFiles: stage.claimedFiles,\n timeoutMs: timeoutMs > 0 ? Math.max(1000, timeoutMs - (Date.now() - startTs)) : undefined,\n signal: options.signal,\n command: (stage.inputs.command as string[] | undefined),\n cwd: options.workspaceRoot,\n workspaceRoot: options.workspaceRoot,\n explicitApproval: Boolean(run.approvedBy || options.explicitApproval),\n });\n\n const execId = execRes.executionId ?? createExecutionId('exec');\n const execStatus = execRes.status ?? (execRes.ok ? 'SUCCEEDED' : 'FAILED');\n const execFiles = execRes.filesModified ?? [];\n const baseReceipt = (verified: boolean, verificationStatus: ExecutionReceipt['verificationStatus'], fp?: string, report?: ExecutionReceipt['verificationReport']): ExecutionReceipt => ({\n executionId: execId,\n stageId: stage.id,\n executionStatus: execStatus,\n verificationStatus,\n verifierId: report?.verifierId,\n verifierVersion: report?.verifierVersion,\n workspaceFingerprint: fp,\n verifiedAt: report?.verifiedAt,\n checksPerformed: report?.checksPerformed ?? [],\n evidenceRefs: report?.evidenceRefs ?? execFiles,\n command: execRes.command ?? (stage.inputs.command as string[] | undefined),\n cwd: execRes.cwd ?? options.workspaceRoot,\n exitCode: execRes.exitCode,\n durationMs: execRes.durationMs,\n stdout: execRes.stdout,\n stderr: execRes.stderr,\n timedOut: execRes.timedOut,\n aborted: execRes.aborted,\n filesModified: execFiles,\n executedAt: execRes.endedAt ?? new Date().toISOString(),\n verified,\n verificationReport: report,\n });\n\n if (execRes.isPlaceholder) {\n throw new Error(execRes.error || 'Placeholder runtime cannot execute stages.');\n }\n if (execStatus === 'TIMED_OUT' || execRes.timedOut || (timeoutMs > 0 && Date.now() - startTs > timeoutMs)) {\n stage.receipt = baseReceipt(false, 'NOT_TESTED');\n lastError = execRes.error || `Stage execution timed out${timeoutMs > 0 ? ` after ${timeoutMs}ms` : ''}.`;\n haltState = 'TIMED_OUT';\n break;\n }\n if (execStatus === 'CANCELLED' || execRes.aborted) {\n stage.receipt = baseReceipt(false, 'NOT_TESTED');\n lastError = execRes.error || 'Stage execution cancelled.';\n haltState = 'CANCELLED';\n break;\n }\n if (execStatus === 'PREPARED' || execStatus === 'NOT_EXECUTED' || execStatus === 'UNSUPPORTED' || execStatus === 'BLOCKED') {\n stage.receipt = baseReceipt(false, 'NOT_TESTED');\n lastError = execRes.reason || execRes.error || `Stage did not execute (${execStatus}).`;\n haltState = 'BLOCKED';\n break;\n }\n if (execStatus !== 'SUCCEEDED' || !execRes.ok) {\n throw new Error(execRes.error || 'Stage execution failed in runtime adapter.');\n }\n\n // Mandatory independent verification gate: never default to verified without a real verifier run.\n const rootForVerify = options.workspaceRoot ?? execRes.cwd;\n const preVerifyFingerprint = await this.computeWorkspaceFingerprint(rootForVerify, execFiles);\n if (!options.verificationEngine) {\n const unverifiedReceipt = baseReceipt(false, 'NOT_TESTED', preVerifyFingerprint);\n stage.receipt = unverifiedReceipt;\n stage.outputs = { outcome: 'unverified', verified: false, receipt: unverifiedReceipt };\n lastError = 'Independent verification engine is required before verified completion; execution finished unverified.';\n haltState = 'BLOCKED';\n break;\n }\n\n this.transitionState(run, 'VERIFYING', `Running independent verification for stage \"${stage.name}\".`, stage.id);\n const checks = (stage.inputs.contractChecks as any) ?? [];\n const modified = await this.loadModifiedFileContents(rootForVerify, execFiles);\n const verificationReport = await options.verificationEngine.verify(checks, modified, [], stage.retryCount, run.maxRetries, {\n executionId: execId,\n stageId: stage.id,\n workspaceFingerprint: preVerifyFingerprint,\n evidenceRefs: execFiles,\n });\n\n if (verificationReport.executionId && verificationReport.executionId !== execId) {\n throw new Error(`Stale verification receipt rejected: bound to \"${verificationReport.executionId}\", expected \"${execId}\".`);\n }\n if (verificationReport.workspaceFingerprint && verificationReport.workspaceFingerprint !== preVerifyFingerprint) {\n throw new Error('Stale verification receipt rejected: workspace fingerprint mismatch.');\n }\n const postVerifyFingerprint = await this.computeWorkspaceFingerprint(rootForVerify, execFiles);\n if (postVerifyFingerprint !== preVerifyFingerprint) {\n throw new Error('Verification invalidated: workspace files changed during verification.');\n }\n if (!verificationReport.canComplete || !verificationReport.mandatoryGatesPassed || verificationReport.verificationStatus !== 'PASS') {\n throw new Error(`Verification failed (${verificationReport.verificationStatus}): ${verificationReport.summary}`);\n }\n\n receipt = baseReceipt(true, 'PASS', preVerifyFingerprint, verificationReport);\n stage.status = 'COMPLETED';\n stage.completedAt = new Date().toISOString();\n stage.outputs = { outcome: 'success', verified: true, receipt };\n stage.receipt = receipt;\n run.metrics.stagesCompleted += 1;\n stageSuccess = true;\n } catch (err: any) {\n lastError = err.message;\n if (stage.retryCount < run.maxRetries) {\n stage.retryCount += 1;\n run.metrics.correctionsCount += 1;\n this.transitionState(run, 'CORRECTING', `Retrying stage \"${stage.name}\" (attempt ${stage.retryCount}/${run.maxRetries}): ${redact(err.message)}`, stage.id);\n await this.store.saveRun(run);\n } else {\n break;\n }\n }\n }\n\n this.lockManager.releaseAllForStage(stage.id);\n\n if (haltState) {\n stage.status = haltState;\n stage.error = redact(lastError ?? `Execution halted (${haltState}).`);\n run.error = stage.error;\n this.transitionState(run, haltState, stage.error, stage.id);\n await this.store.saveRun(run);\n return run;\n }\n\n if (timeoutMs > 0 && Date.now() - startTs > timeoutMs) {\n stage.status = 'TIMED_OUT';\n this.transitionState(run, 'TIMED_OUT', `Execution timed out after ${timeoutMs}ms.`, stage.id);\n await this.store.saveRun(run);\n return run;\n }\n\n if (!stageSuccess) {\n stage.status = 'FAILED';\n stage.error = lastError;\n throw new Error(lastError || `Stage \"${stage.name}\" failed after ${run.maxRetries} retries.`);\n }\n\n this.transitionState(run, 'RUNNING', `Stage \"${stage.name}\" completed and verified successfully.`, stage.id);\n await this.store.saveRun(run);\n }\n\n // Final Completion: only reachable when every stage executed and passed independent verification\n const allStagesVerified = run.stages.every((s) => s.status === 'COMPLETED' && s.receipt?.verified === true && s.receipt.verificationStatus === 'PASS');\n if (!allStagesVerified) {\n this.transitionState(run, 'BLOCKED', 'Run cannot complete because one or more stages lack verified completion.');\n run.error = 'One or more stages lack verified completion.';\n run.metrics.durationMs = Date.now() - startTs;\n await this.store.saveRun(run);\n return run;\n }\n\n this.transitionState(run, 'COMPLETED', 'Workflow executed and independently verified.');\n run.metrics.durationMs = Date.now() - startTs;\n await this.store.saveRun(run);\n return run;\n } catch (err: any) {\n this.transitionState(run, 'FAILED', `Execution failed: ${err.message}`);\n run.error = err.message;\n run.metrics.durationMs = Date.now() - startTs;\n await this.store.saveRun(run);\n return run;\n }\n }\n\n async resume(runId: string, options?: Omit<RunOptions, 'runId'>): Promise<OrchestrationRun> {\n const run = await this.store.getRun(runId);\n if (!run) {\n throw new DevWorkspaceError('NOT_FOUND', `Orchestration run \"${runId}\" not found.`);\n }\n\n if (run.state !== 'PAUSED' && run.state !== 'BLOCKED' && run.state !== 'WAITING_APPROVAL' && run.state !== 'AWAITING_APPROVAL') {\n throw new DevWorkspaceError('USAGE', `Run \"${runId}\" is in state \"${run.state}\"; only PAUSED, BLOCKED, or approved runs can be resumed.`);\n }\n\n this.transitionState(run, 'READY', 'Run resumed by developer request.');\n await this.store.saveRun(run);\n\n return this.run({\n ...options,\n runId,\n });\n }\n\n async cancel(runId: string, reason = 'Cancelled by developer'): Promise<OrchestrationRun> {\n const run = await this.store.getRun(runId);\n if (!run) {\n throw new DevWorkspaceError('NOT_FOUND', `Orchestration run \"${runId}\" not found.`);\n }\n\n if (['COMPLETED', 'SUCCEEDED', 'FAILED', 'CANCELLED', 'TIMED_OUT'].includes(run.state)) {\n throw new DevWorkspaceError('USAGE', `Cannot cancel run \"${runId}\" in terminal state \"${run.state}\".`);\n }\n\n // Release any active locks\n for (const stage of run.stages) {\n this.lockManager.releaseAllForStage(stage.id);\n }\n\n run.error = reason;\n run.cancellationReason = reason;\n this.transitionState(run, 'CANCELLED', reason);\n await this.store.saveRun(run);\n return run;\n }\n}\n"]}
|
|
@@ -1,11 +1,22 @@
|
|
|
1
1
|
import type { RoutingDecision } from '../routing/types.js';
|
|
2
|
-
import type { AgentRuntimeAdapter } from '../runtime/types.js';
|
|
2
|
+
import type { AgentRuntimeAdapter, RuntimeExecutionStatus } from '../runtime/types.js';
|
|
3
3
|
import type { IndependentVerificationEngine } from '../verification/engine.js';
|
|
4
|
-
import type { VerificationEvaluationReport } from '../verification/types.js';
|
|
4
|
+
import type { VerificationEvaluationReport, VerificationStatus } from '../verification/types.js';
|
|
5
5
|
export declare const ORCHESTRATION_STATES: readonly ["CREATED", "PLANNED", "ANALYZING", "PLANNING", "AWAITING_APPROVAL", "WAITING_APPROVAL", "READY", "RUNNING", "VERIFYING", "CORRECTING", "COMPLETED", "SUCCEEDED", "FAILED", "CANCELLED", "TIMED_OUT", "BLOCKED", "PAUSED"];
|
|
6
6
|
export type OrchestrationState = (typeof ORCHESTRATION_STATES)[number];
|
|
7
7
|
export type StageStatus = 'PENDING' | 'READY' | 'RUNNING' | 'WAITING_APPROVAL' | 'VERIFYING' | 'SUCCEEDED' | 'COMPLETED' | 'FAILED' | 'SKIPPED' | 'CANCELLED' | 'TIMED_OUT' | 'BLOCKED';
|
|
8
8
|
export interface ExecutionReceipt {
|
|
9
|
+
executionId: string;
|
|
10
|
+
stageId: string;
|
|
11
|
+
executionStatus: RuntimeExecutionStatus;
|
|
12
|
+
verificationStatus: VerificationStatus;
|
|
13
|
+
verifierId?: string;
|
|
14
|
+
verifierVersion?: string;
|
|
15
|
+
workspaceFingerprint?: string;
|
|
16
|
+
verifiedAt?: string;
|
|
17
|
+
checksPerformed: string[];
|
|
18
|
+
evidenceRefs: string[];
|
|
19
|
+
stale?: boolean;
|
|
9
20
|
command?: string[];
|
|
10
21
|
cwd?: string;
|
|
11
22
|
exitCode?: number;
|
|
@@ -32,8 +32,8 @@ export function isValidStateTransition(from, to) {
|
|
|
32
32
|
WAITING_APPROVAL: ['READY', 'CANCELLED', 'PAUSED', 'FAILED'],
|
|
33
33
|
READY: ['RUNNING', 'AWAITING_APPROVAL', 'WAITING_APPROVAL', 'BLOCKED', 'CANCELLED', 'PAUSED', 'FAILED'],
|
|
34
34
|
RUNNING: ['RUNNING', 'AWAITING_APPROVAL', 'WAITING_APPROVAL', 'VERIFYING', 'CORRECTING', 'COMPLETED', 'SUCCEEDED', 'FAILED', 'CANCELLED', 'TIMED_OUT', 'BLOCKED', 'PAUSED'],
|
|
35
|
-
VERIFYING: ['COMPLETED', 'SUCCEEDED', 'CORRECTING', 'FAILED', 'CANCELLED', 'TIMED_OUT'],
|
|
36
|
-
CORRECTING: ['RUNNING', 'VERIFYING', 'FAILED', 'CANCELLED', 'TIMED_OUT'],
|
|
35
|
+
VERIFYING: ['RUNNING', 'COMPLETED', 'SUCCEEDED', 'CORRECTING', 'BLOCKED', 'FAILED', 'CANCELLED', 'TIMED_OUT'],
|
|
36
|
+
CORRECTING: ['RUNNING', 'VERIFYING', 'BLOCKED', 'FAILED', 'CANCELLED', 'TIMED_OUT'],
|
|
37
37
|
COMPLETED: [],
|
|
38
38
|
SUCCEEDED: [],
|
|
39
39
|
FAILED: ['READY', 'RUNNING'], // Allow re-try/restart if explicitly commanded
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/intelligence/orchestration/types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,SAAS;IACT,SAAS;IACT,WAAW;IACX,UAAU;IACV,mBAAmB;IACnB,kBAAkB;IAClB,OAAO;IACP,SAAS;IACT,WAAW;IACX,YAAY;IACZ,WAAW;IACX,WAAW;IACX,QAAQ;IACR,WAAW;IACX,WAAW;IACX,SAAS;IACT,QAAQ;CACA,CAAC;
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/intelligence/orchestration/types.ts"],"names":[],"mappings":"AAKA,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,SAAS;IACT,SAAS;IACT,WAAW;IACX,UAAU;IACV,mBAAmB;IACnB,kBAAkB;IAClB,OAAO;IACP,SAAS;IACT,WAAW;IACX,YAAY;IACZ,WAAW;IACX,WAAW;IACX,QAAQ;IACR,WAAW;IACX,WAAW;IACX,SAAS;IACT,QAAQ;CACA,CAAC;AA6HX;;GAEG;AACH,MAAM,UAAU,sBAAsB,CAAC,IAAwB,EAAE,EAAsB;IACrF,IAAI,IAAI,KAAK,EAAE;QAAE,OAAO,IAAI,CAAC;IAE7B,MAAM,gBAAgB,GAAqD;QACzE,OAAO,EAAE,CAAC,SAAS,EAAE,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,SAAS,EAAE,WAAW,CAAC;QAC9F,OAAO,EAAE,CAAC,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,SA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GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;IACvC,OAAO,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AAChD,CAAC","sourcesContent":["import type { RoutingDecision } from '../routing/types.js';\nimport type { AgentRuntimeAdapter, RuntimeExecutionStatus } from '../runtime/types.js';\nimport type { IndependentVerificationEngine } from '../verification/engine.js';\nimport type { VerificationEvaluationReport, VerificationStatus } from '../verification/types.js';\n\nexport const ORCHESTRATION_STATES = [\n 'CREATED',\n 'PLANNED',\n 'ANALYZING',\n 'PLANNING',\n 'AWAITING_APPROVAL',\n 'WAITING_APPROVAL',\n 'READY',\n 'RUNNING',\n 'VERIFYING',\n 'CORRECTING',\n 'COMPLETED',\n 'SUCCEEDED',\n 'FAILED',\n 'CANCELLED',\n 'TIMED_OUT',\n 'BLOCKED',\n 'PAUSED',\n] as const;\n\nexport type OrchestrationState = (typeof ORCHESTRATION_STATES)[number];\n\nexport type StageStatus =\n | 'PENDING'\n | 'READY'\n | 'RUNNING'\n | 'WAITING_APPROVAL'\n | 'VERIFYING'\n | 'SUCCEEDED'\n | 'COMPLETED'\n | 'FAILED'\n | 'SKIPPED'\n | 'CANCELLED'\n | 'TIMED_OUT'\n | 'BLOCKED';\n\nexport interface ExecutionReceipt {\n executionId: string;\n stageId: string;\n executionStatus: RuntimeExecutionStatus;\n verificationStatus: VerificationStatus;\n verifierId?: string;\n verifierVersion?: string;\n workspaceFingerprint?: string;\n verifiedAt?: string;\n checksPerformed: string[];\n evidenceRefs: string[];\n stale?: boolean;\n command?: string[];\n cwd?: string;\n exitCode?: number;\n durationMs: number;\n stdout?: string;\n stderr?: string;\n timedOut?: boolean;\n aborted?: boolean;\n filesModified: string[];\n executedAt: string;\n verified: boolean;\n verificationReport?: VerificationEvaluationReport;\n}\n\nexport interface ExecutionStage {\n id: string;\n name: string;\n agentId: string;\n skillIds: string[];\n status: StageStatus;\n dependsOn: string[];\n claimedFiles: string[];\n inputs: Record<string, unknown>;\n outputs?: Record<string, unknown>;\n modifiedFiles: string[];\n startedAt?: string;\n completedAt?: string;\n error?: string;\n retryCount: number;\n receipt?: ExecutionReceipt;\n isDestructive?: boolean;\n requiresApproval?: boolean;\n}\n\nexport interface RunMetrics {\n durationMs: number;\n tokensEstimate: number;\n filesModifiedCount: number;\n stagesCompleted: number;\n correctionsCount: number;\n}\n\nexport interface RunCheckpoint {\n at: string;\n state: OrchestrationState;\n stageId?: string;\n note: string;\n}\n\nexport interface OrchestrationRun {\n runId: string;\n taskId?: string;\n idempotencyKey?: string;\n request: string;\n state: OrchestrationState;\n routing: RoutingDecision;\n stages: ExecutionStage[];\n currentStageIndex: number;\n checkpoints: RunCheckpoint[];\n approvedBy?: string;\n approvedAt?: string;\n cancellationReason?: string;\n retryCount: number;\n maxRetries: number;\n metrics: RunMetrics;\n createdAt: string;\n updatedAt: string;\n error?: string;\n isDryRun?: boolean;\n timeoutMs?: number;\n}\n\nexport interface PlanOptions {\n request?: string;\n prompt?: string;\n title?: string;\n workspaceRoot?: string;\n taskId?: string;\n idempotencyKey?: string;\n autoApprove?: boolean;\n maxRetries?: number;\n dryRun?: boolean;\n}\n\nexport interface RunOptions {\n runId: string;\n timeoutSeconds?: number;\n timeoutMs?: number;\n signal?: AbortSignal;\n runtimeAdapter?: AgentRuntimeAdapter;\n verificationEngine?: IndependentVerificationEngine;\n explicitApproval?: boolean;\n workspaceRoot?: string;\n}\n\n/**\n * Validates whether transition from `from` state to `to` state is permitted.\n */\nexport function isValidStateTransition(from: OrchestrationState, to: OrchestrationState): boolean {\n if (from === to) return true;\n\n const validTransitions: Record<OrchestrationState, OrchestrationState[]> = {\n CREATED: ['PLANNED', 'READY', 'AWAITING_APPROVAL', 'WAITING_APPROVAL', 'BLOCKED', 'CANCELLED'],\n PLANNED: ['READY', 'AWAITING_APPROVAL', 'WAITING_APPROVAL', 'BLOCKED', 'CANCELLED'],\n ANALYZING: ['PLANNING', 'READY', 'AWAITING_APPROVAL', 'WAITING_APPROVAL', 'FAILED', 'CANCELLED'],\n PLANNING: ['READY', 'AWAITING_APPROVAL', 'WAITING_APPROVAL', 'FAILED', 'CANCELLED'],\n AWAITING_APPROVAL: ['READY', 'CANCELLED', 'PAUSED', 'FAILED'],\n WAITING_APPROVAL: ['READY', 'CANCELLED', 'PAUSED', 'FAILED'],\n READY: ['RUNNING', 'AWAITING_APPROVAL', 'WAITING_APPROVAL', 'BLOCKED', 'CANCELLED', 'PAUSED', 'FAILED'],\n RUNNING: ['RUNNING', 'AWAITING_APPROVAL', 'WAITING_APPROVAL', 'VERIFYING', 'CORRECTING', 'COMPLETED', 'SUCCEEDED', 'FAILED', 'CANCELLED', 'TIMED_OUT', 'BLOCKED', 'PAUSED'],\n VERIFYING: ['RUNNING', 'COMPLETED', 'SUCCEEDED', 'CORRECTING', 'BLOCKED', 'FAILED', 'CANCELLED', 'TIMED_OUT'],\n CORRECTING: ['RUNNING', 'VERIFYING', 'BLOCKED', 'FAILED', 'CANCELLED', 'TIMED_OUT'],\n COMPLETED: [],\n SUCCEEDED: [],\n FAILED: ['READY', 'RUNNING'], // Allow re-try/restart if explicitly commanded\n CANCELLED: [],\n TIMED_OUT: ['READY', 'RUNNING'], // Allow restart with longer timeout\n BLOCKED: ['READY', 'RUNNING', 'CANCELLED'],\n PAUSED: ['READY', 'RUNNING', 'CANCELLED'],\n };\n\n const allowed = validTransitions[from];\n return allowed ? allowed.includes(to) : false;\n}\n"]}
|