scai
Version:
> **AI-powered CLI for local code analysis, commit message suggestions, and natural-language queries.** 100% local, private, GDPR-friendly, made in Denmark/EU with ❤️.
124 lines (114 loc) • 5.19 kB
JavaScript
// File: src/agents/finalPlanGenStep.ts
import { generate } from '../lib/generate.js';
import { PLAN_ACTIONS } from '../utils/planActions.js';
import { logInputOutput } from '../utils/promptLogHelper.js';
import { cleanupModule } from '../pipeline/modules/cleanupModule.js';
const MAX_STEPS = 100;
/**
* FINAL PLAN GENERATOR
* Generates steps that finalize results, commit changes, or prepare outputs.
*/
export const finalPlanGenStep = {
name: 'finalPlanGen',
description: 'Generates finalization steps to wrap up and commit results.',
requires: ['analysis.intent', 'analysis.focus'],
produces: ['analysis.planSuggestion'],
async run(context) {
var _a, _b;
context.analysis || (context.analysis = {});
(_a = context.analysis).planSuggestion || (_a.planSuggestion = {});
(_b = context.analysis.planSuggestion).plan || (_b.plan = { steps: [] });
// Restrict actions to FINALIZE group only
const effectiveActions = PLAN_ACTIONS.filter(a => a.groups?.includes('finalize'));
const actionsJson = JSON.stringify(effectiveActions, null, 2);
const intentText = context.analysis.intent?.normalizedQuery ?? '';
const intentCategory = context.analysis.intent?.intentCategory ?? '';
const prompt = `
You are an autonomous coding agent.
Your task is to produce a structured plan describing finalization steps
to wrap up work, commit changes, or produce outputs safely.
Intent / task description:
${intentText}
If the intent indicates that no finalization is required, return an empty plan object with an empty "steps" array:
{ "steps": [] }
Allowed actions (finalize only):
${actionsJson}
Task category:
${intentCategory}
Folder structure:
${context.analysis.folderCapsulesHuman ?? ''}
Existing relevant files:
${JSON.stringify(context.analysis.focus?.relevantFiles ?? {}, null, 2)}
⚡ Phase guidance:
- Actions are grouped into phases: info, transform, finalize.
- Only include finalize steps in this phase.
- Each step must include: "action", "targetFile" (optional), "description", "metadata"
Return a strictly valid JSON plan:
{
"steps": [
{ "action": "stepName", "targetFile": "optional/path.ts", "description": "explanation", "metadata": {} }
]
}
`.trim();
try {
console.log('FinalPlanGenStep prompt', prompt);
const genInput = { query: intentText, content: prompt };
const genOutput = await generate(genInput);
const raw = typeof genOutput.data === 'string'
? genOutput.data
: JSON.stringify(genOutput.data ?? '{}');
const cleaned = await cleanupModule.run({ query: intentText, content: raw });
const jsonString = typeof cleaned.content === 'string'
? cleaned.content
: JSON.stringify(cleaned.content ?? '{}');
let plan = JSON.parse(jsonString);
if (!plan || !Array.isArray(plan.steps))
throw new Error('Invalid final plan structure');
if (plan.steps.length > MAX_STEPS)
plan.steps = plan.steps.slice(0, MAX_STEPS);
// Map groups & metadata
plan.steps = plan.steps.map(step => {
const actionDef = PLAN_ACTIONS.find(a => a.action === step.action);
return {
...step,
metadata: {
...step.metadata,
routingConfidence: context.analysis?.routingDecision?.confidence ?? 0
},
groups: actionDef?.groups ?? ['finalize']
};
});
// Ensure at least one summary step if plan is empty
if (plan.steps.length === 0) {
plan.steps.push({
action: 'finalizeSummary',
description: 'Summarize what actions were taken and provide a response to the user.',
metadata: {
routingConfidence: context.analysis?.routingDecision?.confidence ?? 0
},
groups: ['finalize']
});
}
// Replace existing finalize steps in planSuggestion
context.analysis.planSuggestion.plan.steps = [
...context.analysis.planSuggestion.plan.steps.filter(s => !s.groups?.includes('finalize')),
...plan.steps
];
logInputOutput('finalPlanGen', 'output', plan);
}
catch (err) {
console.warn('⚠️ Failed to generate final plan:', err);
context.analysis.planSuggestion.plan.steps = [
{
action: 'finalizeSummary',
description: 'Summarize what actions were taken and provide a response to the user.',
metadata: {
routingConfidence: context.analysis?.routingDecision?.confidence ?? 0
},
groups: ['finalize']
}
];
logInputOutput('finalPlanGen', 'output', context.analysis.planSuggestion.plan);
}
}
};