Skip to content
Back to search

Agent-Skills-4-Vibe-Coding-CLI

πŸ›°οΈ Agent skills setup for AntiGravity Advanced Edition β€’ v4.3.8 Meta-Engine

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Dokhacgiakhoa/Agent-Skills-4-Vibe-Coding-CLI with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Dokhacgiakhoa/Agent-Skills-4-Vibe-Coding-CLI'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/dokhacgiakhoa--agent-skills-4-vibe-coding-cli/badge.svg)](/listings/dokhacgiakhoa--agent-skills-4-vibe-coding-cli)

HTML

<a href="/listings/dokhacgiakhoa--agent-skills-4-vibe-coding-cli"><img src="/api/listings/dokhacgiakhoa--agent-skills-4-vibe-coding-cli/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Antigravity uses a **Dual-Scope Strategy** to ensure absolute stability:

1. **Global Scope (Project Root)**: Installs `GEMINI.md` (Configuration). 2. **Workspace Scope (`.agent/`)**: Installs Rules, Skills, and Workflows (The Brain).

# ONE COMMAND TO RULE THEM ALL
npx agent-skills-setup-for-antigravity [project-name]

> [!TIP] > **New to npx?** Check our [NPX Installation Guide](docs/INSTALL_NPX_GUIDE.md) for a step-by-step setup.

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md Β· README Β· 141 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <div align="center">
  2. # πŸ›°οΈ Agent skills setup for AntiGravity
  3. ### *Advanced Edition β€’ v4.3.8 Meta-Engine*
  4. <!-- BADGES: Spaced & Tightly Wrapped to prevent Underlines -->
  5. <p align="center">
  6. <a href="https://www.npmjs.com/package/agent-skills-setup-for-antigravity"><img src="https://img.shields.io/npm/v/agent-skills-setup-for-antigravity?color=2ea44f&logo=npm" alt="npm version" /></a>&nbsp;&nbsp;
  7. <a href="https://www.npmjs.com/package/agent-skills-setup-for-antigravity"><img src="https://img.shields.io/npm/dm/agent-skills-setup-for-antigravity?color=blueviolet&logo=npm" alt="npm downloads" /></a>&nbsp;&nbsp;
  8. <a href="https://github.com/Dokhacgiakhoa/Agent-skills-setup-for-AntiGravity/actions"><img src="https://img.shields.io/github/actions/workflow/status/Dokhacgiakhoa/Agent-skills-setup-for-AntiGravity/npm-publish.yml?branch=main&logo=github&label=BUILD" alt="Build Status" /></a>&nbsp;&nbsp;
  9. <a href="LICENSE"><img src="https://img.shields.io/npm/l/agent-skills-setup-for-antigravity?color=orange" alt="License" /></a>
  10. </p>
  11. <!-- SECOND ROW: Stats -->
  12. <p align="center">
  13. <a href="https://socket.dev/npm/package/agent-skills-setup-for-antigravity"><img src="https://socket.dev/api/badge/npm/package/agent-skills-setup-for-antigravity" alt="Socket Badge" /></a>&nbsp;&nbsp;
  14. <a href="https://github.com/Dokhacgiakhoa/Agent-skills-setup-for-AntiGravity"><img src="https://img.shields.io/github/languages/code-size/Dokhacgiakhoa/Agent-skills-setup-for-AntiGravity?color=blue" alt="Code Size" /></a>&nbsp;&nbsp;
  15. <img src="https://img.shields.io/badge/Files-10.9k-blueviolet" alt="Total Files" />&nbsp;&nbsp;
  16. <img src="https://img.shields.io/badge/Lines_of_Code-669k-ff69b4" alt="Lines of Code" />
  17. </p>
  18. <br>
  19. **Easy Vibe, Lazy Code. One Command to Rule Them All.**
  20. [Explore Docs](https://agent-skills-setup-for-antigravity.vercel.app) β€’ [Github](https://github.com/Dokhacgiakhoa/Agent-skills-setup-for-AntiGravity) β€’ [Report Bug](https://github.com/Dokhacgiakhoa/Agent-skills-setup-for-AntiGravity/issues)
  21. ---
  22. ### πŸ“Š System Identity Matrix
  23. | **16** Rules | **575** Skills | **30** Flows | **10.9k** Files | **669k** Lines |
  24. | :---: | :---: | :---: | :---: | :---: |
  25. | *Governance* | *Operational* | *Standardized* | *Workspace* | *Codebase* |
  26. </div>
  27. <br>
  28. ## ⚑ Smart Installation (npx)
  29. Antigravity uses a **Dual-Scope Strategy** to ensure absolute stability:
  30. 1. **Global Scope (Project Root)**: Installs `GEMINI.md` (Configuration).
  31. 2. **Workspace Scope (`.agent/`)**: Installs Rules, Skills, and Workflows (The Brain).
  32. ```bash
  33. # ONE COMMAND TO RULE THEM ALL
  34. npx agent-skills-setup-for-antigravity [project-name]
  35. ```
  36. > [!TIP]
  37. > **New to npx?** Check our [NPX Installation Guide](docs/INSTALL_NPX_GUIDE.md) for a step-by-step setup.
  38. ---
  39. ## ✨ The Premium Edge (v4.3.8)
  40. Why choose AntiGravity over standard AI wrappers?
  41. | Feature | **AntiGravity IDE** | Standard AI Wrappers |
  42. | :--- | :--- | :--- |
  43. | **🧠 Fractal Intelligence** | **573 Core Skills** with 2977 nested tactics | Single-purpose prompts |
  44. | **πŸ›‘οΈ Watchdog System** | Real-time hang detection & error learning | Direct failures / Silent crashes |
  45. | **🌊 Scale Adaptive** | Modular DNA for Instant, Creative, or SME | One-size-fits-all |
  46. | **πŸ› οΈ Self-Healing** | Auto-repair logic via unified god command | Manual JSON debugging |
  47. | **πŸ”’ Provenance** | NPM Signed Builds (Sigstore) | Unverified builds |
  48. ---
  49. ## 🎯 3 Steps to Your First App
  50. 1. **Launch Terminal**: Open Command Prompt or Powershell.
  51. 2. **Execute God Command**: \`npx agent-skills-setup-for-antigravity my-app\`
  52. 3. **Talk to the Brain**: Interact with your new Virtual Team.
  53. ---
  54. ## πŸ“‚ Visual Brain Structure
  55. A fracture-free, standardized architecture for scalable AI development.
  56. ```text
  57. your-project/
  58. β”œβ”€β”€ .agent/ # 🧠 THE BRAIN (Fractal Core)
  59. β”‚ β”œβ”€β”€ .shared/ # ⛩️ Core Library (API/DB/Security Standards)
  60. β”‚ β”œβ”€β”€ rules/ # βš–οΈ Governance (Compliance, Context)
  61. β”‚ β”œβ”€β”€ skills/ # πŸ› οΈ Mastery (573 Fractal Skills)
  62. β”‚ └── workflows/ # πŸš€ Ops (/create, /debug, /audit)
  63. └── GEMINI.md # πŸ“‹ Agent Identity & Configuration
  64. ```
  65. > [!NOTE]
  66. > **Scope Definition**:
  67. > - **Global**: The CLI Tool (`npx agent-skills-setup-for-antigravity`) acts as the installer.
  68. > - **Workspace**: All Rules (`.agent/rules`), Skills, and Workflows are installed **Locally** into your project. This ensures total isolation context.
  69. ---
  70. ## πŸš€ Power Commands
  71. | Command | Action | Logic |
  72. | :--- | :--- | :--- |
  73. | `npx agent-skills-setup-for-antigravity manager` | **Manager View** | Launches Realtime Swarm Dashboard (Agent-First Mode). |
  74. | `npx agent-skills-setup-for-antigravity .` | **Repair / Sync** | Scans Global (`GEMINI.md`) & Workspace (`.agent`). Fills gaps. |
  75. | `npx agent-skills-setup-for-antigravity validate` | **Health Check** | Verifies integrity of both scopes. |
  76. | `npx agent-skills-setup-for-antigravity update` | **Upgrade** | Updates Core DNA while respecting Scope boundaries. |
  77. ---
  78. ## ❓ Frequent Questions
  79. <details>
  80. <summary><strong>Q: Is this just another AI wrapper?</strong></summary>
  81. A: No. Wrappers are stateless. Antigravity installs a **Fractal Memory System** (`.agent` folder) directly into your project. It gives your AI long-term memory, context awareness, and self-correction capabilities.
  82. </details>
  83. <details>
  84. <summary><strong>Q: What is "Pure Install"?</strong></summary>
  85. A: Starting from v4.1.23, we stripped all bloat. No internal scripts, no dev dependencies. You get **only** the production artifacts needed to run your AI team.
  86. </details>
  87. <details>
  88. <summary><strong>Q: Can I customize the Agents?</strong></summary>
  89. A: Yes. "Agents" are now dynamic personas powered by **Skills**. You can teach them new tricks by adding files to `.agent/skills/` or editing `GEMINI.md`. The system adapts to your instructions instantly.
  90. </details>
  91. <br>
  92. ---
  93. - **[Gemini Usage Guide](docs/GEMINI_USAGE.md)**: How to configure and use with Google Gemini.
  94. - **[Master Operations](docs/MASTER_OPERATIONS.md)**: Deep dive into the IDE's core mechanics.
  95. - **[Publishing Guide](docs/PUBLISHING_GUIDE.md)**: How to release your own Agent packages.
  96. ---
  97. <div align="center">
  98. Developed with πŸ’‘ by <strong>Dokhacgiakhoa</strong><br>
  99. <a href="LICENSE">MIT LICENSE</a>
  100. </div>
.agent/skills/loki-mode/autonomy/run.sh Β· Bundled script Β· 1,991 lines Β· 3 findings marked
  1. #!/bin/bash
  2. #===============================================================================
  3. # Loki Mode - Autonomous Runner
  4. # Single script that handles prerequisites, setup, and autonomous execution
  5. #
  6. # Usage:
  7. # ./autonomy/run.sh [PRD_PATH]
  8. # ./autonomy/run.sh ./docs/requirements.md
  9. # ./autonomy/run.sh # Interactive mode
  10. #
  11. # Environment Variables:
  12. # LOKI_MAX_RETRIES - Max retry attempts (default: 50)
  13. # LOKI_BASE_WAIT - Base wait time in seconds (default: 60)
  14. # LOKI_MAX_WAIT - Max wait time in seconds (default: 3600)
  15. # LOKI_SKIP_PREREQS - Skip prerequisite checks (default: false)
  16. # LOKI_DASHBOARD - Enable web dashboard (default: true)
  17. # LOKI_DASHBOARD_PORT - Dashboard port (default: 57374)
  18. #
  19. # Resource Monitoring (prevents system overload):
  20. # LOKI_RESOURCE_CHECK_INTERVAL - Check resources every N seconds (default: 300 = 5min)
  21. # LOKI_RESOURCE_CPU_THRESHOLD - CPU % threshold to warn (default: 80)
  22. # LOKI_RESOURCE_MEM_THRESHOLD - Memory % threshold to warn (default: 80)
  23. #
  24. # Security & Autonomy Controls (Enterprise):
  25. # LOKI_STAGED_AUTONOMY - Require approval before execution (default: false)
  26. # LOKI_AUDIT_LOG - Enable audit logging (default: false)
  27. # LOKI_MAX_PARALLEL_AGENTS - Limit concurrent agent spawning (default: 10)
  28. # LOKI_SANDBOX_MODE - Run in sandboxed container (default: false, requires Docker)
  29. # LOKI_ALLOWED_PATHS - Comma-separated paths agents can modify (default: all)
  30. # LOKI_BLOCKED_COMMANDS - Comma-separated blocked shell commands (default: rm -rf /)
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 30 on GitHub
  31. #
  32. # SDLC Phase Controls (all enabled by default, set to 'false' to skip):
  33. # LOKI_PHASE_UNIT_TESTS - Run unit tests (default: true)
  34. # LOKI_PHASE_API_TESTS - Functional API testing (default: true)
  35. # LOKI_PHASE_E2E_TESTS - E2E/UI testing with Playwright (default: true)
  36. # LOKI_PHASE_SECURITY - Security scanning OWASP/auth (default: true)
  37. # LOKI_PHASE_INTEGRATION - Integration tests SAML/OIDC/SSO (default: true)
  38. # LOKI_PHASE_CODE_REVIEW - 3-reviewer parallel code review (default: true)
  39. # LOKI_PHASE_WEB_RESEARCH - Competitor/feature gap research (default: true)
  40. # LOKI_PHASE_PERFORMANCE - Load/performance testing (default: true)
  41. # LOKI_PHASE_ACCESSIBILITY - WCAG compliance testing (default: true)
  42. # LOKI_PHASE_REGRESSION - Regression testing (default: true)
  43. # LOKI_PHASE_UAT - UAT simulation (default: true)
  44. #
  45. # Autonomous Loop Controls (Ralph Wiggum Mode):
  46. # LOKI_COMPLETION_PROMISE - EXPLICIT stop condition text (default: none - runs forever)
  47. # Example: "ALL TESTS PASSING 100%"
  48. # Only stops when Claude outputs this EXACT text
  49. # LOKI_MAX_ITERATIONS - Max loop iterations before exit (default: 1000)
  50. # LOKI_PERPETUAL_MODE - Ignore ALL completion signals (default: false)
  51. # Set to 'true' for truly infinite operation
  52. #===============================================================================
  53. set -uo pipefail
  54. SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  55. PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
  56. #===============================================================================
  57. # Self-Copy Protection
  58. # Bash reads scripts incrementally, so editing a running script corrupts execution.
  59. # Solution: Copy ourselves to /tmp and run from there. The original can be safely edited.
  60. #===============================================================================
  61. if [[ -z "${LOKI_RUNNING_FROM_TEMP:-}" ]]; then
  62. TEMP_SCRIPT="/tmp/loki-run-$$.sh"
  63. cp "${BASH_SOURCE[0]}" "$TEMP_SCRIPT"
  64. chmod +x "$TEMP_SCRIPT"
  65. export LOKI_RUNNING_FROM_TEMP=1
  66. export LOKI_ORIGINAL_SCRIPT_DIR="$SCRIPT_DIR"
  67. export LOKI_ORIGINAL_PROJECT_DIR="$PROJECT_DIR"
  68. exec "$TEMP_SCRIPT" "$@"
  69. fi
  70. # Restore original paths when running from temp
  71. SCRIPT_DIR="${LOKI_ORIGINAL_SCRIPT_DIR:-$SCRIPT_DIR}"
  72. PROJECT_DIR="${LOKI_ORIGINAL_PROJECT_DIR:-$PROJECT_DIR}"
  73. # Clean up temp script on exit
  74. trap 'rm -f "${BASH_SOURCE[0]}" 2>/dev/null' EXIT
  75. # Configuration
  76. MAX_RETRIES=${LOKI_MAX_RETRIES:-50}
  77. BASE_WAIT=${LOKI_BASE_WAIT:-60}
  78. MAX_WAIT=${LOKI_MAX_WAIT:-3600}
  79. SKIP_PREREQS=${LOKI_SKIP_PREREQS:-false}
  80. ENABLE_DASHBOARD=${LOKI_DASHBOARD:-true}
  81. DASHBOARD_PORT=${LOKI_DASHBOARD_PORT:-57374}
  82. RESOURCE_CHECK_INTERVAL=${LOKI_RESOURCE_CHECK_INTERVAL:-300} # Check every 5 minutes
  83. RESOURCE_CPU_THRESHOLD=${LOKI_RESOURCE_CPU_THRESHOLD:-80} # CPU % threshold
  84. RESOURCE_MEM_THRESHOLD=${LOKI_RESOURCE_MEM_THRESHOLD:-80} # Memory % threshold
  85. # Security & Autonomy Controls
  86. STAGED_AUTONOMY=${LOKI_STAGED_AUTONOMY:-false} # Require plan approval
  87. AUDIT_LOG_ENABLED=${LOKI_AUDIT_LOG:-false} # Enable audit logging
  88. MAX_PARALLEL_AGENTS=${LOKI_MAX_PARALLEL_AGENTS:-10} # Limit concurrent agents
  89. SANDBOX_MODE=${LOKI_SANDBOX_MODE:-false} # Docker sandbox mode
  90. ALLOWED_PATHS=${LOKI_ALLOWED_PATHS:-""} # Empty = all paths allowed
  91. BLOCKED_COMMANDS=${LOKI_BLOCKED_COMMANDS:-"rm -rf /,dd if=,mkfs,:(){ :|:& };:"}
    • Note: Quoted as data in code: Matches a classic shell fork-bomb pattern
    • Line 98 on GitHub
  92. STATUS_MONITOR_PID=""
  93. DASHBOARD_PID=""
  94. RESOURCE_MONITOR_PID=""
  95. # SDLC Phase Controls (all enabled by default)
  96. PHASE_UNIT_TESTS=${LOKI_PHASE_UNIT_TESTS:-true}
  97. PHASE_API_TESTS=${LOKI_PHASE_API_TESTS:-true}
  98. PHASE_E2E_TESTS=${LOKI_PHASE_E2E_TESTS:-true}
  99. PHASE_SECURITY=${LOKI_PHASE_SECURITY:-true}
  100. PHASE_INTEGRATION=${LOKI_PHASE_INTEGRATION:-true}
  101. PHASE_CODE_REVIEW=${LOKI_PHASE_CODE_REVIEW:-true}
  102. PHASE_WEB_RESEARCH=${LOKI_PHASE_WEB_RESEARCH:-true}
  103. PHASE_PERFORMANCE=${LOKI_PHASE_PERFORMANCE:-true}
  104. PHASE_ACCESSIBILITY=${LOKI_PHASE_ACCESSIBILITY:-true}
  105. PHASE_REGRESSION=${LOKI_PHASE_REGRESSION:-true}
  106. PHASE_UAT=${LOKI_PHASE_UAT:-true}
  107. # Autonomous Loop Controls (Ralph Wiggum Mode)
  108. # Default: No auto-completion - runs until max iterations or explicit promise
  109. COMPLETION_PROMISE=${LOKI_COMPLETION_PROMISE:-""}
  110. MAX_ITERATIONS=${LOKI_MAX_ITERATIONS:-1000}
  111. ITERATION_COUNT=0
  112. # Perpetual mode: never stop unless max iterations (ignores all completion signals)
  113. PERPETUAL_MODE=${LOKI_PERPETUAL_MODE:-false}
  114. # Colors
  115. RED='\033[0;31m'
  116. GREEN='\033[0;32m'
  117. YELLOW='\033[1;33m'
  118. BLUE='\033[0;34m'
  119. CYAN='\033[0;36m'
  120. BOLD='\033[1m'
  121. NC='\033[0m'
  122. #===============================================================================
  123. # Logging Functions
  124. #===============================================================================
  125. log_header() {
  126. echo ""
  127. echo -e "${BLUE}╔════════════════════════════════════════════════════════════════╗${NC}"
  128. echo -e "${BLUE}β•‘${NC} ${BOLD}$1${NC}"
  129. echo -e "${BLUE}β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•${NC}"
  130. }
  131. log_info() { echo -e "${GREEN}[INFO]${NC} $*"; }
  132. log_warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
  133. log_warning() { log_warn "$@"; } # Alias for backwards compatibility
  134. log_error() { echo -e "${RED}[ERROR]${NC} $*"; }
  135. log_step() { echo -e "${CYAN}[STEP]${NC} $*"; }
  136. #===============================================================================
  137. # Prerequisites Check
  138. #===============================================================================
  139. check_prerequisites() {
  140. log_header "Checking Prerequisites"
  141. local missing=()
  142. # Check Claude Code CLI
  143. log_step "Checking Claude Code CLI..."
  144. if command -v claude &> /dev/null; then
  145. local version=$(claude --version 2>/dev/null | head -1 || echo "unknown")
  146. log_info "Claude Code CLI: $version"
  147. else
  148. missing+=("claude")
  149. log_error "Claude Code CLI not found"
  150. log_info "Install: https://claude.ai/code or npm install -g @anthropic-ai/claude-code"
  151. fi
  152. # Check Python 3
  153. log_step "Checking Python 3..."
  154. if command -v python3 &> /dev/null; then
  155. local py_version=$(python3 --version 2>&1)
  156. log_info "Python: $py_version"
  157. else
  158. missing+=("python3")
  159. log_error "Python 3 not found"
  160. fi
  161. # Check Git
  162. log_step "Checking Git..."
  163. if command -v git &> /dev/null; then
  164. local git_version=$(git --version)
  165. log_info "Git: $git_version"
  166. else
  167. missing+=("git")
  168. log_error "Git not found"
  169. fi
  170. # Check Node.js (optional but recommended)
  171. log_step "Checking Node.js (optional)..."
  172. if command -v node &> /dev/null; then
  173. local node_version=$(node --version)
  174. log_info "Node.js: $node_version"
  175. else
  176. log_warn "Node.js not found (optional, needed for some builds)"
  177. fi
  178. # Check npm (optional)
  179. if command -v npm &> /dev/null; then
  180. local npm_version=$(npm --version)
  181. log_info "npm: $npm_version"
  182. fi
  183. # Check curl (for web fetches)
  184. log_step "Checking curl..."
  185. if command -v curl &> /dev/null; then
  186. log_info "curl: available"
  187. else
  188. missing+=("curl")
  189. log_error "curl not found"
  190. fi
  191. # Check jq (optional but helpful)
  192. log_step "Checking jq (optional)..."
  193. if command -v jq &> /dev/null; then
  194. log_info "jq: available"
  195. else
  196. log_warn "jq not found (optional, for JSON parsing)"
  197. fi
  198. # Summary
  199. echo ""
  200. if [ ${#missing[@]} -gt 0 ]; then
  201. log_error "Missing required tools: ${missing[*]}"
  202. log_info "Please install the missing tools and try again."
  203. return 1
  204. else
  205. log_info "All required prerequisites are installed!"
  206. return 0
  207. fi
  208. }
  209. #===============================================================================
  210. # Skill Installation Check
  211. #===============================================================================
  212. check_skill_installed() {
  213. log_header "Checking Loki Mode Skill"
  214. local skill_locations=(
  215. "$HOME/.claude/skills/loki-mode/SKILL.md"
  216. ".claude/skills/loki-mode/SKILL.md"
  217. "$PROJECT_DIR/SKILL.md"
  218. )
  219. for loc in "${skill_locations[@]}"; do
  220. if [ -f "$loc" ]; then
  221. log_info "Skill found: $loc"
  222. return 0
  223. fi
  224. done
  225. log_warn "Loki Mode skill not found in standard locations"
  226. log_info "The skill will be used from: $PROJECT_DIR/SKILL.md"
  227. if [ -f "$PROJECT_DIR/SKILL.md" ]; then
  228. log_info "Using skill from project directory"
  229. return 0
  230. else
  231. log_error "SKILL.md not found!"
  232. return 1
  233. fi
  234. }
  235. #===============================================================================
  236. # Initialize Loki Directory
  237. #===============================================================================
  238. init_loki_dir() {
  239. log_header "Initializing Loki Mode Directory"
  240. mkdir -p .loki/{state,queue,messages,logs,config,prompts,artifacts,scripts}
  241. mkdir -p .loki/queue
  242. mkdir -p .loki/state/checkpoints
  243. mkdir -p .loki/artifacts/{releases,reports,backups}
  244. mkdir -p .loki/memory/{ledgers,handoffs,learnings,episodic,semantic,skills}
  245. mkdir -p .loki/metrics/{efficiency,rewards}
  246. mkdir -p .loki/rules
  247. mkdir -p .loki/signals
  248. # Initialize queue files if they don't exist
  249. for queue in pending in-progress completed failed dead-letter; do
  250. if [ ! -f ".loki/queue/${queue}.json" ]; then
  251. echo "[]" > ".loki/queue/${queue}.json"
  252. fi
  253. done
  254. # Initialize orchestrator state if it doesn't exist
  255. if [ ! -f ".loki/state/orchestrator.json" ]; then
  256. cat > ".loki/state/orchestrator.json" << EOF
  257. {
  258. "version": "$(cat "$PROJECT_DIR/VERSION" 2>/dev/null || echo "2.2.0")",
  259. "currentPhase": "BOOTSTRAP",
  260. "startedAt": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  261. "agents": {},
  262. "metrics": {
  263. "tasksCompleted": 0,
  264. "tasksFailed": 0,
  265. "retries": 0
  266. }
  267. }
  268. EOF
  269. fi
  270. log_info "Loki directory initialized: .loki/"
  271. }
  272. #===============================================================================
  273. # Task Status Monitor
  274. #===============================================================================
  275. update_status_file() {
  276. # Create a human-readable status file
  277. local status_file=".loki/STATUS.txt"
  278. # Get current phase
  279. local current_phase="UNKNOWN"
  280. if [ -f ".loki/state/orchestrator.json" ]; then
  281. current_phase=$(python3 -c "import json; print(json.load(open('.loki/state/orchestrator.json')).get('currentPhase', 'UNKNOWN'))" 2>/dev/null || echo "UNKNOWN")
  282. fi
  283. # Count tasks in each queue
  284. local pending=0 in_progress=0 completed=0 failed=0
  285. [ -f ".loki/queue/pending.json" ] && pending=$(python3 -c "import json; print(len(json.load(open('.loki/queue/pending.json'))))" 2>/dev/null || echo "0")
  286. [ -f ".loki/queue/in-progress.json" ] && in_progress=$(python3 -c "import json; print(len(json.load(open('.loki/queue/in-progress.json'))))" 2>/dev/null || echo "0")
  287. [ -f ".loki/queue/completed.json" ] && completed=$(python3 -c "import json; print(len(json.load(open('.loki/queue/completed.json'))))" 2>/dev/null || echo "0")
  288. [ -f ".loki/queue/failed.json" ] && failed=$(python3 -c "import json; print(len(json.load(open('.loki/queue/failed.json'))))" 2>/dev/null || echo "0")
  289. cat > "$status_file" << EOF
  290. ╔════════════════════════════════════════════════════════════════╗
  291. β•‘ LOKI MODE STATUS β•‘
  292. β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
  293. Updated: $(date)
  294. Phase: $current_phase
  295. Tasks:
  296. β”œβ”€ Pending: $pending
  297. β”œβ”€ In Progress: $in_progress
  298. β”œβ”€ Completed: $completed
  299. └─ Failed: $failed
  300. Monitor: watch -n 2 cat .loki/STATUS.txt
  301. EOF
  302. }
  303. start_status_monitor() {
  304. log_step "Starting status monitor..."
  305. # Initial update
  306. update_status_file
  307. update_agents_state
  308. # Background update loop
  309. (
  310. while true; do
  311. update_status_file
  312. update_agents_state
  313. sleep 5
  314. done
  315. ) &
  316. STATUS_MONITOR_PID=$!
  317. log_info "Status monitor started"
  318. log_info "Monitor progress: ${CYAN}watch -n 2 cat .loki/STATUS.txt${NC}"
  319. }
  320. stop_status_monitor() {
  321. if [ -n "$STATUS_MONITOR_PID" ]; then
  322. kill "$STATUS_MONITOR_PID" 2>/dev/null || true
  323. wait "$STATUS_MONITOR_PID" 2>/dev/null || true
  324. fi
  325. stop_resource_monitor
  326. }
  327. #===============================================================================
  328. # Web Dashboard
  329. #===============================================================================
  330. generate_dashboard() {
  331. # Generate HTML dashboard with Anthropic design language + Agent Monitoring
  332. cat > .loki/dashboard/index.html << 'DASHBOARD_HTML'
  333. <!DOCTYPE html>
  334. <html lang="en">
  335. <head>
  336. <meta charset="UTF-8">
  337. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  338. <title>Loki Mode Dashboard</title>
  339. <style>
  340. * { box-sizing: border-box; margin: 0; padding: 0; }
  341. body {
  342. font-family: 'SΓΆhne', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  343. background: #FAF9F6;
  344. color: #1A1A1A;
  345. padding: 24px;
  346. min-height: 100vh;
  347. }
  348. .header {
  349. text-align: center;
  350. padding: 32px 20px;
  351. margin-bottom: 32px;
  352. }
  353. .header h1 {
  354. color: #D97757;
  355. font-size: 28px;
  356. font-weight: 600;
  357. letter-spacing: -0.5px;
  358. margin-bottom: 8px;
  359. }
  360. .header .subtitle {
  361. color: #666;
  362. font-size: 14px;
  363. font-weight: 400;
  364. }
  365. .header .phase {
  366. display: inline-block;
  367. margin-top: 16px;
  368. padding: 8px 16px;
  369. background: #FFF;
  370. border: 1px solid #E5E3DE;
  371. border-radius: 20px;
  372. font-size: 13px;
  373. color: #1A1A1A;
  374. font-weight: 500;
  375. }
  376. .stats {
  377. display: flex;
  378. justify-content: center;
  379. gap: 16px;
  380. margin-bottom: 40px;
  381. flex-wrap: wrap;
  382. }
  383. .stat {
  384. background: #FFF;
  385. border: 1px solid #E5E3DE;
  386. border-radius: 12px;
  387. padding: 20px 32px;
  388. text-align: center;
  389. min-width: 140px;
  390. transition: box-shadow 0.2s ease;
  391. }
  392. .stat:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.06); }
  393. .stat .number { font-size: 36px; font-weight: 600; margin-bottom: 4px; }
  394. .stat .label { font-size: 12px; color: #888; text-transform: uppercase; letter-spacing: 0.5px; }
  395. .stat.pending .number { color: #D97757; }
  396. .stat.progress .number { color: #5B8DEF; }
  397. .stat.completed .number { color: #2E9E6E; }
  398. .stat.failed .number { color: #D44F4F; }
  399. .stat.agents .number { color: #9B6DD6; }
  400. .section-header {
  401. text-align: center;
  402. font-size: 16px;
  403. font-weight: 600;
  404. color: #666;
  405. margin: 40px 0 20px 0;
  406. text-transform: uppercase;
  407. letter-spacing: 1px;
  408. }
  409. .agents-grid {
  410. display: grid;
  411. grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  412. gap: 16px;
  413. max-width: 1400px;
  414. margin: 0 auto 40px auto;
  415. }
  416. .agent-card {
  417. background: #FFF;
  418. border: 1px solid #E5E3DE;
  419. border-radius: 12px;
  420. padding: 16px;
  421. transition: box-shadow 0.2s ease, border-color 0.2s ease;
  422. }
  423. .agent-card:hover {
  424. box-shadow: 0 4px 12px rgba(0,0,0,0.06);
  425. border-color: #9B6DD6;
  426. }
  427. .agent-card .agent-header {
  428. display: flex;
  429. justify-content: space-between;
  430. align-items: flex-start;
  431. margin-bottom: 12px;
  432. }
  433. .agent-card .agent-id {
  434. font-size: 11px;
  435. color: #999;
  436. font-family: monospace;
  437. }
  438. .agent-card .model-badge {
  439. padding: 4px 10px;
  440. border-radius: 6px;
  441. font-size: 10px;
  442. font-weight: 600;
  443. text-transform: uppercase;
  444. letter-spacing: 0.5px;
  445. }
  446. .agent-card .model-badge.sonnet {
  447. background: #E8F0FD;
  448. color: #5B8DEF;
  449. }
  450. .agent-card .model-badge.haiku {
  451. background: #FFF4E6;
  452. color: #F59E0B;
  453. }
  454. .agent-card .model-badge.opus {
  455. background: #F3E8FF;
  456. color: #9B6DD6;
  457. }
  458. .agent-card .agent-type {
  459. font-size: 14px;
  460. font-weight: 600;
  461. color: #1A1A1A;
  462. margin-bottom: 8px;
  463. }
  464. .agent-card .agent-status {
  465. display: inline-block;
  466. padding: 3px 8px;
  467. border-radius: 4px;
  468. font-size: 10px;
  469. font-weight: 500;
  470. margin-bottom: 12px;
  471. }
  472. .agent-card .agent-status.active {
  473. background: #E6F5EE;
  474. color: #2E9E6E;
  475. }
  476. .agent-card .agent-status.completed {
  477. background: #F0EFEA;
  478. color: #666;
  479. }
  480. .agent-card .agent-work {
  481. font-size: 12px;
  482. color: #666;
  483. line-height: 1.5;
  484. margin-bottom: 8px;
  485. }
  486. .agent-card .agent-meta {
  487. display: flex;
  488. gap: 12px;
  489. font-size: 11px;
  490. color: #999;
  491. margin-top: 8px;
  492. padding-top: 8px;
  493. border-top: 1px solid #F0EFEA;
  494. }
  495. .agent-card .agent-meta span {
  496. display: flex;
  497. align-items: center;
  498. gap: 4px;
  499. }
  500. .columns {
  501. display: flex;
  502. gap: 20px;
  503. overflow-x: auto;
  504. padding-bottom: 24px;
  505. max-width: 1400px;
  506. margin: 0 auto;
  507. }
  508. .column {
  509. flex: 1;
  510. min-width: 300px;
  511. max-width: 350px;
  512. background: #FFF;
  513. border: 1px solid #E5E3DE;
  514. border-radius: 12px;
  515. padding: 20px;
  516. }
  517. .column h2 {
  518. font-size: 13px;
  519. font-weight: 600;
  520. color: #666;
  521. margin-bottom: 16px;
  522. display: flex;
  523. align-items: center;
  524. gap: 10px;
  525. text-transform: uppercase;
  526. letter-spacing: 0.5px;
  527. }
  528. .column h2 .count {
  529. background: #F0EFEA;
  530. padding: 3px 10px;
  531. border-radius: 12px;
  532. font-size: 11px;
  533. color: #1A1A1A;
  534. }
  535. .column.pending h2 .count { background: #FCEEE8; color: #D97757; }
  536. .column.progress h2 .count { background: #E8F0FD; color: #5B8DEF; }
  537. .column.completed h2 .count { background: #E6F5EE; color: #2E9E6E; }
  538. .column.failed h2 .count { background: #FCE8E8; color: #D44F4F; }
  539. .task {
  540. background: #FAF9F6;
  541. border: 1px solid #E5E3DE;
  542. border-radius: 8px;
  543. padding: 14px;
  544. margin-bottom: 12px;
  545. transition: border-color 0.2s ease;
  546. }
  547. .task:hover { border-color: #D97757; }
  548. .task .id { font-size: 10px; color: #999; margin-bottom: 6px; font-family: monospace; }
  549. .task .type {
  550. display: inline-block;
  551. background: #FCEEE8;
  552. color: #D97757;
  553. padding: 3px 10px;
  554. border-radius: 4px;
  555. font-size: 11px;
  556. font-weight: 500;
  557. margin-bottom: 8px;
  558. }
  559. .task .title { font-size: 13px; color: #1A1A1A; line-height: 1.5; }
  560. .task .error {
  561. font-size: 11px;
  562. color: #D44F4F;
  563. margin-top: 10px;
  564. padding: 10px;
  565. background: #FCE8E8;
  566. border-radius: 6px;
  567. font-family: monospace;
  568. }
  569. .refresh {
  570. position: fixed;
  571. bottom: 24px;
  572. right: 24px;
  573. background: #D97757;
  574. color: white;
  575. border: none;
  576. padding: 12px 24px;
  577. border-radius: 8px;
  578. cursor: pointer;
  579. font-size: 14px;
  580. font-weight: 500;
  581. transition: background 0.2s ease;
  582. box-shadow: 0 4px 12px rgba(217, 119, 87, 0.3);
  583. }
  584. .refresh:hover { background: #C56747; }
  585. .updated {
  586. text-align: center;
  587. color: #999;
  588. font-size: 12px;
  589. margin-top: 24px;
  590. }
  591. .empty {
  592. color: #999;
  593. font-size: 13px;
  594. text-align: center;
  595. padding: 24px;
  596. font-style: italic;
  597. }
  598. .powered-by {
  599. text-align: center;
  600. margin-top: 40px;
  601. padding-top: 24px;
  602. border-top: 1px solid #E5E3DE;
  603. color: #999;
  604. font-size: 12px;
  605. }
  606. .powered-by span { color: #D97757; font-weight: 500; }
  607. </style>
  608. </head>
  609. <body>
  610. <div class="header">
  611. <h1>LOKI MODE</h1>
  612. <div class="subtitle">Autonomous Multi-Agent Startup System</div>
  613. <div class="phase" id="phase">Loading...</div>
  614. </div>
  615. <div class="stats">
  616. <div class="stat agents"><div class="number" id="agents-count">-</div><div class="label">Active Agents</div></div>
  617. <div class="stat pending"><div class="number" id="pending-count">-</div><div class="label">Pending</div></div>
  618. <div class="stat progress"><div class="number" id="progress-count">-</div><div class="label">In Progress</div></div>
  619. <div class="stat completed"><div class="number" id="completed-count">-</div><div class="label">Completed</div></div>
  620. <div class="stat failed"><div class="number" id="failed-count">-</div><div class="label">Failed</div></div>
  621. </div>
  622. <div class="section-header">Active Agents</div>
  623. <div class="agents-grid" id="agents-grid"></div>
  624. <div class="section-header">Task Queue</div>
  625. <div class="columns">
  626. <div class="column pending"><h2>Pending <span class="count" id="pending-badge">0</span></h2><div id="pending-tasks"></div></div>
  627. <div class="column progress"><h2>In Progress <span class="count" id="progress-badge">0</span></h2><div id="progress-tasks"></div></div>
  628. <div class="column completed"><h2>Completed <span class="count" id="completed-badge">0</span></h2><div id="completed-tasks"></div></div>
  629. <div class="column failed"><h2>Failed <span class="count" id="failed-badge">0</span></h2><div id="failed-tasks"></div></div>
  630. </div>
  631. <div class="updated" id="updated">Last updated: -</div>
  632. <div class="powered-by">Powered by <span>Claude</span></div>
  633. <button class="refresh" onclick="loadData()">Refresh</button>
  634. <script>
  635. async function loadJSON(path) {
  636. try {
  637. const res = await fetch(path + '?t=' + Date.now());
  638. if (!res.ok) return [];
  639. const text = await res.text();
  640. if (!text.trim()) return [];
  641. const data = JSON.parse(text);
  642. return Array.isArray(data) ? data : (data.tasks || data.agents || []);
  643. } catch { return []; }
  644. }
  645. function getModelClass(model) {
  646. if (!model) return 'sonnet';
  647. const m = model.toLowerCase();
  648. if (m.includes('haiku')) return 'haiku';
  649. if (m.includes('opus')) return 'opus';
  650. return 'sonnet';
  651. }
  652. function formatDuration(isoDate) {
  653. if (!isoDate) return 'Unknown';
  654. const start = new Date(isoDate);
  655. const now = new Date();
  656. const seconds = Math.floor((now - start) / 1000);
  657. if (seconds < 60) return seconds + 's';
  658. if (seconds < 3600) return Math.floor(seconds / 60) + 'm';
  659. return Math.floor(seconds / 3600) + 'h ' + Math.floor((seconds % 3600) / 60) + 'm';
  660. }
  661. function renderAgent(agent) {
  662. const modelClass = getModelClass(agent.model);
  663. const modelName = agent.model || 'Sonnet 4.5';
  664. const agentType = agent.agent_type || 'general-purpose';
  665. const status = agent.status === 'completed' ? 'completed' : 'active';
  666. const currentTask = agent.current_task || (agent.tasks_completed && agent.tasks_completed.length > 0
  667. ? 'Completed: ' + agent.tasks_completed.join(', ')
  668. : 'Initializing...');
  669. const duration = formatDuration(agent.spawned_at);
  670. const tasksCount = agent.tasks_completed ? agent.tasks_completed.length : 0;
  671. return `
  672. <div class="agent-card">
  673. <div class="agent-header">
  674. <div class="agent-id">${agent.agent_id || 'Unknown'}</div>
  675. <div class="model-badge ${modelClass}">${modelName}</div>
  676. </div>
  677. <div class="agent-type">${agentType}</div>
  678. <div class="agent-status ${status}">${status}</div>
  679. <div class="agent-work">${currentTask}</div>
  680. <div class="agent-meta">
  681. <span>⏱ ${duration}</span>
  682. <span>βœ“ ${tasksCount} tasks</span>
  683. </div>
  684. </div>
  685. `;
  686. }
  687. function renderTask(task) {
  688. const payload = task.payload || {};
  689. const title = payload.description || payload.action || task.type || 'Task';
  690. const error = task.lastError ? `<div class="error">${task.lastError}</div>` : '';
  691. return `<div class="task"><div class="id">${task.id}</div><span class="type">${task.type || 'general'}</span><div class="title">${title}</div>${error}</div>`;
  692. }
  693. async function loadData() {
  694. const [pending, progress, completed, failed, agents] = await Promise.all([
  695. loadJSON('../queue/pending.json'),
  696. loadJSON('../queue/in-progress.json'),
  697. loadJSON('../queue/completed.json'),
  698. loadJSON('../queue/failed.json'),
  699. loadJSON('../state/agents.json')
  700. ]);
  701. // Agent stats
  702. document.getElementById('agents-count').textContent = agents.length;
  703. document.getElementById('agents-grid').innerHTML = agents.length
  704. ? agents.map(renderAgent).join('')
  705. : '<div class="empty">No active agents</div>';
  706. // Task stats
  707. document.getElementById('pending-count').textContent = pending.length;
  708. document.getElementById('progress-count').textContent = progress.length;
  709. document.getElementById('completed-count').textContent = completed.length;
  710. document.getElementById('failed-count').textContent = failed.length;
  711. document.getElementById('pending-badge').textContent = pending.length;
  712. document.getElementById('progress-badge').textContent = progress.length;
  713. document.getElementById('completed-badge').textContent = completed.length;
  714. document.getElementById('failed-badge').textContent = failed.length;
  715. document.getElementById('pending-tasks').innerHTML = pending.length ? pending.map(renderTask).join('') : '<div class="empty">No pending tasks</div>';
  716. document.getElementById('progress-tasks').innerHTML = progress.length ? progress.map(renderTask).join('') : '<div class="empty">No tasks in progress</div>';
  717. document.getElementById('completed-tasks').innerHTML = completed.length ? completed.slice(-10).reverse().map(renderTask).join('') : '<div class="empty">No completed tasks</div>';
  718. document.getElementById('failed-tasks').innerHTML = failed.length ? failed.map(renderTask).join('') : '<div class="empty">No failed tasks</div>';
  719. try {
  720. const state = await fetch('../state/orchestrator.json?t=' + Date.now()).then(r => r.json());
  721. document.getElementById('phase').textContent = 'Phase: ' + (state.currentPhase || 'UNKNOWN');
  722. } catch { document.getElementById('phase').textContent = 'Phase: UNKNOWN'; }
  723. document.getElementById('updated').textContent = 'Last updated: ' + new Date().toLocaleTimeString();
  724. }
  725. loadData();
  726. setInterval(loadData, 3000);
  727. </script>
  728. </body>
  729. </html>
  730. DASHBOARD_HTML
  731. }
  732. update_agents_state() {
  733. # Aggregate agent information from .agent/sub-agents/*.json into .loki/state/agents.json
  734. local agents_dir=".agent/sub-agents"
  735. local output_file=".loki/state/agents.json"
  736. # Initialize empty array if no agents directory
  737. if [ ! -d "$agents_dir" ]; then
  738. echo "[]" > "$output_file"
  739. return
  740. fi
  741. # Find all agent JSON files and aggregate them
  742. local agents_json="["
  743. local first=true
  744. for agent_file in "$agents_dir"/*.json; do
  745. # Skip if no JSON files exist
  746. [ -e "$agent_file" ] || continue
  747. # Read agent JSON
  748. local agent_data=$(cat "$agent_file" 2>/dev/null)
  749. if [ -n "$agent_data" ]; then
  750. # Add comma separator for all but first entry
  751. if [ "$first" = true ]; then
  752. first=false
  753. else
  754. agents_json="${agents_json},"
  755. fi
  756. agents_json="${agents_json}${agent_data}"
  757. fi
  758. done
  759. agents_json="${agents_json}]"
  760. # Write aggregated data
  761. echo "$agents_json" > "$output_file"
  762. }
  763. #===============================================================================
  764. # Resource Monitoring
  765. #===============================================================================
  766. check_system_resources() {
  767. # Check CPU and memory usage and write status to .loki/state/resources.json
  768. local output_file=".loki/state/resources.json"
  769. # Get CPU usage (average across all cores)
  770. local cpu_usage=0
  771. if [[ "$OSTYPE" == "darwin"* ]]; then
  772. # macOS: get CPU idle from top header, calculate usage = 100 - idle
  773. local idle=$(top -l 2 -n 0 | grep "CPU usage" | tail -1 | awk -F'[:,]' '{for(i=1;i<=NF;i++) if($i ~ /idle/) print $(i)}' | awk '{print int($1)}')
  774. cpu_usage=$((100 - ${idle:-0}))
  775. elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
  776. # Linux: use top or mpstat
  777. cpu_usage=$(top -bn2 | grep "Cpu(s)" | tail -1 | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print int(100 - $1)}')
  778. else
  779. cpu_usage=0
  780. fi
  781. # Get memory usage
  782. local mem_usage=0
  783. if [[ "$OSTYPE" == "darwin"* ]]; then
  784. # macOS: use vm_stat
  785. local page_size=$(pagesize)
  786. local vm_stat=$(vm_stat)
  787. local pages_free=$(echo "$vm_stat" | awk '/Pages free/ {print $3}' | tr -d '.')
  788. local pages_active=$(echo "$vm_stat" | awk '/Pages active/ {print $3}' | tr -d '.')
  789. local pages_inactive=$(echo "$vm_stat" | awk '/Pages inactive/ {print $3}' | tr -d '.')
  790. local pages_speculative=$(echo "$vm_stat" | awk '/Pages speculative/ {print $3}' | tr -d '.')
  791. local pages_wired=$(echo "$vm_stat" | awk '/Pages wired down/ {print $4}' | tr -d '.')
  792. local total_pages=$((pages_free + pages_active + pages_inactive + pages_speculative + pages_wired))
  793. local used_pages=$((pages_active + pages_wired))
  794. mem_usage=$((used_pages * 100 / total_pages))
  795. elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
  796. # Linux: use free
  797. mem_usage=$(free | grep Mem | awk '{print int($3/$2 * 100)}')
  798. else
  799. mem_usage=0
  800. fi
  801. # Determine status
  802. local cpu_status="ok"
  803. local mem_status="ok"
  804. local overall_status="ok"
  805. local warning_message=""
  806. if [ "$cpu_usage" -ge "$RESOURCE_CPU_THRESHOLD" ]; then
  807. cpu_status="high"
  808. overall_status="warning"
  809. warning_message="CPU usage is ${cpu_usage}% (threshold: ${RESOURCE_CPU_THRESHOLD}%). Consider reducing parallel agent count or pausing non-critical tasks."
  810. fi
  811. if [ "$mem_usage" -ge "$RESOURCE_MEM_THRESHOLD" ]; then
  812. mem_status="high"
  813. overall_status="warning"
  814. if [ -n "$warning_message" ]; then
  815. warning_message="${warning_message} Memory usage is ${mem_usage}% (threshold: ${RESOURCE_MEM_THRESHOLD}%)."
  816. else
  817. warning_message="Memory usage is ${mem_usage}% (threshold: ${RESOURCE_MEM_THRESHOLD}%). Consider reducing parallel agent count or cleaning up resources."
  818. fi
  819. fi
  820. # Write JSON status
  821. cat > "$output_file" << EOF
  822. {
  823. "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  824. "cpu": {
  825. "usage_percent": $cpu_usage,
  826. "threshold_percent": $RESOURCE_CPU_THRESHOLD,
  827. "status": "$cpu_status"
  828. },
  829. "memory": {
  830. "usage_percent": $mem_usage,
  831. "threshold_percent": $RESOURCE_MEM_THRESHOLD,
  832. "status": "$mem_status"
  833. },
  834. "overall_status": "$overall_status",
  835. "warning_message": "$warning_message"
  836. }
  837. EOF
  838. # Log warning if resources are high
  839. if [ "$overall_status" = "warning" ]; then
  840. log_warn "RESOURCE WARNING: $warning_message"
  841. fi
  842. }
  843. start_resource_monitor() {
  844. log_step "Starting resource monitor (checks every ${RESOURCE_CHECK_INTERVAL}s)..."
  845. # Initial check
  846. check_system_resources
  847. # Background monitoring loop
  848. (
  849. while true; do
  850. sleep "$RESOURCE_CHECK_INTERVAL"
  851. check_system_resources
  852. done
  853. ) &
  854. RESOURCE_MONITOR_PID=$!
  855. log_info "Resource monitor started (CPU threshold: ${RESOURCE_CPU_THRESHOLD}%, Memory threshold: ${RESOURCE_MEM_THRESHOLD}%)"
  856. log_info "Check status: ${CYAN}cat .loki/state/resources.json${NC}"
  857. }
  858. stop_resource_monitor() {
  859. if [ -n "$RESOURCE_MONITOR_PID" ]; then
  860. kill "$RESOURCE_MONITOR_PID" 2>/dev/null || true
  861. wait "$RESOURCE_MONITOR_PID" 2>/dev/null || true
  862. fi
  863. }
  864. #===============================================================================
  865. # Audit Logging (Enterprise Security)
  866. #===============================================================================
  867. audit_log() {
  868. # Log security-relevant events for enterprise compliance
  869. local event_type="$1"
  870. local event_data="$2"
  871. local audit_file=".loki/logs/audit-$(date +%Y%m%d).jsonl"
  872. if [ "$AUDIT_LOG_ENABLED" != "true" ]; then
  873. return
  874. fi
  875. mkdir -p .loki/logs
  876. local log_entry=$(cat << EOF
  877. {"timestamp":"$(date -u +%Y-%m-%dT%H:%M:%SZ)","event":"$event_type","data":"$event_data","user":"$(whoami)","pid":$$}
  878. EOF
  879. )
  880. echo "$log_entry" >> "$audit_file"
  881. }
  882. check_staged_autonomy() {
  883. # In staged autonomy mode, write plan and wait for approval
  884. local plan_file="$1"
  885. if [ "$STAGED_AUTONOMY" != "true" ]; then
  886. return 0
  887. fi
  888. log_info "STAGED AUTONOMY: Waiting for plan approval..."
  889. log_info "Review plan at: $plan_file"
  890. log_info "Create .loki/signals/PLAN_APPROVED to continue"
  891. audit_log "STAGED_AUTONOMY_WAIT" "plan=$plan_file"
  892. # Wait for approval signal
  893. while [ ! -f ".loki/signals/PLAN_APPROVED" ]; do
  894. sleep 5
  895. done
  896. rm -f ".loki/signals/PLAN_APPROVED"
  897. audit_log "STAGED_AUTONOMY_APPROVED" "plan=$plan_file"
  898. log_success "Plan approved, continuing execution..."
  899. }
  900. check_command_allowed() {
  901. # Check if a command is in the blocked list
  902. local command="$1"
  903. IFS=',' read -ra BLOCKED_ARRAY <<< "$BLOCKED_COMMANDS"
  904. for blocked in "${BLOCKED_ARRAY[@]}"; do
  905. if [[ "$command" == *"$blocked"* ]]; then
  906. audit_log "BLOCKED_COMMAND" "command=$command,pattern=$blocked"
  907. log_error "SECURITY: Blocked dangerous command: $command"
  908. return 1
  909. fi
  910. done
  911. return 0
  912. }
  913. #===============================================================================
  914. # Cross-Project Learnings Database
  915. #===============================================================================
  916. init_learnings_db() {
  917. # Initialize the cross-project learnings database
  918. local learnings_dir="${HOME}/.loki/learnings"
  919. mkdir -p "$learnings_dir"
  920. # Create database files if they don't exist
  921. if [ ! -f "$learnings_dir/patterns.jsonl" ]; then
  922. echo '{"version":"1.0","created":"'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'"}' > "$learnings_dir/patterns.jsonl"
  923. fi
  924. if [ ! -f "$learnings_dir/mistakes.jsonl" ]; then
  925. echo '{"version":"1.0","created":"'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'"}' > "$learnings_dir/mistakes.jsonl"
  926. fi
  927. if [ ! -f "$learnings_dir/successes.jsonl" ]; then
  928. echo '{"version":"1.0","created":"'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'"}' > "$learnings_dir/successes.jsonl"
  929. fi
  930. log_info "Learnings database initialized at: $learnings_dir"
  931. }
  932. save_learning() {
  933. # Save a learning to the cross-project database
  934. local learning_type="$1" # pattern, mistake, success
  935. local category="$2"
  936. local description="$3"
  937. local project="${4:-$(basename "$(pwd)")}"
  938. local learnings_dir="${HOME}/.loki/learnings"
  939. local target_file="$learnings_dir/${learning_type}s.jsonl"
  940. if [ ! -d "$learnings_dir" ]; then
  941. init_learnings_db
  942. fi
  943. local learning_entry=$(cat << EOF
  944. {"timestamp":"$(date -u +%Y-%m-%dT%H:%M:%SZ)","project":"$project","category":"$category","description":"$description"}
  945. EOF
  946. )
  947. echo "$learning_entry" >> "$target_file"
  948. log_info "Saved $learning_type: $category"
  949. }
  950. get_relevant_learnings() {
  951. # Get learnings relevant to the current context
  952. local context="$1"
  953. local learnings_dir="${HOME}/.loki/learnings"
  954. local output_file=".loki/state/relevant-learnings.json"
  955. if [ ! -d "$learnings_dir" ]; then
  956. echo '{"patterns":[],"mistakes":[],"successes":[]}' > "$output_file"
  957. return
  958. fi
  959. # Simple grep-based relevance (can be enhanced with embeddings)
  960. # Pass context via environment variable to avoid quote escaping issues
  961. export LOKI_CONTEXT="$context"
  962. python3 << 'LEARNINGS_SCRIPT'
  963. import json
  964. import os
  965. learnings_dir = os.path.expanduser("~/.loki/learnings")
  966. context = os.environ.get("LOKI_CONTEXT", "").lower()
  967. def load_jsonl(filepath):
  968. entries = []
  969. try:
  970. with open(filepath, 'r') as f:
  971. for line in f:
  972. try:
  973. entry = json.loads(line)
  974. if 'description' in entry:
  975. entries.append(entry)
  976. except:
  977. continue
  978. except:
  979. pass
  980. return entries
  981. def filter_relevant(entries, context, limit=5):
  982. scored = []
  983. for e in entries:
  984. desc = e.get('description', '').lower()
  985. cat = e.get('category', '').lower()
  986. score = sum(1 for word in context.split() if word in desc or word in cat)
  987. if score > 0:
  988. scored.append((score, e))
  989. scored.sort(reverse=True, key=lambda x: x[0])
  990. return [e for _, e in scored[:limit]]
  991. patterns = load_jsonl(f"{learnings_dir}/patterns.jsonl")
  992. mistakes = load_jsonl(f"{learnings_dir}/mistakes.jsonl")
  993. successes = load_jsonl(f"{learnings_dir}/successes.jsonl")
  994. result = {
  995. "patterns": filter_relevant(patterns, context),
  996. "mistakes": filter_relevant(mistakes, context),
  997. "successes": filter_relevant(successes, context)
  998. }
  999. with open(".loki/state/relevant-learnings.json", 'w') as f:
  1000. json.dump(result, f, indent=2)
  1001. LEARNINGS_SCRIPT
  1002. log_info "Loaded relevant learnings to: $output_file"
  1003. }
  1004. extract_learnings_from_session() {
  1005. # Extract learnings from completed session
  1006. local continuity_file=".loki/CONTINUITY.md"
  1007. if [ ! -f "$continuity_file" ]; then
  1008. return
  1009. fi
  1010. log_info "Extracting learnings from session..."
  1011. # Parse CONTINUITY.md for Mistakes & Learnings section
  1012. python3 << EXTRACT_SCRIPT
  1013. import re
  1014. import json
  1015. import os
  1016. from datetime import datetime, timezone
  1017. continuity_file = ".loki/CONTINUITY.md"
  1018. learnings_dir = os.path.expanduser("~/.loki/learnings")
  1019. if not os.path.exists(continuity_file):
  1020. exit(0)
  1021. with open(continuity_file, 'r') as f:
  1022. content = f.read()
  1023. # Find Mistakes & Learnings section
  1024. mistakes_match = re.search(r'## Mistakes & Learnings\n(.*?)(?=\n## |\Z)', content, re.DOTALL)
  1025. if mistakes_match:
  1026. mistakes_text = mistakes_match.group(1)
  1027. # Extract bullet points
  1028. bullets = re.findall(r'[-*]\s+(.+)', mistakes_text)
  1029. for bullet in bullets:
  1030. entry = {
  1031. "timestamp": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
  1032. "project": os.path.basename(os.getcwd()),
  1033. "category": "session",
  1034. "description": bullet.strip()
  1035. }
  1036. with open(f"{learnings_dir}/mistakes.jsonl", 'a') as f:
  1037. f.write(json.dumps(entry) + "\n")
  1038. print(f"Extracted: {bullet[:50]}...")
  1039. print("Learning extraction complete")
  1040. EXTRACT_SCRIPT
  1041. }
  1042. start_dashboard() {
  1043. log_header "Starting Loki Dashboard"
  1044. # Create dashboard directory
  1045. mkdir -p .loki/dashboard
  1046. # Generate HTML
  1047. generate_dashboard
  1048. # Kill any existing process on the dashboard port
  1049. if lsof -i :$DASHBOARD_PORT &>/dev/null; then
  1050. log_step "Killing existing process on port $DASHBOARD_PORT..."
  1051. lsof -ti :$DASHBOARD_PORT | xargs kill -9 2>/dev/null || true
  1052. sleep 1
  1053. fi
  1054. # Start Python HTTP server from .loki/ root so it can serve queue/ and state/
  1055. log_step "Starting dashboard server..."
  1056. (
  1057. cd .loki
  1058. python3 -m http.server $DASHBOARD_PORT --bind 127.0.0.1 2>&1 | while read line; do
  1059. echo "[dashboard] $line" >> logs/dashboard.log
  1060. done
  1061. ) &
  1062. DASHBOARD_PID=$!
  1063. sleep 1
  1064. if kill -0 $DASHBOARD_PID 2>/dev/null; then
  1065. log_info "Dashboard started (PID: $DASHBOARD_PID)"
  1066. log_info "Dashboard: ${CYAN}http://127.0.0.1:$DASHBOARD_PORT/dashboard/index.html${NC}"
  1067. # Open in browser (macOS)
  1068. if [[ "$OSTYPE" == "darwin"* ]]; then
  1069. open "http://127.0.0.1:$DASHBOARD_PORT/dashboard/index.html" 2>/dev/null || true
  1070. fi
  1071. return 0
  1072. else
  1073. log_warn "Dashboard failed to start"
  1074. DASHBOARD_PID=""
  1075. return 1
  1076. fi
  1077. }
  1078. stop_dashboard() {
  1079. if [ -n "$DASHBOARD_PID" ]; then
  1080. kill "$DASHBOARD_PID" 2>/dev/null || true
  1081. wait "$DASHBOARD_PID" 2>/dev/null || true
  1082. fi
  1083. }
  1084. #===============================================================================
  1085. # Calculate Exponential Backoff
  1086. #===============================================================================
  1087. calculate_wait() {
  1088. local retry="$1"
  1089. local wait_time=$((BASE_WAIT * (2 ** retry)))
  1090. # Add jitter (0-30 seconds)
  1091. local jitter=$((RANDOM % 30))
  1092. wait_time=$((wait_time + jitter))
  1093. # Cap at max wait
  1094. if [ $wait_time -gt $MAX_WAIT ]; then
  1095. wait_time=$MAX_WAIT
  1096. fi
  1097. echo $wait_time
  1098. }
  1099. #===============================================================================
  1100. # Rate Limit Detection
  1101. #===============================================================================
  1102. # Detect rate limit from log and calculate wait time until reset
  1103. # Returns: seconds to wait, or 0 if no rate limit detected
  1104. detect_rate_limit() {
  1105. local log_file="$1"
  1106. # Look for rate limit message like "resets 4am" or "resets 10pm"
  1107. local reset_time=$(grep -o "resets [0-9]\+[ap]m" "$log_file" 2>/dev/null | tail -1 | grep -o "[0-9]\+[ap]m")
  1108. if [ -z "$reset_time" ]; then
  1109. echo 0
  1110. return
  1111. fi
  1112. # Parse the reset time
  1113. local hour=$(echo "$reset_time" | grep -o "[0-9]\+")
  1114. local ampm=$(echo "$reset_time" | grep -o "[ap]m")
  1115. # Convert to 24-hour format
  1116. if [ "$ampm" = "pm" ] && [ "$hour" -ne 12 ]; then
  1117. hour=$((hour + 12))
  1118. elif [ "$ampm" = "am" ] && [ "$hour" -eq 12 ]; then
  1119. hour=0
  1120. fi
  1121. # Get current time
  1122. local current_hour=$(date +%H)
  1123. local current_min=$(date +%M)
  1124. local current_sec=$(date +%S)
  1125. # Calculate seconds until reset
  1126. local current_secs=$((current_hour * 3600 + current_min * 60 + current_sec))
  1127. local reset_secs=$((hour * 3600))
  1128. local wait_secs=$((reset_secs - current_secs))
  1129. # If reset time is in the past, it means tomorrow
  1130. if [ $wait_secs -le 0 ]; then
  1131. wait_secs=$((wait_secs + 86400)) # Add 24 hours
  1132. fi
  1133. # Add 2 minute buffer to ensure limit is actually reset
  1134. wait_secs=$((wait_secs + 120))
  1135. echo $wait_secs
  1136. }
  1137. # Format seconds into human-readable time
  1138. format_duration() {
  1139. local secs="$1"
  1140. local hours=$((secs / 3600))
  1141. local mins=$(((secs % 3600) / 60))
  1142. if [ $hours -gt 0 ]; then
  1143. echo "${hours}h ${mins}m"
  1144. else
  1145. echo "${mins}m"
  1146. fi
  1147. }
  1148. #===============================================================================
  1149. # Check Completion
  1150. #===============================================================================
  1151. is_completed() {
  1152. # Check orchestrator state
  1153. if [ -f ".loki/state/orchestrator.json" ]; then
  1154. if command -v python3 &> /dev/null; then
  1155. local phase=$(python3 -c "import json; print(json.load(open('.loki/state/orchestrator.json')).get('currentPhase', ''))" 2>/dev/null || echo "")
  1156. # Accept various completion states
  1157. if [ "$phase" = "COMPLETED" ] || [ "$phase" = "complete" ] || [ "$phase" = "finalized" ] || [ "$phase" = "growth-loop" ]; then
  1158. return 0
  1159. fi
  1160. fi
  1161. fi
  1162. # Check for completion marker
  1163. if [ -f ".loki/COMPLETED" ]; then
  1164. return 0
  1165. fi
  1166. return 1
  1167. }
  1168. # Check if completion promise is fulfilled in log output
  1169. check_completion_promise() {
  1170. local log_file="$1"
  1171. # Check for the completion promise phrase in recent log output
  1172. if grep -q "COMPLETION PROMISE FULFILLED" "$log_file" 2>/dev/null; then
  1173. return 0
  1174. fi
  1175. # Check for custom completion promise text
  1176. if [ -n "$COMPLETION_PROMISE" ] && grep -qF "$COMPLETION_PROMISE" "$log_file" 2>/dev/null; then
  1177. return 0
  1178. fi
  1179. return 1
  1180. }
  1181. # Check if max iterations reached
  1182. check_max_iterations() {
  1183. if [ $ITERATION_COUNT -ge $MAX_ITERATIONS ]; then
  1184. log_warn "Max iterations ($MAX_ITERATIONS) reached. Stopping."
  1185. return 0
  1186. fi
  1187. return 1
  1188. }
  1189. # Check if context clear was requested by agent
  1190. check_context_clear_signal() {
  1191. if [ -f ".loki/signals/CONTEXT_CLEAR_REQUESTED" ]; then
  1192. log_info "Context clear signal detected from agent"
  1193. rm -f ".loki/signals/CONTEXT_CLEAR_REQUESTED"
  1194. return 0
  1195. fi
  1196. return 1
  1197. }
  1198. # Load latest ledger content for context injection
  1199. load_ledger_context() {
  1200. local ledger_content=""
  1201. # Find most recent ledger
  1202. local latest_ledger=$(ls -t .loki/memory/ledgers/LEDGER-*.md 2>/dev/null | head -1)
  1203. if [ -n "$latest_ledger" ] && [ -f "$latest_ledger" ]; then
  1204. ledger_content=$(cat "$latest_ledger" | head -100)
  1205. echo "$ledger_content"
  1206. fi
  1207. }
  1208. # Load recent handoffs for context
  1209. load_handoff_context() {
  1210. local handoff_content=""
  1211. # Find most recent handoff (last 24 hours)
  1212. local recent_handoff=$(find .loki/memory/handoffs -name "*.md" -mtime -1 2>/dev/null | head -1)
  1213. if [ -n "$recent_handoff" ] && [ -f "$recent_handoff" ]; then
  1214. handoff_content=$(cat "$recent_handoff" | head -80)
  1215. echo "$handoff_content"
  1216. fi
  1217. }
  1218. # Load relevant learnings
  1219. load_learnings_context() {
  1220. local learnings=""
  1221. # Get recent learnings (last 7 days)
  1222. for learning in $(find .loki/memory/learnings -name "*.md" -mtime -7 2>/dev/null | head -5); do
  1223. learnings+="$(head -30 "$learning")\n---\n"
  1224. done
  1225. echo -e "$learnings"
  1226. }
  1227. #===============================================================================
  1228. # Save/Load Wrapper State
  1229. #===============================================================================
  1230. save_state() {
  1231. local retry_count="$1"
  1232. local status="$2"
  1233. local exit_code="$3"
  1234. cat > ".loki/autonomy-state.json" << EOF
  1235. {
  1236. "retryCount": $retry_count,
  1237. "status": "$status",
  1238. "lastExitCode": $exit_code,
  1239. "lastRun": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
  1240. "prdPath": "${PRD_PATH:-}",
  1241. "pid": $$,
  1242. "maxRetries": $MAX_RETRIES,
  1243. "baseWait": $BASE_WAIT
  1244. }
  1245. EOF
  1246. }
  1247. load_state() {
  1248. if [ -f ".loki/autonomy-state.json" ]; then
  1249. if command -v python3 &> /dev/null; then
  1250. RETRY_COUNT=$(python3 -c "import json; print(json.load(open('.loki/autonomy-state.json')).get('retryCount', 0))" 2>/dev/null || echo "0")
  1251. else
  1252. RETRY_COUNT=0
  1253. fi
  1254. else
  1255. RETRY_COUNT=0
  1256. fi
  1257. }
  1258. #===============================================================================
  1259. # Build Resume Prompt
  1260. #===============================================================================
  1261. build_prompt() {
  1262. local retry="$1"
  1263. local prd="$2"
  1264. local iteration="$3"
  1265. # Build SDLC phases configuration
  1266. local phases=""
  1267. [ "$PHASE_UNIT_TESTS" = "true" ] && phases="${phases}UNIT_TESTS,"
  1268. [ "$PHASE_API_TESTS" = "true" ] && phases="${phases}API_TESTS,"
  1269. [ "$PHASE_E2E_TESTS" = "true" ] && phases="${phases}E2E_TESTS,"
  1270. [ "$PHASE_SECURITY" = "true" ] && phases="${phases}SECURITY,"
  1271. [ "$PHASE_INTEGRATION" = "true" ] && phases="${phases}INTEGRATION,"
  1272. [ "$PHASE_CODE_REVIEW" = "true" ] && phases="${phases}CODE_REVIEW,"
  1273. [ "$PHASE_WEB_RESEARCH" = "true" ] && phases="${phases}WEB_RESEARCH,"
  1274. [ "$PHASE_PERFORMANCE" = "true" ] && phases="${phases}PERFORMANCE,"
  1275. [ "$PHASE_ACCESSIBILITY" = "true" ] && phases="${phases}ACCESSIBILITY,"
  1276. [ "$PHASE_REGRESSION" = "true" ] && phases="${phases}REGRESSION,"
  1277. [ "$PHASE_UAT" = "true" ] && phases="${phases}UAT,"
  1278. phases="${phases%,}" # Remove trailing comma
  1279. # Ralph Wiggum Mode - Reason-Act-Reflect-VERIFY cycle with self-verification loop (Boris Cherny pattern)
  1280. local rarv_instruction="RALPH WIGGUM MODE ACTIVE. Use Reason-Act-Reflect-VERIFY cycle: 1) REASON - READ .loki/CONTINUITY.md including 'Mistakes & Learnings' section to avoid past errors. CHECK .loki/state/relevant-learnings.json for cross-project learnings from previous projects (mistakes to avoid, patterns to apply). Check .loki/state/ and .loki/queue/, identify next task. CHECK .loki/state/resources.json for system resource warnings - if CPU or memory is high, reduce parallel agent spawning or pause non-critical tasks. Limit to MAX_PARALLEL_AGENTS=${MAX_PARALLEL_AGENTS}. If queue empty, find new improvements. 2) ACT - Execute task, write code, commit changes atomically (git checkpoint). 3) REFLECT - Update .loki/CONTINUITY.md with progress, update state, identify NEXT improvement. Save valuable learnings for future projects. 4) VERIFY - Run automated tests (unit, integration, E2E), check compilation/build, verify against spec. IF VERIFICATION FAILS: a) Capture error details (stack trace, logs), b) Analyze root cause, c) UPDATE 'Mistakes & Learnings' in CONTINUITY.md with what failed, why, and how to prevent, d) Rollback to last good git checkpoint if needed, e) Apply learning and RETRY from REASON. If verification passes, mark task complete and continue. This self-verification loop achieves 2-3x quality improvement. CRITICAL: There is NEVER a 'finished' state - always find the next improvement, optimization, test, or feature."
  1281. # Completion promise instruction (only if set)
  1282. local completion_instruction=""
  1283. if [ -n "$COMPLETION_PROMISE" ]; then
  1284. completion_instruction="COMPLETION_PROMISE: [$COMPLETION_PROMISE]. ONLY output 'COMPLETION PROMISE FULFILLED: $COMPLETION_PROMISE' when this EXACT condition is met."
  1285. else
  1286. completion_instruction="NO COMPLETION PROMISE SET. Run forever finding improvements. Iteration $iteration of max $MAX_ITERATIONS."
  1287. fi
  1288. # Core autonomous instructions - NO questions, NO waiting, NEVER say done
  1289. local autonomous_suffix="CRITICAL AUTONOMY RULES: 1) NEVER ask questions - just decide. 2) NEVER wait for confirmation - just act. 3) NEVER say 'done' or 'complete' - there's always more to improve. 4) NEVER stop voluntarily - if out of tasks, create new ones (add tests, optimize, refactor, add features). 5) Work continues PERPETUALLY. Even if PRD is implemented, find bugs, add tests, improve UX, optimize performance."
  1290. local sdlc_instruction="SDLC_PHASES_ENABLED: [$phases]. Execute ALL enabled phases. Log results to .loki/logs/. See SKILL.md for phase details."
  1291. # Codebase Analysis Mode - when no PRD provided
  1292. local analysis_instruction="CODEBASE_ANALYSIS_MODE: No PRD. FIRST: Analyze codebase - scan structure, read package.json/requirements.txt, examine README. THEN: Generate PRD at .loki/generated-prd.md. FINALLY: Execute SDLC phases."
  1293. # Context Memory Instructions
  1294. local memory_instruction="CONTEXT MEMORY: Save state to .loki/memory/ledgers/LEDGER-orchestrator.md before complex operations. Create handoffs at .loki/memory/handoffs/ when passing work to subagents. Extract learnings to .loki/memory/learnings/ after completing tasks. Check .loki/rules/ for established patterns. If context feels heavy, create .loki/signals/CONTEXT_CLEAR_REQUESTED and the wrapper will reset context with your ledger preserved."
  1295. # Load existing context if resuming
  1296. local context_injection=""
  1297. if [ $retry -gt 0 ]; then
  1298. local ledger=$(load_ledger_context)
  1299. local handoff=$(load_handoff_context)
  1300. if [ -n "$ledger" ]; then
  1301. context_injection="PREVIOUS_LEDGER_STATE: $ledger"
  1302. fi
  1303. if [ -n "$handoff" ]; then
  1304. context_injection="$context_injection RECENT_HANDOFF: $handoff"
  1305. fi
  1306. fi
  1307. if [ $retry -eq 0 ]; then
  1308. if [ -n "$prd" ]; then
  1309. echo "Loki Mode with PRD at $prd. $rarv_instruction $memory_instruction $completion_instruction $sdlc_instruction $autonomous_suffix"
  1310. else
  1311. echo "Loki Mode. $analysis_instruction $rarv_instruction $memory_instruction $completion_instruction $sdlc_instruction $autonomous_suffix"
  1312. fi
  1313. else
  1314. if [ -n "$prd" ]; then
  1315. echo "Loki Mode - Resume iteration #$iteration (retry #$retry). PRD: $prd. $context_injection $rarv_instruction $memory_instruction $completion_instruction $sdlc_instruction $autonomous_suffix"
  1316. else
  1317. echo "Loki Mode - Resume iteration #$iteration (retry #$retry). $context_injection Use .loki/generated-prd.md if exists. $rarv_instruction $memory_instruction $completion_instruction $sdlc_instruction $autonomous_suffix"
  1318. fi
  1319. fi
  1320. }
  1321. #===============================================================================
  1322. # Main Autonomous Loop
  1323. #===============================================================================
  1324. run_autonomous() {
  1325. local prd_path="$1"
  1326. log_header "Starting Autonomous Execution"
  1327. # Auto-detect PRD if not provided
  1328. if [ -z "$prd_path" ]; then
  1329. log_step "No PRD provided, searching for existing PRD files..."
  1330. local found_prd=""
  1331. # Search common PRD file patterns
  1332. for pattern in "PRD.md" "prd.md" "REQUIREMENTS.md" "requirements.md" "SPEC.md" "spec.md" \
  1333. "docs/PRD.md" "docs/prd.md" "docs/REQUIREMENTS.md" "docs/requirements.md" \
  1334. "docs/SPEC.md" "docs/spec.md" ".github/PRD.md" "PROJECT.md" "project.md"; do
  1335. if [ -f "$pattern" ]; then
  1336. found_prd="$pattern"
  1337. break
  1338. fi
  1339. done
  1340. if [ -n "$found_prd" ]; then
  1341. log_info "Found existing PRD: $found_prd"
  1342. prd_path="$found_prd"
  1343. elif [ -f ".loki/generated-prd.md" ]; then
  1344. log_info "Using previously generated PRD: .loki/generated-prd.md"
  1345. prd_path=".loki/generated-prd.md"
  1346. else
  1347. log_info "No PRD found - will analyze codebase and generate one"
  1348. fi
  1349. fi
  1350. log_info "PRD: ${prd_path:-Codebase Analysis Mode}"
  1351. log_info "Max retries: $MAX_RETRIES"
  1352. log_info "Max iterations: $MAX_ITERATIONS"
  1353. log_info "Completion promise: $COMPLETION_PROMISE"
  1354. log_info "Base wait: ${BASE_WAIT}s"
  1355. log_info "Max wait: ${MAX_WAIT}s"
  1356. echo ""
  1357. load_state
  1358. local retry=$RETRY_COUNT
  1359. # Check max iterations before starting
  1360. if check_max_iterations; then
  1361. log_error "Max iterations already reached. Reset with: rm .loki/autonomy-state.json"
  1362. return 1
  1363. fi
  1364. while [ $retry -lt $MAX_RETRIES ]; do
  1365. # Increment iteration count
  1366. ((ITERATION_COUNT++))
  1367. # Check max iterations
  1368. if check_max_iterations; then
  1369. save_state $retry "max_iterations_reached" 0
  1370. return 0
  1371. fi
  1372. local prompt=$(build_prompt $retry "$prd_path" $ITERATION_COUNT)
  1373. echo ""
  1374. log_header "Attempt $((retry + 1)) of $MAX_RETRIES"
  1375. log_info "Prompt: $prompt"
  1376. echo ""
  1377. save_state $retry "running" 0
  1378. # Run Claude Code with live output
  1379. local start_time=$(date +%s)
  1380. local log_file=".loki/logs/autonomy-$(date +%Y%m%d).log"
  1381. echo ""
  1382. echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  1383. echo -e "${CYAN} CLAUDE CODE OUTPUT (live)${NC}"
  1384. echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  1385. echo ""
  1386. # Log start time
  1387. echo "=== Session started at $(date) ===" >> "$log_file"
  1388. echo "=== Prompt: $prompt ===" >> "$log_file"
  1389. set +e
  1390. # Run Claude with stream-json for real-time output
  1391. # Parse JSON stream, display formatted output, and track agents
  1392. claude --dangerously-skip-permissions -p "$prompt" \
  1393. --output-format stream-json --verbose 2>&1 | \
  1394. tee -a "$log_file" | \
  1395. python3 -u -c '
  1396. import sys
  1397. import json
  1398. import os
  1399. from datetime import datetime, timezone
  1400. # ANSI colors
  1401. CYAN = "\033[0;36m"
  1402. GREEN = "\033[0;32m"
  1403. YELLOW = "\033[1;33m"
  1404. MAGENTA = "\033[0;35m"
  1405. DIM = "\033[2m"
  1406. NC = "\033[0m"
  1407. # Agent tracking
  1408. AGENTS_FILE = ".loki/state/agents.json"
  1409. QUEUE_IN_PROGRESS = ".loki/queue/in-progress.json"
  1410. active_agents = {} # tool_id -> agent_info
  1411. orchestrator_id = "orchestrator-main"
  1412. session_start = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
  1413. def init_orchestrator():
  1414. """Initialize the main orchestrator agent (always visible)."""
  1415. active_agents[orchestrator_id] = {
  1416. "agent_id": orchestrator_id,
  1417. "tool_id": orchestrator_id,
  1418. "agent_type": "orchestrator",
  1419. "model": "sonnet",
  1420. "current_task": "Initializing...",
  1421. "status": "active",
  1422. "spawned_at": session_start,
  1423. "tasks_completed": [],
  1424. "tool_count": 0
  1425. }
  1426. save_agents()
  1427. def update_orchestrator_task(tool_name, description=""):
  1428. """Update orchestrator current task based on tool usage."""
  1429. if orchestrator_id in active_agents:
  1430. active_agents[orchestrator_id]["tool_count"] = active_agents[orchestrator_id].get("tool_count", 0) + 1
  1431. if description:
  1432. active_agents[orchestrator_id]["current_task"] = f"{tool_name}: {description[:80]}"
  1433. else:
  1434. active_agents[orchestrator_id]["current_task"] = f"Using {tool_name}..."
  1435. save_agents()
  1436. def load_agents():
  1437. """Load existing agents from file."""
  1438. try:
  1439. if os.path.exists(AGENTS_FILE):
  1440. with open(AGENTS_FILE, "r") as f:
  1441. data = json.load(f)
  1442. return {a.get("tool_id", a.get("agent_id")): a for a in data if isinstance(a, dict)}
  1443. except:
  1444. pass
  1445. return {}
  1446. def save_agents():
  1447. """Save agents to file for dashboard."""
  1448. try:
  1449. os.makedirs(os.path.dirname(AGENTS_FILE), exist_ok=True)
  1450. agents_list = list(active_agents.values())
  1451. with open(AGENTS_FILE, "w") as f:
  1452. json.dump(agents_list, f, indent=2)
  1453. except Exception as e:
  1454. print(f"{YELLOW}[Agent save error: {e}]{NC}", file=sys.stderr)
  1455. def save_in_progress(tasks):
  1456. """Save in-progress tasks to queue file."""
  1457. try:
  1458. os.makedirs(os.path.dirname(QUEUE_IN_PROGRESS), exist_ok=True)
  1459. with open(QUEUE_IN_PROGRESS, "w") as f:
  1460. json.dump(tasks, f, indent=2)
  1461. except:
  1462. pass
  1463. def process_stream():
  1464. global active_agents
  1465. active_agents = load_agents()
  1466. # Always show the main orchestrator
  1467. init_orchestrator()
  1468. print(f"{MAGENTA}[Orchestrator Active]{NC} Main agent started", flush=True)
  1469. for line in sys.stdin:
  1470. line = line.strip()
  1471. if not line:
  1472. continue
  1473. try:
  1474. data = json.loads(line)
  1475. msg_type = data.get("type", "")
  1476. if msg_type == "assistant":
  1477. # Extract and print assistant text
  1478. message = data.get("message", {})
  1479. content = message.get("content", [])
  1480. for item in content:
  1481. if item.get("type") == "text":
  1482. text = item.get("text", "")
  1483. if text:
  1484. print(text, end="", flush=True)
  1485. elif item.get("type") == "tool_use":
  1486. tool = item.get("name", "unknown")
  1487. tool_id = item.get("id", "")
  1488. tool_input = item.get("input", {})
  1489. # Extract description based on tool type
  1490. tool_desc = ""
  1491. if tool == "Read":
  1492. tool_desc = tool_input.get("file_path", "")
  1493. elif tool == "Edit" or tool == "Write":
  1494. tool_desc = tool_input.get("file_path", "")
  1495. elif tool == "Bash":
  1496. tool_desc = tool_input.get("description", tool_input.get("command", "")[:60])
  1497. elif tool == "Grep":
  1498. tool_desc = f"pattern: {tool_input.get('pattern', '')}"
  1499. elif tool == "Glob":
  1500. tool_desc = tool_input.get("pattern", "")
  1501. # Update orchestrator with current tool activity
  1502. update_orchestrator_task(tool, tool_desc)
  1503. # Track Task tool calls (agent spawning)
  1504. if tool == "Task":
  1505. agent_type = tool_input.get("subagent_type", "general-purpose")
  1506. description = tool_input.get("description", "")
  1507. model = tool_input.get("model", "sonnet")
  1508. agent_info = {
  1509. "agent_id": f"agent-{tool_id[:8]}",
  1510. "tool_id": tool_id,
  1511. "agent_type": agent_type,
  1512. "model": model,
  1513. "current_task": description,
  1514. "status": "active",
  1515. "spawned_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
  1516. "tasks_completed": []
  1517. }
  1518. active_agents[tool_id] = agent_info
  1519. save_agents()
  1520. print(f"\n{MAGENTA}[Agent Spawned: {agent_type}]{NC} {description}", flush=True)
  1521. # Track TodoWrite for task updates
  1522. elif tool == "TodoWrite":
  1523. todos = tool_input.get("todos", [])
  1524. in_progress = [t for t in todos if t.get("status") == "in_progress"]
  1525. save_in_progress([{"id": f"todo-{i}", "type": "todo", "payload": {"action": t.get("content", "")}} for i, t in enumerate(in_progress)])
  1526. print(f"\n{CYAN}[Tool: {tool}]{NC} {len(todos)} items", flush=True)
  1527. else:
  1528. print(f"\n{CYAN}[Tool: {tool}]{NC}", flush=True)
  1529. elif msg_type == "user":
  1530. # Tool results - check for agent completion
  1531. content = data.get("message", {}).get("content", [])
  1532. for item in content:
  1533. if item.get("type") == "tool_result":
  1534. tool_id = item.get("tool_use_id", "")
  1535. # Mark agent as completed if it was a Task
  1536. if tool_id in active_agents:
  1537. active_agents[tool_id]["status"] = "completed"
  1538. active_agents[tool_id]["completed_at"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
  1539. save_agents()
  1540. print(f"{DIM}[Agent Complete]{NC} ", end="", flush=True)
  1541. else:
  1542. print(f"{DIM}[Result]{NC} ", end="", flush=True)
  1543. elif msg_type == "result":
  1544. # Session complete - mark all agents as completed
  1545. completed_at = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
  1546. for agent_id in active_agents:
  1547. if active_agents[agent_id].get("status") == "active":
  1548. active_agents[agent_id]["status"] = "completed"
  1549. active_agents[agent_id]["completed_at"] = completed_at
  1550. active_agents[agent_id]["current_task"] = "Session complete"
  1551. # Add session stats to orchestrator
  1552. if orchestrator_id in active_agents:
  1553. tool_count = active_agents[orchestrator_id].get("tool_count", 0)
  1554. active_agents[orchestrator_id]["tasks_completed"].append(f"{tool_count} tools used")
  1555. save_agents()
  1556. print(f"\n{GREEN}[Session complete]{NC}", flush=True)
  1557. is_error = data.get("is_error", False)
  1558. sys.exit(1 if is_error else 0)
  1559. except json.JSONDecodeError:
  1560. # Not JSON, print as-is
  1561. print(line, flush=True)
  1562. except Exception as e:
  1563. print(f"{YELLOW}[Parse error: {e}]{NC}", file=sys.stderr)
  1564. if __name__ == "__main__":
  1565. try:
  1566. process_stream()
  1567. except KeyboardInterrupt:
  1568. sys.exit(130)
  1569. except BrokenPipeError:
  1570. sys.exit(0)
  1571. '
  1572. local exit_code=${PIPESTATUS[0]}
  1573. set -e
  1574. echo ""
  1575. echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  1576. echo ""
  1577. # Log end time
  1578. echo "=== Session ended at $(date) with exit code $exit_code ===" >> "$log_file"
  1579. local end_time=$(date +%s)
  1580. local duration=$((end_time - start_time))
  1581. log_info "Claude exited with code $exit_code after ${duration}s"
  1582. save_state $retry "exited" $exit_code
  1583. # Check for success - ONLY stop on explicit completion promise
  1584. # There's never a "complete" product - always improvements, bugs, features
  1585. if [ $exit_code -eq 0 ]; then
  1586. # Perpetual mode: NEVER stop, always continue
  1587. if [ "$PERPETUAL_MODE" = "true" ]; then
  1588. log_info "Perpetual mode: Ignoring exit, continuing immediately..."
  1589. ((retry++))
  1590. continue # Immediately start next iteration, no wait
  1591. fi
  1592. # Only stop if EXPLICIT completion promise text was output
  1593. if [ -n "$COMPLETION_PROMISE" ] && check_completion_promise "$log_file"; then
  1594. echo ""
  1595. log_header "COMPLETION PROMISE FULFILLED: $COMPLETION_PROMISE"
  1596. log_info "Explicit completion promise detected in output."
  1597. save_state $retry "completion_promise_fulfilled" 0
  1598. return 0
  1599. fi
  1600. # Warn if Claude says it's "done" but no explicit promise
  1601. if is_completed; then
  1602. log_warn "Claude claims completion, but no explicit promise fulfilled."
  1603. log_warn "Projects are never truly complete - there are always improvements!"
  1604. fi
  1605. # SUCCESS exit - continue IMMEDIATELY to next iteration (no wait!)
  1606. log_info "Iteration complete. Continuing to next iteration..."
  1607. ((retry++))
  1608. continue # Immediately start next iteration, no exponential backoff
  1609. fi
  1610. # Only apply retry logic for ERRORS (non-zero exit code)
  1611. # Handle retry - check for rate limit first
  1612. local rate_limit_wait=$(detect_rate_limit "$log_file")
  1613. local wait_time
  1614. if [ $rate_limit_wait -gt 0 ]; then
  1615. wait_time=$rate_limit_wait
  1616. local human_time=$(format_duration $wait_time)
  1617. log_warn "Rate limit detected! Waiting until reset (~$human_time)..."
  1618. log_info "Rate limit resets at approximately $(date -v+${wait_time}S '+%I:%M %p' 2>/dev/null || date -d "+${wait_time} seconds" '+%I:%M %p' 2>/dev/null || echo 'soon')"
  1619. else
  1620. wait_time=$(calculate_wait $retry)
  1621. log_warn "Will retry in ${wait_time}s..."
  1622. fi
  1623. log_info "Press Ctrl+C to cancel"
  1624. # Countdown with progress
  1625. local remaining=$wait_time
  1626. local interval=10
  1627. # Use longer interval for long waits
  1628. if [ $wait_time -gt 1800 ]; then
  1629. interval=60
  1630. fi
  1631. while [ $remaining -gt 0 ]; do
  1632. local human_remaining=$(format_duration $remaining)
  1633. printf "\r${YELLOW}Resuming in ${human_remaining}...${NC} "
  1634. sleep $interval
  1635. remaining=$((remaining - interval))
  1636. done
  1637. echo ""
  1638. ((retry++))
  1639. done
  1640. log_error "Max retries ($MAX_RETRIES) exceeded"
  1641. save_state $retry "failed" 1
  1642. return 1
  1643. }
  1644. #===============================================================================
  1645. # Cleanup Handler
  1646. #===============================================================================
  1647. cleanup() {
  1648. echo ""
  1649. log_warn "Received interrupt signal"
  1650. stop_dashboard
  1651. stop_status_monitor
  1652. save_state ${RETRY_COUNT:-0} "interrupted" 130
  1653. log_info "State saved. Run again to resume."
  1654. exit 130
  1655. }
  1656. #===============================================================================
  1657. # Main Entry Point
  1658. #===============================================================================
  1659. main() {
  1660. trap cleanup INT TERM
  1661. echo ""
  1662. echo -e "${BOLD}${BLUE}"
  1663. echo " β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—"
  1664. echo " β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β–ˆβ–ˆβ•—β–ˆβ–ˆβ•”β•β•β•β•β•"
  1665. echo " β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β–ˆβ–ˆβ–ˆβ–ˆβ•”β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— "
  1666. echo " β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•— β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘β–ˆβ–ˆβ•”β•β•β• "
  1667. echo " β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•—β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β•šβ•β• β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—"
  1668. echo " β•šβ•β•β•β•β•β•β• β•šβ•β•β•β•β•β• β•šβ•β• β•šβ•β•β•šβ•β• β•šβ•β• β•šβ•β• β•šβ•β•β•β•β•β• β•šβ•β•β•β•β•β• β•šβ•β•β•β•β•β•β•"
  1669. echo -e "${NC}"
  1670. echo -e " ${CYAN}Autonomous Multi-Agent Startup System${NC}"
  1671. echo -e " ${CYAN}Version: $(cat "$PROJECT_DIR/VERSION" 2>/dev/null || echo "2.x.x")${NC}"
  1672. echo ""
  1673. # Parse arguments
  1674. PRD_PATH="${1:-}"
  1675. # Validate PRD if provided
  1676. if [ -n "$PRD_PATH" ] && [ ! -f "$PRD_PATH" ]; then
  1677. log_error "PRD file not found: $PRD_PATH"
  1678. exit 1
  1679. fi
  1680. # Check prerequisites (unless skipped)
  1681. if [ "$SKIP_PREREQS" != "true" ]; then
  1682. if ! check_prerequisites; then
  1683. exit 1
  1684. fi
  1685. else
  1686. log_warn "Skipping prerequisite checks (LOKI_SKIP_PREREQS=true)"
  1687. fi
  1688. # Check skill installation
  1689. if ! check_skill_installed; then
  1690. exit 1
  1691. fi
  1692. # Initialize .loki directory
  1693. init_loki_dir
  1694. # Start web dashboard (if enabled)
  1695. if [ "$ENABLE_DASHBOARD" = "true" ]; then
  1696. start_dashboard
  1697. else
  1698. log_info "Dashboard disabled (LOKI_DASHBOARD=false)"
  1699. fi
  1700. # Start status monitor (background updates to .loki/STATUS.txt)
  1701. start_status_monitor
  1702. # Start resource monitor (background CPU/memory checks)
  1703. start_resource_monitor
  1704. # Initialize cross-project learnings database
  1705. init_learnings_db
  1706. # Load relevant learnings for this project context
  1707. if [ -n "$PRD_PATH" ] && [ -f "$PRD_PATH" ]; then
  1708. get_relevant_learnings "$(cat "$PRD_PATH" | head -100)"
  1709. else
  1710. get_relevant_learnings "general development"
  1711. fi
  1712. # Log session start for audit
  1713. audit_log "SESSION_START" "prd=$PRD_PATH,dashboard=$ENABLE_DASHBOARD,staged_autonomy=$STAGED_AUTONOMY"
  1714. # Run autonomous loop
  1715. local result=0
  1716. run_autonomous "$PRD_PATH" || result=$?
  1717. # Extract and save learnings from this session
  1718. extract_learnings_from_session
  1719. # Log session end for audit
  1720. audit_log "SESSION_END" "result=$result,prd=$PRD_PATH"
  1721. # Cleanup
  1722. stop_dashboard
  1723. stop_status_monitor
  1724. exit $result
  1725. }
  1726. # Run main
  1727. main "$@"

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.