# natural-language-planner

Adopt this skill: https://proskills.md/skills/productivity/natural-language-planner

Page: https://proskills.md/skills/productivity/natural-language-planner
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 53503
sha: 0828961b053e0d7e9f15033a22721089abea1503
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/SKILL.md
truncated: true

````text
---
slug: natural-language-planner
displayName: Natural Language Planner
name: natural-language-planner
description: >
  Natural language task and project management. Use when the user talks about
  things they need to do, projects they're working on, tasks, deadlines, or
  asks for a project overview / dashboard. Captures tasks from conversation,
  organises them into projects, tracks progress, and serves a local Kanban
  dashboard.
license: Complete terms in LICENSE.txt
---

# Natural Language Planner

You are an intelligent task and project manager. You capture tasks from
natural conversation, organise them into projects, and help the user stay on
top of their work — all stored as simple Markdown files on their local machine.

---

## 1. First-Time Setup

Before calling any planner Python helpers against an existing workspace, point the skill at the correct workspace first:

```python
from scripts.config_manager import set_config_path
set_config_path("/mnt/ClawFiles/nlplanner")  # use the real workspace root
```

This matters on systems with multiple planner locations. If you skip `set_config_path(...)`, the scripts may silently fall back to `~/nlplanner/.nlplanner/config.json`, and updates/archives can hit the wrong workspace.

If the workspace has **not** been initialised yet (no `.nlplanner/config.json`
exists in the workspace path), walk the user through setup:

1. Ask where they'd like to store their planner data.
   Suggest a sensible default:
   - **Windows**: `~/nlplanner`
   - **macOS / Linux**: `~/nlplanner`
2. Run the initialisation script:

```python
import sys, os

# Locate the skill root automatically (env var, openclaw dir, pnpm, or cwd)
from scripts.config_manager import get_skill_root
skill_root = str(get_skill_root())
if skill_root not in sys.path:
    sys.path.insert(0, skill_root)

from scripts.file_manager import init_workspace
init_workspace("<WORKSPACE_PATH>")
```

> **Tip:** If auto-detection fails, set the `NLP_SKILL_PATH` environment
> variable to the directory containing `SKILL.md`, `scripts/`, and
> `templates/`.

3. Confirm success:
   > "Your planner workspace is ready at `<path>`. Just tell me about anything
   > you need to do and I'll keep track of it for you."

### Re-initialisation

If the workspace directory is missing or corrupted, offer to re-create it.
Existing files are never deleted — `init_workspace` only creates what's missing.

---

## 2. Listening for Tasks & Projects

During **every** conversation turn, look for signals that the user is talking
about work they need to do, are doing, or have finished.

### Intent detection patterns

| User says (examples) | Detected intent | Action |
|---|---|---|
| "I need to…", "I should…", "Remind me to…", "Don't forget to…" | **New task** | `create_task(...)` |
| "I'm working on…", "Started the…", "Currently doing…" | **Status → in-progress** | `update_task(id, {"status": "in-progress"})` |
| "Finished the…", "Done with…", "Completed…" | **Status → done** | `update_task(id, {"status": "done"})` |
| "Let me start a project for…", "I have a big project…" | **New project** | `create_project(...)` |
| "This is related to…", "Part of the… project" | **Link / move** | `move_task(...)` or `link_tasks(...)` |
| "Cancel…", "Nevermind about…", "Drop the…" | **Archive** | `archive_task(...)` |
| "I'm about halfway through…", "Almost done with…", "80% done" | **Progress update** | `update_task(id, {"progress": N})` (0–100) |
| "Break this down…", "This is a big task", complex multi-step requests | **Suggest subtasks** | Offer breakdown, then `create_task(…, details={"subtasks": […]})` or `add_subtasks(id, [...])` |
| "Show me what I'm working on", "What's on my plate?" | **Overview** | List tasks / offer dashboard |

### Task creation workflow

Every time you create a task, follow these three steps in order:

#### Step 1 — Extract structured data

Pull as much structured information as you can from the conversation.
Fill in reasonable defaults for anything missing.

- **Title**: Short, action-oriented phrase.
- **Priority**: Look for words like *urgent*, *important*, *critical* → high;
  *whenever*, *low priority*, *nice to have* → low; otherwise medium.
- **Due date**: Parse natural language dates ("next Tuesday", "end of month",
  "by Friday"). Convert to ISO format (`YYYY-MM-DD`).
- **Tags**: Intelligently infer tags from context. Follow these rules:
  1. **Reuse existing tags first** — before inventing a new tag, check what
     tags already exist across the workspace (via `search_tasks` or
     `list_tasks`). Consistent tagging makes filtering useful.
  2. **Infer from domain** — if the user says "fix the login bug", add
     `bug` and `auth`. If they say "design the landing page", add `design`
     and `frontend`.
  3. **Infer from history** — if the user has been working on a series of
     tasks tagged `backend`, and they add a new API-related task, carry
     `backend` forward without being asked.
  4. **Cross-reference projects** — tasks in a project should generally
     inherit the project's tags, plus task-specific ones.
  5. **Keep tags short and lowercase** — single words or hyphenated phrases
     (e.g., `ui`, `bug-fix`, `q1-planning`).
  6. **Suggest but don't over-tag** — 2–4 tags per task is ideal. Don't add
     tags that add no filtering value (e.g., don't tag everything `task`).
- **Description**: A sentence or two expanding on the title.
- **Dependencies**: "Before I do X, I need Y" → link Y as dependency of X.
- **Context**: Save a brief summary of the conversation that led to the task.

#### Step 2 — Add Agent Tips (2–4 tips)

Before you call `create_task`, think about what would genuinely help the
user succeed at this task and prepare **2–4 tips** covering any of:

- **Approach** — a suggested way to tackle the work.
- **Tools / resources** — specific libraries, services, docs, or examples.
- **Pitfalls** — common mistakes or things to watch out for.
- **Inspiration** — creative ideas, reference projects, or lateral thinking.

This step is **not optional**. Every new task should ship with agent tips.
See **Section 6** for detailed guidance on writing great tips.

#### Step 3 — Create the task

Pass the structured data *and* tips together in a single `create_task` call:

```python
from scripts.file_manager import create_task
task_id = create_task(
    "Design new homepage layout",
    project_id="website-redesign",
    details={
        "description": "Create wireframes and mockups for the new homepage",
        "priority": "high",
        "due": "2026-02-15",
        "tags": ["design", "frontend"],
        "context": "User wants a modern, clean look — homepage is the top priority",
        "agent_tips": [
            "Start mobile-first — most traffic is from phones these days",
            "Figma has a free tier that works well for wireframing collaboratively",
            "Run a Lighthouse audit on the current page first so you have a baseline",
        ],
    }
)
```

### Avoiding duplicates

Before creating a new task, search existing tasks (by title similarity) to
check whether the user is referring to something already tracked. If a likely
match exists, update it instead of creating a duplicate.

```python
from scripts.index_manager import search_tasks
matches = search_tasks("deploy to staging")
# If matches[0] looks like the same task → update instead of create
```

---

## 3. Automatic Organisation

- When **3 or more tasks** share a common theme and aren't already in a
  project, suggest creating a project:
  > "I notice you have several tasks related to the website redesign.
  > Want me to group them into a project?"

- When the user confirms, create the project and move the tasks into it.

- New tasks that clearly belong to an existing project should be placed
  there automatically (tell the user which project you chose).

- Tasks without a clear project go to **inbox**.

---

## 4. Proactive Check-ins

Track the `last_checkin` date on eac
````

## File: examples/sample_project/README.md
size: 499
sha: fbc3dc2e3f43191585b9ff5b0b1d6cc2087ec075
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/examples/sample_project/README.md

```text
---
id: website-redesign
title: Website Redesign
created: '2026-02-09'
status: active
tags:
- design
- frontend
---

## Description
Modernise the company website with new branding, improved UX, and mobile-first responsive design.

## Goals
- Redesign homepage with new brand identity
- Make all pages mobile-responsive
- Improve page load performance by 50%
- Update content across all pages

## Notes
- Stakeholder meeting scheduled for Feb 12
- Brand guidelines document available in shared drive
```

## File: README.md
size: 11199
sha: 65009dfe221abc4e73173a1e9ff2855caca7a629
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/README.md

````text
# Natural Language Planner

An OpenClaw skill that turns natural conversation into organised tasks and projects — stored as simple Markdown files on your local machine.

## What It Does

- **Talk naturally** — just mention what you need to do and the AI captures it as a task
- **Automatic organisation** — tasks are grouped into projects, priorities set, due dates parsed
- **Visual dashboard** — a local Kanban board at `localhost:8080` shows everything at a glance
- **Proactive check-ins** — the AI asks about stale tasks so nothing falls through the cracks
- **Local-first** — all data is Markdown + YAML on your filesystem. No accounts, no cloud, no lock-in

## Quick Start

### 1. Install the dependency

```bash
pip install pyyaml
```

### 2. Add the skill to your AI assistant

Copy or clone this directory into your skills folder. The AI will detect the
`SKILL.md` and activate the planner automatically.

### 3. Start using it

Just talk to your AI assistant:

> "I need to redesign the homepage by next Friday — it's the most urgent thing right now."

The assistant will:
- Create a task titled **Redesign homepage** with high priority and a due date
- Place it in the **inbox** (or an existing project if one fits)
- Confirm what it did

### 4. Open the dashboard (optional)

The AI assistant automatically starts the dashboard when you work with tasks.
You can also start it manually:

```bash
python -m scripts dashboard ~/nlplanner

# Or use the standalone launcher (works from any directory):
python dashboard-daemon.py ~/nlplanner

# Or the shell script equivalent:
./start-dashboard.sh ~/nlplanner
```

## Workspace Structure

All your data lives in one directory (default `~/nlplanner`):

```
~/nlplanner/
├── .nlplanner/          # Config and dashboard files
│   └── config.json
├── projects/
│   ├── inbox/           # Uncategorised tasks
│   │   └── tasks/
│   ├── website-redesign/
│   │   ├── README.md    # Project metadata
│   │   ├── tasks/       # Task markdown files
│   │   └── attachments/ # Images, documents
│   └── ...
└── archive/             # Archived projects and tasks
```

Every task and project is a Markdown file with YAML frontmatter — readable
and editable in any text editor.

## Configuration

Settings live in `.nlplanner/config.json`:

| Setting | Default | Description |
|---|---|---|
| `checkin_frequency_hours` | 24 | How often to ask about stale tasks |
| `reminder_style` | `"casual-checkin"` | Reminder tone preset: `productivity-bro`, `casual-checkin`, `strict-coach`, `completion-tracker` |
| `reminder_proactivity` | `"proactive"` | Reminder behavior: automatic (`proactive`) or only when asked (`on-request`) |
| `auto_archive_completed_days` | 30 | Days before done tasks auto-archive |
| `default_priority` | `"medium"` | Default priority for new tasks |
| `dashboard_port` | 8080 | Port for the local dashboard |
| `dashboard_auto_start` | `true` | Agent auto-starts the dashboard on first task operation |
| `dashboard_allow_network` | `false` | Bind to all interfaces (0.0.0.0) instead of localhost |

## Dashboard Features

The browser-based dashboard includes:

- **This Week view** — focus cards for what you're working on this week
- **Kanban board** — drag-free columns for To Do, In Progress, Done
- **Project overview** — cards showing each project with task counts
- **Timeline** — upcoming deadlines sorted by date
- **Search** — find any task instantly
- **Task detail modal** — click to see full task info, attachments, and AI tips
- **Image gallery** — attachments displayed as thumbnails with lightbox
- **Dark mode** — toggle via the header icon (persists across sessions)
- **Auto-refresh** — updates every 5 seconds

## Remote Access (Tunnels)

Want to check your dashboard from your phone or share a link with someone?
The planner can create a secure tunnel to expose your local dashboard.

```bash
# Auto-detects cloudflared, ngrok, or localtunnel
python -m scripts tunnel ~/nlplanner
```

Or ask the AI: *"Make my dashboard accessible from my phone."*

**Supported tools** (install one):

| Tool | Install | Notes |
|---|---|---|
| Cloudflare Tunnel | `winget install cloudflare.cloudflared` / `brew install cloudflared` | Free, no account needed for quick tunnels |
| ngrok | [ngrok.com/download](https://ngrok.com/download) | Free tier, requires account |
| localtunnel | `npm install -g localtunnel` | Free, no account |

> **Security note:** The dashboard has no authentication. Anyone with the
> tunnel URL can view your tasks. Share the link carefully.

## Persistent Service (Raspberry Pi / Servers)

On a headless device (Raspberry Pi, home server, NAS), you can run the
dashboard as a systemd service so it starts on boot and stays running:

1. Create the service file:

```bash
sudo tee /etc/systemd/system/nlplanner-dashboard.service << 'EOF'
[Unit]
Description=Natural Language Planner Dashboard
After=network.target

[Service]
Type=simple
User=YOUR_USERNAME
ExecStart=/usr/bin/python3 /path/to/natural-language-planner/dashboard-daemon.py --network /path/to/workspace
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF
```

`dashboard-daemon.py` automatically locates the skill's `scripts/` and
`templates/` directories regardless of how the skill was installed (symlink,
pnpm global, local checkout). If auto-detection doesn't work for your setup,
add an `Environment=NLP_SKILL_PATH=/path/to/skill` line under `[Service]`.

2. Enable and start:

```bash
sudo systemctl daemon-reload
sudo systemctl enable nlplanner-dashboard.service
sudo systemctl start nlplanner-dashboard.service
```

3. Check status and logs:

```bash
systemctl status nlplanner-dashboard.service
journalctl -u nlplanner-dashboard.service -f
```

> **Tip:** Before starting, make sure nothing else is using port 8080
> (`sudo ss -tlnp | grep 8080`). Stale services from earlier setups are
> a common cause of port conflicts. Check with
> `systemctl list-units --type=service | grep dashboard`.

Omit `--network` if the dashboard should only be accessible on localhost.

## Static Export

Export a self-contained HTML snapshot of your dashboard for hosting on any
static platform (GitHub Pages, Netlify, Vercel).

```bash
# Default: exports to <workspace>/.nlplanner/export/
python -m scripts export ~/nlplanner

# Export to a specific directory (e.g. for GitHub Pages)
python -m scripts export ~/nlplanner --output ./docs
```

The export inlines all CSS, JS, and data into a single `index.html` that
works without a server. Note that exports are snapshots — re-export after
changes for an updated version.

## Startup & Port Locking

The dashboard locks to port **8080 by default**. If the port is already in
use the server will **fail immediately** with a clear error instead of
silently falling back to another port.

To allow automatic fallback (not recommended for production), pass
`--no-strict-port`:

```bash
python -m scripts dashboard --no-strict-port ~/nlplanner
```

### Freeing a stuck port

```bash
# Linux / macOS
lsof -i :8080
kill <PID>

# Windows
netstat -ano | findstr :8080
taskkill /PID <PID> /F
```

### Using a different port

Edit `<workspace>/.nlplanner/config.json`:

```json
{
  "settings": {
    "dashboard_port": 9000
  }
}
```

Or pass `--port`:

```bash
python -m scripts dashboard --port 9000 ~/nlplanner
```

## Environment Variables

| Variable | Default | Description |
|---|---|---|
| `NLP_SKILL_PATH` | *(auto-detected)* | Override the skill root directory. Point it at the folder containing `SKILL.md`, `scripts/`, and `templates/`. |
| `SKILL_PATH` | *(auto-detected)* | Alias for `NLP_SKILL_PATH`. `NLP_SKILL_PATH` takes priority if both are set. |

The skill searches for its own installation in this order:
1. `NLP_SKILL_PATH` / `SKILL_PATH` environment variable
2. `~/.openclaw/skills/natural-language-planner`
3. pnpm global `node_modules` (for OpenClaw bundled installs)
4. Relative to the running script

## Requirements

- **Python 3.9+**
- **PyYAML** (`pip install pyyaml`)
- No other external dependencies for core functionality
- For remote access: `cloudflared`, `ngrok`, or `localtunnel` (optional)

## Project Structure

```
natural-language-planner/
├── SKILL.md              # AI skill instructions
├── dashboard-daemon.py   # Standalone launcher (smart path resolution)
├── start-dashboard.sh    # Shell script launcher
├── scripts/
│   ├── __init__.py       # Package init
│   ├── __main__.py       # CLI entry point
│   ├── file_manager.py   # CRUD for projects and tasks
│   ├── config_manager.py # Settings management
│   ├── index_manager.py  # Search and lookup
│   ├── dashboard_server.py # Local web server + auto-start
│   ├── tunnel.py         # Remote access via tunnels
│   ├── export.py         # Static HTML snapshot export
│   └── utils.py          # Shared utilities
├── templates/
│   ├── dashboard/        # HTML/CSS/JS for the dashboard
│   ├── project_template.md
│   └── task_template.md
├── tests/                # Unit tests
└── examples/             # Sample data and conversations
```

## Troubleshooting

**"Skill not found"**
- Verify the skill directory exists: `ls ~/.openclaw/skills/natural-language-planner`
- Or set the path explicitly: `export NLP_SKILL_PATH=/path/to/natural-language-planner`

**"Port 8080 is unavailable"**
- Something else is using the port. Find it: `lsof -i :8080` (Linux/macOS) or `netstat -ano | findstr :8080` (Windows)
- Kill the process and retry, or change the port in config

**"Dashboard not responding"**
- Check the log: `tail -f /tmp/nlplanner-dashboard.log`
- Verify the workspace has data: `ls <workspace>/projects/`

**"No workspace specified"**
- Pass the workspace path: `python -m scripts dashboard ~/nlplanner`
- Or run `python -m scripts init ~/nlplanner` to create one

## Contributing

Contributions are welcome! Here's how:

1. **Fork** this repository
2. Create a **feature branch** (`git checkout -b feature/my-idea`)
3. Make your changes and add tests
4. Submit a **pull request** with a clear description

### Development

```bash
# Run tests
python -m pytest tests/ -v

# Start dashboard in development
python -m scripts dashboard ~/nlplanner

# Start a tunnel for remote access
python -m scripts tunnel ~/nlplanner

# Export a static snapshot
python -m scripts export ~/nlplanner --output ./docs
```

### Areas for contribution

- Better natural date parsing
- Drag-and-drop in the Kanban board
- Import from Todoist / Notion / other tools
- Authentication for tunneled dashboards
- Time tracking

## Design Principles

1. **Local-first** — your data never leaves your machine
2. **Human-readable** — everything is Markdown you can edit by hand
3. **Non-destructive** — archive, never delete
4. **Minimal dependencies** — stdlib where possible
5. **Cross-platform** — works on Windows, macOS, and Linux

## License

MIT — see [LICENSE.txt](LICENSE.txt)
````

## File: scripts/__init__.py
size: 781
sha: f9b6bb83bc6d38bb2042d6eb55d3983a4a6d6bdc
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/scripts/__init__.py

```text
"""
Natural Language Planner - Python utilities for task and project management.

This package provides core functionality for the Natural Language Planner skill,
including file operations, configuration management, search indexing, and a
local dashboard server.

Modules:
    utils           - Shared utilities (slug generation, YAML/Markdown parsing, etc.)
    config_manager  - User settings and configuration management
    file_manager    - Core CRUD operations for projects and tasks
    index_manager   - Fast search and lookup optimization
    dashboard_server - Local web server for the visual dashboard
    tunnel          - Cloudflare/ngrok tunnel integration for remote access
    export          - Static HTML snapshot export for deployment
"""

__version__ = "1.0.0"
```

## File: scripts/__main__.py
size: 9464
sha: 8fbaab431211e8e1427f0f0a64d66d97d3852927
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/scripts/__main__.py

```text
"""
CLI entry point for the Natural Language Planner.

Usage:
    python -m scripts <command> [arguments]

Commands:
    init <workspace_path>       Initialise a new workspace
    dashboard [--port PORT]     Start the dashboard server
    list-tasks [--project ID]   List all tasks
    list-projects               List all projects
    stats                       Show summary statistics
    search <query>              Search tasks
    rebuild-index               Rebuild the search index
    tunnel [workspace_path]     Start a tunnel for remote dashboard access
    export [--output DIR]       Export dashboard as a static HTML snapshot
"""

import sys
import argparse
import json

from .utils import setup_logging
from .file_manager import init_workspace, list_tasks, list_projects
from .config_manager import load_config, set_workspace_path
from .index_manager import rebuild_index, search_tasks, get_stats
from .dashboard_server import start_dashboard, ensure_dashboard, get_dashboard_url, get_dashboard_port
from .tunnel import start_tunnel, stop_tunnel, get_tunnel_url, detect_tunnel_tool, get_install_instructions
from .export import export_dashboard

def main() -> None:
    setup_logging()

    parser = argparse.ArgumentParser(
        prog="python -m scripts",
        description="Natural Language Planner — CLI",
    )
    sub = parser.add_subparsers(dest="command", help="Available commands")

    # init
    p_init = sub.add_parser("init", help="Initialise a new workspace")
    p_init.add_argument("workspace_path", help="Directory for planner data")

    # dashboard
    p_dash = sub.add_parser("dashboard", help="Start the dashboard server")
    p_dash.add_argument("--port", type=int, default=None, help="Port (default: 8080)")
    p_dash.add_argument("--network", action="store_true", help="Bind to all interfaces (0.0.0.0)")
    p_dash.add_argument(
        "--no-strict-port", dest="strict_port", action="store_false",
        help="Allow fallback to next free port if requested port is busy",
    )
    p_dash.add_argument("workspace_path", nargs="?", default=None, help="Workspace directory")

    # list-tasks
    p_lt = sub.add_parser("list-tasks", help="List tasks")
    p_lt.add_argument("--project", default=None, help="Filter by project ID")
    p_lt.add_argument("--status", default=None, help="Filter by status")
    p_lt.add_argument("workspace_path", nargs="?", default=None, help="Workspace directory")

    # list-projects
    p_lp = sub.add_parser("list-projects", help="List projects")
    p_lp.add_argument("workspace_path", nargs="?", default=None, help="Workspace directory")

    # stats
    p_st = sub.add_parser("stats", help="Show summary statistics")
    p_st.add_argument("workspace_path", nargs="?", default=None, help="Workspace directory")

    # search
    p_se = sub.add_parser("search", help="Search tasks")
    p_se.add_argument("query", help="Search query")
    p_se.add_argument("workspace_path", nargs="?", default=None, help="Workspace directory")

    # rebuild-index
    p_ri = sub.add_parser("rebuild-index", help="Rebuild the search index")
    p_ri.add_argument("workspace_path", nargs="?", default=None, help="Workspace directory")

    # tunnel
    p_tn = sub.add_parser("tunnel", help="Start a tunnel for remote dashboard access")
    p_tn.add_argument("--tool", choices=["cloudflared", "ngrok", "lt"], default=None,
                       help="Tunnel tool to use (default: auto-detect)")
    p_tn.add_argument("workspace_path", nargs="?", default=None, help="Workspace directory")

    # export
    p_ex = sub.add_parser("export", help="Export dashboard as static HTML snapshot")
    p_ex.add_argument("--output", default=None, help="Output directory (default: <workspace>/.nlplanner/export/)")
    p_ex.add_argument("workspace_path", nargs="?", default=None, help="Workspace directory")

    args = parser.parse_args()

    if not args.command:
        parser.print_help()
        sys.exit(1)

    # ── Dispatch ────────────────────────────────────────────

    if args.command == "init":
        path = args.workspace_path
        ok = init_workspace(path)
        if ok:
            print(f"Workspace initialised at: {path}")
        else:
            print("Failed to initialise workspace.", file=sys.stderr)
            sys.exit(1)

    elif args.command == "dashboard":
        _ensure_workspace(args)
        allow_network = getattr(args, "network", False)
        strict_port = getattr(args, "strict_port", True)
        try:
            url = start_dashboard(
                port=args.port,
                allow_network=allow_network or None,
                strict_port=strict_port,
            )
        except RuntimeError as e:
            print(f"ERROR: {e}", file=sys.stderr)
            sys.exit(1)
        if url:
            print(f"Dashboard running at {url}")
            print("Press Ctrl+C to stop.")
            try:
                import time
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                print("\nStopping dashboard.")
        else:
            print("Failed to start dashboard.", file=sys.stderr)
            sys.exit(1)

    elif args.command == "list-tasks":
        _ensure_workspace(args)
        filters = {}
        if args.status:
            filters["status"] = args.status
        tasks = list_tasks(filter_by=filters or None, project_id=args.project)
        if not tasks:
            print("No tasks found.")
        for t in tasks:
            status = t.get("status", "?")
            priority = t.get("priority", "?")
            due = t.get("due", "")
            due_str = f"  due {due}" if due else ""
            print(f"  [{status}] {t.get('id', '?')}  {t.get('title', '?')}  ({priority}){due_str}")

    elif args.command == "list-projects":
        _ensure_workspace(args)
        projects = list_projects()
        if not projects:
            print("No projects found.")
        for p in projects:
            print(f"  {p.get('id', '?')}  —  {p.get('title', '?')}  [{p.get('status', '?')}]")

    elif args.command == "stats":
        _ensure_workspace(args)
        rebuild_index()
        s = get_stats()
        print(json.dumps(s, indent=2))

    elif args.command == "search":
        _ensure_workspace(args)
        rebuild_index()
        results = search_tasks(args.query)
        if not results:
            print("No results.")
        for t in results:
            print(f"  {t.get('id', '?')}  {t.get('title', '?')}  [{t.get('status', '?')}]")

    elif args.command == "rebuild-index":
        _ensure_workspace(args)
        rebuild_index()
        print("Index rebuilt.")

    elif args.command == "tunnel":
        _ensure_workspace(args)

        # Ensure the dashboard is running first
        dash_url = ensure_dashboard()
        if not dash_url:
            print("Failed to start dashboard. Cannot create tunnel.", file=sys.stderr)
            sys.exit(1)

        port = get_dashboard_port()
        print(f"Dashboard running at {dash_url}")

        # Check if a tool is available
        tool = getattr(args, "tool", None) or detect_tunnel_tool()
        if not tool:
            print("\nNo tunnel tool found on your system.\n")
            print(get_install_instructions())
            sys.exit(1)

        print(f"Starting {tool} tunnel on port {port}...")
        tunnel_url = start_tunnel(port, tool=tool)
        if tunnel_url:
            print(f"\nPublic URL: {tunnel_url}")
            print("\nAnyone with this URL can access your dashboard.")
            print("WARNING: The dashboard has no authentication — share this URL carefully.")
            print("Press Ctrl+C to stop the tunnel.")
            try:
                import time
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                print("\nStopping tunnel...")
                stop_tunnel()
                print("Tunnel stopped.")
        else:
            print("Failed to start tunnel.", file=sys.stderr)
            sys.exit(1)

    elif args.command == "export":
        _ensure_workspace(args)
        output_dir = getattr(args, "output", None)
        path = export_dashboard(output_dir=output_dir)
        if path:
            print(f"Dashboard exported to: {path}")
            print("Open this file in a browser, or deploy it to any static hosting service.")
        else:
            print("Failed to export dashboard.", file=sys.stderr)
            sys.exit(1)

def _ensure_workspace(args: argparse.Namespace) -> None:
    """Point the config manager at the workspace, if provided."""
    ws = getattr(args, "workspace_path", None)
    if ws:
        # Persist resolved path into config so workspace_path matches this machine
        # (avoids stale paths like /mnt/... when testing a synced copy on Windows).
        if not set_workspace_path(ws):
            print(f"Failed to use workspace: {ws}", file=sys.stderr)
            sys.exit(1)
    else:
        # Try loading existing config to find workspace path
        config = load_config()
        if not config.get("workspace_path"):
            print(
                "No workspace specified. Either pass a path or run 'init' first.",
                file=sys.stderr,
            )
            sys.exit(1)

if __name__ == "__main__":
    main()
```

## File: scripts/config_manager.py
size: 14481
sha: dc6a37a3cca6473d5426bdae313122034a1460d6
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/scripts/config_manager.py

```text
"""
Configuration management for the Natural Language Planner.

Handles loading, saving, and accessing user settings stored in
.nlplanner/config.json within the workspace directory.
"""

import json
import logging
import os
import shutil
import subprocess
from pathlib import Path
from typing import Any, Optional

from .utils import ensure_directory, safe_read_file, safe_write_file

logger = logging.getLogger("nlplanner.config")

# Default configuration values
DEFAULT_CONFIG: dict[str, Any] = {
    "version": "1.0.0",
    "workspace_path": "",
    "settings": {
        "checkin_frequency_hours": 24,
        "reminder_style": "casual-checkin",
        "reminder_proactivity": "proactive",
        "auto_archive_completed_days": 30,
        "default_priority": "medium",
        "dashboard_port": 8080,
        "dashboard_auto_start": True,
        "dashboard_allow_network": False,
        "enable_notifications": False,
    },
    "preferences": {
        "default_project": "inbox",
        "task_id_format": "task-{counter:03d}",
        "project_id_format": "{slug}",
    },
}

# Module-level cached config path
_config_path: Optional[Path] = None

def _get_config_path(workspace_path: Optional[str] = None) -> Path:
    """
    Resolve the path to config.json.

    Args:
        workspace_path: Explicit workspace path. If None, uses cached or default.

    Returns:
        Path to the config.json file.
    """
    global _config_path

    if workspace_path:
        p = Path(workspace_path).expanduser().resolve()
        _config_path = p / ".nlplanner" / "config.json"
    elif _config_path is None:
        # Fallback: look for a config in the current directory or home
        _config_path = Path.home() / "nlplanner" / ".nlplanner" / "config.json"

    return _config_path

def set_config_path(workspace_path: str) -> None:
    """
    Set the workspace path used by the config manager.

    Call this early — before any other config operations — to point
    the planner at the correct workspace directory.

    Args:
        workspace_path: Absolute or ~-relative path to the workspace root.
    """
    _get_config_path(workspace_path)
    logger.info("Config path set to %s", _config_path)

def load_config(workspace_path: Optional[str] = None) -> dict[str, Any]:
    """
    Load the configuration file.

    If the file doesn't exist, returns a copy of DEFAULT_CONFIG.

    Args:
        workspace_path: Optional explicit workspace path.

    Returns:
        Configuration dictionary.

    Example:
        >>> config = load_config("/home/user/nlplanner")
        >>> config["settings"]["dashboard_port"]
        8080
    """
    path = _get_config_path(workspace_path)

    if not path.exists():
        logger.info("No config file found at %s — using defaults.", path)
        return _deep_copy_config(DEFAULT_CONFIG)

    raw = safe_read_file(path)
    if raw is None:
        logger.warning("Could not read config — using defaults.")
        return _deep_copy_config(DEFAULT_CONFIG)

    try:
        config = json.loads(raw)
        # Merge with defaults so new keys are always present
        merged = _merge_config(DEFAULT_CONFIG, config)
        return merged
    except json.JSONDecodeError as e:
        logger.error("Invalid JSON in config file: %s", e)
        return _deep_copy_config(DEFAULT_CONFIG)

def save_config(config: dict[str, Any], workspace_path: Optional[str] = None) -> bool:
    """
    Persist the configuration dictionary to disk.

    Args:
        config: The configuration dictionary to save.
        workspace_path: Optional explicit workspace path.

    Returns:
        True if saved successfully, False otherwise.
    """
    path = _get_config_path(workspace_path)
    ensure_directory(path.parent)

    try:
        content = json.dumps(config, indent=2, ensure_ascii=False)
        return safe_write_file(path, content)
    except (TypeError, ValueError) as e:
        logger.error("Failed to serialize config: %s", e)
        return False

def get_workspace_path() -> str:
    """
    Return the configured workspace path.

    Returns:
        The workspace root directory path as a string.
    """
    config = load_config()
    return config.get("workspace_path", "")

def set_workspace_path(path: str) -> bool:
    """
    Update the workspace path in the configuration.

    Also updates the internal config path pointer so subsequent
    operations use the new workspace.

    Args:
        path: New workspace root directory path.

    Returns:
        True if the config was saved successfully.
    """
    resolved = str(Path(path).expanduser().resolve())
    set_config_path(resolved)
    config = load_config(resolved)
    config["workspace_path"] = resolved
    return save_config(config, resolved)

def get_setting(key: str) -> Any:
    """
    Get a single setting value by key.

    Args:
        key: The setting name (e.g., 'dashboard_port').

    Returns:
        The setting value, or None if not found.
    """
    config = load_config()
    return config.get("settings", {}).get(key)

def set_setting(key: str, value: Any) -> bool:
    """
    Update a single setting value.

    Args:
        key: The setting name.
        value: The new value.

    Returns:
        True if saved successfully.
    """
    config = load_config()
    config.setdefault("settings", {})[key] = value
    return save_config(config)

def get_checkin_frequency() -> int:
    """
    Get the check-in frequency in hours.

    Returns:
        Number of hours between proactive check-ins.
    """
    return get_setting("checkin_frequency_hours") or 24

def set_checkin_frequency(hours: int) -> bool:
    """
    Set the check-in frequency.

    Args:
        hours: Number of hours between check-ins (minimum 1).

    Returns:
        True if saved successfully.
    """
    hours = max(1, hours)
    return set_setting("checkin_frequency_hours", hours)

def get_reminder_style() -> str:
    """
    Get the configured reminder style.

    Returns:
        One of:
        - productivity-bro
        - casual-checkin
        - strict-coach
        - completion-tracker
    """
    style = str(get_setting("reminder_style") or "casual-checkin").strip()
    allowed = {
        "productivity-bro",
        "casual-checkin",
        "strict-coach",
        "completion-tracker",
    }
    return style if style in allowed else "casual-checkin"

def set_reminder_style(style: str) -> bool:
    """
    Set the reminder style.

    Args:
        style: One of:
            - productivity-bro
            - casual-checkin
            - strict-coach
            - completion-tracker

    Returns:
        True if saved successfully.
    """
    style = str(style).strip()
    allowed = {
        "productivity-bro",
        "casual-checkin",
        "strict-coach",
        "completion-tracker",
    }
    if style not in allowed:
        logger.warning("Invalid reminder style '%s'; keeping existing value.", style)
        return False
    return set_setting("reminder_style", style)

def get_reminder_proactivity() -> str:
    """
    Get reminder proactivity mode.

    Returns:
        "proactive" or "on-request".
    """
    mode = str(get_setting("reminder_proactivity") or "proactive").strip()
    return mode if mode in {"proactive", "on-request"} else "proactive"

def set_reminder_proactivity(mode: str) -> bool:
    """
    Set reminder proactivity mode.

    Args:
        mode: "proactive" or "on-request".

    Returns:
        True if saved successfully.
    """
    mode = str(mode).strip()
    if mode not in {"proactive", "on-request"}:
        logger.warning(
            "Invalid reminder proactivity mode '%s'; keeping existing value.",
            mode,
        )
        return False
    return set_setting("reminder_proactivity", mode)

def get_preference(key: str) -> Any:
    """
    Get a single preference value by key.

    Args:
        key: The preference name (e.g., 'default_project').

    Returns:
        The preference value, or None if not found.
    """
    config = load_config()
    return config.get("preferences", {}).get(key)

# ── Skill root resolution ──────────────────────────────────────────

_skill_root_cache: Optional[Path] = None

_SKILL_MARKER_FILES = ("SKILL.md", "scripts", "templates")

def _is_skill_root(path: Path) -> bool:
    """Return True if *path* looks like the natural-language-planner skill root."""
    return all((path / marker).exists() for marker in _SKILL_MARKER_FILES)

def clear_skill_root_cache() -> None:
    """Clear cached skill root so the next lookup re-detects locations."""
    global _skill_root_cache
    _skill_root_cache = None

def _pnpm_global_root() -> Optional[Path]:
    """Ask pnpm for the global modules root, if available."""
    pnpm = shutil.which("pnpm")
    if not pnpm:
        return None
    try:
        result = subprocess.run(
            [pnpm, "root", "-g"],
            capture_output=True, text=True, timeout=5,
        )
        if result.returncode == 0 and result.stdout.strip():
            return Path(result.stdout.strip())
    except (OSError, subprocess.TimeoutExpired):
        pass
    return None

def _npm_global_root() -> Optional[Path]:
    """Ask npm for the global modules root, if available."""
    npm = shutil.which("npm")
    if not npm:
        return None
    try:
        result = subprocess.run(
            [npm, "root", "-g"],
            capture_output=True,
            text=True,
            timeout=5,
        )
        if result.returncode == 0 and result.stdout.strip():
            return Path(result.stdout.strip())
    except (OSError, subprocess.TimeoutExpired):
        pass
    return None

def get_skill_root() -> Path:
    """
    Locate the natural-language-planner skill directory.

    Resolution order:

    1. ``NLP_SKILL_PATH`` environment variable (explicit override).
    2. ``~/.openclaw/skills/natural-language-planner`` (local checkout).
    3. Skill bundled with an installed OpenClaw package.
    4. Current working directory.

    Returns:
        Resolved ``Path`` to the skill root directory.

    Raises:
        FileNotFoundError: If none of the candidate locations contain the skill.
    """
    global _skill_root_cache
    if _skill_root_cache is not None:
        return _skill_root_cache

    # 1. Explicit env var (NLP_SKILL_PATH takes priority, SKILL_PATH as alias)
    env = os.environ.get("NLP_SKILL_PATH") or os.environ.get("SKILL_PATH")
    if env:
        p = Path(env).expanduser().resolve()
        if _is_skill_root(p):
            _skill_root_cache = p
            logger.info("Skill root (from env): %s", p)
            return p
        raise FileNotFoundError(
            f"Skill path env var is set to '{env}' but that directory does "
            "not contain the expected skill files (SKILL.md, scripts/, templates/)."
        )

    # 2. Preferred local git checkout path
    local_checkout = Path.home() / ".openclaw" / "skills" / "natural-language-planner"
    if _is_skill_root(local_checkout):
        # Keep the configured local path as-is to avoid symlink canonicalization
        # into global package paths (which obscures source-of-truth identity).
        _skill_root_cache = local_checkout
        logger.info("Skill root (local checkout): %s", _skill_root_cache)
        return _skill_root_cache

    # 3. Installed OpenClaw package paths (npm/pnpm package layouts)
    installed_candidates: list[Path] = []

    # First, try package-relative location when this module is imported from OpenClaw.
    # .../openclaw/skills/natural-language-planner/scripts/config_manager.py
    #                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    module_path = Path(__file__).resolve()
    if len(module_path.parents) >= 4:
        module_openclaw_dir = module_path.parents[3]
        installed_candidates.append(
            module_openclaw_dir / "skills" / "natural-language-planner"
        )

    npm_root = _npm_global_root()
    if npm_root:
        installed_candidates.extend(
            [
                npm_root / "natural-language-planner",
                npm_root / "openclaw" / "skills" / "natural-language-planner",
            ]
        )

    pnpm_root = _pnpm_global_root()
    if pnpm_root:
        installed_candidates.extend(
            [
                pnpm_root / "natural-language-planner",
                pnpm_root / "openclaw" / "skills" / "natural-language-planner",
            ]
        )

    seen: set[Path] = set()
    for candidate in installed_candidates:
        resolved = candidate.resolve()
        if resolved in seen:
            continue
        seen.add(resolved)
        if _is_skill_root(resolved):
            _skill_root_cache = resolved
            logger.info("Skill root (installed package): %s", resolved)
            return resolved

    # 4. Current working directory
    cwd = Path.cwd().resolve()
    if _is_skill_root(cwd):
        _skill_root_cache = cwd
        logger.info("Skill root (cwd): %s", cwd)
        return cwd

    raise FileNotFoundError(
        "Could not locate the natural-language-planner skill.\n"
        "Searched:\n"
        f"  - NLP_SKILL_PATH / SKILL_PATH env var (not set)\n"
        f"  - {local_checkout}\n"
        f"  - installed OpenClaw package candidates ({len(seen)} checked)\n"
        f"  - {cwd}\n"
        "Set NLP_SKILL_PATH (or SKILL_PATH) to the directory "
        "containing SKILL.md, scripts/, and templates/."
    )

# ── Internal helpers ────────────────────────────────────────────────

def _deep_copy_config(source: dict) -> dict:
    """Return a deep copy of a config dict via JSON round-trip."""
    return json.loads(json.dumps(source))

def _merge_config(defaults: dict, overrides: dict) -> dict:
    """
    Recursively merge *overrides* into *defaults*.

    Keys present in overrides take precedence; keys only in defaults
    are preserved so that newly added settings always appear.
    """
    merged = _deep_copy_config(defaults)
    for key, value in overrides.items():
        if key in merged and isinstance(merged[key], dict) and isinstance(value, dict):
            merged[key] = _merge_config(merged[key], value)
        else:
            merged[key] = value
    return merged
```

## File: scripts/dashboard_server.py
size: 21122
sha: a4ca0254142fa85872935a574d6d58f831100d79
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/scripts/dashboard_server.py

```text
"""
Local web server for the Natural Language Planner dashboard.

Serves the dashboard single-page app and provides a JSON API for
reading task/project data from the workspace.

Uses only the Python standard library (http.server) so there are no
external dependencies.  For production-style usage consider replacing
with FastAPI or similar, but this works great for local use.
"""

import json
import logging
import mimetypes
import socket
import threading
import time
from functools import partial
from http.server import HTTPServer, SimpleHTTPRequestHandler
from pathlib import Path
from typing import Any, Optional
from urllib.parse import urlparse, parse_qs, unquote

from .config_manager import (
    clear_skill_root_cache,
    get_setting,
    get_skill_root,
    load_config,
    set_setting,
)
from .file_manager import list_projects, list_tasks, get_project, get_task, get_today_tasks, set_today_tasks
from .index_manager import rebuild_index, get_stats, search_tasks, get_tasks_due_soon, get_overdue_tasks, get_tasks_needing_checkin

logger = logging.getLogger("nlplanner.dashboard")

_server: Optional[HTTPServer] = None
_thread: Optional[threading.Thread] = None
_started_at: float = 0.0

class DashboardHandler(SimpleHTTPRequestHandler):
    """
    HTTP request handler for the dashboard.

    Serves static files from the dashboard directory and handles
    /api/* routes for JSON data.
    """

    def __init__(self, *args, dashboard_dir: str = "", **kwargs):
        self._dashboard_dir = dashboard_dir
        super().__init__(*args, directory=dashboard_dir, **kwargs)

    def do_GET(self) -> None:
        """Route GET requests to the appropriate handler."""
        parsed = urlparse(self.path)
        path = parsed.path

        if path.startswith("/api/"):
            self._handle_api(path, parsed.query)
        else:
            # Serve static files from the dashboard directory
            super().do_GET()

    def do_POST(self) -> None:
        """Route POST requests to the appropriate handler."""
        parsed = urlparse(self.path)
        path = parsed.path

        if path == "/api/today":
            self._api_today_set()
        else:
            self._json_response({"error": "Not found"}, status=404)

    def _handle_api(self, path: str, query_string: str) -> None:
        """Dispatch API requests."""
        params = parse_qs(query_string)

        routes: dict[str, Any] = {
            "/api/stats": self._api_stats,
            "/api/projects": self._api_projects,
            "/api/tasks": self._api_tasks,
            "/api/search": self._api_search,
            "/api/due-soon": self._api_due_soon,
            "/api/overdue": self._api_overdue,
            "/api/today": self._api_today_get,
            "/api/needs-attention": self._api_needs_attention,
            "/api/health": self._api_health,
        }

        # Dynamic routes: /api/attachment/<project>/<file>, /api/project/<id>, /api/task/<id>
        if path.startswith("/api/attachment/"):
            parts = path.split("/api/attachment/")[1].strip("/").split("/", 1)
            if len(parts) == 2:
                self._api_serve_attachment(unquote(parts[0]), unquote(parts[1]))
            else:
                self._json_response({"error": "Bad attachment path"}, status=400)
            return
        if path.startswith("/api/project/"):
            project_id = path.split("/api/project/")[1].strip("/")
            self._api_single_project(project_id)
            return
        if path.startswith("/api/task/"):
            task_id = path.split("/api/task/")[1].strip("/")
            self._api_single_task(task_id)
            return

        handler = routes.get(path)
        if handler:
            handler(params)
        else:
            self._json_response({"error": "Not found"}, status=404)

    # ── API handlers ───────────────────────────────────────────

    def _api_health(self, params: dict) -> None:
        """Return server health status and uptime."""
        uptime = round(time.time() - _started_at, 1) if _started_at else 0
        self._json_response({
            "status": "ok",
            "uptime_seconds": uptime,
            "port": _server.server_address[1] if _server else None,
        })

    def _api_stats(self, params: dict) -> None:
        rebuild_index()
        self._json_response(get_stats())

    def _api_projects(self, params: dict) -> None:
        projects = list_projects()
        self._json_response(projects)

    def _api_tasks(self, params: dict) -> None:
        project = params.get("project", [None])[0]
        status = params.get("status", [None])[0]
        priority = params.get("priority", [None])[0]
        include_archived = params.get("include_archived", [""])[0].lower() in ("1", "true", "yes")

        filters: dict[str, Any] = {}
        if status:
            filters["status"] = status
        if priority:
            filters["priority"] = priority

        tasks = list_tasks(filter_by=filters if filters else None, project_id=project,
                           include_archived=include_archived)
        self._json_response(tasks)

    def _api_search(self, params: dict) -> None:
        query = params.get("q", [""])[0]
        if not query:
            self._json_response([])
            return
        rebuild_index()
        results = search_tasks(query)
        self._json_response(results)

    def _api_due_soon(self, params: dict) -> None:
        try:
            days = max(1, min(365, int(params.get("days", ["7"])[0])))
        except (ValueError, TypeError):
            days = 7
        rebuild_index()
        self._json_response(get_tasks_due_soon(days))

    def _api_overdue(self, params: dict) -> None:
        rebuild_index()
        self._json_response(get_overdue_tasks())

    def _api_needs_attention(self, params: dict) -> None:
        """Combine overdue tasks and stale check-in tasks into one list."""
        rebuild_index()
        overdue = get_overdue_tasks()
        stale = get_tasks_needing_checkin()
        seen = set()
        items = []
        for t in overdue:
            t["_attention_reason"] = f"Overdue by {t.get('_days_overdue', '?')} days"
            items.append(t)
            seen.add(t.get("id"))
        for t in stale:
            if t.get("id") not in seen:
                t["_attention_reason"] = "No check-in recently"
                items.append(t)
        self._json_response(items)

    def _api_single_project(self, project_id: str) -> None:
        project = get_project(project_id)
        if project:
            self._json_response(project)
        else:
            self._json_response({"error": "Project not found"}, status=404)

    def _api_single_task(self, task_id: str) -> None:
        task = get_task(task_id)
        if task:
            self._json_response(task)
        else:
            self._json_response({"error": "Task not found"}, status=404)

    def _api_today_get(self, params: dict) -> None:
        """Return the list of task IDs pinned to today's focus."""
        self._json_response({"task_ids": get_today_tasks()})

    def _api_today_set(self) -> None:
        """Set the list of task IDs for today's focus (POST with JSON body)."""
        try:
            content_length = int(self.headers.get("Content-Length", 0))
            body = self.rfile.read(content_length).decode("utf-8")
            data = json.loads(body)
        except (ValueError, json.JSONDecodeError) as e:
            self._json_response({"error": f"Invalid JSON: {e}"}, status=400)
            return

        task_ids = data.get("task_ids")
        if not isinstance(task_ids, list):
            self._json_response({"error": "task_ids must be a list"}, status=400)
            return

        ok = set_today_tasks([str(tid) for tid in task_ids])
        if ok:
            self._json_response({"task_ids": get_today_tasks()})
        else:
            self._json_response({"error": "Failed to save"}, status=500)

    def _api_serve_attachment(self, project_id: str, filename: str) -> None:
        """Serve a file from project attachments or media directory."""
        config = load_config()
        ws = config.get("workspace_path", "")
        if not ws:
            self._json_response({"error": "Workspace not configured"}, status=500)
            return

        # Security: prevent path traversal in both project_id and filename
        safe_project = Path(project_id).name
        safe_name = Path(filename).name
        ws_root = Path(ws).resolve()

        # Check both locations (backwards compat + new media dir)
        paths_to_try = [
            (ws_root / "projects" / safe_project / "attachments" / safe_name).resolve(),
            (ws_root / "media" / safe_project / safe_name).resolve(),
        ]

        file_path = None
        for candidate in paths_to_try:
            # Ensure the resolved path is still within the workspace
            if not candidate.is_relative_to(ws_root):
                continue
            if candidate.is_file():
                file_path = candidate
                break

        if not file_path:
            self._json_response({"error": "Attachment not found"}, status=404)
            return

        content_type, _ = mimetypes.guess_type(str(file_path))
        content_type = content_type or "application/octet-stream"

        try:
            data = file_path.read_bytes()
            self.send_response(200)
            self.send_header("Content-Type", content_type)
            self.send_header("Content-Length", str(len(data)))
            self.send_header("Cache-Control", "public, max-age=10")
            self.end_headers()
            self.wfile.write(data)
        except OSError as e:
            logger.error("Failed to serve attachment %s: %s", file_path, e)
            self._json_response({"error": "Failed to read file"}, status=500)

    # ── Response helpers ───────────────────────────────────────

    def _json_response(self, data: Any, status: int = 200) -> None:
        """Send a JSON response."""
        body = json.dumps(data, default=str, ensure_ascii=False).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, format: str, *args: Any) -> None:
        """Redirect access logs to our logger instead of stderr."""
        logger.debug(format, *args)

# ── Internal helpers ──────────────────────────────────────────────

def _resolve_dashboard_dir() -> str:
    """
    Find the dashboard static files directory.

    Looks in the workspace .nlplanner/dashboard first, then falls back to
    the templates/dashboard shipped with the skill (located via
    :func:`get_skill_root`).
    """
    config = load_config()
    ws = config.get("workspace_path", "")

    if ws:
        ws_dashboard = Path(ws) / ".nlplanner" / "dashboard"
        if (ws_dashboard / "index.html").exists():
            return str(ws_dashboard)

    try:
        skill_root = get_skill_root()
        templates = skill_root / "templates" / "dashboard"
        if (templates / "index.html").exists():
            return str(templates)
    except FileNotFoundError:
        pass

    raise FileNotFoundError(
        "Dashboard static files not found. Ensure the templates/dashboard/ "
        "directory exists, run init_workspace() first, or set the "
        "NLP_SKILL_PATH environment variable."
    )

def _is_port_available(host: str, port: int) -> bool:
    """Check if a TCP port is available for binding."""
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.bind((host, port))
            return True
    except OSError:
        return False

def _find_available_port(host: str, start_port: int, max_attempts: int = 10) -> int:
    """
    Find an available port starting from start_port.

    Tries consecutive ports until one is available.

    Args:
        host: The host to bind to.
        start_port: Port to try first.
        max_attempts: How many consecutive ports to try.

    Returns:
        An available port number.

    Raises:
        OSError: If no port is available within the range.
    """
    for offset in range(max_attempts):
        port = start_port + offset
        if _is_port_available(host, port):
            return port
    raise OSError(
        f"No available port found in range {start_port}-{start_port + max_attempts - 1}"
    )

def _resolve_host() -> str:
    """Return the bind host based on configuration."""
    config = load_config()
    allow_network = config.get("settings", {}).get("dashboard_allow_network", False)
    return "0.0.0.0" if allow_network else "127.0.0.1"

def _get_lan_ip() -> str:
    """Best-effort detection of the machine's LAN IP address.

    Returns ``"127.0.0.1"`` if the address cannot be determined (e.g.
    no network interfaces are up).
    """
    try:
        # Open a UDP socket to an external address (nothing is actually sent)
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.connect(("8.8.8.8", 80))
            return s.getsockname()[0]
    except OSError:
        return "127.0.0.1"

# ── Public functions ──────────────────────────────────────────────

def start_dashboard(
    port: Optional[int] = None,
    allow_network: Optional[bool] = None,
    strict_port: bool = True,
) -> str:
    """
    Start the dashboard web server in a background thread.

    Args:
        port: Port number (default: from config or 8080).
        allow_network: If True, bind to 0.0.0.0 (all interfaces).
                       If None, reads from config.
        strict_port: If True (default), fail when the requested port is
                     unavailable instead of falling back to the next free
                     port.  Set to False to allow automatic fallback.

    Returns:
        The dashboard URL, or empty string on failure.

    Raises:
        RuntimeError: If *strict_port* is True and the port is unavailable.

    Example:
        >>> url = start_dashboard()
        >>> print(url)
        http://localhost:8080
    """
    global _server, _thread, _started_at

    # Always re-detect skill root on startup to avoid stale module-level cache.
    clear_skill_root_cache()

    if _server is not None:
        logger.info("Dashboard is already running.")
        return get_dashboard_url()

    config = load_config()

    if port is None:
        port = config.get("settings", {}).get("dashboard_port", 8080)

    if allow_network is None:
        allow_network = config.get("settings", {}).get("dashboard_allow_network", False)

    host = "0.0.0.0" if allow_network else "127.0.0.1"
    try:
        dashboard_dir = _resolve_dashboard_dir()
    except FileNotFoundError as e:
        logger.error("%s", e)
        return ""
    handler = partial(DashboardHandler, dashboard_dir=dashboard_dir)

    if strict_port:
        if not _is_port_available(host, port):
            raise RuntimeError(
                f"Port {port} is unavailable (strict_port=True). "
                f"Free the port or set strict_port=False to allow fallback.\n"
                f"  Check what is using it: lsof -i :{port}  or  "
                f"ss -tlnp sport = :{port}"
            )
        actual_port = port
    else:
        try:
            actual_port = _find_available_port(host, port)
            if actual_port != port:
                logger.warning(
                    "Port %d is occupied, falling back to port %d.",
                    port, actual_port,
                )
        except OSError as e:
            logger.error("Could not find an available port: %s", e)
            return ""

    try:
        _server = HTTPServer((host, actual_port), handler)
    except OSError as e:
        logger.error("Could not start dashboard on port %d: %s", actual_port, e)
        return ""

    _started_at = time.time()
    _thread = threading.Thread(target=_server.serve_forever, daemon=True)
    _thread.start()

    if allow_network:
        lan_ip = _get_lan_ip()
        url = f"http://{lan_ip}:{actual_port}"
    else:
        url = f"http://localhost:{actual_port}"
    logger.info(
        "Dashboard started at %s (serving from %s, strict_port=%s)",
        url, dashboard_dir, strict_port,
    )

    if actual_port != port:
        set_setting("dashboard_port", actual_port)

    return url

def ensure_dashboard(
    port: Optional[int] = None,
    allow_network: Optional[bool] = None,
    strict_port: bool = True,
) -> str:
    """
    Ensure the dashboard is running and healthy.

    This is the recommended function for the agent to call. It:
    1. Returns the existing URL if the server is already running.
    2. Starts a new server if not running.
    3. Verifies the server is responsive.

    Args:
        port: Optional port override.
        allow_network: If True, bind to all interfaces (``0.0.0.0``)
                       so the dashboard is reachable from other devices
                       on the LAN.  If None, reads from config.
        strict_port: If True (default), fail when the port is unavailable.
                     If False, fall back to the next free port.

    Returns:
        The dashboard URL, or empty string on failure.

    Example:
        >>> url = ensure_dashboard()
        >>> print(url)
        http://localhost:8080
    """
    if is_running():
        return get_dashboard_url()

    url = start_dashboard(port=port, allow_network=allow_network, strict_port=strict_port)
    if not url:
        return ""

    # Brief pause to let the server thread start accepting connections
    time.sleep(0.1)

    if is_running():
        logger.info("Dashboard ensured at %s", url)
        return url

    logger.warning("Dashboard started but may not be healthy.")
    return url

def stop_dashboard() -> None:
    """Stop the running dashboard server and release its port."""
    global _server, _thread, _started_at

    if _server is None:
        logger.info("Dashboard is not running.")
        return

    _server.shutdown()       # Stop the serve_forever() loop
    _server.server_close()   # Close the socket — releases the port immediately
    _server = None
    _thread = None
    _started_at = 0.0
    logger.info("Dashboard stopped.")

def restart_dashboard(
    allow_network: Optional[bool] = None,
    strict_port: bool = True,
) -> str:
    """
    Stop and restart the dashboard server on the **same port**.

    Use this after skill updates that change Python scripts, dashboard
    templates, or any other server-side code.  It fully tears down the
    existing server (including closing the socket so the port is freed
    immediately) and starts a fresh one, re-resolving the dashboard
    directory and reloading configuration.

    Args:
        allow_network: If True, bind to all interfaces (``0.0.0.0``).
                       If None, reads from config.
        strict_port: If True (default), fail when the port is unavailable.

    Returns:
        The new dashboard URL, or empty string on failure.

    Example:
        >>> url = restart_dashboard()
        >>> print(url)
        http://localhost:8080
    """
    # Ensure restart does not reuse a stale cached skill root.
    clear_skill_root_cache()
    port = get_dashboard_port() or None
    stop_dashboard()
    return ensure_dashboard(port=port, allow_network=allow_network, strict_port=strict_port)

def get_dashboard_url() -> str:
    """
    Get the URL of the running dashboard.

    When the server is bound to all interfaces (``0.0.0.0``), returns
    the LAN IP so the URL is directly usable from other devices on the
    network.  When bound to ``127.0.0.1``, returns ``localhost``.

    Returns:
        The dashboard URL, or an empty string if not running.
    """
    if _server is None:
        return ""
    host, port = _server.server_address
    if host == "0.0.0.0":
        return f"http://{_get_lan_ip()}:{port}"
    return f"http://localhost:{port}"

def get_dashboard_port() -> int:
    """
    Get the port of the running dashboard.

    Returns:
        The port number, or 0 if not running.
    """
    if _server is None:
        return 0
    return _server.server_address[1]

def is_running() -> bool:
    """Check whether the dashboard server is currently running."""
    return _server is not None

def get_uptime() -> float:
    """
    Get dashboard uptime in seconds.

    Returns:
        Uptime in seconds, or 0.0 if not running.
    """
    if not is_running() or _started_at == 0.0:
        return 0.0
    return time.time() - _started_at
```

## File: scripts/export.py
size: 7998
sha: 1928c99d51898ac9c2154eab48b8bfcad14bc5b1
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/scripts/export.py

```text
"""
Static HTML export for the Natural Language Planner dashboard.

Generates a single self-contained index.html file with all task/project
data inlined as JSON, plus embedded CSS and JS. The exported file can
be opened directly in a browser or deployed to any static hosting service
(GitHub Pages, Netlify, Vercel, etc.).

Note: The export is a point-in-time snapshot — it does not auto-update.
"""

import json
import logging
from pathlib import Path
from typing import Optional

from .config_manager import load_config
from .file_manager import list_projects, list_tasks
from .index_manager import rebuild_index, get_stats
from .utils import ensure_directory

logger = logging.getLogger("nlplanner.export")

def export_dashboard(output_dir: Optional[str] = None) -> Optional[str]:
    """
    Export the dashboard as a self-contained static HTML file.

    Reads all current task and project data, embeds it as JSON in the
    dashboard HTML, and writes a single file that works without a server.

    Args:
        output_dir: Directory to write the export to. Defaults to
                    <workspace>/.nlplanner/export/

    Returns:
        Path to the exported index.html, or None on failure.

    Example:
        >>> path = export_dashboard()
        >>> print(path)
        '/home/user/nlplanner/.nlplanner/export/index.html'
    """
    config = load_config()
    ws = config.get("workspace_path", "")

    if not ws:
        logger.error("Workspace not configured. Run init first.")
        return None

    # Resolve output directory
    if output_dir:
        out = Path(output_dir).expanduser().resolve()
    else:
        out = Path(ws) / ".nlplanner" / "export"

    ensure_directory(out)

    # Gather data
    rebuild_index()
    projects = list_projects()
    tasks = list_tasks()
    stats = get_stats()

    data_payload = {
        "projects": projects,
        "tasks": tasks,
        "stats": stats,
        "exported_at": __import__("datetime").datetime.now().isoformat(timespec="seconds"),
    }

    # Read the template files
    templates_dir = Path(__file__).parent.parent / "templates" / "dashboard"
    html_content = _read_file(templates_dir / "index.html")
    css_content = _read_file(templates_dir / "styles.css")
    js_content = _read_file(templates_dir / "app.js")

    if not all([html_content, css_content, js_content]):
        logger.error("Could not read dashboard template files.")
        return None

    # Build the static JS that injects data instead of fetching from API
    static_js = _build_static_js(js_content, data_payload)

    # Inline CSS and JS into the HTML
    export_html = _inline_assets(html_content, css_content, static_js)

    # Write the export
    output_path = out / "index.html"
    try:
        output_path.write_text(export_html, encoding="utf-8")
    except OSError as e:
        logger.error("Failed to write export: %s", e)
        return None

    logger.info("Dashboard exported to %s", output_path)
    return str(output_path)

def _read_file(path: Path) -> Optional[str]:
    """Read a text file, returning None on error."""
    try:
        return path.read_text(encoding="utf-8")
    except OSError as e:
        logger.error("Could not read %s: %s", path, e)
        return None

def _escape_json_for_html(json_str: str) -> str:
    """Escape a JSON string so it is safe to embed inside an HTML <script> block.

    Prevents ``</script>`` and ``<!--`` sequences in the data from breaking
    out of the surrounding ``<script>`` tag.  These replacements produce
    strings that are still valid JavaScript string literals.
    """
    return json_str.replace("<", "\<").replace(">", "\>").replace("&", "\&")

def _build_static_js(original_js: str, data: dict) -> str:
    """
    Transform the dashboard JS for static/offline use.

    Replaces the API fetch logic with a pre-loaded data blob so the
    dashboard works as a standalone file without a running server.
    """
    data_json = _escape_json_for_html(
        json.dumps(data, default=str, ensure_ascii=False)
    )

    # Prepend the inlined data and override the api() and loadAll() functions
    static_preamble = f"""
// ── STATIC EXPORT: Data is inlined, no server needed ──────────
window.__NLP_STATIC_DATA__ = {data_json};
window.__NLP_STATIC_MODE__ = true;
"""

    # Patch: replace the api() function to return inlined data
    # and replace loadAll() to use the static data directly
    static_patch = """
// ── STATIC EXPORT: Patched loader ─────────────────────────────
(function() {
  var _origInit = null;
  var _checkInterval = setInterval(function() {
    // Wait for the app IIFE to set up, then patch
    if (window.__NLP_STATIC_MODE__) {
      clearInterval(_checkInterval);
    }
  }, 50);
})();
"""

    # Instead of patching inline, we'll wrap: let the original JS load,
    # but override the fetch-based `api` function at the window level
    # so it returns static data.  The app.js uses a local `api()` inside
    # the IIFE, so we need a different approach: inject a <script> block
    # before app.js that sets window.fetch to return our data.

    fetch_override = f"""
// ── STATIC EXPORT: Override fetch for offline use ─────────────
(function() {{
  var DATA = {data_json};
  var originalFetch = window.fetch;
  window.fetch = function(url, opts) {{
    if (typeof url !== 'string') return originalFetch(url, opts);
    // Parse the pathname
    var a = document.createElement('a');
    a.href = url;
    var path = a.pathname;
    if (path === '/api/stats') return fakeResponse(DATA.stats);
    if (path === '/api/projects') return fakeResponse(DATA.projects);
    if (path === '/api/tasks') return fakeResponse(DATA.tasks);
    if (path === '/api/health') return fakeResponse({{status:'ok',static:true}});
    if (path.indexOf('/api/search') === 0) {{
      var q = (new URL(url, location.origin)).searchParams.get('q') || '';
      q = q.toLowerCase();
      var results = DATA.tasks.filter(function(t) {{
        var s = ((t.title||'')+(t.project||'')+((t.tags||[]).join(' '))).toLowerCase();
        return s.indexOf(q) !== -1;
      }});
      return fakeResponse(results);
    }}
    if (path.indexOf('/api/task/') === 0) {{
      var tid = path.split('/api/task/')[1];
      var task = null;
      for (var i=0;i<DATA.tasks.length;i++) {{
        if (DATA.tasks[i].id===tid) {{ task = DATA.tasks[i]; break; }}
      }}
      return fakeResponse(task || {{error:'Not found'}});
    }}
    if (path.indexOf('/api/project/') === 0) {{
      var pid = path.split('/api/project/')[1];
      var proj = null;
      for (var j=0;j<DATA.projects.length;j++) {{
        if (DATA.projects[j].id===pid) {{ proj = DATA.projects[j]; break; }}
      }}
      return fakeResponse(proj || {{error:'Not found'}});
    }}
    // Fallback for other requests (attachments etc)
    return originalFetch(url, opts);
  }};
  function fakeResponse(data) {{
    return Promise.resolve(new Response(JSON.stringify(data), {{
      status: 200,
      headers: {{'Content-Type':'application/json'}}
    }}));
  }}
}})();
"""
    return fetch_override + "\n" + original_js

def _inline_assets(html: str, css: str, js: str) -> str:
    """
    Replace external CSS/JS references with inline <style> and <script> blocks.
    """
    # Replace the <link rel="stylesheet" href="styles.css" /> with inline CSS
    html = html.replace(
        '<link rel="stylesheet" href="styles.css" />',
        f"<style>\n{css}\n</style>",
    )

    # Replace <script src="app.js"></script> with inline JS
    html = html.replace(
        '<script src="app.js"></script>',
        f"<script>\n{js}\n</script>",
    )

    # Add a banner comment
    html = html.replace(
        "<title>NL Planner",
        "<!-- Static export — generated by Natural Language Planner -->\n  <title>NL Planner",
    )

    return html
```

## File: scripts/file_manager.py
size: 45705
sha: f858f4443c8e695f1e87ec48e97cfd2d0e97552b
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/scripts/file_manager.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/bparticle/natural-language-planner/blob/HEAD/scripts/file_manager.py

## File: scripts/index_manager.py
size: 12062
sha: 13012f72b895d9d2913a46f86d5120306e3d67e8
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/scripts/index_manager.py

```text
"""
Search and fast-lookup optimisation for the Natural Language Planner.

Builds an in-memory index from the markdown files so that queries,
due-date checks, and check-in lookups are fast even with many tasks.
"""

import json
import logging
import re
from datetime import date, datetime, timedelta
from pathlib import Path
from typing import Any, Optional

from .utils import parse_frontmatter, safe_read_file, safe_write_file, ensure_directory
from .config_manager import load_config

logger = logging.getLogger("nlplanner.index")

# In-memory index
_index: dict[str, Any] = {"tasks": {}, "projects": {}, "built_at": ""}

# ── Public API ─────────────────────────────────────────────────────

def rebuild_index() -> bool:
    """
    Rebuild the in-memory index by scanning all markdown files.

    Also persists the index to .nlplanner/index.json for faster cold starts.

    Returns:
        True if the index was built successfully.

    Example:
        >>> rebuild_index()
        True
        >>> len(search_tasks("backend"))
        3
    """
    root = _workspace_root()
    if root is None:
        return False

    global _index
    _index = {"tasks": {}, "projects": {}, "built_at": datetime.now().isoformat()}

    # Index projects
    projects_dir = root / "projects"
    if projects_dir.exists():
        for readme in projects_dir.glob("*/README.md"):
            raw = safe_read_file(readme)
            if raw is None:
                continue
            meta, body = parse_frontmatter(raw)
            pid = meta.get("id", readme.parent.name)
            _index["projects"][pid] = {
                **meta,
                "_body": body,
                "_path": str(readme),
            }

    # Index tasks
    for task_file in projects_dir.glob("*/tasks/task-*.md"):
        raw = safe_read_file(task_file)
        if raw is None:
            continue
        meta, body = parse_frontmatter(raw)
        tid = meta.get("id", task_file.stem)
        entry = {**meta, "_body": body, "_path": str(task_file)}
        _enrich_subtask_counts(entry, body)
        _index["tasks"][tid] = entry

    # Per-project nested archives (projects/<id>/archive/tasks/)
    for task_file in projects_dir.glob("*/archive/tasks/task-*.md"):
        raw = safe_read_file(task_file)
        if raw is None:
            continue
        meta, body = parse_frontmatter(raw)
        tid = meta.get("id", task_file.stem)
        entry = {**meta, "_body": body, "_path": str(task_file), "_archived": True}
        entry["status"] = "archived"
        _enrich_subtask_counts(entry, body)
        _index["tasks"][tid] = entry

    # Workspace archive (archive/<id>/tasks/) — last write wins over nested for duplicate IDs
    archive_dir = root / "archive"
    if archive_dir.exists():
        for task_file in archive_dir.glob("*/tasks/task-*.md"):
            raw = safe_read_file(task_file)
            if raw is None:
                continue
            meta, body = parse_frontmatter(raw)
            tid = meta.get("id", task_file.stem)
            entry = {**meta, "_body": body, "_path": str(task_file), "_archived": True}
            entry["status"] = "archived"
            _enrich_subtask_counts(entry, body)
            _index["tasks"][tid] = entry

    # Persist to disk
    _persist_index(root)

    task_count = len(_index["tasks"])
    project_count = len(_index["projects"])
    logger.info("Index rebuilt: %d tasks, %d projects.", task_count, project_count)
    return True

def search_tasks(query: str, include_archived: bool = False) -> list[dict[str, Any]]:
    """
    Search tasks by a text query.

    Matches against title, description body, tags, and project name.
    Case-insensitive substring matching.

    Args:
        query: Search string.
        include_archived: Whether to include archived tasks in results.

    Returns:
        List of matching task metadata dicts, sorted by relevance (title
        matches first, then body matches).

    Example:
        >>> results = search_tasks("deploy")
        >>> [r["title"] for r in results]
        ['Deploy to staging', 'Set up deploy pipeline']
    """
    _ensure_index()
    query_lower = query.lower()
    title_matches = []
    other_matches = []

    for tid, task in _index["tasks"].items():
        if not include_archived and task.get("_archived"):
            continue
        if task.get("status") == "archived" and not include_archived:
            continue

        title = (task.get("title") or "").lower()
        body = (task.get("_body") or "").lower()
        tags = " ".join(task.get("tags") or []).lower()
        project = (task.get("project") or "").lower()

        searchable = f"{title} {body} {tags} {project}"

        if query_lower in title:
            title_matches.append(_clean_task(task))
        elif query_lower in searchable:
            other_matches.append(_clean_task(task))

    return title_matches + other_matches

def get_tasks_due_soon(days: int = 7) -> list[dict[str, Any]]:
    """
    Return active tasks with due dates within the next N days.

    Args:
        days: Number of days to look ahead.

    Returns:
        List of task metadata dicts sorted by due date (soonest first).

    Example:
        >>> upcoming = get_tasks_due_soon(3)
        >>> [t["title"] for t in upcoming]
        ['Submit report', 'Review PR']
    """
    _ensure_index()
    today = date.today()
    horizon = today + timedelta(days=days)
    results = []

    for tid, task in _index["tasks"].items():
        if task.get("status") in ("done", "archived"):
            continue
        due_str = task.get("due", "")
        if not due_str:
            continue
        try:
            due_date = date.fromisoformat(str(due_str))
        except (ValueError, TypeError):
            continue

        if due_date <= horizon:
            entry = _clean_task(task)
            entry["_due_date"] = due_date.isoformat()
            entry["_overdue"] = due_date < today
            results.append(entry)

    results.sort(key=lambda t: t.get("_due_date", "9999"))
    return results

def get_tasks_needing_checkin() -> list[dict[str, Any]]:
    """
    Return active tasks that haven't been checked on recently.

    Uses the configured check-in frequency from config.json.

    Returns:
        List of task metadata dicts that need a check-in.

    Example:
        >>> stale = get_tasks_needing_checkin()
        >>> len(stale)
        2
    """
    _ensure_index()
    config = load_config()
    freq_hours = config.get("settings", {}).get("checkin_frequency_hours", 24)
    cutoff = datetime.now() - timedelta(hours=freq_hours)

    results = []
    for tid, task in _index["tasks"].items():
        status = task.get("status", "")
        if status in ("done", "archived"):
            continue

        last_checkin_str = task.get("last_checkin", "")
        if not last_checkin_str:
            results.append(_clean_task(task))
            continue

        try:
            last_checkin = datetime.fromisoformat(str(last_checkin_str))
        except (ValueError, TypeError):
            # If it's just a date string like "2026-02-09", parse that
            try:
                last_checkin = datetime.fromisoformat(str(last_checkin_str) + "T00:00:00")
            except (ValueError, TypeError):
                results.append(_clean_task(task))
                continue

        if last_checkin < cutoff:
            results.append(_clean_task(task))

    return results

def get_overdue_tasks() -> list[dict[str, Any]]:
    """
    Return all active tasks that are past their due date.

    Returns:
        List of overdue task metadata dicts.
    """
    _ensure_index()
    today = date.today()
    results = []

    for tid, task in _index["tasks"].items():
        if task.get("status") in ("done", "archived"):
            continue
        due_str = task.get("due", "")
        if not due_str:
            continue
        try:
            due_date = date.fromisoformat(str(due_str))
        except (ValueError, TypeError):
            continue
        if due_date < today:
            entry = _clean_task(task)
            entry["_days_overdue"] = (today - due_date).days
            results.append(entry)

    results.sort(key=lambda t: t.get("_days_overdue", 0), reverse=True)
    return results

def get_stats() -> dict[str, Any]:
    """
    Return summary statistics about all tasks and projects.

    Returns:
        Dictionary with counts by status, priority, overdue tasks, etc.
    """
    _ensure_index()
    today = date.today()

    stats: dict[str, Any] = {
        "total_tasks": 0,
        "by_status": {"todo": 0, "in-progress": 0, "done": 0, "archived": 0},
        "by_priority": {"low": 0, "medium": 0, "high": 0},
        "overdue": 0,
        "due_this_week": 0,
        "total_projects": len(_index["projects"]),
        "active_projects": 0,
    }

    for tid, task in _index["tasks"].items():
        stats["total_tasks"] += 1
        status = task.get("status", "todo")
        stats["by_status"][status] = stats["by_status"].get(status, 0) + 1

        priority = task.get("priority", "medium")
        if priority in stats["by_priority"]:
            stats["by_priority"][priority] += 1

        due_str = task.get("due", "")
        if due_str and status not in ("done", "archived"):
            try:
                due_date = date.fromisoformat(str(due_str))
                if due_date < today:
                    stats["overdue"] += 1
                elif due_date <= today + timedelta(days=7):
                    stats["due_this_week"] += 1
            except (ValueError, TypeError):
                pass

    for pid, proj in _index["projects"].items():
        if proj.get("status") == "active":
            stats["active_projects"] += 1

    return stats

# ── Internal helpers ───────────────────────────────────────────────

def _workspace_root() -> Optional[Path]:
    """Get workspace root from config."""
    config = load_config()
    ws = config.get("workspace_path", "")
    if not ws:
        logger.error("Workspace not configured.")
        return None
    return Path(ws)

def _ensure_index() -> None:
    """Rebuild the index if it hasn't been built yet."""
    if not _index["tasks"] and not _index["projects"]:
        rebuild_index()

def _clean_task(task: dict[str, Any]) -> dict[str, Any]:
    """Return a copy of task metadata without internal fields."""
    return {k: v for k, v in task.items() if not k.startswith("_")}

_SUBTASK_RE = re.compile(r"^- \[([ xX])\] (.+)$", re.MULTILINE)

def _enrich_subtask_counts(entry: dict[str, Any], body: str) -> None:
    """Parse subtasks from body and add count fields to the index entry."""
    if "## Subtasks" not in body:
        return
    section = body.split("## Subtasks")[1].split("\n## ")[0]
    items = _SUBTASK_RE.findall(section)
    if items:
        entry["subtask_count"] = len(items)
        entry["subtask_done"] = sum(1 for mark, _ in items if mark in ("x", "X"))

def _persist_index(root: Path) -> None:
    """Save the index to disk for faster cold starts."""
    index_path = root / ".nlplanner" / "index.json"
    ensure_directory(index_path.parent)

    # Strip body text to keep the index file small
    slim = {
        "built_at": _index["built_at"],
        "tasks": {
            tid: {k: v for k, v in t.items() if k != "_body"}
            for tid, t in _index["tasks"].items()
        },
        "projects": {
            pid: {k: v for k, v in p.items() if k != "_body"}
            for pid, p in _index["projects"].items()
        },
    }

    try:
        content = json.dumps(slim, indent=2, default=str, ensure_ascii=False)
        safe_write_file(index_path, content)
    except (TypeError, ValueError) as e:
        logger.warning("Failed to persist index: %s", e)
```

## File: scripts/tunnel.py
size: 8070
sha: 4ec7b6049da5cef1c7a8d2ae80b3c58fccc68cd6
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/scripts/tunnel.py

```text
"""
Tunnel integration for remote dashboard access.

Provides a simple way to expose the local dashboard to the internet
using Cloudflare Tunnel (cloudflared), ngrok, or localtunnel.

No external Python dependencies — these tools are invoked as subprocesses.
"""

import logging
import re
import shutil
import subprocess
import threading
import time
from typing import Optional

logger = logging.getLogger("nlplanner.tunnel")

_process: Optional[subprocess.Popen] = None
_tunnel_url: str = ""
_monitor_thread: Optional[threading.Thread] = None

# ── Tunnel tool detection ──────────────────────────────────────────

def detect_tunnel_tool() -> Optional[str]:
    """
    Detect which tunnel tool is available on the system.

    Checks in order of preference: cloudflared, ngrok, localtunnel (lt).

    Returns:
        The name of the available tool, or None if none found.

    Example:
        >>> tool = detect_tunnel_tool()
        >>> print(tool)
        'cloudflared'
    """
    for tool in ["cloudflared", "ngrok", "lt"]:
        if shutil.which(tool):
            logger.info("Tunnel tool found: %s", tool)
            return tool

    logger.info("No tunnel tool found on PATH.")
    return None

def get_install_instructions() -> str:
    """
    Return installation instructions for tunnel tools.

    Returns:
        A human-readable string with install commands for each platform.
    """
    return (
        "To expose your dashboard remotely, install one of these tools:\n"
        "\n"
        "  Cloudflare Tunnel (recommended, free, no account needed for quick tunnels):\n"
        "    Windows:  winget install cloudflare.cloudflared\n"
        "    macOS:    brew install cloudflared\n"
        "    Linux:    https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/\n"
        "\n"
        "  ngrok (free tier available, requires account):\n"
        "    All:      https://ngrok.com/download\n"
        "\n"
        "  localtunnel (npm, no account needed):\n"
        "    All:      npm install -g localtunnel\n"
    )

# ── Start / Stop ──────────────────────────────────────────────────

def start_tunnel(port: int, tool: Optional[str] = None) -> str:
    """
    Start a tunnel to expose a local port to the internet.

    Args:
        port: The local port to tunnel (e.g., 8080).
        tool: Which tool to use. If None, auto-detects.

    Returns:
        The public tunnel URL, or empty string on failure.

    Example:
        >>> url = start_tunnel(8080)
        >>> print(url)
        'https://random-name.trycloudflare.com'
    """
    global _process, _tunnel_url

    if _process is not None:
        logger.info("Tunnel is already running at %s", _tunnel_url)
        return _tunnel_url

    if tool is None:
        tool = detect_tunnel_tool()

    if tool is None:
        logger.error("No tunnel tool available.")
        print(get_install_instructions())
        return ""

    try:
        if tool == "cloudflared":
            return _start_cloudflared(port)
        elif tool == "ngrok":
            return _start_ngrok(port)
        elif tool == "lt":
            return _start_localtunnel(port)
        else:
            logger.error("Unknown tunnel tool: %s", tool)
            return ""
    except Exception as e:
        logger.error("Failed to start tunnel with %s: %s", tool, e)
        return ""

def stop_tunnel() -> None:
    """Stop the running tunnel process."""
    global _process, _tunnel_url, _monitor_thread

    if _process is None:
        logger.info("No tunnel is running.")
        return

    try:
        _process.terminate()
        _process.wait(timeout=5)
    except subprocess.TimeoutExpired:
        _process.kill()
    except Exception as e:
        logger.warning("Error stopping tunnel: %s", e)

    _process = None
    _tunnel_url = ""
    _monitor_thread = None
    logger.info("Tunnel stopped.")

def get_tunnel_url() -> str:
    """
    Get the public URL of the running tunnel.

    Returns:
        The tunnel URL, or empty string if not running.
    """
    return _tunnel_url

def is_tunnel_running() -> bool:
    """Check if a tunnel is currently active."""
    if _process is None:
        return False
    return _process.poll() is None

# ── Tool-specific launchers ────────────────────────────────────────

def _start_cloudflared(port: int) -> str:
    """Start a Cloudflare quick tunnel."""
    global _process, _tunnel_url

    cmd = ["cloudflared", "tunnel", "--url", f"http://localhost:{port}"]
    logger.info("Starting cloudflared: %s", " ".join(cmd))

    _process = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
    )

    # Cloudflared prints the URL to stderr/stdout — watch for it
    url = _capture_url_from_output(
        _process,
        pattern=r"(https://[a-zA-Z0-9-]+\.trycloudflare\.com)",
        timeout=15,
    )

    if url:
        _tunnel_url = url
        logger.info("Cloudflare tunnel active: %s", url)
        return url

    logger.error("Could not capture cloudflared URL within timeout.")
    stop_tunnel()
    return ""

def _start_ngrok(port: int) -> str:
    """Start an ngrok tunnel."""
    global _process, _tunnel_url

    cmd = ["ngrok", "http", str(port), "--log", "stdout"]
    logger.info("Starting ngrok: %s", " ".join(cmd))

    _process = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
    )

    url = _capture_url_from_output(
        _process,
        pattern=r"(https://[a-zA-Z0-9-]+\.ngrok[a-zA-Z0-9.-]*\.[a-z]+)",
        timeout=10,
    )

    if url:
        _tunnel_url = url
        logger.info("ngrok tunnel active: %s", url)
        return url

    logger.error("Could not capture ngrok URL within timeout.")
    stop_tunnel()
    return ""

def _start_localtunnel(port: int) -> str:
    """Start a localtunnel (lt) tunnel."""
    global _process, _tunnel_url

    cmd = ["lt", "--port", str(port)]
    logger.info("Starting localtunnel: %s", " ".join(cmd))

    _process = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
    )

    url = _capture_url_from_output(
        _process,
        pattern=r"(https://[a-zA-Z0-9-]+\.loca\.lt)",
        timeout=10,
    )

    if url:
        _tunnel_url = url
        logger.info("localtunnel active: %s", url)
        return url

    logger.error("Could not capture localtunnel URL within timeout.")
    stop_tunnel()
    return ""

def _capture_url_from_output(
    proc: subprocess.Popen,
    pattern: str,
    timeout: int = 15,
) -> str:
    """
    Read process output line by line and capture the first URL matching pattern.

    Runs in the current thread, blocking up to `timeout` seconds.
    After capturing, spawns a background thread to drain remaining output.
    """
    url = ""
    deadline = time.time() + timeout

    while time.time() < deadline:
        if proc.stdout is None:
            break
        # Use a short readline with the deadline in mind
        line = proc.stdout.readline()
        if not line:
            if proc.poll() is not None:
                break
            time.sleep(0.1)
            continue

        match = re.search(pattern, line)
        if match:
            url = match.group(1)
            break

    # Drain remaining output in background to prevent pipe blocking
    if proc.stdout:
        def _drain():
            try:
                for _ in proc.stdout:
                    pass
            except Exception:
                pass

        global _monitor_thread
        _monitor_thread = threading.Thread(target=_drain, daemon=True)
        _monitor_thread.start()

    return url
```

## File: scripts/utils.py
size: 7618
sha: 924f8403a08847a5ffb1e31d752358104deb4034
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/scripts/utils.py

```text
"""
Shared utilities for the Natural Language Planner.

Provides common functions used across all modules: slug generation,
YAML frontmatter parsing/serializing, date handling, and ID generation.
"""

import re
import uuid
import logging
from pathlib import Path
from datetime import datetime, date
from typing import Any, Optional

logger = logging.getLogger("nlplanner")

def generate_slug(text: str, max_length: int = 50) -> str:
    """
    Generate a URL/filesystem-safe slug from text.

    Args:
        text: The text to slugify.
        max_length: Maximum length of the slug.

    Returns:
        A lowercase, hyphen-separated slug string.

    Example:
        >>> generate_slug("My Cool Project!")
        'my-cool-project'
    """
    slug = text.lower().strip()
    slug = re.sub(r"[^\w\s-]", "", slug)
    slug = re.sub(r"[\s_]+", "-", slug)
    slug = re.sub(r"-+", "-", slug)
    slug = slug.strip("-")
    return slug[:max_length]

def generate_id(prefix: str = "") -> str:
    """
    Generate a unique ID with an optional prefix.

    Args:
        prefix: Optional prefix for the ID (e.g., 'task', 'proj').

    Returns:
        A unique identifier string.

    Example:
        >>> generate_id("task")
        'task-a1b2c3d4'
    """
    short_uuid = uuid.uuid4().hex[:8]
    if prefix:
        return f"{prefix}-{short_uuid}"
    return short_uuid

def generate_task_id(counter: int) -> str:
    """
    Generate a sequential task ID.

    Args:
        counter: The task number.

    Returns:
        Formatted task ID like 'task-001'.

    Example:
        >>> generate_task_id(42)
        'task-042'
    """
    return f"task-{counter:03d}"

def parse_frontmatter(content: str) -> tuple[dict[str, Any], str]:
    """
    Parse YAML frontmatter from a markdown file's content.

    Expects content in the form:
        ---
        key: value
        ---
        Body text here.

    Args:
        content: The full markdown file content.

    Returns:
        A tuple of (frontmatter_dict, body_text).
        If no frontmatter is found, returns ({}, full_content).

    Example:
        >>> meta, body = parse_frontmatter("---\\ntitle: Hello\\n---\\nWorld")
        >>> meta
        {'title': 'Hello'}
        >>> body
        'World'
    """
    # Lazy import to avoid import-time dependency issues
    try:
        import yaml
    except ImportError:
        logger.error("PyYAML is required. Install with: pip install pyyaml")
        return {}, content

    pattern = r"^---\s*\n(.*?)\n---\s*\n?(.*)"
    match = re.match(pattern, content, re.DOTALL)
    if not match:
        return {}, content

    try:
        frontmatter = yaml.safe_load(match.group(1)) or {}
    except yaml.YAMLError as e:
        logger.warning("Failed to parse YAML frontmatter: %s", e)
        frontmatter = {}

    body = match.group(2).strip()
    return frontmatter, body

def serialize_frontmatter(metadata: dict[str, Any], body: str) -> str:
    """
    Serialize metadata and body into a markdown string with YAML frontmatter.

    Args:
        metadata: Dictionary of metadata fields.
        body: The markdown body content.

    Returns:
        Complete markdown string with YAML frontmatter block.

    Example:
        >>> content = serialize_frontmatter({"title": "Hello"}, "World")
        >>> print(content)
        ---
        title: Hello
        ---
        <BLANKLINE>
        World
    """
    try:
        import yaml
    except ImportError:
        logger.error("PyYAML is required. Install with: pip install pyyaml")
        return body

    # Custom representer for dates — keep them as plain strings
    def date_representer(dumper: yaml.Dumper, data: date) -> yaml.ScalarNode:
        return dumper.represent_scalar("tag:yaml.org,2002:str", data.isoformat())

    dumper = yaml.Dumper
    dumper.add_representer(date, date_representer)
    dumper.add_representer(datetime, date_representer)

    yaml_str = yaml.dump(
        metadata,
        Dumper=dumper,
        default_flow_style=False,
        sort_keys=False,
        allow_unicode=True,
    )

    return f"---\n{yaml_str.strip()}\n---\n\n{body}"

def today_str() -> str:
    """Return today's date as an ISO-formatted string (YYYY-MM-DD)."""
    return date.today().isoformat()

def now_str() -> str:
    """Return current datetime as an ISO-formatted string."""
    return datetime.now().isoformat(timespec="seconds")

def ensure_directory(path: Path) -> bool:
    """
    Ensure a directory exists, creating it and any parents if needed.

    Args:
        path: The directory path to ensure exists.

    Returns:
        True if the directory exists (or was created), False on error.
    """
    try:
        path.mkdir(parents=True, exist_ok=True)
        return True
    except OSError as e:
        logger.error("Failed to create directory %s: %s", path, e)
        return False

def safe_read_file(path: Path) -> Optional[str]:
    """
    Safely read a text file, returning None on error.

    Args:
        path: Path to the file.

    Returns:
        File contents as a string, or None if the file can't be read.
    """
    try:
        return path.read_text(encoding="utf-8")
    except (OSError, UnicodeDecodeError) as e:
        logger.error("Failed to read file %s: %s", path, e)
        return None

def safe_write_file(path: Path, content: str) -> bool:
    """
    Safely write content to a text file, creating parent directories as needed.

    Args:
        path: Path to the file.
        content: String content to write.

    Returns:
        True if the file was written successfully, False on error.
    """
    try:
        ensure_directory(path.parent)
        path.write_text(content, encoding="utf-8")
        return True
    except OSError as e:
        logger.error("Failed to write file %s: %s", path, e)
        return False

def safe_child_path(root: Path, *segments: str) -> Optional[Path]:
    """Construct a path from *root* + *segments* and verify it stays inside *root*.

    Returns the resolved ``Path`` if the result is inside *root*, or
    ``None`` if any segment (e.g. containing ``..``) would escape it.
    This prevents path-traversal attacks when IDs come from untrusted
    input such as URL parameters or user-supplied project/task names.

    Args:
        root: The trusted base directory (must already be resolved).
        *segments: One or more path components to join.

    Returns:
        Resolved ``Path`` inside *root*, or ``None`` on traversal.
    """
    try:
        target = root.joinpath(*segments).resolve()
        # is_relative_to is available in Python 3.9+
        if target.is_relative_to(root):
            return target
    except (ValueError, OSError):
        pass
    logger.warning("Path traversal blocked: %s / %s", root, segments)
    return None

def validate_status(status: str) -> bool:
    """Check if a status value is valid for tasks."""
    return status in ("todo", "in-progress", "done", "archived")

def validate_priority(priority: str) -> bool:
    """Check if a priority value is valid."""
    return priority in ("low", "medium", "high")

# Configure default logging
def setup_logging(level: int = logging.INFO) -> None:
    """
    Configure logging for the Natural Language Planner.

    Args:
        level: Logging level (default: INFO).
    """
    handler = logging.StreamHandler()
    handler.setFormatter(
        logging.Formatter("[%(name)s %(levelname)s] %(message)s")
    )
    root = logging.getLogger("nlplanner")
    root.setLevel(level)
    if not root.handlers:
        root.addHandler(handler)
```

## File: .claude/settings.local.json
size: 100
sha: 3407af239d1189706dc7ac5c480b38a135c90478
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/.claude/settings.local.json

```text
{
  "permissions": {
    "allow": [
      "Bash(git add:*)",
      "Bash(git commit:*)"
    ]
  }
}
```

## File: .gitignore
size: 333
sha: 2c4b114ef615916d2dbe26de38634183bfcbb06a
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/.gitignore

```text
# Python
__pycache__/
*.py[cod]
*.pyo
*.egg-info/
dist/
build/

# Testing
.pytest_cache/
.coverage
htmlcov/

# IDE / Editor
.vscode/
.idea/
*.swp
*.swo
*~

# OS
.DS_Store
Thumbs.db
desktop.ini

# User workspace data (never commit someone's actual planner data)
# The test-nlplanner workspace is outside this repo, so no issue there.
```

## File: ARCHITECTURE.md
size: 9147
sha: a0364cab17c015c4ece1c816e77b6f9b93dfb866
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/ARCHITECTURE.md

````text
# Architecture Overview

Technical reference for contributors and maintainers.

## System Diagram

```
┌────────────────────────────────────────────────┐
│                  SKILL.md                       │
│  (AI instructions — intent detection, routing)  │
└──────────────────┬─────────────────────────────┘
                   │ calls
                   ▼
┌──────────────────────────────────────────┐
│            Python Scripts                │
│                                          │
│  ┌──────────────┐  ┌─────────────────┐   │
│  │ file_manager │  │ config_manager  │   │
│  │  (CRUD ops)  │  │  (settings)     │   │
│  └──────┬───────┘  └────────┬────────┘   │
│         │                   │            │
│  ┌──────┴───────┐  ┌───────┴────────┐   │
│  │index_manager │  │dashboard_server│   │
│  │  (search)    │  │  (HTTP + API)  │   │
│  └──────┬───────┘  └───────┬────────┘   │
│         │                   │            │
│  ┌──────┴───────────────────┴────────┐   │
│  │            utils.py               │   │
│  │  (slugs, YAML, file I/O, IDs)    │   │
│  └───────────────────────────────────┘   │
└──────────────────┬───────────────────────┘
                   │ reads/writes
                   ▼
┌──────────────────────────────────────────┐
│           Workspace (filesystem)         │
│                                          │
│  .nlplanner/config.json                  │
│  projects/*/README.md                    │
│  projects/*/tasks/task-NNN.md            │
│  projects/*/attachments/*                │
│  archive/...                             │
└──────────────────────────────────────────┘
                   ▲
                   │ serves via HTTP
┌──────────────────┴───────────────────────┐
│         Dashboard (browser)              │
│                                          │
│  index.html + app.js + styles.css        │
│  ┌─────────────────────────────┐         │
│  │ Kanban │ Projects │ Timeline│         │
│  └─────────────────────────────┘         │
│  Polls /api/* endpoints for data         │
└──────────────────────────────────────────┘
```

## Module Responsibilities

### `utils.py` — Foundation Layer

Shared utilities with zero internal dependencies.

| Function | Purpose |
|---|---|
| `generate_slug()` | Filesystem-safe names from text |
| `generate_task_id()` | Sequential `task-NNN` IDs |
| `parse_frontmatter()` | YAML frontmatter → dict + body |
| `serialize_frontmatter()` | dict + body → Markdown string |
| `safe_read_file()` / `safe_write_file()` | Error-handled file I/O |
| `ensure_directory()` | Recursive mkdir |
| `validate_status()` / `validate_priority()` | Input validation |

### `config_manager.py` — Settings

Manages `.nlplanner/config.json`. Provides typed getters/setters for all
user-configurable settings. Merges with defaults so new settings are always
available after upgrades.

**Key design decision**: The config path is set once via `set_config_path()`
and cached at module level. This avoids threading the workspace path through
every function call.

### `file_manager.py` — Core CRUD

All create/read/update/list/archive operations for projects and tasks.

**Key functions**:
- `init_workspace()` — creates the full directory tree
- `create_project()` / `create_task()` — write new Markdown files
- `get_project()` / `get_task()` — read and parse files
- `list_tasks()` — glob-based listing with filter support
- `update_task()` — merge updates into existing frontmatter
- `archive_task()` / `archive_project()` — move to `archive/`
- `move_task()` — relocate between projects
- `link_tasks()` — add dependency relationships (with circular check)

**Task ID strategy**: Sequential counters (`task-001`, `task-002`, ...) scanned
from all existing files. This is simple, human-readable, and avoids conflicts
as long as there's a single writer (the AI assistant).

### `index_manager.py` — Search & Analytics

In-memory index rebuilt from disk on demand. Provides:
- Full-text search across titles, bodies, tags
- Due-soon / overdue queries
- Check-in staleness detection
- Summary statistics

The index is also persisted to `.nlplanner/index.json` (without body text)
for potential future use by external tools.

### `dashboard_server.py` — Web Interface

Lightweight HTTP server using Python's `http.server` stdlib module.

**Static files**: Served from `templates/dashboard/` (or workspace copy).

**API routes**:

| Endpoint | Returns |
|---|---|
| `GET /api/stats` | Summary statistics |
| `GET /api/projects` | All projects |
| `GET /api/tasks` | All tasks (filterable via query params) |
| `GET /api/task/<id>` | Single task detail |
| `GET /api/project/<id>` | Single project detail |
| `GET /api/search?q=...` | Search results |
| `GET /api/due-soon?days=N` | Tasks due within N days |
| `GET /api/overdue` | Overdue tasks |
| `GET /api/today` | Today's focus task IDs |
| `POST /api/today` | Set today's focus task IDs (JSON body: `{"task_ids": [...]}`) |

**Threading**: The server runs in a daemon thread so it doesn't block the
AI assistant. `start_dashboard()` / `stop_dashboard()` control the lifecycle.

## Data Format

### Frontmatter Schema — Tasks

```yaml
id: task-001          # Unique, sequential
title: string         # Short description
project: string       # Parent project slug
status: todo | in-progress | done | archived
priority: low | medium | high
created: YYYY-MM-DD
due: YYYY-MM-DD | ''
last_checkin: YYYY-MM-DD
tags: [string]
dependencies: [task-id]
```

### Frontmatter Schema — Projects

```yaml
id: project-slug      # URL/filesystem-safe
title: string
created: YYYY-MM-DD
status: active | archived
tags: [string]
color: '#hex'         # Accent colour — auto-assigned from palette, user-overridable
```

## Error Handling Strategy

1. All file I/O goes through `safe_read_file()` / `safe_write_file()` which
   catch OS errors and return `None` / `False`.
2. Functions that can fail return `Optional` types — callers check for `None`.
3. The `logging` module is used throughout (never `print()`).
4. Validation functions (`validate_status`, etc.) reject bad input before
   it reaches the filesystem.

## Cross-Platform Notes

- All paths use `pathlib.Path` — forward/backward slashes handled automatically.
- `~` expansion via `Path.expanduser()`.
- File encoding is always UTF-8.
- The dashboard binds to `127.0.0.1` by default. Set
  `dashboard_allow_network` to `true` to bind to `0.0.0.0` (all
  interfaces) for LAN access on headless / remote devices.

## Extension Points

The architecture is designed to be extended:

- **New file types**: Add a new `create_*` / `get_*` pattern in `file_manager.py`
- **New API endpoints**: Add routes in `DashboardHandler._handle_api()`
- **New dashboard views**: Add HTML section + JS render function + CSS
- **Import/export**: Write converters that read/write the Markdown format
- **CLI**: Import `file_manager` functions directly from a CLI script
- **Sync**: The Markdown-on-filesystem design is naturally git-friendly

## Performance Considerations

- **< 100 tasks**: No optimisation needed; glob scanning is fast.
- **100–1000 tasks**: The in-memory index helps; `rebuild_index()` scans once.
- **1000+ tasks**: Consider adding SQLite as an optional index backend
  (the Markdown files remain the source of truth).

## Security

- Dashboard runs on `127.0.0.1` by default (not accessible from network).
  When `dashboard_allow_network` is enabled it binds to `0.0.0.0`.
- No authentication — when network access is enabled, anyone on the LAN
  can view the dashboard.
- No data leaves the machine.
- File operations are confined to the workspace directory.
````

## File: CUsersbrunotest-nlplanner/.nlplanner/index.json
size: 79
sha: 1167430fa55d49e9fd8828259d33406d9aa70173
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/C%EF%80%BA%EF%81%9CUsers%EF%81%9Cbruno%EF%81%9Ctest-nlplanner/.nlplanner/index.json

```text
{
  "built_at": "2026-03-18T14:28:27.599222",
  "tasks": {},
  "projects": {}
}
```

## File: dashboard-daemon.py
size: 5278
sha: 6b1a52e9c7f1eb20f96a679d7df422a4daa03313
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/dashboard-daemon.py

```text
#!/usr/bin/env python3
"""
Standalone launcher for the Natural Language Planner dashboard.

Resolves the skill installation directory automatically so this script
works whether the skill is:
  - Installed via symlink at ~/.openclaw/skills/natural-language-planner
  - Bundled inside the OpenClaw pnpm global package
  - Run directly from a local clone / checkout

Override the skill location:
    NLP_SKILL_PATH=/path/to/skill  (or SKILL_PATH=/path/to/skill)

Usage:
    python dashboard-daemon.py [--port PORT] [--network] [--no-strict-port] [workspace_path]
"""

import argparse
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path

SKILL_NAME = "natural-language-planner"
SKILL_MARKERS = ("SKILL.md", "scripts", "templates")

def _is_skill_root(path: Path) -> bool:
    return all((path / m).exists() for m in SKILL_MARKERS)

def _pnpm_global_root() -> "Path | None":
    pnpm = shutil.which("pnpm")
    if not pnpm:
        return None
    try:
        result = subprocess.run(
            [pnpm, "root", "-g"],
            capture_output=True, text=True, timeout=5,
        )
        if result.returncode == 0 and result.stdout.strip():
            return Path(result.stdout.strip())
    except (OSError, subprocess.TimeoutExpired):
        pass
    return None

def resolve_skill_root() -> Path:
    """
    Find the skill root using the same resolution order as
    ``config_manager.get_skill_root()``.
    """
    # 1. Explicit env var (NLP_SKILL_PATH takes priority, SKILL_PATH as alias)
    env = os.environ.get("NLP_SKILL_PATH") or os.environ.get("SKILL_PATH")
    if env:
        p = Path(env).expanduser().resolve()
        if _is_skill_root(p):
            return p
        print(
            f"ERROR: Skill path '{env}' does not contain the expected "
            "skill files (SKILL.md, scripts/, templates/).",
            file=sys.stderr,
        )
        sys.exit(1)

    # 2. Standard OpenClaw skill directory
    openclaw_path = (Path.home() / ".openclaw" / "skills" / SKILL_NAME).resolve()
    if _is_skill_root(openclaw_path):
        return openclaw_path

    # 3. pnpm global package
    pnpm_root = _pnpm_global_root()
    if pnpm_root:
        for candidate in (
            pnpm_root / SKILL_NAME,
            pnpm_root / "openclaw" / "skills" / SKILL_NAME,
        ):
            resolved = candidate.resolve()
            if _is_skill_root(resolved):
                return resolved

    # 4. Relative to this script (works for local clones)
    here = Path(__file__).resolve().parent
    if _is_skill_root(here):
        return here

    searched = [
        f"  - NLP_SKILL_PATH / SKILL_PATH env var (not set)",
        f"  - {openclaw_path}",
        f"  - pnpm global root ({pnpm_root or 'pnpm not found'})",
        f"  - {here}",
    ]
    print(
        "ERROR: Could not locate the natural-language-planner skill.\n"
        "Searched:\n" + "\n".join(searched) + "\n\n"
        "Set NLP_SKILL_PATH (or SKILL_PATH) to the directory "
        "containing SKILL.md, scripts/, and templates/.",
        file=sys.stderr,
    )
    sys.exit(1)

def main() -> None:
    parser = argparse.ArgumentParser(
        description="Natural Language Planner — Dashboard Daemon",
    )
    parser.add_argument("--port", type=int, default=None, help="Port (default: 8080)")
    parser.add_argument("--network", action="store_true", help="Bind to all interfaces (0.0.0.0)")
    parser.add_argument(
        "--no-strict-port", dest="strict_port", action="store_false",
        help="Allow fallback to the next free port if the requested port is busy "
             "(default: fail if port is unavailable)",
    )
    parser.add_argument("workspace_path", nargs="?", default=None, help="Workspace directory")
    args = parser.parse_args()

    skill_root = resolve_skill_root()
    print(f"Skill root: {skill_root}")

    if str(skill_root) not in sys.path:
        sys.path.insert(0, str(skill_root))

    from scripts.utils import setup_logging
    from scripts.config_manager import set_workspace_path, load_config
    from scripts.dashboard_server import start_dashboard

    setup_logging()

    if args.workspace_path:
        if not set_workspace_path(args.workspace_path):
            print(f"Failed to use workspace: {args.workspace_path}", file=sys.stderr)
            sys.exit(1)
    else:
        config = load_config()
        if not config.get("workspace_path"):
            print(
                "No workspace specified. Pass a path or run 'init' first.",
                file=sys.stderr,
            )
            sys.exit(1)

    allow_network = args.network or None
    try:
        url = start_dashboard(
            port=args.port,
            allow_network=allow_network,
            strict_port=args.strict_port,
        )
    except RuntimeError as e:
        print(f"ERROR: {e}", file=sys.stderr)
        sys.exit(1)

    if url:
        print(f"Dashboard running at {url}")
        print("Press Ctrl+C to stop.")
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print("\nStopping dashboard.")
    else:
        print("Failed to start dashboard.", file=sys.stderr)
        sys.exit(1)

if __name__ == "__main__":
    main()
```

## File: docs/superpowers/specs/2026-03-18-harden-dashboard-design.md
size: 21079
sha: 7be9aa68306922f5a249f57b23790d193f327f40
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/docs/superpowers/specs/2026-03-18-harden-dashboard-design.md

````text
# Harden Dashboard — Design Spec

**Date:** 2026-03-18
**Scope:** Full harden pass on `templates/dashboard/` (index.html, styles.css, app.js)
**Approach:** Single organized commit, changes grouped by concern within each file

---

## Background

A comprehensive audit of the NL Planner dashboard identified zero ARIA attributes across all interactive elements, no focus management in the modal, no `prefers-reduced-motion` support, missing text overflow guards, no error states for API failures, no debounce on search, and weak empty states. This spec covers all of those findings in a single hardening pass.

---

## Section 1 — ARIA & Semantics

### index.html changes

**Header buttons:**
- `#btn-theme` → add `aria-label="Toggle dark mode"` and `aria-pressed="false"` (JS updates this on toggle). Do NOT add `aria-disabled` as a static attribute — it is only set dynamically.
- `#btn-refresh` → add `aria-label="Refresh data"`. Do NOT add `aria-disabled` as a static attribute — it is only set dynamically when a fetch is in flight.

**Search:**
- `.search-box` div → add `role="search"`
- `#search-input` → add `aria-label="Search tasks"`. Do NOT add `aria-controls` — the search drives a full view panel, not a combobox, so `aria-controls` would create a misleading ARIA relationship without the required combobox pattern.
- Add a visually-hidden `<span id="search-status" role="status" aria-live="polite" aria-atomic="true"></span>` inside `#view-search` for result-count announcements (e.g., "3 results for 'deploy'", "No results").

**Navigation tabs:**
- `.view-tabs` nav → add `role="tablist"` and `aria-label="Dashboard views"`
- Each tab button (class `.tab`) → add `role="tab"`, `id="tab-{view-name}"`, `aria-controls="view-{view-name}"`
- Set `aria-selected` initial values concretely in HTML: the focus tab (active on load) gets `aria-selected="true"`, all other tabs get `aria-selected="false"`
- Each view div → add `role="tabpanel"`, `aria-labelledby="tab-{view-name}"`, `tabindex="0"`

**Stats bar:**
- `#stats-bar` → add `aria-label="Task statistics"`
- Do NOT add `aria-live` to the entire `#stats-bar` container — it re-renders wholesale and would announce all content on every update. Instead, add a separate visually-hidden `<span id="stats-status" role="status" aria-live="polite" aria-atomic="true"></span>` immediately after `#stats-bar`. JS sets its text to a brief summary after each data load (e.g., "Stats updated: 12 tasks, 3 overdue").

**Today section:**
- `#today-list` → add `aria-live="polite"` is acceptable here because the today section re-renders only when today tasks genuinely change (pinned/unpinned), not on every filter or tab switch. Keep `aria-live="polite"`.

**Attention/overdue banner:**
- The banner already exists as a static element `#attention-banner` in `index.html`. Add `role="status"` and `aria-live="polite"` to the existing element. Do NOT create a new element — JS currently shows/hides it via `style.display`.

**Modal:**
- `#modal-overlay` → add `role="dialog"`, `aria-modal="true"`, `aria-labelledby="modal-title"`
- `.modal-close` button → add `aria-label="Close task detail"`

### app.js changes

**Tab switching:** On each tab click, set `aria-selected="true"` on the clicked tab and `aria-selected="false"` on all others.

**`toggleTheme()`:** Toggle `aria-pressed` on `#btn-theme` — set to `"true"` when dark mode is active, `"false"` when light.

**`handleSearch()`:** After rendering results, set `#search-status` text content to e.g. `"3 results for 'deploy'"` or `"No results for 'foo'"`.

**`loadAll()` start/end:** Set `aria-disabled="true"` + `disabled = true` on `#btn-refresh` when fetch begins; remove both on completion (success or error). This replaces/supplements the existing `spinning` class — see Section 5.

**After data renders:** Set `#stats-status` text to a brief summary e.g. `"Stats updated"`.

### Visually-hidden utility class (styles.css)

```css
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}
```

Apply to `#search-status` and `#stats-status` spans.

---

## Section 2 — Focus Management

### Focus trap utility (app.js)

Add a `trapFocus(el)` function. Initialise the module-level variable as `let removeTrap = null;` so `closeModal()` can safely call `removeTrap?.()` even before any modal has been opened.

```js
let removeTrap = null;

function trapFocus(el) {
  const focusable = el.querySelectorAll(
    'button:not([disabled]), [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
  );
  const first = focusable[0];
  const last = focusable[focusable.length - 1];

  function handler(e) {
    if (e.key !== 'Tab') return;
    if (e.shiftKey) {
      if (document.activeElement === first) { e.preventDefault(); last.focus(); }
    } else {
      if (document.activeElement === last) { e.preventDefault(); first.focus(); }
    }
  }

  el.addEventListener('keydown', handler);
  return () => el.removeEventListener('keydown', handler);
}
```

### openModal(id)

1. Store `document.activeElement` as `lastFocusedEl` (module-level variable, initialised to `null`)
2. Open modal (existing logic)
3. Move focus to `els.modalClose`
4. `removeTrap = trapFocus(els.modal)`

### closeModal()

1. `removeTrap?.(); removeTrap = null;`
2. Close modal (existing logic)
3. `lastFocusedEl?.focus(); lastFocusedEl = null;`

**Note on stale focus target:** After a data re-render (triggered by visibility-change while modal is closed), the previously focused card element may be removed from the DOM. `focus()` on a detached element silently fails — this is acceptable behaviour for this app. The focus simply lands on `<body>`. No additional mitigation is needed.

**Existing Escape key handler:** The existing `keydown` handler in `init()` already uses if/else to close the lightbox first, then calls `closeModal()`. This is compatible with the new focus-restore call in `closeModal()` — no change needed to the Escape handler.

### Focus rings (styles.css)

Replace the bare border-color change on `.filter-select:focus` with a visible ring:

```css
.filter-select:focus {
  border-color: var(--blue);
  box-shadow: 0 0 0 3px var(--blue-light);
  outline: none;
}
```

Add keyboard-only focus rings to tab buttons (actual class: `.tab`) and ghost buttons:

```css
.tab:focus-visible,
.btn-ghost:focus-visible {
  outline: 2px solid var(--blue);
  outline-offset: 2px;
}
```

Use `:focus-visible` (not `:focus`) to avoid showing rings on mouse clicks.

### Theme flash fix

**styles.css:** Remove `transition: background 200ms ease, color 200ms ease` from the `body` default rule. Add:

```css
body.theme-ready {
  transition: background 200ms ease, color 200ms ease;
}
```

**app.js:** The double-rAF must be added inside `initTheme()` itself — not in a `DOMContentLoaded` handler. This is because `init()` is called immediately if `document.readyState !== "loading"` (which is the common case for a script at the bottom of `<body>`), meaning `DOMContentLoaded` may never fire in this code path. Modify `initTheme()`:

```js
function initTheme() {
  const saved = localStorage.getItem("nlp-theme");
  if (saved === "dark" || (!saved && window.matchMedia("(prefers-color-scheme: dark)").matches)) {
    els.body.classList.add("dark");
  }
  // Add transition class after first paint to prevent flash on load
  requestAnimationFrame(() => requestAnimationFrame(() => {
    document.body.classList.add('theme-ready');
  }));
}
```

The double-rAF guarantees the theme is applied and painted before the transition is enabled, eliminating the flash-then-transition on load.

---

## Section 3 — Motion & Transitions

### prefers-reduced-motion (styles.css)

Add at the bottom of `styles.css`, after all other rules:

```css
@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
    scroll-behavior: auto !important;
  }
}
```

This single block covers all keyframe animations (spin, modal-in, modal-slide-up) and all CSS transitions, including the hardcoded `width 400ms ease` on `.progress-bar-modal .progress-bar-fill` (line ~964) which is not a `var(--transition)` reference.

### Modal progress animation (styles.css + index.html + app.js)

Replace `max-height` animation on the modal progress section with `grid-template-rows`.

**index.html:** Restructure `#modal-progress` to use the grid animation pattern. The actual existing markup (lines 208–216) includes a `.modal-progress-header` with `#modal-progress-pct`. Preserve all existing children:

```html
<!-- Before (actual markup) -->
<div class="modal-progress" id="modal-progress" style="display:none">
  <div class="modal-progress-header">
    <span class="modal-progress-label">Progress</span>
    <span class="modal-progress-pct" id="modal-progress-pct"></span>
  </div>
  <div class="progress-bar progress-bar-modal">
    <div class="progress-bar-fill" id="modal-progress-fill"></div>
  </div>
</div>

<!-- After -->
<div class="modal-progress-wrapper" id="modal-progress">
  <div class="modal-progress-inner">
    <div class="modal-progress-header">
      <span class="modal-progress-label">Progress</span>
      <span class="modal-progress-pct" id="modal-progress-pct"></span>
    </div>
    <div class="progress-bar progress-bar-modal">
      <div class="progress-bar-fill" id="modal-progress-fill"></div>
    </div>
  </div>
</div>
```

`id="modal-progress"` stays on the outermost element so `els.modalProgress` (and `els.modalProgressPct`, `els.modalProgressFill`) in `app.js` still work — they reference descendant elements by their own IDs, not by position.

**styles.css:** Replace the existing `.modal-progress` rules with:

```css
.modal-progress-wrapper {
  display: grid;
  grid-template-rows: 0fr;
  transition: grid-template-rows 250ms ease;
}
.modal-progress-wrapper.open {
  grid-template-rows: 1fr;
}
.modal-progress-inner {
  overflow: hidden;
  padding-bottom: 0;
  transition: padding-bottom 250ms ease;
}
.modal-progress-wrapper.open .modal-progress-inner {
  padding-bottom: 12px;
}
```

**app.js:** Replace all instances of `els.modalProgress.style.display = 'none'` with `els.modalProgress.classList.remove('open')`, and `els.modalProgress.style.display = ''` (or `block`) with `els.modalProgress.classList.add('open')`. Remove the `style="display:none"` from the HTML too, since the CSS `grid-template-rows: 0fr` hides it by default.

---

## Section 4 — Text Overflow

### styles.css additions

Verify each selector against the actual HTML before applying. Confirmed class names from the codebase:

**Focus card titles** — class is `.focus-card-title` (clamp to 2 lines, with flex shrink guard):
```css
.focus-card-title {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  min-width: 0; /* flex shrink guard — allows shrinking below content size */
}
```

**Kanban task card titles** — class is `.task-card-title` (clamp to 2 lines, with flex shrink guard):
```css
.task-card-title {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  min-width: 0; /* flex shrink guard */
}
```

**Modal title** — class is `.modal-title` (allow wrapping, prevent overflow):
```css
.modal-title {
  overflow-wrap: break-word;
  word-break: break-word;
}
```

**Project card titles** — actual class is `.project-card-title` (NOT `.project-card-name`):
```css
.project-card-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
}
```

**Flex shrink guards** — `min-width: 0` inlined into the relevant CSS blocks above:
- `.focus-card-title` — included in the block above
- `.task-card-title` — include `min-width: 0` in the clamp block below
- `.project-card-title` — include `min-width: 0` in the ellipsis block below (`.project-card-header` does not exist in the codebase; `.task-card-body` has no CSS rules and is a plain block, so the guard belongs on the title directly)

Note: `.today-item-title` already has `min-width: 0` in the existing CSS — no change needed there.

---

## Section 5 — Error & Loading States

### Error banner (index.html)

Add after line 86 (`</section>` closing `.top-bar`), before `<nav class="view-tabs">`, hidden by default:

```html
<div id="error-banner" role="alert" hidden>
  <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/>
    <line x1="12" y1="16" x2="12.01" y2="16"/>
  </svg>
  <span id="error-message">Could not reach the planner server.</span>
  <button id="btn-retry" class="btn btn-ghost">Retry</button>
</div>
```

`role="alert"` causes screen readers to announce it immediately when it appears (equivalent to `aria-live="assertive"`). No separate `aria-live` is needed.

### Error banner styles (styles.css)

```css
#error-banner {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 24px;
  background: var(--red-light);
  color: var(--red);
  border-bottom: 1px solid var(--red);
  font-size: 0.88rem;
}
#error-banner[hidden] { display: none; }
```

Dark mode: `--red-light` is `rgba(239,68,68,.15)` and `--red` is `#ef4444` — contrast is adequate on dark backgrounds. No dark-mode override needed.

### app.js changes

**Module-level state additions:**
```js
let isLoading = false;
let isInitialLoad = true;
let lastFocusedEl = null;
```

**`loadAll()` refactor:**

The existing `loadAll()` already has a `spinning` class animation on `#btn-refresh`. Preserve the spin animation and add the disabled/aria-disabled guard:

```js
async function loadAll() {
  if (isLoading) return;
  isLoading = true;
  els.btnRefresh.disabled = true;
  els.btnRefresh.setAttribute('aria-disabled', 'true');
  els.btnRefresh.classList.add('spinning'); // preserve existing animation

  try {
    // ... existing fetch logic unchanged ...
    hideError();
    isInitialLoad = false;
  } catch (err) {
    showError('Could not reach the planner server.');
  } finally {
    isLoading = false;
    els.btnRefresh.disabled = false;
    els.btnRefresh.setAttribute('aria-disabled', 'false');
    els.btnRefresh.classList.remove('spinning');
  }
}
```

**Error helpers:**
```js
function showError(msg) {
  els.errorMessage.textContent = msg;
  els.errorBanner.hidden = false;
}

function hideError() {
  els.errorBanner.hidden = true;
}
```

**`#btn-retry` listener (in `init()`):**
```js
els.btnRetry.addEventListener('click', () => {
  hideError();
  loadAll();
});
```

**Add to `els` cache:**
```js
modal: $('#task-modal'),          // needed by trapFocus and openModal
errorBanner: $('#error-banner'),
errorMessage: $('#error-message'),
btnRetry: $('#btn-retry'),
statsStatus: $('#stats-status'),
searchStatus: $('#search-status'),
```

**Loading state:**

When `isInitialLoad` is `true` and `allTasks` is empty, the main content area shows:

```html
<div class="loading-state">Loading…</div>
```

```css
.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 64px 24px;
  color: var(--text-muted);
  font-size: 0.9rem;
}
```

Each view-render function (`renderFocusView`, `renderBoard`, etc.) checks `if (isInitialLoad && allTasks.length === 0)` at the top and returns the loading markup early. `isInitialLoad` is set to `false` after the first successful `loadAll()` completes (inside the `try` block).

---

## Section 6 — Debounce & Interaction Guards

### Debounce utility (app.js)

Add near the top of `app.js`, before `init()`:

```js
function debounce(fn, ms) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), ms);
  };
}
```

### Search debounce

**Important:** `handleSearch` already implements a correct internal pattern: it calls `hideSearch()` immediately for empty queries, then debounces only the API call via `searchDebounce = setTimeout(...)`. Wrapping the whole function in `debounce()` would delay the `hideSearch()` path by 300ms — creating a visible lag when the user clears the search box.

The correct approach is to replace the ad-hoc `let searchDebounce` + `clearTimeout`/`setTimeout` inside `handleSearch` with the `debounce` utility extracted as a named function:

```js
// Remove: let searchDebounce = null; (module-level variable)

// Add a debounced API caller:
const debouncedSearchApi = debounce(async (query) => {
  const results = await api(`/api/search?q=${encodeURIComponent(query)}`);
  showSearch(results || []);
}, 300);

// Rewrite handleSearch to use it:
function handleSearch() {
  const query = els.searchInput.value.trim();
  if (!query) {
    hideSearch();
    return;
  }
  debouncedSearchApi(query);
}
```

The event listener registration stays the same — no wrapping needed:
```js
els.searchInput.addEventListener('input', handleSearch);
```

Keep the existing `keydown` Enter handler as-is — it calls `handleSearch()` directly and fires immediately.

### isLoading guard

Covered in Section 5. The `isLoading` flag at the top of `loadAll()` also gates visibility-change and interval-triggered calls from racing.

### Kanban column overflow fix (styles.css)

The actual task list class inside kanban columns is `.column-body` (not `.kanban-column-tasks`).

```css
/* Remove overflow: hidden from the column wrapper */
.kanban-column {
  /* remove: overflow: hidden */
  overflow: visible; /* or simply remove the property */
}

/* Move scrolling to the task list */
.column-body {
  overflow-y: auto;
  flex: 1;
  min-height: 0;
}
```

`.kanban-column` already uses `display: flex; flex-direction: column` so `.column-body` will correctly fill available height.

---

## Section 7 — Empty States

### Kanban empty columns (app.js)

When a kanban column renders zero task cards, append inside `.column-body`:

```html
<div class="empty-column">No tasks here</div>
```

```css
.empty-column {
  text-align: center;
  color: var(--text-muted);
  font-size: 0.85rem;
  padding: 32px 0;
}
```

### Search empty state (app.js)

When `handleSearch` returns zero results, set the content of `#view-search`:

```html
<div class="empty-state">
  <p>No tasks match "<strong id="empty-search-query"></strong>"</p>
</div>
```

Also update `#search-status` (visually hidden): `"No results for '${query}'"`.

### Filter empty state (app.js)

When active filters produce zero tasks in any view, render:

```html
<div class="empty-state">
  <p>No tasks match the current filters.</p>
  <button class="btn btn-ghost js-clear-filters">Clear filters</button>
</div>
```

**Wiring:** Because the app is inside an IIFE and `clearAllFilters()` is not on the global scope, attach the click handler immediately after injecting the empty state HTML:

```js
// Inside the render function, after setting innerHTML:
const clearBtn = container.querySelector('.js-clear-filters');
if (clearBtn) clearBtn.addEventListener('click', clearAllFilters);
```

### Shared empty state styles

```css
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 48px 24px;
  color: var(--text-muted);
  font-size: 0.9rem;
  text-align: center;
}
```

---

## Lightbox (out of scope, noted)

The lightbox (`#lightbox-overlay`) has the same missing focus trap and ARIA issues as the modal. This is out of scope for this pass but should be addressed in a follow-up harden pass.

---

## Files Changed

| File | Nature of changes |
|------|-------------------|
| `templates/dashboard/index.html` | ARIA attributes on buttons/tabs/modal/search; error banner; `#stats-status` and `#search-status` spans; tabpanel roles; `#attention-banner` ARIA; modal-progress wrapper restructure |
| `templates/dashboard/styles.css` | `.sr-only` utility; focus rings (`.filter-select`, `.tab`, `.btn-ghost`); `prefers-reduced-motion` block; `grid-template-rows` animation; text overflow guards; error banner and loading/empty state styles; `body.theme-ready` theme flash fix |
| `templates/dashboard/app.js` | `trapFocus()`, `debounce()`; `isLoading`, `isInitialLoad`, `lastFocusedEl`, `removeTrap` state; `showError()`/`hideError()`; `aria-selected` management; `aria-pressed` toggle; `#btn-retry` handler; focus save/restore; double-rAF in `initTheme()`; `#search-status` and `#stats-status` updates; `debouncedSearchApi` extraction (replaces `searchDebounce` variable); `.js-clear-filters` wiring; `loadAll()` guard + spinner reconciliation |

---

## Out of Scope

- Virtual scrolling / pagination for archive (separate `/optimize` task)
- Loading skeleton screens (separate `/delight` task)
- Font or color palette changes (separate `/normalize` task)
- RTL language support (no i18n requirement identified for this project)
- Lightbox focus trap and ARIA (follow-up `/harden` pass)
````

## File: examples/conversation_examples.md
size: 4158
sha: 2e741463f802b93fef385e081443043c298b6a67
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/examples/conversation_examples.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/bparticle/natural-language-planner/blob/HEAD/examples/conversation_examples.md

## File: examples/sample_project/tasks/task-001.md
size: 665
sha: d05e894a76c6144ec2aff214bae69e977db153d0
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/examples/sample_project/tasks/task-001.md

```text
---
id: task-001
title: Design new homepage layout
project: website-redesign
status: in-progress
priority: high
created: '2026-02-09'
due: '2026-02-14'
last_checkin: '2026-02-09'
tags:
- design
- homepage
dependencies: []
---

## Description
Create wireframes and high-fidelity mockups for the new homepage. Should incorporate the updated brand colours and typography.

## Context
User mentioned wanting a modern, clean look. Prefers minimal design with bold typography. Cited Stripe and Linear as design inspiration.

## Notes
- Start with mobile wireframe first
- Include hero section, features grid, testimonials, and CTA
- Use Figma for mockups

## Attachments
```

## File: examples/sample_project/tasks/task-002.md
size: 586
sha: dea2869f51169cde79caddc71f7c797d2fba3b16
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/examples/sample_project/tasks/task-002.md

```text
---
id: task-002
title: Improve mobile responsiveness
project: website-redesign
status: todo
priority: medium
created: '2026-02-09'
due: '2026-02-28'
last_checkin: '2026-02-09'
tags:
- frontend
- mobile
dependencies:
- task-001
---

## Description
Audit all pages for mobile breakpoints and fix layout issues. Target devices: iPhone 14, Pixel 7, iPad.

## Context
Analytics show 60% of traffic is mobile but the current site has poor mobile UX.

## Notes
- Run Lighthouse mobile audit first
- Fix hamburger menu on smaller screens
- Test touch targets are at least 44px

## Attachments
```

## File: examples/sample_project/tasks/task-003.md
size: 533
sha: ccd5dac86d9b519f5b5c5bb75923a7175178662f
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/examples/sample_project/tasks/task-003.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/bparticle/natural-language-planner/blob/HEAD/examples/sample_project/tasks/task-003.md

## File: LICENSE.txt
size: 1094
sha: bf706629e7275c6dfab6c58dbc4aad662954fd69
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/LICENSE.txt

Content is not inlined in the catalog. Read the upstream file: https://github.com/bparticle/natural-language-planner/blob/HEAD/LICENSE.txt

## File: start-dashboard.sh
size: 5628
sha: 65c19f34d52842da4dac4e0f2f213612cd526c16
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/start-dashboard.sh

Content is not inlined in the catalog. Read the upstream file: https://github.com/bparticle/natural-language-planner/blob/HEAD/start-dashboard.sh

## File: templates/dashboard/app.js
size: 58700
sha: 5e458a828dbe27fe768d9d30b1a6546e9922571e
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/templates/dashboard/app.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/bparticle/natural-language-planner/blob/HEAD/templates/dashboard/app.js

## File: templates/dashboard/index.html
size: 14099
sha: a5dd6676400717e0bfc8ae5de959441b88b2ebbc
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/templates/dashboard/index.html

Content is not inlined in the catalog. Read the upstream file: https://github.com/bparticle/natural-language-planner/blob/HEAD/templates/dashboard/index.html

## File: templates/dashboard/styles.css
size: 48518
sha: 009581ad40b6031953287687483b15466afa33ba
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/templates/dashboard/styles.css

Content is not inlined in the catalog. Read the upstream file: https://github.com/bparticle/natural-language-planner/blob/HEAD/templates/dashboard/styles.css

## File: templates/project_template.md
size: 139
sha: 69ab3860017b7bf9aa0094d69b49afb21638be29
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/templates/project_template.md

```text
---
id: {project_id}
title: {title}
created: {date}
status: active
tags: []
---

## Description
{description}

## Goals
- {goal}

## Notes
```

## File: templates/task_template.md
size: 266
sha: e69cfd6faeca71d3c89889cce8daf8f29420c92f
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/templates/task_template.md

```text
---
id: {task_id}
title: {title}
project: {project_id}
status: todo
priority: medium
created: {date}
due: ''
last_checkin: {date}
tags: []
dependencies: []
---

## Description
{description}

## Context
{context}

## Notes

## Subtasks

## Attachments

## Agent Tips
```

## File: tests/test_config_manager.py
size: 5388
sha: 71835017ebb443a42847644ee8f87f5334843dfc
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/tests/test_config_manager.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/bparticle/natural-language-planner/blob/HEAD/tests/test_config_manager.py

## File: tests/test_file_manager.py
size: 8869
sha: 52f7607e996dd96dfbf7c087f0e31661cb2c20a0
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/tests/test_file_manager.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/bparticle/natural-language-planner/blob/HEAD/tests/test_file_manager.py

## File: tests/test_index_manager.py
size: 6294
sha: 8a29ea67815ef0a65e2d1bd52f534f8a1c641b75
upstream: https://github.com/bparticle/natural-language-planner/blob/HEAD/tests/test_index_manager.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/bparticle/natural-language-planner/blob/HEAD/tests/test_index_manager.py
