devworkspace 0.4.5 → 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.
Files changed (263) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +7 -0
  3. package/dist/cli/args.d.ts +30 -0
  4. package/dist/cli/args.js +10 -0
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/cli/help.js +134 -0
  7. package/dist/cli/help.js.map +1 -1
  8. package/dist/cli/render.d.ts +6 -0
  9. package/dist/cli/render.js +106 -0
  10. package/dist/cli/render.js.map +1 -1
  11. package/dist/cli/run.js +351 -1
  12. package/dist/cli/run.js.map +1 -1
  13. package/dist/core/contracts.d.ts +70 -0
  14. package/dist/core/contracts.js +88 -0
  15. package/dist/core/contracts.js.map +1 -0
  16. package/dist/discovery/commands.d.ts +1 -1
  17. package/dist/discovery/commands.js.map +1 -1
  18. package/dist/discovery/detect.d.ts +2 -70
  19. package/dist/discovery/detect.js.map +1 -1
  20. package/dist/discovery/entrypoints.d.ts +2 -11
  21. package/dist/discovery/entrypoints.js.map +1 -1
  22. package/dist/discovery/types.d.ts +79 -0
  23. package/dist/discovery/types.js +2 -0
  24. package/dist/discovery/types.js.map +1 -0
  25. package/dist/dx/dashboard.d.ts +21 -0
  26. package/dist/dx/dashboard.js +274 -0
  27. package/dist/dx/dashboard.js.map +1 -0
  28. package/dist/dx/guidance.d.ts +21 -0
  29. package/dist/dx/guidance.js +266 -0
  30. package/dist/dx/guidance.js.map +1 -0
  31. package/dist/dx/index.d.ts +4 -0
  32. package/dist/dx/index.js +5 -0
  33. package/dist/dx/index.js.map +1 -0
  34. package/dist/dx/onboarding.d.ts +23 -0
  35. package/dist/dx/onboarding.js +155 -0
  36. package/dist/dx/onboarding.js.map +1 -0
  37. package/dist/dx/types.d.ts +70 -0
  38. package/dist/dx/types.js +3 -0
  39. package/dist/dx/types.js.map +1 -0
  40. package/dist/index.d.ts +35 -0
  41. package/dist/index.js +28 -0
  42. package/dist/index.js.map +1 -1
  43. package/dist/integrations/persistentPath.d.ts +2 -9
  44. package/dist/integrations/persistentPath.js.map +1 -1
  45. package/dist/integrations/types.d.ts +4 -1
  46. package/dist/integrations/types.js.map +1 -1
  47. package/dist/intelligence/agents/profiles.d.ts +2 -0
  48. package/dist/intelligence/agents/profiles.js +326 -0
  49. package/dist/intelligence/agents/profiles.js.map +1 -0
  50. package/dist/intelligence/agents/registry.d.ts +15 -0
  51. package/dist/intelligence/agents/registry.js +108 -0
  52. package/dist/intelligence/agents/registry.js.map +1 -0
  53. package/dist/intelligence/agents/types.d.ts +43 -0
  54. package/dist/intelligence/agents/types.js +2 -0
  55. package/dist/intelligence/agents/types.js.map +1 -0
  56. package/dist/intelligence/observability/tracer.d.ts +13 -0
  57. package/dist/intelligence/observability/tracer.js +129 -0
  58. package/dist/intelligence/observability/tracer.js.map +1 -0
  59. package/dist/intelligence/observability/types.d.ts +38 -0
  60. package/dist/intelligence/observability/types.js +2 -0
  61. package/dist/intelligence/observability/types.js.map +1 -0
  62. package/dist/intelligence/orchestration/engine.d.ts +51 -0
  63. package/dist/intelligence/orchestration/engine.js +578 -0
  64. package/dist/intelligence/orchestration/engine.js.map +1 -0
  65. package/dist/intelligence/orchestration/lock-manager.d.ts +21 -0
  66. package/dist/intelligence/orchestration/lock-manager.js +70 -0
  67. package/dist/intelligence/orchestration/lock-manager.js.map +1 -0
  68. package/dist/intelligence/orchestration/store.d.ts +11 -0
  69. package/dist/intelligence/orchestration/store.js +73 -0
  70. package/dist/intelligence/orchestration/store.js.map +1 -0
  71. package/dist/intelligence/orchestration/types.d.ts +111 -0
  72. package/dist/intelligence/orchestration/types.js +48 -0
  73. package/dist/intelligence/orchestration/types.js.map +1 -0
  74. package/dist/intelligence/routing/matcher.d.ts +7 -0
  75. package/dist/intelligence/routing/matcher.js +96 -0
  76. package/dist/intelligence/routing/matcher.js.map +1 -0
  77. package/dist/intelligence/routing/router.d.ts +9 -0
  78. package/dist/intelligence/routing/router.js +198 -0
  79. package/dist/intelligence/routing/router.js.map +1 -0
  80. package/dist/intelligence/routing/types.d.ts +64 -0
  81. package/dist/intelligence/routing/types.js +2 -0
  82. package/dist/intelligence/routing/types.js.map +1 -0
  83. package/dist/intelligence/runtime/adk/adapter.d.ts +7 -0
  84. package/dist/intelligence/runtime/adk/adapter.js +49 -0
  85. package/dist/intelligence/runtime/adk/adapter.js.map +1 -0
  86. package/dist/intelligence/runtime/adk/detector.d.ts +7 -0
  87. package/dist/intelligence/runtime/adk/detector.js +28 -0
  88. package/dist/intelligence/runtime/adk/detector.js.map +1 -0
  89. package/dist/intelligence/runtime/boundary.d.ts +30 -0
  90. package/dist/intelligence/runtime/boundary.js +163 -0
  91. package/dist/intelligence/runtime/boundary.js.map +1 -0
  92. package/dist/intelligence/runtime/external.d.ts +9 -0
  93. package/dist/intelligence/runtime/external.js +76 -0
  94. package/dist/intelligence/runtime/external.js.map +1 -0
  95. package/dist/intelligence/runtime/native.d.ts +19 -0
  96. package/dist/intelligence/runtime/native.js +67 -0
  97. package/dist/intelligence/runtime/native.js.map +1 -0
  98. package/dist/intelligence/runtime/types.d.ts +77 -0
  99. package/dist/intelligence/runtime/types.js +12 -0
  100. package/dist/intelligence/runtime/types.js.map +1 -0
  101. package/dist/intelligence/security/audit.d.ts +8 -0
  102. package/dist/intelligence/security/audit.js +43 -0
  103. package/dist/intelligence/security/audit.js.map +1 -0
  104. package/dist/intelligence/security/policy.d.ts +12 -0
  105. package/dist/intelligence/security/policy.js +153 -0
  106. package/dist/intelligence/security/policy.js.map +1 -0
  107. package/dist/intelligence/security/types.d.ts +25 -0
  108. package/dist/intelligence/security/types.js +2 -0
  109. package/dist/intelligence/security/types.js.map +1 -0
  110. package/dist/intelligence/skills/builtins.d.ts +2 -0
  111. package/dist/intelligence/skills/builtins.js +379 -0
  112. package/dist/intelligence/skills/builtins.js.map +1 -0
  113. package/dist/intelligence/skills/loader.d.ts +4 -0
  114. package/dist/intelligence/skills/loader.js +84 -0
  115. package/dist/intelligence/skills/loader.js.map +1 -0
  116. package/dist/intelligence/skills/registry.d.ts +15 -0
  117. package/dist/intelligence/skills/registry.js +134 -0
  118. package/dist/intelligence/skills/registry.js.map +1 -0
  119. package/dist/intelligence/skills/types.d.ts +35 -0
  120. package/dist/intelligence/skills/types.js +2 -0
  121. package/dist/intelligence/skills/types.js.map +1 -0
  122. package/dist/intelligence/verification/engine.d.ts +37 -0
  123. package/dist/intelligence/verification/engine.js +127 -0
  124. package/dist/intelligence/verification/engine.js.map +1 -0
  125. package/dist/intelligence/verification/reviewer.d.ts +8 -0
  126. package/dist/intelligence/verification/reviewer.js +55 -0
  127. package/dist/intelligence/verification/reviewer.js.map +1 -0
  128. package/dist/intelligence/verification/types.d.ts +43 -0
  129. package/dist/intelligence/verification/types.js +2 -0
  130. package/dist/intelligence/verification/types.js.map +1 -0
  131. package/dist/mcp/setup.d.ts +2 -4
  132. package/dist/mcp/setup.js.map +1 -1
  133. package/dist/mcp/tools.js +6 -6
  134. package/dist/mcp/tools.js.map +1 -1
  135. package/dist/mcp/types.d.ts +4 -0
  136. package/dist/mcp/types.js.map +1 -1
  137. package/dist/mcp/verify.d.ts +1 -1
  138. package/dist/mcp/verify.js.map +1 -1
  139. package/dist/security/redact.js +3 -2
  140. package/dist/security/redact.js.map +1 -1
  141. package/dist/services/doctor.js +4 -0
  142. package/dist/services/doctor.js.map +1 -1
  143. package/dist/services/intelligence.d.ts +44 -0
  144. package/dist/services/intelligence.js +119 -0
  145. package/dist/services/intelligence.js.map +1 -0
  146. package/dist/services/standards.d.ts +85 -0
  147. package/dist/services/standards.js +230 -0
  148. package/dist/services/standards.js.map +1 -0
  149. package/dist/services/taskContext.js +4 -0
  150. package/dist/services/taskContext.js.map +1 -1
  151. package/dist/standards/acquisition/ingest.d.ts +12 -0
  152. package/dist/standards/acquisition/ingest.js +98 -0
  153. package/dist/standards/acquisition/ingest.js.map +1 -0
  154. package/dist/standards/applicability/engine.d.ts +38 -0
  155. package/dist/standards/applicability/engine.js +250 -0
  156. package/dist/standards/applicability/engine.js.map +1 -0
  157. package/dist/standards/builtin/code-quality.d.ts +2 -0
  158. package/dist/standards/builtin/code-quality.js +53 -0
  159. package/dist/standards/builtin/code-quality.js.map +1 -0
  160. package/dist/standards/builtin/database-safety.d.ts +2 -0
  161. package/dist/standards/builtin/database-safety.js +56 -0
  162. package/dist/standards/builtin/database-safety.js.map +1 -0
  163. package/dist/standards/builtin/index.d.ts +8 -0
  164. package/dist/standards/builtin/index.js +14 -0
  165. package/dist/standards/builtin/index.js.map +1 -0
  166. package/dist/standards/builtin/security-baseline.d.ts +2 -0
  167. package/dist/standards/builtin/security-baseline.js +64 -0
  168. package/dist/standards/builtin/security-baseline.js.map +1 -0
  169. package/dist/standards/builtin/testing-contracts.d.ts +2 -0
  170. package/dist/standards/builtin/testing-contracts.js +54 -0
  171. package/dist/standards/builtin/testing-contracts.js.map +1 -0
  172. package/dist/standards/builtin/undo-kit.d.ts +8 -0
  173. package/dist/standards/builtin/undo-kit.js +106 -0
  174. package/dist/standards/builtin/undo-kit.js.map +1 -0
  175. package/dist/standards/config/config.d.ts +12 -0
  176. package/dist/standards/config/config.js +110 -0
  177. package/dist/standards/config/config.js.map +1 -0
  178. package/dist/standards/distribution/cache.d.ts +58 -0
  179. package/dist/standards/distribution/cache.js +425 -0
  180. package/dist/standards/distribution/cache.js.map +1 -0
  181. package/dist/standards/distribution/index.d.ts +6 -0
  182. package/dist/standards/distribution/index.js +7 -0
  183. package/dist/standards/distribution/index.js.map +1 -0
  184. package/dist/standards/distribution/keys.d.ts +53 -0
  185. package/dist/standards/distribution/keys.js +269 -0
  186. package/dist/standards/distribution/keys.js.map +1 -0
  187. package/dist/standards/distribution/package.d.ts +25 -0
  188. package/dist/standards/distribution/package.js +254 -0
  189. package/dist/standards/distribution/package.js.map +1 -0
  190. package/dist/standards/distribution/server.d.ts +38 -0
  191. package/dist/standards/distribution/server.js +204 -0
  192. package/dist/standards/distribution/server.js.map +1 -0
  193. package/dist/standards/distribution/sync.d.ts +56 -0
  194. package/dist/standards/distribution/sync.js +245 -0
  195. package/dist/standards/distribution/sync.js.map +1 -0
  196. package/dist/standards/distribution/types.d.ts +140 -0
  197. package/dist/standards/distribution/types.js +26 -0
  198. package/dist/standards/distribution/types.js.map +1 -0
  199. package/dist/standards/engine/compliance.d.ts +2 -0
  200. package/dist/standards/engine/compliance.js +45 -0
  201. package/dist/standards/engine/compliance.js.map +1 -0
  202. package/dist/standards/engine/engine.d.ts +14 -0
  203. package/dist/standards/engine/engine.js +114 -0
  204. package/dist/standards/engine/engine.js.map +1 -0
  205. package/dist/standards/engine/reporter.d.ts +2 -0
  206. package/dist/standards/engine/reporter.js +42 -0
  207. package/dist/standards/engine/reporter.js.map +1 -0
  208. package/dist/standards/index.d.ts +18 -0
  209. package/dist/standards/index.js +19 -0
  210. package/dist/standards/index.js.map +1 -0
  211. package/dist/standards/registry/registry.d.ts +29 -0
  212. package/dist/standards/registry/registry.js +210 -0
  213. package/dist/standards/registry/registry.js.map +1 -0
  214. package/dist/standards/schema/types.d.ts +133 -0
  215. package/dist/standards/schema/types.js +33 -0
  216. package/dist/standards/schema/types.js.map +1 -0
  217. package/dist/standards/schema/validate.d.ts +6 -0
  218. package/dist/standards/schema/validate.js +131 -0
  219. package/dist/standards/schema/validate.js.map +1 -0
  220. package/dist/standards/templates/index.d.ts +11 -0
  221. package/dist/standards/templates/index.js +176 -0
  222. package/dist/standards/templates/index.js.map +1 -0
  223. package/dist/standards/validators/database.d.ts +5 -0
  224. package/dist/standards/validators/database.js +122 -0
  225. package/dist/standards/validators/database.js.map +1 -0
  226. package/dist/standards/validators/quality.d.ts +6 -0
  227. package/dist/standards/validators/quality.js +91 -0
  228. package/dist/standards/validators/quality.js.map +1 -0
  229. package/dist/standards/validators/registry.d.ts +11 -0
  230. package/dist/standards/validators/registry.js +83 -0
  231. package/dist/standards/validators/registry.js.map +1 -0
  232. package/dist/standards/validators/security.d.ts +7 -0
  233. package/dist/standards/validators/security.js +182 -0
  234. package/dist/standards/validators/security.js.map +1 -0
  235. package/dist/standards/validators/testing.d.ts +6 -0
  236. package/dist/standards/validators/testing.js +142 -0
  237. package/dist/standards/validators/testing.js.map +1 -0
  238. package/dist/standards/validators/types.d.ts +11 -0
  239. package/dist/standards/validators/types.js +2 -0
  240. package/dist/standards/validators/types.js.map +1 -0
  241. package/dist/standards/validators/undo-kit.d.ts +7 -0
  242. package/dist/standards/validators/undo-kit.js +334 -0
  243. package/dist/standards/validators/undo-kit.js.map +1 -0
  244. package/dist/tasks/routing.js +5 -3
  245. package/dist/tasks/routing.js.map +1 -1
  246. package/dist/utils/fs.d.ts +1 -1
  247. package/dist/utils/fs.js.map +1 -1
  248. package/dist/utils/lock.js +11 -3
  249. package/dist/utils/lock.js.map +1 -1
  250. package/dist/utils/paths.js +29 -0
  251. package/dist/utils/paths.js.map +1 -1
  252. package/dist/utils/proc.d.ts +4 -0
  253. package/dist/utils/proc.js +60 -4
  254. package/dist/utils/proc.js.map +1 -1
  255. package/docs/agents.md +15 -0
  256. package/docs/contributing.md +13 -5
  257. package/docs/getting-started.md +7 -0
  258. package/docs/mcp.md +13 -0
  259. package/docs/security/HOME_SERVER_THREAT_MODEL.md +72 -0
  260. package/docs/security/THREAT_MODEL.md +101 -0
  261. package/docs/security.md +8 -2
  262. package/docs/standards.md +143 -0
  263. package/package.json +1 -1
@@ -0,0 +1,578 @@
1
+ import crypto from 'node:crypto';
2
+ import { StageLockManager } from './lock-manager.js';
3
+ import { NativeRuntimeAdapter } from '../runtime/native.js';
4
+ import { createExecutionId } from '../runtime/boundary.js';
5
+ import { isValidStateTransition } from './types.js';
6
+ import { DevWorkspaceError } from '../../errors/index.js';
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';
12
+ export class OrchestrationEngine {
13
+ router;
14
+ store;
15
+ lockManager;
16
+ constructor(router, store) {
17
+ this.router = router;
18
+ this.store = store;
19
+ this.lockManager = new StageLockManager();
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
+ }
103
+ /**
104
+ * Detects potentially destructive operations in stage inputs or prompt.
105
+ */
106
+ detectDestructiveOperation(text, inputs = {}) {
107
+ const reasons = [];
108
+ const fullText = [text, JSON.stringify(inputs)].join(' ');
109
+ // 1. Destructive SQL operations
110
+ 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;
111
+ if (sqlRegex.test(fullText)) {
112
+ reasons.push('Contains destructive SQL statement (DROP / TRUNCATE / ALTER DROP / unqualified DELETE)');
113
+ }
114
+ // 2. Destructive filesystem operations
115
+ 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;
116
+ if (fsRegex.test(fullText)) {
117
+ reasons.push('Contains destructive filesystem or database reset command');
118
+ }
119
+ // 3. Destructive deploy / credential rotation
120
+ const deployRegex = /\b(deploy\s+--prod|publish\s+--force|rotate-all-keys)\b/i;
121
+ if (deployRegex.test(fullText)) {
122
+ reasons.push('Contains production deployment or credential rotation command');
123
+ }
124
+ return {
125
+ isDestructive: reasons.length > 0,
126
+ reasons,
127
+ };
128
+ }
129
+ /**
130
+ * Safely transitions run state, verifying valid transition rules.
131
+ */
132
+ transitionState(run, newState, note, stageId) {
133
+ if (!isValidStateTransition(run.state, newState)) {
134
+ throw new DevWorkspaceError('USAGE', `Invalid state transition from "${run.state}" to "${newState}".`);
135
+ }
136
+ run.state = newState;
137
+ run.updatedAt = new Date().toISOString();
138
+ run.checkpoints.push({
139
+ at: run.updatedAt,
140
+ state: newState,
141
+ stageId,
142
+ note: redact(note),
143
+ });
144
+ }
145
+ async plan(options) {
146
+ const req = (options.request || options.prompt || options.title || '').trim();
147
+ // Idempotency check: if a run with this idempotency key already exists, return it
148
+ if (options.idempotencyKey) {
149
+ const existing = await this.store.getRunByIdempotencyKey(options.idempotencyKey);
150
+ if (existing) {
151
+ return existing;
152
+ }
153
+ }
154
+ const routing = await this.router.route({
155
+ workspaceRoot: options.workspaceRoot || '',
156
+ request: req,
157
+ taskType: undefined,
158
+ });
159
+ const runId = this.store.generateRunId();
160
+ const stages = [];
161
+ // Stage 1: Analysis & Requirements Formulation
162
+ const analysisAgent = routing.selectedAgents.find((a) => a.agentId === 'planner' || a.agentId === 'research') || routing.selectedAgents[0];
163
+ const stage1Destructive = this.detectDestructiveOperation(req, { taskType: routing.taskType });
164
+ stages.push({
165
+ id: 'stage-1-analysis',
166
+ name: 'Task Decomposition & Architecture Context',
167
+ agentId: analysisAgent?.agentId || 'research',
168
+ skillIds: routing.selectedSkills.map((s) => s.skillId),
169
+ status: 'PENDING',
170
+ dependsOn: [],
171
+ claimedFiles: [],
172
+ inputs: { request: req, taskType: routing.taskType },
173
+ modifiedFiles: [],
174
+ retryCount: 0,
175
+ isDestructive: stage1Destructive.isDestructive,
176
+ requiresApproval: stage1Destructive.isDestructive,
177
+ });
178
+ // Stage 2: Implementation (if not read-only)
179
+ const devAgent = routing.selectedAgents.find((a) => a.agentId === 'developer' || a.agentId === 'database-specialist' || a.agentId === 'debugger');
180
+ if (devAgent) {
181
+ const stage2Destructive = this.detectDestructiveOperation(req, { strategy: routing.strategy });
182
+ stages.push({
183
+ id: 'stage-2-implementation',
184
+ name: `Implementation by ${devAgent.role}`,
185
+ agentId: devAgent.agentId,
186
+ skillIds: routing.selectedSkills.map((s) => s.skillId),
187
+ status: 'PENDING',
188
+ dependsOn: ['stage-1-analysis'],
189
+ claimedFiles: routing.relevantFiles,
190
+ inputs: { strategy: routing.strategy },
191
+ modifiedFiles: [],
192
+ retryCount: 0,
193
+ isDestructive: stage2Destructive.isDestructive,
194
+ requiresApproval: stage2Destructive.isDestructive,
195
+ });
196
+ }
197
+ // Stage 3: Independent Review & Verification
198
+ const reviewerAgent = routing.selectedAgents.find((a) => a.agentId === 'code-reviewer' || a.agentId === 'security-auditor' || a.agentId === 'testing');
199
+ if (reviewerAgent) {
200
+ stages.push({
201
+ id: 'stage-3-verification',
202
+ name: `Independent Verification by ${reviewerAgent.role}`,
203
+ agentId: reviewerAgent.agentId,
204
+ skillIds: ['code-review', 'security-audit'],
205
+ status: 'PENDING',
206
+ dependsOn: devAgent ? ['stage-2-implementation'] : ['stage-1-analysis'],
207
+ claimedFiles: [],
208
+ inputs: { verificationContract: 'standard' },
209
+ modifiedFiles: [],
210
+ retryCount: 0,
211
+ isDestructive: false,
212
+ requiresApproval: false,
213
+ });
214
+ }
215
+ const hasDestructive = stages.some((s) => s.isDestructive);
216
+ const requiresApproval = (routing.requiredApprovals.length > 0 || routing.complexity === 'CRITICAL' || hasDestructive) && !options.autoApprove;
217
+ const initialState = requiresApproval ? 'AWAITING_APPROVAL' : 'READY';
218
+ const now = new Date().toISOString();
219
+ const run = {
220
+ runId,
221
+ taskId: options.taskId,
222
+ idempotencyKey: options.idempotencyKey,
223
+ request: req,
224
+ state: initialState,
225
+ routing,
226
+ stages,
227
+ currentStageIndex: 0,
228
+ checkpoints: [
229
+ {
230
+ at: now,
231
+ state: 'CREATED',
232
+ note: `Plan generated with ${stages.length} stage(s) under strategy ${routing.strategy}.`,
233
+ },
234
+ {
235
+ at: now,
236
+ state: initialState,
237
+ note: requiresApproval ? 'Plan requires developer approval before execution.' : 'Plan validated and ready for execution.',
238
+ },
239
+ ],
240
+ retryCount: 0,
241
+ maxRetries: options.maxRetries ?? 3,
242
+ metrics: {
243
+ durationMs: 0,
244
+ tokensEstimate: routing.estimatedResources.tokensEstimate,
245
+ filesModifiedCount: 0,
246
+ stagesCompleted: 0,
247
+ correctionsCount: 0,
248
+ },
249
+ createdAt: now,
250
+ updatedAt: now,
251
+ isDryRun: options.dryRun,
252
+ };
253
+ await this.store.saveRun(run);
254
+ return run;
255
+ }
256
+ async approve(runId, approvedBy = 'user') {
257
+ const run = await this.store.getRun(runId);
258
+ if (!run) {
259
+ throw new DevWorkspaceError('NOT_FOUND', `Orchestration run "${runId}" not found.`);
260
+ }
261
+ if (run.state !== 'AWAITING_APPROVAL' && run.state !== 'WAITING_APPROVAL') {
262
+ throw new DevWorkspaceError('USAGE', `Run "${runId}" is in state "${run.state}", not AWAITING_APPROVAL.`);
263
+ }
264
+ run.approvedBy = approvedBy;
265
+ run.approvedAt = new Date().toISOString();
266
+ this.transitionState(run, 'READY', `Plan approved by ${approvedBy}. Ready for execution.`);
267
+ await this.store.saveRun(run);
268
+ return run;
269
+ }
270
+ async dryRun(runId) {
271
+ const run = await this.store.getRun(runId);
272
+ if (!run) {
273
+ throw new DevWorkspaceError('NOT_FOUND', `Orchestration run "${runId}" not found.`);
274
+ }
275
+ return {
276
+ runId: run.runId,
277
+ state: run.state,
278
+ request: run.request,
279
+ strategy: run.routing?.strategy ?? 'STANDARD',
280
+ totalStages: run.stages.length,
281
+ requiresApproval: run.state === 'AWAITING_APPROVAL' || run.state === 'WAITING_APPROVAL',
282
+ stages: run.stages.map((s) => ({
283
+ id: s.id,
284
+ name: s.name,
285
+ agentId: s.agentId,
286
+ claimedFiles: s.claimedFiles,
287
+ isDestructive: Boolean(s.isDestructive),
288
+ requiresApproval: Boolean(s.requiresApproval),
289
+ dependsOn: s.dependsOn,
290
+ })),
291
+ estimatedDurationMs: run.metrics.durationMs,
292
+ estimatedTokens: run.metrics.tokensEstimate,
293
+ };
294
+ }
295
+ async run(options) {
296
+ const run = await this.store.getRun(options.runId);
297
+ if (!run) {
298
+ throw new DevWorkspaceError('NOT_FOUND', `Orchestration run "${options.runId}" not found.`);
299
+ }
300
+ // Duplicate execution protection: do not re-run an already completed or running run
301
+ if (run.state === 'COMPLETED' || run.state === 'SUCCEEDED') {
302
+ return run;
303
+ }
304
+ if (run.state === 'RUNNING') {
305
+ throw new DevWorkspaceError('USAGE', `Run "${run.runId}" is already running.`);
306
+ }
307
+ if (run.state === 'CANCELLED' || run.state === 'TIMED_OUT') {
308
+ throw new DevWorkspaceError('USAGE', `Cannot run "${run.runId}" in terminal state "${run.state}".`);
309
+ }
310
+ // Approval gating: check if approval is required
311
+ if (run.state === 'AWAITING_APPROVAL' || run.state === 'WAITING_APPROVAL') {
312
+ if (options.explicitApproval) {
313
+ run.approvedBy = run.approvedBy ?? 'explicit-opt-in';
314
+ run.approvedAt = new Date().toISOString();
315
+ this.transitionState(run, 'READY', 'Execution explicitly approved by developer option.');
316
+ }
317
+ else {
318
+ throw new DevWorkspaceError('USAGE', `Run "${run.runId}" requires developer approval before execution.`);
319
+ }
320
+ }
321
+ if (run.state !== 'READY' && run.state !== 'PAUSED' && run.state !== 'BLOCKED') {
322
+ throw new DevWorkspaceError('USAGE', `Run "${run.runId}" is in state "${run.state}"; only READY, PAUSED or unblocked runs can be executed.`);
323
+ }
324
+ // Certify runtime adapter: placeholder runtimes MUST NEVER return successful execution
325
+ const adapter = options.runtimeAdapter ?? new NativeRuntimeAdapter();
326
+ if (adapter.isPlaceholder) {
327
+ this.transitionState(run, 'FAILED', 'Placeholder runtime cannot return a successful execution.');
328
+ run.error = 'No placeholder runtime can return a successful execution.';
329
+ await this.store.saveRun(run);
330
+ return run;
331
+ }
332
+ const startTs = Date.now();
333
+ const timeoutMs = (options.timeoutSeconds ? options.timeoutSeconds * 1000 : options.timeoutMs) ?? 0;
334
+ this.transitionState(run, 'RUNNING', 'Execution started.');
335
+ await this.store.saveRun(run);
336
+ try {
337
+ for (let i = run.currentStageIndex; i < run.stages.length; i++) {
338
+ const stage = run.stages[i];
339
+ run.currentStageIndex = i;
340
+ // Check cancellation
341
+ if (options.signal?.aborted) {
342
+ this.transitionState(run, 'CANCELLED', 'Run cancelled by user request.', stage.id);
343
+ await this.store.saveRun(run);
344
+ return run;
345
+ }
346
+ // Check timeout
347
+ if (timeoutMs > 0 && Date.now() - startTs > timeoutMs) {
348
+ stage.status = 'TIMED_OUT';
349
+ this.transitionState(run, 'TIMED_OUT', `Execution timed out after ${timeoutMs}ms.`, stage.id);
350
+ this.lockManager.releaseAllForStage(stage.id);
351
+ await this.store.saveRun(run);
352
+ return run;
353
+ }
354
+ // Destructive operations safety gate
355
+ if (stage.isDestructive && !run.approvedBy && !options.explicitApproval) {
356
+ stage.status = 'WAITING_APPROVAL';
357
+ this.transitionState(run, 'WAITING_APPROVAL', `Execution halted: stage "${stage.name}" requires explicit approval for destructive operations.`, stage.id);
358
+ await this.store.saveRun(run);
359
+ return run;
360
+ }
361
+ // Single-writer lock acquisition for claimed files
362
+ if (stage.claimedFiles.length > 0) {
363
+ const lockResult = await this.lockManager.acquire(stage.id, stage.agentId, stage.claimedFiles, 'write');
364
+ if (!lockResult.acquired) {
365
+ stage.status = 'BLOCKED';
366
+ this.transitionState(run, 'BLOCKED', `Execution blocked: file lock conflict on ${lockResult.conflictingFiles?.join(', ')}.`, stage.id);
367
+ await this.store.saveRun(run);
368
+ return run;
369
+ }
370
+ }
371
+ stage.status = 'RUNNING';
372
+ stage.startedAt = new Date().toISOString();
373
+ await this.store.saveRun(run);
374
+ // Execute stage work with runtime adapter
375
+ let stageSuccess = false;
376
+ let lastError;
377
+ let receipt;
378
+ let haltState = null;
379
+ while (!stageSuccess && stage.retryCount <= run.maxRetries) {
380
+ try {
381
+ const execRes = await adapter.execute({
382
+ agentId: stage.agentId,
383
+ role: stage.name,
384
+ prompt: run.request,
385
+ skills: stage.skillIds,
386
+ contextFiles: stage.claimedFiles,
387
+ timeoutMs: timeoutMs > 0 ? Math.max(1000, timeoutMs - (Date.now() - startTs)) : undefined,
388
+ signal: options.signal,
389
+ command: stage.inputs.command,
390
+ cwd: options.workspaceRoot,
391
+ workspaceRoot: options.workspaceRoot,
392
+ explicitApproval: Boolean(run.approvedBy || options.explicitApproval),
393
+ });
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,
411
+ durationMs: execRes.durationMs,
412
+ stdout: execRes.stdout,
413
+ stderr: execRes.stderr,
414
+ timedOut: execRes.timedOut,
415
+ aborted: execRes.aborted,
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);
479
+ stage.status = 'COMPLETED';
480
+ stage.completedAt = new Date().toISOString();
481
+ stage.outputs = { outcome: 'success', verified: true, receipt };
482
+ stage.receipt = receipt;
483
+ run.metrics.stagesCompleted += 1;
484
+ stageSuccess = true;
485
+ }
486
+ catch (err) {
487
+ lastError = err.message;
488
+ if (stage.retryCount < run.maxRetries) {
489
+ stage.retryCount += 1;
490
+ run.metrics.correctionsCount += 1;
491
+ this.transitionState(run, 'CORRECTING', `Retrying stage "${stage.name}" (attempt ${stage.retryCount}/${run.maxRetries}): ${redact(err.message)}`, stage.id);
492
+ await this.store.saveRun(run);
493
+ }
494
+ else {
495
+ break;
496
+ }
497
+ }
498
+ }
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
+ }
508
+ if (timeoutMs > 0 && Date.now() - startTs > timeoutMs) {
509
+ stage.status = 'TIMED_OUT';
510
+ this.transitionState(run, 'TIMED_OUT', `Execution timed out after ${timeoutMs}ms.`, stage.id);
511
+ await this.store.saveRun(run);
512
+ return run;
513
+ }
514
+ if (!stageSuccess) {
515
+ stage.status = 'FAILED';
516
+ stage.error = lastError;
517
+ throw new Error(lastError || `Stage "${stage.name}" failed after ${run.maxRetries} retries.`);
518
+ }
519
+ this.transitionState(run, 'RUNNING', `Stage "${stage.name}" completed and verified successfully.`, stage.id);
520
+ await this.store.saveRun(run);
521
+ }
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.');
532
+ run.metrics.durationMs = Date.now() - startTs;
533
+ await this.store.saveRun(run);
534
+ return run;
535
+ }
536
+ catch (err) {
537
+ this.transitionState(run, 'FAILED', `Execution failed: ${err.message}`);
538
+ run.error = err.message;
539
+ run.metrics.durationMs = Date.now() - startTs;
540
+ await this.store.saveRun(run);
541
+ return run;
542
+ }
543
+ }
544
+ async resume(runId, options) {
545
+ const run = await this.store.getRun(runId);
546
+ if (!run) {
547
+ throw new DevWorkspaceError('NOT_FOUND', `Orchestration run "${runId}" not found.`);
548
+ }
549
+ if (run.state !== 'PAUSED' && run.state !== 'BLOCKED' && run.state !== 'WAITING_APPROVAL' && run.state !== 'AWAITING_APPROVAL') {
550
+ throw new DevWorkspaceError('USAGE', `Run "${runId}" is in state "${run.state}"; only PAUSED, BLOCKED, or approved runs can be resumed.`);
551
+ }
552
+ this.transitionState(run, 'READY', 'Run resumed by developer request.');
553
+ await this.store.saveRun(run);
554
+ return this.run({
555
+ ...options,
556
+ runId,
557
+ });
558
+ }
559
+ async cancel(runId, reason = 'Cancelled by developer') {
560
+ const run = await this.store.getRun(runId);
561
+ if (!run) {
562
+ throw new DevWorkspaceError('NOT_FOUND', `Orchestration run "${runId}" not found.`);
563
+ }
564
+ if (['COMPLETED', 'SUCCEEDED', 'FAILED', 'CANCELLED', 'TIMED_OUT'].includes(run.state)) {
565
+ throw new DevWorkspaceError('USAGE', `Cannot cancel run "${runId}" in terminal state "${run.state}".`);
566
+ }
567
+ // Release any active locks
568
+ for (const stage of run.stages) {
569
+ this.lockManager.releaseAllForStage(stage.id);
570
+ }
571
+ run.error = reason;
572
+ run.cancellationReason = reason;
573
+ this.transitionState(run, 'CANCELLED', reason);
574
+ await this.store.saveRun(run);
575
+ return run;
576
+ }
577
+ }
578
+ //# sourceMappingURL=engine.js.map