Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/api/src/controllers/jobs.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export function listJobsController(_req: Request, res: Response): void {
completedAt: job.completedAt,
agentsCompleted: job.agentsCompleted,
error: job.error,
currentStage: job.currentStage,
failure: job.failure,
tokenUsage: summarizeJobTokenUsage(job),
}));

Expand Down Expand Up @@ -47,6 +49,8 @@ export function getJobController(req: Request, res: Response, next: NextFunction
completedAt: job.completedAt,
agentsCompleted: job.agentsCompleted,
error: job.error,
currentStage: job.currentStage,
failure: job.failure,
blueprint: job.blueprint,
tokenUsage: summarizeJobTokenUsage(job),
});
Expand Down
16 changes: 13 additions & 3 deletions apps/api/src/services/generate.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
runOrchestrator,
AGENT_CONFIGS,
selectWorkflow,
StepExecutionError,
type LLMProvider,
} from "@stackforge/agents";
import {
Expand Down Expand Up @@ -300,6 +301,7 @@ function buildEmitter(

if (event.type === "agent_started") {
const startedAgent = event.agent as AgentName;
updateJob(jobId, { currentStage: startedAgent });
const provider = event.agent === "codegen"
? (codegenProviderName ?? baseProviderName)
: baseProviderName;
Expand Down Expand Up @@ -366,7 +368,7 @@ async function startOrchestration(
});

const now = new Date().toISOString();
updateJob(jobId, { status: JOB_STATUS.COMPLETED, blueprint, completedAt: now });
updateJob(jobId, { status: JOB_STATUS.COMPLETED, blueprint, completedAt: now, currentStage: undefined });

emit({
type: "job_completed",
Expand All @@ -376,14 +378,22 @@ async function startOrchestration(
});
} catch (err) {
const error = err instanceof Error ? err.message : String(err);
const failure = err instanceof StepExecutionError
? { stage: err.stage, stepId: err.stepId, message: err.message }
: undefined;
const now = new Date().toISOString();
updateJob(jobId, { status: JOB_STATUS.FAILED, error, completedAt: now });
updateJob(jobId, {
status: JOB_STATUS.FAILED,
error,
completedAt: now,
...(failure !== undefined ? { failure } : {}),
});

emit({
type: "job_failed",
jobId,
timestamp: now,
payload: { error },
payload: { error, ...(failure !== undefined ? { failure } : {}) },
});
} finally {
closeJobClients(jobId);
Expand Down
5 changes: 5 additions & 0 deletions apps/api/src/store/job.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
SSEEvent,
AgentName,
AgentCompletedEvent,
StepFailure,
} from "@stackforge/shared";
import { JOB_STATUS } from "@stackforge/shared";

Expand All @@ -17,6 +18,10 @@ export type StoredJob = {
completedAt?: string;
error?: string;
agentsCompleted: AgentName[];
/** Stage currently running, or the stage that failed. Cleared on completion. */
currentStage?: AgentName | undefined;
/** Set when a pipeline stage caused the failure. */
failure?: StepFailure;
blueprint?: Blueprint;
events: SSEEvent[];
};
Expand Down
9 changes: 9 additions & 0 deletions apps/api/test/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ describe("StackForge API Integration", () => {
expect(json.error).toBe("Validation failed");
});

it("should reject a whitespace-padded prompt that is too short after trimming", async () => {
const res = await fetch(`${baseUrl}/api/generate`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt: " tiny " }),
});
expect(res.status).toBe(422);
});

it("should return runtime provider status", async () => {
const res = await fetch(`${baseUrl}/api/runtime`);
expect([200, 503]).toContain(res.status);
Expand Down
1 change: 1 addition & 0 deletions packages/agents/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export type {
export type { WorkflowEngineOptions, WorkflowRunMeta } from "./workflow/engine.js";
export { ProviderStepExecutor } from "./workflow/provider-step-executor.js";
export type { ProviderStepExecutorOptions } from "./workflow/provider-step-executor.js";
export { StepExecutionError } from "./workflow/step-executor.js";
export type {
AgentStepExecutor,
StepExecutionRequest,
Expand Down
14 changes: 13 additions & 1 deletion packages/agents/src/orchestrator/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
SSEEvent,
TechStack,
} from "@stackforge/shared";
import { BlueprintSchema } from "@stackforge/shared";
import type { AgentCache } from "../cache/agent.cache.js";
import type { LLMProvider } from "../provider/provider.interface.js";
import { AGENT_CONFIGS } from "../config/agent.configs.js";
Expand Down Expand Up @@ -634,10 +635,21 @@ export async function runOrchestrator(options: OrchestratorOptions): Promise<Blu
);
}

return assembleBlueprintFromWorkflow(
const blueprint = assembleBlueprintFromWorkflow(
projectName,
resolvedExecution,
finalState,
workflowMeta?.rawOutputsByStateKey ?? {},
);

const validated = BlueprintSchema.safeParse(blueprint);
if (!validated.success) {
const issues = validated.error.issues
.slice(0, 5)
.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`)
.join("; ");
throw new Error(`Assembled blueprint failed validation: ${issues}`);
}

return validated.data;
}
23 changes: 14 additions & 9 deletions packages/agents/src/workflow/engine.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { AgentName } from "@stackforge/shared";
import { ProviderStepExecutor, type ProviderStepExecutorOptions } from "./provider-step-executor.js";
import type { AgentStepExecutor } from "./step-executor.js";
import { StepExecutionError, type AgentStepExecutor } from "./step-executor.js";
import type { WorkflowDefinition, WorkflowEmit, WorkflowState } from "./types.js";

export type WorkflowRunMeta = {
Expand Down Expand Up @@ -38,14 +38,19 @@ export class WorkflowEngine {
let totalTokensUsed = 0;

for (const step of workflow.steps) {
const stepResult = await this.executor.execute({
jobId: this.options.jobId,
goal: this.options.userGoal,
workflow,
step,
state,
emit: this.options.emit,
});
let stepResult;
try {
stepResult = await this.executor.execute({
jobId: this.options.jobId,
goal: this.options.userGoal,
workflow,
step,
state,
emit: this.options.emit,
});
} catch (error) {
throw new StepExecutionError(step, error);
}
state[step.stateKey] = stepResult.compressedOutput;
rawOutputsByStateKey[step.stateKey] = stepResult.rawOutput;

Expand Down
17 changes: 17 additions & 0 deletions packages/agents/src/workflow/step-executor.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { AgentName } from "@stackforge/shared";
import type { WorkflowDefinition, WorkflowEmit, WorkflowState, WorkflowStep } from "./types.js";

export type StepExecutionRequest = {
Expand Down Expand Up @@ -28,3 +29,19 @@ export type StepExecutionResult = {
export interface AgentStepExecutor {
execute(request: StepExecutionRequest): Promise<StepExecutionResult>;
}

/**
* Thrown by WorkflowEngine when a stage fails. Keeps the original message so
* job errors read the same as before, and adds which stage failed.
*/
export class StepExecutionError extends Error {
readonly stage: AgentName;
readonly stepId: string;

constructor(step: WorkflowStep, cause: unknown) {
super(cause instanceof Error ? cause.message : String(cause), { cause });
this.name = "StepExecutionError";
this.stage = step.agent;
this.stepId = step.id;
}
}
50 changes: 49 additions & 1 deletion packages/agents/test/step-executor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { SSEEvent } from "@stackforge/shared";
import { AgentCache } from "../src/cache/agent.cache.js";
import { MockProvider } from "../src/provider/mock.provider.js";
import { runOrchestrator } from "../src/orchestrator/index.js";
import type { AgentStepExecutor } from "../src/workflow/step-executor.js";
import { StepExecutionError, type AgentStepExecutor } from "../src/workflow/step-executor.js";
import {
buildApiOutput,
buildCodegenOutput,
Expand Down Expand Up @@ -78,4 +78,52 @@ describe("AgentStepExecutor boundary", () => {
}),
).rejects.toThrow("api stage exploded");
});

it("tags stage failures with the failing stage and step id", async () => {
const executor: AgentStepExecutor = {
async execute({ step }) {
if (step.agent === "api") throw new Error("api stage exploded");
return { rawOutput: {}, compressedOutput: "{}", tokensUsed: 0 };
},
};

const error = await runOrchestrator({
jobId: "job-fail-tag",
prompt: "Build a task tracker",
projectName: "x",
emit: () => {},
provider: new MockProvider(),
cache: new AgentCache(),
executor,
}).catch((err: unknown) => err);

expect(error).toBeInstanceOf(StepExecutionError);
expect((error as StepExecutionError).stage).toBe("api");
expect((error as StepExecutionError).stepId).toBe("step-3");
expect((error as StepExecutionError).message).toBe("api stage exploded");
});

it("rejects an assembled blueprint that fails BlueprintSchema", async () => {
const executor: AgentStepExecutor = {
async execute({ step }) {
if (step.stateKey === "plan") {
// Non-string projectName falls back to the caller's name, which is empty here.
return { rawOutput: { projectName: 42 }, compressedOutput: "{}", tokensUsed: 0 };
}
return { rawOutput: {}, compressedOutput: "{}", tokensUsed: 0 };
},
};

await expect(
runOrchestrator({
jobId: "job-invalid-blueprint",
prompt: "Build a task tracker",
projectName: "",
emit: () => {},
provider: new MockProvider(),
cache: new AgentCache(),
executor,
}),
).rejects.toThrow("Assembled blueprint failed validation: projectName");
});
});
4 changes: 2 additions & 2 deletions packages/shared/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ export type {
} from "./schemas/generate.schema.js";

// job schemas
export { AgentNameSchema, JobStatusSchema, JobSchema } from "./schemas/job.schema.js";
export type { Job } from "./schemas/job.schema.js";
export { AgentNameSchema, JobStatusSchema, JobSchema, StepFailureSchema } from "./schemas/job.schema.js";
export type { Job, StepFailure } from "./schemas/job.schema.js";

// sse schemas
export {
Expand Down
26 changes: 13 additions & 13 deletions packages/shared/src/schemas/blueprint.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,45 +11,45 @@ const TechStackSchema = z.object({
});

const FolderNodeSchema = z.object({
path: z.string(),
path: z.string().min(1),
type: z.enum(["file", "dir"]),
description: z.string().optional(),
});

const EntityFieldSchema = z.object({
name: z.string(),
type: z.string(),
name: z.string().min(1),
type: z.string().min(1),
nullable: z.boolean(),
unique: z.boolean().optional(),
foreignKey: z.string().optional(),
});

const EntitySchema = z.object({
name: z.string(),
tableName: z.string(),
name: z.string().min(1),
tableName: z.string().min(1),
fields: z.array(EntityFieldSchema),
indexes: z.array(z.string()).optional(),
});

const RelationshipSchema = z.object({
from: z.string(),
to: z.string(),
from: z.string().min(1),
to: z.string().min(1),
type: z.enum(["one-to-one", "one-to-many", "many-to-many"]),
description: z.string(),
});

const ApiRouteSchema = z.object({
method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]),
path: z.string(),
path: z.string().min(1),
description: z.string(),
auth: z.boolean(),
requestBody: z.string().optional(),
responseType: z.string(),
});

const FrontendPageSchema = z.object({
route: z.string(),
name: z.string(),
route: z.string().min(1),
name: z.string().min(1),
components: z.array(z.string()),
auth: z.boolean(),
description: z.string(),
Expand All @@ -63,13 +63,13 @@ const InfraPlanSchema = z.object({
});

const GeneratedFileSchema = z.object({
path: z.string(),
path: z.string().min(1),
generator: z.string(),
description: z.string(),
});

const GeneratedSourceFileSchema = z.object({
path: z.string(),
path: z.string().min(1),
content: z.string(),
language: z.string().optional(),
});
Expand All @@ -81,7 +81,7 @@ const ReviewerNoteSchema = z.object({
});

export const BlueprintSchema = z.object({
projectName: z.string(),
projectName: z.string().min(1),
generatedAt: z.string().datetime(),
stack: TechStackSchema,
folderStructure: z.array(FolderNodeSchema),
Expand Down
4 changes: 2 additions & 2 deletions packages/shared/src/schemas/generate.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ export const GenerateExecutionSchema = z.object({
});

export const GenerateRequestSchema = z.object({
prompt: z.string().min(10).max(2000),
projectName: z.string().min(1).max(100).optional(),
prompt: z.string().trim().min(10).max(2000),
projectName: z.string().trim().min(1).max(100).optional(),
execution: GenerateExecutionSchema.optional(),
});

Expand Down
11 changes: 11 additions & 0 deletions packages/shared/src/schemas/job.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@ export const AgentNameSchema = z.enum(
AGENT_NAMES as unknown as [string, ...string[]],
);

/** Which pipeline stage failed and why. */
export const StepFailureSchema = z.object({
stage: AgentNameSchema,
stepId: z.string(),
message: z.string(),
});

export type StepFailure = z.infer<typeof StepFailureSchema>;

export const JobStatusSchema = z.enum([
JOB_STATUS.QUEUED,
JOB_STATUS.RUNNING,
Expand All @@ -23,6 +32,8 @@ export const JobSchema = z.object({
completedAt: z.string().datetime().optional(),
error: z.string().optional(),
agentsCompleted: z.array(AgentNameSchema),
currentStage: AgentNameSchema.optional(),
failure: StepFailureSchema.optional(),
blueprint: z.unknown().optional(),
});

Expand Down
Loading
Loading