Autonomous Pipeline — Function Reference
⚠ HERITAGE EXTRACTION — donor AMS autonomous pipeline (Wave 8 quarantine)
This file extracts the donor AMS autonomous pipeline from
projects/unified-mcp/src/controllers/autonomous.js(deleted R53). The 7-phase state machine described below (INIT → GATHER → ANALYZE → PLAN → APPLY → VERIFY → DONE) is the donor surface; Phase 0 Colibri’s β Task Pipeline is an 8-state FSM (INIT → GATHER → ANALYZE → PLAN → APPLY → VERIFY → DONE+CANCELLED) defined in../../concepts/β-task-pipeline.md, and there is noamsAutonomousRuncontroller, noautonomous_sessionstable, and nosrc/controllers/autonomous/sub-modules in Phase 0.The header lists this file under concept ε; that is a donor classification. Phase 0 ε is the Skill Registry with a single tool (
skill_list), not a runtime pipeline. The Phase 0 ε truth is in../../concepts/ε-skill-registry.md.Read this file as donor genealogy only.
Core Algorithm
Seven-phase state machine stored in autonomous_sessions table.
amsAutonomousRun(args)
1. INIT → initPhase() # create session, auto-register project, git checkpoint
2. GATHER → gatherPhase() # git status, roadmap context, codebase scan
3. ANALYZE → analyzePhase() # gap detection by intent
4. PLAN → planPhase() # Eisenhower matrix, fix generation, task DAG
[dry_run exits here with plan only]
5. APPLY → applyPhase() # 4-phase atomic apply (validate, write, commit, db)
6. VERIFY → verifyPhase() # syntax check, git status
7. DONE → update session
On any error: attempt checkpointRollback() if checkpoint exists, set status FAILED or ROLLED_BACK.
Pipeline Phases
Phase 1: INIT — initPhase(projectName, projectPathOverride, intent, safetyConfig, db)
Purpose: Session bootstrap, project auto-registration, git checkpoint. Inputs: projectName, optional path override, resolved intent string, safety config object. Algorithm:
assertProjectName(projectName)— sanitize (no path traversal).- Resolve
projectPath: override →path.resolve(), elseAMS_RUNTIME_PROJECTS_DIR/projectName. - Check
fs.existsSync(projectPath). - If not exists and
auto_register=false→ throw McpError. - If not exists and
auto_register=true:fs.mkdirSync(recursive: true)- Write
TODOS.mdfrom template. - INSERT into
gsd_projectswith owner. - INSERT into
project_membersrole=owner ifAMS_USER_IDset.
- If
!dry_run && projectExistedand path has git →checkpointCreate()for rollback. - INSERT
autonomous_sessionsrow with status=’INIT’. Outputs:{ id: sessionId, checkpoint_hash, projectPath, projectExisted, projectRegistered }
Phase 2: GATHER — gatherPhase(projectName, pathOverride, contextConfig, db, checkpointHash, ...)
Purpose: Collect all context needed for analysis.
Inputs: Project name/path, contextConfig (roadmaps[], auto_detect, include_codebase, max_files).
Algorithm:
- Check user git repo:
git rev-parse --abbrev-ref HEAD+git status --porcelain→ branch, modified count. - Check checkpoint repo:
resolveCheckpointRepo(projectPath)→ mode, gitDir. - Roadmap context:
- If
roadmaps.length > 0→loadRoadmaps(roadmaps). - If
auto_detect→autoDetectRoadmaps(projectPath)(reads TODOS.md, package.json, etc.).
- If
- If
include_codebase !== false→scanCodebase(projectPath, { max_files: contextConfig.max_files || 50 }). Outputs:{ projectPath, projectExisted, projectRegistered, checkpoint, git: { project_repo, checkpoint_repo, isRepo }, roadmap, codebase }Notes for rewrite:scanCodebasemust skip symlinks and limit dir entries to 200 per directory to avoid infinite loops.
Phase 3: ANALYZE — analyzePhase(gathered, intent, db, intentDecision?)
Purpose: Find gaps between codebase state and desired intent. Intent → Gap mapping:
| Intent | Gap detection strategy |
|---|---|
learn |
getContentRecommendations(roadmapId, 5) for each roadmap. Fall back to unstarted roadmap nodes. |
fix |
gathered.codebase.issues → code_issue gaps. Link issues to roadmap nodes via searchNodes(). |
refactor |
Filter issues for large_file, deep_nesting, too_many_imports. Add structural_advice if largest file exceeds threshold. |
analyze / explore |
All code issues + codebase metrics + keyword extraction per roadmap. |
Gap types: learning_gap, code_issue, technical_debt, structural_advice.
Gap severity: high → Q1 (urgent+important), medium → Q2, low → Q4.
Outputs: { gaps[], insights[], intent }
Phase 4: PLAN — planPhase(analysis, sessionId, gathered, db)
Purpose: Eisenhower prioritization, fix generation, task DAG construction. Algorithm:
buildRoadmapDependencyIndex(gathered)→ Map(nodeId → depNodeIds[]).- If
intent === 'fix':generateFixes(fixableIssues, projectPath)→ fix actions with confidence.confidence >= 0.9→ Q1 (urgent+important).- Else → Q2 (not_urgent+important).
- For each remaining gap:
code_issuehigh → Q1, medium → Q2, low → Q4.technical_debt→ Q2 (action: refactor).structural_advice→ Q2 (action: plan).learning_gap→ Q2 (action: learn), with dependency list from index.
buildTaskDag(tasks)→ topological sort, edge list, cycle detection.- Return
{ matrix: {Q1,Q2,Q3,Q4}, actions[], tasks[], task_order[], task_dependencies[], task_cycle? }.
Dry-run exit: If safetyConfig.dry_run=true, return plan without executing APPLY. Response includes eisenhower_matrix, suggested_actions, task_order.
Apply gate: If !AMS_AUTONOMOUS_APPLY_ENABLED → return error, do not proceed.
Phase 5: APPLY — applyPhase(plan, safetyConfig, projectPath, sessionId, db)
Purpose: 4-phase atomic apply with full rollback capability. Safety constraints:
ALLOWED_EXTENSIONS:.js,.ts,.json,.md.max_fileslimit (default 10 from safetyConfig).- Path must not escape
projectPath(resolve + startsWith check).
4-phase atomic sequence:
Sub-phase 1: DRY RUN (Validation)
- For each
file_modifyaction: resolve path, check extension, check file exists. - Load
originalContent = fs.readFileSync(fullPath, 'utf8'). applyChangesToContent(entry.newContent, changeList)→ accumulate conflicts.- If any conflicts → throw McpError (abort before any writes).
- Collect
validatedActionswherenewContent !== originalContent.
Sub-phase 2: ATOMIC WRITE
runWithConcurrency(validatedActions, maxParallel)— default 1, up to 4.- Per file: write to
.ams-temp-{timestamp}-{rand}, thenfs.renameSync()(atomic). - On any write failure: restore all already-written files from
originalContentmap. - Re-throw write error after restoration.
Sub-phase 3: GIT COMMIT (if auto_commit=true)
- Per modified file:
checkpointCreate(projectPath, sessionId, description). - If commit fails → throw McpError (files already written — partial state).
Sub-phase 4: DATABASE OPS
- UPDATE
autonomous_sessions.commit_hashwith last commit hash. - UPDATE
autonomous_sessions.changes_logwith JSON{ files, commits }.
Task creation (after successful write):
- Create tasks in DAG topological order via
createTask(). - UPDATE task with
session_idandeisenhower_quadrant. dbAddTaskDependency(taskId, depTaskId)for each edge.
On outer error: checkpointRollback(projectPath, checkpoint.hash). If rollback also fails → throw critical error with FAILED_ROLLBACK status.
Outputs: { count, checkpoint: hash|null, files_modified[], changes_log }
Phase 6: VERIFY — verifyPhase(applied, projectPath)
Purpose: Post-apply sanity check. Checks per modified file:
- File exists.
.js/.mjsfiles:node --check fullPath(syntax check via execSync)..jsonfiles:JSON.parse(content). Additional checks:package.jsontest script presence.- Git status (clean working tree check).
Returns:
{ success: errors.length === 0, checks[], errors[] }
Tool Entry Points
amsAutonomousRun(args): Promise<object>
Purpose: Full INIT→DONE pipeline runner. Main MCP tool.
Input schema: AutonomousRunSchema — { project_name, project_path?, intent?, goal?, context?, safety? }
Intent detection: detectIntent({ intent, goal, projectName }) — maps explicit string or goal keywords to one of: learn, fix, refactor, analyze, explore.
Default safety config:
| Key | Default | Notes |
|---|---|---|
dry_run |
AMS_AUTONOMOUS_DEFAULT_DRY_RUN env |
env default |
auto_register |
true | create project if absent |
max_files |
10 | file modification cap |
auto_commit |
false | git commit after apply |
require_tests |
false | |
parallel |
false | parallel file writes |
max_parallel |
4 | max concurrent writes |
amsAutonomousApplyChanges(args): Promise<object>
Purpose: Apply externally-supplied file changes to an existing session.
Requires: AMS_AUTONOMOUS_APPLY_ENABLED=true.
Session must be in status DONE or PLAN.
Runs: APPLY → VERIFY → DONE sub-pipeline only.
sessionResume(args): Promise<object>
Purpose: Resume a session stopped at any intermediate phase.
Algorithm: Switch on session.status:
GATHER→ fall through to ANALYZE → PLAN → APPLY/DONE.ANALYZE→ fall through to PLAN → APPLY/DONE.PLAN→ APPLY/DONE.APPLY→ VERIFY → DONE.VERIFY→ DONE. Restoresgathered_context,analysis_result,plan_outputfrom JSON columns.
sessionList(args): Promise<object>
Lists rows from autonomous_sessions.
sessionRollback(args): Promise<object>
Calls checkpointRollback(projectPath, session.checkpoint_hash), sets status to ROLLED_BACK.
Configuration
| Config key | Default | Purpose |
|---|---|---|
AMS_AUTONOMOUS_APPLY_ENABLED |
false |
Gate for destructive apply |
AMS_AUTONOMOUS_DEFAULT_DRY_RUN |
env | Default dry_run flag |
AMS_RUNTIME_PROJECTS_DIR |
AMS_ROOT/data/projects |
Project storage |
AMS_USER_ID |
env | Owner for new projects |
Database Tables
autonomous_sessions— (id UUID, project_name, intent, status, checkpoint_hash, safety_config JSON, gathered_context JSON, analysis_result JSON, plan_output JSON, changes_log JSON, commit_hash, rollback_hash, error_message, created_at, completed_at)gsd_projects— project registryproject_members— (project_id, user_id, role)tasks— created tasks with session_id, eisenhower_quadrant