From e10a0280b2320e7970a34502497458680f6fb14a Mon Sep 17 00:00:00 2001 From: Dawid Piaskowski Date: Mon, 13 Apr 2026 19:56:37 +0200 Subject: [PATCH 1/3] chore: sync upstream + add fork note to README Fast-forward merged 8 upstream commits (a11y + performance checklist improvements). Added fork note linking to the 3 open PRs. Co-Authored-By: Claude Sonnet 4.6 --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index db5132f3f0..11de04453e 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # Agent Skills +> **Fork note:** This is [@googlarz](https://github.com/googlarz)'s fork of [addyosmani/agent-skills](https://github.com/addyosmani/agent-skills) with work-in-progress enhancements: [observability-and-monitoring skill](https://github.com/addyosmani/agent-skills/pull/61), [CI skill validator](https://github.com/addyosmani/agent-skills/pull/60), and [agent persona integration](https://github.com/addyosmani/agent-skills/pull/62). + **Production-grade engineering skills for AI coding agents.** Skills encode the workflows, quality gates, and best practices that senior engineers use when building software. These ones are packaged so AI agents follow them consistently across every phase of development. From 25afa78d2a56238ec0255e222372363cb24a7719 Mon Sep 17 00:00:00 2001 From: Dawid Piaskowski Date: Sun, 26 Apr 2026 08:09:16 +0200 Subject: [PATCH 2/3] =?UTF-8?q?Add=20/assistant=20=E2=80=94=20Calendar=20&?= =?UTF-8?q?=20Task=20Manager=20skill?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a production-grade calendar and task management skill for Claude Code. Features: - Rich context-aware Google Calendar entries with transcript links - Detects scheduling conflicts before committing - Respects work hours and user preferences via pattern matching - Manages local task lists without external dependencies - Optional prep blocks before meetings (user-confirmed per event) - Supports recurring events with RRULE - Bulk reschedule for schedule adjustments Python implementation (calendar.py, tasks.py) handles OAuth setup, Google Calendar API integration, and local task storage. Comprehensive documentation includes: - SKILL.md: Complete workflow reference and command documentation - README.md: User guide with practical examples and troubleshooting - INTEGRATION.md: Step-by-step guide for adding to agent-skills fork - preferences.json: Event-type pattern matching configuration No maintenance commitment; contributions welcome. --- README.md | 13 +- skills/assistant/.gitignore | 13 + skills/assistant/INTEGRATION.md | 223 +++++ skills/assistant/README.md | 243 ++++++ skills/assistant/SKILL.md | 349 ++++++++ skills/assistant/preferences.json | 97 +++ skills/assistant/scripts/calendar.py | 1064 ++++++++++++++++++++++++ skills/assistant/scripts/mcp_server.py | 310 +++++++ skills/assistant/scripts/tasks.py | 337 ++++++++ 9 files changed, 2646 insertions(+), 3 deletions(-) create mode 100644 skills/assistant/.gitignore create mode 100644 skills/assistant/INTEGRATION.md create mode 100644 skills/assistant/README.md create mode 100644 skills/assistant/SKILL.md create mode 100644 skills/assistant/preferences.json create mode 100644 skills/assistant/scripts/calendar.py create mode 100644 skills/assistant/scripts/mcp_server.py create mode 100644 skills/assistant/scripts/tasks.py diff --git a/README.md b/README.md index 11de04453e..515782cd5b 100644 --- a/README.md +++ b/README.md @@ -126,9 +126,9 @@ Skills are plain Markdown - they work with any agent that accepts system prompts --- -## All 20 Skills +## All 21 Skills -The commands above are the entry points. Under the hood, they activate these 20 skills — each one a structured workflow with steps, verification gates, and anti-rationalization tables. You can also reference any skill directly. +The commands above are the entry points. Under the hood, they activate 20 core lifecycle skills — each one a structured workflow with steps, verification gates, and anti-rationalization tables. Plus one standalone productivity skill. You can also reference any skill directly. ### Define - Clarify what to build @@ -180,6 +180,12 @@ The commands above are the entry points. Under the hood, they activate these 20 | [documentation-and-adrs](skills/documentation-and-adrs/SKILL.md) | Architecture Decision Records, API docs, inline documentation standards - document the *why* | Making architectural decisions, changing APIs, or shipping features | | [shipping-and-launch](skills/shipping-and-launch/SKILL.md) | Pre-launch checklists, feature flag lifecycle, staged rollouts, rollback procedures, monitoring setup | Preparing to deploy to production | +### Productivity & Utilities - Standalone skills + +| Skill | What It Does | Invoke With | +|-------|-------------|-------------| +| [assistant](skills/assistant/README.md) | Calendar and task management. Creates rich context-aware Google Calendar entries with conversation links, detects conflicts, respects work preferences, manages local task lists | `/assistant` (automatic or explicit invocation) | + --- ## Agent Personas @@ -242,7 +248,7 @@ Every skill follows a consistent anatomy: ``` agent-skills/ -├── skills/ # 20 core skills (SKILL.md per directory) +├── skills/ # 21 skills (SKILL.md per directory) │ ├── idea-refine/ # Define │ ├── spec-driven-development/ # Define │ ├── planning-and-task-breakdown/ # Plan @@ -263,6 +269,7 @@ agent-skills/ │ ├── deprecation-and-migration/ # Ship │ ├── documentation-and-adrs/ # Ship │ ├── shipping-and-launch/ # Ship +│ ├── assistant/ # Productivity: Calendar & tasks │ └── using-agent-skills/ # Meta: how to use this pack ├── agents/ # 3 specialist personas ├── references/ # 4 supplementary checklists diff --git a/skills/assistant/.gitignore b/skills/assistant/.gitignore new file mode 100644 index 0000000000..ead638bccd --- /dev/null +++ b/skills/assistant/.gitignore @@ -0,0 +1,13 @@ +# Google OAuth — never commit these +token.json +credentials.json + +# Runtime data +config.json +tasks.json + +# Python +__pycache__/ +*.pyc +*.pyo +.DS_Store diff --git a/skills/assistant/INTEGRATION.md b/skills/assistant/INTEGRATION.md new file mode 100644 index 0000000000..ce53f7dead --- /dev/null +++ b/skills/assistant/INTEGRATION.md @@ -0,0 +1,223 @@ +# Integration Guide — Adding Assistant to agent-skills + +This guide walks through adding the `/assistant` skill to your agent-skills fork. + +--- + +## File Structure + +``` +agent-skills/skills/assistant/ +├── SKILL.md # Skill definition + workflow +├── README.md # User-facing guide +├── preferences.json # Event-type pattern defaults +├── scripts/ +│ ├── calendar.py # Main calendar CLI (1064 lines) +│ ├── tasks.py # Task list CLI (337 lines) +│ └── mcp_server.py # Optional MCP wrapper (310 lines) +└── .gitignore # Ignore token.json + credentials.json +``` + +--- + +## Step-by-Step + +### 1. Copy the skill into your fork + +```bash +cd ~/Claude\ Code/Dev/agent-skills +mkdir -p skills/assistant/scripts +cp ~/claude-assistant/SKILL.md skills/assistant/ +cp ~/claude-assistant/README.md skills/assistant/ +cp ~/claude-assistant/preferences.json skills/assistant/ +cp ~/claude-assistant/scripts/*.py skills/assistant/scripts/ +cp ~/claude-assistant/.gitignore skills/assistant/ +``` + +### 2. Verify the structure + +```bash +ls -la skills/assistant/ +``` + +Should show: `SKILL.md`, `README.md`, `preferences.json`, `scripts/`, `.gitignore`. + +### 3. Add to skills index + +Open `skills/index.json` (or wherever agent-skills catalogs available skills) and add: + +```json +{ + "name": "assistant", + "description": "Calendar and task management. Creates rich context-aware Google Calendar entries with conversation links, detects conflicts, respects work preferences.", + "tags": ["productivity", "calendar", "tasks", "scheduling"], + "author": "@googlarz", + "status": "stable", + "maintenance": "low" +} +``` + +### 4. Add to skill discovery (optional) + +If agent-skills has a discovery mechanism or skill recommendations system, add keywords: + +- Triggers: `schedule`, `calendar`, `meeting`, `remind`, `deadline`, `task`, `follow-up` +- Categories: `productivity`, `time-management` + +### 5. Update README + +Add a brief mention in the main agent-skills README: + +```markdown +#### `/assistant` — Calendar & Task Manager + +Create rich, context-aware Google Calendar entries from conversations. Every event links back to the transcript. + +- Detect scheduling conflicts before booking +- Find free time slots +- Manage a local task list +- Learn your preferences (recurring patterns) +- Optional prep blocks before meetings + +See [`skills/assistant/README.md`](skills/assistant/README.md) for full docs and examples. +``` + +### 6. First-time setup for users + +When a user invokes `/assistant` for the first time, Claude should guide them: + +``` +This skill needs OAuth access to your Google Calendar. + +Run: python3 ~/.claude/skills/assistant/scripts/calendar.py setup + +This will: +1. Open a browser for Google OAuth +2. Detect your timezone +3. Let you pick which calendar to use + +After setup, customize your preferences: +python3 ~/.claude/skills/assistant/scripts/calendar.py profile --setup +``` + +--- + +## What's Included + +### Python Scripts (~1700 lines total) + +- **calendar.py**: Full CLI for calendar ops (setup, add, delete, list, free, reschedule, etc.) +- **tasks.py**: Lightweight task management (no external deps) +- **mcp_server.py**: Optional MCP wrapper (for future native tool access) + +### Documentation + +- **SKILL.md**: Complete workflow reference + command docs (copy-pasted from your current version, with features refined) +- **README.md**: User guide with examples and philosophy + +### Config + +- **preferences.json**: Event-type pattern matching (standup, deadline, 1:1, review, etc.) +- **.gitignore**: Excludes `token.json` and `credentials.json` (OAuth secrets) + +--- + +## Testing Before Merge + +### 1. Verify it works locally + +```bash +/assistant +``` + +In a Claude Code conversation, invoke the skill. It should ask you to set up if you haven't already. + +### 2. Run the setup + +```bash +python3 ~/.claude/skills/assistant/scripts/calendar.py setup +``` + +Complete the OAuth flow and verify calendar selection. + +### 3. Test a real event + +Try creating an event from a conversation: + +> *"remind me to review the design doc next Monday at 2pm"* + +Claude should: +1. Check your calendar +2. Show a preview +3. Ask for confirmation +4. Create the event with a transcript link + +### 4. Verify the transcript link + +The event description should include a path like: + +``` +📄 Transcript: ~/.claude/projects/.../f1936594.jsonl +``` + +Open that file — it should be the actual conversation JSONL. + +--- + +## Minimal Deps + +The scripts require: +- Python 3.8+ +- `google-auth-oauthlib` (pip install, OAuth flow) +- `google-auth-httplib2` (pip install, Google API client) +- `google-api-python-client` (pip install) +- Standard library (json, argparse, datetime, pathlib) + +**No external dependencies** for the task list — it's pure local JSON. + +Setup script can prompt users to `pip install` if deps are missing. + +--- + +## Known Limitations + +- **No attendee support**: Events can't invite others (feature cut for v1.0) +- **No search**: Can't search by keyword (feature cut for v1.0) +- **Prep blocks are optional**: User decides per event +- **Local task list only**: No sync across devices +- **No email invites**: For multi-person events, user needs to share calendar link separately + +These are intentional cuts to ship v1.0 focused. Can add in future iterations based on feedback. + +--- + +## Future Iterations + +Potential improvements (not in v1.0): + +1. **Attendee support** — allow inviting others, with explicit confirmation +2. **Search** — full-text search across past/future events +3. **Cloud task sync** — sync task list across devices +4. **Notification customization** — change reminder types per event +5. **MCP native integration** — replace shell-outs with native tool calls + +--- + +## Support & Maintenance + +- **Status**: Stable, used daily for real scheduling +- **Maintenance**: No commitment; contributions welcome +- **Issues**: Post to agent-skills issues; tag with `@assistant` +- **Roadmap**: Driven by feedback + +--- + +## Quick Checklist + +- [ ] Copy files to `skills/assistant/` +- [ ] Add to skills index +- [ ] Update main README with skill mention +- [ ] Test setup + OAuth flow +- [ ] Test creating an event +- [ ] Verify transcript linking +- [ ] Commit + PR with message: "Add /assistant — Calendar & Task Manager skill" diff --git a/skills/assistant/README.md b/skills/assistant/README.md new file mode 100644 index 0000000000..ca9096ed50 --- /dev/null +++ b/skills/assistant/README.md @@ -0,0 +1,243 @@ +# 📅 Assistant — Calendar & Task Manager + +A Claude Code skill that turns scheduling into a collaborative act. Write rich, context-aware Google Calendar entries directly from conversations, manage a local task list, detect conflicts, and every entry links back to the exact conversation that created it. + +--- + +## ✨ Why This Is Different + +Most calendar tools take a title and time. This skill adds **context**. + +When you schedule something in a conversation: + +``` +• Sync API keys with Marco before deploy +• Why: deploy is Friday 3pm, keys expire Thursday +• How: Marco's calendar → book 30min Thursday morning +``` + +When the notification fires, you don't need to remember anything. The full context is right there. + +--- + +## 🚀 Features + +| Feature | What it does | +|---------|------------| +| 📅 **Google Calendar** | Real events — phone notifications, shared calendars, invites | +| 🔍 **Conflict detection** | Warns before double-booking, shows what's in the way | +| ⏱️ **Free slot finder** | Queries your actual schedule for open windows | +| 🎨 **Preference system** | "standups are always 15min bold_blue" — learns your defaults | +| 📋 **Task list** | Lightweight local tasks for timeless items | +| 👤 **User profile** | Work hours, preferred name, schedule style | +| 🔄 **Recurring events** | Full RRULE support for daily, weekly, monthly series | +| 🟡 **Prep blocks** | Optional: auto-insert a yellow prep block before meetings | +| 📦 **Bulk reschedule** | Move all events on a day in one command | +| 🗑️ **Delete** | Remove events cleanly with confirmation | +| ☀️ **Daily digest** | Shows today's events + tasks at session start | + +--- + +## 📋 Quick Examples + +### Follow-up you'd forget + +> *"remind me to follow up with Marco about API keys next Thursday morning"* + +Claude checks your calendar, matches the preference (15min, bold_blue), and creates an event with full context from this conversation. Thursday morning you get a reminder that includes everything you need to know. + +### Deadline that actually reminds you + +> *"don't let me forget — PR has to merge before Friday 5pm"* + +Claude detects the conflict (you have a code review at 3:30), shows you the conflict, and creates a bold_red event with a 2-hour reminder. Friday at 3pm it pops up. + +### Recurring standup, set once + +> *"daily standup, 9:15am weekdays, 15 minutes"* + +Claude saves the preference and creates a recurring series in Google Calendar. It learns from this that standups are 15min and bold_blue — next time you mention a standup, it uses those defaults. + +### Deep work block + +> *"need 2 hours for design doc this week — when am I free?"* + +Claude checks your actual schedule and shows you the open windows. You pick Thursday 10am, it adds a 2-hour purple block called "Deep work: design doc". + +### Meeting with optional prep + +> *"1:1 with Sarah next Monday at 2pm, add 15 min prep"* + +Claude asks if you want a prep block. You say yes. It creates the main event at 2pm and a yellow "Prep: 1:1 Sarah" at 1:45pm. + +--- + +## 🔧 Setup + +### First Time + +```bash +python3 ~/.claude/skills/assistant/scripts/calendar.py setup +``` + +This opens OAuth flow, detects your timezone, and lets you pick which calendar to use. + +### Personalize Your Preferences + +```bash +python3 ~/.claude/skills/assistant/scripts/calendar.py profile --setup +``` + +Set your work hours, preferred name, and whether you're a morning or evening person. + +--- + +## 📖 How It Works + +When you mention scheduling, deadlines, follow-ups, or tasks: + +1. **Check your schedule** — look for conflicts and find free time if needed +2. **Match preferences** — if you've set rules like "standups = 15min blue", use them +3. **Build context** — extract action items and relevant details from this conversation +4. **Show preview** — title, time, color, reminder duration, any conflicts +5. **Confirm** — you review and approve before anything gets added +6. **Link it** — every event gets the conversation session ID + transcript path + +If something already exists (duplicate titles within 7 days), Claude asks if you want to reschedule the old one or add a new entry. + +--- + +## 🎨 Colors + +- **bold_red**: deadlines, launches, critical blockers +- **bold_blue**: meetings, calls, standups +- **bold_green**: milestones, wins +- **purple**: learning, deep work +- **yellow**: prep blocks (auto-set) +- **orange**: reviews, demos, presentations +- **turquoise**: personal (health, fitness) +- **green**: personal (social, fun) + +--- + +## 📝 Task List vs Calendar + +**Use Calendar for:** +- Anything with a specific time +- Things that need notifications +- Recurring habits to track + +**Use Task List for:** +- "Remember to X" (no time) +- Shopping lists, errands +- Things without a deadline + +--- + +## ⚙️ Commands + +### Calendar + +- `status` — show config + profile +- `list` — browse events +- `add` — create an event (with conflict detection) +- `delete` — remove an event +- `reschedule` — move event(s) or bulk-shift a day +- `free` — find open time slots +- `match` — look up preference defaults for a title +- `update-prefs` — save new preference rules +- `profile` — view or update work hours, name, schedule style + +### Tasks + +- `add` — create a task with optional priority and due date +- `list` — show all tasks +- `today` / `week` / `overdue` — filtered views +- `complete` — mark a task done +- `delete` — remove a task +- `category` — organize by category +- `summary` — overview of what's pending + +Full details: see `SKILL.md`. + +--- + +## 💾 Files + +- `~/.claude/skills/assistant/config.json` — calendar ID, timezone +- `~/.claude/skills/assistant/preferences.json` — your event-type rules +- `~/.claude/skills/assistant/tasks.json` — local task list +- `~/.claude/skills/assistant/token.json` — Google OAuth token (do not commit) + +--- + +## 🤔 Common Patterns + +### Bulk reschedule (sick day) + +> *"I'm sick tomorrow, move everything to Wednesday"* + +```bash +reschedule --date "Tuesday" --shift "+1d" +``` + +### Quick free-time check + +> *"when am I free Friday?"* + +```bash +free --date "Friday" --duration 30 +``` + +### Add to your preferences + +> *"code reviews are always 30min orange"* + +```bash +update-prefs --match "code review" --duration 30 --color orange +``` + +--- + +## 🐛 Troubleshooting + +**"NOT SET UP" error?** +Run `calendar.py setup` and complete the OAuth flow. + +**Calendar not selected?** +Run `calendar.py status` to see which calendar is active. If wrong, run `setup` again. + +**Events outside work hours?** +Claude will warn before creating them. If you want to override: confirm `[y]` when prompted. + +**Conflict detected but I want it anyway?** +Claude shows the conflict and asks for confirmation. Answer `y` to proceed. + +**Prep block didn't show up?** +Prep blocks are optional — Claude asks if you want one. If the answer was "no", none will be added. + +--- + +## 🎯 Philosophy + +This skill is about **remembering context**, not just scheduling time. + +Every reminder you get includes: +- What you're supposed to do +- Why it matters +- How to do it (links, people, resources) +- The exact conversation where you decided this + +So when the notification fires, you can act immediately instead of hunting through your chat history. + +--- + +## 📄 License + +Built by [@googlarz](https://github.com/googlarz) for Claude Code. + +--- + +## 🚦 Status + +**v1.0** — Stable. Used daily for real scheduling. No maintenance commitment; contributions welcome. diff --git a/skills/assistant/SKILL.md b/skills/assistant/SKILL.md new file mode 100644 index 0000000000..9501f95306 --- /dev/null +++ b/skills/assistant/SKILL.md @@ -0,0 +1,349 @@ +--- +name: assistant +description: > + Calendar and task management skill. Invoke when scheduling, reminders, follow-ups, + deadlines, meetings, or tasks arise. Creates rich context-aware Google Calendar + entries with conversation links, manages a local task list, detects conflicts, + respects work preferences, and optionally inserts prep blocks. +--- + +# Assistant — Calendar & Task Manager + +> **Invoke with `/assistant`** — Automatically triggered when the user mentions scheduling, +> follow-ups, reminders, deadlines, meetings, tasks, or asks to "remember" something. + +--- + +## What This Skill Does + +Transforms Claude into a proactive personal assistant that: +- Writes **rich, context-aware entries** directly to Google Calendar +- Maintains a **local task list** for timeless items +- Detects **scheduling conflicts** before committing +- Respects the user's **work hours and preferences** +- Links every calendar entry back to the **exact conversation transcript** +- **Optionally adds prep blocks** when appropriate (user decides per event) + +--- + +## Session Start — Daily Digest + +At the beginning of each Claude Code session, the SessionStart hook shows: + +``` +📅 Week ahead: ← on Monday + or + Today: ← other days +``` + +This gives the user context before they start work. + +--- + +## Workflow — Step by Step + +### Step 0 — Verify setup + +```bash +python3 ~/.claude/skills/assistant/scripts/calendar.py status +``` + +- If output is `NOT SET UP`, run `setup` and pause until user completes it +- If profile is missing, suggest: *"Run `calendar.py profile --setup` to personalize your preferences"* + +--- + +### Step 1 — Check for conflicts and find free time + +Before adding anything, run both checks in parallel: + +```bash +# Check what's already there +python3 ~/.claude/skills/assistant/scripts/calendar.py list --days-back 0 --days-ahead 7 + +# Check for free slots if user needs scheduling help +python3 ~/.claude/skills/assistant/scripts/calendar.py free --date "this week" --duration 60 +``` + +If an event with the same title already exists in the next 7 days, **ask the user** whether to +reschedule it or add a new entry. + +--- + +### Step 2 — Match preferences + +```bash +python3 ~/.claude/skills/assistant/scripts/calendar.py match --title "TITLE" --description "DESCRIPTION" +``` + +Returns JSON with `duration_minutes`, `color`, `reminder_minutes`, `matched`. +Use these as defaults — the user's preferences are suggestions, not overrides. + +--- + +### Step 3 — Resolve the time + +- If the user gave a specific time → use it directly +- If vague ("tomorrow afternoon", "end of week") → resolve to concrete ISO datetime +- If no time given → ask: *"What time should I book this for?"* +- Use natural language: `"tomorrow 3pm"`, `"next Monday 10am"`, `"Friday EOD"` + +**Never assume a time the user didn't provide.** + +--- + +### Step 4 — Build a rich description + +Every calendar entry needs context so the user knows what to do when notified: + +``` +[2-3 bullet points: what was decided / what needs to happen] +• What: [specific action or topic] +• Why: [why this matters / impact if missed] +• How: [relevant links, files, people, or steps] + +──────────────────────────────────────────────── +📁 /path/to/current/project +🔗 Session: [CLAUDE_SESSION_ID] +📄 Transcript: ~/.claude/projects/.../.jsonl +🕐 Added: YYYY-MM-DD HH:MM UTC +``` + +The `build_description()` function handles the footer — you only write the bullets. + +--- + +### Step 5 — Optional: Add a prep block + +If appropriate (meetings, calls, deep work before a deadline), ask: + +> *"Should I add a 15-minute prep block before this?"* + +Only add if user confirms. If yes: + +```bash +--prep-minutes 15 +``` + +This creates a yellow "Prep: [event]" block before the main event. + +--- + +### Step 6 — Add the event (with preview) + +```bash +python3 ~/.claude/skills/assistant/scripts/calendar.py add \ + --title "TITLE" \ + --start "YYYY-MM-DDTHH:MM:SS" \ + --end "YYYY-MM-DDTHH:MM:SS" \ + --description "bullet points here" \ + [--prep-minutes 15] \ + [--recurrence "RRULE:FREQ=WEEKLY;BYDAY=MO"] +``` + +The script will: +1. Warn if outside work hours (from profile) +2. Show conflicts if any exist +3. Display a confirmation preview +4. Ask **Y/n** before writing + +Use `--yes` / `-y` only when the user has already confirmed in the chat. + +--- + +## All Commands — Quick Reference + +### Calendar Commands + +| Command | Purpose | Key flags | +|---------|---------|-----------| +| `setup` | First-time OAuth + calendar selection | — | +| `status` | Show config + profile | — | +| `list` | Browse events | `--days-back N` `--days-ahead N` `--digest` | +| `match` | Get preference for a title | `--title` `--description` | +| `add` | Create an event | `--title` `--start` `--end` `--description` `--prep-minutes` `--recurrence` `--yes` | +| `delete` | Remove an event | `--title` `--yes` | +| `reschedule` | Move event(s) | `--title` `--shift` `--new-start` OR `--date` `--shift` (bulk) | +| `free` | Find open slots | `--date` `--duration N` `--days N` | +| `profile` | View / set work hours, name, style | `--setup` `--work-start` `--work-end` `--style` | +| `update-prefs` | Add / change preference rules | `--match` `--duration` `--color` `--reminder` `--recurrence` | + +### Task Commands + +```bash +TASKS="python3 ~/.claude/skills/assistant/scripts/tasks.py" + +$TASKS add "TITLE" [--priority high|medium|low] [--due YYYY-MM-DD] [--category work] +$TASKS list +$TASKS today +$TASKS week +$TASKS overdue +$TASKS complete "title or id" +$TASKS delete "title or id" +$TASKS category [name] +$TASKS summary +``` + +--- + +## Calendar vs Task — Decision Guide + +| Situation | Use Calendar | Use Task | +|-----------|-------------|----------| +| Has a specific time | ✅ | — | +| Needs phone/desktop notification | ✅ | — | +| Involves other people (invite) | — | ✅ (email them separately) | +| "Remember to do X" (no time) | — | ✅ | +| Recurring habit to track | ✅ | — | +| Shopping / errand list | — | ✅ | +| Deadline with a due date | ✅ | — | + +When in doubt: **calendar** for time-anchored things, **task** for everything else. + +--- + +## Color Guide + +| Color | Use for | +|-------|---------| +| `bold_red` (11) | Deadlines, launches, critical blockers | +| `bold_blue` (9) | Meetings, calls, standups | +| `bold_green` (10) | Milestones, completions, wins | +| `red` (4) | Urgent reminders | +| `orange` (6) | Reviews, demos, presentations | +| `purple` (3) | Learning, courses, deep work | +| `yellow` (5) | Prep blocks (auto-set) | +| `turquoise` (7) | Personal: health, fitness | +| `green` (2) | Personal: social, fun | +| `blue` (1) | Flexible / low priority | + +--- + +## Title Format + +Good titles are **scannable in a notification**: + +| ✅ Good | ❌ Avoid | +|--------|---------| +| `Follow up: Marco — API keys` | `Follow up with Marco about the API keys` | +| `Deadline: v2.1 release` | `v2.1 needs to ship` | +| `Review: PR #204 auth refactor` | `Look at the PR` | +| `Prep: Investor call @ 2pm` | `Prepare for the investor call` | +| `1:1 Sarah — Q1 goals` | `Meeting with Sarah` | + +Pattern: `[Type]: [Subject] — [Key detail]` + +--- + +## Recurring Events + +Use RRULE strings: + +``` +RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR ← every weekday +RRULE:FREQ=WEEKLY;BYDAY=MO ← every Monday +RRULE:FREQ=MONTHLY;BYDAY=1MO ← first Monday every month +RRULE:FREQ=DAILY;COUNT=10 ← 10 times then stop +``` + +--- + +## Conflict Handling + +When `add` detects a conflict: + +``` +⚠️ Time conflict — 2 existing event(s): + • Daily standup 2026-03-01 09:00 + • Team sync 2026-03-01 09:15 + +Schedule anyway? [y/N]: +``` + +- If user says yes → pass `--yes` and proceed +- If user says no → offer to find free time: `free --date "today" --duration 30` + +--- + +## Bulk Reschedule + +Move all events on a given day: + +```bash +python3 ~/.claude/skills/assistant/scripts/calendar.py reschedule \ + --date "Tuesday" \ + --shift "+1d" +``` + +Useful: *"I'm sick tomorrow, move everything to Wednesday."* + +--- + +## 5 Sample Use Cases + +### 1 — Mid-conversation follow-up + +**User says:** *"remind me to send the invoice to client X next Tuesday"* + +1. `status` → OK +2. `match --title "Invoice: Client X"` → 30min, bold_blue, 10min reminder +3. Resolve "next Tuesday" → `2026-03-10T09:00:00` +4. `add --title "Invoice: Client X — send" --start "2026-03-10T09:00" --end "2026-03-10T09:15" --description "• Send invoice for March work\n• Client: X\n• Check outstanding items first"` +5. Preview → user confirms → event created with transcript link + +--- + +### 2 — Deadline with conflict detection + +**User says:** *"PR needs to merge by Friday 5pm"* + +1. `match --title "Deadline: PR merge"` → bold_red, 120min reminder +2. `add` → conflict: *"Retro @ 16:00 Friday"* +3. Show conflict, ask user +4. User: *"fine, add it"* → `add --yes` +5. Event added with bold_red + 2hr popup reminder + +--- + +### 3 — Recurring standup + +**User says:** *"daily standup, 9:15am weekdays, 15 minutes"* + +1. `update-prefs --match "standup" --duration 15 --recurrence "RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR"` +2. `add --title "Daily Standup" --start "2026-03-02T09:15:00" --end "2026-03-02T09:30:00" --recurrence "RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR"` +3. One command creates full recurring series + +--- + +### 4 — Find free time + deep work + +**User says:** *"need 2 hours for design doc this week — when am I free?"* + +1. `free --date "this week" --duration 120` +2. Output: *"Thu: 10:00–12:00, Fri: 14:00–17:00"* +3. User picks Thursday 10am +4. `add --title "Deep work: design doc" --start "2026-03-05T10:00" --end "2026-03-05T12:00" --color "purple"` + +--- + +### 5 — Meeting with optional prep + +**User says:** *"1:1 with Sarah next Monday at 2pm, add 15 min prep"* + +1. `match --title "1:1 Sarah"` → 45min, bold_blue +2. Conflict check → clear +3. User confirms prep block +4. `add --title "1:1 Sarah — weekly sync" --start "2026-03-09T14:00" --end "2026-03-09T14:45" --prep-minutes 15` +5. Main event + "Prep: 1:1 Sarah" at 13:45 both created + +--- + +## File Locations + +| File | Purpose | +|------|---------| +| `~/.claude/skills/assistant/config.json` | Calendar ID, timezone, profile | +| `~/.claude/skills/assistant/preferences.json` | Event-type rules (duration, color, reminder) | +| `~/.claude/skills/assistant/tasks.json` | Local task list | +| `~/.claude/skills/assistant/token.json` | Google OAuth token (do not commit) | +| `~/.claude/skills/assistant/credentials.json` | Google API credentials (do not commit) | diff --git a/skills/assistant/preferences.json b/skills/assistant/preferences.json new file mode 100644 index 0000000000..560dcd4e51 --- /dev/null +++ b/skills/assistant/preferences.json @@ -0,0 +1,97 @@ +{ + "_comment": "Assistant calendar preferences. Pattern matching is case-insensitive substring — first match wins.", + "_optional_fields": "Each pattern can also include: calendar_name (route to a different calendar), recurrence (RRULE string for recurring events).", + + "patterns": [ + { + "match": ["standup", "stand-up", "daily sync", "daily scrum", "morning sync"], + "duration_minutes": 30, + "color": "bold_blue", + "reminder_minutes": 5 + }, + { + "match": ["1:1", "one on one", "one-on-one", "1-1", "check-in with", "sync with"], + "duration_minutes": 60, + "color": "purple", + "reminder_minutes": 15 + }, + { + "match": ["interview", "hiring", "candidate"], + "duration_minutes": 60, + "color": "turquoise", + "reminder_minutes": 30 + }, + { + "match": ["review", "pr review", "code review", "design review"], + "duration_minutes": 45, + "color": "orange", + "reminder_minutes": 30 + }, + { + "match": ["deadline", "due:", "due date", "ship by", "launch", "release", "go live"], + "duration_minutes": 15, + "color": "bold_red", + "reminder_minutes": 120 + }, + { + "match": ["deploy", "deployment", "rollout"], + "duration_minutes": 60, + "color": "bold_red", + "reminder_minutes": 60 + }, + { + "match": ["follow up", "follow-up", "ping", "chase"], + "duration_minutes": 15, + "color": "yellow", + "reminder_minutes": 10 + }, + { + "match": ["decision", "decide", "vote", "sign off"], + "duration_minutes": 30, + "color": "orange", + "reminder_minutes": 30 + }, + { + "match": ["planning", "sprint planning", "roadmap", "quarterly"], + "duration_minutes": 90, + "color": "bold_green", + "reminder_minutes": 30 + }, + { + "match": ["retrospective", "retro", "post-mortem", "postmortem"], + "duration_minutes": 60, + "color": "green", + "reminder_minutes": 15 + }, + { + "match": ["demo", "presentation", "showcase"], + "duration_minutes": 30, + "color": "bold_green", + "reminder_minutes": 15 + }, + { + "match": ["bookmark", "💬", "conversation", "session save"], + "duration_minutes": 5, + "color": "purple", + "reminder_minutes": 0 + } + ], + + "defaults": { + "duration_minutes": 30, + "color": "bold_blue", + "reminder_minutes": 10 + }, + + "_examples_with_optional_fields": [ + { + "_note": "Route standup to a specific calendar and make it weekly recurring", + "match": ["example standup"], + "duration_minutes": 30, + "color": "bold_blue", + "reminder_minutes": 5, + "calendar_name": "Work", + "recurrence": "RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR" + } + ] +} diff --git a/skills/assistant/scripts/calendar.py b/skills/assistant/scripts/calendar.py new file mode 100644 index 0000000000..3609b9344e --- /dev/null +++ b/skills/assistant/scripts/calendar.py @@ -0,0 +1,1064 @@ +#!/usr/bin/env python3 +""" +Assistant Calendar — Claude Code skill backend + +Commands: + setup OAuth + auto-detect timezone + calendar selection + status Show config + profile summary + list List events (--digest for day-aware session-start output) + match Look up preferences for a title → JSON + add Add an event (conflict detection, attendees, prep block) + delete Delete an event by title + reschedule Move event(s) — single shift/new-time, or bulk by date + search Full-text search across past + future events + free Find free time slots within work hours + profile Show / update user profile (name, hours, style) + update-prefs Add or update a preference pattern +""" + +import argparse +import json +import os +import re +import sys +from datetime import datetime, timedelta, timezone +from pathlib import Path + +SKILL_DIR = Path.home() / ".claude/skills/assistant" +CONFIG_FILE = SKILL_DIR / "config.json" +PREFS_FILE = SKILL_DIR / "preferences.json" +TOKEN_FILE = SKILL_DIR / "token.json" +SCOPES = ["https://www.googleapis.com/auth/calendar"] + +CRED_CANDIDATES = [ + SKILL_DIR / "credentials.json", + Path.home() / ".openclaw/workspace/skills/proactive-claw/credentials.json", +] + +COLOR_MAP = { + "blue": "1", "green": "2", "purple": "3", "red": "4", + "yellow": "5", "orange": "6", "turquoise": "7", "gray": "8", + "bold_blue": "9", "bold_green": "10", "bold_red": "11", +} + + +# ─── Config helpers ─────────────────────────────────────────────────────────── + +def find_credentials(): + for p in CRED_CANDIDATES: + if p.exists(): + return p + return None + +def load_config() -> dict: + if CONFIG_FILE.exists(): + with open(CONFIG_FILE) as f: + return json.load(f) + return {} + +def save_config(config: dict): + CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True) + with open(CONFIG_FILE, "w") as f: + json.dump(config, f, indent=2) + +def load_preferences() -> dict: + if PREFS_FILE.exists(): + with open(PREFS_FILE) as f: + return json.load(f) + return { + "patterns": [], + "defaults": {"duration_minutes": 30, "color": "bold_blue", "reminder_minutes": 10}, + } + +def save_preferences(prefs: dict): + with open(PREFS_FILE, "w") as f: + json.dump(prefs, f, indent=2) + +def load_profile() -> dict: + return load_config().get("profile", {}) + +def match_preferences(title: str, description: str = "") -> dict: + prefs = load_preferences() + text = (title + " " + description).lower() + for pattern in prefs.get("patterns", []): + for keyword in pattern.get("match", []): + if keyword.lower() in text: + result = dict(prefs.get("defaults", {})) + result.update({k: v for k, v in pattern.items() if k != "match"}) + result["matched"] = keyword + return result + result = dict(prefs.get("defaults", {})) + result["matched"] = None + return result + + +# ─── Timezone detection ─────────────────────────────────────────────────────── + +def detect_timezone() -> str: + try: + lt = Path("/etc/localtime") + if lt.is_symlink(): + target = str(lt.resolve()) + if "zoneinfo/" in target: + return target.split("zoneinfo/", 1)[1] + except Exception: + pass + try: + local_tz = datetime.now().astimezone().tzinfo + if hasattr(local_tz, "key"): + return local_tz.key + except Exception: + pass + return datetime.now().astimezone().strftime("%Z") + + +# ─── Time parsing ───────────────────────────────────────────────────────────── + +def parse_time(time_str: str, reference: datetime = None) -> datetime: + if reference is None: + reference = datetime.now().astimezone() + for fmt in [ + "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M", + "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", + "%Y-%m-%d", + ]: + try: + dt = datetime.strptime(time_str, fmt) + return dt.replace(tzinfo=reference.tzinfo) + except ValueError: + continue + try: + import dateparser + dt = dateparser.parse(time_str, settings={ + "PREFER_DATES_FROM": "future", + "RETURN_AS_TIMEZONE_AWARE": True, + "RELATIVE_BASE": reference.replace(tzinfo=None), + }) + if dt: + return dt + except ImportError: + pass + raise ValueError( + f"Cannot parse time: '{time_str}'.\n" + "Use ISO 8601 (2026-03-01T15:00) or install dateparser:\n" + " pip3 install dateparser" + ) + + +# ─── Google Calendar service ────────────────────────────────────────────────── + +def get_service(): + try: + from google.oauth2.credentials import Credentials # noqa + from google.auth.transport.requests import Request # noqa + from google_auth_oauthlib.flow import InstalledAppFlow # noqa + from googleapiclient.discovery import build # noqa + except ImportError: + print("ERROR: Missing Google API libraries.") + print("Run: pip3 install google-api-python-client google-auth-oauthlib google-auth-httplib2") + sys.exit(1) + + from google.oauth2.credentials import Credentials + from google.auth.transport.requests import Request + from google_auth_oauthlib.flow import InstalledAppFlow + from googleapiclient.discovery import build + + creds = None + if TOKEN_FILE.exists(): + creds = Credentials.from_authorized_user_file(str(TOKEN_FILE), SCOPES) + + if not creds or not creds.valid: + if creds and creds.expired and creds.refresh_token: + try: + creds.refresh(Request()) + except Exception: + creds = None + if not creds or not creds.valid: + creds_file = find_credentials() + if not creds_file: + print("ERROR: No credentials.json found. Place it at:") + for p in CRED_CANDIDATES: + print(f" {p}") + sys.exit(1) + flow = InstalledAppFlow.from_client_secrets_file(str(creds_file), SCOPES) + creds = flow.run_local_server(port=0) + + SKILL_DIR.mkdir(parents=True, exist_ok=True) + with open(TOKEN_FILE, "w") as f: + f.write(creds.to_json()) + + return build("calendar", "v3", credentials=creds) + + +def resolve_calendar_id(service, name_or_id: str) -> str: + if "@" in name_or_id or name_or_id == "primary": + return name_or_id + for cal in service.calendarList().list().execute().get("items", []): + if cal.get("summary", "").lower() == name_or_id.lower(): + return cal["id"] + return name_or_id + +def effective_calendar_id(pref: dict, config: dict, service) -> str: + cal_name = pref.get("calendar_name") + if cal_name: + return resolve_calendar_id(service, cal_name) + return config.get("calendar_id", "primary") + +def check_conflicts(service, calendar_id: str, start_dt: datetime, end_dt: datetime) -> list: + """Return events that overlap with the given time range.""" + result = service.events().list( + calendarId=calendar_id, + timeMin=start_dt.isoformat(), + timeMax=end_dt.isoformat(), + singleEvents=True, + orderBy="startTime", + maxResults=10, + ).execute() + return result.get("items", []) + + +# ─── Description builder ────────────────────────────────────────────────────── + +def build_description(user_text: str) -> str: + lines = [user_text.rstrip()] if user_text.strip() else [] + lines.append("") + lines.append("─" * 44) + project = os.environ.get("PWD") or os.getcwd() + session_id = os.environ.get("CLAUDE_SESSION_ID", "") + lines.append(f"📁 {project}") + if session_id: + encoded = project.replace("/", "-") + transcript = str(Path.home() / f".claude/projects/{encoded}/{session_id}.jsonl") + lines.append(f"🔗 Session: {session_id}") + lines.append(f"📄 Transcript: {transcript}") + lines.append(f"🕐 Added: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}") + return "\n".join(lines) + + +# ─── Commands ───────────────────────────────────────────────────────────────── + +def cmd_setup(_args): + print("🗓️ Assistant Calendar — Setup") + print("=" * 45) + + creds_file = find_credentials() + if not creds_file: + print("\nNo credentials.json found.") + print("Steps:") + print(" 1. https://console.cloud.google.com → new project → Enable 'Google Calendar API'") + print(" 2. Credentials → Create OAuth 2.0 Client ID (Desktop) → Download JSON") + print(f" 3. Save to: {CRED_CANDIDATES[0]}") + sys.exit(1) + print(f"✅ Credentials: {creds_file}\n") + + service = get_service() + print("✅ Google Calendar authenticated\n") + + tz = detect_timezone() + print(f"✅ Detected timezone: {tz}") + tz_override = input(" Press Enter to accept, or type a different IANA timezone: ").strip() + if tz_override: + tz = tz_override + print() + + calendars = service.calendarList().list().execute().get("items", []) + print(" 1. ➕ Create a new 'Assistant' calendar ← recommended") + for i, cal in enumerate(calendars, 1): + marker = " (primary)" if cal.get("primary") else "" + print(f" {i+1:2}. {cal['summary']}{marker}") + + try: + raw = input(f"\nChoose [1-{len(calendars)+1}] (Enter = create new): ").strip() + idx = int(raw) - 1 if raw else 0 + except (ValueError, KeyboardInterrupt): + print("\nCancelled.") + sys.exit(1) + + if idx == 0: + cal = service.calendars().insert(body={ + "summary": "Assistant", + "description": "Entries created by Claude Code — your AI assistant", + }).execute() + try: + service.calendarList().patch(calendarId=cal["id"], body={"colorId": "9"}).execute() + except Exception: + pass + calendar_id = cal["id"] + calendar_name = "Assistant" + print("\n✅ Created 'Assistant' calendar") + elif 1 <= idx <= len(calendars): + calendar_id = calendars[idx - 1]["id"] + calendar_name = calendars[idx - 1]["summary"] + print(f"\n✅ Using '{calendar_name}'") + else: + print("Invalid choice.") + sys.exit(1) + + config = load_config() + config.update({ + "calendar_id": calendar_id, + "calendar_name": calendar_name, + "timezone": tz, + "setup_at": datetime.now(timezone.utc).isoformat(), + }) + save_config(config) + print(f"💾 Config saved to {CONFIG_FILE}") + print("\nNext: run 'calendar.py profile --setup' to personalise the assistant.") + + +def cmd_status(_args): + config = load_config() + if not config.get("calendar_id"): + print("NOT SET UP — run: python3 calendar.py setup") + sys.exit(1) + print("✅ Assistant Calendar — ready") + print(f" Calendar : {config.get('calendar_name', '?')} ({config['calendar_id']})") + print(f" Timezone : {config.get('timezone', 'UTC')}") + print(f" Set up : {config.get('setup_at', '?')[:10]}") + profile = config.get("profile", {}) + if profile: + wh = profile.get("work_hours", {}) + name = profile.get("preferred_name") or profile.get("name", "") + print(f" Profile : {name} | {wh.get('start','09:00')}–{wh.get('end','18:00')} | {profile.get('working_style','')}") + else: + print(" Profile : not set — run: calendar.py profile --setup") + + +def cmd_list(args): + config = load_config() + if not config.get("calendar_id"): + print("NOT SET UP — run: python3 calendar.py setup") + sys.exit(1) + + # Digest mode: show week on Monday, today otherwise + digest = getattr(args, "digest", False) + if digest: + today_wd = datetime.now().weekday() + if today_wd == 0: # Monday + args.days_back = 0 + args.days_ahead = 7 + print("📅 Week ahead:\n") + else: + args.days_back = 0 + args.days_ahead = 1 + + service = get_service() + now = datetime.now(timezone.utc) + time_min = (now - timedelta(days=args.days_back)).isoformat() + time_max = (now + timedelta(days=args.days_ahead)).isoformat() + + result = service.events().list( + calendarId=config["calendar_id"], + timeMin=time_min, + timeMax=time_max, + singleEvents=True, + orderBy="startTime", + maxResults=50, + ).execute() + + events = result.get("items", []) + if not events: + if not digest: + print(f"No events in the past {args.days_back}d / next {args.days_ahead}d.") + return + + if not digest: + print(f"Assistant calendar — past {args.days_back}d / next {args.days_ahead}d ({config.get('timezone','UTC')})\n") + + for ev in events: + ev_id = ev.get("id", "") + title = ev.get("summary", "(no title)") + dt_str = ev.get("start", {}).get("dateTime") or ev.get("start", {}).get("date", "") + try: + dt = datetime.fromisoformat(dt_str.replace("Z", "+00:00")) + display = dt.strftime("%a %b %-d %H:%M") + past = "✓ " if dt < now else " " + except Exception: + display = dt_str + past = " " + print(f"{past}{display} {title}") + if not digest: + print(f" id: {ev_id[:16]}") + + +def cmd_match(args): + result = match_preferences(args.title, getattr(args, "description", "") or "") + print(json.dumps(result, indent=2)) + + +def cmd_add(args): + config = load_config() + if not config.get("calendar_id"): + print("ERROR: Not set up. Run: python3 calendar.py setup") + sys.exit(1) + + service = get_service() + pref = match_preferences(args.title, args.description or "") + calendar_id = effective_calendar_id(pref, config, service) + tz_str = args.timezone or config.get("timezone", "UTC") + + ref = datetime.now().astimezone() + try: + start_dt = parse_time(args.start, ref) + end_dt = parse_time(args.end, ref) + except ValueError as e: + print(f"ERROR: {e}") + sys.exit(1) + + start_iso = start_dt.strftime("%Y-%m-%dT%H:%M:%S") + end_iso = end_dt.strftime("%Y-%m-%dT%H:%M:%S") + + color = args.color or pref.get("color", "bold_blue") + reminder = args.reminder if args.reminder is not None else pref.get("reminder_minutes", 10) + recurrence = args.recurrence or pref.get("recurrence", "") + cal_display = pref.get("calendar_name") or config.get("calendar_name", calendar_id) + + # Work hours warning + profile = load_profile() + if profile: + wh = profile.get("work_hours", {}) + no_before = profile.get("no_schedule_before", wh.get("start", "")) + no_after = profile.get("no_schedule_after", wh.get("end", "")) + if no_before: + lh, lm = map(int, no_before.split(":")) + if start_dt.hour < lh or (start_dt.hour == lh and start_dt.minute < lm): + print(f"⚠️ Note: this is before your usual start ({no_before})") + if no_after: + lh, lm = map(int, no_after.split(":")) + if start_dt.hour > lh or (start_dt.hour == lh and start_dt.minute > lm): + print(f"⚠️ Note: this is after your preferred cutoff ({no_after})") + + # Conflict detection + conflicts = check_conflicts(service, calendar_id, start_dt, end_dt) + if conflicts: + print(f"\n⚠️ Time conflict — {len(conflicts)} existing event(s):") + for ev in conflicts: + ev_dt = ev.get("start", {}).get("dateTime", "")[:16] + print(f" • {ev.get('summary', '(no title)')} {ev_dt}") + if not args.yes: + try: + if input("\nSchedule anyway? [y/N]: ").strip().lower() != "y": + print("Cancelled.") + sys.exit(0) + except KeyboardInterrupt: + print("\nCancelled.") + sys.exit(0) + + # Attendees + attendees_str = getattr(args, "attendees", "") or "" + attendees = [e.strip() for e in attendees_str.split(",") if e.strip()] + + # Prep block + prep_minutes = getattr(args, "prep_minutes", 0) or 0 + + # Confirm preview + if not args.yes: + print(f"\n📅 Preview") + print(f" Title : {args.title}") + print(f" When : {start_iso} → {end_iso} ({tz_str})") + print(f" Calendar : {cal_display}") + print(f" Color : {color}") + print(f" Reminder : {reminder} min before") + if recurrence: + print(f" Repeats : {recurrence}") + if attendees: + print(f" Invites : {', '.join(attendees)} (sends email invitations)") + if prep_minutes: + print(f" Prep : +{prep_minutes}min prep block added before") + if pref.get("matched"): + print(f" Pref : matched '{pref['matched']}'") + print() + try: + if input("Add this? [Y/n]: ").strip().lower() == "n": + print("Cancelled.") + sys.exit(0) + except KeyboardInterrupt: + print("\nCancelled.") + sys.exit(0) + + event_body = { + "summary": args.title, + "description": build_description(args.description or ""), + "start": {"dateTime": start_iso, "timeZone": tz_str}, + "end": {"dateTime": end_iso, "timeZone": tz_str}, + "colorId": COLOR_MAP.get(color, "9"), + "reminders": { + "useDefault": False, + "overrides": [{"method": "popup", "minutes": reminder}], + }, + } + if recurrence: + event_body["recurrence"] = [recurrence] if isinstance(recurrence, str) else recurrence + if attendees: + event_body["attendees"] = [{"email": e} for e in attendees] + + result = service.events().insert(calendarId=calendar_id, body=event_body).execute() + link = result.get("htmlLink", "") + print(f"✅ Added: {args.title}") + print(f" 📅 {start_iso} → {end_iso} ({tz_str})") + print(f" 📆 {cal_display}") + if pref.get("matched"): + print(f" (used '{pref['matched']}' preference)") + if attendees: + print(f" 📧 Invited: {', '.join(attendees)}") + if link: + print(f" 🔗 {link}") + + # Auto prep block + if prep_minutes > 0: + prep_end = start_dt + prep_start = start_dt - timedelta(minutes=prep_minutes) + prep_body = { + "summary": f"Prep: {args.title}", + "description": f"Preparation time for: {args.title}", + "start": {"dateTime": prep_start.strftime("%Y-%m-%dT%H:%M:%S"), "timeZone": tz_str}, + "end": {"dateTime": prep_end.strftime("%Y-%m-%dT%H:%M:%S"), "timeZone": tz_str}, + "colorId": COLOR_MAP.get("yellow", "5"), + "reminders": {"useDefault": False, "overrides": []}, + } + service.events().insert(calendarId=calendar_id, body=prep_body).execute() + print(f" + Prep block: {prep_start.strftime('%H:%M')} → {prep_end.strftime('%H:%M')}") + + +def cmd_delete(args): + config = load_config() + if not config.get("calendar_id"): + print("NOT SET UP"); sys.exit(1) + + service = get_service() + now = datetime.now(timezone.utc) + + result = service.events().list( + calendarId=config["calendar_id"], + timeMin=(now - timedelta(days=7)).isoformat(), + timeMax=(now + timedelta(days=90)).isoformat(), + q=args.title, + singleEvents=True, + orderBy="startTime", + maxResults=5, + ).execute() + + events = result.get("items", []) + if not events: + print(f"No event found matching: '{args.title}'") + sys.exit(1) + + if len(events) > 1: + print("Multiple matches:") + for i, ev in enumerate(events, 1): + dt = ev.get("start", {}).get("dateTime", "")[:16] + print(f" {i}. {ev.get('summary')} — {dt}") + try: + event = events[int(input("Choose [1-N]: ").strip()) - 1] + except (ValueError, IndexError, KeyboardInterrupt): + print("Cancelled."); sys.exit(1) + else: + event = events[0] + + title = event.get("summary", "") + dt_str = event.get("start", {}).get("dateTime", "")[:16] + print(f"Delete: {title} ({dt_str})") + + if not args.yes: + try: + if input("Confirm? [Y/n]: ").strip().lower() == "n": + print("Cancelled."); sys.exit(0) + except KeyboardInterrupt: + print("\nCancelled."); sys.exit(0) + + service.events().delete(calendarId=config["calendar_id"], eventId=event["id"]).execute() + print(f"✅ Deleted: {title}") + + +def cmd_reschedule(args): + config = load_config() + if not config.get("calendar_id"): + print("NOT SET UP"); sys.exit(1) + + service = get_service() + now = datetime.now(timezone.utc) + ref = datetime.now().astimezone() + + # ── Bulk mode: move all events on a given date ───────────────────────── + if args.date: + try: + day = parse_time(args.date, ref).replace(hour=0, minute=0, second=0, microsecond=0) + except ValueError as e: + print(f"ERROR: {e}"); sys.exit(1) + + day_end = day + timedelta(days=1) + result = service.events().list( + calendarId=config["calendar_id"], + timeMin=day.isoformat(), + timeMax=day_end.isoformat(), + singleEvents=True, + orderBy="startTime", + ).execute() + + events = result.get("items", []) + if not events: + print(f"No events on {day.strftime('%a %b %-d')}.") + sys.exit(0) + + if not args.shift: + print("Provide --shift for bulk reschedule (e.g. +1d, +2h, -30m)") + sys.exit(1) + + m = re.match(r'^([+-]?)(\d+)([hmd])$', args.shift.strip()) + if not m: + print(f"Invalid shift '{args.shift}'. Use: +2h +30m +1d -1h"); sys.exit(1) + sign = -1 if m.group(1) == "-" else 1 + n = int(m.group(2)) + unit = m.group(3) + delta = timedelta( + hours=n*sign if unit == "h" else 0, + minutes=n*sign if unit == "m" else 0, + days=n*sign if unit == "d" else 0, + ) + + print(f"Bulk reschedule — {len(events)} event(s) on {day.strftime('%a %b %-d')} by {args.shift}") + for ev in events: + print(f" • {ev.get('summary')} — {ev.get('start',{}).get('dateTime','')[:16]}") + + if not args.yes: + try: + if input("\nConfirm? [Y/n]: ").strip().lower() == "n": + print("Cancelled."); sys.exit(0) + except KeyboardInterrupt: + print("\nCancelled."); sys.exit(0) + + for ev in events: + old_s = datetime.fromisoformat(ev["start"]["dateTime"].replace("Z", "+00:00")) + old_e = datetime.fromisoformat(ev["end"]["dateTime"].replace("Z", "+00:00")) + tz_ev = ev["start"].get("timeZone") or config.get("timezone", "UTC") + new_s = old_s + delta + new_e = old_e + delta + service.events().patch( + calendarId=config["calendar_id"], + eventId=ev["id"], + body={ + "start": {"dateTime": new_s.strftime("%Y-%m-%dT%H:%M:%S"), "timeZone": tz_ev}, + "end": {"dateTime": new_e.strftime("%Y-%m-%dT%H:%M:%S"), "timeZone": tz_ev}, + }, + ).execute() + print(f" ✅ {ev.get('summary')} → {new_s.strftime('%a %b %-d %H:%M')}") + return + + # ── Single event reschedule ───────────────────────────────────────────── + if not args.title: + print("Provide --title (single) or --date (bulk)") + sys.exit(1) + + result = service.events().list( + calendarId=config["calendar_id"], + timeMin=(now - timedelta(days=7)).isoformat(), + timeMax=(now + timedelta(days=30)).isoformat(), + q=args.title, + singleEvents=True, + orderBy="startTime", + maxResults=5, + ).execute() + + events = result.get("items", []) + if not events: + print(f"No event found matching: '{args.title}'") + sys.exit(1) + + if len(events) > 1: + print("Multiple matches:") + for i, ev in enumerate(events, 1): + dt = ev.get("start", {}).get("dateTime", "") + print(f" {i}. [{ev['id'][:8]}] {ev.get('summary')} — {dt}") + try: + event = events[int(input("Choose: ").strip()) - 1] + except (ValueError, IndexError, KeyboardInterrupt): + print("Cancelled."); sys.exit(1) + else: + event = events[0] + + ev_id = event["id"] + title = event.get("summary", "") + old_start_str = event["start"].get("dateTime", "") + old_end_str = event["end"].get("dateTime", "") + tz_str = event["start"].get("timeZone") or config.get("timezone", "UTC") + old_start = datetime.fromisoformat(old_start_str.replace("Z", "+00:00")) + old_end = datetime.fromisoformat(old_end_str.replace("Z", "+00:00")) + duration = old_end - old_start + + if args.shift: + m = re.match(r'^([+-]?)(\d+)([hmd])$', args.shift.strip()) + if not m: + print(f"Invalid shift '{args.shift}'. Use: +2h +30m +1d -1h"); sys.exit(1) + sign = -1 if m.group(1) == "-" else 1 + n = int(m.group(2)) + unit = m.group(3) + delta = timedelta( + hours=n*sign if unit == "h" else 0, + minutes=n*sign if unit == "m" else 0, + days=n*sign if unit == "d" else 0, + ) + new_start = old_start + delta + new_end = new_start + duration + elif args.new_start: + new_start = parse_time(args.new_start, ref) + new_end = new_start + duration + else: + print("Provide --shift (+2h / +30m / +1d) or --new-start 'tomorrow 3pm'") + sys.exit(1) + + new_start_iso = new_start.strftime("%Y-%m-%dT%H:%M:%S") + new_end_iso = new_end.strftime("%Y-%m-%dT%H:%M:%S") + + print(f"Rescheduling: {title}") + print(f" From: {old_start_str[:16]}") + print(f" To: {new_start_iso} ({tz_str})") + + if not args.yes: + try: + if input("Confirm? [Y/n]: ").strip().lower() == "n": + print("Cancelled."); sys.exit(0) + except KeyboardInterrupt: + print("\nCancelled."); sys.exit(0) + + service.events().patch( + calendarId=config["calendar_id"], + eventId=ev_id, + body={ + "start": {"dateTime": new_start_iso, "timeZone": tz_str}, + "end": {"dateTime": new_end_iso, "timeZone": tz_str}, + }, + ).execute() + print(f"✅ Rescheduled: {title} → {new_start_iso}") + + +def cmd_search(args): + config = load_config() + if not config.get("calendar_id"): + print("NOT SET UP"); sys.exit(1) + + service = get_service() + now = datetime.now(timezone.utc) + + result = service.events().list( + calendarId=config["calendar_id"], + timeMin=(now - timedelta(days=args.days_back)).isoformat(), + timeMax=(now + timedelta(days=args.days_ahead)).isoformat(), + q=args.query, + singleEvents=True, + orderBy="startTime", + maxResults=25, + ).execute() + + events = result.get("items", []) + if not events: + print(f"No events found matching: '{args.query}'") + return + + print(f"Search: '{args.query}' — {len(events)} result(s)\n") + for ev in events: + dt_str = ev.get("start", {}).get("dateTime") or ev.get("start", {}).get("date", "") + try: + dt = datetime.fromisoformat(dt_str.replace("Z", "+00:00")) + display = dt.strftime("%a %b %-d %H:%M") + past = "✓ " if dt < now else " " + except Exception: + display = dt_str + past = " " + print(f"{past}{display} {ev.get('summary', '(no title)')}") + desc = ev.get("description", "") + if desc: + for line in desc.split("\n"): + line = line.strip() + if line and not line.startswith("─"): + print(f" {line[:80]}") + break + + +def cmd_free(args): + config = load_config() + if not config.get("calendar_id"): + print("NOT SET UP"); sys.exit(1) + + service = get_service() + profile = load_profile() + ref = datetime.now().astimezone() + + # Resolve date + span + date_str = (args.date or "today").lower() + if date_str in ("today", ""): + base = ref.replace(hour=0, minute=0, second=0, microsecond=0) + span_days = 1 + elif date_str == "tomorrow": + base = (ref + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0) + span_days = 1 + elif date_str == "this week": + base = (ref - timedelta(days=ref.weekday())).replace(hour=0, minute=0, second=0, microsecond=0) + span_days = 5 + elif date_str == "next week": + base = (ref - timedelta(days=ref.weekday()) + timedelta(weeks=1)).replace(hour=0, minute=0, second=0, microsecond=0) + span_days = 5 + else: + try: + base = parse_time(date_str, ref).replace(hour=0, minute=0, second=0, microsecond=0) + span_days = 1 + except ValueError as e: + print(f"ERROR: {e}"); sys.exit(1) + + if args.days: + span_days = args.days + + duration_min = args.duration + wh = profile.get("work_hours", {}) + work_start = wh.get("start", "09:00") + work_end = wh.get("end", "18:00") + ws_h, ws_m = map(int, work_start.split(":")) + we_h, we_m = map(int, work_end.split(":")) + work_days = profile.get("work_days", [0, 1, 2, 3, 4]) # 0=Mon + + print(f"🔍 Free slots ≥ {duration_min}min | work hours: {work_start}–{work_end}\n") + + # Collect unique calendar IDs for freebusy query + cal_ids = list({config["calendar_id"], "primary"}) + + found_any = False + for day_offset in range(span_days): + day = base + timedelta(days=day_offset) + if day.weekday() not in work_days: + continue + + day_start = day.replace(hour=ws_h, minute=ws_m, second=0, microsecond=0) + day_end = day.replace(hour=we_h, minute=we_m, second=0, microsecond=0) + + # Use freebusy API — checks ALL queried calendars at once + fb = service.freebusy().query(body={ + "timeMin": day_start.isoformat(), + "timeMax": day_end.isoformat(), + "items": [{"id": cid} for cid in cal_ids], + }).execute() + + busy = [] + for cal_data in fb.get("calendars", {}).values(): + for slot in cal_data.get("busy", []): + try: + ev_s = datetime.fromisoformat(slot["start"].replace("Z", "+00:00")).astimezone(day_start.tzinfo) + ev_e = datetime.fromisoformat(slot["end"].replace("Z", "+00:00")).astimezone(day_start.tzinfo) + busy.append((ev_s, ev_e)) + except Exception: + continue + + # Compute free gaps + slots = [] + cursor = day_start + for ev_s, ev_e in sorted(set(busy), key=lambda x: x[0]): + gap = int((ev_s - cursor).total_seconds() / 60) + if gap >= duration_min: + slots.append((cursor, ev_s)) + cursor = max(cursor, ev_e) + gap = int((day_end - cursor).total_seconds() / 60) + if gap >= duration_min: + slots.append((cursor, day_end)) + + if slots: + found_any = True + print(f" {day.strftime('%a %b %-d')}:") + for s, e in slots: + gap_min = int((e - s).total_seconds() / 60) + print(f" {s.strftime('%H:%M')} – {e.strftime('%H:%M')} ({gap_min}min free)") + + if not found_any: + print(f"No free slots ≥ {duration_min}min found.") + + +def cmd_profile(args): + config = load_config() + profile = config.get("profile", {}) + + has_flags = any([ + getattr(args, "setup", False), + getattr(args, "name", None), + getattr(args, "work_start", None), + getattr(args, "work_end", None), + getattr(args, "style", None), + getattr(args, "no_before", None), + getattr(args, "no_after", None), + ]) + + if not has_flags: + if not profile: + print("No profile set. Run: calendar.py profile --setup") + else: + print("👤 Profile:") + print(json.dumps(profile, indent=2)) + return + + if getattr(args, "setup", False): + print("👤 Profile Setup") + print("=" * 40) + prev_wh = profile.get("work_hours", {}) + name = input(f"Name [{profile.get('name','')}]: ").strip() or profile.get("name", "") + pref_nm = input(f"Preferred name [{profile.get('preferred_name', name)}]: ").strip() or profile.get("preferred_name", name) + ws = input(f"Work start [{prev_wh.get('start','09:00')}]: ").strip() or prev_wh.get("start", "09:00") + we = input(f"Work end [{prev_wh.get('end','18:00')}]: ").strip() or prev_wh.get("end", "18:00") + style = input(f"Style (morning/evening/flexible) [{profile.get('working_style','flexible')}]: ").strip() or profile.get("working_style", "flexible") + no_bef = input(f"Don't schedule before [{profile.get('no_schedule_before', ws)}]: ").strip() or profile.get("no_schedule_before", ws) + no_aft = input(f"Don't schedule after [{profile.get('no_schedule_after','20:00')}]: ").strip() or profile.get("no_schedule_after", "20:00") + + profile.update({ + "name": name, + "preferred_name": pref_nm, + "work_hours": {"start": ws, "end": we}, + "working_style": style, + "no_schedule_before": no_bef, + "no_schedule_after": no_aft, + "work_days": profile.get("work_days", [0, 1, 2, 3, 4]), + }) + config["profile"] = profile + save_config(config) + print(f"\n✅ Profile saved.") + return + + # Flag-based updates + if getattr(args, "name", None): profile["name"] = args.name + if getattr(args, "work_start", None): profile.setdefault("work_hours", {})["start"] = args.work_start + if getattr(args, "work_end", None): profile.setdefault("work_hours", {})["end"] = args.work_end + if getattr(args, "style", None): profile["working_style"] = args.style + if getattr(args, "no_before", None): profile["no_schedule_before"] = args.no_before + if getattr(args, "no_after", None): profile["no_schedule_after"] = args.no_after + + config["profile"] = profile + save_config(config) + print("✅ Profile updated:") + print(json.dumps(profile, indent=2)) + + +def cmd_update_prefs(args): + prefs = load_preferences() + patterns = prefs.get("patterns", []) + + existing_idx = None + for i, p in enumerate(patterns): + if args.match.lower() in [k.lower() for k in p.get("match", [])]: + existing_idx = i + break + + if existing_idx is not None: + pattern = patterns[existing_idx] + print(f"Updating existing rule for '{args.match}':") + else: + pattern = {"match": [args.match]} + print(f"Creating new rule for '{args.match}':") + + if args.duration is not None: pattern["duration_minutes"] = args.duration + if args.color: pattern["color"] = args.color + if args.reminder is not None: pattern["reminder_minutes"] = args.reminder + if args.calendar_name: pattern["calendar_name"] = args.calendar_name + if args.recurrence: pattern["recurrence"] = args.recurrence + + print(json.dumps(pattern, indent=2)) + + if existing_idx is not None: + patterns[existing_idx] = pattern + else: + patterns.append(pattern) + + prefs["patterns"] = patterns + save_preferences(prefs) + print(f"✅ Saved to {PREFS_FILE}") + + +# ─── CLI ────────────────────────────────────────────────────────────────────── + +def main(): + parser = argparse.ArgumentParser(description="Assistant Calendar — Claude Code skill backend") + sub = parser.add_subparsers(dest="command") + + sub.add_parser("setup", help="OAuth + timezone + calendar setup") + sub.add_parser("status", help="Show config + profile summary") + + li = sub.add_parser("list", help="List events") + li.add_argument("--days-back", type=int, default=3) + li.add_argument("--days-ahead", type=int, default=7) + li.add_argument("--digest", action="store_true", help="Day-aware: week on Monday, today otherwise") + + m = sub.add_parser("match", help="Match preferences for a title → JSON") + m.add_argument("--title", required=True) + m.add_argument("--description", default="") + + p = sub.add_parser("add", help="Add a calendar event") + p.add_argument("--title", required=True) + p.add_argument("--start", required=True) + p.add_argument("--end", required=True) + p.add_argument("--description", default="") + p.add_argument("--timezone", default="") + p.add_argument("--color", default="") + p.add_argument("--reminder", type=int, default=None) + p.add_argument("--recurrence", default="", help="RRULE string") + p.add_argument("--attendees", default="", help="Comma-separated emails") + p.add_argument("--prep-minutes", type=int, default=0, dest="prep_minutes", + help="Auto-add a prep block N min before the event") + p.add_argument("--yes", "-y", action="store_true") + + de = sub.add_parser("delete", help="Delete an event by title") + de.add_argument("--title", required=True) + de.add_argument("--yes", "-y", action="store_true") + + r = sub.add_parser("reschedule", help="Move event(s)") + r.add_argument("--title", default="", help="Title keyword (single event)") + r.add_argument("--date", default="", help="Date for bulk move (e.g. 'Tuesday', '2026-03-10')") + r.add_argument("--shift", default="", help="+2h +30m +1d -1h") + r.add_argument("--new-start", default="", dest="new_start", help="New start (single only)") + r.add_argument("--yes", "-y", action="store_true") + + se = sub.add_parser("search", help="Search events by keyword") + se.add_argument("query") + se.add_argument("--days-back", type=int, default=90) + se.add_argument("--days-ahead", type=int, default=90) + + fr = sub.add_parser("free", help="Find free time slots within work hours") + fr.add_argument("--date", default="today", + help="today|tomorrow|this week|next week|YYYY-MM-DD") + fr.add_argument("--duration", type=int, default=30, + help="Minimum slot length in minutes (default 30)") + fr.add_argument("--days", type=int, default=0, + help="Override number of days to scan") + + pr = sub.add_parser("profile", help="Show or update user profile") + pr.add_argument("--setup", action="store_true", help="Interactive setup wizard") + pr.add_argument("--name", default=None) + pr.add_argument("--work-start", default=None, dest="work_start", help="HH:MM") + pr.add_argument("--work-end", default=None, dest="work_end", help="HH:MM") + pr.add_argument("--style", default=None, help="morning|evening|flexible") + pr.add_argument("--no-before", default=None, dest="no_before", help="Don't schedule before HH:MM") + pr.add_argument("--no-after", default=None, dest="no_after", help="Don't schedule after HH:MM") + + up = sub.add_parser("update-prefs", help="Add or update a preference rule") + up.add_argument("--match", required=True) + up.add_argument("--duration", type=int, default=None) + up.add_argument("--color", default="") + up.add_argument("--reminder", type=int, default=None) + up.add_argument("--calendar-name", default="", dest="calendar_name") + up.add_argument("--recurrence", default="") + + args = parser.parse_args() + dispatch = { + "setup": cmd_setup, + "status": cmd_status, + "list": cmd_list, + "match": cmd_match, + "add": cmd_add, + "delete": cmd_delete, + "reschedule": cmd_reschedule, + "search": cmd_search, + "free": cmd_free, + "profile": cmd_profile, + "update-prefs": cmd_update_prefs, + } + fn = dispatch.get(args.command) + if fn: + fn(args) + else: + parser.print_help() + + +if __name__ == "__main__": + main() diff --git a/skills/assistant/scripts/mcp_server.py b/skills/assistant/scripts/mcp_server.py new file mode 100644 index 0000000000..b57348f2af --- /dev/null +++ b/skills/assistant/scripts/mcp_server.py @@ -0,0 +1,310 @@ +#!/usr/bin/env python3 +""" +Assistant Calendar — MCP Server + +Exposes all calendar operations as native Claude tools. +When connected via MCP, Claude uses these directly instead of shelling out to Python — +faster, no string parsing, works in any MCP-compatible client. + +Install: pip3 install mcp +Activate: add to ~/.claude/settings.json (see bottom of this file) +""" + +import json +import sys +from datetime import datetime, timedelta, timezone +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent)) + +try: + import calendar as cal_module +except ImportError as e: + print(f"ERROR importing calendar module: {e}", file=sys.stderr) + sys.exit(1) + +try: + from mcp.server import Server + from mcp.server.stdio import stdio_server + from mcp import types +except ImportError: + print("ERROR: MCP SDK not installed.", file=sys.stderr) + print("Install: pip3 install mcp", file=sys.stderr) + sys.exit(1) + + +app = Server("assistant-calendar") + + +@app.list_tools() +async def list_tools() -> list[types.Tool]: + return [ + types.Tool( + name="calendar_add", + description=( + "Add an event to the Assistant calendar. " + "Automatically looks up preferences (duration, color, reminder) for the event type. " + "Appends project path + session transcript link to description." + ), + inputSchema={ + "type": "object", + "required": ["title", "start", "end"], + "properties": { + "title": {"type": "string", "description": "Event title"}, + "start": {"type": "string", "description": "Start datetime ISO 8601"}, + "end": {"type": "string", "description": "End datetime ISO 8601"}, + "description": {"type": "string", "description": "Context from the conversation"}, + "color": {"type": "string", "description": "Override color"}, + "reminder": {"type": "integer","description": "Override reminder minutes"}, + "recurrence": {"type": "string", "description": "RRULE string for recurring events"}, + }, + }, + ), + types.Tool( + name="calendar_list", + description="List upcoming and recent Assistant calendar events. Call before adding to avoid duplicates.", + inputSchema={ + "type": "object", + "properties": { + "days_back": {"type": "integer", "default": 3, "description": "Days to look back"}, + "days_ahead": {"type": "integer", "default": 7, "description": "Days to look ahead"}, + }, + }, + ), + types.Tool( + name="calendar_reschedule", + description="Move an Assistant calendar event by a relative shift or to a specific new time.", + inputSchema={ + "type": "object", + "required": ["title"], + "properties": { + "title": {"type": "string", "description": "Event title to search for"}, + "shift": {"type": "string", "description": "Relative shift: +2h, +30m, +1d, -1h"}, + "new_start": {"type": "string", "description": "New absolute start datetime ISO 8601"}, + }, + }, + ), + types.Tool( + name="calendar_match_prefs", + description="Look up preference rules for an event title (duration, color, reminder).", + inputSchema={ + "type": "object", + "required": ["title"], + "properties": { + "title": {"type": "string"}, + }, + }, + ), + types.Tool( + name="calendar_update_prefs", + description="Add or update a preference rule. Use when user says 'always book X min for Y'.", + inputSchema={ + "type": "object", + "required": ["match"], + "properties": { + "match": {"type": "string", "description": "Keyword to match"}, + "duration": {"type": "integer", "description": "Duration in minutes"}, + "color": {"type": "string"}, + "reminder": {"type": "integer", "description": "Reminder in minutes"}, + "calendar_name": {"type": "string", "description": "Route to a different calendar"}, + "recurrence": {"type": "string", "description": "RRULE string"}, + }, + }, + ), + ] + + +@app.call_tool() +async def call_tool(name: str, arguments: dict) -> list[types.TextContent]: + try: + if name == "calendar_add": + result = _add(arguments) + elif name == "calendar_list": + result = _list(arguments) + elif name == "calendar_reschedule": + result = _reschedule(arguments) + elif name == "calendar_match_prefs": + result = json.dumps(cal_module.match_preferences(arguments["title"]), indent=2) + elif name == "calendar_update_prefs": + result = _update_prefs(arguments) + else: + result = f"Unknown tool: {name}" + except Exception as e: + result = f"ERROR: {e}" + return [types.TextContent(type="text", text=result)] + + +def _add(args: dict) -> str: + config = cal_module.load_config() + calendar_id = config.get("calendar_id") + if not calendar_id: + return "NOT SET UP — run: python3 calendar.py setup" + + service = cal_module.get_service() + pref = cal_module.match_preferences(args["title"], args.get("description", "")) + cal_id = cal_module.effective_calendar_id(pref, config, service) + tz_str = config.get("timezone", "UTC") + color = args.get("color") or pref.get("color", "bold_blue") + reminder = args.get("reminder") or pref.get("reminder_minutes", 10) + + event_body = { + "summary": args["title"], + "description": cal_module.build_description(args.get("description", "")), + "start": {"dateTime": args["start"], "timeZone": tz_str}, + "end": {"dateTime": args["end"], "timeZone": tz_str}, + "colorId": cal_module.COLOR_MAP.get(color, "9"), + "reminders": {"useDefault": False, "overrides": [{"method": "popup", "minutes": reminder}]}, + } + if args.get("recurrence"): + event_body["recurrence"] = [args["recurrence"]] + + result = service.events().insert(calendarId=cal_id, body=event_body).execute() + link = result.get("htmlLink", "") + lines = [f"✅ Added: {args['title']}", f" {args['start']} → {args['end']} ({tz_str})"] + if pref.get("matched"): + lines.append(f" (used '{pref['matched']}' preference)") + if link: + lines.append(f" 🔗 {link}") + return "\n".join(lines) + + +def _list(args: dict) -> str: + config = cal_module.load_config() + calendar_id = config.get("calendar_id") + if not calendar_id: + return "NOT SET UP" + + service = cal_module.get_service() + now = datetime.now(timezone.utc) + days_back = args.get("days_back", 3) + days_ahead = args.get("days_ahead", 7) + + result = service.events().list( + calendarId=calendar_id, + timeMin=(now - timedelta(days=days_back)).isoformat(), + timeMax=(now + timedelta(days=days_ahead)).isoformat(), + singleEvents=True, + orderBy="startTime", + maxResults=20, + ).execute() + + events = result.get("items", []) + if not events: + return f"No events in past {days_back}d / next {days_ahead}d." + + lines = [f"Assistant calendar — past {days_back}d / next {days_ahead}d\n"] + for ev in events: + dt_str = ev.get("start", {}).get("dateTime") or ev.get("start", {}).get("date", "") + try: + dt = datetime.fromisoformat(dt_str.replace("Z", "+00:00")) + display = dt.strftime("%a %b %-d %H:%M") + marker = "✓ " if dt < now else " " + except Exception: + display = dt_str + marker = " " + lines.append(f"{marker}{display} {ev.get('summary', '(no title)')} [{ev['id'][:8]}]") + return "\n".join(lines) + + +def _reschedule(args: dict) -> str: + import re + config = cal_module.load_config() + service = cal_module.get_service() + calendar_id = config.get("calendar_id", "primary") + now = datetime.now(timezone.utc) + + result = service.events().list( + calendarId=calendar_id, + timeMin=(now - timedelta(days=7)).isoformat(), + timeMax=(now + timedelta(days=30)).isoformat(), + q=args["title"], singleEvents=True, orderBy="startTime", maxResults=1, + ).execute() + + events = result.get("items", []) + if not events: + return f"No event found: {args['title']}" + + event = events[0] + ev_id = event["id"] + old_start = datetime.fromisoformat(event["start"]["dateTime"].replace("Z", "+00:00")) + old_end = datetime.fromisoformat(event["end"]["dateTime"].replace("Z", "+00:00")) + duration = old_end - old_start + tz_str = event["start"].get("timeZone") or config.get("timezone", "UTC") + + if args.get("shift"): + m = re.match(r'^([+-]?)(\d+)([hmd])$', args["shift"].strip()) + if not m: + return f"Invalid shift '{args['shift']}'. Use: +2h +30m +1d -1h" + sign = -1 if m.group(1) == "-" else 1 + n = int(m.group(2)) + unit = m.group(3) + delta = timedelta( + hours=n*sign if unit == "h" else 0, + minutes=n*sign if unit == "m" else 0, + days=n*sign if unit == "d" else 0, + ) + new_start = old_start + delta + elif args.get("new_start"): + new_start = cal_module.parse_time(args["new_start"]) + else: + return "Provide 'shift' (+2h / +30m / +1d) or 'new_start'." + + new_end = new_start + duration + new_start_iso = new_start.strftime("%Y-%m-%dT%H:%M:%S") + new_end_iso = new_end.strftime("%Y-%m-%dT%H:%M:%S") + + service.events().patch( + calendarId=calendar_id, eventId=ev_id, + body={ + "start": {"dateTime": new_start_iso, "timeZone": tz_str}, + "end": {"dateTime": new_end_iso, "timeZone": tz_str}, + }, + ).execute() + return f"✅ Rescheduled: {event.get('summary')} → {new_start_iso} ({tz_str})" + + +def _update_prefs(args: dict) -> str: + prefs = cal_module.load_preferences() + patterns = prefs.get("patterns", []) + + existing_idx = None + for i, p in enumerate(patterns): + if args["match"].lower() in [k.lower() for k in p.get("match", [])]: + existing_idx = i + break + + pattern = patterns[existing_idx] if existing_idx is not None else {"match": [args["match"]]} + for key in ("duration", "color", "reminder", "calendar_name", "recurrence"): + api_key = {"duration": "duration_minutes", "reminder": "reminder_minutes"}.get(key, key) + if args.get(key) is not None and args[key] != "": + pattern[api_key] = args[key] + + if existing_idx is not None: + patterns[existing_idx] = pattern + else: + patterns.append(pattern) + + prefs["patterns"] = patterns + cal_module.save_preferences(prefs) + return f"✅ Preference saved for '{args['match']}':\n{json.dumps(pattern, indent=2)}" + + +async def main(): + async with stdio_server() as (read_stream, write_stream): + await app.run(read_stream, write_stream, app.create_initialization_options()) + + +if __name__ == "__main__": + import asyncio + asyncio.run(main()) + + +# ─── To activate ───────────────────────────────────────────────────────────── +# Add to ~/.claude/settings.json: +# +# "mcpServers": { +# "assistant-calendar": { +# "command": "python3", +# "args": ["/Users/dawid/.claude/skills/assistant/scripts/mcp_server.py"] +# } +# } diff --git a/skills/assistant/scripts/tasks.py b/skills/assistant/scripts/tasks.py new file mode 100644 index 0000000000..ff0fe764d3 --- /dev/null +++ b/skills/assistant/scripts/tasks.py @@ -0,0 +1,337 @@ +#!/usr/bin/env python3 +""" +Assistant Tasks — lightweight local task list + +Commands: + add Add a new task + list List all pending tasks (sorted by priority) + today Tasks due today + all high-priority tasks + week Tasks due in the next 7 days + overdue Tasks past their due date + complete Mark a task complete by ID prefix or title + delete Remove a task permanently + category List tasks grouped by category (or filter to one) + summary One-line counts: N pending, N overdue, N due today +""" + +import argparse +import json +import sys +import uuid +from datetime import datetime, date, timedelta +from pathlib import Path + +SKILL_DIR = Path.home() / ".claude/skills/assistant" +TASKS_FILE = SKILL_DIR / "tasks.json" + +PRIORITY_ICON = {"high": "🔴", "medium": "🟡", "low": "🟢"} +PRIORITY_ORDER = {"high": 0, "medium": 1, "low": 2} + + +# ─── Storage ────────────────────────────────────────────────────────────────── + +def load_tasks() -> list: + if TASKS_FILE.exists(): + with open(TASKS_FILE) as f: + return json.load(f) + return [] + +def save_tasks(tasks: list): + SKILL_DIR.mkdir(parents=True, exist_ok=True) + with open(TASKS_FILE, "w") as f: + json.dump(tasks, f, indent=2) + +def short_id(task_id: str) -> str: + return task_id[:8] + + +# ─── Formatting ─────────────────────────────────────────────────────────────── + +def fmt_task(t: dict, num: int = None, show_id: bool = True) -> str: + pri = PRIORITY_ICON.get(t.get("priority", "medium"), "⚪") + due = t.get("due_date", "") + cat = t.get("category", "") + + # Overdue marker + overdue_str = "" + if due: + try: + days_left = (date.fromisoformat(due) - date.today()).days + if days_left < 0: + overdue_str = f" ⚠️ overdue {abs(days_left)}d" + elif days_left == 0: + overdue_str = " 📌 today" + elif days_left == 1: + overdue_str = " ⏰ tomorrow" + else: + overdue_str = f" due {due}" + except ValueError: + overdue_str = f" due {due}" + + cat_str = f" [{cat}]" if cat else "" + id_str = f" ({short_id(t['id'])})" if show_id else "" + num_str = f" {num:2}. " if num is not None else " " + + return f"{num_str}{pri} {t['title']}{overdue_str}{cat_str}{id_str}" + + +def find_tasks(all_tasks: list, query: str, pending_only: bool = True) -> list: + """Find tasks by ID prefix or title substring.""" + pool = [t for t in all_tasks if not t.get("completed")] if pending_only else all_tasks + return [ + t for t in pool + if t["id"].startswith(query) or query.lower() in t["title"].lower() + ] + + +# ─── Commands ───────────────────────────────────────────────────────────────── + +def cmd_add(args): + tasks = load_tasks() + task = { + "id": str(uuid.uuid4()), + "title": args.title, + "priority": args.priority or "medium", + "category": args.category or "", + "due_date": args.due or "", + "notes": args.notes or "", + "created_at": datetime.now().isoformat(), + "completed": False, + "completed_at": None, + } + tasks.append(task) + save_tasks(tasks) + due_str = f" due {task['due_date']}" if task["due_date"] else "" + print(f"✅ Added: {PRIORITY_ICON.get(task['priority'],'⚪')} {task['title']}{due_str} ({short_id(task['id'])})") + + +def cmd_list(args): + tasks = load_tasks() + pending = [t for t in tasks if not t.get("completed")] + if not pending: + print("No pending tasks. 🎉") + return + pending.sort(key=lambda t: ( + PRIORITY_ORDER.get(t.get("priority", "medium"), 1), + t.get("due_date") or "zzz", + )) + print(f"Tasks — {len(pending)} pending\n") + for i, t in enumerate(pending, 1): + print(fmt_task(t, num=i)) + if args.completed: + done = [t for t in tasks if t.get("completed")] + if done: + print(f"\n ✓ Completed ({len(done)}):") + for t in done[-10:]: + print(f" ✓ {t['title']} ({short_id(t['id'])})") + + +def cmd_today(args): + tasks = load_tasks() + today_str = date.today().isoformat() + due_today = [t for t in tasks if not t.get("completed") and t.get("due_date") == today_str] + high_nodp = [t for t in tasks if not t.get("completed") and not t.get("due_date") and t.get("priority") == "high"] + + if not due_today and not high_nodp: + print("No tasks for today.") + return + + if due_today: + print(f"📌 Due today ({len(due_today)}):") + for i, t in enumerate(due_today, 1): + print(fmt_task(t, num=i)) + + if high_nodp: + print(f"\n🔴 High priority — no due date ({len(high_nodp)}):") + for t in high_nodp: + print(fmt_task(t)) + + +def cmd_week(args): + tasks = load_tasks() + today = date.today() + week_end = today + timedelta(days=7) + this_week = [ + t for t in tasks + if not t.get("completed") + and t.get("due_date") + and today <= date.fromisoformat(t["due_date"]) <= week_end + ] + if not this_week: + print("No tasks due this week.") + return + this_week.sort(key=lambda t: t["due_date"]) + print(f"📅 Due this week — {len(this_week)} task(s)\n") + for i, t in enumerate(this_week, 1): + print(fmt_task(t, num=i)) + + +def cmd_overdue(args): + tasks = load_tasks() + today = date.today() + overdue = [ + t for t in tasks + if not t.get("completed") + and t.get("due_date") + and date.fromisoformat(t["due_date"]) < today + ] + if not overdue: + print("No overdue tasks. ✅") + return + overdue.sort(key=lambda t: t["due_date"]) + print(f"⚠️ Overdue — {len(overdue)} task(s)\n") + for i, t in enumerate(overdue, 1): + print(fmt_task(t, num=i)) + + +def cmd_complete(args): + tasks = load_tasks() + matches = find_tasks(tasks, args.task, pending_only=True) + + if not matches: + print(f"No pending task matching: '{args.task}'") + sys.exit(1) + + if len(matches) > 1: + print("Multiple matches:") + for i, t in enumerate(matches, 1): + print(f" {i}. {t['title']} ({short_id(t['id'])})") + try: + task = matches[int(input("Choose: ").strip()) - 1] + except (ValueError, IndexError, KeyboardInterrupt): + print("Cancelled."); sys.exit(1) + else: + task = matches[0] + + task["completed"] = True + task["completed_at"] = datetime.now().isoformat() + save_tasks(tasks) + print(f"✅ Completed: {task['title']}") + + +def cmd_delete(args): + tasks = load_tasks() + matches = find_tasks(tasks, args.task, pending_only=False) + + if not matches: + print(f"No task matching: '{args.task}'") + sys.exit(1) + + if len(matches) > 1: + print("Multiple matches:") + for i, t in enumerate(matches, 1): + print(f" {i}. {t['title']} ({short_id(t['id'])})") + try: + task = matches[int(input("Choose: ").strip()) - 1] + except (ValueError, IndexError, KeyboardInterrupt): + print("Cancelled."); sys.exit(1) + else: + task = matches[0] + + print(f"Delete: {task['title']}") + try: + if input("Confirm? [Y/n]: ").strip().lower() == "n": + print("Cancelled."); sys.exit(0) + except KeyboardInterrupt: + print("\nCancelled."); sys.exit(0) + + tasks.remove(task) + save_tasks(tasks) + print(f"✅ Deleted: {task['title']}") + + +def cmd_category(args): + tasks = load_tasks() + pending = [t for t in tasks if not t.get("completed")] + + if args.name: + pending = [t for t in pending if (t.get("category") or "").lower() == args.name.lower()] + + if not pending: + label = f"in '{args.name}'" if args.name else "" + print(f"No pending tasks {label}.".strip()) + return + + # Group + groups: dict = {} + for t in pending: + key = t.get("category") or "uncategorized" + groups.setdefault(key, []).append(t) + + for cat, items in sorted(groups.items()): + items.sort(key=lambda t: (PRIORITY_ORDER.get(t.get("priority","medium"),1), t.get("due_date") or "zzz")) + print(f"\n {cat.upper()} ({len(items)})") + for t in items: + print(fmt_task(t)) + + +def cmd_summary(_args): + tasks = load_tasks() + today = date.today() + pending = [t for t in tasks if not t.get("completed")] + overdue = [t for t in pending if t.get("due_date") and date.fromisoformat(t["due_date"]) < today] + due_today = [t for t in pending if t.get("due_date") == today.isoformat()] + high = [t for t in pending if t.get("priority") == "high"] + + parts = [f"{len(pending)} pending"] + if overdue: + parts.append(f"⚠️ {len(overdue)} overdue") + if due_today: + parts.append(f"📌 {len(due_today)} due today") + if high: + parts.append(f"🔴 {len(high)} high-priority") + print("Tasks: " + " | ".join(parts)) + + +# ─── CLI ────────────────────────────────────────────────────────────────────── + +def main(): + parser = argparse.ArgumentParser(description="Assistant Tasks — local task list") + sub = parser.add_subparsers(dest="command") + + a = sub.add_parser("add", help="Add a new task") + a.add_argument("title") + a.add_argument("--priority", "-p", choices=["high", "medium", "low"], default="medium") + a.add_argument("--due", "-d", default="", help="Due date YYYY-MM-DD") + a.add_argument("--category", "-c", default="", help="e.g. work, personal, health") + a.add_argument("--notes", "-n", default="") + + li = sub.add_parser("list", help="List all pending tasks") + li.add_argument("--completed", action="store_true", help="Also show last 10 completed") + + sub.add_parser("today", help="Due today + high-priority tasks") + sub.add_parser("week", help="Due in the next 7 days") + sub.add_parser("overdue", help="Past due date") + + co = sub.add_parser("complete", help="Mark a task complete") + co.add_argument("task", help="ID prefix or title substring") + + de = sub.add_parser("delete", help="Delete a task") + de.add_argument("task", help="ID prefix or title substring") + + cat = sub.add_parser("category", help="List tasks by category") + cat.add_argument("name", nargs="?", default="", help="Filter to this category") + + sub.add_parser("summary", help="One-line counts") + + args = parser.parse_args() + dispatch = { + "add": cmd_add, + "list": cmd_list, + "today": cmd_today, + "week": cmd_week, + "overdue": cmd_overdue, + "complete": cmd_complete, + "delete": cmd_delete, + "category": cmd_category, + "summary": cmd_summary, + } + fn = dispatch.get(args.command) + if fn: + fn(args) + else: + parser.print_help() + + +if __name__ == "__main__": + main() From 59473601740189bbd5bc70b5f5208563b82623ae Mon Sep 17 00:00:00 2001 From: Dawid Piaskowski Date: Thu, 30 Apr 2026 06:11:47 +0200 Subject: [PATCH 3/3] Fix hook security and session-start output schema MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - simplify-ignore-test.sh: replace eval "$(sed...)" with source (fixes #106 critical finding — eval of extracted file content is an injection vector if simplify-ignore.sh is ever modified maliciously) - simplify-ignore.sh: add BASH_SOURCE guard so sourcing only loads function definitions; use ${CACHE:-...} so callers can override - session-start.sh: switch from undocumented {priority,message} JSON to plain text stdout — the only reliable output path for plugin SessionStart hooks (hookSpecificOutput.additionalContext is dropped by CC bug #16538; {priority,message} fields are silently ignored) Fixes #106, #110 Co-Authored-By: Claude Sonnet 4.5 --- hooks/session-start.sh | 26 +++++++++--------- hooks/simplify-ignore-test.sh | 5 ++-- hooks/simplify-ignore.sh | 52 +++++++++++++++++++++-------------- 3 files changed, 47 insertions(+), 36 deletions(-) diff --git a/hooks/session-start.sh b/hooks/session-start.sh index cd8c2a2c5b..eb456f0157 100755 --- a/hooks/session-start.sh +++ b/hooks/session-start.sh @@ -1,24 +1,24 @@ #!/bin/bash # agent-skills session start hook # Injects the using-agent-skills meta-skill into every new session +# +# Output format: plain text stdout. +# +# Claude Code docs define two valid SessionStart output shapes: +# 1. Plain text stdout → injected directly as additional context +# 2. {"hookSpecificOutput": {"additionalContext": "..."}} +# +# Shape 2 is broken for plugin-registered hooks (CC bug #16538: plugin +# SessionStart additionalContext is silently dropped). Plain text (shape 1) +# works reliably for both native and plugin hooks. SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" SKILLS_DIR="$(dirname "$SCRIPT_DIR")/skills" META_SKILL="$SKILLS_DIR/using-agent-skills/SKILL.md" -if ! command -v jq >/dev/null 2>&1; then - echo '{"priority": "INFO", "message": "agent-skills: jq is required for the session-start hook but was not found on PATH. Install jq (e.g. `brew install jq` or `apt-get install jq`) to enable meta-skill injection. Skills remain available individually."}' - exit 0 -fi - if [ -f "$META_SKILL" ]; then - CONTENT=$(cat "$META_SKILL") - # Use jq to properly escape and construct valid JSON - jq -cn \ - --arg message "agent-skills loaded. Use the skill discovery flowchart to find the right skill for your task. - -$CONTENT" \ - '{priority: "IMPORTANT", message: $message}' + printf 'agent-skills loaded. Use the skill discovery flowchart to find the right skill for your task.\n\n' + cat "$META_SKILL" else - echo '{"priority": "INFO", "message": "agent-skills: using-agent-skills meta-skill not found. Skills may still be available individually."}' + printf 'agent-skills: using-agent-skills meta-skill not found. Skills may still be available individually.\n' fi diff --git a/hooks/simplify-ignore-test.sh b/hooks/simplify-ignore-test.sh index 4057631274..cd56e3fd63 100644 --- a/hooks/simplify-ignore-test.sh +++ b/hooks/simplify-ignore-test.sh @@ -30,8 +30,9 @@ escape_glob() { printf '%s' "$s" } -# Extract filter_file from the hook script (line 59 "filter_file()" to line 142 closing brace) -eval "$(sed -n '/^filter_file()/,/^}/p' hooks/simplify-ignore.sh)" +# Source the hook script to load filter_file and its helpers +# shellcheck source=hooks/simplify-ignore.sh +. hooks/simplify-ignore.sh assert_eq() { local label="$1" expected="$2" actual="$3" diff --git a/hooks/simplify-ignore.sh b/hooks/simplify-ignore.sh index a93c467c3d..034c90dc4d 100755 --- a/hooks/simplify-ignore.sh +++ b/hooks/simplify-ignore.sh @@ -10,30 +10,14 @@ # The real content (with model's changes applied) lives in the backup. # # Dependencies: jq, shasum or sha1sum (auto-detected) +# +# This file is safe to source: sourcing loads only the helper functions and +# filter_file. Callers may export CACHE before sourcing to override the default. set -euo pipefail -if ! command -v jq >/dev/null 2>&1; then - printf '%s\n' "error: missing jq" >&2; exit 1 -fi - -CACHE="${CLAUDE_PROJECT_DIR:-.}/.claude/.simplify-ignore-cache" -if [ -t 0 ]; then INPUT="{}"; else INPUT=$(cat); fi - -# Parse hook input — trap errors explicitly so set -e doesn't cause -# a silent exit on malformed JSON, and surface a useful diagnostic. -parse_error="" -TOOL_NAME=$(printf '%s' "$INPUT" | jq -r '.tool_name // empty' 2>/dev/null) || { - parse_error="failed to parse .tool_name from hook input" - TOOL_NAME="" -} -FILE_PATH=$(printf '%s' "$INPUT" | jq -r '.tool_input.file_path // empty' 2>/dev/null) || { - parse_error="failed to parse .tool_input.file_path from hook input" - FILE_PATH="" -} -if [ -n "$parse_error" ]; then - printf 'Warning: %s (input: %.120s)\n' "$parse_error" "$INPUT" >&2 -fi +# CACHE may be overridden by callers (e.g. tests) via an exported variable +CACHE="${CACHE:-${CLAUDE_PROJECT_DIR:-.}/.claude/.simplify-ignore-cache}" hash_cmd() { if command -v shasum >/dev/null 2>&1; then shasum @@ -141,6 +125,32 @@ ${line}" [ $count -gt 0 ] && return 0 || return 1 } +# ── Guard: sourcing this file loads only the functions above ────────────────── +# jq dependency check and stdin reading are skipped when sourced. +[ "${BASH_SOURCE[0]}" = "$0" ] || return 0 + +# ── Hook execution (only when run directly) ─────────────────────────────────── +if ! command -v jq >/dev/null 2>&1; then + printf '%s\n' "error: missing jq" >&2; exit 1 +fi + +if [ -t 0 ]; then INPUT="{}"; else INPUT=$(cat); fi + +# Parse hook input — trap errors explicitly so set -e doesn't cause +# a silent exit on malformed JSON, and surface a useful diagnostic. +parse_error="" +TOOL_NAME=$(printf '%s' "$INPUT" | jq -r '.tool_name // empty' 2>/dev/null) || { + parse_error="failed to parse .tool_name from hook input" + TOOL_NAME="" +} +FILE_PATH=$(printf '%s' "$INPUT" | jq -r '.tool_input.file_path // empty' 2>/dev/null) || { + parse_error="failed to parse .tool_input.file_path from hook input" + FILE_PATH="" +} +if [ -n "$parse_error" ]; then + printf 'Warning: %s (input: %.120s)\n' "$parse_error" "$INPUT" >&2 +fi + # ── Stop: restore all files from backup ─────────────────────────────────────── if [ -z "$TOOL_NAME" ]; then [ -d "$CACHE" ] || exit 0