chore: consolidate new foundation and archive v1 (#1495)

This commit is contained in:
2026-09-07 12:32:57 -05:00
3511 changed files with 727899 additions and 10 deletions
+195
View File
@@ -0,0 +1,195 @@
import fs from 'node:fs';
import path from 'node:path';
import type { BoardPersona, BoardSynthesis, ForgeTask, PersonaReview } from './types.js';
/**
* Build the brief content for a persona's board evaluation.
*/
export function buildPersonaBrief(brief: string, persona: BoardPersona): string {
return [
`# Board Evaluation: ${persona.name}`,
'',
'## Your Role',
persona.description,
'',
'## Brief Under Review',
brief.trim(),
'',
'## Instructions',
'Evaluate this brief from your perspective. Output a JSON object:',
'{',
` "persona": "${persona.name}",`,
' "verdict": "approve|reject|conditional",',
' "confidence": 0.0-1.0,',
' "concerns": ["..."],',
' "recommendations": ["..."],',
' "key_risks": ["..."]',
'}',
'',
].join('\n');
}
/**
* Write a persona brief to the run directory and return the path.
*/
export function writePersonaBrief(
runDir: string,
baseTaskId: string,
persona: BoardPersona,
brief: string,
): string {
const briefDir = path.join(runDir, '01-board', 'briefs');
fs.mkdirSync(briefDir, { recursive: true });
const briefPath = path.join(briefDir, `${baseTaskId}-${persona.slug}.md`);
fs.writeFileSync(briefPath, buildPersonaBrief(brief, persona), 'utf-8');
return briefPath;
}
/**
* Get the result path for a persona's board review.
*/
export function personaResultPath(runDir: string, taskId: string): string {
return path.join(runDir, '01-board', 'results', `${taskId}.board.json`);
}
/**
* Get the result path for the board synthesis.
*/
export function synthesisResultPath(runDir: string, taskId: string): string {
return path.join(runDir, '01-board', 'results', `${taskId}.board.json`);
}
/**
* Generate one ForgeTask per board persona plus one synthesis task.
*
* Persona tasks run independently (no depends_on).
* The synthesis task depends on all persona tasks with 'all_terminal' policy.
*/
export function generateBoardTasks(
brief: string,
personas: BoardPersona[],
runDir: string,
baseTaskId = 'BOARD',
): ForgeTask[] {
const tasks: ForgeTask[] = [];
const personaTaskIds: string[] = [];
const personaResultPaths: string[] = [];
for (const persona of personas) {
const taskId = `${baseTaskId}-${persona.slug}`;
personaTaskIds.push(taskId);
const briefPath = writePersonaBrief(runDir, baseTaskId, persona, brief);
const resultRelPath = personaResultPath(runDir, taskId);
personaResultPaths.push(resultRelPath);
tasks.push({
id: taskId,
title: `Board review: ${persona.name}`,
description: `Independent board evaluation for ${persona.name}.`,
type: 'review',
dispatch: 'exec',
status: 'pending',
briefPath,
resultPath: resultRelPath,
timeoutSeconds: 120,
qualityGates: [
{
kind: 'authority',
capability: 'board-approval',
reason:
'persona evaluation is judged by board synthesis (authority review); no mechanical gate exists',
},
],
metadata: {
personaName: persona.name,
personaSlug: persona.slug,
personaPath: persona.path,
resultOutputPath: resultRelPath,
},
});
}
// Synthesis task — merges all persona reviews
const synthesisId = `${baseTaskId}-SYNTHESIS`;
const synthesisResult = synthesisResultPath(runDir, synthesisId);
tasks.push({
id: synthesisId,
title: 'Board synthesis',
description: 'Merge independent board reviews into a single recommendation.',
type: 'review',
dispatch: 'exec',
status: 'pending',
briefPath: '',
resultPath: synthesisResult,
timeoutSeconds: 120,
dependsOn: personaTaskIds,
dependsOnPolicy: 'all_terminal',
qualityGates: [
{
kind: 'authority',
capability: 'board-approval',
reason: 'board synthesis is an authority decision; no mechanical gate exists',
},
],
metadata: {
resultOutputPath: synthesisResult,
inputResultPaths: personaResultPaths,
},
});
return tasks;
}
/**
* Merge multiple persona reviews into a board synthesis.
*/
export function synthesizeReviews(reviews: PersonaReview[]): BoardSynthesis {
const verdicts = reviews.map((r) => r.verdict);
let mergedVerdict: PersonaReview['verdict'];
if (verdicts.includes('reject')) {
mergedVerdict = 'reject';
} else if (verdicts.includes('conditional')) {
mergedVerdict = 'conditional';
} else {
mergedVerdict = 'approve';
}
const confidenceValues = reviews.map((r) => r.confidence);
const avgConfidence =
confidenceValues.length > 0
? Math.round((confidenceValues.reduce((a, b) => a + b, 0) / confidenceValues.length) * 1000) /
1000
: 0;
const concerns = unique(reviews.flatMap((r) => r.concerns));
const recommendations = unique(reviews.flatMap((r) => r.recommendations));
const keyRisks = unique(reviews.flatMap((r) => r.keyRisks));
return {
persona: 'Board Synthesis',
verdict: mergedVerdict,
confidence: avgConfidence,
concerns,
recommendations,
keyRisks,
reviews,
};
}
/** Deduplicate while preserving order. */
function unique(items: string[]): string[] {
const seen = new Set<string>();
const result: string[] = [];
for (const item of items) {
if (!seen.has(item)) {
seen.add(item);
result.push(item);
}
}
return result;
}
+102
View File
@@ -0,0 +1,102 @@
import { STAGE_SEQUENCE, STRATEGIC_KEYWORDS, TECHNICAL_KEYWORDS } from './constants.js';
import type { BriefClass, ClassSource } from './types.js';
const VALID_CLASSES: ReadonlySet<string> = new Set<BriefClass>([
'strategic',
'technical',
'hotfix',
]);
/**
* Auto-classify a brief based on keyword analysis.
* Returns 'strategic' if strategic keywords dominate,
* 'technical' if any technical keywords are found,
* otherwise defaults to 'strategic' (full pipeline).
*/
export function classifyBrief(text: string): BriefClass {
const lower = text.toLowerCase();
let strategicHits = 0;
let technicalHits = 0;
for (const kw of STRATEGIC_KEYWORDS) {
if (lower.includes(kw)) strategicHits++;
}
for (const kw of TECHNICAL_KEYWORDS) {
if (lower.includes(kw)) technicalHits++;
}
if (strategicHits > technicalHits) return 'strategic';
if (technicalHits > 0) return 'technical';
return 'strategic';
}
/**
* Parse YAML frontmatter from a brief.
* Supports simple `key: value` pairs via regex (no YAML dependency).
*/
export function parseBriefFrontmatter(text: string): Record<string, string> {
const match = text.match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
if (!match?.[1]) return {};
const result: Record<string, string> = {};
for (const line of match[1].split('\n')) {
const km = line.trim().match(/^(\w[\w-]*)\s*:\s*(.+)$/);
if (km?.[1] && km[2]) {
result[km[1]] = km[2].trim().replace(/^["']|["']$/g, '');
}
}
return result;
}
/**
* Determine brief class from all sources with priority:
* CLI flag > frontmatter > auto-classify.
*/
export function determineBriefClass(
text: string,
cliClass?: string,
): { briefClass: BriefClass; classSource: ClassSource } {
if (cliClass && VALID_CLASSES.has(cliClass)) {
return { briefClass: cliClass as BriefClass, classSource: 'cli' };
}
const fm = parseBriefFrontmatter(text);
if (fm['class'] && VALID_CLASSES.has(fm['class'])) {
return { briefClass: fm['class'] as BriefClass, classSource: 'frontmatter' };
}
return { briefClass: classifyBrief(text), classSource: 'auto' };
}
/**
* Build the stage list based on brief classification.
* - strategic: full pipeline (all stages)
* - technical: skip board (01-board)
* - hotfix: skip board + brief analyzer
*
* forceBoard re-adds the board stage regardless of class.
*/
export function stagesForClass(briefClass: BriefClass, forceBoard = false): string[] {
const stages = ['00-intake', '00b-discovery'];
if (briefClass === 'strategic' || forceBoard) {
stages.push('01-board');
}
if (briefClass === 'strategic' || briefClass === 'technical' || forceBoard) {
stages.push('01b-brief-analyzer');
}
stages.push(
'02-planning-1',
'03-planning-2',
'04-planning-3',
'05-coding',
'06-review',
'07-remediate',
'08-test',
'09-deploy',
);
// Maintain canonical order
return stages.filter((s) => STAGE_SEQUENCE.includes(s));
}
+152
View File
@@ -0,0 +1,152 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Command } from 'commander';
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
import { registerForgeCommand } from './cli.js';
import { loadManifest } from './pipeline-runner.js';
describe('registerForgeCommand', () => {
it('registers a "forge" command on the parent program', () => {
const program = new Command();
registerForgeCommand(program);
const forgeCmd = program.commands.find((c) => c.name() === 'forge');
expect(forgeCmd).toBeDefined();
});
it('registers the four required subcommands under forge', () => {
const program = new Command();
registerForgeCommand(program);
const forgeCmd = program.commands.find((c) => c.name() === 'forge');
expect(forgeCmd).toBeDefined();
const subNames = forgeCmd!.commands.map((c) => c.name());
expect(subNames).toContain('run');
expect(subNames).toContain('status');
expect(subNames).toContain('resume');
expect(subNames).toContain('personas');
});
it('registers "personas list" as a subcommand of "forge personas"', () => {
const program = new Command();
registerForgeCommand(program);
const forgeCmd = program.commands.find((c) => c.name() === 'forge');
const personasCmd = forgeCmd!.commands.find((c) => c.name() === 'personas');
expect(personasCmd).toBeDefined();
const personasSubNames = personasCmd!.commands.map((c) => c.name());
expect(personasSubNames).toContain('list');
});
it('does not modify the parent program name or description', () => {
const program = new Command('mosaic');
program.description('Mosaic Stack CLI');
registerForgeCommand(program);
expect(program.name()).toBe('mosaic');
expect(program.description()).toBe('Mosaic Stack CLI');
});
it('can be called multiple times without throwing', () => {
const program = new Command();
expect(() => {
registerForgeCommand(program);
}).not.toThrow();
});
});
describe('forge run fail-closed behavior (SDLC-D-035)', () => {
let tmpDir: string;
let briefPath: string;
let errSpy: ReturnType<typeof vi.spyOn>;
let logSpy: ReturnType<typeof vi.spyOn>;
let prevExitCode: string | number | null | undefined;
const parse = (args: string[]) => {
const program = new Command();
registerForgeCommand(program);
return program.parseAsync(['forge', ...args], { from: 'user' });
};
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'forge-cli-failclosed-'));
briefPath = path.join(tmpDir, 'brief.md');
fs.writeFileSync(briefPath, '# Fix bug\n\nA bugfix for lint cleanup.');
errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
prevExitCode = process.exitCode;
});
afterEach(() => {
errSpy.mockRestore();
logSpy.mockRestore();
process.exitCode = prevExitCode;
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('exits nonzero with a typed FORGE_NO_EXECUTOR error when no executor is wired and --simulate is absent', async () => {
await parse(['run', '--brief', briefPath, '--codebase', tmpDir]);
expect(process.exitCode).toBe(1);
const errText = errSpy.mock.calls.map((c) => c.join(' ')).join('\n');
expect(errText).toContain('FORGE_NO_EXECUTOR');
// It must never run the pipeline with a stub and report success.
expect(fs.existsSync(path.join(tmpDir, '.forge', 'runs'))).toBe(false);
});
it('completes with typed simulated results and exit 0 under explicit --simulate', async () => {
await parse(['run', '--brief', briefPath, '--codebase', tmpDir, '--simulate']);
expect(process.exitCode).toBeUndefined();
// Loud simulated-mode summary.
const logText = logSpy.mock.calls.map((c) => c.join(' ')).join('\n');
expect(logText).toContain('SIMULATED');
// Manifest records the mode and simulated per-result statuses.
const runsDir = path.join(tmpDir, '.forge', 'runs');
const runIds = fs.readdirSync(runsDir);
expect(runIds).toHaveLength(1);
const manifest = loadManifest(path.join(runsDir, runIds[0]!));
expect(manifest.mode).toBe('simulated');
expect(manifest.status).toBe('simulated');
for (const stageStatus of Object.values(manifest.stages)) {
expect(stageStatus?.status).toBe('simulated');
for (const gateResult of stageStatus?.gateResults ?? []) {
expect(gateResult.outcome).toBe('simulated');
}
}
});
it('resume exits nonzero with a typed FORGE_NO_EXECUTOR error without --simulate', async () => {
const runDir = path.join(tmpDir, '.forge', 'runs', '20260101-000000');
fs.mkdirSync(runDir, { recursive: true });
fs.writeFileSync(
path.join(runDir, 'manifest.json'),
JSON.stringify({
runId: '20260101-000000',
brief: briefPath,
codebase: tmpDir,
briefClass: 'hotfix',
classSource: 'frontmatter',
forceBoard: false,
createdAt: '2026-01-01T00:00:00Z',
updatedAt: '2026-01-01T00:00:00Z',
currentStage: '00-intake',
status: 'in_progress',
stages: { '00-intake': { status: 'passed' } },
}),
);
await parse(['resume', '20260101-000000', '--project', tmpDir]);
expect(process.exitCode).toBe(1);
const errText = errSpy.mock.calls.map((c) => c.join(' ')).join('\n');
expect(errText).toContain('FORGE_NO_EXECUTOR');
});
});
+354
View File
@@ -0,0 +1,354 @@
import fs from 'node:fs';
import path from 'node:path';
import type { Command } from 'commander';
import { classifyBrief } from './brief-classifier.js';
import { STAGE_LABELS, STAGE_SEQUENCE } from './constants.js';
import { ForgeCapabilityError } from './errors.js';
import { getEffectivePersonas, loadBoardPersonas } from './persona-loader.js';
import { generateRunId, getPipelineStatus, loadManifest, runPipeline } from './pipeline-runner.js';
import { createSimulatedExecutor } from './simulated-executor.js';
import type { PipelineOptions, RunManifest, RunMode } from './types.js';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/** Resolve a run's effective mode, defaulting legacy manifests to normal. */
function runModeOf(manifest: RunManifest): RunMode {
return manifest.mode ?? 'normal';
}
/** Print a loud banner so a simulated run can never be misread as verified. */
function printSimulatedBanner(): void {
console.log('');
console.log('[forge] ===============================================================');
console.log('[forge] MODE: SIMULATED — no stage or gate was really executed.');
console.log('[forge] All results are synthetic and MUST NOT be read as verified');
console.log('[forge] success. Wire a real executor/providers and re-run to verify.');
console.log('[forge] ===============================================================');
}
/** Print a typed error line for fail-closed capability errors. */
function printCapabilityError(err: ForgeCapabilityError): void {
console.error(`[forge] error ${err.code}: ${err.message}`);
console.error(`[forge] missing capability: ${err.capability}`);
}
/** Handle a pipeline error uniformly: typed capability errors get their code. */
function handlePipelineError(err: unknown): void {
if (err instanceof ForgeCapabilityError) {
printCapabilityError(err);
} else {
console.error(`[forge] pipeline failed: ${err instanceof Error ? err.message : String(err)}`);
}
process.exitCode = 1;
}
function formatDuration(startedAt?: string, completedAt?: string): string {
if (!startedAt || !completedAt) return '-';
const ms = new Date(completedAt).getTime() - new Date(startedAt).getTime();
const secs = Math.round(ms / 1000);
return secs < 60 ? `${secs}s` : `${Math.floor(secs / 60)}m${secs % 60}s`;
}
function printManifestTable(manifest: RunManifest): void {
const mode = runModeOf(manifest);
console.log(`\nRun ID : ${manifest.runId}`);
console.log(`Status : ${manifest.status}`);
console.log(`Mode : ${mode}`);
if (mode === 'simulated') {
console.log('WARNING: SIMULATED RUN — results are synthetic, not verified success.');
}
console.log(`Brief : ${manifest.brief}`);
console.log(`Class : ${manifest.briefClass} (${manifest.classSource})`);
console.log(`Updated: ${manifest.updatedAt}`);
console.log('');
console.log('Stage'.padEnd(22) + 'Status'.padEnd(24) + 'Duration');
console.log('-'.repeat(60));
for (const stage of STAGE_SEQUENCE) {
const s = manifest.stages[stage];
if (!s) continue;
const label = (STAGE_LABELS[stage] ?? stage).padEnd(22);
const status = s.status.padEnd(24);
const dur = formatDuration(s.startedAt, s.completedAt);
console.log(`${label}${status}${dur}`);
}
console.log('');
}
function resolveRunDir(runId: string, projectRoot?: string): string {
const root = projectRoot ?? process.cwd();
return path.join(root, '.forge', 'runs', runId);
}
function listRecentRuns(projectRoot?: string): void {
const root = projectRoot ?? process.cwd();
const runsDir = path.join(root, '.forge', 'runs');
if (!fs.existsSync(runsDir)) {
console.log('No runs found. Run `mosaic forge run` to start a pipeline.');
return;
}
const entries = fs
.readdirSync(runsDir)
.filter((name) => fs.statSync(path.join(runsDir, name)).isDirectory())
.sort()
.reverse()
.slice(0, 10);
if (entries.length === 0) {
console.log('No runs found.');
return;
}
console.log('\nRecent runs:');
console.log('Run ID'.padEnd(22) + 'Status'.padEnd(24) + 'Mode'.padEnd(12) + 'Brief');
console.log('-'.repeat(80));
for (const runId of entries) {
const runDir = path.join(runsDir, runId);
try {
const manifest = loadManifest(runDir);
const status = manifest.status.padEnd(24);
const mode = runModeOf(manifest).padEnd(12);
const brief = path.basename(manifest.brief);
console.log(`${runId.padEnd(22)}${status}${mode}${brief}`);
} catch {
console.log(`${runId.padEnd(22)}${'(unreadable)'.padEnd(24)}`);
}
}
console.log('');
}
/**
* Apply the exit-code policy for a finished pipeline run (SDLC-D-035):
*
* - exit 0 only for a verified `completed` normal run, or for an overall
* `simulated` run when the caller explicitly passed --simulate;
* - anything else exits nonzero so it can never be read as success.
*/
function applyRunExitPolicy(result: { manifest: RunManifest; runDir: string }, simulate: boolean) {
const { manifest } = result;
if (runModeOf(manifest) === 'simulated') {
if (!simulate || manifest.status !== 'simulated') {
console.error(
'[forge] error FORGE_MODE_MISMATCH: run reports simulated results without an explicit, ' +
'consistent --simulate request; refusing to report success.',
);
process.exitCode = 1;
return;
}
printSimulatedBanner();
console.log(`[forge] run directory: ${result.runDir}`);
return; // exit 0 — the caller explicitly opted into simulation
}
if (manifest.status !== 'completed') {
console.error(`[forge] run did not complete: terminal status '${manifest.status}'`);
process.exitCode = 1;
return;
}
console.log(`[forge] pipeline complete (mode: normal): ${manifest.runId}`);
console.log(`[forge] run directory: ${result.runDir}`);
}
// ---------------------------------------------------------------------------
// Register function
// ---------------------------------------------------------------------------
/**
* Register forge subcommands on an existing Commander program.
* Mirrors the pattern used by registerQualityRails in @mosaicstack/quality-rails.
*/
export function registerForgeCommand(parent: Command): void {
const forge = parent.command('forge').description('Run and manage Forge pipelines');
// ── forge run ────────────────────────────────────────────────────────────
forge
.command('run')
.description('Run a Forge pipeline from a brief markdown file')
.requiredOption('--brief <path>', 'Path to the brief markdown file')
.option('--run-id <id>', 'Override the auto-generated run ID')
.option('--resume', 'Resume an existing run instead of starting a new one', false)
.option('--config <path>', 'Path to forge config file (.forge/config.yaml)')
.option('--codebase <path>', 'Codebase root to pass to the pipeline', process.cwd())
.option('--dry-run', 'Print planned stages without executing', false)
.option(
'--simulate',
'Simulate execution without real providers (every result is typed simulated, never verified)',
false,
)
.action(
async (opts: {
brief: string;
runId?: string;
resume: boolean;
config?: string;
codebase: string;
dryRun: boolean;
simulate: boolean;
}) => {
const briefPath = path.resolve(opts.brief);
if (!fs.existsSync(briefPath)) {
console.error(`[forge] brief not found: ${briefPath}`);
process.exitCode = 1;
return;
}
const briefContent = fs.readFileSync(briefPath, 'utf-8');
const briefClass = classifyBrief(briefContent);
const projectRoot = opts.codebase;
// A real executor is never wired at CLI invocation time today, so the
// only executor we may construct is the explicitly-requested simulated
// one. Normal mode fails closed with FORGE_NO_EXECUTOR.
const executor = opts.simulate ? createSimulatedExecutor() : undefined;
if (opts.resume) {
const runId = opts.runId ?? generateRunId();
const runDir = resolveRunDir(runId, projectRoot);
console.log(`[forge] resuming run: ${runId}`);
try {
const { resumePipeline } = await import('./pipeline-runner.js');
const result = await resumePipeline(runDir, executor, { simulate: opts.simulate });
applyRunExitPolicy(result, opts.simulate);
} catch (err) {
handlePipelineError(err);
}
return;
}
const pipelineOptions: PipelineOptions = {
briefClass,
codebase: projectRoot,
dryRun: opts.dryRun,
executor,
simulate: opts.simulate,
};
if (opts.dryRun) {
const { stagesForClass } = await import('./brief-classifier.js');
const stages = stagesForClass(briefClass);
console.log(`[forge] dry-run — brief class: ${briefClass}`);
console.log('[forge] planned stages:');
for (const stage of stages) {
console.log(` - ${stage} (${STAGE_LABELS[stage] ?? stage})`);
}
return;
}
console.log(`[forge] starting pipeline for brief: ${briefPath}`);
console.log(`[forge] classified as: ${briefClass}`);
if (opts.simulate) {
console.log('[forge] mode: SIMULATED (explicit --simulate)');
}
try {
const result = await runPipeline(briefPath, projectRoot, pipelineOptions);
applyRunExitPolicy(result, opts.simulate);
} catch (err) {
handlePipelineError(err);
}
},
);
// ── forge status ─────────────────────────────────────────────────────────
forge
.command('status [runId]')
.description('Show the status of a pipeline run (omit runId to list recent runs)')
.option('--project <path>', 'Project root (defaults to cwd)', process.cwd())
.action(async (runId: string | undefined, opts: { project: string }) => {
if (!runId) {
listRecentRuns(opts.project);
return;
}
const runDir = resolveRunDir(runId, opts.project);
try {
const manifest = getPipelineStatus(runDir);
printManifestTable(manifest);
} catch (err) {
console.error(
`[forge] could not load run "${runId}": ${err instanceof Error ? err.message : String(err)}`,
);
process.exitCode = 1;
}
});
// ── forge resume ─────────────────────────────────────────────────────────
forge
.command('resume <runId>')
.description('Resume a stopped or failed pipeline run')
.option('--project <path>', 'Project root (defaults to cwd)', process.cwd())
.option(
'--simulate',
'Simulate execution without real providers (every result is typed simulated, never verified)',
false,
)
.action(async (runId: string, opts: { project: string; simulate: boolean }) => {
const runDir = resolveRunDir(runId, opts.project);
if (!fs.existsSync(runDir)) {
console.error(`[forge] run not found: ${runDir}`);
process.exitCode = 1;
return;
}
console.log(`[forge] resuming run: ${runId}`);
if (opts.simulate) {
console.log('[forge] mode: SIMULATED (explicit --simulate)');
}
// No real executor is wired at CLI invocation time; only the explicitly
// requested simulated executor may be constructed (fail closed otherwise).
const executor = opts.simulate ? createSimulatedExecutor() : undefined;
try {
const { resumePipeline } = await import('./pipeline-runner.js');
const result = await resumePipeline(runDir, executor, { simulate: opts.simulate });
applyRunExitPolicy(result, opts.simulate);
} catch (err) {
handlePipelineError(err);
}
});
// ── forge personas ────────────────────────────────────────────────────────
const personas = forge.command('personas').description('Manage Forge board personas');
personas
.command('list')
.description('List configured board personas')
.option(
'--project <path>',
'Project root for persona overrides (defaults to cwd)',
process.cwd(),
)
.option('--board-dir <path>', 'Override the board agents directory')
.action((opts: { project: string; boardDir?: string }) => {
const effectivePersonas = opts.boardDir
? loadBoardPersonas(opts.boardDir)
: getEffectivePersonas(opts.project);
if (effectivePersonas.length === 0) {
console.log('[forge] no board personas configured.');
return;
}
console.log(`\nBoard personas (${effectivePersonas.length}):\n`);
console.log('Slug'.padEnd(24) + 'Name');
console.log('-'.repeat(50));
for (const p of effectivePersonas) {
console.log(`${p.slug.padEnd(24)}${p.name}`);
}
console.log('');
});
}
+268
View File
@@ -0,0 +1,268 @@
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import type { StageSpec } from './types.js';
/** Package root resolved via import.meta.url — works regardless of install location. */
export const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
/** Pipeline asset directory (stages, agents, rails, gates, templates). */
export const PIPELINE_DIR = path.join(PACKAGE_ROOT, 'pipeline');
/** Stage specifications — defines every pipeline stage.
*\n * Gate semantics (SDLC-D-035): every gate is one of
* - a real command string / GateEntry a mechanical runner can execute,
* - an `authority` gate (human/board sign-off; produces waiting-for-authority),
* - a `provider` gate (requires a wired provider such as a reviewer or CI pipeline).
*
* Vacuous gates (`true`, echo'd synthetic approvals, placeholder ci-pipeline
* commands) are forbidden: a stage whose gate has no real implementation
* fails closed instead of passing.
*/
export const STAGE_SPECS: Record<string, StageSpec> = {
'00-intake': {
number: '00',
title: 'Forge Intake',
dispatch: 'exec',
type: 'research',
gate: 'none',
promptFile: '00-intake.md',
qualityGates: [],
},
'00b-discovery': {
number: '00b',
title: 'Forge Discovery',
dispatch: 'exec',
type: 'research',
gate: 'discovery-complete',
promptFile: '00b-discovery.md',
qualityGates: [
{
kind: 'authority',
capability: 'discovery-complete',
reason: 'discovery completion is attested by an authority; no mechanical check exists',
},
],
},
'01-board': {
number: '01',
title: 'Forge Board Review',
dispatch: 'exec',
type: 'review',
gate: 'board-approval',
promptFile: '01-board.md',
qualityGates: [
{
kind: 'authority',
capability: 'board-approval',
reason: 'board approval is a board/human decision; no mechanical gate exists',
},
],
},
'01b-brief-analyzer': {
number: '01b',
title: 'Forge Brief Analyzer',
dispatch: 'exec',
type: 'research',
gate: 'brief-analysis-complete',
promptFile: '01-board.md',
qualityGates: [
{
kind: 'authority',
capability: 'brief-analysis-complete',
reason: 'brief analysis completion is attested by an authority; no mechanical check exists',
},
],
},
'02-planning-1': {
number: '02',
title: 'Forge Planning 1',
dispatch: 'exec',
type: 'research',
gate: 'architecture-approval',
promptFile: '02-planning-1-architecture.md',
qualityGates: [
{
kind: 'authority',
capability: 'architecture-approval',
reason: 'ADR approval requires authority sign-off; no mechanical check exists',
},
],
},
'03-planning-2': {
number: '03',
title: 'Forge Planning 2',
dispatch: 'exec',
type: 'research',
gate: 'implementation-approval',
promptFile: '03-planning-2-implementation.md',
qualityGates: [
{
kind: 'authority',
capability: 'implementation-approval',
reason:
'implementation spec approval requires authority sign-off; no mechanical check exists',
},
],
},
'04-planning-3': {
number: '04',
title: 'Forge Planning 3',
dispatch: 'exec',
type: 'research',
gate: 'decomposition-approval',
promptFile: '04-planning-3-decomposition.md',
qualityGates: [
{
kind: 'authority',
capability: 'decomposition-approval',
reason:
'task decomposition approval requires authority sign-off; no mechanical check exists',
},
],
},
'05-coding': {
number: '05',
title: 'Forge Coding',
dispatch: 'yolo',
type: 'coding',
gate: 'lint-build-test',
promptFile: '05-coding.md',
qualityGates: ['pnpm lint', 'pnpm build', 'pnpm test'],
},
'06-review': {
number: '06',
title: 'Forge Review',
dispatch: 'exec',
type: 'review',
gate: 'review-pass',
promptFile: '06-review.md',
qualityGates: [
{
kind: 'provider',
capability: 'reviewer',
reason:
'review verdicts require a wired reviewer provider; synthetic approvals are not permitted',
},
],
},
'07-remediate': {
number: '07',
title: 'Forge Remediation',
dispatch: 'yolo',
type: 'coding',
gate: 're-review',
promptFile: '07-remediate.md',
qualityGates: [
{
kind: 'authority',
capability: 're-review',
reason: 'remediation re-review is an approval-based gate; no mechanical check exists',
},
],
},
'08-test': {
number: '08',
title: 'Forge Test Validation',
dispatch: 'exec',
type: 'review',
gate: 'tests-green',
promptFile: '08-test.md',
qualityGates: ['pnpm test'],
},
'09-deploy': {
number: '09',
title: 'Forge Deploy',
dispatch: 'exec',
type: 'deploy',
gate: 'deploy-verification',
promptFile: '09-deploy.md',
qualityGates: [
{
kind: 'provider',
capability: 'ci-pipeline',
reason: 'deploy verification requires a wired CI pipeline provider',
},
],
},
};
/** Ordered stage sequence — full pipeline. */
export const STAGE_SEQUENCE = [
'00-intake',
'00b-discovery',
'01-board',
'01b-brief-analyzer',
'02-planning-1',
'03-planning-2',
'04-planning-3',
'05-coding',
'06-review',
'07-remediate',
'08-test',
'09-deploy',
];
/** Per-stage timeout in seconds. */
export const STAGE_TIMEOUTS: Record<string, number> = {
'00-intake': 120,
'00b-discovery': 300,
'01-board': 120,
'01b-brief-analyzer': 300,
'02-planning-1': 600,
'03-planning-2': 600,
'04-planning-3': 600,
'05-coding': 3600,
'06-review': 600,
'07-remediate': 3600,
'08-test': 600,
'09-deploy': 600,
};
/** Human-readable labels per stage. */
export const STAGE_LABELS: Record<string, string> = {
'00-intake': 'INTAKE',
'00b-discovery': 'DISCOVERY',
'01-board': 'BOARD',
'01b-brief-analyzer': 'BRIEF ANALYZER',
'02-planning-1': 'PLANNING 1',
'03-planning-2': 'PLANNING 2',
'04-planning-3': 'PLANNING 3',
'05-coding': 'CODING',
'06-review': 'REVIEW',
'07-remediate': 'REMEDIATE',
'08-test': 'TEST',
'09-deploy': 'DEPLOY',
};
/** Keywords that indicate a strategic brief. */
export const STRATEGIC_KEYWORDS = new Set([
'security',
'pricing',
'architecture',
'integration',
'budget',
'strategy',
'compliance',
'migration',
'partnership',
'launch',
]);
/** Keywords that indicate a technical brief. */
export const TECHNICAL_KEYWORDS = new Set([
'bugfix',
'bug',
'refactor',
'ui',
'style',
'tweak',
'typo',
'lint',
'cleanup',
'rename',
'hotfix',
'patch',
'css',
'format',
]);
+46
View File
@@ -0,0 +1,46 @@
/**
* Typed fail-closed capability errors (SDLC-D-035).
*
* A Forge run must fail closed when a required capability (executor, reviewer
* provider, CI pipeline, authority sign-off) is missing. These typed errors
* name the missing capability so callers can distinguish "not wired" from
* ordinary execution failures.
*/
/** Closed set of typed Forge capability error codes. */
export const FORGE_ERROR_CODES = [
'FORGE_NO_EXECUTOR',
'FORGE_NO_REVIEWER',
'FORGE_NO_CI_PIPELINE',
'FORGE_NO_PROVIDER',
'FORGE_AUTHORITY_REQUIRED',
] as const;
export type ForgeErrorCode = (typeof FORGE_ERROR_CODES)[number];
/** Raised when a required capability is missing and the pipeline must fail closed. */
export class ForgeCapabilityError extends Error {
/** Typed error code from the closed FORGE_ERROR_CODES set. */
readonly code: ForgeErrorCode;
/** The missing capability, e.g. `task-executor`, `reviewer`, `board-approval`. */
readonly capability: string;
constructor(code: ForgeErrorCode, capability: string, message: string) {
super(message);
this.name = 'ForgeCapabilityError';
this.code = code;
this.capability = capability;
}
}
/** Map a provider gate capability to its typed error code. */
export function providerErrorCode(capability: string): ForgeErrorCode {
switch (capability) {
case 'reviewer':
return 'FORGE_NO_REVIEWER';
case 'ci-pipeline':
return 'FORGE_NO_CI_PIPELINE';
default:
return 'FORGE_NO_PROVIDER';
}
}
+111
View File
@@ -0,0 +1,111 @@
// Types
export type {
StageDispatch,
StageType,
StageSpec,
BriefClass,
ClassSource,
ForgeOutcome,
AuthorityGate,
ProviderGate,
ForgeGate,
ForgeGateResult,
ForgeTaskResult,
RunMode,
StageStatus,
RunManifest,
ForgeTaskStatus,
ForgeTask,
TaskExecutor,
BoardPersona,
PersonaReview,
BoardSynthesis,
ForgeConfig,
PipelineOptions,
PipelineResult,
} from './types.js';
// Constants
export {
PACKAGE_ROOT,
PIPELINE_DIR,
STAGE_SPECS,
STAGE_SEQUENCE,
STAGE_TIMEOUTS,
STAGE_LABELS,
STRATEGIC_KEYWORDS,
TECHNICAL_KEYWORDS,
} from './constants.js';
// Brief classifier
export {
classifyBrief,
parseBriefFrontmatter,
determineBriefClass,
stagesForClass,
} from './brief-classifier.js';
// Persona loader
export {
slugify,
personaNameFromMarkdown,
loadBoardPersonas,
loadPersonaOverrides,
loadForgeConfig,
getEffectivePersonas,
} from './persona-loader.js';
// Stage adapter
export {
stageTaskId,
stageDir,
stageBriefPath,
stageResultPath,
loadStagePrompt,
buildStageBrief,
writeStageBrief,
mapStageToTask,
} from './stage-adapter.js';
// Board tasks
export {
buildPersonaBrief,
writePersonaBrief,
personaResultPath,
synthesisResultPath,
generateBoardTasks,
synthesizeReviews,
} from './board-tasks.js';
// Pipeline runner
export {
generateRunId,
saveManifest,
loadManifest,
selectStages,
runPipeline,
resumePipeline,
getPipelineStatus,
} from './pipeline-runner.js';
// Fail-closed errors and typed outcome model (SDLC-D-035)
export { FORGE_ERROR_CODES, ForgeCapabilityError, providerErrorCode } from './errors.js';
export type { ForgeErrorCode } from './errors.js';
export {
isSatisfyingOutcome,
isCapabilityGate,
isCommandGate,
gateLabel,
uniformGateResults,
simulatedGateResults,
waitingGateResults,
blockedGateResults,
evaluateStageGates,
} from './outcomes.js';
export type { StageEvaluation } from './outcomes.js';
// Simulated executor (explicit --simulate only)
export { createSimulatedExecutor } from './simulated-executor.js';
// CLI
export { registerForgeCommand } from './cli.js';
+147
View File
@@ -0,0 +1,147 @@
import type { GateEntry } from '@mosaicstack/macp';
import type {
AuthorityGate,
ForgeGate,
ForgeGateResult,
ForgeOutcome,
ForgeTaskResult,
ProviderGate,
} from './types.js';
/**
* Gate and dependency satisfaction predicate (SDLC-D-035).
*
* ONLY a verified `passed` outcome satisfies. Every other member of the closed
* outcome set — including `simulated` — is non-satisfying, so a simulated or
* authority-blocked result can never be read as success-by-verification.
*/
export function isSatisfyingOutcome(outcome: ForgeOutcome): boolean {
return outcome === 'passed';
}
/** Whether a gate is an authority or provider gate (capability-based, command-less). */
export function isCapabilityGate(gate: ForgeGate): gate is AuthorityGate | ProviderGate {
if (typeof gate !== 'object' || gate === null) return false;
const kind = (gate as Record<string, unknown>)['kind'];
return kind === 'authority' || kind === 'provider';
}
/** Whether a gate definition carries a real command a mechanical runner can execute. */
export function isCommandGate(gate: ForgeGate): gate is string | GateEntry {
if (typeof gate === 'string') {
return gate.trim().length > 0;
}
if (isCapabilityGate(gate)) {
// Authority and provider gates are satisfied by a capability, not a command.
return false;
}
return typeof gate.command === 'string' && gate.command.trim().length > 0;
}
/** Typed label identifying a gate in results and logs. */
export function gateLabel(gate: ForgeGate): string {
if (typeof gate === 'string') return gate;
if (isCapabilityGate(gate)) return `${gate.kind}:${gate.capability}`;
return gate.command || gate.type || 'unnamed-gate';
}
/** Reason string stamped on every simulated gate result. */
export const SIMULATED_GATE_REASON =
'simulated execution (--simulate): gate was not evaluated by a real implementation';
/** Build typed gate results with a uniform outcome for a stage's declared gates. */
export function uniformGateResults(
gates: ForgeGate[],
outcome: ForgeOutcome,
reason: string,
): ForgeGateResult[] {
return gates.map((gate) => ({ gate: gateLabel(gate), outcome, reason }));
}
/** Typed simulated gate results — used exclusively in `--simulate` runs. */
export function simulatedGateResults(gates: ForgeGate[]): ForgeGateResult[] {
return uniformGateResults(gates, 'simulated', SIMULATED_GATE_REASON);
}
/** Typed waiting-for-authority gate results for approval-based stages. */
export function waitingGateResults(gates: ForgeGate[], reason: string): ForgeGateResult[] {
return uniformGateResults(gates, 'waiting-for-authority', reason);
}
/** Typed blocked gate results for stages whose provider capability is not wired. */
export function blockedGateResults(gates: ForgeGate[], reason: string): ForgeGateResult[] {
return uniformGateResults(gates, 'blocked', reason);
}
/** Outcome of evaluating a completed stage in normal mode. */
export interface StageEvaluation {
outcome: ForgeOutcome;
reason: string;
gateResults: ForgeGateResult[];
}
/**
* Evaluate a stage's declared gates against the executor's typed result.
*
* Fail-closed mapping:
* - a `simulated` task or gate outcome in normal mode maps to `error`
* - a missing gate result for a required command gate maps to `blocked`
* - a non-passing task outcome propagates as the stage outcome
* - only verified `passed` task and gate outcomes yield a `passed` stage
*/
export function evaluateStageGates(
stageName: string,
gates: ForgeGate[],
result: ForgeTaskResult,
): StageEvaluation {
const gateResults = result.gate_results ?? [];
if (result.outcome === 'simulated') {
return {
outcome: 'error',
reason: `executor reported a simulated outcome for stage '${stageName}' in normal mode — refusing to treat simulated results as verified`,
gateResults,
};
}
if (!isSatisfyingOutcome(result.outcome)) {
return {
outcome: result.outcome,
reason: `task outcome is '${result.outcome}': ${result.reason}`,
gateResults,
};
}
for (const gate of gates) {
// Authority and provider gates are pre-flighted before execution; they have
// no mechanical result to verify here.
if (!isCommandGate(gate)) continue;
const label = gateLabel(gate);
const gateResult = gateResults.find((r) => r.gate === label);
if (!gateResult) {
return {
outcome: 'blocked',
reason: `no gate result was reported for required gate '${label}' (stage '${stageName}')`,
gateResults,
};
}
if (!isSatisfyingOutcome(gateResult.outcome)) {
return {
outcome: gateResult.outcome === 'simulated' ? 'error' : gateResult.outcome,
reason: `gate '${label}' outcome is '${gateResult.outcome}': ${gateResult.reason}`,
gateResults,
};
}
}
return {
outcome: 'passed',
reason:
gates.length === 0
? "stage declares no gates; task outcome 'passed' accepted"
: 'all declared gates verified passed',
gateResults,
};
}
+153
View File
@@ -0,0 +1,153 @@
import fs from 'node:fs';
import path from 'node:path';
import { PIPELINE_DIR } from './constants.js';
import type { BoardPersona, ForgeConfig } from './types.js';
/** Board agents directory within the pipeline assets. */
const BOARD_AGENTS_DIR = path.join(PIPELINE_DIR, 'agents', 'board');
/**
* Convert a string to a URL-safe slug.
*/
export function slugify(value: string): string {
const slug = value
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
return slug || 'persona';
}
/**
* Extract persona name from the first heading line in markdown.
* Strips trailing em-dash or hyphen-separated subtitle.
*/
export function personaNameFromMarkdown(markdown: string, fallback: string): string {
const firstLine = markdown.trim().split('\n')[0] ?? fallback;
let heading = firstLine.replace(/^#+\s*/, '').trim();
if (heading.includes('—')) {
heading = heading.split('—')[0]!.trim();
} else if (heading.includes('-')) {
heading = heading.split('-')[0]!.trim();
}
return heading || fallback;
}
/**
* Load board personas from the pipeline assets directory.
* Returns sorted list of persona definitions.
*/
export function loadBoardPersonas(boardDir: string = BOARD_AGENTS_DIR): BoardPersona[] {
if (!fs.existsSync(boardDir)) return [];
const files = fs
.readdirSync(boardDir)
.filter((f) => f.endsWith('.md'))
.sort();
return files.map((file) => {
const filePath = path.join(boardDir, file);
const content = fs.readFileSync(filePath, 'utf-8').trim();
const stem = path.basename(file, '.md');
return {
name: personaNameFromMarkdown(content, stem.toUpperCase()),
slug: slugify(stem),
description: content,
path: path.relative(PIPELINE_DIR, filePath),
};
});
}
/**
* Load project-level persona overrides from {projectRoot}/.forge/personas/.
* Returns a map of slug → override content.
*/
export function loadPersonaOverrides(projectRoot: string): Record<string, string> {
const overridesDir = path.join(projectRoot, '.forge', 'personas');
if (!fs.existsSync(overridesDir)) return {};
const result: Record<string, string> = {};
const files = fs.readdirSync(overridesDir).filter((f) => f.endsWith('.md'));
for (const file of files) {
const slug = slugify(path.basename(file, '.md'));
result[slug] = fs.readFileSync(path.join(overridesDir, file), 'utf-8').trim();
}
return result;
}
/**
* Load project-level Forge config from {projectRoot}/.forge/config.yaml.
* Parses simple YAML key-value pairs via regex (no YAML dependency).
*/
export function loadForgeConfig(projectRoot: string): ForgeConfig {
const configPath = path.join(projectRoot, '.forge', 'config.yaml');
if (!fs.existsSync(configPath)) return {};
const text = fs.readFileSync(configPath, 'utf-8');
const config: ForgeConfig = {};
// Parse simple list values under board: and specialists: sections
const boardAdditional = parseYamlList(text, 'additionalMembers');
const boardSkip = parseYamlList(text, 'skipMembers');
const specialistsInclude = parseYamlList(text, 'alwaysInclude');
if (boardAdditional.length > 0 || boardSkip.length > 0) {
config.board = {};
if (boardAdditional.length > 0) config.board.additionalMembers = boardAdditional;
if (boardSkip.length > 0) config.board.skipMembers = boardSkip;
}
if (specialistsInclude.length > 0) {
config.specialists = { alwaysInclude: specialistsInclude };
}
return config;
}
/**
* Parse a simple YAML list under a given key name.
*/
function parseYamlList(text: string, key: string): string[] {
const pattern = new RegExp(`${key}:\\s*\\n((?:\\s+-\\s+.+\\n?)*)`, 'm');
const match = text.match(pattern);
if (!match?.[1]) return [];
return match[1]
.split('\n')
.map((line) => line.trim().replace(/^-\s+/, '').trim())
.filter(Boolean);
}
/**
* Get effective board personas after applying project overrides and config.
*
* - Base personas loaded from pipeline/agents/board/
* - Project overrides from {projectRoot}/.forge/personas/ APPENDED to base
* - Config skipMembers removes personas; additionalMembers adds custom paths
*/
export function getEffectivePersonas(projectRoot: string, boardDir?: string): BoardPersona[] {
let personas = loadBoardPersonas(boardDir);
const overrides = loadPersonaOverrides(projectRoot);
const config = loadForgeConfig(projectRoot);
// Apply overrides — append project content to base persona description
personas = personas.map((p) => {
const override = overrides[p.slug];
if (override) {
return { ...p, description: `${p.description}\n\n${override}` };
}
return p;
});
// Apply config: skip members
if (config.board?.skipMembers?.length) {
const skip = new Set(config.board.skipMembers.map((s) => slugify(s)));
personas = personas.filter((p) => !skip.has(p.slug));
}
return personas;
}
+476
View File
@@ -0,0 +1,476 @@
import fs from 'node:fs';
import path from 'node:path';
import { STAGE_SEQUENCE, STAGE_SPECS } from './constants.js';
import { determineBriefClass, stagesForClass } from './brief-classifier.js';
import { ForgeCapabilityError, providerErrorCode } from './errors.js';
import {
blockedGateResults,
evaluateStageGates,
isCapabilityGate,
simulatedGateResults,
waitingGateResults,
} from './outcomes.js';
import { mapStageToTask } from './stage-adapter.js';
import { createSimulatedExecutor } from './simulated-executor.js';
import type {
ForgeTask,
ForgeTaskResult,
PipelineOptions,
PipelineResult,
RunManifest,
RunMode,
StageStatus,
TaskExecutor,
} from './types.js';
/** Reason stamped on stages that complete under explicit simulation. */
const SIMULATED_STAGE_REASON =
'simulated execution (--simulate): stage was not executed by a real executor';
/**
* Generate a timestamp-based run ID.
*/
export function generateRunId(): string {
const now = new Date();
const pad = (n: number, w = 2) => String(n).padStart(w, '0');
return [
now.getUTCFullYear(),
pad(now.getUTCMonth() + 1),
pad(now.getUTCDate()),
'-',
pad(now.getUTCHours()),
pad(now.getUTCMinutes()),
pad(now.getUTCSeconds()),
].join('');
}
/**
* Get the ISO timestamp for now.
*/
function nowISO(): string {
return new Date().toISOString();
}
/**
* Create and persist a run manifest.
*/
function createManifest(opts: {
runId: string;
briefPath: string;
codebase: string;
briefClass: RunManifest['briefClass'];
classSource: RunManifest['classSource'];
forceBoard: boolean;
mode: RunMode;
runDir: string;
}): RunManifest {
const ts = nowISO();
const manifest: RunManifest = {
runId: opts.runId,
brief: opts.briefPath,
codebase: opts.codebase,
briefClass: opts.briefClass,
classSource: opts.classSource,
forceBoard: opts.forceBoard,
mode: opts.mode,
createdAt: ts,
updatedAt: ts,
currentStage: '',
status: 'in_progress',
stages: {},
};
saveManifest(opts.runDir, manifest);
return manifest;
}
/**
* Save a manifest to disk.
*/
export function saveManifest(runDir: string, manifest: RunManifest): void {
manifest.updatedAt = nowISO();
const manifestPath = path.join(runDir, 'manifest.json');
fs.mkdirSync(path.dirname(manifestPath), { recursive: true });
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n', 'utf-8');
}
/**
* Load a manifest from disk.
*/
export function loadManifest(runDir: string): RunManifest {
const manifestPath = path.join(runDir, 'manifest.json');
if (!fs.existsSync(manifestPath)) {
throw new Error(`manifest.json not found: ${manifestPath}`);
}
return JSON.parse(fs.readFileSync(manifestPath, 'utf-8')) as RunManifest;
}
/**
* Select and validate stages, optionally skipping to a specific stage.
*/
export function selectStages(stages?: string[], skipTo?: string): string[] {
const selected = stages ?? [...STAGE_SEQUENCE];
const unknown = selected.filter((s) => !STAGE_SEQUENCE.includes(s));
if (unknown.length > 0) {
throw new Error(`Unknown Forge stages requested: ${unknown.join(', ')}`);
}
if (!skipTo) return selected;
if (!selected.includes(skipTo)) {
throw new Error(`skip_to stage '${skipTo}' is not present in the selected stage list`);
}
const skipIndex = selected.indexOf(skipTo);
return selected.slice(skipIndex);
}
/**
* Fail closed when the required executor capability is missing (SDLC-D-035).
*/
function requireExecutor(executor: TaskExecutor | undefined, simulate: boolean): TaskExecutor {
if (executor) return executor;
if (simulate) return createSimulatedExecutor({ log: false });
throw new ForgeCapabilityError(
'FORGE_NO_EXECUTOR',
'task-executor',
'no task executor is wired; refusing to run the pipeline with a stub executor (fail closed). ' +
'Pass --simulate to opt into explicitly simulated execution.',
);
}
/**
* Pre-flight a stage's gates in normal mode (fail closed, SDLC-D-035).
*
* - authority gates: record a typed `waiting-for-authority` stage result and
* raise FORGE_AUTHORITY_REQUIRED — approval-based gates never pass vacuously.
* - provider gates: record a typed `blocked` stage result and raise the typed
* capability error for the missing provider.
*
* Returns the stage status to record when the pre-flight blocks, or undefined
* when the stage may proceed.
*/
function preflightStageGates(
stageName: string,
manifest: RunManifest,
): { status: StageStatus; error: ForgeCapabilityError } | undefined {
const spec = STAGE_SPECS[stageName];
if (!spec) throw new Error(`Unknown Forge stage: ${stageName}`);
for (const gate of spec.qualityGates) {
if (!isCapabilityGate(gate)) continue;
const startedAt = manifest.stages[stageName]?.startedAt;
const completedAt = nowISO();
if (gate.kind === 'authority') {
const reason = `gate '${gate.capability}' requires authority sign-off; no mechanical implementation exists (${gate.reason})`;
return {
status: {
status: 'waiting-for-authority',
reason,
startedAt,
completedAt,
gateResults: waitingGateResults(spec.qualityGates, reason),
},
error: new ForgeCapabilityError(
'FORGE_AUTHORITY_REQUIRED',
gate.capability,
`stage '${stageName}' is blocked on authority gate '${gate.capability}': ${gate.reason}. ` +
'The pipeline fails closed instead of passing vacuously. Record the approval out-of-band ' +
'or run with --simulate for explicitly simulated execution.',
),
};
}
const reason = `gate '${gate.capability}' requires provider '${gate.capability}' and none is wired (${gate.reason})`;
return {
status: {
status: 'blocked',
reason,
startedAt,
completedAt,
gateResults: blockedGateResults(spec.qualityGates, reason),
},
error: new ForgeCapabilityError(
providerErrorCode(gate.capability),
gate.capability,
`stage '${stageName}' requires provider '${gate.capability}' which is not wired: ${gate.reason}. ` +
'The pipeline fails closed instead of passing vacuously.',
),
};
}
return undefined;
}
/**
* Execute the given stage tasks sequentially, updating the manifest.
*
* Normal mode requires a real executor and evaluates every declared command
* gate through the typed outcome model; any non-verified result fails closed.
* Simulate mode types every stage and gate result as `simulated`.
*/
async function executeStages(opts: {
manifest: RunManifest;
runDir: string;
tasks: ForgeTask[];
stageNames: string[];
executor: TaskExecutor;
simulate: boolean;
}): Promise<void> {
const { manifest, runDir, tasks, stageNames, executor, simulate } = opts;
for (let i = 0; i < tasks.length; i++) {
const task = tasks[i]!;
const stageName = stageNames[i]!;
const spec = STAGE_SPECS[stageName];
if (!spec) throw new Error(`Unknown Forge stage: ${stageName}`);
// Update manifest: stage in progress
manifest.currentStage = stageName;
manifest.stages[stageName] = {
status: 'in_progress',
startedAt: nowISO(),
};
saveManifest(runDir, manifest);
// Fail-closed pre-flight (normal mode only): authority/provider gates have
// no mechanical implementation and must never pass vacuously.
if (!simulate) {
const blocked = preflightStageGates(stageName, manifest);
if (blocked) {
manifest.stages[stageName] = blocked.status;
manifest.status =
blocked.status.status === 'waiting-for-authority' ? 'waiting-for-authority' : 'failed';
saveManifest(runDir, manifest);
throw blocked.error;
}
}
let result: ForgeTaskResult;
try {
await executor.submitTask(task);
result = await executor.waitForCompletion(task.id, task.timeoutSeconds * 1000);
} catch (error) {
// Process errors (including timeouts) map to the fail-closed `error` outcome.
const reason = error instanceof Error ? error.message : String(error);
manifest.stages[stageName] = {
status: 'error',
reason: `executor error: ${reason}`,
startedAt: manifest.stages[stageName]?.startedAt,
completedAt: nowISO(),
gateResults: [],
};
manifest.status = 'failed';
saveManifest(runDir, manifest);
throw error instanceof Error ? error : new Error(reason);
}
if (simulate) {
manifest.stages[stageName] = {
status: 'simulated',
reason: SIMULATED_STAGE_REASON,
startedAt: manifest.stages[stageName]?.startedAt,
completedAt: nowISO(),
gateResults: simulatedGateResults(spec.qualityGates),
};
saveManifest(runDir, manifest);
continue;
}
const evaluation = evaluateStageGates(stageName, spec.qualityGates, result);
manifest.stages[stageName] = {
status: evaluation.outcome,
reason: evaluation.reason,
startedAt: manifest.stages[stageName]?.startedAt,
completedAt: nowISO(),
gateResults: evaluation.gateResults,
};
if (evaluation.outcome !== 'passed') {
manifest.status =
evaluation.outcome === 'waiting-for-authority' ? 'waiting-for-authority' : 'failed';
saveManifest(runDir, manifest);
throw new Error(`Stage ${stageName} ${evaluation.outcome}: ${evaluation.reason}`);
}
saveManifest(runDir, manifest);
}
}
/**
* Run the Forge pipeline.
*
* 1. Fail closed unless a real executor is wired or simulation is explicit
* 2. Classify the brief
* 3. Generate a run ID and create run directory
* 4. Map stages to tasks and submit to TaskExecutor
* 5. Track manifest with typed stage outcomes
* 6. Return pipeline result
*/
export async function runPipeline(
briefPath: string,
projectRoot: string,
options: PipelineOptions,
): Promise<PipelineResult> {
const simulate = options.simulate ?? false;
const executor = requireExecutor(options.executor, simulate);
const mode: RunMode = simulate ? 'simulated' : 'normal';
const resolvedRoot = path.resolve(projectRoot);
const resolvedBrief = path.resolve(briefPath);
const briefContent = fs.readFileSync(resolvedBrief, 'utf-8');
// Classify brief
const { briefClass, classSource } = determineBriefClass(briefContent, options.briefClass);
// Determine stages
const classStages = options.stages ?? stagesForClass(briefClass, options.forceBoard);
const selectedStages = selectStages(classStages, options.skipTo);
// Create run directory
const runId = generateRunId();
const runDir = path.join(resolvedRoot, '.forge', 'runs', runId);
fs.mkdirSync(runDir, { recursive: true });
// Create manifest
const manifest = createManifest({
runId,
briefPath: resolvedBrief,
codebase: options.codebase ?? '',
briefClass,
classSource,
forceBoard: options.forceBoard ?? false,
mode,
runDir,
});
// Map stages to tasks
const tasks: ForgeTask[] = [];
for (let i = 0; i < selectedStages.length; i++) {
const stageName = selectedStages[i]!;
const task = mapStageToTask({
stageName,
briefContent,
projectRoot: resolvedRoot,
runId,
runDir,
});
// Override dependency chain for selected (possibly filtered) stages
if (i > 0) {
task.dependsOn = [tasks[i - 1]!.id];
} else {
delete task.dependsOn;
}
tasks.push(task);
}
// Execute stages
await executeStages({ manifest, runDir, tasks, stageNames: selectedStages, executor, simulate });
// All stages reached a terminal state for this mode
manifest.status = simulate ? 'simulated' : 'completed';
saveManifest(runDir, manifest);
return {
runId,
briefPath: resolvedBrief,
projectRoot: resolvedRoot,
runDir,
taskIds: tasks.map((t) => t.id),
stages: selectedStages,
manifest,
};
}
/**
* Resume a pipeline from the last non-passed stage.
*/
export async function resumePipeline(
runDir: string,
executor?: TaskExecutor,
options?: { simulate?: boolean },
): Promise<PipelineResult> {
const simulate = options?.simulate ?? false;
const wiredExecutor = requireExecutor(executor, simulate);
const mode: RunMode = simulate ? 'simulated' : 'normal';
const manifest = loadManifest(runDir);
const resolvedRoot = path.dirname(path.dirname(path.dirname(runDir))); // .forge/runs/{id} → project root
const briefContent = fs.readFileSync(manifest.brief, 'utf-8');
const allStages = stagesForClass(manifest.briefClass, manifest.forceBoard);
manifest.mode = mode;
// Find first non-satisfying stage (only a verified `passed` counts as done;
// simulated and waiting-for-authority stages are re-run).
const resumeFrom = allStages.find((s) => manifest.stages[s]?.status !== 'passed');
if (!resumeFrom) {
manifest.status = mode === 'simulated' ? 'simulated' : 'completed';
saveManifest(runDir, manifest);
return {
runId: manifest.runId,
briefPath: manifest.brief,
projectRoot: resolvedRoot,
runDir,
taskIds: [],
stages: allStages,
manifest,
};
}
const remainingStages = selectStages(allStages, resumeFrom);
manifest.status = 'in_progress';
const tasks: ForgeTask[] = [];
for (let i = 0; i < remainingStages.length; i++) {
const stageName = remainingStages[i]!;
const task = mapStageToTask({
stageName,
briefContent,
projectRoot: resolvedRoot,
runId: manifest.runId,
runDir,
});
if (i > 0) {
task.dependsOn = [tasks[i - 1]!.id];
} else {
delete task.dependsOn;
}
tasks.push(task);
}
await executeStages({
manifest,
runDir,
tasks,
stageNames: remainingStages,
executor: wiredExecutor,
simulate,
});
manifest.status = simulate ? 'simulated' : 'completed';
saveManifest(runDir, manifest);
return {
runId: manifest.runId,
briefPath: manifest.brief,
projectRoot: resolvedRoot,
runDir,
taskIds: tasks.map((t) => t.id),
stages: remainingStages,
manifest,
};
}
/**
* Get the status of a pipeline run.
*/
export function getPipelineStatus(runDir: string): RunManifest {
return loadManifest(runDir);
}
@@ -0,0 +1,32 @@
import type { ForgeTask, ForgeTaskResult, TaskExecutor } from './types.js';
/**
* Simulated executor — used ONLY when the caller explicitly passes --simulate.
*
* It submits no real work and returns typed `simulated` results so a simulated
* run can never be confused with a verified one. In normal mode (no --simulate)
* the CLI refuses to run at all with FORGE_NO_EXECUTOR instead of wiring this
* stub (fail closed, SDLC-D-035).
*/
export function createSimulatedExecutor(options?: { log?: boolean }): TaskExecutor {
const log = options?.log ?? true;
return {
async submitTask(task: ForgeTask) {
if (log) console.log(` [forge:simulated] stage submitted: ${task.id} (${task.title})`);
},
async waitForCompletion(taskId: string): Promise<ForgeTaskResult> {
if (log) console.log(` [forge:simulated] stage complete: ${taskId}`);
return {
task_id: taskId,
outcome: 'simulated',
reason: 'no executor wired; simulated execution requested via --simulate',
completed_at: new Date().toISOString(),
exit_code: 0,
gate_results: [],
};
},
async getTaskStatus() {
return 'completed' as const;
},
};
}
+169
View File
@@ -0,0 +1,169 @@
import fs from 'node:fs';
import path from 'node:path';
import { PIPELINE_DIR, STAGE_SEQUENCE, STAGE_SPECS, STAGE_TIMEOUTS } from './constants.js';
import type { ForgeTask } from './types.js';
/**
* Generate a deterministic task ID for a stage within a run.
*/
export function stageTaskId(runId: string, stageName: string): string {
const spec = STAGE_SPECS[stageName];
if (!spec) throw new Error(`Unknown Forge stage: ${stageName}`);
return `FORGE-${runId}-${spec.number}`;
}
/**
* Get the directory for a stage's artifacts within a run.
*/
export function stageDir(runDir: string, stageName: string): string {
return path.join(runDir, stageName);
}
/**
* Get the brief path for a stage within a run.
*/
export function stageBriefPath(runDir: string, stageName: string): string {
return path.join(stageDir(runDir, stageName), 'brief.md');
}
/**
* Get the result path for a stage within a run.
*/
export function stageResultPath(runDir: string, stageName: string): string {
return path.join(stageDir(runDir, stageName), 'result.json');
}
/**
* Load a stage prompt from the pipeline assets.
*/
export function loadStagePrompt(promptFile: string): string {
const promptPath = path.join(PIPELINE_DIR, 'stages', promptFile);
return fs.readFileSync(promptPath, 'utf-8').trim();
}
/**
* Build the brief content for a stage, combining source brief with stage definition.
*/
export function buildStageBrief(opts: {
stageName: string;
stagePrompt: string;
briefContent: string;
projectRoot: string;
runId: string;
runDir: string;
}): string {
return [
`# Forge Pipeline Stage: ${opts.stageName}`,
'',
`Run ID: ${opts.runId}`,
`Project Root: ${opts.projectRoot}`,
'',
'## Source Brief',
opts.briefContent.trim(),
'',
`Read previous stage results from ${opts.runDir}/ before proceeding.`,
'',
'## Stage Definition',
opts.stagePrompt,
'',
].join('\n');
}
/**
* Write the stage brief to disk and return the path.
*/
export function writeStageBrief(opts: {
stageName: string;
briefContent: string;
projectRoot: string;
runId: string;
runDir: string;
}): string {
const spec = STAGE_SPECS[opts.stageName];
if (!spec) throw new Error(`Unknown Forge stage: ${opts.stageName}`);
const briefPath = stageBriefPath(opts.runDir, opts.stageName);
fs.mkdirSync(path.dirname(briefPath), { recursive: true });
const stagePrompt = loadStagePrompt(spec.promptFile);
const content = buildStageBrief({
stageName: opts.stageName,
stagePrompt,
briefContent: opts.briefContent,
projectRoot: opts.projectRoot,
runId: opts.runId,
runDir: opts.runDir,
});
fs.writeFileSync(briefPath, content, 'utf-8');
return briefPath;
}
/**
* Convert a Forge stage into a ForgeTask ready for submission to a TaskExecutor.
*/
export function mapStageToTask(opts: {
stageName: string;
briefContent: string;
projectRoot: string;
runId: string;
runDir: string;
}): ForgeTask {
const { stageName, briefContent, projectRoot, runId, runDir } = opts;
const spec = STAGE_SPECS[stageName];
if (!spec) throw new Error(`Unknown Forge stage: ${stageName}`);
const timeout = STAGE_TIMEOUTS[stageName];
if (timeout === undefined) {
throw new Error(`Missing stage timeout for Forge stage: ${stageName}`);
}
const briefPath = writeStageBrief({
stageName,
briefContent,
projectRoot,
runId,
runDir,
});
const resultPath = stageResultPath(runDir, stageName);
const taskId = stageTaskId(runId, stageName);
const promptPath = path.join(PIPELINE_DIR, 'stages', spec.promptFile);
const task: ForgeTask = {
id: taskId,
title: spec.title,
description: `Forge stage ${stageName} via MACP`,
status: 'pending',
dispatch: spec.dispatch,
type: spec.type,
briefPath: path.resolve(briefPath),
resultPath: path.resolve(resultPath),
timeoutSeconds: timeout,
qualityGates: [...spec.qualityGates],
metadata: {
runId,
runDir,
stageName,
stageNumber: spec.number,
gate: spec.gate,
promptPath: path.resolve(promptPath),
resultOutputPath: path.resolve(resultPath),
},
};
// Build dependency chain from stage sequence
const stageIndex = STAGE_SEQUENCE.indexOf(stageName);
if (stageIndex > 0) {
const prevStage = STAGE_SEQUENCE[stageIndex - 1]!;
task.dependsOn = [stageTaskId(runId, prevStage)];
}
// exec dispatch stages get a worktree reference
if (spec.dispatch === 'exec') {
task.worktree = path.resolve(projectRoot);
}
return task;
}
+218
View File
@@ -0,0 +1,218 @@
import type { GateEntry } from '@mosaicstack/macp';
/** Stage dispatch mode. */
export type StageDispatch = 'exec' | 'yolo' | 'pi';
/** Stage type — determines agent selection and gate requirements. */
export type StageType = 'research' | 'review' | 'coding' | 'deploy';
/**
* Typed outcome for every gate and stage evaluation — closed set (SDLC-D-035).
*
* Only `passed` means "verified by a real implementation". `simulated` is
* produced exclusively in explicit `--simulate` runs and is never satisfying.
*/
export type ForgeOutcome =
| 'passed'
| 'failed'
| 'blocked'
| 'error'
| 'waiting-for-authority'
| 'simulated'
| 'not-applicable';
/** A gate that requires authority (human/board) sign-off; no mechanical command can satisfy it. */
export interface AuthorityGate {
kind: 'authority';
capability: string;
reason: string;
}
/** A gate that requires a wired provider (e.g. an AI reviewer, CI pipeline) to evaluate. */
export interface ProviderGate {
kind: 'provider';
capability: string;
reason: string;
}
/** Forge quality gate: a real command, an authority sign-off, or a provider-backed check. */
export type ForgeGate = string | GateEntry | AuthorityGate | ProviderGate;
/** Typed result of evaluating a single quality gate. */
export interface ForgeGateResult {
gate: string;
outcome: ForgeOutcome;
reason: string;
exitCode?: number;
output?: string;
timedOut?: boolean;
}
/** Typed result of a task/stage execution returned by a TaskExecutor. */
export interface ForgeTaskResult {
task_id: string;
outcome: ForgeOutcome;
reason: string;
completed_at: string;
exit_code: number;
gate_results: ForgeGateResult[];
}
/** Stage specification — defines a single pipeline stage. */
export interface StageSpec {
number: string;
title: string;
dispatch: StageDispatch;
type: StageType;
gate: string;
promptFile: string;
qualityGates: ForgeGate[];
}
/** Brief classification. */
export type BriefClass = 'strategic' | 'technical' | 'hotfix';
/** How the brief class was determined. */
export type ClassSource = 'cli' | 'frontmatter' | 'auto';
/** Per-stage status within a run manifest. */
export interface StageStatus {
status: 'pending' | 'in_progress' | ForgeOutcome;
/** Why the stage reached its current (terminal) outcome, when applicable. */
reason?: string;
startedAt?: string;
completedAt?: string;
/** Typed per-gate results recorded alongside the stage outcome. */
gateResults?: ForgeGateResult[];
}
/** Execution mode of a run. */
export type RunMode = 'normal' | 'simulated';
/** Run manifest — persisted to disk as manifest.json. */
export interface RunManifest {
runId: string;
brief: string;
codebase: string;
briefClass: BriefClass;
classSource: ClassSource;
forceBoard: boolean;
/**
* Execution mode. `simulated` runs stub execution; their results are typed
* `simulated` and must never be read as verified success. Optional because
* manifests written before this field existed default to `normal`.
*/
mode?: RunMode;
createdAt: string;
updatedAt: string;
currentStage: string;
status:
| 'in_progress'
| 'completed'
| 'failed'
| 'interrupted'
| 'rejected'
| 'simulated'
| 'waiting-for-authority';
stages: Record<string, StageStatus>;
}
/** Task status for the executor. */
export type ForgeTaskStatus =
| 'pending'
| 'running'
| 'completed'
| 'failed'
| 'gated'
| 'escalated';
/** Task submitted to a TaskExecutor. */
export interface ForgeTask {
id: string;
title: string;
description: string;
status: ForgeTaskStatus;
type: StageType;
dispatch: StageDispatch;
briefPath: string;
resultPath: string;
timeoutSeconds: number;
qualityGates: ForgeGate[];
worktree?: string;
command?: string;
dependsOn?: string[];
dependsOnPolicy?: 'all' | 'any' | 'all_terminal';
metadata: Record<string, unknown>;
}
/** Abstract task executor — decouples from packages/coord. */
export interface TaskExecutor {
submitTask(task: ForgeTask): Promise<void>;
waitForCompletion(taskId: string, timeoutMs: number): Promise<ForgeTaskResult>;
getTaskStatus(taskId: string): Promise<ForgeTaskStatus>;
}
/** Board persona loaded from markdown. */
export interface BoardPersona {
name: string;
slug: string;
description: string;
path: string;
}
/** Board review result from a single persona. */
export interface PersonaReview {
persona: string;
verdict: 'approve' | 'reject' | 'conditional';
confidence: number;
concerns: string[];
recommendations: string[];
keyRisks: string[];
}
/** Board synthesis result merging all persona reviews. */
export interface BoardSynthesis extends PersonaReview {
reviews: PersonaReview[];
}
/** Project-level Forge configuration (.forge/config.yaml). */
export interface ForgeConfig {
board?: {
additionalMembers?: string[];
skipMembers?: string[];
};
specialists?: {
alwaysInclude?: string[];
};
}
/** Options for running a pipeline. */
export interface PipelineOptions {
briefClass?: BriefClass;
forceBoard?: boolean;
codebase?: string;
stages?: string[];
skipTo?: string;
dryRun?: boolean;
/**
* Real task executor. Required in normal mode: the pipeline fails closed
* with FORGE_NO_EXECUTOR when it is absent.
*/
executor?: TaskExecutor;
/**
* Explicit opt-in to simulated execution. Every stage and gate result is
* typed `simulated` and is never satisfying.
*/
simulate?: boolean;
}
/** Pipeline run result. */
export interface PipelineResult {
runId: string;
briefPath: string;
projectRoot: string;
runDir: string;
taskIds: string[];
stages: string[];
manifest: RunManifest;
}