devworkspace 0.4.5 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +57 -0
- package/README.md +7 -0
- package/dist/cli/args.d.ts +30 -0
- package/dist/cli/args.js +10 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/help.js +134 -0
- package/dist/cli/help.js.map +1 -1
- package/dist/cli/render.d.ts +6 -0
- package/dist/cli/render.js +106 -0
- package/dist/cli/render.js.map +1 -1
- package/dist/cli/run.js +351 -1
- package/dist/cli/run.js.map +1 -1
- package/dist/core/contracts.d.ts +70 -0
- package/dist/core/contracts.js +88 -0
- package/dist/core/contracts.js.map +1 -0
- package/dist/discovery/commands.d.ts +1 -1
- package/dist/discovery/commands.js.map +1 -1
- package/dist/discovery/detect.d.ts +2 -70
- package/dist/discovery/detect.js.map +1 -1
- package/dist/discovery/entrypoints.d.ts +2 -11
- package/dist/discovery/entrypoints.js.map +1 -1
- package/dist/discovery/types.d.ts +79 -0
- package/dist/discovery/types.js +2 -0
- package/dist/discovery/types.js.map +1 -0
- package/dist/dx/dashboard.d.ts +21 -0
- package/dist/dx/dashboard.js +274 -0
- package/dist/dx/dashboard.js.map +1 -0
- package/dist/dx/guidance.d.ts +21 -0
- package/dist/dx/guidance.js +266 -0
- package/dist/dx/guidance.js.map +1 -0
- package/dist/dx/index.d.ts +4 -0
- package/dist/dx/index.js +5 -0
- package/dist/dx/index.js.map +1 -0
- package/dist/dx/onboarding.d.ts +23 -0
- package/dist/dx/onboarding.js +155 -0
- package/dist/dx/onboarding.js.map +1 -0
- package/dist/dx/types.d.ts +70 -0
- package/dist/dx/types.js +3 -0
- package/dist/dx/types.js.map +1 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +28 -0
- package/dist/index.js.map +1 -1
- package/dist/integrations/persistentPath.d.ts +2 -9
- package/dist/integrations/persistentPath.js.map +1 -1
- package/dist/integrations/types.d.ts +4 -1
- package/dist/integrations/types.js.map +1 -1
- package/dist/intelligence/agents/profiles.d.ts +2 -0
- package/dist/intelligence/agents/profiles.js +326 -0
- package/dist/intelligence/agents/profiles.js.map +1 -0
- package/dist/intelligence/agents/registry.d.ts +15 -0
- package/dist/intelligence/agents/registry.js +108 -0
- package/dist/intelligence/agents/registry.js.map +1 -0
- package/dist/intelligence/agents/types.d.ts +43 -0
- package/dist/intelligence/agents/types.js +2 -0
- package/dist/intelligence/agents/types.js.map +1 -0
- package/dist/intelligence/observability/tracer.d.ts +13 -0
- package/dist/intelligence/observability/tracer.js +129 -0
- package/dist/intelligence/observability/tracer.js.map +1 -0
- package/dist/intelligence/observability/types.d.ts +38 -0
- package/dist/intelligence/observability/types.js +2 -0
- package/dist/intelligence/observability/types.js.map +1 -0
- package/dist/intelligence/orchestration/engine.d.ts +42 -0
- package/dist/intelligence/orchestration/engine.js +418 -0
- package/dist/intelligence/orchestration/engine.js.map +1 -0
- package/dist/intelligence/orchestration/lock-manager.d.ts +21 -0
- package/dist/intelligence/orchestration/lock-manager.js +70 -0
- package/dist/intelligence/orchestration/lock-manager.js.map +1 -0
- package/dist/intelligence/orchestration/store.d.ts +11 -0
- package/dist/intelligence/orchestration/store.js +73 -0
- package/dist/intelligence/orchestration/store.js.map +1 -0
- package/dist/intelligence/orchestration/types.d.ts +100 -0
- package/dist/intelligence/orchestration/types.js +48 -0
- package/dist/intelligence/orchestration/types.js.map +1 -0
- package/dist/intelligence/routing/matcher.d.ts +7 -0
- package/dist/intelligence/routing/matcher.js +96 -0
- package/dist/intelligence/routing/matcher.js.map +1 -0
- package/dist/intelligence/routing/router.d.ts +9 -0
- package/dist/intelligence/routing/router.js +198 -0
- package/dist/intelligence/routing/router.js.map +1 -0
- package/dist/intelligence/routing/types.d.ts +64 -0
- package/dist/intelligence/routing/types.js +2 -0
- package/dist/intelligence/routing/types.js.map +1 -0
- package/dist/intelligence/runtime/adk/adapter.d.ts +7 -0
- package/dist/intelligence/runtime/adk/adapter.js +60 -0
- package/dist/intelligence/runtime/adk/adapter.js.map +1 -0
- package/dist/intelligence/runtime/adk/detector.d.ts +7 -0
- package/dist/intelligence/runtime/adk/detector.js +28 -0
- package/dist/intelligence/runtime/adk/detector.js.map +1 -0
- package/dist/intelligence/runtime/external.d.ts +9 -0
- package/dist/intelligence/runtime/external.js +102 -0
- package/dist/intelligence/runtime/external.js.map +1 -0
- package/dist/intelligence/runtime/native.d.ts +19 -0
- package/dist/intelligence/runtime/native.js +99 -0
- package/dist/intelligence/runtime/native.js.map +1 -0
- package/dist/intelligence/runtime/types.d.ts +49 -0
- package/dist/intelligence/runtime/types.js +2 -0
- package/dist/intelligence/runtime/types.js.map +1 -0
- package/dist/intelligence/security/audit.d.ts +8 -0
- package/dist/intelligence/security/audit.js +43 -0
- package/dist/intelligence/security/audit.js.map +1 -0
- package/dist/intelligence/security/policy.d.ts +12 -0
- package/dist/intelligence/security/policy.js +153 -0
- package/dist/intelligence/security/policy.js.map +1 -0
- package/dist/intelligence/security/types.d.ts +25 -0
- package/dist/intelligence/security/types.js +2 -0
- package/dist/intelligence/security/types.js.map +1 -0
- package/dist/intelligence/skills/builtins.d.ts +2 -0
- package/dist/intelligence/skills/builtins.js +379 -0
- package/dist/intelligence/skills/builtins.js.map +1 -0
- package/dist/intelligence/skills/loader.d.ts +4 -0
- package/dist/intelligence/skills/loader.js +84 -0
- package/dist/intelligence/skills/loader.js.map +1 -0
- package/dist/intelligence/skills/registry.d.ts +15 -0
- package/dist/intelligence/skills/registry.js +134 -0
- package/dist/intelligence/skills/registry.js.map +1 -0
- package/dist/intelligence/skills/types.d.ts +35 -0
- package/dist/intelligence/skills/types.js +2 -0
- package/dist/intelligence/skills/types.js.map +1 -0
- package/dist/intelligence/verification/engine.d.ts +23 -0
- package/dist/intelligence/verification/engine.js +66 -0
- package/dist/intelligence/verification/engine.js.map +1 -0
- package/dist/intelligence/verification/reviewer.d.ts +8 -0
- package/dist/intelligence/verification/reviewer.js +55 -0
- package/dist/intelligence/verification/reviewer.js.map +1 -0
- package/dist/intelligence/verification/types.d.ts +32 -0
- package/dist/intelligence/verification/types.js +2 -0
- package/dist/intelligence/verification/types.js.map +1 -0
- package/dist/mcp/setup.d.ts +2 -4
- package/dist/mcp/setup.js.map +1 -1
- package/dist/mcp/tools.js +6 -6
- package/dist/mcp/tools.js.map +1 -1
- package/dist/mcp/types.d.ts +4 -0
- package/dist/mcp/types.js.map +1 -1
- package/dist/mcp/verify.d.ts +1 -1
- package/dist/mcp/verify.js.map +1 -1
- package/dist/security/redact.js +3 -2
- package/dist/security/redact.js.map +1 -1
- package/dist/services/doctor.js +4 -0
- package/dist/services/doctor.js.map +1 -1
- package/dist/services/intelligence.d.ts +44 -0
- package/dist/services/intelligence.js +119 -0
- package/dist/services/intelligence.js.map +1 -0
- package/dist/services/standards.d.ts +85 -0
- package/dist/services/standards.js +230 -0
- package/dist/services/standards.js.map +1 -0
- package/dist/services/taskContext.js +4 -0
- package/dist/services/taskContext.js.map +1 -1
- package/dist/standards/acquisition/ingest.d.ts +12 -0
- package/dist/standards/acquisition/ingest.js +98 -0
- package/dist/standards/acquisition/ingest.js.map +1 -0
- package/dist/standards/applicability/engine.d.ts +38 -0
- package/dist/standards/applicability/engine.js +250 -0
- package/dist/standards/applicability/engine.js.map +1 -0
- package/dist/standards/builtin/code-quality.d.ts +2 -0
- package/dist/standards/builtin/code-quality.js +53 -0
- package/dist/standards/builtin/code-quality.js.map +1 -0
- package/dist/standards/builtin/database-safety.d.ts +2 -0
- package/dist/standards/builtin/database-safety.js +56 -0
- package/dist/standards/builtin/database-safety.js.map +1 -0
- package/dist/standards/builtin/index.d.ts +8 -0
- package/dist/standards/builtin/index.js +14 -0
- package/dist/standards/builtin/index.js.map +1 -0
- package/dist/standards/builtin/security-baseline.d.ts +2 -0
- package/dist/standards/builtin/security-baseline.js +64 -0
- package/dist/standards/builtin/security-baseline.js.map +1 -0
- package/dist/standards/builtin/testing-contracts.d.ts +2 -0
- package/dist/standards/builtin/testing-contracts.js +54 -0
- package/dist/standards/builtin/testing-contracts.js.map +1 -0
- package/dist/standards/builtin/undo-kit.d.ts +8 -0
- package/dist/standards/builtin/undo-kit.js +106 -0
- package/dist/standards/builtin/undo-kit.js.map +1 -0
- package/dist/standards/config/config.d.ts +12 -0
- package/dist/standards/config/config.js +110 -0
- package/dist/standards/config/config.js.map +1 -0
- package/dist/standards/distribution/cache.d.ts +57 -0
- package/dist/standards/distribution/cache.js +411 -0
- package/dist/standards/distribution/cache.js.map +1 -0
- package/dist/standards/distribution/index.d.ts +6 -0
- package/dist/standards/distribution/index.js +7 -0
- package/dist/standards/distribution/index.js.map +1 -0
- package/dist/standards/distribution/keys.d.ts +53 -0
- package/dist/standards/distribution/keys.js +269 -0
- package/dist/standards/distribution/keys.js.map +1 -0
- package/dist/standards/distribution/package.d.ts +25 -0
- package/dist/standards/distribution/package.js +248 -0
- package/dist/standards/distribution/package.js.map +1 -0
- package/dist/standards/distribution/server.d.ts +38 -0
- package/dist/standards/distribution/server.js +204 -0
- package/dist/standards/distribution/server.js.map +1 -0
- package/dist/standards/distribution/sync.d.ts +51 -0
- package/dist/standards/distribution/sync.js +212 -0
- package/dist/standards/distribution/sync.js.map +1 -0
- package/dist/standards/distribution/types.d.ts +140 -0
- package/dist/standards/distribution/types.js +26 -0
- package/dist/standards/distribution/types.js.map +1 -0
- package/dist/standards/engine/compliance.d.ts +2 -0
- package/dist/standards/engine/compliance.js +45 -0
- package/dist/standards/engine/compliance.js.map +1 -0
- package/dist/standards/engine/engine.d.ts +14 -0
- package/dist/standards/engine/engine.js +114 -0
- package/dist/standards/engine/engine.js.map +1 -0
- package/dist/standards/engine/reporter.d.ts +2 -0
- package/dist/standards/engine/reporter.js +42 -0
- package/dist/standards/engine/reporter.js.map +1 -0
- package/dist/standards/index.d.ts +18 -0
- package/dist/standards/index.js +19 -0
- package/dist/standards/index.js.map +1 -0
- package/dist/standards/registry/registry.d.ts +29 -0
- package/dist/standards/registry/registry.js +210 -0
- package/dist/standards/registry/registry.js.map +1 -0
- package/dist/standards/schema/types.d.ts +133 -0
- package/dist/standards/schema/types.js +33 -0
- package/dist/standards/schema/types.js.map +1 -0
- package/dist/standards/schema/validate.d.ts +6 -0
- package/dist/standards/schema/validate.js +131 -0
- package/dist/standards/schema/validate.js.map +1 -0
- package/dist/standards/templates/index.d.ts +11 -0
- package/dist/standards/templates/index.js +176 -0
- package/dist/standards/templates/index.js.map +1 -0
- package/dist/standards/validators/database.d.ts +5 -0
- package/dist/standards/validators/database.js +122 -0
- package/dist/standards/validators/database.js.map +1 -0
- package/dist/standards/validators/quality.d.ts +6 -0
- package/dist/standards/validators/quality.js +91 -0
- package/dist/standards/validators/quality.js.map +1 -0
- package/dist/standards/validators/registry.d.ts +11 -0
- package/dist/standards/validators/registry.js +83 -0
- package/dist/standards/validators/registry.js.map +1 -0
- package/dist/standards/validators/security.d.ts +7 -0
- package/dist/standards/validators/security.js +182 -0
- package/dist/standards/validators/security.js.map +1 -0
- package/dist/standards/validators/testing.d.ts +6 -0
- package/dist/standards/validators/testing.js +142 -0
- package/dist/standards/validators/testing.js.map +1 -0
- package/dist/standards/validators/types.d.ts +11 -0
- package/dist/standards/validators/types.js +2 -0
- package/dist/standards/validators/types.js.map +1 -0
- package/dist/standards/validators/undo-kit.d.ts +7 -0
- package/dist/standards/validators/undo-kit.js +334 -0
- package/dist/standards/validators/undo-kit.js.map +1 -0
- package/dist/tasks/routing.js +5 -3
- package/dist/tasks/routing.js.map +1 -1
- package/dist/utils/fs.d.ts +1 -1
- package/dist/utils/fs.js.map +1 -1
- package/dist/utils/lock.js +11 -3
- package/dist/utils/lock.js.map +1 -1
- package/dist/utils/paths.js +29 -0
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/proc.js +2 -0
- package/dist/utils/proc.js.map +1 -1
- package/docs/contributing.md +9 -0
- package/docs/getting-started.md +7 -0
- package/docs/security/HOME_SERVER_THREAT_MODEL.md +72 -0
- package/docs/security/THREAT_MODEL.md +101 -0
- package/docs/standards.md +143 -0
- package/package.json +1 -1
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { promises as fs } from 'node:fs';
|
|
3
|
+
import { atomicWriteJson, ensureDir, pathExists, randomId, readJsonFile } from '../../utils/fs.js';
|
|
4
|
+
const TRACES_DIR = '.devworkspace/analytics/traces';
|
|
5
|
+
export class LocalTracer {
|
|
6
|
+
workspaceRoot;
|
|
7
|
+
activeTraces = new Map();
|
|
8
|
+
constructor(workspaceRoot) {
|
|
9
|
+
this.workspaceRoot = workspaceRoot;
|
|
10
|
+
}
|
|
11
|
+
tracesPath() {
|
|
12
|
+
return path.join(this.workspaceRoot, TRACES_DIR);
|
|
13
|
+
}
|
|
14
|
+
startTrace(runId) {
|
|
15
|
+
const trace = {
|
|
16
|
+
traceId: `T-${randomId()}`,
|
|
17
|
+
runId,
|
|
18
|
+
startTime: new Date().toISOString(),
|
|
19
|
+
spans: [],
|
|
20
|
+
tokensEstimate: 0,
|
|
21
|
+
filesModified: [],
|
|
22
|
+
};
|
|
23
|
+
this.activeTraces.set(runId, trace);
|
|
24
|
+
return trace;
|
|
25
|
+
}
|
|
26
|
+
addSpan(runId, span) {
|
|
27
|
+
const trace = this.activeTraces.get(runId);
|
|
28
|
+
const fullSpan = {
|
|
29
|
+
...span,
|
|
30
|
+
spanId: `S-${randomId().slice(0, 6)}`,
|
|
31
|
+
};
|
|
32
|
+
if (trace) {
|
|
33
|
+
trace.spans.push(fullSpan);
|
|
34
|
+
}
|
|
35
|
+
return fullSpan;
|
|
36
|
+
}
|
|
37
|
+
async finishTrace(runId, tokensEstimate = 0, filesModified = []) {
|
|
38
|
+
const trace = this.activeTraces.get(runId);
|
|
39
|
+
if (!trace)
|
|
40
|
+
return null;
|
|
41
|
+
trace.endTime = new Date().toISOString();
|
|
42
|
+
trace.totalDurationMs = new Date(trace.endTime).getTime() - new Date(trace.startTime).getTime();
|
|
43
|
+
trace.tokensEstimate = tokensEstimate;
|
|
44
|
+
trace.filesModified = filesModified;
|
|
45
|
+
const dir = this.tracesPath();
|
|
46
|
+
await ensureDir(dir);
|
|
47
|
+
const filePath = path.join(dir, `${runId}.json`);
|
|
48
|
+
await atomicWriteJson(filePath, trace);
|
|
49
|
+
this.activeTraces.delete(runId);
|
|
50
|
+
return trace;
|
|
51
|
+
}
|
|
52
|
+
async getTrace(runId) {
|
|
53
|
+
const filePath = path.join(this.tracesPath(), `${runId}.json`);
|
|
54
|
+
if (!(await pathExists(filePath)))
|
|
55
|
+
return null;
|
|
56
|
+
try {
|
|
57
|
+
return await readJsonFile(filePath);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
async listTraces() {
|
|
64
|
+
const dir = this.tracesPath();
|
|
65
|
+
if (!(await pathExists(dir)))
|
|
66
|
+
return [];
|
|
67
|
+
const traces = [];
|
|
68
|
+
try {
|
|
69
|
+
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
70
|
+
for (const e of entries) {
|
|
71
|
+
if (e.isFile() && e.name.endsWith('.json')) {
|
|
72
|
+
const runId = e.name.slice(0, -5);
|
|
73
|
+
const t = await this.getTrace(runId);
|
|
74
|
+
if (t)
|
|
75
|
+
traces.push(t);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return [];
|
|
81
|
+
}
|
|
82
|
+
return traces;
|
|
83
|
+
}
|
|
84
|
+
async computeMetrics() {
|
|
85
|
+
const traces = await this.listTraces();
|
|
86
|
+
const totalRuns = traces.length;
|
|
87
|
+
let successfulRuns = 0;
|
|
88
|
+
let failedRuns = 0;
|
|
89
|
+
let totalDuration = 0;
|
|
90
|
+
let totalTokens = 0;
|
|
91
|
+
const agentCounts = {};
|
|
92
|
+
const skillCounts = {};
|
|
93
|
+
for (const t of traces) {
|
|
94
|
+
const hasErrors = t.spans.some((s) => s.status === 'ERROR');
|
|
95
|
+
if (hasErrors)
|
|
96
|
+
failedRuns++;
|
|
97
|
+
else
|
|
98
|
+
successfulRuns++;
|
|
99
|
+
totalDuration += t.totalDurationMs || 0;
|
|
100
|
+
totalTokens += t.tokensEstimate || 0;
|
|
101
|
+
for (const s of t.spans) {
|
|
102
|
+
if (s.agentId) {
|
|
103
|
+
agentCounts[s.agentId] = (agentCounts[s.agentId] || 0) + 1;
|
|
104
|
+
}
|
|
105
|
+
if (s.skillId) {
|
|
106
|
+
skillCounts[s.skillId] = (skillCounts[s.skillId] || 0) + 1;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const topAgents = Object.entries(agentCounts)
|
|
111
|
+
.map(([agentId, count]) => ({ agentId, count }))
|
|
112
|
+
.sort((a, b) => b.count - a.count)
|
|
113
|
+
.slice(0, 5);
|
|
114
|
+
const topSkills = Object.entries(skillCounts)
|
|
115
|
+
.map(([skillId, count]) => ({ skillId, count }))
|
|
116
|
+
.sort((a, b) => b.count - a.count)
|
|
117
|
+
.slice(0, 5);
|
|
118
|
+
return {
|
|
119
|
+
totalRuns,
|
|
120
|
+
successfulRuns,
|
|
121
|
+
failedRuns,
|
|
122
|
+
averageDurationMs: totalRuns > 0 ? Math.round(totalDuration / totalRuns) : 0,
|
|
123
|
+
totalTokensEstimate: totalTokens,
|
|
124
|
+
topAgents,
|
|
125
|
+
topSkills,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
//# sourceMappingURL=tracer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tracer.js","sourceRoot":"","sources":["../../../src/intelligence/observability/tracer.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AAEzC,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,mB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K,CAAC;aACjC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QAEf,OAAO;YACL,SAAS;YACT,cAAc;YACd,UAAU;YACV,iBAAiB,EAAE,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5E,mBAAmB,EAAE,WAAW;YAChC,SAAS;YACT,SAAS;SACV,CAAC;IACJ,CAAC;CACF","sourcesContent":["import path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport type { ExecutionTrace, PerformanceMetrics, TraceSpan } from './types.js';\nimport { atomicWriteJson, ensureDir, pathExists, randomId, readJsonFile } from '../../utils/fs.js';\n\nconst TRACES_DIR = '.devworkspace/analytics/traces';\n\nexport class LocalTracer {\n private workspaceRoot: string;\n private activeTraces: Map<string, ExecutionTrace> = new Map();\n\n constructor(workspaceRoot: string) {\n this.workspaceRoot = workspaceRoot;\n }\n\n private tracesPath(): string {\n return path.join(this.workspaceRoot, TRACES_DIR);\n }\n\n startTrace(runId: string): ExecutionTrace {\n const trace: ExecutionTrace = {\n traceId: `T-${randomId()}`,\n runId,\n startTime: new Date().toISOString(),\n spans: [],\n tokensEstimate: 0,\n filesModified: [],\n };\n this.activeTraces.set(runId, trace);\n return trace;\n }\n\n addSpan(runId: string, span: Omit<TraceSpan, 'spanId'>): TraceSpan {\n const trace = this.activeTraces.get(runId);\n const fullSpan: TraceSpan = {\n ...span,\n spanId: `S-${randomId().slice(0, 6)}`,\n };\n if (trace) {\n trace.spans.push(fullSpan);\n }\n return fullSpan;\n }\n\n async finishTrace(runId: string, tokensEstimate = 0, filesModified: string[] = []): Promise<ExecutionTrace | null> {\n const trace = this.activeTraces.get(runId);\n if (!trace) return null;\n\n trace.endTime = new Date().toISOString();\n trace.totalDurationMs = new Date(trace.endTime).getTime() - new Date(trace.startTime).getTime();\n trace.tokensEstimate = tokensEstimate;\n trace.filesModified = filesModified;\n\n const dir = this.tracesPath();\n await ensureDir(dir);\n const filePath = path.join(dir, `${runId}.json`);\n await atomicWriteJson(filePath, trace);\n this.activeTraces.delete(runId);\n return trace;\n }\n\n async getTrace(runId: string): Promise<ExecutionTrace | null> {\n const filePath = path.join(this.tracesPath(), `${runId}.json`);\n if (!(await pathExists(filePath))) return null;\n try {\n return await readJsonFile<ExecutionTrace>(filePath);\n } catch {\n return null;\n }\n }\n\n async listTraces(): Promise<ExecutionTrace[]> {\n const dir = this.tracesPath();\n if (!(await pathExists(dir))) return [];\n\n const traces: ExecutionTrace[] = [];\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n if (e.isFile() && e.name.endsWith('.json')) {\n const runId = e.name.slice(0, -5);\n const t = await this.getTrace(runId);\n if (t) traces.push(t);\n }\n }\n } catch {\n return [];\n }\n return traces;\n }\n\n async computeMetrics(): Promise<PerformanceMetrics> {\n const traces = await this.listTraces();\n const totalRuns = traces.length;\n let successfulRuns = 0;\n let failedRuns = 0;\n let totalDuration = 0;\n let totalTokens = 0;\n\n const agentCounts: Record<string, number> = {};\n const skillCounts: Record<string, number> = {};\n\n for (const t of traces) {\n const hasErrors = t.spans.some((s) => s.status === 'ERROR');\n if (hasErrors) failedRuns++;\n else successfulRuns++;\n\n totalDuration += t.totalDurationMs || 0;\n totalTokens += t.tokensEstimate || 0;\n\n for (const s of t.spans) {\n if (s.agentId) {\n agentCounts[s.agentId] = (agentCounts[s.agentId] || 0) + 1;\n }\n if (s.skillId) {\n skillCounts[s.skillId] = (skillCounts[s.skillId] || 0) + 1;\n }\n }\n }\n\n const topAgents = Object.entries(agentCounts)\n .map(([agentId, count]) => ({ agentId, count }))\n .sort((a, b) => b.count - a.count)\n .slice(0, 5);\n\n const topSkills = Object.entries(skillCounts)\n .map(([skillId, count]) => ({ skillId, count }))\n .sort((a, b) => b.count - a.count)\n .slice(0, 5);\n\n return {\n totalRuns,\n successfulRuns,\n failedRuns,\n averageDurationMs: totalRuns > 0 ? Math.round(totalDuration / totalRuns) : 0,\n totalTokensEstimate: totalTokens,\n topAgents,\n topSkills,\n };\n }\n}\n"]}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export interface TraceSpan {
|
|
2
|
+
spanId: string;
|
|
3
|
+
parentSpanId?: string;
|
|
4
|
+
name: string;
|
|
5
|
+
agentId?: string;
|
|
6
|
+
skillId?: string;
|
|
7
|
+
startTime: string;
|
|
8
|
+
endTime?: string;
|
|
9
|
+
durationMs?: number;
|
|
10
|
+
status: 'OK' | 'ERROR';
|
|
11
|
+
metadata?: Record<string, unknown>;
|
|
12
|
+
error?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface ExecutionTrace {
|
|
15
|
+
traceId: string;
|
|
16
|
+
runId: string;
|
|
17
|
+
startTime: string;
|
|
18
|
+
endTime?: string;
|
|
19
|
+
totalDurationMs?: number;
|
|
20
|
+
spans: TraceSpan[];
|
|
21
|
+
tokensEstimate: number;
|
|
22
|
+
filesModified: string[];
|
|
23
|
+
}
|
|
24
|
+
export interface PerformanceMetrics {
|
|
25
|
+
totalRuns: number;
|
|
26
|
+
successfulRuns: number;
|
|
27
|
+
failedRuns: number;
|
|
28
|
+
averageDurationMs: number;
|
|
29
|
+
totalTokensEstimate: number;
|
|
30
|
+
topAgents: {
|
|
31
|
+
agentId: string;
|
|
32
|
+
count: number;
|
|
33
|
+
}[];
|
|
34
|
+
topSkills: {
|
|
35
|
+
skillId: string;
|
|
36
|
+
count: number;
|
|
37
|
+
}[];
|
|
38
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/intelligence/observability/types.ts"],"names":[],"mappings":"","sourcesContent":["export interface TraceSpan {\n spanId: string;\n parentSpanId?: string;\n name: string;\n agentId?: string;\n skillId?: string;\n startTime: string;\n endTime?: string;\n durationMs?: number;\n status: 'OK' | 'ERROR';\n metadata?: Record<string, unknown>;\n error?: string;\n}\n\nexport interface ExecutionTrace {\n traceId: string;\n runId: string;\n startTime: string;\n endTime?: string;\n totalDurationMs?: number;\n spans: TraceSpan[];\n tokensEstimate: number;\n filesModified: string[];\n}\n\nexport interface PerformanceMetrics {\n totalRuns: number;\n successfulRuns: number;\n failedRuns: number;\n averageDurationMs: number;\n totalTokensEstimate: number;\n topAgents: { agentId: string; count: number }[];\n topSkills: { skillId: string; count: number }[];\n}\n"]}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { IntelligentRouter } from '../routing/router.js';
|
|
2
|
+
import { OrchestrationStore } from './store.js';
|
|
3
|
+
import type { OrchestrationRun, OrchestrationState, PlanOptions, RunOptions } from './types.js';
|
|
4
|
+
export interface DryRunPlanSummary {
|
|
5
|
+
runId: string;
|
|
6
|
+
state: OrchestrationState;
|
|
7
|
+
request: string;
|
|
8
|
+
strategy: string;
|
|
9
|
+
totalStages: number;
|
|
10
|
+
requiresApproval: boolean;
|
|
11
|
+
stages: Array<{
|
|
12
|
+
id: string;
|
|
13
|
+
name: string;
|
|
14
|
+
agentId: string;
|
|
15
|
+
claimedFiles: string[];
|
|
16
|
+
isDestructive: boolean;
|
|
17
|
+
requiresApproval: boolean;
|
|
18
|
+
dependsOn: string[];
|
|
19
|
+
}>;
|
|
20
|
+
estimatedDurationMs: number;
|
|
21
|
+
estimatedTokens: number;
|
|
22
|
+
}
|
|
23
|
+
export declare class OrchestrationEngine {
|
|
24
|
+
private router;
|
|
25
|
+
private store;
|
|
26
|
+
private lockManager;
|
|
27
|
+
constructor(router: IntelligentRouter, store: OrchestrationStore);
|
|
28
|
+
/**
|
|
29
|
+
* Detects potentially destructive operations in stage inputs or prompt.
|
|
30
|
+
*/
|
|
31
|
+
private detectDestructiveOperation;
|
|
32
|
+
/**
|
|
33
|
+
* Safely transitions run state, verifying valid transition rules.
|
|
34
|
+
*/
|
|
35
|
+
private transitionState;
|
|
36
|
+
plan(options: PlanOptions): Promise<OrchestrationRun>;
|
|
37
|
+
approve(runId: string, approvedBy?: string): Promise<OrchestrationRun>;
|
|
38
|
+
dryRun(runId: string): Promise<DryRunPlanSummary>;
|
|
39
|
+
run(options: RunOptions): Promise<OrchestrationRun>;
|
|
40
|
+
resume(runId: string, options?: Omit<RunOptions, 'runId'>): Promise<OrchestrationRun>;
|
|
41
|
+
cancel(runId: string, reason?: string): Promise<OrchestrationRun>;
|
|
42
|
+
}
|
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
import { StageLockManager } from './lock-manager.js';
|
|
2
|
+
import { NativeRuntimeAdapter } from '../runtime/native.js';
|
|
3
|
+
import { isValidStateTransition } from './types.js';
|
|
4
|
+
import { DevWorkspaceError } from '../../errors/index.js';
|
|
5
|
+
import { redact } from '../../security/redact.js';
|
|
6
|
+
export class OrchestrationEngine {
|
|
7
|
+
router;
|
|
8
|
+
store;
|
|
9
|
+
lockManager;
|
|
10
|
+
constructor(router, store) {
|
|
11
|
+
this.router = router;
|
|
12
|
+
this.store = store;
|
|
13
|
+
this.lockManager = new StageLockManager();
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Detects potentially destructive operations in stage inputs or prompt.
|
|
17
|
+
*/
|
|
18
|
+
detectDestructiveOperation(text, inputs = {}) {
|
|
19
|
+
const reasons = [];
|
|
20
|
+
const fullText = [text, JSON.stringify(inputs)].join(' ');
|
|
21
|
+
// 1. Destructive SQL operations
|
|
22
|
+
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;
|
|
23
|
+
if (sqlRegex.test(fullText)) {
|
|
24
|
+
reasons.push('Contains destructive SQL statement (DROP / TRUNCATE / ALTER DROP / unqualified DELETE)');
|
|
25
|
+
}
|
|
26
|
+
// 2. Destructive filesystem operations
|
|
27
|
+
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;
|
|
28
|
+
if (fsRegex.test(fullText)) {
|
|
29
|
+
reasons.push('Contains destructive filesystem or database reset command');
|
|
30
|
+
}
|
|
31
|
+
// 3. Destructive deploy / credential rotation
|
|
32
|
+
const deployRegex = /\b(deploy\s+--prod|publish\s+--force|rotate-all-keys)\b/i;
|
|
33
|
+
if (deployRegex.test(fullText)) {
|
|
34
|
+
reasons.push('Contains production deployment or credential rotation command');
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
isDestructive: reasons.length > 0,
|
|
38
|
+
reasons,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Safely transitions run state, verifying valid transition rules.
|
|
43
|
+
*/
|
|
44
|
+
transitionState(run, newState, note, stageId) {
|
|
45
|
+
if (!isValidStateTransition(run.state, newState)) {
|
|
46
|
+
throw new DevWorkspaceError('USAGE', `Invalid state transition from "${run.state}" to "${newState}".`);
|
|
47
|
+
}
|
|
48
|
+
run.state = newState;
|
|
49
|
+
run.updatedAt = new Date().toISOString();
|
|
50
|
+
run.checkpoints.push({
|
|
51
|
+
at: run.updatedAt,
|
|
52
|
+
state: newState,
|
|
53
|
+
stageId,
|
|
54
|
+
note: redact(note),
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
async plan(options) {
|
|
58
|
+
const req = (options.request || options.prompt || options.title || '').trim();
|
|
59
|
+
// Idempotency check: if a run with this idempotency key already exists, return it
|
|
60
|
+
if (options.idempotencyKey) {
|
|
61
|
+
const existing = await this.store.getRunByIdempotencyKey(options.idempotencyKey);
|
|
62
|
+
if (existing) {
|
|
63
|
+
return existing;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const routing = await this.router.route({
|
|
67
|
+
workspaceRoot: options.workspaceRoot || '',
|
|
68
|
+
request: req,
|
|
69
|
+
taskType: undefined,
|
|
70
|
+
});
|
|
71
|
+
const runId = this.store.generateRunId();
|
|
72
|
+
const stages = [];
|
|
73
|
+
// Stage 1: Analysis & Requirements Formulation
|
|
74
|
+
const analysisAgent = routing.selectedAgents.find((a) => a.agentId === 'planner' || a.agentId === 'research') || routing.selectedAgents[0];
|
|
75
|
+
const stage1Destructive = this.detectDestructiveOperation(req, { taskType: routing.taskType });
|
|
76
|
+
stages.push({
|
|
77
|
+
id: 'stage-1-analysis',
|
|
78
|
+
name: 'Task Decomposition & Architecture Context',
|
|
79
|
+
agentId: analysisAgent?.agentId || 'research',
|
|
80
|
+
skillIds: routing.selectedSkills.map((s) => s.skillId),
|
|
81
|
+
status: 'PENDING',
|
|
82
|
+
dependsOn: [],
|
|
83
|
+
claimedFiles: [],
|
|
84
|
+
inputs: { request: req, taskType: routing.taskType },
|
|
85
|
+
modifiedFiles: [],
|
|
86
|
+
retryCount: 0,
|
|
87
|
+
isDestructive: stage1Destructive.isDestructive,
|
|
88
|
+
requiresApproval: stage1Destructive.isDestructive,
|
|
89
|
+
});
|
|
90
|
+
// Stage 2: Implementation (if not read-only)
|
|
91
|
+
const devAgent = routing.selectedAgents.find((a) => a.agentId === 'developer' || a.agentId === 'database-specialist' || a.agentId === 'debugger');
|
|
92
|
+
if (devAgent) {
|
|
93
|
+
const stage2Destructive = this.detectDestructiveOperation(req, { strategy: routing.strategy });
|
|
94
|
+
stages.push({
|
|
95
|
+
id: 'stage-2-implementation',
|
|
96
|
+
name: `Implementation by ${devAgent.role}`,
|
|
97
|
+
agentId: devAgent.agentId,
|
|
98
|
+
skillIds: routing.selectedSkills.map((s) => s.skillId),
|
|
99
|
+
status: 'PENDING',
|
|
100
|
+
dependsOn: ['stage-1-analysis'],
|
|
101
|
+
claimedFiles: routing.relevantFiles,
|
|
102
|
+
inputs: { strategy: routing.strategy },
|
|
103
|
+
modifiedFiles: [],
|
|
104
|
+
retryCount: 0,
|
|
105
|
+
isDestructive: stage2Destructive.isDestructive,
|
|
106
|
+
requiresApproval: stage2Destructive.isDestructive,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
// Stage 3: Independent Review & Verification
|
|
110
|
+
const reviewerAgent = routing.selectedAgents.find((a) => a.agentId === 'code-reviewer' || a.agentId === 'security-auditor' || a.agentId === 'testing');
|
|
111
|
+
if (reviewerAgent) {
|
|
112
|
+
stages.push({
|
|
113
|
+
id: 'stage-3-verification',
|
|
114
|
+
name: `Independent Verification by ${reviewerAgent.role}`,
|
|
115
|
+
agentId: reviewerAgent.agentId,
|
|
116
|
+
skillIds: ['code-review', 'security-audit'],
|
|
117
|
+
status: 'PENDING',
|
|
118
|
+
dependsOn: devAgent ? ['stage-2-implementation'] : ['stage-1-analysis'],
|
|
119
|
+
claimedFiles: [],
|
|
120
|
+
inputs: { verificationContract: 'standard' },
|
|
121
|
+
modifiedFiles: [],
|
|
122
|
+
retryCount: 0,
|
|
123
|
+
isDestructive: false,
|
|
124
|
+
requiresApproval: false,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
const hasDestructive = stages.some((s) => s.isDestructive);
|
|
128
|
+
const requiresApproval = (routing.requiredApprovals.length > 0 || routing.complexity === 'CRITICAL' || hasDestructive) && !options.autoApprove;
|
|
129
|
+
const initialState = requiresApproval ? 'AWAITING_APPROVAL' : 'READY';
|
|
130
|
+
const now = new Date().toISOString();
|
|
131
|
+
const run = {
|
|
132
|
+
runId,
|
|
133
|
+
taskId: options.taskId,
|
|
134
|
+
idempotencyKey: options.idempotencyKey,
|
|
135
|
+
request: req,
|
|
136
|
+
state: initialState,
|
|
137
|
+
routing,
|
|
138
|
+
stages,
|
|
139
|
+
currentStageIndex: 0,
|
|
140
|
+
checkpoints: [
|
|
141
|
+
{
|
|
142
|
+
at: now,
|
|
143
|
+
state: 'CREATED',
|
|
144
|
+
note: `Plan generated with ${stages.length} stage(s) under strategy ${routing.strategy}.`,
|
|
145
|
+
},
|
|
146
|
+
{
|
|
147
|
+
at: now,
|
|
148
|
+
state: initialState,
|
|
149
|
+
note: requiresApproval ? 'Plan requires developer approval before execution.' : 'Plan validated and ready for execution.',
|
|
150
|
+
},
|
|
151
|
+
],
|
|
152
|
+
retryCount: 0,
|
|
153
|
+
maxRetries: options.maxRetries ?? 3,
|
|
154
|
+
metrics: {
|
|
155
|
+
durationMs: 0,
|
|
156
|
+
tokensEstimate: routing.estimatedResources.tokensEstimate,
|
|
157
|
+
filesModifiedCount: 0,
|
|
158
|
+
stagesCompleted: 0,
|
|
159
|
+
correctionsCount: 0,
|
|
160
|
+
},
|
|
161
|
+
createdAt: now,
|
|
162
|
+
updatedAt: now,
|
|
163
|
+
isDryRun: options.dryRun,
|
|
164
|
+
};
|
|
165
|
+
await this.store.saveRun(run);
|
|
166
|
+
return run;
|
|
167
|
+
}
|
|
168
|
+
async approve(runId, approvedBy = 'user') {
|
|
169
|
+
const run = await this.store.getRun(runId);
|
|
170
|
+
if (!run) {
|
|
171
|
+
throw new DevWorkspaceError('NOT_FOUND', `Orchestration run "${runId}" not found.`);
|
|
172
|
+
}
|
|
173
|
+
if (run.state !== 'AWAITING_APPROVAL' && run.state !== 'WAITING_APPROVAL') {
|
|
174
|
+
throw new DevWorkspaceError('USAGE', `Run "${runId}" is in state "${run.state}", not AWAITING_APPROVAL.`);
|
|
175
|
+
}
|
|
176
|
+
run.approvedBy = approvedBy;
|
|
177
|
+
run.approvedAt = new Date().toISOString();
|
|
178
|
+
this.transitionState(run, 'READY', `Plan approved by ${approvedBy}. Ready for execution.`);
|
|
179
|
+
await this.store.saveRun(run);
|
|
180
|
+
return run;
|
|
181
|
+
}
|
|
182
|
+
async dryRun(runId) {
|
|
183
|
+
const run = await this.store.getRun(runId);
|
|
184
|
+
if (!run) {
|
|
185
|
+
throw new DevWorkspaceError('NOT_FOUND', `Orchestration run "${runId}" not found.`);
|
|
186
|
+
}
|
|
187
|
+
return {
|
|
188
|
+
runId: run.runId,
|
|
189
|
+
state: run.state,
|
|
190
|
+
request: run.request,
|
|
191
|
+
strategy: run.routing?.strategy ?? 'STANDARD',
|
|
192
|
+
totalStages: run.stages.length,
|
|
193
|
+
requiresApproval: run.state === 'AWAITING_APPROVAL' || run.state === 'WAITING_APPROVAL',
|
|
194
|
+
stages: run.stages.map((s) => ({
|
|
195
|
+
id: s.id,
|
|
196
|
+
name: s.name,
|
|
197
|
+
agentId: s.agentId,
|
|
198
|
+
claimedFiles: s.claimedFiles,
|
|
199
|
+
isDestructive: Boolean(s.isDestructive),
|
|
200
|
+
requiresApproval: Boolean(s.requiresApproval),
|
|
201
|
+
dependsOn: s.dependsOn,
|
|
202
|
+
})),
|
|
203
|
+
estimatedDurationMs: run.metrics.durationMs,
|
|
204
|
+
estimatedTokens: run.metrics.tokensEstimate,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
async run(options) {
|
|
208
|
+
const run = await this.store.getRun(options.runId);
|
|
209
|
+
if (!run) {
|
|
210
|
+
throw new DevWorkspaceError('NOT_FOUND', `Orchestration run "${options.runId}" not found.`);
|
|
211
|
+
}
|
|
212
|
+
// Duplicate execution protection: do not re-run an already completed or running run
|
|
213
|
+
if (run.state === 'COMPLETED' || run.state === 'SUCCEEDED') {
|
|
214
|
+
return run;
|
|
215
|
+
}
|
|
216
|
+
if (run.state === 'RUNNING') {
|
|
217
|
+
throw new DevWorkspaceError('USAGE', `Run "${run.runId}" is already running.`);
|
|
218
|
+
}
|
|
219
|
+
if (run.state === 'CANCELLED' || run.state === 'TIMED_OUT') {
|
|
220
|
+
throw new DevWorkspaceError('USAGE', `Cannot run "${run.runId}" in terminal state "${run.state}".`);
|
|
221
|
+
}
|
|
222
|
+
// Approval gating: check if approval is required
|
|
223
|
+
if (run.state === 'AWAITING_APPROVAL' || run.state === 'WAITING_APPROVAL') {
|
|
224
|
+
if (options.explicitApproval) {
|
|
225
|
+
run.approvedBy = run.approvedBy ?? 'explicit-opt-in';
|
|
226
|
+
run.approvedAt = new Date().toISOString();
|
|
227
|
+
this.transitionState(run, 'READY', 'Execution explicitly approved by developer option.');
|
|
228
|
+
}
|
|
229
|
+
else {
|
|
230
|
+
throw new DevWorkspaceError('USAGE', `Run "${run.runId}" requires developer approval before execution.`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (run.state !== 'READY' && run.state !== 'PAUSED' && run.state !== 'BLOCKED') {
|
|
234
|
+
throw new DevWorkspaceError('USAGE', `Run "${run.runId}" is in state "${run.state}"; only READY, PAUSED or unblocked runs can be executed.`);
|
|
235
|
+
}
|
|
236
|
+
// Certify runtime adapter: placeholder runtimes MUST NEVER return successful execution
|
|
237
|
+
const adapter = options.runtimeAdapter ?? new NativeRuntimeAdapter();
|
|
238
|
+
if (adapter.isPlaceholder) {
|
|
239
|
+
this.transitionState(run, 'FAILED', 'Placeholder runtime cannot return a successful execution.');
|
|
240
|
+
run.error = 'No placeholder runtime can return a successful execution.';
|
|
241
|
+
await this.store.saveRun(run);
|
|
242
|
+
return run;
|
|
243
|
+
}
|
|
244
|
+
const startTs = Date.now();
|
|
245
|
+
const timeoutMs = (options.timeoutSeconds ? options.timeoutSeconds * 1000 : options.timeoutMs) ?? 0;
|
|
246
|
+
this.transitionState(run, 'RUNNING', 'Execution started.');
|
|
247
|
+
await this.store.saveRun(run);
|
|
248
|
+
try {
|
|
249
|
+
for (let i = run.currentStageIndex; i < run.stages.length; i++) {
|
|
250
|
+
const stage = run.stages[i];
|
|
251
|
+
run.currentStageIndex = i;
|
|
252
|
+
// Check cancellation
|
|
253
|
+
if (options.signal?.aborted) {
|
|
254
|
+
this.transitionState(run, 'CANCELLED', 'Run cancelled by user request.', stage.id);
|
|
255
|
+
await this.store.saveRun(run);
|
|
256
|
+
return run;
|
|
257
|
+
}
|
|
258
|
+
// Check timeout
|
|
259
|
+
if (timeoutMs > 0 && Date.now() - startTs > timeoutMs) {
|
|
260
|
+
stage.status = 'TIMED_OUT';
|
|
261
|
+
this.transitionState(run, 'TIMED_OUT', `Execution timed out after ${timeoutMs}ms.`, stage.id);
|
|
262
|
+
this.lockManager.releaseAllForStage(stage.id);
|
|
263
|
+
await this.store.saveRun(run);
|
|
264
|
+
return run;
|
|
265
|
+
}
|
|
266
|
+
// Destructive operations safety gate
|
|
267
|
+
if (stage.isDestructive && !run.approvedBy && !options.explicitApproval) {
|
|
268
|
+
stage.status = 'WAITING_APPROVAL';
|
|
269
|
+
this.transitionState(run, 'WAITING_APPROVAL', `Execution halted: stage "${stage.name}" requires explicit approval for destructive operations.`, stage.id);
|
|
270
|
+
await this.store.saveRun(run);
|
|
271
|
+
return run;
|
|
272
|
+
}
|
|
273
|
+
// Single-writer lock acquisition for claimed files
|
|
274
|
+
if (stage.claimedFiles.length > 0) {
|
|
275
|
+
const lockResult = await this.lockManager.acquire(stage.id, stage.agentId, stage.claimedFiles, 'write');
|
|
276
|
+
if (!lockResult.acquired) {
|
|
277
|
+
stage.status = 'BLOCKED';
|
|
278
|
+
this.transitionState(run, 'BLOCKED', `Execution blocked: file lock conflict on ${lockResult.conflictingFiles?.join(', ')}.`, stage.id);
|
|
279
|
+
await this.store.saveRun(run);
|
|
280
|
+
return run;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
stage.status = 'RUNNING';
|
|
284
|
+
stage.startedAt = new Date().toISOString();
|
|
285
|
+
await this.store.saveRun(run);
|
|
286
|
+
// Execute stage work with runtime adapter
|
|
287
|
+
let stageSuccess = false;
|
|
288
|
+
let lastError;
|
|
289
|
+
let receipt;
|
|
290
|
+
while (!stageSuccess && stage.retryCount <= run.maxRetries) {
|
|
291
|
+
try {
|
|
292
|
+
const execRes = await adapter.execute({
|
|
293
|
+
agentId: stage.agentId,
|
|
294
|
+
role: stage.name,
|
|
295
|
+
prompt: run.request,
|
|
296
|
+
skills: stage.skillIds,
|
|
297
|
+
contextFiles: stage.claimedFiles,
|
|
298
|
+
timeoutMs: timeoutMs > 0 ? Math.max(1000, timeoutMs - (Date.now() - startTs)) : undefined,
|
|
299
|
+
signal: options.signal,
|
|
300
|
+
command: stage.inputs.command,
|
|
301
|
+
cwd: options.workspaceRoot,
|
|
302
|
+
});
|
|
303
|
+
if (execRes.isPlaceholder || !execRes.ok) {
|
|
304
|
+
throw new Error(execRes.error || 'Stage execution failed in runtime adapter.');
|
|
305
|
+
}
|
|
306
|
+
// Independent verification gate
|
|
307
|
+
let verificationReport = undefined;
|
|
308
|
+
if (options.verificationEngine) {
|
|
309
|
+
this.transitionState(run, 'VERIFYING', `Running independent verification for stage "${stage.name}".`, stage.id);
|
|
310
|
+
const checks = stage.inputs.contractChecks ?? [];
|
|
311
|
+
const modified = (execRes.filesModified ?? []).map((f) => ({ path: f, content: '' }));
|
|
312
|
+
verificationReport = await options.verificationEngine.verify(checks, modified);
|
|
313
|
+
if (!verificationReport.canComplete) {
|
|
314
|
+
throw new Error(`Verification failed: ${verificationReport.summary}`);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
// Execution receipt
|
|
318
|
+
receipt = {
|
|
319
|
+
command: stage.inputs.command,
|
|
320
|
+
cwd: options.workspaceRoot,
|
|
321
|
+
exitCode: execRes.exitCode ?? 0,
|
|
322
|
+
durationMs: execRes.durationMs,
|
|
323
|
+
stdout: execRes.stdout,
|
|
324
|
+
stderr: execRes.stderr,
|
|
325
|
+
timedOut: execRes.timedOut,
|
|
326
|
+
aborted: execRes.aborted,
|
|
327
|
+
filesModified: execRes.filesModified,
|
|
328
|
+
executedAt: new Date().toISOString(),
|
|
329
|
+
verified: true,
|
|
330
|
+
verificationReport,
|
|
331
|
+
};
|
|
332
|
+
stage.status = 'COMPLETED';
|
|
333
|
+
stage.completedAt = new Date().toISOString();
|
|
334
|
+
stage.outputs = { outcome: 'success', verified: true, receipt };
|
|
335
|
+
stage.receipt = receipt;
|
|
336
|
+
run.metrics.stagesCompleted += 1;
|
|
337
|
+
stageSuccess = true;
|
|
338
|
+
}
|
|
339
|
+
catch (err) {
|
|
340
|
+
lastError = err.message;
|
|
341
|
+
if (stage.retryCount < run.maxRetries) {
|
|
342
|
+
stage.retryCount += 1;
|
|
343
|
+
run.metrics.correctionsCount += 1;
|
|
344
|
+
this.transitionState(run, 'CORRECTING', `Retrying stage "${stage.name}" (attempt ${stage.retryCount}/${run.maxRetries}): ${redact(err.message)}`, stage.id);
|
|
345
|
+
await this.store.saveRun(run);
|
|
346
|
+
}
|
|
347
|
+
else {
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
this.lockManager.releaseAllForStage(stage.id);
|
|
353
|
+
if (timeoutMs > 0 && Date.now() - startTs > timeoutMs) {
|
|
354
|
+
stage.status = 'TIMED_OUT';
|
|
355
|
+
this.transitionState(run, 'TIMED_OUT', `Execution timed out after ${timeoutMs}ms.`, stage.id);
|
|
356
|
+
await this.store.saveRun(run);
|
|
357
|
+
return run;
|
|
358
|
+
}
|
|
359
|
+
if (!stageSuccess) {
|
|
360
|
+
stage.status = 'FAILED';
|
|
361
|
+
stage.error = lastError;
|
|
362
|
+
throw new Error(lastError || `Stage "${stage.name}" failed after ${run.maxRetries} retries.`);
|
|
363
|
+
}
|
|
364
|
+
this.transitionState(run, 'RUNNING', `Stage "${stage.name}" completed successfully.`, stage.id);
|
|
365
|
+
await this.store.saveRun(run);
|
|
366
|
+
}
|
|
367
|
+
// Verification transition
|
|
368
|
+
this.transitionState(run, 'VERIFYING', 'All stages finished. Running independent verification gates.');
|
|
369
|
+
await this.store.saveRun(run);
|
|
370
|
+
// Final Completion
|
|
371
|
+
this.transitionState(run, 'COMPLETED', 'Workflow successfully verified and completed.');
|
|
372
|
+
run.metrics.durationMs = Date.now() - startTs;
|
|
373
|
+
await this.store.saveRun(run);
|
|
374
|
+
return run;
|
|
375
|
+
}
|
|
376
|
+
catch (err) {
|
|
377
|
+
this.transitionState(run, 'FAILED', `Execution failed: ${err.message}`);
|
|
378
|
+
run.error = err.message;
|
|
379
|
+
run.metrics.durationMs = Date.now() - startTs;
|
|
380
|
+
await this.store.saveRun(run);
|
|
381
|
+
return run;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
async resume(runId, options) {
|
|
385
|
+
const run = await this.store.getRun(runId);
|
|
386
|
+
if (!run) {
|
|
387
|
+
throw new DevWorkspaceError('NOT_FOUND', `Orchestration run "${runId}" not found.`);
|
|
388
|
+
}
|
|
389
|
+
if (run.state !== 'PAUSED' && run.state !== 'BLOCKED' && run.state !== 'WAITING_APPROVAL' && run.state !== 'AWAITING_APPROVAL') {
|
|
390
|
+
throw new DevWorkspaceError('USAGE', `Run "${runId}" is in state "${run.state}"; only PAUSED, BLOCKED, or approved runs can be resumed.`);
|
|
391
|
+
}
|
|
392
|
+
this.transitionState(run, 'READY', 'Run resumed by developer request.');
|
|
393
|
+
await this.store.saveRun(run);
|
|
394
|
+
return this.run({
|
|
395
|
+
...options,
|
|
396
|
+
runId,
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
async cancel(runId, reason = 'Cancelled by developer') {
|
|
400
|
+
const run = await this.store.getRun(runId);
|
|
401
|
+
if (!run) {
|
|
402
|
+
throw new DevWorkspaceError('NOT_FOUND', `Orchestration run "${runId}" not found.`);
|
|
403
|
+
}
|
|
404
|
+
if (['COMPLETED', 'SUCCEEDED', 'FAILED', 'CANCELLED', 'TIMED_OUT'].includes(run.state)) {
|
|
405
|
+
throw new DevWorkspaceError('USAGE', `Cannot cancel run "${runId}" in terminal state "${run.state}".`);
|
|
406
|
+
}
|
|
407
|
+
// Release any active locks
|
|
408
|
+
for (const stage of run.stages) {
|
|
409
|
+
this.lockManager.releaseAllForStage(stage.id);
|
|
410
|
+
}
|
|
411
|
+
run.error = reason;
|
|
412
|
+
run.cancellationReason = reason;
|
|
413
|
+
this.transitionState(run, 'CANCELLED', reason);
|
|
414
|
+
await this.store.saveRun(run);
|
|
415
|
+
return run;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
//# sourceMappingURL=engine.js.map
|