Skip to content
Back to search

agent-skills-hub

Agent Skills Hub is a global library of AI agent skills that work across OpenClaw, Claude Code, Gemini, Cursor, Antigravity, and more.

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/agent-skills-hub/agent-skills-hub 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/agent-skills-hub/agent-skills-hub'

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/agent-skills-hub--agent-skills-hub/badge.svg)](/listings/agent-skills-hub--agent-skills-hub)

HTML

<a href="/listings/agent-skills-hub--agent-skills-hub"><img src="/api/listings/agent-skills-hub--agent-skills-hub/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.

Prerequisites

- Node.js - npm / npx - Any supported agent framework (optional)

Installation

The fastest way to get started is via **NPX**.

# Install skills globally (default: ~/.agent/skills)
npx agent-skills-hub

This installs the full skill registry in a global location that most agents can read from.

Project-Local Skills (Recommended)

For repo-aware agents, you can keep skills **inside your project**.

Create a `skills/` directory at your project root:

git clone https://github.com/legendaryabhi/agent-skills-hub.git ./skills

Each skill folder must contain a **`SKILL.md`** file.

Supported agents will **automatically detect and load local skills at runtime**, giving your agent full project context without any extra configuration.

> **Priority rule:** > Project-local skills override global skills when both exist.

Targeted Installs

Install skills directly into agent-specific locations:

# Claude Code
npx agent-skills-hub --claude

# Gemini CLI
npx agent-skills-hub --gemini

# Cursor IDE
npx agent-skills-hub --cursor

# Kiro CLI/IDE
npx agent-skills-hub --kiro

# Codex CLI
npx agent-skills-hub --codex

# Antigravity IDE
npx agent-skills-hub --antigravity

# OpenCode CLI
npx agent-skills-hub --opencode

# AdaL CLI
npx agent-skills-hub --adal

# OpenClaw
npx agent-skills-hub --openclaw

| Tool | Flag | Install Path | | ------------ | --------------- | ------------------------------- | | Claude Code | `--claude` | `~/.claude/skills/` | | Gemini CLI | `--gemini` | `~/.gemini/skills/` | | Cursor IDE | `--cursor` | `~/.cursor/skills/` | | Kiro CLI/IDE | `--kiro` | `~/.kiro/skills/` | | Codex CLI | `--codex` | `~/.codex/skills/` | | Antigravity | `--antigravity` | `~/.gemini/antigravity/skills/` | | OpenCode | `--opencode` | `~/.agents/skills/` | | AdaL CLI | `--adal` | `~/.adal/skills/` | | OpenClaw | `--openclaw` | `~/.openclaw/skills/` | | Custom | `--path <dir>` | `<dir>` |

Install a Specific Skill

npx agent-skills-hub install react-patterns
npx agent-skills-hub install react-patterns --cursor

This installs only the requested skill instead of the full registry.

Manual Clone (Advanced)

If you prefer full control:

git clone https://github.com/legendaryabhi/agent-skills-hub.git ~/skills

You can then:

- Symlink skills into agent directories - Copy skills into your project’s `skills/` folder - Customize skills directly

<p align="right">(<a href="#readme-top">back to top</a>)</p>

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 · 371 lines

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

  1. <a id="readme-top"></a>
  2. [![Contributors][contributors-shield]][contributors-url]
  3. [![Forks][forks-shield]][forks-url]
  4. [![Stargazers][stars-shield]][stars-url]
  5. [![Issues][issues-shield]][issues-url]
  6. [![MIT License][license-shield]][license-url]
  7. [![npm version][npm-shield]][npm-url]
  8. <br />
  9. <div align="center">
  10. ![banner](./assets/banner.png)
  11. <h3 align="center">Agent Skills Hub</h3>
  12. <p align="center">
  13. The universal registry of agentic skills for AI coding agents.
  14. <br />
  15. <strong>790+ skills</strong> for Claude Code, Gemini, Cursor, Kiro, Codex, Antigravity, OpenCode, and other agent frameworks.
  16. <br />
  17. <br />
  18. <a href="#getting-started"><strong>Install Now »</strong></a>
  19. <br />
  20. <br />
  21. <a href="https://agent-skills-hub.github.io">Search Skills</a>
  22. &middot;
  23. <a href="#usage">View Demos</a>
  24. &middot;
  25. <a href="https://github.com/legendaryabhi/agent-skills-hub/issues">Report Bug</a>
  26. &middot;
  27. <a href="https://github.com/legendaryabhi/agent-skills-hub/issues">Request Feature</a>
  28. </p>
  29. </div>
  30. <!-- TABLE OF CONTENTS -->
  31. <details>
  32. <summary>Table of Contents</summary>
  33. <ol>
  34. <li>
  35. <a href="#about-the-project">About The Project</a>
  36. <ul>
  37. <li><a href="#why-agent-skills">Why Agent Skills?</a></li>
  38. <li><a href="#built-with">Built With</a></li>
  39. </ul>
  40. </li>
  41. <li>
  42. <a href="#getting-started">Getting Started</a>
  43. <ul>
  44. <li><a href="#prerequisites">Prerequisites</a></li>
  45. <li><a href="#installation">Installation (NPX)</a></li>
  46. </ul>
  47. </li>
  48. <li><a href="#usage">Usage</a></li>
  49. <li><a href="#skill-catalog">Skill Catalog</a></li>
  50. <li><a href="#roadmap">Roadmap</a></li>
  51. <li><a href="#contributing">Contributing</a></li>
  52. <li><a href="#license">License</a></li>
  53. </ol>
  54. </details>
  55. ## About The Project
  56. **Agent Skills Hub** is a centralized, open-source registry of **agentic skills** — reusable, structured instructions that teach AI agents _how to actually do things correctly_.
  57. Think of skills as **plugins for reasoning**:
  58. - They encode **best practices**
  59. - They define **tool usage**
  60. - They enforce **project-specific workflows**
  61. This repository is shipped as an **NPX-first CLI**, making skills instantly installable into popular agent environments.
  62. > If prompts are _what_ to do,
  63. > **skills are _how_ to do it right.**
  64. <p align="right">(<a href="#readme-top">back to top</a>)</p>
  65. ### Why Agent Skills?
  66. Modern AI agents are powerful generalists, but they lack:
  67. - Repo-specific context
  68. - Tooling conventions
  69. - Deployment workflows
  70. - Organizational standards
  71. **Agent Skills solve this gap.**
  72. Each skill is a Markdown-based definition that can teach an agent:
  73. - How to write production-ready code
  74. - How to use a specific CLI or API
  75. - How to follow your internal processes
  76. - How to reason consistently across tasks
  77. Skills work across **Claude Code, Gemini CLI, Cursor, Kiro, Codex, Antigravity, OpenCode, AdaL**, and more.
  78. <p align="right">(<a href="#readme-top">back to top</a>)</p>
  79. ### Built With
  80. - [![JavaScript][javascript-shield]][javascript-url]
  81. - [![Node.js][nodejs-shield]][nodejs-url]
  82. - [![Python][python-shield]][python-url]
  83. - [![Shell][shell-shield]][shell-url]
  84. - [![Markdown][markdown-shield]][markdown-url]
  85. <p align="right">(<a href="#readme-top">back to top</a>)</p>
  86. ## Getting Started
  87. ### Prerequisites
  88. - Node.js
  89. - npm / npx
  90. - Any supported agent framework (optional)
  91. ### Installation
  92. The fastest way to get started is via **NPX**.
  93. ```bash
  94. # Install skills globally (default: ~/.agent/skills)
  95. npx agent-skills-hub
  96. ```
  97. This installs the full skill registry in a global location that most agents can read from.
  98. ### Project-Local Skills (Recommended)
  99. For repo-aware agents, you can keep skills **inside your project**.
  100. Create a `skills/` directory at your project root:
  101. ```bash
  102. git clone https://github.com/legendaryabhi/agent-skills-hub.git ./skills
  103. ```
  104. Each skill folder must contain a **`SKILL.md`** file.
  105. Supported agents will **automatically detect and load local skills at runtime**, giving your agent full project context without any extra configuration.
  106. > **Priority rule:**
  107. > Project-local skills override global skills when both exist.
  108. ### Targeted Installs
  109. Install skills directly into agent-specific locations:
  110. ```bash
  111. # Claude Code
  112. npx agent-skills-hub --claude
  113. # Gemini CLI
  114. npx agent-skills-hub --gemini
  115. # Cursor IDE
  116. npx agent-skills-hub --cursor
  117. # Kiro CLI/IDE
  118. npx agent-skills-hub --kiro
  119. # Codex CLI
  120. npx agent-skills-hub --codex
  121. # Antigravity IDE
  122. npx agent-skills-hub --antigravity
  123. # OpenCode CLI
  124. npx agent-skills-hub --opencode
  125. # AdaL CLI
  126. npx agent-skills-hub --adal
  127. # OpenClaw
  128. npx agent-skills-hub --openclaw
  129. ```
  130. | Tool | Flag | Install Path |
  131. | ------------ | --------------- | ------------------------------- |
  132. | Claude Code | `--claude` | `~/.claude/skills/` |
  133. | Gemini CLI | `--gemini` | `~/.gemini/skills/` |
  134. | Cursor IDE | `--cursor` | `~/.cursor/skills/` |
  135. | Kiro CLI/IDE | `--kiro` | `~/.kiro/skills/` |
  136. | Codex CLI | `--codex` | `~/.codex/skills/` |
  137. | Antigravity | `--antigravity` | `~/.gemini/antigravity/skills/` |
  138. | OpenCode | `--opencode` | `~/.agents/skills/` |
  139. | AdaL CLI | `--adal` | `~/.adal/skills/` |
  140. | OpenClaw | `--openclaw` | `~/.openclaw/skills/` |
  141. | Custom | `--path <dir>` | `<dir>` |
  142. ### Install a Specific Skill
  143. ```bash
  144. npx agent-skills-hub install react-patterns
  145. npx agent-skills-hub install react-patterns --cursor
  146. ```
  147. This installs only the requested skill instead of the full registry.
  148. ### Manual Clone (Advanced)
  149. If you prefer full control:
  150. ```bash
  151. git clone https://github.com/legendaryabhi/agent-skills-hub.git ~/skills
  152. ```
  153. You can then:
  154. - Symlink skills into agent directories
  155. - Copy skills into your project’s `skills/` folder
  156. - Customize skills directly
  157. <p align="right">(<a href="#readme-top">back to top</a>)</p>
  158. ## Usage
  159. Usage depends on your agent framework.
  160. ### OpenClaw
  161. OpenClaw automatically loads skills from:
  162. ```bash
  163. ~/.openclaw/skills
  164. ```
  165. Once installed, skills are injected at runtime.
  166. ### Claude Code
  167. Claude Code reads skills from:
  168. ```bash
  169. ~/.claude/skills
  170. ```
  171. Example:
  172. ```text
  173. /load @react-best-practices
  174. Help me refactor this component using the loaded patterns.
  175. ```
  176. ### Cursor / VS Code
  177. 1. Install skills to:
  178. ```bash
  179. ~/.cursor/skills
  180. ```
  181. 2. Reference them in chat:
  182. ```text
  183. @react-best-practices How should I structure this useEffect?
  184. ```
  185. ### Demos
  186. Gemini CLI using `react-patterns` skill from Agent Skills Hub
  187. ```bash
  188. npx agent-skills-hub install react-patterns --gemini
  189. ```
  190. https://github.com/user-attachments/assets/f01c532e-7f21-4543-8bed-ab8a4ecfe288
  191. > PRs with demos are highly welcome.
  192. <p align="right">(<a href="#readme-top">back to top</a>)</p>
  193. ## Skill Catalog
  194. We currently maintain **790+ skills** across multiple domains.
  195. **Browse the full catalog:**
  196. [CATALOG.md](CATALOG.md)
  197. ### Category Highlights
  198. - **Architecture**: `system-design`, `c4-model`, `microservices`
  199. - **Development**: `react-patterns`, `typescript-expert`, `python-optimization`
  200. - **Security**: `owasp-top-10`, `pentest-checklist`
  201. - **Ops & Cloud**: `docker-mastery`, `kubernetes-debug`
  202. - **Business**: `seo-audit`, `startup-analysis`
  203. <p align="right">(<a href="#readme-top">back to top</a>)</p>
  204. ## Roadmap
  205. - [x] NPX-based installer
  206. - [x] Multi-agent support
  207. - [x] 790+ curated skills
  208. - [ ] Skill versioning
  209. - [ ] Skill dependency graph
  210. - [ ] Web catalog explorer
  211. - [ ] Agent marketplace integrations
  212. See the [open issues](https://github.com/legendaryabhi/agent-skills-hub/issues).
  213. <p align="right">(<a href="#readme-top">back to top</a>)</p>
  214. ## Contributing
  215. We’re building the **open standard for agent skills**.
  216. 1. Fork the repo
  217. 2. Create a `SKILL.md`:
  218. 3. Submit a PR
  219. See [CONTRIBUTING.md](CONTRIBUTING.md) for full guidelines.
  220. <p align="right">(<a href="#readme-top">back to top</a>)</p>
  221. ## License
  222. Distributed under the **MIT License**.
  223. See `LICENSE` for details.
  224. <p align="right">(<a href="#readme-top">back to top</a>)</p>
  225. ## Acknowledgement
  226. This project is built on top of
  227. [antigravity-awesome-skills](https://github.com/sickn33/antigravity-awesome-skills) [MIT license](https://github.com/sickn33/antigravity-awesome-skills?tab=MIT-1-ov-file#readme).
  228. On top of the original work, I have added:
  229. - Support for multiple AI agent workflows (Kiro, Antigravity, OpenCode, AdaL, and more)
  230. - 120+ scientific skills from [K-Dense-AI/claude-scientific-skills](https://github.com/K-Dense-AI/claude-scientific-skills)
  231. - Marketing skills from [coreyhaines31/marketingskills](https://github.com/coreyhaines31/marketingskills)
  232. - A single-file skill download workflow
  233. - NPX-based installation and agent-specific integrations
  234. - More coming soon...
  235. See [ATTRIBUTION.md](ATTRIBUTION.md) for full credits.
  236. Thanks to the original authors for laying the foundation.
  237. <!-- MARKDOWN LINKS -->
  238. [npm-shield]: https://img.shields.io/npm/v/agent-skills-hub.svg?style=for-the-badge
  239. [npm-url]: https://www.npmjs.com/package/agent-skills-hub
  240. [contributors-shield]: https://img.shields.io/github/contributors/legendaryabhi/agent-skills-hub.svg?style=for-the-badge
  241. [contributors-url]: https://github.com/legendaryabhi/agent-skills-hub/graphs/contributors
  242. [forks-shield]: https://img.shields.io/github/forks/legendaryabhi/agent-skills-hub.svg?style=for-the-badge
  243. [forks-url]: https://github.com/legendaryabhi/agent-skills-hub/network/members
  244. [stars-shield]: https://img.shields.io/github/stars/legendaryabhi/agent-skills-hub.svg?style=for-the-badge
  245. [stars-url]: https://github.com/legendaryabhi/agent-skills-hub/stargazers
  246. [issues-shield]: https://img.shields.io/github/issues/legendaryabhi/agent-skills-hub.svg?style=for-the-badge
  247. [issues-url]: https://github.com/legendaryabhi/agent-skills-hub/issues
  248. [license-shield]: https://img.shields.io/github/license/legendaryabhi/agent-skills-hub.svg?style=for-the-badge
  249. [license-url]: https://github.com/legendaryabhi/agent-skills-hub/blob/main/LICENSE
  250. <!-- Built With Badges -->
  251. [javascript-shield]: https://img.shields.io/badge/JavaScript-F7DF1E?style=for-the-badge&logo=javascript&logoColor=000
  252. [javascript-url]: https://developer.mozilla.org/en-US/docs/Web/JavaScript
  253. [nodejs-shield]: https://img.shields.io/badge/Node.js-339933?style=for-the-badge&logo=nodedotjs&logoColor=white
  254. [nodejs-url]: https://nodejs.org/
  255. [python-shield]: https://img.shields.io/badge/Python-3776AB?style=for-the-badge&logo=python&logoColor=white
  256. [python-url]: https://www.python.org/
  257. [shell-shield]: https://img.shields.io/badge/Shell-4EAA25?style=for-the-badge&logo=gnu-bash&logoColor=white
  258. [shell-url]: https://www.gnu.org/software/bash/
  259. [markdown-shield]: https://img.shields.io/badge/Markdown-000000?style=for-the-badge&logo=markdown&logoColor=white
  260. [markdown-url]: https://www.markdownguide.org/
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.