--- name: run description: | Automated PDCA execution loop. Single-command orchestration that initializes a run, flows through Plan/Do/Check/Act phases, emits events at every step, saves artifacts to disk, and handles cycle-back with structured feedback. Use instead of manually following orchestration steps. User: "archeflow:run" User: "Run this through ArcheFlow" User: "archeflow:run --start-from check" User: "archeflow:run --dry-run" --- # ArcheFlow Run — Automated PDCA Execution Loop This skill automates the full orchestration cycle. When invoked, Claude executes all PDCA phases end-to-end, emitting events and saving artifacts at every step. No manual phase-by-phase intervention needed. ## Prerequisites Load these skills (they are referenced throughout): - `archeflow:orchestration` — agent prompts, workflow selection, adaptation rules - `archeflow:process-log` — event schema and DAG parent rules - `archeflow:artifact-routing` — artifact naming, context injection, cycle archiving ## Invocation ``` archeflow:run # Full run, auto-select workflow archeflow:run --workflow standard # Force a specific workflow archeflow:run --start-from do # Resume from Do phase (requires prior artifacts) archeflow:run --start-from check # Resume from Check phase archeflow:run --dry-run # Plan phase only, show cost estimate archeflow:run --max-cycles 1 # Override max cycles ``` --- ## Execution Steps ### 0. Initialize Generate a run ID and set up the artifact directory. ```bash # Generate run_id RUN_ID="$(date -u +%Y-%m-%d)-" # Create artifact directory mkdir -p .archeflow/artifacts/${RUN_ID} # Emit run.start event (seq=1, parent=[]) ./lib/archeflow-event.sh "$RUN_ID" run.start plan "" \ '{"task":"","workflow":"","max_cycles":}' ``` **Track state:** Maintain these variables throughout the run: - `RUN_ID` — unique run identifier - `SEQ` — current sequence number (read from event file line count after each emit) - `CYCLE` — current PDCA cycle number (starts at 1) - `WORKFLOW` — fast/standard/thorough (may change via adaptation rules) - `ESCALATED` — boolean, set true if A1 triggers After emitting `run.start`, record `SEQ_RUN_START=1`. If `--start-from` is specified, verify that the required prior artifacts exist in `.archeflow/artifacts/${RUN_ID}/` before skipping phases. If missing, abort with an error. #### 0a. Strategy Resolution Determine the execution strategy before proceeding. Strategy controls the overall flow shape (cyclic vs linear). ```bash # Read strategy from config or CLI flag STRATEGY=$(grep '^strategy:' "$CONFIG" 2>/dev/null | sed 's/strategy:\s*//' | tr -d '"' | head -1) STRATEGY="${STRATEGY:-auto}" # CLI override: --strategy pdca|pipeline # (parsed from invocation args, overrides config) # Auto-select logic if [[ "$STRATEGY" == "auto" ]]; then TASK_LOWER=$(echo "$TASK" | tr '[:upper:]' '[:lower:]') if echo "$TASK_LOWER" | grep -qE '(fix|bug|patch|hotfix)'; then STRATEGY="pipeline" elif echo "$TASK_LOWER" | grep -qE '(refactor|redesign|review)'; then STRATEGY="pdca" elif [[ "$WORKFLOW" == "fast" ]]; then STRATEGY="pipeline" elif [[ "$WORKFLOW" == "thorough" ]]; then STRATEGY="pdca" else STRATEGY="pdca" fi fi echo "Strategy: $STRATEGY" ``` **Strategy dispatch:** If `STRATEGY=pdca`, execute Steps 1-5 below (existing PDCA flow). If `STRATEGY=pipeline`, skip to the "Pipeline Strategy Execution" section at the end of this skill. #### 0b. Lib Script Validation Verify that all required library scripts exist and are executable before proceeding. Fail fast if any dependency is missing. ```bash # Required lib scripts REQUIRED_LIBS=( "archeflow-event.sh" "archeflow-memory.sh" "archeflow-git.sh" "archeflow-rollback.sh" "archeflow-report.sh" "archeflow-progress.sh" ) MISSING=() for lib in "${REQUIRED_LIBS[@]}"; do if [[ ! -x "./lib/$lib" ]]; then MISSING+=("$lib") fi done if [[ ${#MISSING[@]} -gt 0 ]]; then echo "ERROR: Missing or non-executable lib scripts:" >&2 for m in "${MISSING[@]}"; do echo " - lib/$m" >&2 done echo "Ensure ArcheFlow is installed correctly. See README for setup." >&2 exit 1 fi # Check jq availability (required for event processing and memory) if ! command -v jq &>/dev/null; then echo "ERROR: jq is required but not found in PATH." >&2 echo "Install with: apt install jq / brew install jq" >&2 exit 1 fi ``` #### 0c. Memory Injection Load cross-run memory lessons and inject into agent prompts. Use `--audit` to track which lessons were injected for this run: ```bash # Load cross-run memory for this domain (with audit trail) MEMORY_LESSONS=$(./lib/archeflow-memory.sh inject "$DOMAIN" "" --audit "$RUN_ID") # Inject into Explorer/Creator prompts if non-empty if [[ -n "$MEMORY_LESSONS" ]]; then EXPLORER_PROMPT="${EXPLORER_PROMPT} ${MEMORY_LESSONS}" CREATOR_PROMPT="${CREATOR_PROMPT} ${MEMORY_LESSONS}" fi ``` #### 0d. Model Configuration Read model assignment from `.archeflow/config.yaml` and resolve the model for each archetype based on the current workflow. Per-workflow overrides take precedence over per-archetype overrides, which take precedence over the default. ```bash CONFIG=".archeflow/config.yaml" # Read default model DEFAULT_MODEL=$(grep -A1 '^models:' "$CONFIG" 2>/dev/null | grep 'default:' | sed 's/.*default:\s*//' | tr -d '"' | head -1) DEFAULT_MODEL="${DEFAULT_MODEL:-sonnet}" # Resolve model for a given archetype and workflow # Usage: resolve_model resolve_model() { local arch="$1" wf="$2" model="" # Check per-workflow per-archetype override model=$(sed -n "/workflows:/,\$p" "$CONFIG" 2>/dev/null \ | sed -n "/${wf}:/,/^ [a-z]/p" \ | grep -A1 "archetypes:" | grep "${arch}:" \ | sed "s/.*${arch}:\s*//" | tr -d '"' | head -1) [[ -n "$model" ]] && echo "$model" && return # Check per-workflow default model=$(sed -n "/workflows:/,\$p" "$CONFIG" 2>/dev/null \ | sed -n "/${wf}:/,/^ [a-z]/p" \ | grep 'default:' | sed 's/.*default:\s*//' | tr -d '"' | head -1) [[ -n "$model" ]] && echo "$model" && return # Check per-archetype override model=$(sed -n "/^ archetypes:/,/^ [a-z]/p" "$CONFIG" 2>/dev/null \ | grep "${arch}:" | sed "s/.*${arch}:\s*//" | tr -d '"' | head -1) [[ -n "$model" ]] && echo "$model" && return # Fall back to default echo "$DEFAULT_MODEL" } # Example: EXPLORER_MODEL=$(resolve_model explorer "$WORKFLOW") ``` Use `resolve_model` when spawning each agent to pass the correct model. The resolved model can be included in the `agent.start` event data for cost tracking. --- ### Status Token Protocol Every agent ends its output with a `STATUS:` line. The orchestrator parses this to decide the next action. **Parsing:** ```bash STATUS=$(tail -20 "$AGENT_OUTPUT" | grep -oE 'STATUS: (DONE|DONE_WITH_CONCERNS|NEEDS_CONTEXT|BLOCKED)' | head -1) STATUS="${STATUS#STATUS: }" if [[ -z "$STATUS" ]]; then STATUS="DONE"; fi ``` **Status to action mapping:** | Status | Action | |--------|--------| | `DONE` | Proceed to next phase or agent | | `DONE_WITH_CONCERNS` | Log concerns in event data, proceed | | `NEEDS_CONTEXT` | Pause run, request missing information from user | | `BLOCKED` | Abort phase, report blocker to user | Include the parsed status in the `agent.complete` event data: `"status":""`. --- ### 1. Plan Phase #### 1a. Explorer (if standard or thorough) ```bash # Emit agent.start ./lib/archeflow-event.sh "$RUN_ID" agent.start plan explorer \ '{"archetype":"explorer","prompt_summary":"Research codebase context for task"}' "$SEQ_RUN_START" ``` Spawn the Explorer agent using the prompt from `archeflow:orchestration` Step 1. ``` Agent( description: "Explorer: research context for ", prompt: "", subagent_type: "Explore" ) ``` After Explorer returns: 1. Save output to `.archeflow/artifacts/${RUN_ID}/plan-explorer.md` 2. Emit `agent.complete`: ```bash ./lib/archeflow-event.sh "$RUN_ID" agent.complete plan explorer \ '{"archetype":"explorer","duration_ms":,"artifacts":["plan-explorer.md"],"summary":"<1-line summary>"}' "$SEQ_EXPLORER_START" ``` 3. Record `SEQ_EXPLORER_COMPLETE` for DAG references. #### 1b. Creator The Creator receives Explorer output (if it exists) or performs Mini-Reflect (fast workflow). ```bash # Emit agent.start — parent is explorer.complete (or run.start for fast) ./lib/archeflow-event.sh "$RUN_ID" agent.start plan creator \ '{"archetype":"creator","prompt_summary":"Design solution proposal"}' "$SEQ_EXPLORER_COMPLETE" ``` Spawn the Creator agent using the prompt from `archeflow:orchestration` Step 1. **Context injection (from artifact-routing skill):** - Fast workflow: task description only - Standard/thorough: task description + contents of `plan-explorer.md` - Cycle 2+: task description + `plan-explorer.md` + `act-feedback.md` from prior cycle ``` Agent( description: "Creator: design proposal for ", prompt: "", subagent_type: "Plan" ) ``` After Creator returns: 1. Save output to `.archeflow/artifacts/${RUN_ID}/plan-creator.md` 2. Emit `agent.complete` 3. Record `SEQ_CREATOR_COMPLETE` #### 1c. Confidence Gate (Adaptation Rule A3) **Parsing instructions:** Read `plan-creator.md`, locate the `### Confidence` table. Extract scores for each axis as floats: ```bash CONF_FILE=".archeflow/artifacts/${RUN_ID}/plan-creator.md" # Extract confidence scores (expects format: "| Task understanding | 0.8 |") TASK_UNDERSTANDING=$(grep -i "task understanding" "$CONF_FILE" | grep -oE '[0-9]+\.[0-9]+' | head -1) SOLUTION_COMPLETENESS=$(grep -i "solution completeness" "$CONF_FILE" | grep -oE '[0-9]+\.[0-9]+' | head -1) RISK_COVERAGE=$(grep -i "risk coverage" "$CONF_FILE" | grep -oE '[0-9]+\.[0-9]+' | head -1) # Fallback: if unparseable, emit warning and default to 0.0 (triggers gate, not bypasses it) if [[ -z "$TASK_UNDERSTANDING" || -z "$SOLUTION_COMPLETENESS" || -z "$RISK_COVERAGE" ]]; then echo "WARNING: Could not parse confidence scores from plan-creator.md" >&2 ./lib/archeflow-event.sh "$RUN_ID" decision plan "" \ '{"what":"confidence_parse_failure","chosen":"warn","rationale":"one or more scores unparseable"}' "$SEQ_CREATOR_COMPLETE" fi TASK_UNDERSTANDING="${TASK_UNDERSTANDING:-0.0}" SOLUTION_COMPLETENESS="${SOLUTION_COMPLETENESS:-0.0}" RISK_COVERAGE="${RISK_COVERAGE:-0.0}" ``` **Pause branch** (Task understanding < 0.5): The Creator does not sufficiently understand the task. Do not spawn Maker. 1. Emit decision event with `"chosen":"pause"` 2. Display message to user: "Creator rated task understanding at . Clarification needed before proceeding." 3. Block until the user provides clarification 4. Re-run Creator with the clarification appended to the task description ```bash ./lib/archeflow-event.sh "$RUN_ID" decision plan "" \ '{"what":"confidence_gate","chosen":"pause","rationale":"task_understanding scored '"$TASK_UNDERSTANDING"'"}' "$SEQ_CREATOR_COMPLETE" ``` **Upgrade branch** (Solution completeness < 0.5): The Creator's proposal is incomplete — more research is needed. 1. If fast workflow: upgrade to standard, spawn Explorer, then re-run Creator with Explorer output 2. If already standard/thorough: re-run Explorer with a focused prompt targeting the incomplete areas ```bash ./lib/archeflow-event.sh "$RUN_ID" decision plan "" \ '{"what":"confidence_gate","chosen":"upgrade","rationale":"solution_completeness scored '"$SOLUTION_COMPLETENESS"'"}' "$SEQ_CREATOR_COMPLETE" # If fast → standard upgrade: WORKFLOW="standard" # Spawn Explorer, then re-run Creator with Explorer findings ``` **Mini-Explorer branch** (Risk coverage < 0.5): The Creator identified risks but lacks confidence in their assessment. Spawn a focused Explorer to investigate. ``` Agent( description: "Mini-Explorer: investigate risk area for ", prompt: "You are the EXPLORER archetype. The Creator rated risk coverage at . Identified risks: Research ONLY the risky areas. Answer: Is the risk real? What mitigations exist? What tests/guards would help? Limit: focused output only.", subagent_type: "Explore" ) ``` Save output to `.archeflow/artifacts/${RUN_ID}/plan-mini-explorer.md`. The Maker receives both `plan-creator.md` and `plan-mini-explorer.md` as context. ```bash ./lib/archeflow-event.sh "$RUN_ID" decision plan "" \ '{"what":"confidence_gate","chosen":"mini_explorer","rationale":"risk_coverage scored '"$RISK_COVERAGE"'"}' "$SEQ_CREATOR_COMPLETE" ``` **Note:** The mini-Explorer runs in parallel with Do phase preparation (5 min max). The Maker can proceed once both `plan-creator.md` and `plan-mini-explorer.md` are available. #### 1d. Phase Transition: Plan to Do ```bash # Parent = all completing events in Plan phase ./lib/archeflow-event.sh "$RUN_ID" phase.transition do "" \ '{"from":"plan","to":"do","artifacts_so_far":["plan-explorer.md","plan-creator.md"]}' "$SEQ_CREATOR_COMPLETE" ``` Record `SEQ_PLAN_TO_DO`. --- ### 2. Do Phase #### 2a. Maker **Context injection (from artifact-routing skill):** - Contents of `plan-creator.md` (the proposal) - Cycle 2+: also contents of `act-feedback.md` filtered to Maker-routed findings only ```bash ./lib/archeflow-event.sh "$RUN_ID" agent.start do maker \ '{"archetype":"maker","prompt_summary":"Implement proposal in isolated worktree"}' "$SEQ_PLAN_TO_DO" ``` ``` Agent( description: "Maker: implement ", prompt: " >", isolation: "worktree", mode: "bypassPermissions" ) ``` After Maker returns: 1. Save implementation summary to `.archeflow/artifacts/${RUN_ID}/do-maker.md` 2. Capture list of changed files: `git diff --name-only` on the Maker's branch, save to `.archeflow/artifacts/${RUN_ID}/do-maker-files.txt` 3. Emit `agent.complete`: ```bash ./lib/archeflow-event.sh "$RUN_ID" agent.complete do maker \ '{"archetype":"maker","duration_ms":,"artifacts":["do-maker.md","do-maker-files.txt"],"summary":""}' "$SEQ_MAKER_START" ``` 4. Record `SEQ_MAKER_COMPLETE` **Critical:** Verify the Maker committed its changes before proceeding. If uncommitted changes exist, instruct the Maker to commit. #### 2a-ii. Test-First Validation After Maker completes, check `do-maker-files.txt` for test files: ```bash TEST_FILES=$(grep -iE '([/_.-](test|spec)[/_.-]|\.(test|spec)\.|_(test|spec)\.|/tests?/|/__tests__/|/specs?/)' ".archeflow/artifacts/${RUN_ID}/do-maker-files.txt" || true) ``` If `TEST_FILES` is empty and domain is not `writing`: 1. Check if `plan-creator.md` contains a `### Test Strategy` section 2. If yes: re-run Maker with targeted test instruction (one retry within Do phase) 3. If no test strategy specified: emit WARNING event and proceed ```bash ./lib/archeflow-event.sh "$RUN_ID" decision do "" \ '{"what":"test_first_gate","chosen":"","rationale":""}' "$SEQ_MAKER_COMPLETE" ``` The re-run prompt for the retry case: > "The proposal specified these test cases: . No test files were found in your changes. Add the specified tests before finishing." This is one retry within the Do phase, not a full PDCA cycle. If the retry also produces no tests, emit WARNING and proceed to Check. #### 2b. Phase Transition: Do to Check ```bash ./lib/archeflow-event.sh "$RUN_ID" phase.transition check "" \ '{"from":"do","to":"check","artifacts_so_far":["plan-explorer.md","plan-creator.md","do-maker.md","do-maker-files.txt"]}' "$SEQ_MAKER_COMPLETE" ``` Record `SEQ_DO_TO_CHECK`. --- ### 3. Check Phase **Important:** Spawn Guardian FIRST, then evaluate A2 before spawning other reviewers. #### 3a. Guardian (always first) **Context injection:** Maker's git diff + proposal risk section only (not full proposal, not Explorer research). ```bash ./lib/archeflow-event.sh "$RUN_ID" agent.start check guardian \ '{"archetype":"guardian","prompt_summary":"Security and risk review of changes"}' "$SEQ_DO_TO_CHECK" ``` ``` Agent( description: "Guardian: security review for ", prompt: "" ) ``` After Guardian returns: 1. Save to `.archeflow/artifacts/${RUN_ID}/check-guardian.md` 2. Emit `review.verdict`: ```bash ./lib/archeflow-event.sh "$RUN_ID" review.verdict check guardian \ '{"archetype":"guardian","verdict":"","findings":[...]}' "$SEQ_GUARDIAN_START" ``` 3. Record `SEQ_GUARDIAN_VERDICT` #### 3b. Guardian Fast-Path Check (Adaptation Rule A2) Parse Guardian's output. If **0 CRITICAL and 0 WARNING** AND workflow is not escalated AND not first cycle of thorough: ```bash ./lib/archeflow-event.sh "$RUN_ID" decision check "" \ '{"what":"guardian_fast_path","chosen":"skip_remaining_reviewers","rationale":"0 CRITICAL, 0 WARNING"}' "$SEQ_GUARDIAN_VERDICT" ``` Skip to Phase Transition (3d). Log "Guardian fast-path taken" in report. Otherwise, proceed to spawn remaining reviewers. #### 3c. Remaining Reviewers (in parallel) Spawn these based on workflow (see `archeflow:orchestration` for which reviewers apply): **Skeptic** (standard/thorough): - Context: Creator's proposal (assumptions section focus) - Save to: `check-skeptic.md` **Sage** (standard/thorough): - Context: Creator's proposal + Maker's diff + implementation summary - Save to: `check-sage.md` **Trickster** (thorough only): - Context: Maker's diff only - Save to: `check-trickster.md` Spawn all applicable reviewers in parallel (multiple Agent calls in one message). For each: ```bash # Emit agent.start with parent = SEQ_DO_TO_CHECK ./lib/archeflow-event.sh "$RUN_ID" agent.start check \ '{"archetype":"","prompt_summary":""}' "$SEQ_DO_TO_CHECK" ``` After each returns, emit `review.verdict` and save artifact. #### 3c-ii. Evidence Validation After all reviewers complete, scan CRITICAL/WARNING findings for two conditions: 1. **Banned phrases** — hedged language without evidence 2. **Missing evidence** — no command output, code citation, or reproduction steps Downgrade unsupported findings to INFO before proceeding to Act. ```bash BANNED_PHRASES=("might be" "could potentially" "appears to" "seems like" "may not") EVIDENCE_MARKERS=("exit" "output" "line [0-9]" ":[0-9]" "returned" "FAIL" "PASS" "assert") for artifact in .archeflow/artifacts/${RUN_ID}/check-*.md; do REVIEWER=$(basename "$artifact" .md | sed 's/check-//') # Read findings table rows (CRITICAL and WARNING only) grep -E '\| (CRITICAL|WARNING) \|' "$artifact" 2>/dev/null | while IFS= read -r line; do SEVERITY=$(echo "$line" | grep -oE '(CRITICAL|WARNING)' | head -1) DOWNGRADE_REASON="" # Check 1: banned phrases for phrase in "${BANNED_PHRASES[@]}"; do if echo "$line" | grep -qi "$phrase"; then DOWNGRADE_REASON="banned phrase: $phrase" break fi done # Check 2: no evidence markers (only if not already flagged) if [[ -z "$DOWNGRADE_REASON" ]]; then HAS_EVIDENCE=false for marker in "${EVIDENCE_MARKERS[@]}"; do if echo "$line" | grep -qiE "$marker"; then HAS_EVIDENCE=true break fi done if [[ "$HAS_EVIDENCE" == "false" ]]; then DOWNGRADE_REASON="no evidence cited" fi fi if [[ -n "$DOWNGRADE_REASON" ]]; then echo "EVIDENCE DOWNGRADE: $REVIEWER $SEVERITY finding — $DOWNGRADE_REASON" ./lib/archeflow-event.sh "$RUN_ID" decision check "" \ '{"what":"evidence_downgrade","from":"'"$SEVERITY"'","to":"INFO","reviewer":"'"$REVIEWER"'","reason":"'"$DOWNGRADE_REASON"'"}' # Note: the orchestrator tracks downgraded findings separately — # do not modify the artifact file (avoids sed corruption on table rows) fi done done ``` **Important:** Downgraded findings are tracked in events, NOT by modifying artifact files. The Act phase reads the decision events to know which findings were downgraded and excludes them from CRITICAL tallies. #### 3d. Phase Transition: Check to Act Collect all verdict seq numbers for the parent array. ```bash ./lib/archeflow-event.sh "$RUN_ID" phase.transition act "" \ '{"from":"check","to":"act"}' "" ``` Record `SEQ_CHECK_TO_ACT`. --- ### 4. Act Phase #### 4a. Collect Verdicts Read all `check-*.md` artifacts. Tally findings: - Count CRITICAL, WARNING, INFO per reviewer - Check for unanimous approval #### 4b. Escalation Check (Adaptation Rule A1) If workflow is `fast` and Guardian found 2+ CRITICAL: - Set `ESCALATED=true` - Upgrade next cycle to `standard` (add Skeptic + Sage) - Emit decision event #### 4c. Branch: All Approved If all reviewers approved (and completion criteria met, if defined): 1. Emit `cycle.boundary`: ```bash ./lib/archeflow-event.sh "$RUN_ID" cycle.boundary act "" \ '{"cycle":,"max_cycles":,"exit_condition":"all_approved","met":true,"next_action":"complete"}' "$SEQ_CHECK_TO_ACT" ``` 2. **Pre-merge hook check:** ```bash # Read hooks config if it exists if [[ -f ".archeflow/hooks.yaml" ]]; then PRE_MERGE_HOOKS=$(grep -A5 "pre-merge:" .archeflow/hooks.yaml || true) if [[ -n "$PRE_MERGE_HOOKS" ]]; then echo "Running pre-merge hooks..." # Execute hooks; abort merge if fail_action: abort # Hook execution is project-specific — see .archeflow/hooks.yaml fi fi ``` 3. **Merge the Maker's worktree branch:** ```bash ./lib/archeflow-git.sh merge "$RUN_ID" --no-ff ``` 4. **Post-merge test validation** (using the auto-rollback script): ```bash # Run tests and auto-revert if they fail if ! ./lib/archeflow-rollback.sh "$RUN_ID"; then # Rollback script already reverted HEAD and emitted decision event # If cycles remain, cycle back with integration test failure feedback if [[ "$CYCLE" -lt "$MAX_CYCLES" ]]; then echo "Cycling back with integration test failure feedback..." # Build act-feedback.md with "integration test failure on main" as top finding # Continue to step 4d (Issues Found) else echo "Max cycles reached. Reporting failure to user." # Continue to step 4e (Max Cycles Reached) fi fi ``` 5. **Clean up worktree:** ```bash ./lib/archeflow-git.sh cleanup "$RUN_ID" ``` 6. Proceed to Completion (step 5) #### 4d. Branch: Issues Found (cycles remaining) If any reviewer rejected and `CYCLE < MAX_CYCLES`: 1. Build structured feedback using the Cycle Feedback Protocol from `archeflow:orchestration`: - Extract findings from all `check-*.md` artifacts - Route findings: Guardian/Skeptic issues → Creator, Sage issues → Maker - Check convergence: same finding in 2 consecutive cycles → escalate to user - Dedup cross-archetype findings 2. Save to `.archeflow/artifacts/${RUN_ID}/act-feedback.md` 3. Save applied fixes log (initially empty, populated during next Do phase): ```bash touch .archeflow/artifacts/${RUN_ID}/act-fixes.jsonl ``` 4. Emit `cycle.boundary`: ```bash ./lib/archeflow-event.sh "$RUN_ID" cycle.boundary act "" \ '{"cycle":,"max_cycles":,"exit_condition":"all_approved","met":false,"next_action":"cycle_back"}' "$SEQ_CHECK_TO_ACT" ``` 5. Archive current cycle artifacts: ```bash mkdir -p .archeflow/artifacts/${RUN_ID}/cycle-${CYCLE} cp .archeflow/artifacts/${RUN_ID}/plan-*.md .archeflow/artifacts/${RUN_ID}/cycle-${CYCLE}/ cp .archeflow/artifacts/${RUN_ID}/do-*.md .archeflow/artifacts/${RUN_ID}/do-*.txt .archeflow/artifacts/${RUN_ID}/cycle-${CYCLE}/ 2>/dev/null || true cp .archeflow/artifacts/${RUN_ID}/check-*.md .archeflow/artifacts/${RUN_ID}/cycle-${CYCLE}/ ``` 6. Increment `CYCLE`, go back to Step 1 (Plan Phase) #### 4e. Branch: Max Cycles Reached If `CYCLE >= MAX_CYCLES` and issues remain: 1. Report all unresolved findings to the user 2. Present the best implementation (on its branch, not merged) 3. Let the user decide: merge as-is, fix manually, or abandon 4. Emit `cycle.boundary` with `"met": false, "next_action": "user_decision"` --- ### 5. Completion ```bash # Emit run.complete ./lib/archeflow-event.sh "$RUN_ID" run.complete act "" \ '{"status":"completed","cycles":,"agents_total":,"fixes_total":,"shadows":0,"artifacts":[]}' # Check for regressions from previously fixed findings if ./lib/archeflow-memory.sh regression-check ".archeflow/events/${RUN_ID}.jsonl"; then echo "No regressions detected." else echo "WARNING: Regressions detected — previously fixed findings have reappeared." echo "Review the regression output above and consider addressing them." fi # Generate report ./lib/archeflow-report.sh .archeflow/events/${RUN_ID}.jsonl # Update run index echo '{"run_id":"'$RUN_ID'","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","task":"","workflow":"","status":"completed","cycles":}' \ >> .archeflow/events/index.jsonl ``` Display the orchestration report to the user (see `archeflow:orchestration` report format). --- ## Fix Tracking When the Maker addresses review findings in cycle 2+, emit `fix.applied` for each: ```bash ./lib/archeflow-event.sh "$RUN_ID" fix.applied act "" \ '{"source":"","finding":"","file":"","line":}' "$SEQ_OF_REVIEW" ``` Also append to `.archeflow/artifacts/${RUN_ID}/act-fixes.jsonl`: ```jsonl {"source":"guardian","finding":"SQL injection","file":"src/auth.ts","line":48,"fixed_in_cycle":2} ``` --- ## Dry-Run Mode When `--dry-run` is specified: 1. Run **only the Plan phase** (Explorer + Creator) 2. Display: ``` Dry run for: "" Workflow: ( cycles max) Agents per cycle: Max agents total: Plan phase result: see .archeflow/artifacts//plan-creator.md Creator confidence: Estimated phases: Plan (done) -> Do -> Check -> Act Proceed with full run? [y/n] ``` 3. Do NOT emit `run.complete` — the run is paused, not finished 4. If user says yes, continue from `--start-from do` using the saved artifacts --- ## Start-From Mode When `--start-from ` is specified: | Start from | Required artifacts in `.archeflow/artifacts//` | |------------|-------------------------------------------------------| | `plan` | None (equivalent to full run) | | `do` | `plan-creator.md` | | `check` | `plan-creator.md`, `do-maker.md`, `do-maker-files.txt` | | `act` | All `check-*.md` files | Validate required artifacts exist. If missing, error: ``` Cannot start from : missing artifact . Run the prior phase first. ``` When resuming, emit a `run.start` event with `{"resumed_from":""}` in data. --- ## Error Handling - **Agent fails to return:** Wait up to 5 minutes. If no response, emit `agent.complete` with `"error": true`, log the failure, and abort the run. Do not retry blindly. - **Event emitter fails:** Log a warning but do not block orchestration. Events are observation, not control flow. - **Artifact write fails:** This IS blocking. Artifacts are required for phase handoff. Abort and report. - **Merge conflict:** Do not force-resolve. Report the conflict, leave the branch intact, let the user decide. --- ## Progress Display Throughout the run, display live progress using the format from `archeflow:using-archeflow`: ``` ━━━ ArcheFlow Run: ━━━━━━━━━━━━━━━━━━━ Run ID: | Workflow: | Cycle: 1/ [Plan] Explorer researching... -> done (35s) [Plan] Creator designing proposal... -> done (25s, confidence: 0.8) [Do] Maker implementing... -> done (90s, 4 files, 8 tests) [Check] Guardian reviewing... -> APPROVED [Check] Skeptic challenging... -> APPROVED (1 INFO) [Check] Sage reviewing... -> APPROVED [Act] All approved — merging... -> merged to main ━━━ Complete: 3m 10s, 1 cycle ━━━━━━━━━━━━━━━ Artifacts: .archeflow/artifacts// Report: .archeflow/events/.jsonl ``` --- ## Pipeline Strategy Execution When `STRATEGY=pipeline`, execute this linear flow instead of the PDCA cycle above. ### Pipeline Phases ``` Plan -> Implement -> Spec-Review -> Quality-Review -> Verify ``` No cycle-back. Each phase runs once. ### 1. Plan Spawn Creator only (no Explorer). Use fast-workflow Creator prompt with Mini-Reflect. Save output to `.archeflow/artifacts/${RUN_ID}/plan-creator.md`. ### 2. Implement Spawn Maker in isolated worktree with Creator's proposal. Save output to `.archeflow/artifacts/${RUN_ID}/do-maker.md`. ### 3. Spec-Review Run Guardian and Skeptic **sequentially** (Guardian first, then Skeptic only if Guardian has findings). - Guardian receives: Maker's git diff + proposal risk section - Skeptic receives: Creator's proposal (assumptions focus) Save to `check-guardian.md` and `check-skeptic.md`. ### 4. Quality-Review Spawn Sage with proposal + diff + implementation summary. Save to `check-sage.md`. ### 5. Verify Run the project's test suite. If tests pass and no CRITICAL findings exist: 1. Merge the Maker's branch 2. Emit `run.complete` If CRITICAL findings exist: 1. **Do NOT merge yet** — the branch remains separate 2. Spawn Maker for a **single targeted fix** — provide only the CRITICAL findings as context 3. Re-run the reviewer(s) that raised the CRITICAL finding(s) on just the fixed files 4. Re-run test suite 5. If tests pass and re-review approves: merge 6. If still failing after this one fix attempt: **abort** — do NOT merge, report to user with the branch name for manual resolution ```bash # Pipeline verify: explicit merge guard if [[ "$VERIFY_PASS" == "true" ]]; then ./lib/archeflow-git.sh merge "$RUN_ID" --no-ff ./lib/archeflow-rollback.sh "$RUN_ID" # post-merge test validation else echo "Pipeline aborted: CRITICAL findings not resolved after 1 fix attempt." echo "Branch: archeflow/$RUN_ID (not merged)" # Emit run.complete with status: aborted fi ``` WARNINGs are logged in the run event but do not block the merge. ### Pipeline Progress Display ``` ━━━ ArcheFlow Pipeline: ━━━━━━━━━━━━━━━━ Run ID: | Strategy: pipeline [Plan] Creator designing... -> done (20s) [Implement] Maker building... -> done (60s, 3 files) [Spec] Guardian reviewing... -> APPROVED [Quality] Sage reviewing... -> APPROVED (1 WARNING) [Verify] Tests passing... -> merged to main ━━━ Complete: 2m 15s ━━━━━━━━━━━━━━━━━━━━━━━━━━ ```