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 no amsAutonomousRun controller, no autonomous_sessions table, and no src/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:

  1. assertProjectName(projectName) — sanitize (no path traversal).
  2. Resolve projectPath: override → path.resolve(), else AMS_RUNTIME_PROJECTS_DIR/projectName.
  3. Check fs.existsSync(projectPath).
  4. If not exists and auto_register=false → throw McpError.
  5. If not exists and auto_register=true:
    • fs.mkdirSync(recursive: true)
    • Write TODOS.md from template.
    • INSERT into gsd_projects with owner.
    • INSERT into project_members role=owner if AMS_USER_ID set.
  6. If !dry_run && projectExisted and path has git → checkpointCreate() for rollback.
  7. INSERT autonomous_sessions row 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:

  1. Check user git repo: git rev-parse --abbrev-ref HEAD + git status --porcelain → branch, modified count.
  2. Check checkpoint repo: resolveCheckpointRepo(projectPath) → mode, gitDir.
  3. Roadmap context:
    • If roadmaps.length > 0loadRoadmaps(roadmaps).
    • If auto_detectautoDetectRoadmaps(projectPath) (reads TODOS.md, package.json, etc.).
  4. If include_codebase !== falsescanCodebase(projectPath, { max_files: contextConfig.max_files || 50 }). Outputs: { projectPath, projectExisted, projectRegistered, checkpoint, git: { project_repo, checkpoint_repo, isRepo }, roadmap, codebase } Notes for rewrite: scanCodebase must 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:

  1. buildRoadmapDependencyIndex(gathered) → Map(nodeId → depNodeIds[]).
  2. If intent === 'fix': generateFixes(fixableIssues, projectPath) → fix actions with confidence.
    • confidence >= 0.9 → Q1 (urgent+important).
    • Else → Q2 (not_urgent+important).
  3. For each remaining gap:
    • code_issue high → 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.
  4. buildTaskDag(tasks) → topological sort, edge list, cycle detection.
  5. 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_files limit (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_modify action: 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 validatedActions where newContent !== originalContent.

Sub-phase 2: ATOMIC WRITE

  • runWithConcurrency(validatedActions, maxParallel) — default 1, up to 4.
  • Per file: write to .ams-temp-{timestamp}-{rand}, then fs.renameSync() (atomic).
  • On any write failure: restore all already-written files from originalContent map.
  • 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_hash with last commit hash.
  • UPDATE autonomous_sessions.changes_log with JSON { files, commits }.

Task creation (after successful write):

  • Create tasks in DAG topological order via createTask().
  • UPDATE task with session_id and eisenhower_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/.mjs files: node --check fullPath (syntax check via execSync).
  • .json files: JSON.parse(content). Additional checks:
  • package.json test 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. Restores gathered_context, analysis_result, plan_output from 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 registry
  • project_members — (project_id, user_id, role)
  • tasks — created tasks with session_id, eisenhower_quadrant

Back to top

Colibri — documentation-first MCP runtime. Apache 2.0 + Commons Clause.

This site uses Just the Docs, a documentation theme for Jekyll.