Skip to content
Back to search

claude-nights-watch-marketplace

MarketplaceWorks with Claude CodeGitHub

Official marketplace for Claude Nights Watch plugin

Safety scan

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

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/aniketkarne-claudenightswatch/badge.svg)](/listings/aniketkarne-claudenightswatch)

HTML

<a href="/listings/aniketkarne-claudenightswatch"><img src="/api/listings/aniketkarne-claudenightswatch/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

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

Prerequisites

1. [Claude CLI](https://docs.anthropic.com/en/docs/claude-code/quickstart) installed and configured 2. (Optional) [ccusage](https://www.npmjs.com/package/ccusage) for accurate timing:

   npm install -g ccusage

---

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.

.claude-plugin/marketplace.json · Manifest · 16 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. {
  2. "name": "claude-nights-watch-marketplace",
  3. "description": "Official marketplace for Claude Nights Watch plugin",
  4. "owner": {
  5. "name": "Aniket Karne",
  6. "email": "[email protected]",
  7. "url": "https://github.com/aniketkarne/ClaudeNightsWatch"
  8. },
  9. "plugins": [
  10. {
  11. "name": "claude-nights-watch",
  12. "source": "./",
  13. "description": "Autonomous task execution daemon for Claude CLI"
  14. }
  15. ]
  16. }
README.md · README · 618 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. # Claude Nights Watch 🌙
  2. [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
  3. [![Shell Script](https://img.shields.io/badge/Language-Shell-green.svg)](https://www.gnu.org/software/bash/)
  4. [![Claude Code Plugin](https://img.shields.io/badge/Plugin-Ready-blue.svg)](https://docs.anthropic.com/claude-code)
  5. [![GitHub stars](https://img.shields.io/github/stars/aniketkarne/ClaudeNightsWatch.svg?style=social&label=Star)](https://github.com/aniketkarne/ClaudeNightsWatch)
  6. **🚀 NEW: Now available as a Claude Code Plugin!** 🎉
  7. Autonomous task execution system for Claude CLI that monitors your usage windows and executes predefined tasks automatically. Built on top of the claude-auto-renew concept but instead of simple renewals, it executes complex tasks from a task.md file.
  8. **⚠️ Warning**: This tool uses `--dangerously-skip-permissions` for autonomous execution. Use with caution!
  9. ## 🎯 Two Ways to Use Claude Nights Watch
  10. Choose your preferred installation method:
  11. ### 🔥 **Recommended: Claude Code Plugin** (NEW!)
  12. - **Seamless Integration**: Works directly within Claude Code
  13. - **7 Slash Commands**: `/nights-watch start/stop/status/logs/task/setup/restart`
  14. - **AI Agent Integration**: Built-in Task Executor agent for autonomous guidance
  15. - **Smart Hooks**: Automatic session integration and activity logging
  16. - **MCP Server**: Programmatic control tools for Claude
  17. - **Enhanced UX**: Better error handling and user experience
  18. ### ⚡ **Original Daemon Method** (Legacy)
  19. - **Standalone Operation**: Works independently of Claude Code
  20. - **Script-based Control**: Direct shell script execution
  21. - **Proven Reliability**: Battle-tested daemon implementation
  22. - **Full Feature Set**: All core functionality available
  23. ## 🎯 Overview
  24. Claude Nights Watch extends the auto-renewal concept to create a fully autonomous task execution system. When your Claude usage window is about to expire, instead of just saying "hi", it reads your `task.md` file and executes the defined tasks autonomously.
  25. ### Key Features
  26. - 🤖 **Autonomous Execution**: Runs tasks without manual intervention
  27. - 📋 **Task-Based Workflow**: Define tasks in a simple markdown file
  28. - 🛡️ **Safety Rules**: Configure safety constraints in `rules.md`
  29. - ⏰ **Smart Timing**: Uses ccusage for accurate timing or falls back to time-based checking
  30. - 📅 **Scheduled Start**: Can be configured to start at a specific time
  31. - 📊 **Comprehensive Logging**: Track all activities and executions
  32. - 🔄 **Based on Proven Code**: Built on the reliable claude-auto-renew daemon
  33. ## 🚀 Quick Start
  34. ### Prerequisites
  35. 1. [Claude CLI](https://docs.anthropic.com/en/docs/claude-code/quickstart) installed and configured
  36. 2. (Optional) [ccusage](https://www.npmjs.com/package/ccusage) for accurate timing:
  37. ```bash
  38. npm install -g ccusage
  39. ```
  40. ---
  41. ## 🔥 Plugin Installation (Recommended)
  42. ### Option 1: As Claude Code Plugin
  43. #### Standard Installation
  44. ```bash
  45. # Method 1: From marketplace
  46. claude plugin marketplace add https://github.com/aniketkarne/ClaudeNightsWatch
  47. claude plugin install claude-nights-watch@claude-nights-watch-marketplace
  48. # Method 2: Direct from GitHub
  49. claude plugin install https://github.com/aniketkarne/ClaudeNightsWatch
  50. # Method 3: From local directory (for development)
  51. claude plugin marketplace add /path/to/ClaudeNightsWatch
  52. claude plugin install claude-nights-watch@claude-nights-watch-marketplace
  53. ```
  54. #### One-Command Installation
  55. Use the [Claude Plugins CLI](https://claude-plugins.dev) to skip the marketplace setup:
  56. ```bash
  57. npx claude-plugins install @aniketkarne/claude-nights-watch-marketplace/claude-nights-watch
  58. ```
  59. This automatically adds the marketplace and installs the plugin in a single step.
  60. ### Plugin Usage
  61. ```bash
  62. # Interactive setup
  63. /nights-watch setup
  64. # Start daemon
  65. /nights-watch start
  66. # Check status
  67. /nights-watch status
  68. # View logs in real-time
  69. /nights-watch logs -f
  70. # Stop daemon
  71. /nights-watch stop
  72. ```
  73. **Plugin Features:**
  74. - 🎯 **7 Slash Commands**: `/nights-watch start/stop/status/logs/task/setup/restart`
  75. - 🧠 **AI Agent**: Built-in Task Executor for autonomous guidance
  76. - 🔗 **MCP Server**: 8 programmatic tools for Claude control
  77. - 🎣 **Smart Hooks**: Automatic session integration
  78. ---
  79. ## ⚡ Original Daemon Installation (Legacy)
  80. ### Option 2: Install as Standalone Daemon
  81. 1. Clone this repository:
  82. ```bash
  83. git clone https://github.com/aniketkarne/ClaudeNightsWatch.git
  84. cd ClaudeNightsWatch
  85. ```
  86. 2. Make scripts executable:
  87. ```bash
  88. chmod +x *.sh
  89. ```
  90. 3. Run the interactive setup:
  91. ```bash
  92. ./setup-nights-watch.sh
  93. ```
  94. ### Daemon Usage
  95. 1. **Create your task file** (`task.md`):
  96. ```markdown
  97. # Daily Development Tasks
  98. 1. Run linting on all source files
  99. 2. Update dependencies to latest versions
  100. 3. Run the test suite
  101. 4. Generate coverage report
  102. 5. Create a summary of changes
  103. ```
  104. 2. **Create safety rules** (`rules.md`):
  105. ```markdown
  106. # Safety Rules
  107. - Never delete files without backing up
  108. - Only work within the project directory
  109. - Always create feature branches for changes
  110. - Never commit sensitive information
  111. ```
  112. 3. **Start the daemon**:
  113. ```bash
  114. ./claude-nights-watch-manager.sh start
  115. ```
  116. **Legacy Commands:**
  117. ```bash
  118. ./claude-nights-watch-manager.sh start [--at TIME] # Start daemon
  119. ./claude-nights-watch-manager.sh stop # Stop daemon
  120. ./claude-nights-watch-manager.sh status # Check status
  121. ./claude-nights-watch-manager.sh logs [-f] # View logs
  122. ./claude-nights-watch-manager.sh task # View task/rules
  123. ./claude-nights-watch-manager.sh restart # Restart daemon
  124. ```
  125. ## 📝 Configuration
  126. ### Task File (task.md)
  127. The task file contains the instructions that Claude will execute. It should be clear, specific, and well-structured. See `examples/task.example.md` for a comprehensive example.
  128. ### Rules File (rules.md)
  129. The rules file defines safety constraints and best practices. It's prepended to every task execution to ensure safe autonomous operation. See `examples/rules.example.md` for recommended rules.
  130. ### Environment Variables
  131. - `CLAUDE_NIGHTS_WATCH_DIR`: Set the directory containing task.md and rules.md (default: current directory)
  132. ## 🎮 Commands
  133. ### 🔥 Plugin Commands (NEW!)
  134. When using as a Claude Code plugin, use slash commands:
  135. ```bash
  136. # Start the daemon
  137. /nights-watch start
  138. # Start with scheduled time
  139. /nights-watch start --at "09:00"
  140. /nights-watch start --at "2025-01-28 14:30"
  141. # Stop the daemon
  142. /nights-watch stop
  143. # Check status
  144. /nights-watch status
  145. # View logs
  146. /nights-watch logs
  147. /nights-watch logs -f # Follow mode
  148. # View current task and rules
  149. /nights-watch task
  150. # Interactive setup
  151. /nights-watch setup
  152. # Restart daemon
  153. /nights-watch restart
  154. ```
  155. ### ⚡ Original Daemon Commands (Legacy)
  156. For standalone daemon usage:
  157. ```bash
  158. # Start the daemon
  159. ./claude-nights-watch-manager.sh start
  160. # Start with scheduled time
  161. ./claude-nights-watch-manager.sh start --at "09:00"
  162. ./claude-nights-watch-manager.sh start --at "2025-01-28 14:30"
  163. # Stop the daemon
  164. ./claude-nights-watch-manager.sh stop
  165. # Check status
  166. ./claude-nights-watch-manager.sh status
  167. # View logs
  168. ./claude-nights-watch-manager.sh logs
  169. ./claude-nights-watch-manager.sh logs -f # Follow mode
  170. # Use interactive log viewer
  171. ./view-logs.sh
  172. # View current task and rules
  173. ./claude-nights-watch-manager.sh task
  174. # Restart daemon
  175. ./claude-nights-watch-manager.sh restart
  176. ```
  177. ---
  178. ## 🧠 Plugin Features (NEW!)
  179. ### Task Executor Agent
  180. Built-in AI agent that helps with:
  181. - **Autonomous Task Planning**: Designing effective autonomous workflows
  182. - **Safety Rule Creation**: Building comprehensive safety constraints
  183. - **Daemon Management**: Starting, stopping, and troubleshooting
  184. - **Log Analysis**: Interpreting execution results and identifying issues
  185. **Usage:**
  186. ```
  187. User: "Help me create an autonomous code review workflow"
  188. Agent: Provides expert guidance and can execute /nights-watch commands
  189. User: "My daemon isn't working, help debug"
  190. Agent: Analyzes logs and suggests solutions
  191. ```
  192. ### MCP Server Integration
  193. Provides 8 programmatic tools for Claude:
  194. - `get_daemon_status` - Query daemon state
  195. - `start_daemon` - Start with optional schedule
  196. - `stop_daemon` - Stop the daemon
  197. - `get_logs` - Retrieve log entries
  198. - `read_task` - Read task.md content
  199. - `read_rules` - Read rules.md content
  200. - `write_task` - Update task.md
  201. - `write_rules` - Update rules.md
  202. ### Smart Hooks
  203. Automatic integration with Claude Code sessions:
  204. - **SessionStart**: Shows daemon status when starting Claude Code
  205. - **SessionEnd**: Prompts to start daemon if tasks are configured
  206. - **PostToolUse**: Logs file modifications for audit trail
  207. These hooks run silently in the background, enhancing your workflow.
  208. ## 🔧 How It Works
  209. 1. **Monitoring**: The daemon continuously monitors your Claude usage windows
  210. 2. **Timing**: When approaching the 5-hour limit (within 2 minutes), it prepares for execution
  211. 3. **Task Preparation**: Reads both `rules.md` and `task.md`, combining them into a single prompt
  212. 4. **Autonomous Execution**: Executes the task using `claude --dangerously-skip-permissions`
  213. 5. **Logging**: All activities are logged to `logs/claude-nights-watch-daemon.log`
  214. ### Timing Logic
  215. - **With ccusage**: Gets accurate remaining time from the API
  216. - **Without ccusage**: Falls back to timestamp-based checking
  217. - **Adaptive intervals**:
  218. - \>30 minutes remaining: Check every 10 minutes
  219. - 5-30 minutes remaining: Check every 2 minutes
  220. - <5 minutes remaining: Check every 30 seconds
  221. ## ⚠️ Safety Considerations
  222. **IMPORTANT**: This tool runs Claude with the `--dangerously-skip-permissions` flag, meaning it will execute tasks without asking for confirmation.
  223. ### Best Practices:
  224. 1. **Always test tasks manually first** before setting up autonomous execution
  225. 2. **Use comprehensive rules.md** to prevent destructive actions
  226. 3. **Start with simple, safe tasks** and gradually increase complexity
  227. 4. **Monitor logs regularly** to ensure proper execution
  228. 5. **Keep backups** of important data
  229. 6. **Run in isolated environments** when possible
  230. ### Recommended Restrictions:
  231. - Limit file system access to project directories
  232. - Prohibit deletion commands
  233. - Prevent system modifications
  234. - Restrict network access
  235. - Set resource limits
  236. ## 📁 File Structure
  237. ### 🔥 Plugin Structure (NEW!)
  238. When installed as a Claude Code plugin, the following structure is used:
  239. ```
  240. claude-nights-watch/
  241. ├── .claude-plugin/ # Plugin metadata (NEW!)
  242. │ └── plugin.json # Plugin manifest
  243. ├── commands/ # Slash command definitions (NEW!)
  244. │ ├── bin/nights-watch # Command wrapper
  245. │ ├── start.md # Start command documentation
  246. │ ├── stop.md # Stop command documentation
  247. │ ├── status.md # Status command documentation
  248. │ ├── logs.md # Logs command documentation
  249. │ ├── task.md # Task command documentation
  250. │ ├── setup.md # Setup command documentation
  251. │ └── restart.md # Restart command documentation
  252. ├── agents/ # AI agents (NEW!)
  253. │ └── task-executor.md # Autonomous task planning agent
  254. ├── hooks/ # Event handlers (NEW!)
  255. │ ├── hooks.json # Hook configuration
  256. │ └── scripts/ # Hook implementation scripts
  257. │ ├── check-daemon-status.sh # Session start hook
  258. │ ├── session-end-prompt.sh # Session end hook
  259. │ └── log-file-changes.sh # File modification hook
  260. ├── mcp-server/ # Model Context Protocol (NEW!)
  261. │ └── nights-watch-server.sh # MCP server implementation
  262. ├── .mcp.json # MCP server configuration (NEW!)
  263. └── [original files continue below...]
  264. ```
  265. ### ⚡ Original Daemon Structure (Legacy)
  266. The original standalone daemon structure:
  267. ```
  268. claude-nights-watch/
  269. ├── claude-nights-watch-daemon.sh # Core daemon process
  270. ├── claude-nights-watch-manager.sh # Daemon management interface
  271. ├── setup-nights-watch.sh # Interactive setup script
  272. ├── view-logs.sh # Interactive log viewer
  273. ├── README.md # This file
  274. ├── LICENSE # MIT License
  275. ├── CONTRIBUTING.md # Contribution guidelines
  276. ├── CHANGELOG.md # Version history
  277. ├── SUMMARY.md # Project summary
  278. ├── .gitignore # Git ignore file
  279. ├── .github/ # GitHub templates
  280. │ ├── ISSUE_TEMPLATE/
  281. │ │ ├── bug_report.md
  282. │ │ └── feature_request.md
  283. │ └── pull_request_template.md
  284. ├── logs/ # All logs stored here (created on first run)
  285. ├── examples/ # Example files
  286. │ ├── task.example.md # Example task file
  287. │ └── rules.example.md # Example rules file
  288. └── test/ # Test scripts and files
  289. ├── README.md # Testing documentation
  290. ├── test-immediate-execution.sh # Direct task execution test
  291. ├── test-simple.sh # Simple functionality test
  292. ├── test-task-simple.md # Simple test task
  293. ├── test-rules-simple.md # Simple test rules
  294. ├── test-plugin-comprehensive.sh # Plugin functionality tests (NEW!)
  295. └── test-functional-realworld.sh # Real-world testing suite (NEW!)
  296. ```
  297. ## 📊 Logging
  298. All logs are stored in the `logs/` directory within the project. Each log contains:
  299. - **Timestamps**: Every action is timestamped
  300. - **Full Prompts**: Complete prompt sent to Claude (rules + task)
  301. - **Full Responses**: Everything Claude outputs
  302. - **Status Messages**: Success/failure indicators
  303. ### Viewing Logs
  304. Use the interactive log viewer:
  305. ```bash
  306. ./view-logs.sh
  307. ```
  308. Features:
  309. - Browse all log files
  310. - View full logs or last 50 lines
  311. - Filter to see only prompts sent to Claude
  312. - Filter to see only Claude's responses
  313. - Search for errors
  314. - Follow logs in real-time
  315. ## 🧪 Testing
  316. ### Plugin Testing (NEW!)
  317. Comprehensive test suites for the Claude Code plugin:
  318. ```bash
  319. cd test
  320. # Run comprehensive plugin structure tests
  321. ./test-plugin-comprehensive.sh
  322. # Run functional and real-world testing
  323. ./test-functional-realworld.sh
  324. # Run immediate execution test (no waiting)
  325. ./test-immediate-execution.sh
  326. # Run simple functionality test
  327. ./test-simple.sh
  328. ```
  329. ### Original Daemon Testing (Legacy)
  330. ```bash
  331. cd test
  332. ./test-simple.sh # Run a simple test
  333. ```
  334. See `test/README.md` for detailed testing instructions.
  335. **New Testing Features:**
  336. - **Plugin Structure Validation**: Tests all plugin components
  337. - **Functional Testing**: Validates script execution and integration
  338. - **Real-World Simulation**: Tests complete user workflows
  339. - **Environment Testing**: Validates plugin environment variables
  340. - **Error Handling**: Tests graceful failure scenarios
  341. ## 🐛 Troubleshooting
  342. ### Plugin Issues (NEW!)
  343. **Plugin not loading:**
  344. ```bash
  345. # Check plugin installation
  346. claude plugin list | grep claude-nights-watch
  347. # Reinstall if needed
  348. claude plugin uninstall claude-nights-watch
  349. claude plugin install https://github.com/aniketkarne/ClaudeNightsWatch
  350. # Debug mode
  351. claude --debug
  352. ```
  353. **Commands not working:**
  354. ```bash
  355. # Verify command scripts are executable
  356. ls -la ~/.claude/plugins/claude-nights-watch/commands/bin/
  357. # Make executable if needed
  358. chmod +x ~/.claude/plugins/claude-nights-watch/commands/bin/nights-watch
  359. ```
  360. **Agent not responding:**
  361. - Ensure plugin is properly installed
  362. - Check that agent file exists in `agents/task-executor.md`
  363. - Verify MCP server is running
  364. ### Original Daemon Issues (Legacy)
  365. **Daemon won't start:**
  366. - Check if Claude CLI is installed: `which claude`
  367. - Verify task.md exists in the working directory
  368. - Check logs: `./claude-nights-watch-manager.sh logs`
  369. **Tasks not executing:**
  370. - Verify you have remaining Claude usage: `ccusage blocks`
  371. - Check if past scheduled start time
  372. - Ensure task.md is not empty
  373. - Review logs for errors
  374. **Timing issues:**
  375. - Install ccusage for better accuracy: `npm install -g ccusage`
  376. - Check system time is correct
  377. - Verify `.claude-last-activity` timestamp
  378. ### Common Issues (Both Methods)
  379. **Permission errors:**
  380. ```bash
  381. # Ensure all scripts are executable
  382. chmod +x *.sh
  383. chmod +x commands/bin/nights-watch
  384. chmod +x hooks/scripts/*.sh
  385. chmod +x mcp-server/*.sh
  386. ```
  387. **Missing dependencies:**
  388. - Install Claude CLI: https://docs.anthropic.com/claude-code
  389. - Install ccusage: `npm install -g ccusage` (recommended)
  390. - Verify bash is available: `which bash`
  391. **Configuration issues:**
  392. - Check task.md exists and has content
  393. - Verify rules.md exists (recommended)
  394. - Ensure proper file permissions
  395. - Check environment variables
  396. ## 🤝 Contributing
  397. Contributions are welcome! Please follow these steps:
  398. 1. **Fork the repository** on GitHub
  399. 2. **Clone your fork** locally
  400. 3. **Create a feature branch** (`git checkout -b feature/amazing-feature`)
  401. 4. **Make your changes** following our guidelines
  402. 5. **Test thoroughly** using the test suite
  403. 6. **Commit your changes** (`git commit -m 'Add amazing feature'`)
  404. 7. **Push to your fork** (`git push origin feature/amazing-feature`)
  405. 8. **Create a Pull Request** on GitHub
  406. Please ensure:
  407. - Code follows existing style
  408. - Safety is prioritized
  409. - Documentation is updated
  410. - Examples are provided
  411. - Tests pass
  412. See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines.
  413. ## 📄 License
  414. This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
  415. ## 🙏 Acknowledgments
  416. - **Created by**: [Aniket Karne](https://github.com/aniketkarne)
  417. - **Built on top of**: The excellent [CCAutoRenew](https://github.com/aniketkarne/CCAutoRenew) project
  418. - **Plugin Development**: Complete Claude Code plugin implementation with slash commands, AI agents, MCP server, and smart hooks
  419. - **Enhanced Features**: Task Executor agent, comprehensive testing suites, and dual installation methods
  420. - **Thanks to**: The Claude CLI team for the amazing tool and plugin system
  421. ---
  422. ---
  423. ## 🔄 Migration Guide
  424. ### From Daemon to Plugin
  425. If you're currently using the standalone daemon and want to migrate to the plugin:
  426. 1. **Install the plugin**:
  427. ```bash
  428. claude plugin install https://github.com/aniketkarne/ClaudeNightsWatch
  429. ```
  430. 2. **Copy your existing files**:
  431. ```bash
  432. # Copy your task.md and rules.md to the new location
  433. cp task.md rules.md ~/.claude/plugins/claude-nights-watch/
  434. ```
  435. 3. **Update your workflow**:
  436. - Replace `./claude-nights-watch-manager.sh start` with `/nights-watch start`
  437. - Replace `./claude-nights-watch-manager.sh logs` with `/nights-watch logs`
  438. - Use `/nights-watch setup` for configuration
  439. 4. **Benefits you'll gain**:
  440. - 🤖 **AI Agent Integration**: Get help from the Task Executor agent
  441. - 🎯 **Better Commands**: More intuitive slash command interface
  442. - 🔗 **MCP Integration**: Programmatic control for Claude
  443. - 🎣 **Smart Hooks**: Automatic session integration
  444. ### From Plugin to Daemon
  445. If you prefer the standalone approach:
  446. 1. **Install as daemon**:
  447. ```bash
  448. git clone https://github.com/aniketkarne/ClaudeNightsWatch.git
  449. cd ClaudeNightsWatch
  450. chmod +x *.sh
  451. ```
  452. 2. **Copy your plugin files**:
  453. ```bash
  454. # Copy from plugin location to daemon location
  455. cp ~/.claude/plugins/claude-nights-watch/task.md .
  456. cp ~/.claude/plugins/claude-nights-watch/rules.md .
  457. ```
  458. 3. **Use daemon commands**:
  459. ```bash
  460. ./claude-nights-watch-manager.sh start
  461. ```
  462. **Note**: The plugin method is recommended for new users due to better integration and enhanced features.
  463. ---
  464. **Remember**: With great automation comes great responsibility. Always review your tasks and rules carefully before enabling autonomous execution! 🚨
claude-nights-watch-daemon.sh · Bundled script · 409 lines · 1 finding marked
  1. #!/bin/bash
  2. # Claude Nights Watch Daemon - Autonomous Task Execution
  3. # Based on claude-auto-renew-daemon but executes tasks instead of simple renewals
  4. LOG_FILE="${CLAUDE_NIGHTS_WATCH_DIR:-$(dirname "$0")}/logs/claude-nights-watch-daemon.log"
  5. PID_FILE="${CLAUDE_NIGHTS_WATCH_DIR:-$(dirname "$0")}/logs/claude-nights-watch-daemon.pid"
  6. LAST_ACTIVITY_FILE="$HOME/.claude-last-activity"
  7. START_TIME_FILE="${CLAUDE_NIGHTS_WATCH_DIR:-$(dirname "$0")}/logs/claude-nights-watch-start-time"
  8. TASK_FILE="task.md"
  9. RULES_FILE="rules.md"
  10. TASK_DIR="${CLAUDE_NIGHTS_WATCH_DIR:-$(pwd)}"
  11. # Ensure logs directory exists
  12. mkdir -p "$(dirname "$LOG_FILE")" 2>/dev/null
  13. # Function to log messages
  14. log_message() {
  15. echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
  16. }
  17. # Function to handle shutdown
  18. cleanup() {
  19. log_message "Daemon shutting down..."
  20. rm -f "$PID_FILE"
  21. exit 0
  22. }
  23. # Set up signal handlers
  24. trap cleanup SIGTERM SIGINT
  25. # Function to check if we're past the start time
  26. is_start_time_reached() {
  27. if [ ! -f "$START_TIME_FILE" ]; then
  28. # No start time set, always active
  29. return 0
  30. fi
  31. local start_epoch=$(cat "$START_TIME_FILE")
  32. local current_epoch=$(date +%s)
  33. if [ "$current_epoch" -ge "$start_epoch" ]; then
  34. return 0 # Start time reached
  35. else
  36. return 1 # Still waiting
  37. fi
  38. }
  39. # Function to get time until start
  40. get_time_until_start() {
  41. if [ ! -f "$START_TIME_FILE" ]; then
  42. echo "0"
  43. return
  44. fi
  45. local start_epoch=$(cat "$START_TIME_FILE")
  46. local current_epoch=$(date +%s)
  47. local diff=$((start_epoch - current_epoch))
  48. if [ "$diff" -le 0 ]; then
  49. echo "0"
  50. else
  51. echo "$diff"
  52. fi
  53. }
  54. # Function to get ccusage command
  55. get_ccusage_cmd() {
  56. if command -v ccusage &> /dev/null; then
  57. echo "ccusage"
  58. elif command -v bunx &> /dev/null; then
  59. echo "bunx ccusage"
  60. elif command -v npx &> /dev/null; then
  61. echo "npx ccusage@latest"
  62. else
  63. return 1
  64. fi
  65. }
  66. # Function to get minutes until reset
  67. get_minutes_until_reset() {
  68. local ccusage_cmd=$(get_ccusage_cmd)
  69. if [ $? -ne 0 ]; then
  70. return 1
  71. fi
  72. # Use JSON output with --active flag to get only the active block
  73. local json_output=$($ccusage_cmd blocks --json --active 2>/dev/null)
  74. if [ -z "$json_output" ]; then
  75. # No active block - fallback to 0 like original behavior
  76. echo "0"
  77. return 0
  78. fi
  79. # Extract endTime from the active block
  80. local end_time=$(echo "$json_output" | grep '"endTime"' | head -1 | sed 's/.*"endTime": *"\([^"]*\)".*/\1/')
  81. if [ -z "$end_time" ]; then
  82. echo "0"
  83. return 0
  84. fi
  85. # Convert ISO timestamp to Unix epoch for calculation
  86. local end_epoch
  87. if command -v date &> /dev/null; then
  88. # Try different date command formats (macOS vs Linux)
  89. # Linux format (handles UTC properly)
  90. if end_epoch=$(date -d "$end_time" +%s 2>/dev/null); then
  91. :
  92. # macOS format - need to specify UTC timezone
  93. elif end_epoch=$(TZ=UTC date -j -f "%Y-%m-%dT%H:%M:%S.000Z" "$end_time" +%s 2>/dev/null); then
  94. :
  95. # macOS format without milliseconds in UTC
  96. elif end_epoch=$(TZ=UTC date -j -f "%Y-%m-%dT%H:%M:%SZ" "$end_time" +%s 2>/dev/null); then
  97. :
  98. # Try stripping the .000Z and parsing in UTC
  99. elif stripped_time=$(echo "$end_time" | sed 's/\.000Z$/Z/') && end_epoch=$(TZ=UTC date -j -f "%Y-%m-%dT%H:%M:%SZ" "$stripped_time" +%s 2>/dev/null); then
  100. :
  101. else
  102. log_message "Could not parse ccusage endTime format: $end_time" >&2
  103. echo "0"
  104. return 0
  105. fi
  106. else
  107. echo "0"
  108. return 0
  109. fi
  110. local current_epoch=$(date +%s)
  111. local time_diff=$((end_epoch - current_epoch))
  112. local remaining_minutes=$((time_diff / 60))
  113. if [ "$remaining_minutes" -gt 0 ]; then
  114. echo $remaining_minutes
  115. else
  116. echo "0"
  117. return 0
  118. fi
  119. }
  120. # Function to prepare task with rules
  121. prepare_task_prompt() {
  122. local prompt=""
  123. # Add rules if they exist
  124. if [ -f "$TASK_DIR/$RULES_FILE" ]; then
  125. prompt="IMPORTANT RULES TO FOLLOW:\n\n"
  126. prompt+=$(cat "$TASK_DIR/$RULES_FILE")
  127. prompt+="\n\n---END OF RULES---\n\n"
  128. log_message "Applied rules from $RULES_FILE"
  129. fi
  130. # Add task content
  131. if [ -f "$TASK_DIR/$TASK_FILE" ]; then
  132. prompt+="TASK TO EXECUTE:\n\n"
  133. prompt+=$(cat "$TASK_DIR/$TASK_FILE")
  134. prompt+="\n\n---END OF TASK---\n\n"
  135. prompt+="Please read the above task, create a todo list from it, and then execute it step by step."
  136. else
  137. log_message "ERROR: Task file not found at $TASK_DIR/$TASK_FILE"
  138. return 1
  139. fi
  140. echo -e "$prompt"
  141. }
  142. # Function to execute task
  143. execute_task() {
  144. log_message "Starting task execution from $TASK_FILE..."
  145. if ! command -v claude &> /dev/null; then
  146. log_message "ERROR: claude command not found"
  147. return 1
  148. fi
  149. # Check if task file exists
  150. if [ ! -f "$TASK_DIR/$TASK_FILE" ]; then
  151. log_message "ERROR: Task file not found at $TASK_DIR/$TASK_FILE"
  152. return 1
  153. fi
  154. # Prepare the full prompt with rules and task
  155. local full_prompt=$(prepare_task_prompt)
  156. if [ $? -ne 0 ]; then
  157. return 1
  158. fi
  159. log_message "Executing task with Claude (autonomous mode)..."
  160. # Log the full prompt being sent
  161. echo "" >> "$LOG_FILE"
  162. echo "=== PROMPT SENT TO CLAUDE ===" >> "$LOG_FILE"
  163. echo -e "$full_prompt" >> "$LOG_FILE"
  164. echo "=== END OF PROMPT ===" >> "$LOG_FILE"
  165. echo "" >> "$LOG_FILE"
  166. # Execute task with Claude in autonomous mode
  167. # Log everything - both the execution and the response
  168. log_message "=== CLAUDE RESPONSE START ==="
  169. (echo -e "$full_prompt" | claude --dangerously-skip-permissions 2>&1) | tee -a "$LOG_FILE" &
  170. local pid=$!
  171. # Monitor execution (no timeout for complex tasks)
  172. log_message "Task execution started (PID: $pid)"
  173. # Wait for completion
  174. wait $pid
  175. local result=$?
  176. log_message "=== CLAUDE RESPONSE END ==="
  177. if [ $result -eq 0 ]; then
  178. log_message "Task execution completed successfully"
  179. date +%s > "$LAST_ACTIVITY_FILE"
  180. return 0
  181. else
  182. log_message "ERROR: Task execution failed with code $result"
  183. return 1
  184. fi
  185. }
  186. # Function to calculate next check time
  187. calculate_sleep_duration() {
  188. local minutes_remaining=$(get_minutes_until_reset)
  189. if [ -n "$minutes_remaining" ] && [ "$minutes_remaining" -gt 0 ]; then
  190. log_message "Time remaining: $minutes_remaining minutes" >&2
  191. if [ "$minutes_remaining" -le 5 ]; then
  192. # Check every 30 seconds when close to reset
  193. echo 30
  194. elif [ "$minutes_remaining" -le 30 ]; then
  195. # Check every 2 minutes when within 30 minutes
  196. echo 120
  197. else
  198. # Check every 10 minutes otherwise
  199. echo 600
  200. fi
  201. else
  202. # Fallback: check based on last activity
  203. if [ -f "$LAST_ACTIVITY_FILE" ]; then
  204. local last_activity=$(cat "$LAST_ACTIVITY_FILE")
  205. local current_time=$(date +%s)
  206. local time_diff=$((current_time - last_activity))
  207. local remaining=$((18000 - time_diff)) # 5 hours = 18000 seconds
  208. if [ "$remaining" -le 300 ]; then # 5 minutes
  209. echo 30
  210. elif [ "$remaining" -le 1800 ]; then # 30 minutes
  211. echo 120
  212. else
  213. echo 600
  214. fi
  215. else
  216. # No info available, check every 5 minutes
  217. echo 300
  218. fi
  219. fi
  220. }
  221. # Main daemon loop
  222. main() {
  223. # Check if already running
  224. if [ -f "$PID_FILE" ]; then
  225. OLD_PID=$(cat "$PID_FILE")
  226. if kill -0 "$OLD_PID" 2>/dev/null; then
  227. echo "Daemon already running with PID $OLD_PID"
  228. exit 1
  229. else
  230. log_message "Removing stale PID file"
  231. rm -f "$PID_FILE"
  232. fi
  233. fi
  234. # Save PID
  235. echo $$ > "$PID_FILE"
  236. log_message "=== Claude Nights Watch Daemon Started ==="
  237. log_message "PID: $$"
  238. log_message "Logs: $LOG_FILE"
  239. log_message "Task directory: $TASK_DIR"
  240. # Check for task file
  241. if [ ! -f "$TASK_DIR/$TASK_FILE" ]; then
  242. log_message "WARNING: Task file not found at $TASK_DIR/$TASK_FILE"
  243. log_message "Please create a task.md file with your tasks"
  244. fi
  245. # Check for rules file
  246. if [ -f "$TASK_DIR/$RULES_FILE" ]; then
  247. log_message "Rules file found at $TASK_DIR/$RULES_FILE"
  248. else
  249. log_message "No rules file found. Consider creating $RULES_FILE for safety constraints"
  250. fi
  251. # Check for start time
  252. if [ -f "$START_TIME_FILE" ]; then
  253. start_epoch=$(cat "$START_TIME_FILE")
  254. log_message "Start time configured: $(date -d "@$start_epoch" 2>/dev/null || date -r "$start_epoch")"
  255. else
  256. log_message "No start time set - will begin monitoring immediately"
  257. fi
  258. # Check ccusage availability
  259. if ! get_ccusage_cmd &> /dev/null; then
  260. log_message "WARNING: ccusage not found. Using time-based checking."
  261. log_message "Install ccusage for more accurate timing: npm install -g ccusage"
  262. fi
  263. # Main loop
  264. while true; do
  265. # Check if we're past start time
  266. if ! is_start_time_reached; then
  267. time_until_start=$(get_time_until_start)
  268. hours=$((time_until_start / 3600))
  269. minutes=$(((time_until_start % 3600) / 60))
  270. seconds=$((time_until_start % 60))
  271. if [ "$hours" -gt 0 ]; then
  272. log_message "Waiting for start time (${hours}h ${minutes}m remaining)..."
  273. sleep 300 # Check every 5 minutes when waiting
  274. elif [ "$minutes" -gt 2 ]; then
  275. log_message "Waiting for start time (${minutes}m ${seconds}s remaining)..."
  276. sleep 60 # Check every minute when close
  277. elif [ "$time_until_start" -gt 10 ]; then
  278. log_message "Waiting for start time (${minutes}m ${seconds}s remaining)..."
  279. sleep 10 # Check every 10 seconds when very close
  280. else
  281. log_message "Waiting for start time (${seconds}s remaining)..."
  282. sleep 2 # Check every 2 seconds when imminent
  283. fi
  284. continue
  285. fi
  286. # If we just reached start time, log it
  287. if [ -f "$START_TIME_FILE" ]; then
  288. # Check if this is the first time we're active
  289. if [ ! -f "${START_TIME_FILE}.activated" ]; then
  290. log_message "✅ Start time reached! Beginning task execution monitoring..."
  291. touch "${START_TIME_FILE}.activated"
  292. fi
  293. fi
  294. # Get minutes until reset
  295. minutes_remaining=$(get_minutes_until_reset)
  296. # Check if we should execute task
  297. should_execute=false
  298. if [ -n "$minutes_remaining" ] && [ "$minutes_remaining" -gt 0 ]; then
  299. if [ "$minutes_remaining" -le 2 ]; then
  300. should_execute=true
  301. log_message "Reset imminent ($minutes_remaining minutes), preparing to execute task..."
  302. fi
  303. else
  304. # Fallback check
  305. if [ -f "$LAST_ACTIVITY_FILE" ]; then
  306. last_activity=$(cat "$LAST_ACTIVITY_FILE")
  307. current_time=$(date +%s)
  308. time_diff=$((current_time - last_activity))
  309. if [ $time_diff -ge 18000 ]; then
  310. should_execute=true
  311. log_message "5 hours elapsed since last activity, executing task..."
  312. fi
  313. else
  314. # No activity recorded, safe to start
  315. should_execute=true
  316. log_message "No previous activity recorded, starting initial task execution..."
  317. fi
  318. fi
  319. # Execute task if needed
  320. if [ "$should_execute" = true ]; then
  321. # Check if task file exists before execution
  322. if [ ! -f "$TASK_DIR/$TASK_FILE" ]; then
  323. log_message "ERROR: Cannot execute - task file not found at $TASK_DIR/$TASK_FILE"
  324. log_message "Waiting 5 minutes before next check..."
  325. sleep 300
  326. continue
  327. fi
  328. # Wait a bit to ensure we're in the renewal window
  329. sleep 60
  330. # Try to execute task
  331. if execute_task; then
  332. log_message "Task execution completed!"
  333. # Sleep for 5 minutes after successful execution
  334. sleep 300
  335. else
  336. log_message "Task execution failed, will retry in 1 minute"
  337. sleep 60
  338. fi
  339. fi
  340. # Calculate how long to sleep
  341. sleep_duration=$(calculate_sleep_duration)
  342. log_message "Next check in $((sleep_duration / 60)) minutes"
  343. # Sleep until next check
  344. sleep "$sleep_duration"
  345. done
  346. }
  347. # Start the daemon
  348. main

Ratings and comments

Sign in to rate this skill.

Sign in

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