import "./subsystem-Ci61Iebe.js";
import "./paths-aMBPuCJR.js";
import "./exec-B5OgjUV4.js";
import "./image-ops-DfgorOBP.js";
import "./tool-images-D39TNWEi.js";
import { a as jsonResult, o as readNumberParam, t as ToolInputError, u as readStringParam } from "./common-BkBiFnII.js";
import { r as optionalStringEnum } from "./typebox-BrLUZMNm.js";
import fs from "node:fs/promises";
import path from "node:path";
import { Type } from "@sinclair/typebox";

//#region src/agents/tools/misc/architect-pipeline-tool.ts
const ArchitectPipelineToolSchema = Type.Object({
	action: optionalStringEnum([
		"init",
		"get",
		"update",
		"decision_gate"
	]),
	path: Type.Optional(Type.String()),
	project: Type.Optional(Type.String()),
	currentPhase: optionalStringEnum([
		"planning",
		"construction",
		"validation"
	]),
	currentStep: Type.Optional(Type.Number({ minimum: 1 })),
	status: optionalStringEnum([
		"running",
		"blocked",
		"complete",
		"escalated"
	]),
	retryCount: Type.Optional(Type.Number({ minimum: 0 })),
	conceptBriefPath: Type.Optional(Type.String()),
	prdPath: Type.Optional(Type.String()),
	wireframesPath: Type.Optional(Type.String()),
	schemaPath: Type.Optional(Type.String()),
	designSystemPath: Type.Optional(Type.String()),
	infraReady: Type.Optional(Type.Boolean()),
	codeReady: Type.Optional(Type.Boolean()),
	securityReportPath: Type.Optional(Type.String()),
	deployInstructionsPath: Type.Optional(Type.String()),
	report: optionalStringEnum([
		"PASS",
		"FAIL",
		"ERROR"
	]),
	findings: Type.Optional(Type.String()),
	maxRetries: Type.Optional(Type.Number({ minimum: 1 }))
});
function defaultState(project = "unnamed-project") {
	return {
		project,
		currentPhase: "planning",
		currentStep: 1,
		retryCount: 0,
		status: "running",
		sharedContext: {
			conceptBriefPath: "concept_brief.json",
			prdPath: "prd.md",
			wireframesPath: "wireframes.md",
			schemaPath: "data-schema.json",
			designSystemPath: "design-system.md"
		},
		artifacts: {
			infraReady: false,
			codeReady: false,
			securityReportPath: "security-report.md",
			deployInstructionsPath: "DEPLOY_INSTRUCTIONS.md"
		}
	};
}
function isWithinWorkspace(candidatePath, workspaceDir) {
	const rel = path.relative(workspaceDir, candidatePath);
	return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
}
function resolveStatePath(params) {
	const workspaceDir = path.resolve(params.workspaceDir);
	const rawPath = params.rawPath?.trim();
	const statePath = rawPath ? path.resolve(workspaceDir, rawPath) : path.join(workspaceDir, "state.json");
	if (!isWithinWorkspace(statePath, workspaceDir)) throw new ToolInputError("path must stay within the workspace directory");
	return statePath;
}
async function readState(statePath) {
	try {
		const raw = await fs.readFile(statePath, "utf-8");
		return JSON.parse(raw);
	} catch (error) {
		if (error.code === "ENOENT") return null;
		throw error;
	}
}
async function writeState(statePath, state) {
	await fs.mkdir(path.dirname(statePath), { recursive: true });
	await fs.writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`, "utf-8");
}
function createArchitectPipelineTool(options) {
	return {
		label: "Architect Pipeline",
		name: "architect_pipeline",
		description: "Manage Architect CEO orchestration state.json and enforce audit decision gates for retries/escalation.",
		parameters: ArchitectPipelineToolSchema,
		execute: async (_callId, input) => {
			const params = input ?? {};
			const action = readStringParam(params, "action") ?? "get";
			const statePath = resolveStatePath({
				workspaceDir: options.workspaceDir,
				rawPath: readStringParam(params, "path")
			});
			if (action === "init") {
				const state = defaultState(readStringParam(params, "project") ?? "unnamed-project");
				await writeState(statePath, state);
				return jsonResult({
					action,
					path: statePath,
					state
				});
			}
			const current = await readState(statePath);
			if (!current) throw new ToolInputError(`state file not found at ${statePath}. Run action=init first or provide an existing path.`);
			if (action === "get") return jsonResult({
				action,
				path: statePath,
				state: current
			});
			if (action === "update") {
				const next = {
					...current,
					project: readStringParam(params, "project") ?? current.project,
					currentPhase: readStringParam(params, "currentPhase") ?? current.currentPhase,
					currentStep: readNumberParam(params, "currentStep", { integer: true }) ?? current.currentStep,
					retryCount: readNumberParam(params, "retryCount", { integer: true }) ?? current.retryCount,
					status: readStringParam(params, "status") ?? current.status,
					sharedContext: {
						...current.sharedContext,
						conceptBriefPath: readStringParam(params, "conceptBriefPath") ?? current.sharedContext.conceptBriefPath,
						prdPath: readStringParam(params, "prdPath") ?? current.sharedContext.prdPath,
						wireframesPath: readStringParam(params, "wireframesPath") ?? current.sharedContext.wireframesPath,
						schemaPath: readStringParam(params, "schemaPath") ?? current.sharedContext.schemaPath,
						designSystemPath: readStringParam(params, "designSystemPath") ?? current.sharedContext.designSystemPath
					},
					artifacts: {
						...current.artifacts,
						infraReady: typeof params.infraReady === "boolean" ? params.infraReady : current.artifacts.infraReady,
						codeReady: typeof params.codeReady === "boolean" ? params.codeReady : current.artifacts.codeReady,
						securityReportPath: readStringParam(params, "securityReportPath") ?? current.artifacts.securityReportPath,
						deployInstructionsPath: readStringParam(params, "deployInstructionsPath") ?? current.artifacts.deployInstructionsPath
					}
				};
				await writeState(statePath, next);
				return jsonResult({
					action,
					path: statePath,
					state: next
				});
			}
			if (action === "decision_gate") {
				const report = readStringParam(params, "report", { required: true }).toUpperCase();
				const findings = readStringParam(params, "findings");
				const maxRetries = readNumberParam(params, "maxRetries", { integer: true }) ?? 5;
				const retryCount = report === "PASS" ? current.retryCount : current.retryCount + 1;
				const status = report === "PASS" ? "complete" : retryCount >= maxRetries ? "escalated" : "running";
				const next = {
					...current,
					currentPhase: report === "PASS" ? "validation" : current.currentPhase,
					retryCount,
					status,
					latestAudit: {
						report,
						findings,
						at: (/* @__PURE__ */ new Date()).toISOString(),
						retryCount
					}
				};
				await writeState(statePath, next);
				return jsonResult({
					action,
					path: statePath,
					report,
					status,
					retryCount,
					maxRetries,
					nextAction: report === "PASS" ? "package_app_and_generate_deploy_instructions" : status === "escalated" ? "escalate_to_human" : "send_findings_to_builder_then_reaudit",
					state: next
				});
			}
			throw new ToolInputError("Unknown action.");
		}
	};
}

//#endregion
export { createArchitectPipelineTool };