@williambeto/ai-workflow 2.2.7 → 2.3.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 (68) hide show
  1. package/AGENTS.md +27 -0
  2. package/CHANGELOG.md +34 -0
  3. package/dist-assets/agents/astra.md +74 -45
  4. package/dist-assets/agents/atlas.md +110 -152
  5. package/dist-assets/agents/nexus.md +64 -19
  6. package/dist-assets/agents/orion.md +72 -27
  7. package/dist-assets/agents/phoenix.md +64 -19
  8. package/dist-assets/agents/sage.md +67 -36
  9. package/dist-assets/commands/atlas.md +66 -6
  10. package/dist-assets/commands/audit.md +62 -4
  11. package/dist-assets/commands/deploy.md +66 -5
  12. package/dist-assets/commands/discover.md +72 -4
  13. package/dist-assets/commands/implement.md +66 -18
  14. package/dist-assets/commands/optimize-tokens.md +60 -4
  15. package/dist-assets/commands/plan.md +64 -4
  16. package/dist-assets/commands/release.md +76 -5
  17. package/dist-assets/commands/run.md +62 -16
  18. package/dist-assets/commands/spec-create.md +66 -4
  19. package/dist-assets/commands/spec-implement.md +68 -4
  20. package/dist-assets/commands/spec-review.md +63 -4
  21. package/dist-assets/commands/update-memory.md +62 -4
  22. package/dist-assets/commands/validate.md +70 -6
  23. package/dist-assets/docs/cli-reference.md +38 -10
  24. package/dist-assets/skills/architecture/SKILL.md +62 -7
  25. package/dist-assets/skills/backend-development/SKILL.md +62 -7
  26. package/dist-assets/skills/deployment/SKILL.md +62 -7
  27. package/dist-assets/skills/design-principles/SKILL.md +59 -7
  28. package/dist-assets/skills/documentation/SKILL.md +61 -7
  29. package/dist-assets/skills/frontend-development/SKILL.md +62 -7
  30. package/dist-assets/skills/full-stack-development/SKILL.md +62 -7
  31. package/dist-assets/skills/optimize-tokens/SKILL.md +61 -7
  32. package/dist-assets/skills/pr-workflow/SKILL.md +65 -7
  33. package/dist-assets/skills/product-discovery/SKILL.md +81 -7
  34. package/dist-assets/skills/product-planning/SKILL.md +62 -7
  35. package/dist-assets/skills/project-memory/SKILL.md +55 -22
  36. package/dist-assets/skills/prompt-engineer/SKILL.md +59 -7
  37. package/dist-assets/skills/qa-workflow/SKILL.md +72 -7
  38. package/dist-assets/skills/refactoring/SKILL.md +68 -7
  39. package/dist-assets/skills/release-workflow/SKILL.md +72 -7
  40. package/dist-assets/skills/spec-driven-development/SKILL.md +75 -7
  41. package/dist-assets/skills/technical-leadership/SKILL.md +61 -7
  42. package/dist-assets/skills/ui-ux-design/SKILL.md +60 -7
  43. package/docs/compatibility/provider-usage.md +46 -0
  44. package/docs/compatibility/runtime-matrix.md +31 -0
  45. package/docs/getting-started/DESKTOP_PROMPT.md +52 -0
  46. package/docs/getting-started/quickstart.md +17 -0
  47. package/docs/getting-started/upgrading-to-v2.md +55 -0
  48. package/package.json +20 -4
  49. package/read_only_safety_verification.md +48 -0
  50. package/src/cli.js +4 -2
  51. package/src/commands/collect-evidence.js +3 -39
  52. package/src/commands/doctor.js +16 -0
  53. package/src/commands/execute.js +312 -119
  54. package/src/core/delegation-controller.js +193 -0
  55. package/src/core/evidence/evidence-ledger.js +53 -0
  56. package/src/core/execution-planner.js +4 -1
  57. package/src/core/finalization/finalizer.js +77 -0
  58. package/src/core/finalization/workspace-snapshot.js +110 -0
  59. package/src/core/gates/branch-gate.js +23 -35
  60. package/src/core/healing/healer-engine.js +34 -1
  61. package/src/core/healing/runtime-remediation-executor.js +136 -0
  62. package/src/core/request-classifier.js +15 -5
  63. package/src/core/request-router.js +289 -0
  64. package/src/core/runtime/opencode-adapter.js +170 -62
  65. package/src/core/validation/evidence-collector.js +26 -3
  66. package/src/core/validation/stack-detector.js +65 -0
  67. package/src/core/validation/validation-planner.js +134 -0
  68. package/src/core/workspace/read-only-workspace.js +119 -0
@@ -2,15 +2,89 @@ import { RequestClassifier } from "../core/request-classifier.js";
2
2
  import { ExecutionPlanner } from "../core/execution-planner.js";
3
3
  import { WorkflowStateMachine } from "../core/workflow-state-machine.js";
4
4
  import { BranchGate } from "../core/gates/branch-gate.js";
5
+ import { EvidenceLedger } from "../core/evidence/evidence-ledger.js";
6
+ import { DelegationController } from "../core/delegation-controller.js";
5
7
  import { OpenCodeAdapter } from "../core/runtime/opencode-adapter.js";
6
8
  import { runCollectEvidence } from "./collect-evidence.js";
7
9
  import { QualityGuard } from "../core/validation/quality-guard.js";
8
10
  import { HandoffEngine } from "../core/handoff/handoff-engine.js";
9
11
  import { HealerEngine } from "../core/healing/healer-engine.js";
10
- import { createCliRemediationExecutor } from "../core/healing/cli-remediation-executor.js";
12
+ import { createRuntimeRemediationExecutor } from "../core/healing/runtime-remediation-executor.js";
11
13
  import { isRecoverableGateFailure, isTerminalFailure } from "../core/statuses.js";
14
+ import { Finalizer } from "../core/finalization/finalizer.js";
12
15
  import fs from "node:fs/promises";
13
16
  import path from "node:path";
17
+ import { execSync } from "node:child_process";
18
+
19
+ async function captureReadOnlyState(cwd) {
20
+ const finalizer = new Finalizer({ cwd });
21
+ const snapshot = await finalizer.snapshotManager.capture();
22
+
23
+ const execGit = (args) => {
24
+ try {
25
+ return execSync(`git ${args}`, { cwd, encoding: "utf8", stdio: "pipe" }).trim();
26
+ } catch {
27
+ return "";
28
+ }
29
+ };
30
+
31
+ const head = execGit("rev-parse HEAD");
32
+ const branch = execGit("rev-parse --abbrev-ref HEAD");
33
+ const indexTree = execGit("write-tree");
34
+ const porcelainStatus = execGit("status --porcelain");
35
+
36
+ return {
37
+ snapshot,
38
+ head,
39
+ branch,
40
+ indexTree,
41
+ porcelainStatus
42
+ };
43
+ }
44
+
45
+ function compareReadOnlyState(before, after) {
46
+ const violations = [];
47
+
48
+ // 1. Compare branch
49
+ if (before.branch !== after.branch) {
50
+ violations.push(`Branch changed from '${before.branch}' to '${after.branch}'`);
51
+ }
52
+
53
+ // 2. Compare HEAD
54
+ if (before.head !== after.head) {
55
+ violations.push(`Git HEAD changed from '${before.head}' to '${after.head}' (commit or reset made inside read-only task)`);
56
+ }
57
+
58
+ // 3. Compare index tree
59
+ if (before.indexTree !== after.indexTree) {
60
+ violations.push(`Git index tree changed from '${before.indexTree}' to '${after.indexTree}'`);
61
+ }
62
+
63
+ // 4. Compare porcelain status
64
+ if (before.porcelainStatus !== after.porcelainStatus) {
65
+ violations.push(`Git status changed. Before:\n${before.porcelainStatus}\nAfter:\n${after.porcelainStatus}`);
66
+ }
67
+
68
+ // 5. Compare workspace files (SHA-256 hashes)
69
+ const beforeFiles = before.snapshot.files || {};
70
+ const afterFiles = after.snapshot.files || {};
71
+
72
+ for (const [file, info] of Object.entries(afterFiles)) {
73
+ const prevInfo = beforeFiles[file];
74
+ if (!prevInfo) {
75
+ violations.push(`File added: ${file}`);
76
+ } else if (prevInfo.sha256 !== info.sha256) {
77
+ violations.push(`File content modified: ${file}`);
78
+ }
79
+ }
80
+ for (const file of Object.keys(beforeFiles)) {
81
+ if (!afterFiles[file]) {
82
+ violations.push(`File deleted: ${file}`);
83
+ }
84
+ }
85
+
86
+ return violations;
87
+ }
14
88
 
15
89
  function slugify(text) {
16
90
  return text
@@ -34,7 +108,7 @@ function combineValidation(evidence, quality) {
34
108
  /**
35
109
  * runExecute - Coordinators natural request execution.
36
110
  */
37
- export async function runExecute({ cwd, naturalRequest, override, taskSlug: taskSlugOverride }) {
111
+ export async function runExecute({ cwd, naturalRequest, taskSlug: taskSlugOverride }) {
38
112
  if (!naturalRequest || !naturalRequest.trim()) {
39
113
  throw new Error("Missing request. Please provide a natural request string via positional arguments or --request flag.");
40
114
  }
@@ -42,131 +116,250 @@ export async function runExecute({ cwd, naturalRequest, override, taskSlug: task
42
116
  const taskSlug = taskSlugOverride || slugify(naturalRequest);
43
117
  console.log(`\n[AI WORKFLOW] Executing natural request intake [slug: ${taskSlug}]...\n`);
44
118
 
45
- const stateMachine = new WorkflowStateMachine();
46
-
47
- // 1. Classification
48
- const classifier = new RequestClassifier();
49
- const classification = classifier.classify(naturalRequest);
50
- console.log(`[CLASSIFIED] Intent: ${classification.intent}, Mode: ${classification.mode}, Profile: ${classification.profile}`);
51
- stateMachine.transitionTo("CLASSIFIED");
52
-
53
- // 2. Planning
54
- const planner = new ExecutionPlanner({ cwd });
55
- const plan = planner.plan(classification, taskSlug);
56
- console.log(`[PLANNED] Owner: ${plan.owner}, Remediation limit: ${plan.remediationLimit}`);
57
- stateMachine.transitionTo("PLANNED");
58
-
59
- // 3. Branch Gate
60
- const branchGate = new BranchGate({ memoryDir: path.join(cwd, ".ai-workflow"), cwd });
61
- const gateResult = branchGate.check(override, {
62
- autoRecover: true,
63
- taskSlug,
64
- readOnly: !plan.branchNeeded
65
- });
66
-
67
- if (gateResult.blocked) {
68
- stateMachine.transitionTo("BLOCKED");
69
- throw new Error(`[GATE BLOCKED] ${gateResult.reason}`);
70
- }
71
- console.log(`[PASS] Branch Gate: ${gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : `${gateResult.branch} is authorized`}.`);
72
- stateMachine.transitionTo("BRANCH_READY");
73
-
74
- // 4. Spec template creation (for full/deep mode)
75
- if (plan.specPath) {
76
- const fullSpecPath = path.join(cwd, plan.specPath);
77
- const specExists = await fs.access(fullSpecPath).then(() => true).catch(() => false);
78
- if (!specExists) {
79
- await fs.mkdir(path.dirname(fullSpecPath), { recursive: true });
80
- const specTemplatePath = path.join(cwd, ".ai-workflow/templates/specs/standard.md");
81
- const templateContent = await fs.readFile(specTemplatePath, "utf8").catch(() => {
82
- return `# [STANDARD] Specification: ${classification.request}\n\n## Metadata\n\n- ID: SPEC-${taskSlug}\n- Author: Spec-Engineer\n- Status: DRAFT\n- Date: ${new Date().toISOString().split("T")[0]}\n\n## Functional Requirements\n\n- ${classification.request}\n\n## Technical Implementation Plan\n\n### Files to Create/Modify\n\n- \`src/index.js\`\n\n## Acceptance Criteria\n\n- [ ] Implemented successfully\n\n## Testing Strategy\n\n- [ ] Behavior tests pass`;
83
- });
84
- await fs.writeFile(fullSpecPath, templateContent);
85
- console.log(`[EXECUTE] Created DRAFT specification template at: ${plan.specPath}`);
86
- }
87
- }
119
+ const ledger = new EvidenceLedger({ cwd, workflowId: taskSlug });
120
+ const delegationController = new DelegationController({ cwd, ledger, adapter: new OpenCodeAdapter({ cwd }) });
88
121
 
89
- // 5. Delegation
90
- stateMachine.transitionTo("DELEGATED");
91
- stateMachine.transitionTo("IMPLEMENTING");
122
+ let plan = null;
123
+ try {
124
+ const stateMachine = new WorkflowStateMachine();
92
125
 
93
- const adapter = new OpenCodeAdapter({ cwd });
94
- let promptMsg = classification.request;
95
- if (plan.specPath) {
96
- promptMsg = `Please review and fill in the specification file at: ${plan.specPath}. Make sure to change the Status field to 'APPROVED' in the Metadata section, and then implement the behavior described.`;
97
- }
126
+ // 1. Classification
127
+ const classifier = new RequestClassifier();
128
+ const classification = classifier.classify(naturalRequest, { cwd });
129
+ console.log(`[CLASSIFIED] Intent: ${classification.intent}, Mode: ${classification.mode}, Profile: ${classification.profile}`);
130
+ stateMachine.transitionTo("CLASSIFIED");
98
131
 
99
- const runResult = await adapter.execute(promptMsg, {
100
- agent: plan.owner,
101
- dangerouslySkipPermissions: true
102
- });
132
+ await delegationController.route(naturalRequest, classification);
103
133
 
104
- if (!runResult.success) {
105
- console.error(`[EXECUTE] OpenCode adapter execution reported failure.`);
106
- }
107
- stateMachine.transitionTo("IMPLEMENTED");
108
-
109
- // 6. Validation
110
- stateMachine.transitionTo("VALIDATING");
111
- const validateWorkflow = async () => {
112
- const evidence = await runCollectEvidence({
113
- cwd,
114
- exitOnError: false,
134
+ const routingDecision = classification.routingDecision || {};
135
+ if (routingDecision.permissionDecision === "blocked") {
136
+ stateMachine.transitionTo("BLOCKED");
137
+ throw new Error(`[ROUTE BLOCKED] ${routingDecision.reason}`);
138
+ }
139
+ if (routingDecision.permissionDecision === "rerouted") {
140
+ console.log(`[REROUTED] ${routingDecision.reason}`);
141
+ }
142
+
143
+ // 2. Planning
144
+ const planner = new ExecutionPlanner({ cwd });
145
+ plan = planner.plan(classification, taskSlug);
146
+ console.log(`[PLANNED] Owner: ${plan.owner}, Remediation limit: ${plan.remediationLimit}`);
147
+ stateMachine.transitionTo("PLANNED");
148
+
149
+ // 3. Branch Gate
150
+ const branchGate = new BranchGate({ memoryDir: path.join(cwd, ".ai-workflow"), cwd });
151
+ const gateResult = branchGate.check(undefined, {
152
+ autoRecover: true,
115
153
  taskSlug,
116
- mode: plan.mode,
117
- profile: plan.profile,
118
- branchRecovery: gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : "NOT_REQUIRED"
154
+ readOnly: !plan.branchNeeded
119
155
  });
120
- const quality = await new QualityGuard({ cwd, taskSlug, mode: plan.mode }).verify();
121
- return combineValidation(evidence, quality);
122
- };
123
156
 
124
- let result = await validateWorkflow();
125
-
126
- // 7. Bounded Remediation
127
- if (isRecoverableGateFailure(result.overallStatus)) {
128
- stateMachine.transitionTo("REMEDIATING");
129
- console.log(`\n[REMEDIATION REQUIRED] ${result.overallStatus}. Starting bounded ${plan.mode} remediation.`);
130
- const executor = createCliRemediationExecutor(cwd);
131
- const healer = new HealerEngine({ cwd, mode: plan.mode, taskSlug });
132
-
133
- result = await healer.run({
134
- initialResult: result,
135
- validate: async () => {
136
- stateMachine.transitionTo("REVALIDATING");
137
- const res = await validateWorkflow();
138
- return res;
139
- },
140
- remediate: executor
157
+ if (gateResult.blocked) {
158
+ stateMachine.transitionTo("BLOCKED");
159
+ throw new Error(`[GATE BLOCKED] ${gateResult.reason}`);
160
+ }
161
+ console.log(`[PASS] Branch Gate: ${gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : `${gateResult.branch} is authorized`}.`);
162
+ stateMachine.transitionTo("BRANCH_READY");
163
+
164
+ const checkBranchSafety = () => {
165
+ if (plan.branchNeeded) {
166
+ const currentBranch = branchGate.getCurrentBranch();
167
+ if (branchGate.protectedBranches.includes(currentBranch)) {
168
+ stateMachine.transitionTo("BLOCKED");
169
+ throw new Error(`[WORKFLOW BLOCKED] Security violation: current branch is protected '${currentBranch}'!`);
170
+ }
171
+ }
172
+ };
173
+
174
+ // 4. Spec template creation (for full/deep mode)
175
+ if (plan.specPath) {
176
+ const fullSpecPath = path.join(cwd, plan.specPath);
177
+ const specExists = await fs.access(fullSpecPath).then(() => true).catch(() => false);
178
+ if (!specExists) {
179
+ await fs.mkdir(path.dirname(fullSpecPath), { recursive: true });
180
+ const specTemplatePath = path.join(cwd, ".ai-workflow/templates/specs/standard.md");
181
+ const templateContent = await fs.readFile(specTemplatePath, "utf8").catch(() => {
182
+ return `# [STANDARD] Specification: ${classification.request}\n\n## Metadata\n\n- ID: SPEC-${taskSlug}\n- Author: Spec-Engineer\n- Status: DRAFT\n- Date: ${new Date().toISOString().split("T")[0]}\n\n## Functional Requirements\n\n- ${classification.request}\n\n## Technical Implementation Plan\n\n### Files to Create/Modify\n\n- \`src/index.js\`\n\n## Acceptance Criteria\n\n- [ ] Implemented successfully\n\n## Testing Strategy\n\n- [ ] Behavior tests pass`;
183
+ });
184
+ await fs.writeFile(fullSpecPath, templateContent);
185
+ console.log(`[EXECUTE] Created DRAFT specification template at: ${plan.specPath}`);
186
+ }
187
+ }
188
+
189
+ // 5. Delegation
190
+ stateMachine.transitionTo("DELEGATED");
191
+ stateMachine.transitionTo("IMPLEMENTING");
192
+
193
+ let promptMsg = classification.request;
194
+ if (plan.specPath) {
195
+ promptMsg = `Please review and fill in the specification file at: ${plan.specPath}. Make sure to change the Status field to 'APPROVED' in the Metadata section, and then implement the behavior described.`;
196
+ }
197
+
198
+ let readOnlyStateBefore = null;
199
+ if (!plan.branchNeeded) {
200
+ readOnlyStateBefore = await captureReadOnlyState(cwd);
201
+ }
202
+
203
+ const runResult = await delegationController.implement(promptMsg, plan.owner, { readOnly: !plan.branchNeeded });
204
+
205
+ if (!runResult.success) {
206
+ console.error(`[EXECUTE] OpenCode adapter execution reported failure: ${runResult.error || "Unknown error"}`);
207
+ stateMachine.transitionTo("BLOCKED");
208
+ throw new Error(`[WORKFLOW BLOCKED] OpenCode runtime execution failed: ${runResult.error || "Unknown error"}`);
209
+ }
210
+
211
+ if (!plan.branchNeeded) {
212
+ const readOnlyStateAfter = await captureReadOnlyState(cwd);
213
+ const violations = compareReadOnlyState(readOnlyStateBefore, readOnlyStateAfter);
214
+ if (violations.length > 0) {
215
+ console.error(`[EXECUTE] Read-only confinement violation detected:`);
216
+ for (const v of violations) {
217
+ console.error(` - ${v}`);
218
+ }
219
+ stateMachine.transitionTo("BLOCKED");
220
+ throw new Error(`[WORKFLOW BLOCKED] Read-only confinement violation: files were written/modified, index or commits modified: \n${violations.join("\n")}`);
221
+ }
222
+
223
+ stateMachine.transitionTo("IMPLEMENTED");
224
+ stateMachine.transitionTo("VALIDATING");
225
+ stateMachine.transitionTo("COMPLETED");
226
+
227
+ console.log("\n--- Final Handoff ---");
228
+ console.log(`\n[AI WORKFLOW COMPLETE] COMPLETED`);
229
+ console.log(`Handoff Packet: [IN-MEMORY] (No handoff file written in read-only mode)\n`);
230
+
231
+ return {
232
+ overallStatus: "PASS",
233
+ evidence: {
234
+ internalStatus: "PASS",
235
+ commandsRun: []
236
+ },
237
+ quality: {
238
+ overallStatus: "PASS"
239
+ },
240
+ stateHistory: stateMachine.getHistory()
241
+ };
242
+ }
243
+
244
+ stateMachine.transitionTo("IMPLEMENTED");
245
+ checkBranchSafety();
246
+
247
+ // Capture snapshot immediately after last implementation write
248
+ const finalizer = new Finalizer({ cwd });
249
+ let lastWriteSnapshot = await finalizer.snapshotManager.capture();
250
+
251
+ // 6. Validation
252
+ stateMachine.transitionTo("VALIDATING");
253
+ const validateWorkflow = async () => {
254
+ const evidence = await runCollectEvidence({
255
+ cwd,
256
+ exitOnError: false,
257
+ taskSlug,
258
+ mode: plan.mode,
259
+ profile: plan.profile,
260
+ branchRecovery: gateResult.recovered ? `${gateResult.branchBefore} -> ${gateResult.branch}` : "NOT_REQUIRED"
261
+ });
262
+ const quality = await new QualityGuard({ cwd, taskSlug, mode: plan.mode }).verify();
263
+ return combineValidation(evidence, quality);
264
+ };
265
+
266
+ let result = await delegationController.validate(taskSlug, plan.mode, plan.profile, validateWorkflow);
267
+
268
+ // 7. Bounded Remediation
269
+ if (isRecoverableGateFailure(result.overallStatus)) {
270
+ console.log(`\n[REMEDIATION REQUIRED] ${result.overallStatus}. Starting bounded ${plan.mode} remediation.`);
271
+ const executor = createRuntimeRemediationExecutor(cwd, ledger);
272
+ const healer = new HealerEngine({ cwd, mode: plan.mode, taskSlug, ledger });
273
+
274
+ result = await healer.run({
275
+ initialResult: result,
276
+ validate: async () => {
277
+ stateMachine.transitionTo("REVALIDATING");
278
+ const res = await delegationController.validate(taskSlug, plan.mode, plan.profile, validateWorkflow);
279
+ return res;
280
+ },
281
+ remediate: async (remedCtx) => {
282
+ stateMachine.transitionTo("REMEDIATING");
283
+ const remRes = await executor(remedCtx);
284
+ if (remRes.applied) {
285
+ checkBranchSafety();
286
+ // Update snapshot because remediation wrote new changes
287
+ lastWriteSnapshot = await finalizer.snapshotManager.capture();
288
+ }
289
+ return remRes;
290
+ }
291
+ });
292
+ }
293
+
294
+ if (isTerminalFailure(result.overallStatus)) {
295
+ stateMachine.transitionTo("BLOCKED");
296
+ throw new Error(`[WORKFLOW BLOCKED] ${result.overallStatus}: Validation could not be resolved safely.`);
297
+ }
298
+
299
+ checkBranchSafety();
300
+
301
+ // 8. Finalizer / Stabilization Loop
302
+ let integrity = await finalizer.verifyIntegrity(lastWriteSnapshot);
303
+ let revalidationCount = 0;
304
+ const maxRevalidations = 2;
305
+
306
+ while (!integrity.valid && revalidationCount < maxRevalidations) {
307
+ console.log(`\n[FINALIZER WARNING] Workspace mutated during validation! Re-running validation to stabilize.`);
308
+ console.log(`Changes detected:`, integrity.changes);
309
+
310
+ checkBranchSafety();
311
+
312
+ // Update snapshot to current workspace state before validation runs
313
+ lastWriteSnapshot = await finalizer.snapshotManager.capture();
314
+ revalidationCount++;
315
+
316
+ // Re-run validation
317
+ result = await delegationController.validate(taskSlug, plan.mode, plan.profile, validateWorkflow);
318
+
319
+ checkBranchSafety();
320
+
321
+ // Verify integrity against the snapshot taken before this validation iteration
322
+ integrity = await finalizer.verifyIntegrity(lastWriteSnapshot);
323
+ }
324
+
325
+ let finalStatus = result.overallStatus;
326
+ if (!integrity.valid) {
327
+ console.log(`\n[FINALIZER BLOCKED] BLOCKED: workspace did not stabilize`);
328
+ console.log(`Final changes detected:`, integrity.changes);
329
+ finalStatus = "FAIL_QUALITY_GATE";
330
+ }
331
+
332
+ const finalState = finalStatus === "PASS"
333
+ ? "COMPLETED"
334
+ : finalStatus === "PASS_WITH_NOTES"
335
+ ? "COMPLETED_WITH_NOTES"
336
+ : "BLOCKED";
337
+
338
+ stateMachine.transitionTo(finalState);
339
+
340
+ console.log("\n--- Final Handoff ---");
341
+ const handoffEngine = new HandoffEngine({ cwd });
342
+ const handoffPath = await handoffEngine.generate({
343
+ taskId: taskSlug,
344
+ status: finalState,
345
+ specPaths: plan.specPath ? [plan.specPath] : [],
346
+ evidence: result.evidence,
347
+ nextActions: `Profile ${plan.profile}. Observed execution completed with status ${finalState}.`
141
348
  });
142
- }
143
349
 
144
- if (isTerminalFailure(result.overallStatus)) {
145
- stateMachine.transitionTo("BLOCKED");
146
- throw new Error(`[WORKFLOW BLOCKED] ${result.overallStatus}: Validation could not be resolved safely.`);
147
- }
350
+ console.log(`\n[AI WORKFLOW COMPLETE] ${finalState}`);
351
+ console.log(`Handoff Packet: ${path.relative(cwd, handoffPath)}\n`);
148
352
 
149
- // 8. Finalizer
150
- const finalState = result.overallStatus === "PASS"
151
- ? "COMPLETED"
152
- : result.overallStatus === "PASS_WITH_NOTES"
153
- ? "COMPLETED_WITH_NOTES"
154
- : "BLOCKED";
155
-
156
- stateMachine.transitionTo(finalState);
157
-
158
- console.log("\n--- Final Handoff ---");
159
- const handoffEngine = new HandoffEngine({ cwd });
160
- const handoffPath = await handoffEngine.generate({
161
- taskId: taskSlug,
162
- status: finalState,
163
- specPaths: plan.specPath ? [plan.specPath] : [],
164
- evidence: result.evidence,
165
- nextActions: `Profile ${plan.profile}. Observed execution completed with status ${finalState}.`
166
- });
167
-
168
- console.log(`\n[AI WORKFLOW COMPLETE] ${finalState}`);
169
- console.log(`Handoff Packet: ${path.relative(cwd, handoffPath)}\n`);
170
-
171
- return { ...result, stateHistory: stateMachine.getHistory() };
353
+ return { ...result, overallStatus: finalStatus, stateHistory: stateMachine.getHistory() };
354
+ } finally {
355
+ if (typeof plan !== "undefined" && plan && !plan.branchNeeded) {
356
+ console.log(`\n[READ-ONLY LEDGER] (In-Memory/Stdout)\n${JSON.stringify(ledger.getEvents(), null, 2)}\n`);
357
+ } else {
358
+ try {
359
+ await ledger.save(`.ai-workflow/history/${taskSlug}-ledger.json`);
360
+ } catch (err) {
361
+ // ignore or log
362
+ }
363
+ }
364
+ }
172
365
  }
@@ -0,0 +1,193 @@
1
+ import { OpenCodeAdapter } from "./runtime/opencode-adapter.js";
2
+
3
+ /**
4
+ * DelegationController - Manages and logs coordination between Atlas, Astra, Sage, and Phoenix.
5
+ */
6
+ export class DelegationController {
7
+ constructor({ cwd = process.cwd(), ledger, adapter } = {}) {
8
+ this.cwd = cwd;
9
+ this.ledger = ledger;
10
+ this.adapter = adapter || new OpenCodeAdapter({ cwd });
11
+ }
12
+
13
+ /**
14
+ * Logs routing decision by Atlas.
15
+ */
16
+ async route(naturalRequest, classification) {
17
+ const decision = classification.routingDecision || {};
18
+ this.lastRoutingDecision = decision;
19
+
20
+ if (this.ledger) {
21
+ this.ledger.logEvent({
22
+ actor: "Atlas",
23
+ actorType: "control-plane",
24
+ observed: true,
25
+ eventType: "routing",
26
+ provenance: "request-classifier",
27
+ data: {
28
+ request: naturalRequest,
29
+ requestedActor: decision.requestedActor || null,
30
+ selectedActor: decision.selectedActor || null,
31
+ operationType: decision.operationType || null,
32
+ mutationIntent: decision.mutationIntent || null,
33
+ permissionDecision: decision.permissionDecision || null,
34
+ reason: decision.reason || null,
35
+ workflowPath: decision.workflowPath || [],
36
+ classification,
37
+ event: "routing.completed",
38
+ runtimeAgentRequested: null,
39
+ runtimeAgentApplied: null,
40
+ runtimeAgentSupported: false,
41
+ status: decision.permissionDecision === "blocked" ? "BLOCKED" : "COMPLETED"
42
+ }
43
+ });
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Logs and executes the implementation process by Astra.
49
+ */
50
+ async implement(promptMsg, owner, options = {}) {
51
+ const decision = this.lastRoutingDecision || {};
52
+ const inspection = await this.adapter.inspect();
53
+ const isSpecialized = ["Nexus", "Orion", "Astra", "Sage", "Phoenix"].includes(owner);
54
+ const supportsAgent = inspection.supports?.agent;
55
+ const canApply = !isSpecialized || supportsAgent;
56
+
57
+ if (this.ledger) {
58
+ this.ledger.logEvent({
59
+ actor: canApply ? owner : "Atlas",
60
+ actorType: canApply ? "runtime-agent" : "control-plane",
61
+ observed: true,
62
+ runtime: "opencode",
63
+ eventType: "implementation_start",
64
+ provenance: "opencode-adapter",
65
+ data: {
66
+ agent: owner,
67
+ prompt: promptMsg,
68
+ event: "implementation.started",
69
+ requestedActor: decision.requestedActor || null,
70
+ selectedActor: decision.selectedActor || null,
71
+ runtimeAgentRequested: owner,
72
+ runtimeAgentApplied: null,
73
+ runtimeAgentSupported: supportsAgent || false,
74
+ permissionDecision: decision.permissionDecision || null,
75
+ reason: decision.reason || null,
76
+ status: "started"
77
+ }
78
+ });
79
+ }
80
+
81
+ const runResult = await this.adapter.execute(promptMsg, { agent: owner, ...options });
82
+
83
+ if (this.ledger) {
84
+ const isApplied = runResult.runtimeAgentApplied === owner;
85
+ this.ledger.logEvent({
86
+ actor: isApplied ? owner : "Atlas",
87
+ actorType: isApplied ? "runtime-agent" : "control-plane",
88
+ observed: true,
89
+ runtime: "opencode",
90
+ eventType: "implementation_complete",
91
+ provenance: "opencode-adapter",
92
+ data: {
93
+ success: runResult.success,
94
+ commandsRun: runResult.commandsRun || [],
95
+ eventCount: runResult.eventCount || 0,
96
+ error: runResult.error,
97
+ event: "implementation.completed",
98
+ requestedActor: decision.requestedActor || null,
99
+ selectedActor: decision.selectedActor || null,
100
+ runtimeAgentRequested: runResult.runtimeAgentRequested || owner || null,
101
+ runtimeAgentApplied: runResult.runtimeAgentApplied || null,
102
+ runtimeAgentSupported: runResult.runtimeAgentSupported !== undefined ? runResult.runtimeAgentSupported : (supportsAgent || false),
103
+ permissionDecision: decision.permissionDecision || null,
104
+ reason: runResult.error || decision.reason || null,
105
+ status: runResult.status || (runResult.success ? "COMPLETED" : "FAILED")
106
+ }
107
+ });
108
+ }
109
+
110
+ return runResult;
111
+ }
112
+
113
+ /**
114
+ * Runs validation locally without logging Sage since no validation agent runtime was executed.
115
+ */
116
+ async validate(taskSlug, mode, profile, verifyFn) {
117
+ const result = await verifyFn();
118
+
119
+ if (mode === "full") {
120
+ const decision = this.lastRoutingDecision || {};
121
+ const inspection = await this.adapter.inspect();
122
+ const supportsAgent = inspection.supports?.agent;
123
+ const canApply = supportsAgent;
124
+
125
+ if (this.ledger) {
126
+ this.ledger.logEvent({
127
+ actor: canApply ? "Sage" : "Atlas",
128
+ actorType: canApply ? "auditor" : "control-plane",
129
+ observed: true,
130
+ runtime: "opencode",
131
+ eventType: "validation_start",
132
+ provenance: "opencode-adapter",
133
+ data: {
134
+ agent: "Sage",
135
+ event: "validation.started",
136
+ requestedActor: decision.requestedActor || null,
137
+ selectedActor: decision.selectedActor || null,
138
+ runtimeAgentRequested: "Sage",
139
+ runtimeAgentApplied: null,
140
+ runtimeAgentSupported: supportsAgent || false,
141
+ permissionDecision: decision.permissionDecision || null,
142
+ reason: decision.reason || null,
143
+ status: "started"
144
+ }
145
+ });
146
+ }
147
+
148
+ let gitDiff = "";
149
+ try {
150
+ const { execSync } = await import("node:child_process");
151
+ gitDiff = execSync("git diff HEAD", { cwd: this.cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
152
+ } catch {
153
+ // ignore
154
+ }
155
+
156
+ const prompt = `Please validate the implementation. Diff:\n${gitDiff}\nLocal Evidence:\n${JSON.stringify(result, null, 2)}`;
157
+ const runResult = await this.adapter.execute(prompt, { agent: "Sage" });
158
+
159
+ if (this.ledger) {
160
+ const isApplied = runResult.runtimeAgentApplied === "Sage";
161
+ this.ledger.logEvent({
162
+ actor: isApplied ? "Sage" : "Atlas",
163
+ actorType: isApplied ? "auditor" : "control-plane",
164
+ observed: true,
165
+ runtime: "opencode",
166
+ eventType: "validation_complete",
167
+ provenance: "opencode-adapter",
168
+ data: {
169
+ success: runResult.success,
170
+ commandsRun: runResult.commandsRun || [],
171
+ eventCount: runResult.eventCount || 0,
172
+ error: runResult.error,
173
+ event: "validation.completed",
174
+ requestedActor: decision.requestedActor || null,
175
+ selectedActor: decision.selectedActor || null,
176
+ runtimeAgentRequested: runResult.runtimeAgentRequested || "Sage",
177
+ runtimeAgentApplied: runResult.runtimeAgentApplied || null,
178
+ runtimeAgentSupported: runResult.runtimeAgentSupported !== undefined ? runResult.runtimeAgentSupported : (supportsAgent || false),
179
+ permissionDecision: decision.permissionDecision || null,
180
+ reason: runResult.error || decision.reason || null,
181
+ status: runResult.status || (runResult.success ? "COMPLETED" : "FAILED")
182
+ }
183
+ });
184
+ }
185
+
186
+ if (!runResult.success) {
187
+ result.overallStatus = "FAIL_QUALITY_GATE";
188
+ }
189
+ }
190
+
191
+ return result;
192
+ }
193
+ }