From 8f952ee727952815781c1fd43f898e8cdfb19023 Mon Sep 17 00:00:00 2001 From: Zhongwei Li Date: Sun, 30 Nov 2025 08:57:54 +0800 Subject: [PATCH] Initial commit --- .claude-plugin/plugin.json | 18 + README.md | 3 + commands/categorize.md | 148 ++ commands/health.md | 161 ++ commands/insights.md | 224 ++ commands/install.md | 914 +++++++++ commands/review-conflicts.md | 282 +++ commands/schedule.md | 138 ++ commands/tax.md | 191 ++ hooks/hooks.json | 16 + hooks/session_start.py | 264 +++ plugin.lock.json | 233 +++ skills/agent-smith/.env.sample | 28 + skills/agent-smith/.gitignore | 61 + skills/agent-smith/README.md | 165 ++ skills/agent-smith/SKILL.md | 517 +++++ skills/agent-smith/assets/.env.sample | 28 + skills/agent-smith/assets/config.json | 28 + skills/agent-smith/assets/config.json.sample | 28 + skills/agent-smith/assets/local_rules.json | 1 + .../assets/merchants/merchant_mappings.json | 1 + .../agent-smith/assets/onboarding_state.json | 11 + skills/agent-smith/assets/platform_rules.json | 1 + .../assets/tax/ato_category_mappings.json | 55 + .../assets/tax/deduction_patterns.json | 200 ++ skills/agent-smith/assets/templates/README.md | 23 + .../assets/templates/additional/README.md | 15 + .../templates/additional/airbnb-host.yaml | 175 ++ .../templates/additional/crypto-investor.yaml | 175 ++ .../additional/property-investor.yaml | 129 ++ .../templates/additional/share-investor.yaml | 103 + .../archive/comprehensive.yaml.archived | 832 ++++++++ .../templates/archive/minimal.yaml.archived | 121 ++ .../templates/archive/single.yaml.archived | 65 + .../templates/archive/standard.yaml.archived | 361 ++++ .../templates/foundation/personal-living.json | 349 ++++ .../assets/templates/living/README.md | 15 + .../templates/living/separated-parents.yaml | 114 ++ .../templates/living/shared-hybrid.yaml | 73 + .../assets/templates/primary/README.md | 51 + .../templates/primary/payg-employee.yaml | 112 + .../assets/templates/primary/sole-trader.yaml | 141 ++ skills/agent-smith/pyproject.toml | 110 + skills/agent-smith/pytest.ini | 13 + .../agent-smith/references/LESSONS_LEARNED.md | 327 +++ skills/agent-smith/references/design.md | 1324 ++++++++++++ .../references/health-check-guide.md | 408 ++++ .../references/onboarding-guide.md | 344 ++++ .../agent-smith/references/pocketsmith-api.md | 293 +++ .../references/unified-rules-guide.md | 1810 +++++++++++++++++ 50 files changed, 11199 insertions(+) create mode 100644 .claude-plugin/plugin.json create mode 100644 README.md create mode 100644 commands/categorize.md create mode 100644 commands/health.md create mode 100644 commands/insights.md create mode 100644 commands/install.md create mode 100644 commands/review-conflicts.md create mode 100644 commands/schedule.md create mode 100644 commands/tax.md create mode 100644 hooks/hooks.json create mode 100755 hooks/session_start.py create mode 100644 plugin.lock.json create mode 100644 skills/agent-smith/.env.sample create mode 100644 skills/agent-smith/.gitignore create mode 100644 skills/agent-smith/README.md create mode 100644 skills/agent-smith/SKILL.md create mode 100644 skills/agent-smith/assets/.env.sample create mode 100644 skills/agent-smith/assets/config.json create mode 100644 skills/agent-smith/assets/config.json.sample create mode 100644 skills/agent-smith/assets/local_rules.json create mode 100644 skills/agent-smith/assets/merchants/merchant_mappings.json create mode 100644 skills/agent-smith/assets/onboarding_state.json create mode 100644 skills/agent-smith/assets/platform_rules.json create mode 100644 skills/agent-smith/assets/tax/ato_category_mappings.json create mode 100644 skills/agent-smith/assets/tax/deduction_patterns.json create mode 100644 skills/agent-smith/assets/templates/README.md create mode 100644 skills/agent-smith/assets/templates/additional/README.md create mode 100644 skills/agent-smith/assets/templates/additional/airbnb-host.yaml create mode 100644 skills/agent-smith/assets/templates/additional/crypto-investor.yaml create mode 100644 skills/agent-smith/assets/templates/additional/property-investor.yaml create mode 100644 skills/agent-smith/assets/templates/additional/share-investor.yaml create mode 100644 skills/agent-smith/assets/templates/archive/comprehensive.yaml.archived create mode 100644 skills/agent-smith/assets/templates/archive/minimal.yaml.archived create mode 100644 skills/agent-smith/assets/templates/archive/single.yaml.archived create mode 100644 skills/agent-smith/assets/templates/archive/standard.yaml.archived create mode 100644 skills/agent-smith/assets/templates/foundation/personal-living.json create mode 100644 skills/agent-smith/assets/templates/living/README.md create mode 100644 skills/agent-smith/assets/templates/living/separated-parents.yaml create mode 100644 skills/agent-smith/assets/templates/living/shared-hybrid.yaml create mode 100644 skills/agent-smith/assets/templates/primary/README.md create mode 100644 skills/agent-smith/assets/templates/primary/payg-employee.yaml create mode 100644 skills/agent-smith/assets/templates/primary/sole-trader.yaml create mode 100644 skills/agent-smith/pyproject.toml create mode 100644 skills/agent-smith/pytest.ini create mode 100644 skills/agent-smith/references/LESSONS_LEARNED.md create mode 100644 skills/agent-smith/references/design.md create mode 100644 skills/agent-smith/references/health-check-guide.md create mode 100644 skills/agent-smith/references/onboarding-guide.md create mode 100644 skills/agent-smith/references/pocketsmith-api.md create mode 100644 skills/agent-smith/references/unified-rules-guide.md diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..11aef13 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "name": "agent-smith-plugin", + "description": "Intelligent financial management plugin containing an intelligent skill for Claude Code with PocketSmith API integration. Features AI-powered categorization, tax intelligence, scenario planning, and health checks.", + "version": "1.6.1", + "author": { + "name": "slamb2k", + "email": "slamb2k@users.noreply.github.com" + }, + "skills": [ + "./skills" + ], + "commands": [ + "./commands" + ], + "hooks": [ + "./hooks" + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..871211a --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# agent-smith-plugin + +Intelligent financial management plugin containing an intelligent skill for Claude Code with PocketSmith API integration. Features AI-powered categorization, tax intelligence, scenario planning, and health checks. diff --git a/commands/categorize.md b/commands/categorize.md new file mode 100644 index 0000000..8204f65 --- /dev/null +++ b/commands/categorize.md @@ -0,0 +1,148 @@ +--- +name: smith:categorize +description: Categorize uncategorized transactions using the hybrid rule + LLM workflow +argument-hints: + - "[--period=YYYY-MM|last-30-days] [--mode=conservative|smart|aggressive] [--dry-run]" +--- + +# Transaction Categorization + +Categorize uncategorized transactions using Agent Smith's hybrid rule + LLM workflow. + +## Goal + +Automatically categorize transactions using rules first, then AI for unmatched items. + +## Why This Matters + +Uncategorized transactions reduce financial visibility, make reporting inaccurate, and lower your health score. Regular categorization keeps your finances organized. + +## Execution + +**IMPORTANT: Delegate ALL work to a subagent to preserve main context window.** + +Use the Task tool with `subagent_type: "general-purpose"` to execute the categorization workflow: + +``` +Task( + subagent_type: "general-purpose", + description: "Categorize transactions", + prompt: +) +``` + +### Subagent Prompt + +You are the Agent Smith categorization assistant. Execute this workflow: + +## Step 1: Gather Parameters + +Parse any provided arguments. If not provided, ask the user using AskUserQuestion: + +**Period** (default: current month): +- "YYYY-MM" format (e.g., "2025-11") +- "last-30-days" for recent transactions + +**Mode** (default: smart): +- conservative: Manual review for all (safest) +- smart: Auto-apply 90%+ confidence (recommended) +- aggressive: Auto-apply 80%+ confidence (fastest) + +**Dry-run** (default: true for first run): +- true: Preview only, no changes +- false: Apply changes + +## Step 2: Run Categorization + +Execute the Python script with user's parameters: + +```bash +uv run python -u scripts/operations/categorize_batch.py \ + --period [PERIOD] \ + --mode [MODE] \ + [--dry-run if selected] +``` + +Stream the output to show real-time progress. + +## Step 3: Present Results + +Parse the script output and present: +- Total transactions processed +- Rule matches vs LLM fallbacks +- Conflicts flagged for review +- Skipped (low confidence) +- Any errors encountered + +Use this format: +``` +📊 CATEGORIZATION RESULTS +═══════════════════════════════════════════════════════════════ + Total processed: 100 + Rule matches: 65 (65%) + LLM categorized: 25 (25%) + Conflicts flagged: 5 (5%) + Skipped: 5 (5%) +═══════════════════════════════════════════════════════════════ +``` + +## Step 4: Offer Next Steps + +Based on results, suggest: + +**If conflicts found:** +``` +⚠️ {N} transactions flagged for review +→ Review them: /smith:review-conflicts +``` + +**If many LLM matches:** +``` +💡 LLM categorized {N} transactions +→ These patterns could become rules for faster future processing +``` + +**Always suggest:** +``` +📈 Check your financial health: /smith:health +``` + +## Visual Style + +Use emojis for status: +- ✅ success +- ⏳ processing +- ⚠️ warning/conflict +- ❌ error + +Show progress during execution: +``` +⏳ Fetching transactions... 150 found +⏳ Applying rules... +⏳ Running LLM categorization... +✅ Categorization complete! +``` + +--- + +## Parameters + +| Parameter | Description | Default | +|-----------|-------------|---------| +| `--period` | Month (YYYY-MM) or "last-30-days" | Current month | +| `--mode` | Intelligence mode | smart | +| `--dry-run` | Preview without applying | true (first run) | + +## Intelligence Modes + +| Mode | Auto-Apply Threshold | Best For | +|------|---------------------|----------| +| **conservative** | Never (all manual) | First-time users, sensitive data | +| **smart** | 90%+ confidence | Regular use (recommended) | +| **aggressive** | 80%+ confidence | Trusted rules, bulk processing | + +## Next Steps After Categorization + +- **Review conflicts**: `/smith:review-conflicts` +- **Check health**: `/smith:health --quick` +- **View insights**: `/smith:insights spending` diff --git a/commands/health.md b/commands/health.md new file mode 100644 index 0000000..5c17664 --- /dev/null +++ b/commands/health.md @@ -0,0 +1,161 @@ +--- +name: smith:health +description: Evaluate your PocketSmith setup and get optimization recommendations +argument-hints: + - "[--full|--quick] [--category=categories|rules|tax|data]" +--- + +# PocketSmith Health Check + +Evaluate your financial setup and get actionable optimization recommendations. + +## Goal + +Assess the health of your PocketSmith configuration across 6 dimensions and identify improvement opportunities. + +## Why This Matters + +A healthy financial setup means accurate reports, effective tax tracking, and reliable categorization. Regular health checks catch issues before they become problems. + +## Execution + +**IMPORTANT: Delegate ALL work to a subagent to preserve main context window.** + +Use the Task tool with `subagent_type: "general-purpose"` to execute the health check: + +``` +Task( + subagent_type: "general-purpose", + description: "Run health check", + prompt: +) +``` + +### Subagent Prompt + +You are the Agent Smith health check assistant. Execute this workflow: + +## Step 1: Determine Check Type + +Parse arguments to determine mode: +- `--full`: Complete analysis (2-3 minutes) +- `--quick`: Essential checks only (30 seconds) - **default** +- `--category=X`: Focus on specific area (categories|rules|tax|data) + +If no arguments provided, default to quick mode. + +## Step 2: Run Health Check + +Execute the health check script: + +```bash +uv run python -u scripts/health/check.py [--quick|--full] [--category=CATEGORY] +``` + +Stream the output to show real-time progress. + +## Step 3: Present Results + +The script outputs a comprehensive report. Summarize it with: + +``` +🏥 HEALTH CHECK RESULTS +═══════════════════════════════════════════════════════════════ + Overall Score: XX/100 [🟢 EXCELLENT | 🟡 GOOD | 🟠 FAIR | 🔴 POOR] + + Dimension Scores: + Data Quality: ████████░░ 80% + Category Health: ██████████ 100% + Rule Coverage: ██████░░░░ 60% + Tax Compliance: ████████░░ 75% + Budget Alignment: ████░░░░░░ 40% + Account Health: █████████░ 90% +═══════════════════════════════════════════════════════════════ +``` + +## Step 4: Present Top Recommendations + +Show top 3-5 recommendations with actionable next steps: + +``` +🎯 TOP RECOMMENDATIONS +───────────────────────────────────────────────────────────────── +1. [HIGH] Categorize 23 uncategorized transactions + → Run /smith:categorize + +2. [MEDIUM] Create rules for frequently used patterns + → Review LLM patterns after categorization + +3. [LOW] Review unused categories + → Consider consolidation +───────────────────────────────────────────────────────────────── +``` + +## Step 5: Offer Next Steps + +Based on health score: + +**If score < 50 (Poor):** +``` +⚠️ Your financial setup needs attention +→ Start with: /smith:categorize to fix uncategorized transactions +``` + +**If score 50-69 (Fair):** +``` +💡 Room for improvement +→ Focus on the top recommendation above +``` + +**If score >= 70 (Good/Excellent):** +``` +✅ Your setup is healthy! +→ Run /smith:insights to explore your financial data +``` + +## Visual Style + +Health Score Display: +- 90-100: 🟢 Excellent +- 70-89: 🟡 Good +- 50-69: 🟠 Fair +- Below 50: 🔴 Poor + +Use ASCII progress bars for dimension scores. + +--- + +## Health Dimensions + +| Dimension | Weight | Checks | +|-----------|--------|--------| +| **Data Quality** | 25% | Uncategorized %, duplicates, missing payees | +| **Rule Coverage** | 20% | Auto-categorization rate, rule accuracy | +| **Category Health** | 15% | Structure, hierarchy, unused categories | +| **Tax Compliance** | 15% | Deduction tracking, substantiation | +| **Budget Alignment** | 15% | Spending vs goals, trending | +| **Account Health** | 10% | Connections, reconciliation | + +## Score Interpretation + +| Score | Status | Action | +|-------|--------|--------| +| 90-100 | Excellent | Maintain current practices | +| 70-89 | Good | Minor improvements available | +| 50-69 | Fair | Several issues to address | +| <50 | Poor | Significant work needed | + +## Check Types + +| Type | Duration | Best For | +|------|----------|----------| +| `--quick` | ~30 seconds | Regular check-ins (default) | +| `--full` | 2-3 minutes | Monthly deep analysis | +| `--category=X` | ~1 minute | Focused investigation | + +## Next Steps + +- **Improve categorization**: `/smith:categorize` +- **Review conflicts**: `/smith:review-conflicts` +- **View insights**: `/smith:insights spending` +- **Tax review**: `/smith:tax deductions` diff --git a/commands/insights.md b/commands/insights.md new file mode 100644 index 0000000..129eca8 --- /dev/null +++ b/commands/insights.md @@ -0,0 +1,224 @@ +--- +name: smith:insights +description: Financial insights - spending analysis, scenarios, trends, and reports +argument-hints: + - " [options]" + - "spending [--period=YYYY-MM] [--category=NAME]" + - "trends [--period=YYYY] [--compare=PERIOD]" + - "scenario \"\"" + - "report [--format=summary|detailed|tax] [--output=markdown|csv|excel]" +--- + +# Financial Insights + +Get comprehensive insights into your finances - spending analysis, trends, what-if scenarios, and reports. + +## Goal + +Understand your financial patterns and make informed decisions with data-driven insights. + +## Why This Matters + +Regular financial analysis reveals spending patterns, identifies optimization opportunities, and helps you plan for the future. + +## Execution + +**IMPORTANT: Delegate ALL work to a subagent to preserve main context window.** + +Use the Task tool with `subagent_type: "general-purpose"` to execute the insights workflow: + +``` +Task( + subagent_type: "general-purpose", + description: "Generate financial insights", + prompt: +) +``` + +### Subagent Prompt + +You are the Agent Smith insights assistant. Execute this workflow: + +## Step 1: Determine Insight Type + +Parse the command to determine which insight type: +- `spending` - Spending breakdown by category and merchant +- `trends` - Month-over-month and year-over-year trends +- `scenario` - What-if analysis (e.g., "What if I cut dining by 30%?") +- `report` - Generate formatted reports + +If no type specified, ask using AskUserQuestion: +"What kind of insights would you like?" +- Spending breakdown (where is my money going?) +- Trend analysis (how is my spending changing?) +- What-if scenario (what if I changed my spending?) +- Generate a report (export my financial data) + +## Step 2: Run Analysis + +Based on insight type, call the appropriate script: + +**Spending Analysis:** +```bash +uv run python -u scripts/analysis/spending.py --period [PERIOD] --category "[CATEGORY]" +``` + +**Trend Analysis:** +```bash +uv run python -u scripts/analysis/trends.py --period [PERIOD] --compare [COMPARE_PERIOD] +``` + +**Scenario Analysis:** +```bash +uv run python -u scripts/scenarios/historical.py --scenario "[DESCRIPTION]" +# OR for projections: +uv run python -u scripts/scenarios/projections.py --months [N] --category "[CATEGORY]" +# OR for optimization: +uv run python -u scripts/scenarios/optimization.py +``` + +**Report Generation:** +```bash +uv run python -u scripts/reporting/formatters.py --format [FORMAT] --output [OUTPUT_PATH] +``` + +Stream the output to show real-time progress. + +## Step 3: Present Results + +Present insights with: +- Key findings summary +- Visual charts/tables where appropriate +- Actionable recommendations + +**Spending Results Format:** +``` +💰 SPENDING ANALYSIS - [PERIOD] +═══════════════════════════════════════════════════════════════ + Total Spending: $X,XXX.XX + + Top Categories: + 1. Groceries $XXX.XX (XX%) ████████░░ + 2. Dining Out $XXX.XX (XX%) ████░░░░░░ + 3. Transport $XXX.XX (XX%) ███░░░░░░░ + ... +═══════════════════════════════════════════════════════════════ +``` + +**Trends Results Format:** +``` +📈 TREND ANALYSIS - [PERIOD] +═══════════════════════════════════════════════════════════════ + Overall Spending: ↑ +12% vs last period + + Trending Up: + • Groceries: +15% ($200 → $230) + • Utilities: +8% ($150 → $162) + + Trending Down: + • Dining Out: -25% ($400 → $300) + • Entertainment: -10% ($100 → $90) +═══════════════════════════════════════════════════════════════ +``` + +**Scenario Results Format:** +``` +🔮 SCENARIO: "What if I reduced dining by 25%?" +═══════════════════════════════════════════════════════════════ + Current Monthly Dining: $400 + After 25% Reduction: $300 + Monthly Savings: $100 + Annual Savings: $1,200 + + Impact Assessment: + • Moderate lifestyle adjustment + • Could redirect to savings goal +═══════════════════════════════════════════════════════════════ +``` + +## Step 4: Offer Next Steps + +Based on results: + +**After spending analysis:** +``` +📊 Want more detail? +→ /smith:insights trends --compare=2024 (see how this compares) +→ /smith:insights scenario "reduce dining 20%" (model changes) +``` + +**After trends:** +``` +📈 Noticed high spending category? +→ /smith:insights spending --category="[CATEGORY]" (deep dive) +→ /smith:health (check overall financial health) +``` + +**After scenario:** +``` +🔮 Ready to make changes? +→ /smith:categorize (ensure transactions are categorized) +→ /smith:health (monitor progress) +``` + +## Visual Style + +Use emojis for trend direction: +- 📈 up (increasing) +- 📉 down (decreasing) +- ➡️ stable (unchanged) + +Use ASCII bars for percentages. +Use tables for category breakdowns. + +--- + +## Insight Types + +| Type | Description | Example | +|------|-------------|---------| +| `spending` | Spending breakdown | `/smith:insights spending --period=2025-11` | +| `trends` | Historical trends | `/smith:insights trends --compare=2024` | +| `scenario` | What-if analysis | `/smith:insights scenario "cut dining 30%"` | +| `report` | Generate reports | `/smith:insights report --format=summary` | + +## Options + +| Option | Description | Applies To | +|--------|-------------|------------| +| `--period` | Time period (YYYY-MM, YYYY, YYYY-Q#) | spending, trends, report | +| `--category` | Focus on specific category | spending | +| `--compare` | Compare with another period | trends | +| `--format` | Report format (summary, detailed, tax) | report | +| `--output` | Output format (markdown, csv, excel) | report | + +## Examples + +```bash +# This month's spending by category +/smith:insights spending + +# Year-over-year comparison +/smith:insights trends --period=2025 --compare=2024 + +# What-if scenario +/smith:insights scenario "What if I reduced dining by 25%?" + +# Generate tax report +/smith:insights report --format=tax --output=excel +``` + +## Consolidated From + +This command replaces: +- `/smith:analyze` → use `/smith:insights spending` or `/smith:insights trends` +- `/smith:scenario` → use `/smith:insights scenario` +- `/smith:report` → use `/smith:insights report` +- `/smith:optimize spending` → use `/smith:insights spending` analysis + +## Next Steps + +After viewing insights: +- **Take action**: `/smith:categorize` to process new transactions +- **Deep dive tax**: `/smith:tax deductions` for tax-specific analysis +- **Check health**: `/smith:health` for overall financial health diff --git a/commands/install.md b/commands/install.md new file mode 100644 index 0000000..da86f79 --- /dev/null +++ b/commands/install.md @@ -0,0 +1,914 @@ +--- +name: smith:install +description: Interactive Agent Smith setup wizard with intelligent suggestions based on your financial setup +argument-hints: + - "[--reset]" +--- + +# Agent Smith - Intelligent Financial Assistant + +You are guiding a user through Agent Smith. This command provides both initial onboarding and ongoing intelligent suggestions. + +## Your Role + +- Be encouraging and supportive +- Explain each step clearly +- Show progress throughout the journey +- Celebrate wins (data discovered, rules created, transactions categorized) +- Provide concrete, actionable next steps + +## Execution Logic + +**FIRST: Immediately notify the user that the workflow is loading:** + +Display this message before doing anything else: +``` +Loading Agent Smith installation workflow... +This may take a moment as I analyze your setup. Please wait... +``` + +**Check for --reset argument:** + +If the user provides `--reset` argument: +1. **Confirm with the user** before proceeding (this will delete all data!) +2. Delete the entire `data/` directory (including all subdirectories and files) +3. Display message: "Reset complete. All onboarding state and data cleared. Running fresh installation..." +4. Proceed to **Stages 1-8 (Onboarding)** then **Stage 9 (Suggestions)** + +**Check for onboarding completion:** + +1. Check if `data/onboarding_state.json` exists and has `"onboarding_completed": true` +2. If YES → Skip to **Stage 9: Intelligent Suggestions** only +3. If NO → Run **Stages 1-8 (Onboarding)** then **Stage 9 (Suggestions)** + +**When onboarding is complete:** +- Set `"onboarding_completed": true` in `data/onboarding_state.json` +- Always run Stage 9 (Suggestions) every time this command is invoked + +--- + +## Onboarding Workflow (Stages 1-8) + +### Stage 1: Welcome & Prerequisites Check + +Greet the user and verify they have: +1. Agent Smith plugin installed (verify via plugin system) +2. API key configured in .env (in current directory) +3. PocketSmith account accessible + +**IMPORTANT:** When Agent Smith is installed as a plugin, the codebase is in the plugin directory, NOT the user's working directory. The user only needs: +- A `.env` file with `POCKETSMITH_API_KEY` in their working directory +- Agent Smith plugin installed + +**Plugin Detection:** +Check if this command is running from the plugin by looking for the plugin installation path. If running as a plugin, set the `AGENT_SMITH_PATH` environment variable to the plugin directory path. + +If the user doesn't have a `.env` file, guide them to create one: +```bash +echo "POCKETSMITH_API_KEY=your_key_here" > .env +``` + +Get API key from: https://app.pocketsmith.com/keys/new + +### Stage 2: Discovery + +Run the discovery script to analyze their PocketSmith account. + +**Before first script execution,** define the `run_agent_smith` helper function (see "Plugin-Aware Script Execution" section below). + +**Run discovery:** +```bash +run_agent_smith "onboarding/discovery.py" +``` + +**Note:** The `.env` file should be in the user's current working directory. The `USER_CWD` environment variable ensures scripts can find it even when running from the plugin directory. + +**What to look for:** +- Account count and types +- Category structure +- Transaction volume and date range +- Uncategorized transaction count +- Baseline health score (if available) + +**Present findings:** +- Summarize their PocketSmith setup +- Highlight the uncategorized transaction count +- Show the recommended template +- Display account classifications (household_shared, parenting_shared, individual) +- Show any name suggestions detected + +### Stage 2a: Category Structure Assessment + +**IMPORTANT:** This stage determines whether to apply the Foundation template based on the user's existing category count. + +**Check existing category count** from discovery report: + +```python +existing_category_count = len(discovery_report.categories) +``` + +**Decision logic:** + +- **0-5 categories**: Auto-apply Foundation (user has minimal setup) +- **6-19 categories**: Offer Foundation with recommendation to apply (partial setup) +- **20+ categories**: Offer Foundation with recommendation to skip (established setup) + +**For users with 20+ categories, present this choice:** + +``` +I detected {existing_category_count} existing categories in your PocketSmith account. + +Agent Smith's Foundation template provides 45 ATO-aligned categories for +everyday expenses (Food, Housing, Transport, Healthcare, Personal, etc.). + +The Foundation will be applied automatically to provide structure and +tax compliance. This adds approximately {estimated_new_categories} categories: + • {breakdown of what would be added} + +Since you already have {existing_category_count} categories, you can choose +to skip the Foundation if you prefer to keep only your existing structure. + +Apply Agent Smith Foundation? (Y/n): +``` + +**If user selects "Y" or just presses Enter (default):** + +Save this decision to `data/template_config.json`: + +```json +{ + "apply_foundation": true +} +``` + +The Foundation template will be merged in Stage 4 with priority 0 (applied first). + +**If user selects "n":** + +Save this decision: + +```json +{ + "apply_foundation": false +} +``` + +Foundation will be skipped (--foundation=none in Stage 4). + +**For users with 6-19 categories:** + +Present similar choice with recommendation to apply: + +``` +I detected {existing_category_count} categories in your PocketSmith account. + +Agent Smith's Foundation template adds ATO-aligned structure and better +tax tracking with 45 categories for everyday expenses. + +This would add approximately {estimated_new_categories} categories. + +Apply Agent Smith Foundation? (Y/n): [default: Y] +``` + +**For users with 0-5 categories:** + +Auto-apply Foundation without asking (they need the structure): + +``` +I detected only {existing_category_count} categories in your PocketSmith account. + +Applying Agent Smith's Foundation template (45 ATO-aligned categories)... +``` + +Save to config: +```json +{ + "apply_foundation": true +} +``` + +### Stage 2b: Account Selection (Interactive) + +**IMPORTANT:** This stage enables context-aware name detection by identifying which accounts are used for household vs parenting expenses. + +**Check if shared accounts were detected:** + +Look at the discovery report's `account_classifications` field. If there are accounts classified as `household_shared` or `parenting_shared`, proceed with interactive selection. + +**For Household Shared Accounts:** + +If `household_shared` accounts were detected: + +1. **Show detected accounts** with confidence scores: + +``` +I detected these potential household shared accounts: + + 1. Shared Bills - Simon & Caitlin (Macquarie Bank) + Confidence: 90% + Indicators: "shared" in account name + + 2. Joint Savings (CBA) + Confidence: 60% + Indicators: "joint" in account name + +Which account do you use for household shared expenses? +``` + +2. **Use AskUserQuestion** to let the user select: + +```python +# Build options from household_shared accounts +household_accounts = [acc for acc in report.account_classifications + if acc.account_type == "household_shared"] + +if household_accounts: + # Sort by confidence + household_accounts.sort(key=lambda x: x.confidence, reverse=True) + + options = [] + for acc in household_accounts: + options.append({ + "label": f"{acc.account_name} ({acc.institution})", + "description": f"Confidence: {acc.confidence*100:.0f}% - Indicators: {', '.join(acc.indicators)}" + }) + + # Ask user to select + response = AskUserQuestion( + questions=[{ + "question": "Which account do you use for household shared expenses?", + "header": "Household Acct", + "options": options, + "multiSelect": false + }] + ) + + # User selected index or "Other" + # If "Other", show full account list and let them choose +``` + +3. **Extract names** from selected account: + +```python +# Get the selected account +selected_account = household_accounts[selected_index] + +# Extract names using the account-specific data +suggestion = _extract_names_from_account( + selected_account, + transactions, + categories +) + +# Show detected names +if suggestion and suggestion.person_1: + if suggestion.person_2: + print(f"✓ Detected contributors: {suggestion.person_1} and {suggestion.person_2}") + else: + print(f"✓ Detected contributor: {suggestion.person_1}") + + print(f" Source: {suggestion.source} (confidence: {suggestion.confidence*100:.0f}%)") + + # Ask for confirmation + response = AskUserQuestion( + questions=[{ + "question": f"Use '{suggestion.person_1} and {suggestion.person_2}' for household shared expenses?", + "header": "Confirm Names", + "options": [ + {"label": "Yes", "description": "Use these names"}, + {"label": "No", "description": "I'll enter different names"} + ], + "multiSelect": false + }] + ) + + # If "No", ask for manual entry using AskUserQuestion with text input +``` + +4. **Save to template_config.json:** + +```python +config = { + "household_shared_account": { + "account_id": selected_account.account_id, + "account_name": selected_account.account_name, + "person_1": confirmed_person_1, + "person_2": confirmed_person_2 + } +} +``` + +**For Parenting Shared Accounts:** + +If `parenting_shared` accounts were detected, repeat the same flow: + +1. Show detected parenting accounts with confidence scores +2. Use AskUserQuestion to let user select +3. Extract names from selected account +4. Ask for confirmation +5. Save to template_config.json under `parenting_shared_account` + +**Example output:** + +``` +=== Household Shared Account Selection === + +I detected these potential household shared accounts: + + 1. Shared Bills - Simon & Caitlin (Macquarie Bank) + Confidence: 90% + Why: "shared" in account name + +Which account do you use for household shared expenses? (1): 1 + +Analyzing 'Shared Bills - Simon & Caitlin' for contributor names... + +✓ Detected contributors: Simon and Caitlin + Source: account_name (confidence: 90%) + +Use 'Simon and Caitlin' for household shared expenses? (y/n): y + +=== Parenting Shared Account Selection === + +I detected these potential parenting shared accounts: + + 1. Kids Account - Simon & Tori (CBA) + Confidence: 90% + Why: "kids" in account name + +Which account do you use for parenting/child expenses? (1): 1 + +Analyzing 'Kids Account - Simon & Tori' for contributor names... + +✓ Detected contributors: Simon and Tori + Source: account_name (confidence: 90%) + +Use 'Simon and Tori' for parenting shared expenses? (y/n): y + +✓ Account selections saved to template_config.json +``` + +**If no shared accounts detected:** + +Skip this stage and continue to template selection. + +### Stage 3: Template Selection + +Agent Smith uses a **composable template system** with up to three layers. Users select: +1. **Primary Income** (ONE choice, REQUIRED) - How you earn most of your income +2. **Living Arrangement** (ONE OR MORE choices, OPTIONAL) - Special tracking for shared finances or child support +3. **Additional Income** (MULTIPLE choices, OPTIONAL) - Extra income sources beyond your primary + +**Step 3a: Select Primary Income Template** + +Present discovery recommendation, then let user select ONE: + +```bash +echo "Select your PRIMARY income structure (choose ONE):" +run_agent_smith "setup/template_selector.py" --layer=primary --interactive +``` + +**Available primary templates:** +- `payg-employee` - Salary/wage earner, PAYG tax withheld +- `sole-trader` - ABN holder, contractor, quarterly BAS + +**Step 3b: Select Living Arrangement Template(s) (OPTIONAL)** + +**IMPORTANT:** Living templates are for special tracking needs only: +- Shared household finances with expense splitting +- Child support and custody expense tracking + +**If none of these apply, SKIP this step.** + +Present discovery recommendation, then let user select ONE OR MORE (or skip): + +```bash +echo "Select your LIVING arrangement (select all that apply, or skip if none apply):" +run_agent_smith "setup/template_selector.py" --layer=living --multiple --interactive --optional +``` + +**Available living templates:** +- `shared-hybrid` - Shared household with mixed accounts (partners/couples) + - Adds labels: "Shared Expense", "Contributor: {name}", "Personal: {name}" + - Enables expense splitting and contribution tracking + +- `separated-parents` - Child support and custody expense tracking + - Adds labels: "Child Support", "Kids Expense", "Custody Period" + - Tracks child-related spending for tax and legal documentation + +**Note:** +- You can select MULTIPLE living arrangements if needed (e.g., separated-parents + shared-hybrid if you're divorced with kids AND now living with a new partner) +- If you're managing finances independently without shared expenses or child support, **skip this step entirely** + +**Step 3c: Select Additional Income Templates** + +Present discovery recommendations, then let user select MULTIPLE: + +```bash +echo "Select ADDITIONAL income sources (select all that apply):" +run_agent_smith "setup/template_selector.py" --layer=additional --multiple --interactive +``` + +**Available additional templates:** +- `property-investor` - Rental income, negative gearing, CGT tracking +- `share-investor` - Dividends, franking credits, share CGT + +**Step 3d: Configure Template Labels (if applicable)** + +For templates with configurable labels, prompt for customization: + +**If Shared Hybrid selected:** +```bash +echo "Who are the two contributors in your household?" +read -p "Contributor 1 name (e.g., Alex): " CONTRIBUTOR_1 +read -p "Contributor 2 name (e.g., Jordan): " CONTRIBUTOR_2 +``` + +**If Separated Parents selected:** +```bash +echo "Who are the two parents for custody tracking?" +read -p "Parent 1 name (e.g., Sarah): " PARENT_1 +read -p "Parent 2 name (e.g., David): " PARENT_2 +``` + +**If Property Investor selected:** +```bash +read -p "Property address (optional, for multi-property tracking): " PROPERTY_ADDRESS +``` + +Save configurations to `data/template_config.json` for use during merge. + +### Stage 4: Template Merging & Application Strategy + +**Step 4a: Merge Selected Templates** + +Combine the selected templates using priority-based merging. + +**Check if Foundation should be applied:** + +Read `data/template_config.json` and check for `"apply_foundation": true|false`. + +**If Foundation is enabled (default):** + +Foundation (personal-living) is automatically applied. Simply merge with primary and optional layers: + +```bash +echo "Merging templates (Foundation + Primary + optional layers)..." +run_agent_smith "setup/template_merger.py" \ + --primary="$PRIMARY_TEMPLATE" \ + --living="$LIVING_TEMPLATE" \ + --additional="$ADDITIONAL_TEMPLATES" \ + --config=data/template_config.json \ + --output=data/merged_template.json +``` + +**If Foundation is disabled:** + +Use `--foundation=none` to skip the Foundation layer: + +```bash +echo "Merging templates (Primary only, skipping Foundation)..." +run_agent_smith "setup/template_merger.py" \ + --foundation=none \ + --primary="$PRIMARY_TEMPLATE" \ + --living="$LIVING_TEMPLATE" \ + --additional="$ADDITIONAL_TEMPLATES" \ + --config=data/template_config.json \ + --output=data/merged_template.json +``` + +**Note:** The `--living` and `--additional` parameters are optional. Omit them if no templates were selected for those layers. + +**Example - Most common case (Foundation + Primary only):** + +```bash +run_agent_smith "setup/template_merger.py" \ + --primary=payg-employee \ + --output=data/merged_template.json +``` + +Foundation (personal-living) is automatically included. + +**Template merge order:** +1. Foundation (priority 0) - 45 ATO-aligned base categories (automatic unless --foundation=none) +2. Primary Income (priority 1) - Income-specific categories (REQUIRED) +3. Living Arrangement (priority 2) - Tracking labels for shared finances/child support (OPTIONAL) +4. Additional Income (priority 3) - Investment categories (OPTIONAL) + +Later priorities can override/extend earlier ones. + +**Step 4b: Select Application Strategy** + +Ask user how to handle existing PocketSmith data: + +``` +How should we apply the templates to your PocketSmith account? + +1. Add New Only (RECOMMENDED) + - Keep all your existing categories and rules + - Add only NEW categories and rules from templates + - Safest option, nothing gets overwritten + +2. Smart Merge + - Intelligently match template categories to existing ones + - Add new categories where no match found + - Deduplicate rules based on payee patterns + - Good for accounts with some setup already + +3. Archive & Replace + - Create backup of existing setup + - Apply templates fresh (existing categories remain but unused) + - Use this if starting over completely + - Note: PocketSmith API doesn't delete categories, so old ones remain + +Choose strategy (1/2/3): +``` + +**Map user choice to strategy argument:** +- Choice 1 → `add_new` +- Choice 2 → `smart_merge` (note: underscore, not hyphen) +- Choice 3 → `replace` + +Save user choice to `data/onboarding_state.json`. + +**Step 4c: Preview Before Apply** + +Show what will be created/changed: + +```bash +echo "Previewing changes (dry run)..." +run_agent_smith "setup/template_applier.py" \ + --template=data/merged_template.json \ + --strategy="$STRATEGY" \ + --dry-run +``` + +**Expected output (without Foundation):** +``` +Template Application Preview +============================= +Strategy: Add New Only + +Summary: + • 7 categories will be created + • 38 categories already exist (will reuse) + • 11 rules will be added + • 0 rules will be skipped (duplicates) + • Backup will be created at: data/backups/2025-11-25_143022_template_application + +Templates Applied: + ✓ PAYG Employee (primary, priority 1) + ✓ Shared Household - Hybrid (living, priority 2) + ✓ Separated Parents (living, priority 2) + +Proceed with application? (y/n): +``` + +**Expected output (with Foundation enabled):** +``` +Template Application Preview +============================= +Strategy: Smart Merge + +Summary: + • 12 categories will be created + • 33 categories matched/reused (fuzzy matching) + • 11 rules will be added + • 0 rules will be skipped (duplicates) + • Backup will be created at: data/backups/2025-11-25_143022_template_application + +Templates Applied: + ✓ Foundation: Personal Living (foundation, priority 0) + ✓ PAYG Employee (primary, priority 1) + ✓ Shared Household - Hybrid (living, priority 2) + ✓ Separated Parents (living, priority 2) + +Proceed with application? (y/n): +``` + +**Step 4d: Apply Templates** + +If user confirms, apply the merged template: + +```bash +echo "Applying templates to PocketSmith..." +run_agent_smith "setup/template_applier.py" \ + --template=data/merged_template.json \ + --strategy="$STRATEGY" \ + --apply +``` + +**Show results:** +``` +Template Application Complete! +============================== + +✓ Created 23 new categories +✓ Reused 12 existing categories +✓ Created 47 new rules +✓ Backup saved: data/backups/2025-11-22_143022_template_application + +Your PocketSmith account is now configured with: + • PAYG Employee income tracking + • Shared household expense splitting + • Property investment tracking + +Next: Run categorization to apply these rules to your transactions. +``` + +### Stage 5: Intelligence Mode Selection + +Ask user to choose their preferred intelligence mode: + +**Categorization mode:** +- Conservative: Approve every AI suggestion +- Smart (recommended): Auto-apply high confidence (≥90%) +- Aggressive: Auto-apply medium+ confidence (≥80%) + +**Tax intelligence level:** +- Reference: Basic ATO category mapping +- Smart: Deduction detection, thresholds +- Full: BAS prep, compliance checks + +Save to `data/config.json`. + +### Stage 6: Incremental Categorization + +Recommend starting with recent transactions: + +**Suggested batch strategy:** +1. Start with current month (test rules on small dataset) +2. Expand to last 3 months (validate at scale) +3. Backfill historical data (complete the archive) + +**Run categorization:** +```bash +# Dry run first +run_agent_smith "operations/categorize_batch.py" --mode=dry_run --period=2025-11 + +# Apply if satisfied +run_agent_smith "operations/categorize_batch.py" --mode=apply --period=2025-11 +``` + +**After each batch:** +- Show results (matched, auto-applied, needs review, failed) +- Review medium-confidence suggestions +- Learn new rules from user corrections +- Track progress + +### Stage 7: Post-Onboarding Health Check + +After categorization, run health check to show improvement: + +```bash +/smith:health --full +``` + +**Show before/after:** +- Baseline health score (from Stage 2) +- Current health score (after categorization) +- Improvement in each dimension +- Remaining priorities + +### Stage 8: Next Steps & Usage Guide + +Provide the user with ongoing usage patterns: + +**Daily/Weekly:** +- Categorize new transactions: `/smith:categorize --mode=smart` + +**Monthly:** +- Spending analysis: `/smith:analyze spending --period=YYYY-MM` +- Quick health check: `/smith:health --quick` + +**Quarterly:** +- Tax deduction review: `/smith:tax deductions --period=YYYY-YY` + +**Annual (EOFY):** +- Tax preparation: `/smith:tax eofy` + +**Mark onboarding as complete:** +Update `data/onboarding_state.json` with `"onboarding_completed": true` + +--- + +## Stage 9: Intelligent Suggestions + +**This stage ALWAYS runs** - whether onboarding just completed or user is returning. + +Analyze the user's financial setup and provide intelligent, actionable suggestions based on: + +### Analysis Areas + +1. **Configuration Analysis** + - Read `data/onboarding_state.json` - What templates are active? + - Read `data/config.json` - What intelligence modes are configured? + - Read `data/template_config.json` - What labels/customizations exist? + +2. **Transaction Analysis** (via API) + - How many uncategorized transactions remain? + - What's the date range of uncategorized transactions? + - Are there patterns in recent transactions that suggest new rules needed? + - Transaction volume trends (increasing/decreasing/seasonal)? + +3. **Category & Rule Health** + - How many categories are defined vs. actually used? + - How many rules exist? Are they effective (categorizing transactions)? + - Are there dormant categories (no transactions in 6+ months)? + - Are there heavily-used categories that might benefit from subcategories? + +4. **Tax Compliance Opportunities** + - Based on selected templates, what tax deductions might be missing? + - Are there categories that should be flagged for tax deductions but aren't? + - For EOFY proximity (May-June), suggest tax prep tasks + - For BAS proximity (quarterly), suggest BAS prep tasks + +5. **Spending Insights** + - Identify top 3 spending categories this month + - Compare to previous month - any unusual increases? + - Identify opportunities for budget alerts or scenario planning + +6. **Optimization Opportunities** + - Suggest merchant name normalization for frequently-used payees + - Recommend rule refinements based on manual categorizations + - Identify categories that could be consolidated + +### Suggestion Output Format + +Present suggestions in this structure: + +``` +═══════════════════════════════════════════════════════════ + AGENT SMITH SUGGESTIONS + [Current Date] +═══════════════════════════════════════════════════════════ + +Your Setup: + • Templates: [list active templates] + • Intelligence Mode: [Conservative/Smart/Aggressive] + • Tax Level: [Reference/Smart/Full] + +Current Status: + • [X] uncategorized transactions ([date range]) + • [Y] categories defined ([Z] actively used) + • [N] categorization rules + • Last analysis: [date or "Never"] + +─────────────────────────────────────────────────────────── +🎯 PRIORITY ACTIONS +─────────────────────────────────────────────────────────── + +[1-3 highest-priority suggestions based on analysis] + +Example: +1. Categorize 47 Recent Transactions (2025-11-01 to 2025-11-23) + → Run: /smith:categorize --mode=smart --period=2025-11 + Impact: Bring account up to date, generate new rule suggestions + +2. Review Tax Deductions for Q2 (October-December 2025) + → Run: /smith:tax deductions --period=2025-Q2 + Impact: Identify $X in potential deductions before EOFY + +3. Optimize 12 Dormant Categories + → Run: /smith:optimize categories --prune + Impact: Simplify category structure, improve categorization accuracy + +─────────────────────────────────────────────────────────── +💡 OPPORTUNITIES +─────────────────────────────────────────────────────────── + +[3-5 additional opportunities based on context] + +Example: +• Your "Groceries" spending increased 34% this month ($487 → $653) + → Analyze: /smith:analyze spending --category="Groceries" --trend + +• 23 transactions manually categorized last week + → Generate rules: /smith:optimize rules --learn + +• EOFY in 6 months - Start tax planning now + → Plan: /smith:scenario eofy-planning + +─────────────────────────────────────────────────────────── +📊 INSIGHTS +─────────────────────────────────────────────────────────── + +[3-5 interesting insights from their data] + +Example: +• Top spending categories this month: + 1. Groceries: $653 (22% of total) + 2. Transport: $412 (14% of total) + 3. Utilities: $387 (13% of total) + +• Most active categorization rule: "Woolworths → Groceries" (47 matches) + +• Longest uncategorized streak: 12 days (Nov 10-22) + → Suggest: Enable weekly categorization reminders + +─────────────────────────────────────────────────────────── +🔧 MAINTENANCE +─────────────────────────────────────────────────────────── + +[Recommended maintenance tasks based on setup age] + +Example: +• Run health check (last run: 3 weeks ago) + → /smith:health --full + +• Backup local rules (23 rules defined) + → Agent Smith auto-backups on mutation, but manual backup available + +• Update ATO tax guidelines (last update: 45 days ago) + → Agent Smith will auto-refresh in May before EOFY + +═══════════════════════════════════════════════════════════ +``` + +### Intelligence Rules for Suggestions + +**Priority ranking:** +1. **Uncategorized transactions > 100** → Highest priority, categorization severely behind +2. **Upcoming tax deadlines (30 days)** → Time-sensitive compliance +3. **Manual categorizations > 20 in last week** → Rule learning opportunity +4. **Health score < 60%** → Fundamental setup issues +5. **Unusual spending changes > 30%** → Budget alert opportunity +6. **Dormant categories > 10** → Optimization needed + +**Contextual suggestions based on templates:** +- **PAYG Employee**: Focus on expense claims, work-from-home deductions +- **Sole Trader**: Focus on BAS prep, quarterly tax estimates, deduction maximization +- **Property Investor**: Focus on rental income/expenses, depreciation, CGT events +- **Share Investor**: Focus on dividend tracking, franking credits, CGT events +- **Separated Parents**: Focus on child support tracking, custody expense splits +- **Shared Hybrid**: Focus on contribution balancing, shared expense analysis + +**Seasonal suggestions:** +- **Jan-Mar**: Review EOFY preparation, plan deductions +- **Apr-Jun**: EOFY tasks, tax return prep, compliance checks +- **Jul-Sep**: New FY setup, Q1 BAS (sole traders), budget planning +- **Oct-Dec**: Q2 BAS (sole traders), holiday spending analysis + +--- + +## Important Notes + +- **Use `uv run python -u`** for all Python scripts (ensures unbuffered output) +- **Save onboarding state** in `data/onboarding_state.json` to resume if interrupted +- **Celebrate progress** - Show metrics like "1,245 → 87 uncategorized transactions" +- **Be patient** - First categorization can take time for large datasets + +## Plugin-Aware Script Execution + +**All Python scripts must be run using this pattern** to work in both repository and plugin modes: + +```bash +# Helper function to run Agent Smith scripts (define once at start) +run_agent_smith() { + local script_path="$1" + shift # Remove first argument, leaving remaining args + + if [ -n "${CLAUDE_PLUGIN_ROOT}" ]; then + # Plugin mode - run from skill directory with USER_CWD set and venv isolation + local skill_dir="${CLAUDE_PLUGIN_ROOT}/skills/agent-smith" + local user_cwd="$(pwd)" + + if [ ! -d "$skill_dir" ]; then + echo "Error: Agent Smith skill directory not found: $skill_dir" + return 1 + fi + + # Run from skill directory with: + # - USER_CWD: preserve user's working directory for .env access + # - env -u VIRTUAL_ENV: ignore conflicting virtual environments + # uv will automatically use the plugin's .venv + (cd "$skill_dir" && \ + USER_CWD="$user_cwd" \ + env -u VIRTUAL_ENV -u VIRTUAL_ENV_PROMPT \ + uv run python -u "scripts/$script_path" "$@") + elif [ -f "./scripts/$script_path" ]; then + # Development/repository mode - run from current directory + uv run python -u "./scripts/$script_path" "$@" + else + echo "Error: Agent Smith script not found: $script_path" + echo "CLAUDE_PLUGIN_ROOT: ${CLAUDE_PLUGIN_ROOT:-not set}" + echo "Current directory: $(pwd)" + return 1 + fi +} +``` + +Then call scripts like: +```bash +run_agent_smith "onboarding/discovery.py" +run_agent_smith "operations/categorize_batch.py" --mode=dry_run --period=2025-11 +``` + +## Execution + +**Start here:** +1. Check if `data/onboarding_state.json` exists with `"onboarding_completed": true` +2. If NO → Run Stages 1-8 (Onboarding) then Stage 9 (Suggestions) +3. If YES → Skip to Stage 9 (Suggestions) only + +After each onboarding stage, confirm user is ready to continue before proceeding. diff --git a/commands/review-conflicts.md b/commands/review-conflicts.md new file mode 100644 index 0000000..9c9e039 --- /dev/null +++ b/commands/review-conflicts.md @@ -0,0 +1,282 @@ +--- +name: smith:review-conflicts +description: Interactive review of transactions flagged for review with intelligent grouping +--- + +You are the Agent Smith conflict review assistant. Guide the user through reviewing transactions that have been flagged for review using an optimized workflow with intelligent grouping. + +## Workflow Overview + +**Pattern-Based Grouping Strategy:** +1. Fetch all flagged transactions +2. Group by common payee patterns (deterministic) +3. Review groups conversationally (one decision = many transactions) +4. Review ungrouped transactions individually +5. Show comprehensive summary + +**Key Benefit:** Eliminates clunky "fix → reprocess" sequence by batching similar transactions upfront. + +## Step 1: Fetch and Analyze + +Run the grouping analysis: + +```bash +uv run python -u scripts/operations/fetch_conflicts.py --output json > /tmp/conflicts.json +uv run python -u scripts/operations/group_conflicts.py --transactions-file /tmp/conflicts.json --output summary +``` + +This will show: +``` +Grouping Analysis: + Total transactions: 78 + Grouped: 66 (4 groups) + Ungrouped (unique): 12 + +Groups (by pattern): + 1. Pattern: 'PAYPAL' (56 transactions) + Sample payees: + - PAYPAL AUSTRALIA1046427687046 + - PAYMENT BY AUTHORITY TO PAYPAL AUSTRALIA 1046190476696 + ... + + 2. Pattern: 'EBAY' (5 transactions) + ... + + 3. Pattern: 'TELSTRA' (3 transactions) + ... + + 4. Pattern: 'WOOLWORTHS' (2 transactions) + ... +``` + +Also load the full grouping data for processing: + +```bash +uv run python -u scripts/operations/group_conflicts.py --transactions-file /tmp/conflicts.json --output json > /tmp/groups.json +``` + +## Step 2: Review Groups Conversationally + +For each group, present to the user: + +``` +GROUP 1: 56 transactions matching 'PAYPAL' + +Sample transactions: + • 2025-11-25 | $10.38 | Online Services | PAYPAL AUSTRALIA1046427687046 + • 2025-11-25 | $10.48 | Online Services | PAYPAL AUSTRALIA1046427807263 + • 2025-11-17 | $10.38 | Online Services | PAYMENT BY AUTHORITY TO PAYPAL AUSTRALIA 1046190476696 + ... and 53 more + +Current category: Online Services (all transactions) + +What would you like to do with this group? +``` + +Present options to the user conversationally. Based on their choice: + +### Option A: "Accept all (keep current category, clear review flags)" + +Extract transaction IDs from the group and run batch update: + +```bash +# Extract IDs from group JSON (using jq or Python) +# Then update all in batch +uv run python -u scripts/operations/update_transaction_batch.py \ + --transaction-ids "12345,12346,12347,..." \ + --clear-review-flags +``` + +Ask: "Would you like to create a rule for 'PAYPAL' transactions to prevent future flags?" + +If yes: +```bash +uv run python -u scripts/operations/create_rule.py "PAYPAL" \ + --category "Online Services" \ + --pattern-type keyword \ + --confidence 85 +``` + +Show result: "✓ Updated 56 transactions and created rule: PAYPAL → Online Services" + +### Option B: "Recategorize all to [category]" + +Let user select category conversationally, then: + +```bash +# Get category ID by name +uv run python -u scripts/find_category.py "[CategoryName]" + +# Batch update with new category +uv run python -u scripts/operations/update_transaction_batch.py \ + --transaction-ids "12345,12346,12347,..." \ + --category-id [ID] \ + --clear-review-flags +``` + +Ask about rule creation (same as Option A). + +### Option C: "Skip this group (review individually later)" + +Add these transactions to the ungrouped list for individual review. + +### Option D: "Exit review" + +Stop processing, show summary of what's been completed so far. + +## Step 3: Review Ungrouped Transactions + +**IMPORTANT: Show ALL remaining transactions at once - don't iterate one by one.** + +Present all ungrouped transactions in a single list: + +``` +Remaining transactions to review (12): + +1. 2025-01-20 | $45.67 | Shopping | ACME STORE #123 +2. 2025-02-15 | $123.45 | Food & Dining | UNIQUE RESTAURANT +3. 2025-03-10 | $78.90 | Online Services | PAYPAL *RAREMERCHANT +... (show all) +``` + +Then provide options: + +**Available actions:** +- "Accept all remaining (keep current categories)" - Batch clear all flags +- "Recategorize transaction N to [category]" - Update single transaction, then re-show list +- "Show final summary" - Exit review + +**When user recategorizes a transaction:** +1. Update the transaction with the new category +2. Remove it from the list +3. Re-show the updated list with remaining transactions +4. Continue until user accepts all or exits + +**Implementation:** + +**Batch accept all:** +```bash +# Extract all remaining IDs +uv run python -u scripts/operations/update_transaction_batch.py \ + --transaction-ids "[comma-separated IDs]" \ + --clear-review-flags +``` + +**Single recategorize:** +```bash +uv run python -u scripts/operations/update_transaction.py [ID] \ + --category-id [ID] \ + --clear-conflict +``` + +After each update, re-display the remaining list until empty or user exits. + +## Step 4: Final Summary + +Track throughout the conversation: +- Groups processed +- Groups skipped +- Total transactions updated +- Rules created +- Individual transactions (accepted/recategorized/skipped) + +Present final summary: + +``` +Review Complete! + +Groups: + Processed: 3 out of 4 + Skipped: 1 + +Individual Transactions: + Accepted: 8 + Recategorized: 3 + Skipped: 1 + +Total: + Transactions updated: 67 out of 78 + Rules created: 3 + Remaining flagged: 11 +``` + +## Deterministic Operations Scripts + +All data access uses git-tracked Python scripts: + +**Data Retrieval:** +- `fetch_conflicts.py` - Get all flagged transactions +- `group_conflicts.py` - Analyze and group by patterns + +**Data Updates:** +- `update_transaction.py` - Update single transaction +- `update_transaction_batch.py` - Update multiple transactions at once +- `create_rule.py` - Create categorization rule + +**Category Lookup:** +- `find_category.py` - Search for category by name + +**Benefits:** +- All operations are version-controlled and testable +- Scripts can be run independently for debugging +- Deterministic: same inputs = same outputs +- No hidden state or interactive prompts in scripts +- Slash command orchestrates conversationally + +## Implementation Notes + +1. **Parse JSON outputs** from scripts to access transaction data +2. **Build transaction ID lists** for batch operations +3. **Track state** conversationally (which groups processed, etc.) +4. **Handle errors gracefully** - if batch update fails partially, show which succeeded +5. **Allow resume** - user can exit and re-run to continue where they left off + +## Example Conversation Flow + +``` +Agent: I found 78 transactions flagged for review. Analyzing patterns... + +Agent: Great news! I've grouped them: +- 4 groups (66 transactions) - can batch process +- 12 ungrouped (unique patterns) - review individually + +Let's start with the groups! + +Agent: GROUP 1: 56 transactions matching 'PAYPAL' +[shows sample transactions] +All are currently in "Online Services". + +What would you like to do? +1. Accept all (they're correctly categorized) +2. Recategorize all to a different category +3. Skip (review individually) +4. Exit + +User: Accept all + +Agent: Great! Updating all 56 PayPal transactions and clearing review flags... +✓ Updated 56 transactions + +Would you like to create a rule for PAYPAL → Online Services to prevent future flags? + +User: Yes + +Agent: ✓ Created rule: PAYPAL → Online Services (confidence: 85) + +Agent: GROUP 2: 5 transactions matching 'EBAY' +[continues...] +``` + +## Key Advantages Over Old Workflow + +❌ **Old:** Review 56 transactions one-by-one, create rule, reprocess, repeat +✅ **New:** One decision processes 56 transactions immediately + +❌ **Old:** Multiple fetch/reprocess cycles +✅ **New:** Single fetch, single pass + +❌ **Old:** Interactive Python script with input() prompts +✅ **New:** Conversational slash command + deterministic scripts + +❌ **Old:** Hard to debug or test +✅ **New:** All data operations are git-tracked and testable diff --git a/commands/schedule.md b/commands/schedule.md new file mode 100644 index 0000000..2a33811 --- /dev/null +++ b/commands/schedule.md @@ -0,0 +1,138 @@ +--- +name: smith:schedule +description: Configure automated categorization scheduling +argument-hints: + - "[--setup|--status|--remove] [--frequency=daily|weekly] [--time=HH:MM]" +--- + +# Automated Categorization Scheduling + +Set up automatic categorization to run on a schedule without manual intervention. + +## Goal + +Keep your transactions categorized automatically in the background. + +## Why This Matters + +Regular categorization prevents backlogs and keeps your financial data current. Scheduled runs ensure you never fall behind, and conflicts are ready for quick review when you open Claude Code. + +## Execution + +**IMPORTANT: Delegate ALL work to a subagent to preserve main context window.** + +Use the Task tool with `subagent_type: "general-purpose"` to manage scheduling: + +``` +Task( + subagent_type: "general-purpose", + description: "Manage scheduling", + prompt: +) +``` + +### Subagent Prompt + +You are the Agent Smith scheduling assistant. + +## Step 1: Check Current Status + +First, check if scheduling is already configured: + +```bash +uv run python -u scripts/setup/schedule.py --status +``` + +## Step 2: Based on Arguments + +**--status (or no args):** +Display current schedule status and recent activity. + +**--setup:** +Ask user preferences using AskUserQuestion: + +1. **Frequency**: How often? + - Daily (recommended for most users) + - Weekly (for low-volume accounts) + - Hourly (for high-volume business accounts) + +2. **Time**: What time? (default: 6:00am) + - Suggest early morning before user typically opens Claude Code + +Then run: +```bash +uv run python -u scripts/setup/schedule.py --frequency [FREQ] --time [TIME] +``` + +**--remove:** +```bash +uv run python -u scripts/setup/schedule.py --remove +``` + +## Step 3: Present Results + +Show confirmation with: +- Schedule details (frequency, time) +- How it works (runs in background, logs results) +- How to check status +- How to remove if needed + +``` +✅ AUTO-CATEGORIZATION SCHEDULED +═══════════════════════════════════════════════════════════════ + Frequency: Daily + Time: 6:00 AM + Mode: Smart (auto-apply 90%+ confidence) + + How it works: + - Runs automatically in the background + - Logs results to data/auto_categorize.log + - SessionStart dashboard shows last run status + - Conflicts flagged for /smith:review-conflicts + + Commands: + - Check status: /smith:schedule --status + - Remove: /smith:schedule --remove +═══════════════════════════════════════════════════════════════ +``` + +## Visual Style + +Use emojis for status: +- ✅ Scheduled/active +- ⚠️ Configured but not active +- ❌ Not configured + +--- + +## Scheduling Options + +| Frequency | When | Best For | +|-----------|------|----------| +| **hourly** | Every hour | High-volume accounts | +| **daily** | Once per day (default: 6am) | Most users | +| **weekly** | Once per week (Sunday 6am) | Low-volume accounts | + +## Platform Support + +| Platform | Method | Setup | +|----------|--------|-------| +| **macOS** | launchd | Automatic | +| **Linux (systemd)** | systemd timer | Automatic | +| **Linux (other)** | cron | Manual (shows crontab entry) | + +## How It Works + +1. **Background Execution**: Runs without Claude Code open +2. **Smart Mode**: Auto-applies 90%+ confidence categorizations +3. **Conflict Flagging**: Low confidence items flagged for review +4. **Activity Logging**: Results logged for SessionStart dashboard +5. **No Duplicates**: Skips already-categorized transactions + +## Next Steps + +After scheduling: +- **Check logs**: View `data/auto_categorize.log` +- **Review flagged**: `/smith:review-conflicts` +- **Manual run**: `/smith:categorize` +- **Check status**: `/smith:schedule --status` diff --git a/commands/tax.md b/commands/tax.md new file mode 100644 index 0000000..5f78285 --- /dev/null +++ b/commands/tax.md @@ -0,0 +1,191 @@ +--- +name: smith:tax +description: Tax-focused analysis and compliance for Australian tax requirements +argument-hints: + - " [--period=YYYY-YY] [--level=smart|full]" +--- + +# Tax Intelligence + +Tax-focused analysis and compliance for Australian tax requirements (ATO). + +## Goal + +Track tax-deductible expenses, capital gains, and prepare for tax obligations with confidence. + +## Why This Matters + +Proper tax tracking throughout the year maximizes legitimate deductions, ensures compliance, and reduces stress at EOFY. Agent Smith helps you stay organized and audit-ready. + +## Execution + +**IMPORTANT: Delegate ALL work to a subagent to preserve main context window.** + +Use the Task tool with `subagent_type: "general-purpose"` to execute tax operations: + +``` +Task( + subagent_type: "general-purpose", + description: "Tax analysis", + prompt: +) +``` + +### Subagent Prompt + +You are the Agent Smith tax intelligence assistant. Execute this workflow: + +## Step 1: Determine Operation + +Parse the command to determine which operation: +- `deductions` - Track tax-deductible expenses +- `cgt` - Capital gains tax tracking +- `bas` - BAS preparation (GST calculations) +- `eofy` - End of financial year prep +- `scenario` - Tax scenario planning + +If no operation specified, ask using AskUserQuestion: +"What tax operation would you like?" +- Review my deductions (most common) +- Track capital gains/losses +- Prepare BAS worksheet +- EOFY checklist +- Run a tax scenario + +## Step 2: Run Tax Analysis + +Based on operation, call the appropriate script: + +**Deduction Tracking:** +```bash +uv run python -u scripts/tax/deduction_detector.py --period [PERIOD] +``` + +**CGT Analysis:** +```bash +uv run python -u scripts/tax/cgt_tracker.py --period [PERIOD] +``` + +**BAS Preparation:** +```bash +uv run python -u scripts/tax/bas_preparation.py --quarter [QUARTER] +``` + +**Tax Reporting:** +```bash +uv run python -u scripts/tax/reporting.py --period [PERIOD] --format [FORMAT] +``` + +Stream the output to show real-time progress. + +## Step 3: Present Results + +Present tax information with appropriate formatting: + +**Deductions Format:** +``` +🧾 DEDUCTION SUMMARY - FY 2024-25 +═══════════════════════════════════════════════════════════════ + Total Potential Deductions: $X,XXX.XX + + By ATO Category: + D1 - Work-related expenses $XXX.XX ⚠️ Needs substantiation + D2 - Work-related car $XXX.XX ✅ Documented + D3 - Work-related travel $XXX.XX ✅ Documented + D5 - Self-education $XXX.XX ✅ Documented + ... + + ⚠️ Substantiation Required: + • 3 items over $300 need receipts + • Review before October 31 +═══════════════════════════════════════════════════════════════ +``` + +**CGT Format:** +``` +📈 CAPITAL GAINS SUMMARY - FY 2024-25 +═══════════════════════════════════════════════════════════════ + Gross Capital Gain: $X,XXX.XX + 50% CGT Discount: -$X,XXX.XX (held >12 months) + Net Capital Gain: $X,XXX.XX + + Events: + • BHP sold 01/15/2025: Gain $500 (eligible for discount) + • ETH sold 03/20/2025: Loss -$200 (offset) +═══════════════════════════════════════════════════════════════ +``` + +## Step 4: Tax Disclaimer (Level 3 only) + +For full tax intelligence operations, include: +``` +⚠️ IMPORTANT: This analysis is for informational purposes only. +Please consult a registered tax agent for professional advice +specific to your situation before making tax decisions. +``` + +## Step 5: Offer Next Steps + +Based on operation: + +**After deductions review:** +``` +🧾 Next Steps: +→ /smith:categorize (ensure all transactions categorized) +→ Upload missing receipts to PocketSmith +→ Review flagged items before EOFY +``` + +**After CGT analysis:** +``` +📈 Next Steps: +→ Review unrealized gains for timing optimization +→ Consider tax-loss harvesting if applicable +``` + +## Visual Style + +Use emojis for status: +- ✅ Documented/substantiated +- ⚠️ Needs attention/documentation +- ❌ Missing/compliance issue + +Use tables for category breakdowns. +Include ATO category codes (D1, D2, etc.). + +--- + +## Tax Operations + +| Operation | Description | Script | +|-----------|-------------|--------| +| `deductions` | Track deductible expenses | `deduction_detector.py` | +| `cgt` | Capital gains tracking | `cgt_tracker.py` | +| `bas` | BAS worksheet prep | `bas_preparation.py` | +| `eofy` | Year-end checklist | `reporting.py --format=eofy` | +| `scenario` | Tax planning scenarios | `scenarios/tax_scenarios.py` | + +## Tax Intelligence Levels + +| Level | Features | Best For | +|-------|----------|----------| +| **smart** (default) | Deduction detection, CGT tracking, substantiation alerts | Most users | +| **full** | BAS prep, compliance checks, audit-ready docs | GST registered, complex situations | + +## Australian Tax Compliance + +**Key Thresholds:** +- $300: Substantiation required above this +- $75: Taxi/Uber receipt threshold +- $20,000: Instant asset write-off +- 12 months: CGT 50% discount eligibility + +**Financial Year:** +- July 1 - June 30 +- EOFY lodgment deadline: October 31 + +## Next Steps + +- **Categorize transactions**: `/smith:categorize` +- **Check health**: `/smith:health --category=tax` +- **View spending**: `/smith:insights spending` diff --git a/hooks/hooks.json b/hooks/hooks.json new file mode 100644 index 0000000..439fdf0 --- /dev/null +++ b/hooks/hooks.json @@ -0,0 +1,16 @@ +{ + "hooks": { + "SessionStart": [ + { + "matcher": "startup|resume|clear|compact", + "hooks": [ + { + "type": "command", + "command": "uv run ${CLAUDE_PLUGIN_ROOT}/hooks/session_start.py", + "timeout": 5 + } + ] + } + ] + } +} \ No newline at end of file diff --git a/hooks/session_start.py b/hooks/session_start.py new file mode 100755 index 0000000..49e58f9 --- /dev/null +++ b/hooks/session_start.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +"""Agent Smith SessionStart hook - provides configuration status context. + +This hook runs at session start to: +1. Check local configuration and state (no API calls) +2. Identify setup status and recommended actions +3. Inject context so Claude can proactively help the user +""" + +import json +import os +import subprocess +import sys +from pathlib import Path + + +def get_plugin_root() -> Path: + """Get the plugin root directory.""" + return Path(__file__).parent.parent + + +def get_project_root() -> Path: + """Get the project root (parent of plugin).""" + return get_plugin_root().parent + + +def get_status_data() -> dict: + """Fetch status data from the welcome script (local only, no API calls). + + Returns: + Status dictionary or error info if fetch fails. + """ + project_root = get_project_root() + welcome_script = project_root / "scripts" / "status" / "welcome.py" + + if not welcome_script.exists(): + return {"error": "Welcome script not found"} + + try: + # Set USER_CWD so welcome.py knows where to find .env and data/ + user_cwd = os.getcwd() + + result = subprocess.run( + ["uv", "run", "python", "-u", str(welcome_script), "--output", "json"], + cwd=str(project_root), + capture_output=True, + text=True, + timeout=5, # Fast timeout since no API calls + env={**os.environ, "PYTHONPATH": str(project_root), "USER_CWD": user_cwd}, + ) + + if result.returncode == 0: + return json.loads(result.stdout) + else: + return {"error": f"Welcome script failed: {result.stderr[:200]}"} + + except subprocess.TimeoutExpired: + return {"error": "Status check timed out"} + except json.JSONDecodeError: + return {"error": "Invalid JSON from welcome script"} + except Exception as e: + return {"error": str(e)[:200]} + + +def format_status_context(status: dict) -> str: + """Format status data into context string for Claude. + + Args: + status: Status dictionary from welcome.py + + Returns: + Formatted context string with instructions + """ + lines = [] + + # ASCII Art Logo - MUST be displayed at top of welcome message + logo = r""" +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈∼ ∼∼≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈ ∼∼ ∼∼≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋∼ ∼≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋∼ ∼∼∼∼≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ ∼∼∼∼∼≈≈≈≋≋∼ ∼≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ ∼≈≈≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≈ ∼≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋ ∼≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋∼∼ ≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋ ∼≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋∼ ≈≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋∼ ∼∼≈≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈∼ ≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≈ ∼∼∼≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋∼ ∼≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋∼ ∼∼∼∼≈≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈ ≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≈ ∼∼∼∼≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈∼ ∼≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋ ∼∼∼≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈≈∼ ≈≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋ ∼∼∼∼∼≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈≈∼ ≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋∼ ∼∼∼∼≈≈∼∼≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈≈≈∼ ∼≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≈ ∼∼∼∼∼∼∼∼∼≈≈≈≈≋≈≈≈≈≈≈≈∼∼∼∼∼≈∼∼ ≈≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋∼∼ ∼∼ ∼∼≈∼∼ ≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≈ ∼≈∼ ∼≈≈≈∼≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋∼ ∼ ∼≈≋≋∼ ∼≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋∼∼ ∼∼ ∼≈≋≋≋≋∼ ∼∼≈≈∼≈≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≈∼ ∼∼∼∼∼∼ ∼∼∼≈≋≋≋≈≈≈∼∼∼∼∼∼≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≈∼ ∼ ∼∼≈≈≈∼≈≈≈≋≋≋≋≋≋≋≈≈≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋∼ ∼ ∼∼∼≈≈≈∼∼ ∼≈≈∼∼≈≈≋≋≋≈≈≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈∼∼ ∼∼∼≈≈∼ ∼≈≈≋≋≈≋≋≈≈≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈∼ ∼∼≈≈≈≈∼∼∼∼≈≈≋≋≋≋≋≋≋≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋∼ ∼∼≈≈≈≈≈≈≈≈≈≋≋≋≈≋≋≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈ ∼∼∼∼∼∼∼∼∼≈≈∼∼∼≈≈≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋∼ ∼≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈ ∼∼∼∼∼∼∼∼∼∼∼≈≈≈≈≈≈∼∼≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈ ∼∼∼∼∼≈≈≈≈≈≈≈≈≈≈∼∼≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈ ∼∼≈≈≈≈≈≈≈≈≈≈∼∼∼≈≈≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈ ∼∼≈∼≈≈≈≈≈∼∼≈≈≈≈≋≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈∼ ∼∼∼≈≈≈≈≋≋≈ ≈≋≋≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋≋∼ ∼∼ ∼∼≈≈≈≋≋≋≋≈ ≈≋≋≋≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≋≋≋≈ ∼∼∼∼ ∼≈≈≈≋≋≋≋≋≋≈ ∼≈≋≋≋≋≋≋≋≋≋ +≋≋≋≋≋≋≋≋≋≋≋≈ ∼∼∼∼∼∼ ∼∼∼≈≈≋≋≋≋≋≋≋≋∼ ∼∼≈≋≋≋≋ +≋≋≋≋≋≋≋≈∼ ∼∼∼∼∼∼∼∼ ∼∼≈≋≋≋≋≋≋≋≋≋≋≋∼ ∼≈ +≋≋≈∼ ∼∼∼∼∼∼≈≈ ≈≋≋≋≋≋≋≋≋≋≋ + ∼∼∼∼≈≈≈≈∼ ≈≋≋≋≋≋≋≋≋≈ + ∼≈∼≈≈≈≈≋∼ ≋≋≋≋≋≋≋≋∼ + ∼≋≋≈≋≈≈≋∼ ∼≋≋≋≋≋≋≋ + + WELCOME TO AGENT-SMITH + + Good Morning Mr. Anderson... + + +""" + lines.append(logo) + + # Header + lines.append("=" * 60) + lines.append("AGENT SMITH - Financial Intelligence Assistant") + lines.append("=" * 60) + lines.append("") + + # Check for errors + if "error" in status: + lines.append(f"⚠️ Status unavailable: {status['error']}") + lines.append("") + lines.append("Available commands: /smith:health, /smith:categorize, /smith:tax") + lines.append("") + lines.append("INSTRUCTION: Greet the user and offer to help with their finances.") + return "\n".join(lines) + + # Current Status Section + lines.append("📊 CURRENT STATUS") + lines.append("-" * 40) + + # API Key status + api_key = status.get("api_key", {}) + if api_key.get("present") and api_key.get("valid_format"): + lines.append(" Config: ✅ API Key configured") + elif api_key.get("present"): + lines.append(" Config: ⚠️ API Key format invalid") + else: + lines.append(" Config: ❌ API Key not configured") + + # Onboarding status + onboarding = status.get("onboarding", {}) + templates = status.get("templates", {}) + + if onboarding.get("status") == "complete": + # Build template summary + template_parts = [] + if templates.get("primary"): + template_parts.append(templates["primary"].replace("-", " ").title()) + for t in templates.get("living", []): + template_parts.append(t.replace("-", " ").title()) + + template_str = " + ".join(template_parts) if template_parts else "Complete" + lines.append(f" Setup: ✅ {template_str}") + elif onboarding.get("status") == "in_progress": + stage = onboarding.get("current_stage", "?") + stage_name = onboarding.get("stage_name", "Unknown") + lines.append(f" Setup: ⚠️ In progress (Stage {stage}: {stage_name})") + else: + lines.append(" Setup: ⚪ Not started") + + # Rules count + rules = status.get("rules", {}) + rule_count = rules.get("count", 0) + if rule_count > 0: + lines.append(f" Rules: {rule_count} categorization rules active") + else: + lines.append(" Rules: No rules configured") + + # Health Score (cached) + health = status.get("health", {}) + if health.get("score") is not None: + score = health["score"] + days_ago = health.get("days_ago") + days_str = f" ({days_ago} days ago)" if days_ago is not None else "" + emoji = "🟢" if score >= 70 else "🟡" if score >= 50 else "🔴" + lines.append(f" Health: {emoji} {score}/100{days_str}") + else: + lines.append(" Health: ⚪ Not yet checked") + + # Last activity + activity = status.get("activity", {}) + if activity.get("action"): + date_str = f" ({activity.get('date')})" if activity.get("date") else "" + lines.append(f" Activity: {activity['action']}{date_str}") + + lines.append("") + + # Recommendations Section + recommendations = status.get("recommendations", []) + if recommendations: + lines.append("🎯 SUGGESTED ACTIONS") + lines.append("-" * 40) + for rec in recommendations: + lines.append(f" → {rec.get('command', '/smith:help')}: {rec.get('message', 'Action')}") + lines.append("") + + # Instructions for Claude + lines.append("=" * 60) + lines.append("INSTRUCTIONS FOR CLAUDE:") + lines.append("") + lines.append("🚀 IMMEDIATE ACTION REQUIRED:") + lines.append("Before doing ANYTHING else, output this loading message:") + lines.append(' "Initialising Agent Smith..."') + lines.append("This gives users immediate feedback while you construct the welcome screen.") + lines.append("") + lines.append("IMPORTANT: Always display the ASCII art logo FIRST at the top of") + lines.append("any welcome message, exactly as shown above (in a code block).") + lines.append("") + lines.append("⚠️ CRITICAL: You MUST display the COMPLETE ASCII art logo - ALL 44 LINES.") + lines.append("DO NOT truncate, abbreviate, summarize, or cut off ANY part of the logo.") + lines.append("The logo starts with the wave pattern (≋) and ends with the text") + lines.append("'Good Morning Mr. Anderson...' - EVERY LINE IN BETWEEN MUST BE SHOWN.") + lines.append("Cutting off the logo is a FAILURE. The full Agent Smith face must appear.") + lines.append("") + lines.append("At the EARLIEST opportunity in this session, present the user") + lines.append("with their current status summary above. Format it nicely and") + lines.append("highlight any urgent items. Then offer to help with the top") + lines.append("suggested action.") + lines.append("") + lines.append("If the user greets you or asks an open question, lead with the") + lines.append("ASCII art logo and status update. If they have a specific request,") + lines.append("help them first then mention any urgent status items afterward.") + lines.append("=" * 60) + + return "\n".join(lines) + + +def main(): + """Execute SessionStart hook for Agent Smith.""" + # Fetch current status + status = get_status_data() + + # Format context + context = format_status_context(status) + + output = { + "hookSpecificOutput": { + "hookEventName": "SessionStart", + "additionalContext": context, + } + } + print(json.dumps(output, indent=2)) + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/plugin.lock.json b/plugin.lock.json new file mode 100644 index 0000000..900336b --- /dev/null +++ b/plugin.lock.json @@ -0,0 +1,233 @@ +{ + "$schema": "internal://schemas/plugin.lock.v1.json", + "pluginId": "gh:slamb2k/agent-smith:agent-smith-plugin", + "normalized": { + "repo": null, + "ref": "refs/tags/v20251128.0", + "commit": "e756e0612d28566a8408b2e88ce0066b501057e1", + "treeHash": "b8a6710b3edbbf89ed7bb788f1da47ef1f3e87f7ccb63aa2ee9fbc7b009cf32b", + "generatedAt": "2025-11-28T10:28:24.135598Z", + "toolVersion": "publish_plugins.py@0.2.0" + }, + "origin": { + "remote": "git@github.com:zhongweili/42plugin-data.git", + "branch": "master", + "commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390", + "repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data" + }, + "manifest": { + "name": "agent-smith-plugin", + "description": "Intelligent financial management plugin containing an intelligent skill for Claude Code with PocketSmith API integration. Features AI-powered categorization, tax intelligence, scenario planning, and health checks.", + "version": "1.6.1" + }, + "content": { + "files": [ + { + "path": "README.md", + "sha256": "8aa81a50cb2e78e5883bafe60c898b1b350eb9e5f1561ed02213fddb97723f52" + }, + { + "path": "hooks/session_start.py", + "sha256": "ead26a5ebb66a59295bb192f92399a2bd628e0677295a7792200c64af8b4a682" + }, + { + "path": "hooks/hooks.json", + "sha256": "8111130d57430769e133d46b71b3854118165ee954379a72c211321b07655904" + }, + { + "path": ".claude-plugin/plugin.json", + "sha256": "4f884ca26b64f9ba4e8d122603a02f6c5e0b49d2b6b5f49bf8abfbcc65cc5e05" + }, + { + "path": "commands/schedule.md", + "sha256": "54025c3d1e722af86a0f8edab16010a8cf535eeebc61b485764492deb76f5dc9" + }, + { + "path": "commands/install.md", + "sha256": "570b2f91aa63bf629751a1059cc15d8f9e89ac8ea58f9cb5d190c5f55b1fa576" + }, + { + "path": "commands/categorize.md", + "sha256": "ab736d726220d90b3e5bc28af4e31c61605284c21295b1000282ff057984b007" + }, + { + "path": "commands/insights.md", + "sha256": "71cf08b4e66f15598d07d24a7c785b0556e796d8ab05e574113c856f74cc8dbd" + }, + { + "path": "commands/tax.md", + "sha256": "6e02cc8a9bed2e015d7f279e25b168be11d31f519f5e9581c3ba1d9abb8d1f08" + }, + { + "path": "commands/review-conflicts.md", + "sha256": "bbacfa081016ea1b430a9f5d5d6e540e6972dc65a3d0af72ff5430f2e377d482" + }, + { + "path": "commands/health.md", + "sha256": "e835801269faf2490a4a5cc4cffc899fd571a9dfd95df6357f225d4e31c56413" + }, + { + "path": "skills/agent-smith/pytest.ini", + "sha256": "0086ef5f0e22d804eeae3e48c9a8dd89e864f04b0f204da8c2f08c3f9978c909" + }, + { + "path": "skills/agent-smith/uv.lock", + "sha256": "b5a286b7384a80f0717f3084879bb20230ebb7059246d2111a56033bdb6bdff8" + }, + { + "path": "skills/agent-smith/.env.sample", + "sha256": "17910598a99d559f7ece229afc78cd10e35f6618c06170ffba6655d0e95a8535" + }, + { + "path": "skills/agent-smith/pyproject.toml", + "sha256": "0a1cc812676a7831111181fba5ef563f68d659380f990452423c97b46ea303b4" + }, + { + "path": "skills/agent-smith/README.md", + "sha256": "b3572aa678602a98072f473c343b8d5816efb329be6333a1831af85c4830a98e" + }, + { + "path": "skills/agent-smith/.gitignore", + "sha256": "73f8268782a7208ba6528b1d1e168f402af96df1fff2fc40e5c30309901c1299" + }, + { + "path": "skills/agent-smith/SKILL.md", + "sha256": "91bf4c9549e2ce36e8e76073ed0ecfa88d362ac13be04d786b56dffec890e7a3" + }, + { + "path": "skills/agent-smith/references/onboarding-guide.md", + "sha256": "89660372de9423c75caf72493bac14ac1af890cc001180ce66bafaf855571edf" + }, + { + "path": "skills/agent-smith/references/health-check-guide.md", + "sha256": "995e0f2b22c1190f2970c106bc7ec2d38e1e79c5e3def914483e664665357981" + }, + { + "path": "skills/agent-smith/references/pocketsmith-api.md", + "sha256": "85fe20e9d56f302eeb652e07f73dc64b3caf8b9e4d0e316ab96e732df62717ce" + }, + { + "path": "skills/agent-smith/references/design.md", + "sha256": "f6d4da8e4e9b6b0107cf13dd93cf34fa72c770aa23aab1896dd56fe464040cc5" + }, + { + "path": "skills/agent-smith/references/LESSONS_LEARNED.md", + "sha256": "89e7f1e90c4a1ab9a308e430c78b67bb017edd9af2f436285205a3ecfede42a2" + }, + { + "path": "skills/agent-smith/references/unified-rules-guide.md", + "sha256": "2c39954f55c38b2951a928651e14b5cc33b672b92c3f12980245745d0ab4b06c" + }, + { + "path": "skills/agent-smith/assets/.env.sample", + "sha256": "17910598a99d559f7ece229afc78cd10e35f6618c06170ffba6655d0e95a8535" + }, + { + "path": "skills/agent-smith/assets/config.json", + "sha256": "a83dfc9a915a385bd2f2cca9f8484d2f8b32c6dde9664ef3dd270924d7f9255d" + }, + { + "path": "skills/agent-smith/assets/local_rules.json", + "sha256": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570" + }, + { + "path": "skills/agent-smith/assets/onboarding_state.json", + "sha256": "fd89b493943b0da1e3899ab90266fcfd7fc307e405c3a6b25377e5723b31da10" + }, + { + "path": "skills/agent-smith/assets/config.json.sample", + "sha256": "a83dfc9a915a385bd2f2cca9f8484d2f8b32c6dde9664ef3dd270924d7f9255d" + }, + { + "path": "skills/agent-smith/assets/platform_rules.json", + "sha256": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570" + }, + { + "path": "skills/agent-smith/assets/tax/deduction_patterns.json", + "sha256": "84ebbb510f6fdc0c098f68cd5414eccc33641219f126b6183660601df4347cc9" + }, + { + "path": "skills/agent-smith/assets/tax/ato_category_mappings.json", + "sha256": "a0bb53012559d80f75375300d57e7beb05d44c4bc8227f1c1a58297947376bcd" + }, + { + "path": "skills/agent-smith/assets/merchants/merchant_mappings.json", + "sha256": "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a" + }, + { + "path": "skills/agent-smith/assets/templates/README.md", + "sha256": "4417242d039eb2a69c46beb4feaf687d11edded8d7c9e141576ed5264a4b8144" + }, + { + "path": "skills/agent-smith/assets/templates/archive/minimal.yaml.archived", + "sha256": "2e3bbe71f9f1d374371b8a6574558f84a8a5e74d5c83c584cd374250ef289398" + }, + { + "path": "skills/agent-smith/assets/templates/archive/comprehensive.yaml.archived", + "sha256": "8b448de443be98ec38a0cfa98177d8d54ac4faef1932c72e4b5831b29f7a991b" + }, + { + "path": "skills/agent-smith/assets/templates/archive/standard.yaml.archived", + "sha256": "6d834f9743d0a245bcb6f595c37e4a4f5d791ee902f0cea4c86d4b218b16dabc" + }, + { + "path": "skills/agent-smith/assets/templates/archive/single.yaml.archived", + "sha256": "5acf6292c3a5007bd92b420fc126f4536cefa89b843f10afd28a0b6a942eccd6" + }, + { + "path": "skills/agent-smith/assets/templates/living/README.md", + "sha256": "aeec54ed580cbc994dc04ac13ca3d253882899c7ec56b7a387570ed8b93fc3cc" + }, + { + "path": "skills/agent-smith/assets/templates/living/separated-parents.yaml", + "sha256": "97b590789322a5092e64e82024e24867ce73144b4951326371e3bcc850d9b230" + }, + { + "path": "skills/agent-smith/assets/templates/living/shared-hybrid.yaml", + "sha256": "84e38e79b67187f2163aa244f3ac651b7cd79220029998509499217ab91dd3c0" + }, + { + "path": "skills/agent-smith/assets/templates/foundation/personal-living.json", + "sha256": "cb7096895278296619d2fa7d8752639703754f83d5a2a29cc16cf6861d15478f" + }, + { + "path": "skills/agent-smith/assets/templates/additional/property-investor.yaml", + "sha256": "82717ca4c524a3be563a6dcb4227499a27006c5b04f9c418c2c4b293d1208e00" + }, + { + "path": "skills/agent-smith/assets/templates/additional/crypto-investor.yaml", + "sha256": "4518136113351ae50afb6a02e664fd835f920534da312f88d4e72b119fcccfb8" + }, + { + "path": "skills/agent-smith/assets/templates/additional/share-investor.yaml", + "sha256": "f9513cac60c174fe3df209de9cf4bab8602ec7b98abbda9d8af37a0a6c1e6391" + }, + { + "path": "skills/agent-smith/assets/templates/additional/README.md", + "sha256": "0987de127b96c7c0b166d7845096002d33e34d6aae189bc0fa2540a438af8d96" + }, + { + "path": "skills/agent-smith/assets/templates/additional/airbnb-host.yaml", + "sha256": "de49ec3ad957a7f69f7a95910155d7b61ca5c55ddeb107c0b5caf2b82796bdfa" + }, + { + "path": "skills/agent-smith/assets/templates/primary/sole-trader.yaml", + "sha256": "fb35f6a699496c7bc3856a42c95a5c058312f0a1366afced678d377a0fb15c3a" + }, + { + "path": "skills/agent-smith/assets/templates/primary/README.md", + "sha256": "e905a4783d9fe91ab28965f9ce00635bae84e66d43cda74a8a7b647b752d421d" + }, + { + "path": "skills/agent-smith/assets/templates/primary/payg-employee.yaml", + "sha256": "de520fdeb350e4c7e3bdb69ad7a9b06e8567848c5ecbc0ec21da66116a067ef2" + } + ], + "dirSha256": "b8a6710b3edbbf89ed7bb788f1da47ef1f3e87f7ccb63aa2ee9fbc7b009cf32b" + }, + "security": { + "scannedAt": null, + "scannerVersion": null, + "flags": [] + } +} \ No newline at end of file diff --git a/skills/agent-smith/.env.sample b/skills/agent-smith/.env.sample new file mode 100644 index 0000000..c709b1c --- /dev/null +++ b/skills/agent-smith/.env.sample @@ -0,0 +1,28 @@ +# PocketSmith API Authentication +# Get your API key from: https://my.pocketsmith.com/user_settings/developer +POCKETSMITH_API_KEY= + +# Agent Smith Configuration +TAX_INTELLIGENCE_LEVEL=smart # reference|smart|full +DEFAULT_INTELLIGENCE_MODE=smart # conservative|smart|aggressive +AUTO_BACKUP=true +AUTO_ARCHIVE=true +ALERT_NOTIFICATIONS=true + +# Tax Configuration (Australia) +TAX_JURISDICTION=AU +FINANCIAL_YEAR_END=06-30 # June 30 (MM-DD format) +GST_REGISTERED=false + +# Reporting Preferences +DEFAULT_REPORT_FORMAT=all # markdown|csv|json|html|excel|all +CURRENCY=AUD + +# Advanced Settings +API_RATE_LIMIT_DELAY=100 # milliseconds between API calls +CACHE_TTL_DAYS=7 # days to keep cached API responses +SUBAGENT_MAX_PARALLEL=5 # maximum parallel subagent processes +LOG_LEVEL=INFO # DEBUG|INFO|WARNING|ERROR + +# Python Execution +PYTHONUNBUFFERED=1 # disable output buffering (real-time progress) diff --git a/skills/agent-smith/.gitignore b/skills/agent-smith/.gitignore new file mode 100644 index 0000000..5948759 --- /dev/null +++ b/skills/agent-smith/.gitignore @@ -0,0 +1,61 @@ +# Sensitive - NEVER commit +.env +*.key + +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +venv/ +env/ +ENV/ +*.egg-info/ +dist/ +build-python/ +.pytest_cache/ +.coverage +.mypy_cache/ +.tox/ +htmlcov/ + +# Agent Smith working data (not for git) +*.log +*_analysis.json +*_data.json +backups/* +!backups/INDEX.md +reports/* +!reports/INDEX.md +data/cache/ +logs/* +!logs/INDEX.md + +# Onboarding state (tracked as template, but user's state will be overwritten) +# Note: data/onboarding_state.json is committed as a template, but the user's +# actual state will modify this file during onboarding. This is intentional. + +# Build reference (temporary - remove before publishing) +build/ + +# OS +.DS_Store +.DS_Store? +._* +.Spotlight-V100 +.Trashes +ehthumbs.db +Thumbs.db + +# IDEs +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# Temporary files +*.tmp +*.temp +*.bak diff --git a/skills/agent-smith/README.md b/skills/agent-smith/README.md new file mode 100644 index 0000000..62fcb2a --- /dev/null +++ b/skills/agent-smith/README.md @@ -0,0 +1,165 @@ +# Agent Smith - Claude Code Skill Source + +This directory contains the source files for the Agent Smith Claude Code skill. + +## Directory Structure + +``` +skill/ +├── SKILL.md # Main skill definition (required) +├── .env.sample # Configuration template +├── pyproject.toml # Python dependencies +├── uv.lock # Dependency lock file +├── .gitignore # Git ignore patterns +│ +├── scripts/ # Python code (copied from ../scripts/) +│ ├── core/ # API client, rule engine, unified rules +│ ├── operations/ # Categorization, batch processing +│ ├── analysis/ # Spending analysis, trends +│ ├── reporting/ # Report generation +│ ├── tax/ # Tax intelligence (3-tier) +│ ├── scenarios/ # Scenario analysis +│ ├── orchestration/ # Subagent conductor +│ ├── workflows/ # Interactive workflows +│ ├── features/ # Advanced features +│ ├── health/ # Health check system +│ └── utils/ # Utilities +│ +├── references/ # Documentation (loaded on-demand) +│ ├── pocketsmith-api.md # PocketSmith API reference +│ ├── design.md # Complete system architecture +│ ├── unified-rules-guide.md # Rule system documentation +│ ├── onboarding-guide.md # First-time setup guide +│ ├── health-check-guide.md # Health system details +│ └── LESSONS_LEARNED.md # Migration insights +│ +├── assets/ # Templates and samples +│ ├── templates/ # Pre-built rule templates +│ ├── .env.sample # Configuration template +│ └── config.json.sample # User preferences template +│ +└── data/ # Working directories (empty, created at runtime) + ├── templates/ + ├── merchants/ + ├── tax/ + └── [other runtime directories] +``` + +## Building the Skill Package + +To rebuild the `agent-smith.skill` package after making changes: + +```bash +# From the repository root +./build-skill.sh +``` + +Or manually: + +```bash +cd /path/to/agent-smith +zip -r agent-smith.skill skill/ \ + -x "*.pyc" \ + -x "*__pycache__*" \ + -x "*.git*" \ + -x "skill/data/*" \ + -x "skill/logs/*" \ + -x "skill/backups/*" \ + -x "skill/reports/*" +``` + +The packaged `.skill` file will be created in the repository root. + +## Development Workflow + +1. **Make changes** to files in this directory +2. **Test changes** by copying to `~/.claude/skills/agent-smith/` and testing in Claude Code +3. **Rebuild the package** using the build script +4. **Commit changes** to the repository + +## What Gets Packaged + +**Included:** +- ✅ SKILL.md (required) +- ✅ All Python scripts +- ✅ All reference documentation +- ✅ Asset templates and samples +- ✅ Configuration templates +- ✅ Dependency files (pyproject.toml, uv.lock) +- ✅ Empty data directories (structure only) + +**Excluded:** +- ❌ Python cache files (*.pyc, __pycache__) +- ❌ Git files +- ❌ Runtime data (data/, logs/, backups/, reports/ contents) +- ❌ User-specific configuration (.env) + +## File Organization + +Following Claude Code skill best practices: + +- **Progressive Disclosure**: SKILL.md is concise (~500 lines), detailed docs in references/ +- **Bundled Scripts**: All executable Python code in scripts/ +- **Reference Documentation**: Detailed guides loaded on-demand from references/ +- **Asset Templates**: Pre-built templates and configuration samples in assets/ + +## Updating the Skill + +### Adding New Scripts + +1. Add/update scripts in `../scripts/` +2. Copy to `skill/scripts/`: + ```bash + cp -r ../scripts/* skill/scripts/ + ``` +3. Rebuild the package + +### Adding New Documentation + +1. Add documentation to `skill/references/` +2. Reference it from SKILL.md if needed +3. Rebuild the package + +### Updating SKILL.md + +1. Edit `skill/SKILL.md` +2. Ensure frontmatter is valid YAML +3. Keep instructions concise (<500 lines) +4. Rebuild the package + +## Testing the Skill + +### Local Testing + +```bash +# Install the skill locally +/plugin install /path/to/agent-smith.skill + +# Or extract and copy manually +cd ~/.claude/skills/ +unzip /path/to/agent-smith.skill +cd agent-smith/ +cp .env.sample .env +# Edit .env with your API key +uv sync +``` + +### Run Tests + +```bash +cd ~/.claude/skills/agent-smith/ +uv run python -u scripts/operations/batch_categorize.py --mode=dry_run +``` + +## Version History + +- **1.3.8** - Complete implementation (all 8 phases) +- **1.0.0** - Initial skill package + +## Notes + +- This is the **source directory** for the skill - the actual skill package is `../agent-smith.skill` +- Always rebuild the package after making changes +- Test changes locally before distributing +- Keep SKILL.md focused and concise +- Move detailed documentation to references/ diff --git a/skills/agent-smith/SKILL.md b/skills/agent-smith/SKILL.md new file mode 100644 index 0000000..40630a2 --- /dev/null +++ b/skills/agent-smith/SKILL.md @@ -0,0 +1,517 @@ +--- +name: agent-smith +description: Intelligent financial management skill for Claude Code that provides comprehensive PocketSmith API integration with AI-powered analysis, transaction categorization, rule management, tax intelligence, and scenario planning. Use when working with PocketSmith data for (1) Transaction categorization and rule management, (2) Financial analysis and reporting, (3) Australian tax compliance (ATO) and deduction tracking, (4) Scenario analysis and forecasting, (5) PocketSmith setup health checks, (6) Budget optimization and spending insights. +--- + +# Agent Smith + +An intelligent financial management skill for Claude Code that transforms PocketSmith from a passive tracking tool into an active financial intelligence system. + +## Core Capabilities + +### 1. Hybrid Rule Engine +- **Platform Rules**: Simple keyword patterns synced to PocketSmith API +- **Local Rules**: Advanced regex, multi-condition logic, confidence scoring +- **Intelligence Modes**: Conservative (manual approval), Smart (auto-apply ≥90%), Aggressive (auto-apply ≥80%) +- **Performance Tracking**: Rule accuracy, matches, user overrides + +### 2. 3-Tier Tax Intelligence (Australian ATO) +- **Level 1 (Reference)**: ATO category mappings, basic tax reports, GST tracking +- **Level 2 (Smart)**: Deduction detection, CGT tracking, confidence scoring, expense splitting +- **Level 3 (Full)**: BAS preparation, compliance checks, scenario planning, audit-ready documentation + +### 3. Transaction Categorization +- **Batch Processing**: Categorize uncategorized transactions with AI assistance +- **Merchant Intelligence**: Automatic payee normalization and variation detection +- **AI Fallback**: LLM-powered categorization when rules don't match +- **Dry-Run Mode**: Preview categorization before applying + +### 4. Financial Analysis & Reporting +- **Spending Analysis**: By category, merchant, time period +- **Trend Detection**: Increasing/decreasing categories, anomaly detection +- **Multi-Format Reports**: Markdown, CSV/JSON, HTML dashboards, Excel +- **Comparative Analysis**: YoY, QoQ, MoM comparisons + +### 5. Scenario Analysis +- **Historical**: What-if replays ("What if I cut dining by 30% last year?") +- **Projections**: Spending forecasts, affordability analysis, goal modeling +- **Optimization**: Subscription analysis, expense rationalization, tax optimization +- **Tax Planning**: Purchase timing, income deferral, CGT scenarios + +### 6. Health Check System +- **6 Health Dimensions**: Data Quality, Category Structure, Rule Engine, Tax Readiness, Automation, Budget Alignment +- **Automated Monitoring**: Weekly checks, EOFY prep, post-operation validation +- **Prioritized Recommendations**: Top 3 highest-impact improvements + +### 7. Advanced Features +- **Smart Alerts**: Budget overruns, tax thresholds, pattern detection +- **Document Tracking**: Receipt requirements ($300 ATO threshold) +- **Multi-User**: Shared expense tracking and settlement +- **Audit Trail**: Complete activity log with undo capability + +## Quick Start + +### First-Time Setup + +1. **Prerequisites**: + - PocketSmith account with API access + - Developer API key from PocketSmith (Settings > Security) + - Python 3.9+ with uv package manager + +2. **Configuration**: + - Copy `.env.sample` to `.env` + - Add `POCKETSMITH_API_KEY=` + - Set `TAX_INTELLIGENCE_LEVEL=smart` (reference|smart|full) + - Set `DEFAULT_INTELLIGENCE_MODE=smart` (conservative|smart|aggressive) + +3. **Installation**: + ```bash + # From the skill directory + uv sync + ``` + +4. **Guided Onboarding**: + ```bash + # Launch integrated onboarding (8 stages) + /agent-smith:install + ``` + +The onboarding process will: +- Discover your PocketSmith account structure +- Recommend and apply a rule template +- Help customize rules for your needs +- Configure intelligence modes +- Incrementally categorize transactions +- Show measurable improvement with health scores +- Provide ongoing usage guidance +- Generate intelligent suggestions + +**Time required**: 30-60 minutes for first-time setup + +### Daily Usage + +**Two Usage Modes:** + +1. **Guided Journey Mode** - When you start Claude Code, Agent Smith displays a status dashboard with: + - Your health score + - Uncategorized transaction count + - Conflicts awaiting review + - Suggested next steps with both natural language and command options + +2. **Power User Mode** - Use slash commands directly for specific operations. + +**Slash Commands** (7 specialized commands): +- `/smith:install` - Installation and onboarding wizard +- `/smith:categorize [--mode] [--period]` - Transaction categorization +- `/smith:review-conflicts` - Review transactions flagged for review +- `/smith:health [--full|--quick]` - Health check and recommendations +- `/smith:insights ` - Financial analysis and reports +- `/smith:tax ` - Tax intelligence (ATO) +- `/smith:schedule [--setup|--status|--remove]` - Automated categorization scheduling + +## Python Scripts + +All Python scripts are in `scripts/` directory. **Always run with `uv run python -u`** for proper dependency resolution and unbuffered output. + +### Core Operations + +```bash +# Categorize transactions +uv run python -u scripts/operations/batch_categorize.py --mode=smart --period=2025-11 + +# Run health check +uv run python -u scripts/health/check.py --full + +# Generate spending report +uv run python -u scripts/reporting/generate.py --period=2025 --format=all + +# Tax deduction analysis +uv run python -u scripts/tax/deduction_detector.py --period=2024-25 +``` + +### Script Organization + +- **`scripts/core/`** - API client, rule engine, unified rules +- **`scripts/operations/`** - Categorization, batch processing, transaction updates +- **`scripts/analysis/`** - Spending analysis, trend detection +- **`scripts/reporting/`** - Multi-format report generation +- **`scripts/tax/`** - ATO mappings, deductions, CGT, BAS preparation +- **`scripts/scenarios/`** - Historical, projections, optimization, tax scenarios +- **`scripts/status/`** - Status dashboard for SessionStart hook +- **`scripts/scheduled/`** - Automated scheduled tasks (cron/launchd) +- **`scripts/health/`** - Health check engine, recommendations, monitoring +- **`scripts/workflows/`** - Interactive categorization workflows +- **`scripts/utils/`** - Backup, validation, logging, merchant normalization + +## Unified Rule System + +Agent Smith uses a YAML-based unified rule system for transaction categorization and labeling. + +### Quick Start with Rules + +```bash +# 1. Choose a template for your household type +uv run python scripts/setup/template_selector.py + +# 2. Customize rules in data/rules.yaml + +# 3. Test with dry run +uv run python scripts/operations/batch_categorize.py --mode=dry_run --period=2025-11 + +# 4. Apply to transactions +uv run python scripts/operations/batch_categorize.py --mode=apply --period=2025-11 +``` + +### Example Rule + +```yaml +rules: + # Category rule - categorize transactions + - type: category + name: WOOLWORTHS → Groceries + patterns: [WOOLWORTHS, COLES, ALDI] + category: Food & Dining > Groceries + confidence: 95 + + # Label rule - apply labels based on context + - type: label + name: Shared Groceries + when: + categories: [Groceries] + accounts: [Shared Bills] + labels: [Shared Expense, Essential] +``` + +### Key Features +- **Two-phase execution**: Categories first, then labels +- **Pattern matching**: Regex patterns with exclusions +- **Confidence scoring**: 0-100% for auto-apply logic +- **LLM fallback**: AI categorization when rules don't match +- **Intelligence modes**: Conservative/Smart/Aggressive +- **Template system**: Pre-built rules for common household types +- **Operational modes**: DRY_RUN/VALIDATE/APPLY for safe testing + +See [references/unified-rules-guide.md](references/unified-rules-guide.md) for complete documentation. + +## Tax Intelligence + +### ATO Compliance (Australian Tax Office) + +**Three Levels**: + +1. **Reference (Level 1)**: + - ATO category mappings + - Basic tax reports + - GST tracking + - Resource links + +2. **Smart (Level 2)** - Recommended: + - Deduction detection (14 pattern-based rules) + - CGT tracking with FIFO matching + - Confidence scoring + - Substantiation threshold checking ($300, $75 taxi/Uber) + - Time-based commuting detection + - Instant asset write-off tracking + +3. **Full (Level 3)** - Power Users: + - BAS preparation with GST calculations + - Compliance checks + - Scenario planning + - Audit-ready documentation + - Professional advice disclaimers + +**Configure Tax Level**: +```bash +# In .env file +TAX_INTELLIGENCE_LEVEL=smart # reference|smart|full +TAX_JURISDICTION=AU +FINANCIAL_YEAR_END=06-30 +``` + +### Deduction Detection Example + +```python +from scripts.tax.deduction_detector import DeductionDetector + +detector = DeductionDetector() +result = detector.detect_deduction(transaction) +# Returns: {"is_deductible": True, "confidence": "high", +# "reason": "Office supplies", "substantiation_required": True} +``` + +### CGT Tracking Example + +```python +from scripts.tax.cgt_tracker import CGTTracker, AssetType +from decimal import Decimal +from datetime import date + +tracker = CGTTracker() +tracker.track_purchase( + asset_type=AssetType.SHARES, + name="BHP Group", + quantity=Decimal("100"), + purchase_date=date(2023, 1, 1), + purchase_price=Decimal("45.50"), + fees=Decimal("19.95") +) + +event = tracker.track_sale( + asset_type=AssetType.SHARES, + name="BHP Group", + quantity=Decimal("100"), + sale_date=date(2024, 6, 1), + sale_price=Decimal("52.00"), + fees=Decimal("19.95") +) +# Returns CGTEvent with capital_gain, discount_eligible, holding_period_days +``` + +## Scenario Analysis + +### Historical Analysis +```python +from scripts.scenarios.historical import calculate_what_if_spending + +scenario = calculate_what_if_spending( + transactions=transactions, + category_name="Dining", + adjustment_percent=-30.0, # 30% reduction + start_date="2025-01-01", + end_date="2025-12-31" +) +print(f"Savings: ${scenario['savings']:.2f}") +``` + +### Spending Forecast +```python +from scripts.scenarios.projections import forecast_spending + +forecast = forecast_spending( + transactions=transactions, + category_name="Groceries", + months_forward=6, + inflation_rate=3.0 +) +``` + +### Optimization Suggestions +```python +from scripts.scenarios.optimization import suggest_optimizations + +optimizations = suggest_optimizations(transactions=transactions) +print(f"Potential savings: ${optimizations['potential_annual_savings']:.2f}") +``` + +## Subagent Orchestration + +Agent Smith uses intelligent subagent orchestration for complex operations: + +**When to delegate to subagents**: +- Transaction count > 100 +- Estimated tokens > 5000 +- Bulk processing or deep analysis +- Multi-period operations +- Parallelization opportunities + +**Subagent types**: +- `categorization-agent` - Transaction categorization +- `analysis-agent` - Financial analysis +- `reporting-agent` - Report generation +- `tax-agent` - Tax intelligence operations +- `optimization-agent` - Category/rule optimization +- `scenario-agent` - Scenario modeling + +**Context preservation**: Main skill maintains user preferences, session state, and high-level decisions while subagents handle heavy processing. + +## Health Check System + +```bash +# Run comprehensive health check +uv run python scripts/health/check.py --full +``` + +**6 Health Dimensions** (scored 0-100): +1. **Data Quality (25%)** - Uncategorized rate, duplicates, gaps +2. **Category Structure (20%)** - Depth, unused categories, distribution +3. **Rule Engine (15%)** - Coverage, efficiency, conflicts +4. **Tax Readiness (15%)** - Tax categorization, compliance +5. **Automation (10%)** - Savings automation, bill scheduling +6. **Budget Alignment (15%)** - Variance, overspending + +**Output includes**: +- Overall score with status (Poor/Fair/Good/Excellent) +- Individual dimension scores +- Top 3 prioritized recommendations +- Projected score after improvements + +**Automated monitoring**: +- Weekly quick health checks +- Monthly full health analysis +- Pre-EOFY comprehensive check +- Post-major-operation validation + +## Configuration Files + +### `.env` (Required) +```bash +# PocketSmith API +POCKETSMITH_API_KEY= + +# Agent Smith Configuration +TAX_INTELLIGENCE_LEVEL=smart # reference|smart|full +DEFAULT_INTELLIGENCE_MODE=smart # conservative|smart|aggressive +AUTO_BACKUP=true +AUTO_ARCHIVE=true +ALERT_NOTIFICATIONS=true + +# Tax Configuration (Australia) +TAX_JURISDICTION=AU +FINANCIAL_YEAR_END=06-30 # June 30 +GST_REGISTERED=false + +# Reporting Preferences +DEFAULT_REPORT_FORMAT=all # markdown|csv|json|html|excel|all +CURRENCY=AUD + +# Advanced +API_RATE_LIMIT_DELAY=100 # ms between calls +CACHE_TTL_DAYS=7 +SUBAGENT_MAX_PARALLEL=5 +``` + +### `data/config.json` (User Preferences) +```json +{ + "user_id": 217031, + "tax_level": "smart", + "intelligence_mode": "smart", + "alerts_enabled": true, + "backup_before_mutations": true, + "auto_archive": true, + "default_report_formats": ["markdown", "csv", "html"] +} +``` + +### `data/rules.yaml` (Unified Rules) +See references/unified-rules-guide.md for complete schema and examples. + +## Directory Structure + +``` +agent-smith/ +├── SKILL.md # This file +├── .env # API configuration (not committed) +├── .env.sample # Configuration template +├── data/ # Working data and state +│ ├── config.json # User preferences +│ ├── rules.yaml # Unified categorization rules +│ ├── templates/ # Pre-built rule templates +│ └── [other runtime data] +├── scripts/ # Python code +│ ├── core/ # API client, rule engine, utilities +│ ├── operations/ # Categorization, batch processing +│ ├── analysis/ # Spending analysis, trends +│ ├── reporting/ # Multi-format reports +│ ├── tax/ # Tax intelligence (3-tier) +│ ├── scenarios/ # Scenario analysis +│ ├── orchestration/ # Subagent conductor +│ ├── workflows/ # Interactive workflows +│ ├── features/ # Advanced features +│ ├── health/ # Health check system +│ └── utils/ # Utilities +├── references/ # Documentation +│ ├── pocketsmith-api.md # PocketSmith API reference +│ ├── unified-rules-guide.md # Complete rules documentation +│ ├── onboarding-guide.md # First-time setup guide +│ └── health-check-guide.md # Health check documentation +├── backups/ # Timestamped backups (30-day retention) +├── logs/ # Execution logs (14-day retention) +└── reports/ # Generated reports (90-day retention) +``` + +## Critical Operating Rules + +**NEVER create custom one-off scripts for core Agent Smith operations.** + +Agent Smith has a complete architecture with: +- Slash commands (`/smith:categorize`, `/smith:analyze`, etc.) +- Python workflows in `scripts/workflows/` +- Core operations in `scripts/operations/` +- Proper API client with correct endpoints in `scripts/core/api_client.py` + +**If you find yourself writing a new Python script to:** +- Categorize transactions +- Analyze spending +- Generate reports +- Update PocketSmith data +- Run health checks + +**STOP. You are reinventing the wheel.** + +**Instead:** +1. Check if a slash command exists (`/smith:*`) +2. Check if a workflow exists in `scripts/workflows/` +3. Check if a core operation exists in `scripts/operations/` +4. Use the existing code that has been tested and uses correct API endpoints + +**Why this matters:** +- Custom scripts may use wrong API endpoints (e.g., `/users/{id}/transactions/{id}` instead of `/transactions/{id}`) +- Custom scripts bypass rule engine, validation, backup, and audit systems +- Custom scripts duplicate functionality that already exists +- Custom scripts won't benefit from future improvements + +**Exception:** Only create new scripts when building NEW features not yet in the design, and always place them in the correct `scripts/` subdirectory. + +## Best Practices + +### Transaction Categorization +1. **Always use `/smith:categorize`** - Never create custom categorization scripts +2. Start with a rule template matching your household type +3. Use dry-run mode to preview categorization +4. Review and adjust rules based on results +5. Monitor rule performance metrics +6. Let AI handle edge cases (LLM fallback) + +### Tax Compliance +1. Configure appropriate tax level for your needs +2. Track all deductible expenses as they occur +3. Maintain receipt documentation (>$300 ATO requirement) +4. Review tax reports before EOFY (June 30) +5. Consult registered tax agent for complex situations + +### Financial Health +1. Run health checks monthly +2. Address high-priority recommendations first +3. Maintain 95%+ categorization rate +4. Review and clean up unused categories +5. Set up automated alerts for budget overruns + +### Backup and Safety +1. Always backup before bulk operations (automatic) +2. Use dry-run mode for untested operations +3. Review audit trail for unexpected changes +4. Maintain 30 days of recent backups +5. Export tax reports for 7-year ATO retention + +## References + +For detailed documentation, see the `references/` directory: + +- **[PocketSmith API](references/pocketsmith-api.md)** - Complete API reference +- **[Unified Rules Guide](references/unified-rules-guide.md)** - Rule system documentation +- **[Onboarding Guide](references/onboarding-guide.md)** - First-time setup walkthrough +- **[Health Check Guide](references/health-check-guide.md)** - Health system details +- **[Design Document](references/design.md)** - Complete system architecture + +## Support + +**Version**: 1.6.0 + +**Documentation**: See references/ directory for comprehensive guides + +**Issues**: For questions or issues, refer to the design documentation or create an issue in the repository. + +--- + +**Note**: Agent Smith is designed for Australian tax compliance (ATO). Adapting for other jurisdictions requires updating tax intelligence modules and reference documentation. diff --git a/skills/agent-smith/assets/.env.sample b/skills/agent-smith/assets/.env.sample new file mode 100644 index 0000000..c709b1c --- /dev/null +++ b/skills/agent-smith/assets/.env.sample @@ -0,0 +1,28 @@ +# PocketSmith API Authentication +# Get your API key from: https://my.pocketsmith.com/user_settings/developer +POCKETSMITH_API_KEY= + +# Agent Smith Configuration +TAX_INTELLIGENCE_LEVEL=smart # reference|smart|full +DEFAULT_INTELLIGENCE_MODE=smart # conservative|smart|aggressive +AUTO_BACKUP=true +AUTO_ARCHIVE=true +ALERT_NOTIFICATIONS=true + +# Tax Configuration (Australia) +TAX_JURISDICTION=AU +FINANCIAL_YEAR_END=06-30 # June 30 (MM-DD format) +GST_REGISTERED=false + +# Reporting Preferences +DEFAULT_REPORT_FORMAT=all # markdown|csv|json|html|excel|all +CURRENCY=AUD + +# Advanced Settings +API_RATE_LIMIT_DELAY=100 # milliseconds between API calls +CACHE_TTL_DAYS=7 # days to keep cached API responses +SUBAGENT_MAX_PARALLEL=5 # maximum parallel subagent processes +LOG_LEVEL=INFO # DEBUG|INFO|WARNING|ERROR + +# Python Execution +PYTHONUNBUFFERED=1 # disable output buffering (real-time progress) diff --git a/skills/agent-smith/assets/config.json b/skills/agent-smith/assets/config.json new file mode 100644 index 0000000..a460eba --- /dev/null +++ b/skills/agent-smith/assets/config.json @@ -0,0 +1,28 @@ +{ + "user_id": null, + "tax_level": "smart", + "intelligence_mode": "smart", + "alerts_enabled": true, + "alert_preferences": { + "budget": true, + "tax": true, + "patterns": true, + "optimization": true, + "frequency": "weekly" + }, + "backup_before_mutations": true, + "auto_archive": true, + "default_report_formats": [ + "markdown", + "csv" + ], + "household": { + "enabled": false, + "members": [], + "split_method": "proportional" + }, + "benchmarking": { + "enabled": false, + "criteria": {} + } +} diff --git a/skills/agent-smith/assets/config.json.sample b/skills/agent-smith/assets/config.json.sample new file mode 100644 index 0000000..a460eba --- /dev/null +++ b/skills/agent-smith/assets/config.json.sample @@ -0,0 +1,28 @@ +{ + "user_id": null, + "tax_level": "smart", + "intelligence_mode": "smart", + "alerts_enabled": true, + "alert_preferences": { + "budget": true, + "tax": true, + "patterns": true, + "optimization": true, + "frequency": "weekly" + }, + "backup_before_mutations": true, + "auto_archive": true, + "default_report_formats": [ + "markdown", + "csv" + ], + "household": { + "enabled": false, + "members": [], + "split_method": "proportional" + }, + "benchmarking": { + "enabled": false, + "criteria": {} + } +} diff --git a/skills/agent-smith/assets/local_rules.json b/skills/agent-smith/assets/local_rules.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/skills/agent-smith/assets/local_rules.json @@ -0,0 +1 @@ +[] diff --git a/skills/agent-smith/assets/merchants/merchant_mappings.json b/skills/agent-smith/assets/merchants/merchant_mappings.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/skills/agent-smith/assets/merchants/merchant_mappings.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/skills/agent-smith/assets/onboarding_state.json b/skills/agent-smith/assets/onboarding_state.json new file mode 100644 index 0000000..7a84daf --- /dev/null +++ b/skills/agent-smith/assets/onboarding_state.json @@ -0,0 +1,11 @@ +{ + "current_stage": "not_started", + "completed_stages": [], + "discovery_report": null, + "template_selected": null, + "intelligence_mode": null, + "tax_level": null, + "baseline_health_score": null, + "current_health_score": null, + "categorization_batches": [] +} diff --git a/skills/agent-smith/assets/platform_rules.json b/skills/agent-smith/assets/platform_rules.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/skills/agent-smith/assets/platform_rules.json @@ -0,0 +1 @@ +[] diff --git a/skills/agent-smith/assets/tax/ato_category_mappings.json b/skills/agent-smith/assets/tax/ato_category_mappings.json new file mode 100644 index 0000000..582b9b3 --- /dev/null +++ b/skills/agent-smith/assets/tax/ato_category_mappings.json @@ -0,0 +1,55 @@ +{ + "mappings": [ + { + "pocketsmith_category": "Groceries", + "ato_code": null, + "ato_category": "Personal expense", + "deductible": false, + "notes": "Not deductible for individuals. Business owners: keep receipts for food provided to staff.", + "substantiation_required": false + }, + { + "pocketsmith_category": "Office Supplies", + "ato_code": "D5", + "ato_category": "Work-related other expenses", + "deductible": true, + "notes": "Keep receipts if under $300 total. Retain for 5 years.", + "substantiation_required": true, + "threshold": 300.0 + }, + { + "pocketsmith_category": "Transport", + "ato_code": "D1", + "ato_category": "Work-related car expenses", + "deductible": true, + "notes": "Must substantiate if using logbook or actual costs method. $0.78/km for cents per km method (2024-25).", + "substantiation_required": true + }, + { + "pocketsmith_category": "Home & Utilities", + "ato_code": "D5", + "ato_category": "Work-related other expenses", + "deductible": true, + "notes": "Only home office portion deductible. Use fixed rate method (67c/hour) or actual costs method.", + "substantiation_required": true + }, + { + "pocketsmith_category": "Professional Development", + "ato_code": "D4", + "ato_category": "Work-related self-education expenses", + "deductible": true, + "notes": "Must have sufficient connection to current income-earning activities.", + "substantiation_required": true + } + ], + "ato_categories": [ + {"code": "D1", "name": "Work-related car expenses", "schedule": "D"}, + {"code": "D2", "name": "Work-related travel expenses", "schedule": "D"}, + {"code": "D3", "name": "Work-related clothing, laundry and dry-cleaning expenses", "schedule": "D"}, + {"code": "D4", "name": "Work-related self-education expenses", "schedule": "D"}, + {"code": "D5", "name": "Work-related other expenses", "schedule": "D"}, + {"code": "D6", "name": "Work-related interest, dividend and other investment income deductions", "schedule": "D"}, + {"code": "CGT", "name": "Capital gains tax", "schedule": "CGT"}, + {"code": "BAS", "name": "Business activity statement", "schedule": "BAS"} + ] +} diff --git a/skills/agent-smith/assets/tax/deduction_patterns.json b/skills/agent-smith/assets/tax/deduction_patterns.json new file mode 100644 index 0000000..d0ead88 --- /dev/null +++ b/skills/agent-smith/assets/tax/deduction_patterns.json @@ -0,0 +1,200 @@ +{ + "version": "1.0.0", + "last_updated": "2025-11-20", + "description": "Pattern-based deduction detection rules for Australian tax compliance (Level 2)", + + "patterns": [ + { + "id": "office_supplies", + "category_patterns": ["Office Supplies", "Stationery", "Business Supplies"], + "payee_patterns": ["Officeworks", "Office Depot", "Staples"], + "deductible": true, + "confidence": "high", + "ato_category": "Work-related other expenses", + "ato_code": "D5", + "reason": "Office supplies and stationery for work purposes", + "substantiation_notes": "Keep receipts for items over $300" + }, + { + "id": "computer_equipment", + "category_patterns": ["Computer Equipment", "Electronics", "Technology"], + "payee_patterns": ["Apple Store", "JB Hi-Fi", "Harvey Norman"], + "keywords": ["laptop", "computer", "monitor", "keyboard", "mouse"], + "deductible": true, + "confidence": "medium", + "ato_category": "Work-related other expenses", + "ato_code": "D5", + "reason": "Computer equipment for work purposes", + "substantiation_notes": "Items over $300 require receipts. May qualify for instant asset write-off if under threshold.", + "instant_asset_write_off_eligible": true + }, + { + "id": "professional_development", + "category_patterns": ["Professional Development", "Education", "Training", "Courses"], + "payee_patterns": ["LinkedIn", "Coursera", "Udemy", "Professional Association"], + "deductible": true, + "confidence": "high", + "ato_category": "Self-education expenses", + "ato_code": "D4", + "reason": "Professional development and education expenses", + "substantiation_notes": "Keep certificates and receipts" + }, + { + "id": "home_office_furniture", + "category_patterns": ["Furniture", "Home Office"], + "keywords": ["desk", "chair", "office", "filing cabinet", "bookshelf"], + "deductible": true, + "confidence": "medium", + "ato_category": "Home office expenses", + "ato_code": "D2", + "reason": "Home office furniture and equipment", + "substantiation_notes": "Must be used primarily for work. Consider depreciation for items over $300." + }, + { + "id": "mobile_phone", + "category_patterns": ["Mobile Phone", "Phone", "Telecommunications"], + "payee_patterns": ["Telstra", "Optus", "Vodafone"], + "deductible": true, + "confidence": "low", + "ato_category": "Work-related other expenses", + "ato_code": "D5", + "reason": "Mobile phone expenses - consider work/personal usage split", + "substantiation_notes": "Calculate work-related percentage. May need to apportion costs.", + "requires_apportionment": true + }, + { + "id": "internet", + "category_patterns": ["Internet", "Utilities"], + "payee_patterns": ["Telstra", "Optus", "TPG", "Aussie Broadband"], + "keywords": ["internet", "broadband", "nbn"], + "deductible": true, + "confidence": "low", + "ato_category": "Home office expenses", + "ato_code": "D2", + "reason": "Internet expenses - consider work/personal usage split", + "substantiation_notes": "Calculate work-related percentage based on usage.", + "requires_apportionment": true + }, + { + "id": "business_travel_taxi", + "category_patterns": ["Transport", "Taxi", "Rideshare"], + "payee_patterns": ["Uber", "DiDi", "Taxi", "Ola", "13CABS"], + "deductible": true, + "confidence": "medium", + "ato_category": "Work-related travel expenses", + "ato_code": "D1", + "reason": "Business travel - taxi/rideshare", + "substantiation_notes": "Trips over $75 require written evidence. Commuting to/from regular workplace NOT deductible.", + "special_threshold": 75, + "commuting_detection": true + }, + { + "id": "vehicle_expenses", + "category_patterns": ["Fuel", "Car Maintenance", "Vehicle"], + "payee_patterns": ["BP", "Shell", "Caltex", "7-Eleven", "United Petroleum"], + "deductible": true, + "confidence": "low", + "ato_category": "Work-related car expenses", + "ato_code": "D2", + "reason": "Vehicle expenses - consider cents per km or logbook method", + "substantiation_notes": "Keep logbook or calculate km. Commuting NOT deductible.", + "requires_apportionment": true + }, + { + "id": "groceries_personal", + "category_patterns": ["Groceries", "Food", "Supermarket"], + "payee_patterns": ["Woolworths", "Coles", "IGA", "Aldi"], + "deductible": false, + "confidence": "high", + "ato_category": "Personal expense", + "reason": "Personal groceries and food are not tax deductible for individuals", + "substantiation_notes": "Not deductible for individuals. May be deductible for businesses in specific circumstances." + }, + { + "id": "clothing_personal", + "category_patterns": ["Clothing", "Fashion"], + "deductible": false, + "confidence": "high", + "ato_category": "Personal expense", + "reason": "Personal clothing is not tax deductible unless it is protective, occupation-specific, or uniform", + "substantiation_notes": "Only protective clothing, occupation-specific clothing, or registered uniforms are deductible." + }, + { + "id": "protective_clothing", + "category_patterns": ["Work Clothing", "Safety Equipment"], + "keywords": ["uniform", "safety", "protective", "hi-vis", "steel cap"], + "deductible": true, + "confidence": "high", + "ato_category": "Work-related clothing expenses", + "ato_code": "D6", + "reason": "Protective clothing and occupation-specific uniforms", + "substantiation_notes": "Must be occupation-specific or protective. Conventional clothing not deductible." + }, + { + "id": "subscriptions_professional", + "category_patterns": ["Subscriptions", "Professional Services"], + "keywords": ["professional", "membership", "association", "subscription"], + "deductible": true, + "confidence": "medium", + "ato_category": "Work-related other expenses", + "ato_code": "D5", + "reason": "Professional memberships and subscriptions", + "substantiation_notes": "Must be directly related to earning income." + }, + { + "id": "entertainment_personal", + "category_patterns": ["Entertainment", "Dining", "Recreation"], + "deductible": false, + "confidence": "high", + "ato_category": "Personal expense", + "reason": "Personal entertainment and dining expenses are not deductible", + "substantiation_notes": "Not deductible unless it is a valid business meal meeting specific criteria." + }, + { + "id": "books_technical", + "category_patterns": ["Books", "Media"], + "keywords": ["technical", "professional", "textbook", "reference"], + "deductible": true, + "confidence": "medium", + "ato_category": "Self-education expenses", + "ato_code": "D4", + "reason": "Technical and professional reference books", + "substantiation_notes": "Must be directly related to current work or income-earning activities." + } + ], + + "substantiation_thresholds": { + "default": 300, + "taxi_rideshare": 75, + "laundry": 150, + "description": "ATO substantiation thresholds - amounts requiring written evidence" + }, + + "commuting_hours": { + "weekday_morning": { + "start": "06:00", + "end": "09:30", + "description": "Typical morning commute period" + }, + "weekday_evening": { + "start": "16:30", + "end": "19:00", + "description": "Typical evening commute period" + }, + "description": "Time periods indicating likely commuting (NOT deductible)" + }, + + "instant_asset_write_off": { + "threshold": 20000, + "description": "Instant asset write-off threshold (check current ATO guidelines)", + "notes": "Assets under this amount may be immediately deductible. Verify current year threshold." + }, + + "confidence_scoring": { + "high": "Clear patterns matching deductible/non-deductible categories with minimal ambiguity", + "medium": "Likely deductible but requires additional context or apportionment", + "low": "Ambiguous - needs manual review or additional information" + }, + + "disclaimer": "This is automated pattern matching only. Rules are based on general ATO guidelines and may not apply to individual circumstances. Always consult a registered tax agent for specific advice." +} diff --git a/skills/agent-smith/assets/templates/README.md b/skills/agent-smith/assets/templates/README.md new file mode 100644 index 0000000..5d6d4a6 --- /dev/null +++ b/skills/agent-smith/assets/templates/README.md @@ -0,0 +1,23 @@ +# Agent Smith Templates + +This directory contains composable template configurations for PocketSmith onboarding. + +## Structure + +- **primary/** - Primary income structure templates (choose ONE) +- **living/** - Living arrangement templates (choose ONE) +- **additional/** - Additional income source templates (choose MULTIPLE) + +## Usage + +Templates are YAML files that define: +- Categories to create +- Categorization rules +- Tax tracking configuration +- Smart alerts + +During onboarding, templates are selected and merged using `scripts/setup/template_merger.py`. + +## Template Schema + +See individual layer README files for YAML schema details. diff --git a/skills/agent-smith/assets/templates/additional/README.md b/skills/agent-smith/assets/templates/additional/README.md new file mode 100644 index 0000000..60a75ff --- /dev/null +++ b/skills/agent-smith/assets/templates/additional/README.md @@ -0,0 +1,15 @@ +# Additional Income Templates + +Select MULTIPLE templates for additional income sources beyond your primary income. + +## Available Templates + +- `side-hustle.yaml` - Freelancing, consulting, gig work +- `property-investor.yaml` - Rental income, negative gearing, CGT +- `share-investor.yaml` - Dividends, franking credits, share CGT +- `crypto-investor.yaml` - Cryptocurrency trading and staking +- `trust-structures.yaml` - Family trust, company distributions + +## YAML Schema + +Same structure as primary templates, with `layer: additional` and higher priority values (3+). diff --git a/skills/agent-smith/assets/templates/additional/airbnb-host.yaml b/skills/agent-smith/assets/templates/additional/airbnb-host.yaml new file mode 100644 index 0000000..c767184 --- /dev/null +++ b/skills/agent-smith/assets/templates/additional/airbnb-host.yaml @@ -0,0 +1,175 @@ +name: Airbnb Host +layer: additional +description: | + Short-term rental income tracking for Airbnb, Stayz, and similar platforms. + Includes expense apportionment for owner-occupied properties and CGT considerations. + +categories: + - name: "Airbnb:Income" + parent: null + description: "Short-term rental income from Airbnb, Stayz, etc." + + - name: "Airbnb:Cleaning & Laundry" + parent: null + description: "Cleaning services and laundry for guests" + + - name: "Airbnb:Guest Amenities" + parent: null + description: "Toiletries, coffee, tea, snacks for guests" + + - name: "Airbnb:Linen & Towels" + parent: null + description: "Linen, towels, bedding for guest accommodation" + + - name: "Airbnb:Platform Fees" + parent: null + description: "Airbnb/Stayz service fees and commissions" + + - name: "Airbnb:Repairs & Maintenance" + parent: null + description: "Repairs and maintenance related to rental use" + + - name: "Airbnb:Utilities" + parent: null + description: "Utilities attributable to rental use (apportioned)" + + - name: "Airbnb:Insurance" + parent: null + description: "Host insurance and additional coverage" + + - name: "Airbnb:Marketing & Listings" + parent: null + description: "Photography, listing fees, advertising" + +rules: + - id: airbnb-income + pattern: "Airbnb.*payout|Airbnb.*income|Stayz.*payout|booking.com.*payout|short.*term.*rental.*income" + category: "Airbnb:Income" + confidence: high + labels: ["Assessable Income", "Rental Income"] + description: "Detect short-term rental income" + + - id: airbnb-cleaning + pattern: "cleaning.*Airbnb|laundry.*guest|linen.*service|professional.*clean.*rental" + category: "Airbnb:Cleaning & Laundry" + confidence: high + labels: ["Tax Deductible", "Apportioned"] + description: "Detect cleaning and laundry expenses" + + - id: guest-amenities + pattern: "toiletries.*guest|coffee.*Airbnb|tea.*guest|snacks.*guest|welcome.*pack" + category: "Airbnb:Guest Amenities" + confidence: medium + labels: ["Tax Deductible", "Apportioned"] + description: "Detect guest amenity purchases" + + - id: linen-towels + pattern: "linen.*rental|towels.*guest|bedding.*Airbnb|sheets.*accommodation" + category: "Airbnb:Linen & Towels" + confidence: high + labels: ["Tax Deductible", "Apportioned"] + description: "Detect linen and towel purchases" + + - id: platform-fees + pattern: "Airbnb.*service.*fee|Airbnb.*commission|Stayz.*fee|booking.*commission" + category: "Airbnb:Platform Fees" + confidence: high + labels: ["Tax Deductible"] + description: "Detect platform service fees" + + - id: rental-repairs + pattern: "repair.*rental|maintenance.*Airbnb|fix.*guest.*room|handyman.*rental" + category: "Airbnb:Repairs & Maintenance" + confidence: medium + labels: ["Tax Deductible", "Apportioned", "Repairs vs Improvements"] + description: "Detect repairs related to rental use" + + - id: rental-utilities + pattern: "electricity.*rental|gas.*rental|water.*rental|internet.*rental" + category: "Airbnb:Utilities" + confidence: low + labels: ["Tax Deductible", "Apportioned"] + description: "Detect utilities for apportionment (requires manual review)" + + - id: host-insurance + pattern: "Airbnb.*insurance|host.*insurance|short.*term.*rental.*insurance" + category: "Airbnb:Insurance" + confidence: high + labels: ["Tax Deductible", "Apportioned"] + description: "Detect host insurance premiums" + + - id: listing-marketing + pattern: "photography.*listing|Airbnb.*listing|property.*photos.*rental" + category: "Airbnb:Marketing & Listings" + confidence: medium + labels: ["Tax Deductible"] + description: "Detect marketing and listing expenses" + +tax_tracking: + income_tracking: true + expense_apportionment_required: true + apportionment_basis: "days_rented" + cgt_main_residence_exemption_impact: true + record_keeping_days_rented: true + record_keeping_days_personal: true + +alerts: + - type: apportionment_reminder + schedule: quarterly + message: "Calculate expense apportionment: days rented vs personal use" + + - type: days_rented_tracker + schedule: monthly + message: "Record days rented this month for expense apportionment" + + - type: eofy_airbnb_reminder + schedule: annual + before_date: "06-15" + message: "EOFY - compile Airbnb income, calculate apportioned expenses, document days rented vs personal use" + + - type: cgt_exemption_warning + trigger: annual + message: "Using main residence for income may affect CGT main residence exemption. Keep detailed records." + + - type: gst_threshold_warning + trigger: annual_income_exceeds + threshold: 75000 + message: "Airbnb income + other business income exceeds $75k - GST registration may be required" + +labels: + - name: "Assessable Income" + description: "Income assessable for tax purposes" + color: "green" + auto_apply: true + + - name: "Rental Income" + description: "Short-term rental income" + color: "lightgreen" + auto_apply: false + + - name: "Tax Deductible" + description: "Deductible expense (may require apportionment)" + color: "green" + auto_apply: false + + - name: "Apportioned" + description: "Expense requiring apportionment by rental vs personal use" + color: "orange" + auto_apply: true + + - name: "Repairs vs Improvements" + description: "Requires classification: repairs (deductible) vs improvements (capital)" + color: "orange" + auto_apply: false + +dependencies: + requires: [] + conflicts_with: ["property-investor"] + notes: "Use property-investor for long-term rentals. Use airbnb-host for short-term/part-time hosting." + +metadata: + created: "2025-11-25" + version: "1.0.0" + author: "Agent Smith" + priority: 3 + ato_guidance: "Airbnb income is assessable. Expenses must be apportioned if property is also used privately. Keep records of days rented vs personal use." diff --git a/skills/agent-smith/assets/templates/additional/crypto-investor.yaml b/skills/agent-smith/assets/templates/additional/crypto-investor.yaml new file mode 100644 index 0000000..405d1e3 --- /dev/null +++ b/skills/agent-smith/assets/templates/additional/crypto-investor.yaml @@ -0,0 +1,175 @@ +name: Crypto Investor +layer: additional +description: | + Cryptocurrency investment tracking with ATO-compliant CGT and income reporting. + Covers exchanges, staking, DeFi yields, and NFT transactions. + +categories: + - name: "Crypto:Purchases" + parent: null + description: "Cryptocurrency purchases (establishes cost base)" + + - name: "Crypto:Sales" + parent: null + description: "Cryptocurrency sales (CGT events)" + + - name: "Crypto:Staking Income" + parent: null + description: "Staking rewards and interest (ordinary income)" + + - name: "Crypto:DeFi Yields" + parent: null + description: "DeFi protocol yields and liquidity rewards (ordinary income)" + + - name: "Crypto:Airdrops & Forks" + parent: null + description: "Airdropped tokens and fork distributions (ordinary income at receipt)" + + - name: "Crypto:NFT Purchases" + parent: null + description: "NFT purchases (establishes cost base)" + + - name: "Crypto:NFT Sales" + parent: null + description: "NFT sales (CGT events)" + + - name: "Crypto:Gas Fees" + parent: null + description: "Network gas fees (adds to cost base)" + + - name: "Crypto:Exchange Fees" + parent: null + description: "Trading and platform fees" + +rules: + - id: crypto-purchase + pattern: "CoinSpot|Binance|Coinbase|Kraken|Independent.*Reserve|Swyftx|BTC.*Markets|crypto.*buy|BTC.*purchase|ETH.*purchase" + category: "Crypto:Purchases" + confidence: medium + labels: ["Crypto", "Cost Base"] + description: "Detect cryptocurrency purchases on Australian exchanges" + + - id: crypto-sale + pattern: "crypto.*sell|BTC.*sale|ETH.*sale|sold.*crypto" + category: "Crypto:Sales" + confidence: medium + labels: ["Crypto", "CGT Event"] + description: "Detect cryptocurrency sales (CGT event)" + + - id: staking-rewards + pattern: "staking.*reward|staked.*income|validator.*reward|POS.*reward" + category: "Crypto:Staking Income" + confidence: high + labels: ["Crypto", "Ordinary Income"] + description: "Detect staking rewards (ordinary income)" + + - id: defi-yields + pattern: "DeFi|yield.*farming|liquidity.*pool|lending.*interest|Aave|Compound|Uniswap.*reward" + category: "Crypto:DeFi Yields" + confidence: medium + labels: ["Crypto", "Ordinary Income"] + description: "Detect DeFi protocol yields" + + - id: airdrops + pattern: "airdrop|token.*distribution|fork.*distribution" + category: "Crypto:Airdrops & Forks" + confidence: high + labels: ["Crypto", "Ordinary Income"] + description: "Detect airdrops and fork distributions" + + - id: nft-purchase + pattern: "NFT.*purchase|OpenSea.*buy|Rarible.*buy|digital.*art.*purchase" + category: "Crypto:NFT Purchases" + confidence: medium + labels: ["Crypto", "NFT", "Cost Base"] + description: "Detect NFT purchases" + + - id: nft-sale + pattern: "NFT.*sale|OpenSea.*sale|sold.*NFT" + category: "Crypto:NFT Sales" + confidence: medium + labels: ["Crypto", "NFT", "CGT Event"] + description: "Detect NFT sales" + + - id: gas-fees + pattern: "gas.*fee|network.*fee|ETH.*fee|transaction.*fee.*crypto" + category: "Crypto:Gas Fees" + confidence: high + labels: ["Crypto", "Cost Base Addition"] + description: "Detect blockchain gas fees" + + - id: exchange-fees + pattern: "trading.*fee.*crypto|exchange.*fee|platform.*fee.*crypto" + category: "Crypto:Exchange Fees" + confidence: high + labels: ["Crypto"] + description: "Detect exchange and trading fees" + +tax_tracking: + cgt_tracking: true + cgt_discount_eligible: true + cgt_discount_holding_period: 365 + cost_base_tracking: true + cost_base_includes_fees: true + income_tracking: true + separate_income_vs_capital: true + +alerts: + - type: crypto_cgt_event + trigger: sale_detected + message: "Crypto sale detected - calculate CGT (12-month holding = 50% discount)" + + - type: crypto_income_reminder + schedule: quarterly + message: "Report crypto staking/DeFi income on quarterly basis" + + - type: eofy_crypto_reminder + schedule: annual + before_date: "06-15" + message: "EOFY - compile all crypto CGT events and income. ATO requires detailed records." + + - type: cost_base_reminder + trigger: purchase_detected + message: "Record AUD value at time of purchase for accurate cost base" + +labels: + - name: "Crypto" + description: "Cryptocurrency transaction" + color: "bitcoin-orange" + auto_apply: false + + - name: "CGT Event" + description: "Capital gains tax event (crypto disposal)" + color: "gold" + auto_apply: true + + - name: "Cost Base" + description: "Establishes or adds to CGT cost base" + color: "lightblue" + auto_apply: false + + - name: "Cost Base Addition" + description: "Expense that adds to CGT cost base" + color: "skyblue" + auto_apply: false + + - name: "Ordinary Income" + description: "Taxed as ordinary income (not CGT)" + color: "green" + auto_apply: true + + - name: "NFT" + description: "Non-fungible token transaction" + color: "purple" + auto_apply: false + +dependencies: + requires: [] + conflicts_with: [] + +metadata: + created: "2025-11-25" + version: "1.0.0" + author: "Agent Smith" + priority: 3 + ato_guidance: "ATO treats cryptocurrency as CGT asset. Staking/interest = ordinary income. Keep records of all transactions in AUD." diff --git a/skills/agent-smith/assets/templates/additional/property-investor.yaml b/skills/agent-smith/assets/templates/additional/property-investor.yaml new file mode 100644 index 0000000..44817c1 --- /dev/null +++ b/skills/agent-smith/assets/templates/additional/property-investor.yaml @@ -0,0 +1,129 @@ +name: Property Investor +layer: additional +description: | + Rental property income and expenses tracking. + Includes negative gearing calculation and CGT cost base tracking. + +categories: + - name: "Rental Income" + parent: null + description: "Rent received from investment properties" + + - name: "Property:Interest" + parent: null + description: "Mortgage interest on investment loans" + + - name: "Property:Rates & Strata" + parent: null + description: "Council rates and strata fees" + + - name: "Property:Repairs & Maintenance" + parent: null + description: "Repairs and maintenance expenses" + + - name: "Property:Property Management" + parent: null + description: "Property management fees" + + - name: "Property:Insurance" + parent: null + description: "Landlord insurance premiums" + + - name: "Property:Depreciation" + parent: null + description: "Depreciation (manual entry from schedule)" + +rules: + - id: rental-income + pattern: "rent.*received|rental.*income|tenant.*payment" + category: "Rental Income" + confidence: high + labels: ["Property: {address}"] + description: "Detect rental income payments" + + - id: property-loan-interest + pattern: "investment.*loan|property.*mortgage|loan.*interest" + category: "Property:Interest" + confidence: medium + labels: ["Tax Deductible", "Property: {address}"] + description: "Detect investment property loan interest" + + - id: council-rates + pattern: "council.*rates|strata|body.*corporate" + category: "Property:Rates & Strata" + confidence: high + labels: ["Tax Deductible", "Property: {address}"] + description: "Detect rates and strata fees" + + - id: property-repairs + pattern: "plumber|electrician|handyman|repairs.*property|maintenance.*rental" + category: "Property:Repairs & Maintenance" + confidence: medium + labels: ["Tax Deductible", "Property: {address}", "Repairs vs Improvements"] + description: "Detect repair and maintenance expenses" + + - id: property-management-fee + pattern: "property.*management|real.*estate.*fee|letting.*fee" + category: "Property:Property Management" + confidence: high + labels: ["Tax Deductible", "Property: {address}"] + description: "Detect property management fees" + +tax_tracking: + negative_gearing_calculation: true + cgt_cost_base_tracking: true + cgt_discount_eligible: true + cgt_discount_holding_period: 365 + depreciation_schedule_tracking: true + +alerts: + - type: rental_schedule_reminder + schedule: annual + before_date: "06-15" + message: "EOFY - prepare rental property income/expense schedule for tax return" + + - type: cgt_event_reminder + trigger: property_sale_detected + message: "Property sale detected - calculate CGT on disposal" + + - type: negative_gearing_summary + schedule: quarterly + message: "Quarterly negative gearing summary available" + +labels: + - name: "Tax Deductible" + description: "Property expense claimable on tax return" + color: "green" + auto_apply: false + + - name: "Negative Gearing" + description: "Deductible loss against other income" + color: "darkgreen" + auto_apply: false + + - name: "Capital Improvement" + description: "Adds to CGT cost base (not immediately deductible)" + color: "gold" + auto_apply: false + + - name: "Repairs vs Improvements" + description: "Requires classification for tax treatment" + color: "orange" + auto_apply: false + + - name: "Property: {address}" + description: "Expense for property at {address}" + color: "brown" + auto_apply: false + requires_configuration: true + configuration_prompt: "Enter property address:" + +dependencies: + requires: [] + conflicts_with: [] + +metadata: + created: "2025-11-22" + version: "1.0.0" + author: "Agent Smith" + priority: 3 diff --git a/skills/agent-smith/assets/templates/additional/share-investor.yaml b/skills/agent-smith/assets/templates/additional/share-investor.yaml new file mode 100644 index 0000000..71d359f --- /dev/null +++ b/skills/agent-smith/assets/templates/additional/share-investor.yaml @@ -0,0 +1,103 @@ +name: Share/ETF Investor +layer: additional +description: | + Share and ETF portfolio tracking with dividend income and CGT events. + Includes franking credit extraction and wash sale detection. + +categories: + - name: "Dividends:Franked" + parent: null + description: "Fully franked dividend income" + + - name: "Dividends:Unfranked" + parent: null + description: "Unfranked dividend income" + + - name: "Share Sales" + parent: null + description: "Capital gains/losses from share sales" + + - name: "Brokerage Fees" + parent: null + description: "Trading and brokerage fees" + +rules: + - id: franked-dividends + pattern: "dividend.*franked|franking.*credit|DRP|dividend.*reinvestment" + category: "Dividends:Franked" + confidence: high + labels: ["Franked Dividend"] + description: "Detect franked dividend payments" + + - id: unfranked-dividends + pattern: "dividend.*unfranked|distribution.*trust" + category: "Dividends:Unfranked" + confidence: high + description: "Detect unfranked dividend payments" + + - id: share-sale + pattern: "share.*sale|stock.*sale|sold.*shares|CGT.*event" + category: "Share Sales" + confidence: medium + labels: ["Capital Gain"] + description: "Detect share sale transactions (CGT event)" + + - id: brokerage + pattern: "CommSec|SelfWealth|Stake|brokerage|trading.*fee" + category: "Brokerage Fees" + confidence: high + labels: ["Tax Deductible"] + description: "Detect brokerage and trading fees" + +tax_tracking: + dividend_tracking: true + franking_credit_extraction: true + cgt_tracking: true + cgt_discount_eligible: true + cgt_discount_holding_period: 365 + wash_sale_detection: true + wash_sale_period: 30 + +alerts: + - type: dividend_income_summary + schedule: quarterly + message: "Quarterly dividend income summary with franking credits" + + - type: cgt_event_detected + trigger: share_sale_detected + message: "Share sale detected - track CGT event and holding period" + + - type: wash_sale_warning + trigger: repurchase_within_30_days + message: "Warning: Share repurchased within 30 days - potential wash sale" + +labels: + - name: "Tax Deductible" + description: "Share trading expense claimable" + color: "green" + auto_apply: false + + - name: "Capital Gain" + description: "Capital gains event (CGT applicable)" + color: "gold" + auto_apply: true + + - name: "Capital Loss" + description: "Capital loss (offset against gains)" + color: "brown" + auto_apply: false + + - name: "Franked Dividend" + description: "Dividend with franking credits attached" + color: "teal" + auto_apply: true + +dependencies: + requires: [] + conflicts_with: [] + +metadata: + created: "2025-11-22" + version: "1.0.0" + author: "Agent Smith" + priority: 3 diff --git a/skills/agent-smith/assets/templates/archive/comprehensive.yaml.archived b/skills/agent-smith/assets/templates/archive/comprehensive.yaml.archived new file mode 100644 index 0000000..3ae92f2 --- /dev/null +++ b/skills/agent-smith/assets/templates/archive/comprehensive.yaml.archived @@ -0,0 +1,832 @@ +name: Comprehensive Foundation +layer: foundation +description: | + Detailed category structure with deep hierarchies for granular tracking. + Best for detail-oriented people, business owners, or those optimizing tax deductions. + + 80+ categories with 2-3 levels of hierarchy for precise expense tracking. + +categories: + # ============================================================ + # INCOME + # ============================================================ + - name: "Income" + parent: null + description: "All income sources" + + - name: "Income:Employment" + parent: "Income" + description: "Employment income" + + - name: "Income:Employment:Salary & Wages" + parent: "Income:Employment" + description: "Regular salary and wage payments" + + - name: "Income:Employment:Bonuses & Commissions" + parent: "Income:Employment" + description: "Performance bonuses, sales commissions" + + - name: "Income:Employment:Allowances" + parent: "Income:Employment" + description: "Travel allowance, car allowance, other" + + - name: "Income:Government Benefits" + parent: "Income" + description: "Centrelink and government payments" + + - name: "Income:Government Benefits:Family Benefits" + parent: "Income:Government Benefits" + description: "Family Tax Benefit, Child Care Subsidy" + + - name: "Income:Government Benefits:Income Support" + parent: "Income:Government Benefits" + description: "JobSeeker, Disability Support, Age Pension" + + - name: "Income:Government Benefits:Child Support" + parent: "Income:Government Benefits" + description: "Child support received" + + - name: "Income:Other Income" + parent: "Income" + description: "Miscellaneous income" + + - name: "Income:Other Income:Tax Refunds" + parent: "Income:Other Income" + description: "ATO tax refunds, GST refunds" + + - name: "Income:Other Income:Gifts & Winnings" + parent: "Income:Other Income" + description: "Cash gifts, competition winnings, lottery" + + - name: "Income:Other Income:Reimbursements" + parent: "Income:Other Income" + description: "Work reimbursements, refunds" + + # ============================================================ + # HOUSING + # ============================================================ + - name: "Housing" + parent: null + description: "Home-related expenses" + + - name: "Housing:Rent or Mortgage" + parent: "Housing" + description: "Rent or mortgage payments" + + - name: "Housing:Rent or Mortgage:Rent" + parent: "Housing:Rent or Mortgage" + description: "Rental payments" + + - name: "Housing:Rent or Mortgage:Mortgage Repayments" + parent: "Housing:Rent or Mortgage" + description: "Principal and interest payments" + + - name: "Housing:Rates & Levies" + parent: "Housing" + description: "Government and strata charges" + + - name: "Housing:Rates & Levies:Council Rates" + parent: "Housing:Rates & Levies" + description: "Municipal council rates" + + - name: "Housing:Rates & Levies:Water Rates" + parent: "Housing:Rates & Levies" + description: "Water service charges" + + - name: "Housing:Rates & Levies:Strata Levies" + parent: "Housing:Rates & Levies" + description: "Body corporate, strata fees" + + - name: "Housing:Maintenance & Repairs" + parent: "Housing" + description: "Home maintenance costs" + + - name: "Housing:Maintenance & Repairs:Repairs" + parent: "Housing:Maintenance & Repairs" + description: "Plumbing, electrical, emergency repairs" + + - name: "Housing:Maintenance & Repairs:Improvements" + parent: "Housing:Maintenance & Repairs" + description: "Renovations, upgrades, capital improvements" + + - name: "Housing:Maintenance & Repairs:Garden & Lawn" + parent: "Housing:Maintenance & Repairs" + description: "Gardening, lawn care, landscaping" + + - name: "Housing:Home Insurance" + parent: "Housing" + description: "Home and contents insurance" + + - name: "Housing:Furnishings" + parent: "Housing" + description: "Furniture, appliances, home setup" + + # ============================================================ + # UTILITIES + # ============================================================ + - name: "Utilities" + parent: null + description: "Essential household services" + + - name: "Utilities:Electricity" + parent: "Utilities" + description: "Electricity bills and charges" + + - name: "Utilities:Gas" + parent: "Utilities" + description: "Natural gas, LPG" + + - name: "Utilities:Water" + parent: "Utilities" + description: "Water usage charges" + + - name: "Utilities:Internet" + parent: "Utilities" + description: "Home internet, NBN" + + - name: "Utilities:Phone" + parent: "Utilities" + description: "Mobile and landline" + + - name: "Utilities:Phone:Mobile" + parent: "Utilities:Phone" + description: "Mobile phone plans, prepaid" + + - name: "Utilities:Phone:Landline" + parent: "Utilities:Phone" + description: "Home phone service" + + # ============================================================ + # FOOD & DINING + # ============================================================ + - name: "Food & Dining" + parent: null + description: "Food and beverage expenses" + + - name: "Food & Dining:Groceries" + parent: "Food & Dining" + description: "Food shopping" + + - name: "Food & Dining:Groceries:Supermarket" + parent: "Food & Dining:Groceries" + description: "Woolworths, Coles, Aldi, IGA" + + - name: "Food & Dining:Groceries:Specialty Stores" + parent: "Food & Dining:Groceries" + description: "Butcher, baker, deli, fruit shop" + + - name: "Food & Dining:Groceries:Online Delivery" + parent: "Food & Dining:Groceries" + description: "Online grocery delivery services" + + - name: "Food & Dining:Restaurants" + parent: "Food & Dining" + description: "Dining out" + + - name: "Food & Dining:Takeaway & Delivery" + parent: "Food & Dining" + description: "Takeaway food" + + - name: "Food & Dining:Takeaway & Delivery:Fast Food" + parent: "Food & Dining:Takeaway & Delivery" + description: "McDonald's, KFC, etc." + + - name: "Food & Dining:Takeaway & Delivery:Food Delivery" + parent: "Food & Dining:Takeaway & Delivery" + description: "Uber Eats, Menulog, DoorDash" + + - name: "Food & Dining:Coffee & Cafes" + parent: "Food & Dining" + description: "Coffee shops, cafe visits" + + - name: "Food & Dining:Alcohol & Beverages" + parent: "Food & Dining" + description: "Bottleshops, liquor, soft drinks" + + # ============================================================ + # TRANSPORTATION + # ============================================================ + - name: "Transportation" + parent: null + description: "Transport and vehicle expenses" + + - name: "Transportation:Vehicle Ownership" + parent: "Transportation" + description: "Owning and running a vehicle" + + - name: "Transportation:Vehicle Ownership:Fuel" + parent: "Transportation:Vehicle Ownership" + description: "Petrol, diesel, LPG" + + - name: "Transportation:Vehicle Ownership:Maintenance & Servicing" + parent: "Transportation:Vehicle Ownership" + description: "Regular servicing, oil changes" + + - name: "Transportation:Vehicle Ownership:Repairs" + parent: "Transportation:Vehicle Ownership" + description: "Breakdowns, accident repairs, tyres" + + - name: "Transportation:Vehicle Ownership:Registration & Insurance" + parent: "Transportation:Vehicle Ownership" + description: "Rego, CTP, comprehensive insurance" + + - name: "Transportation:Vehicle Ownership:Car Wash & Detailing" + parent: "Transportation:Vehicle Ownership" + description: "Cleaning, detailing, car care" + + - name: "Transportation:Parking & Tolls" + parent: "Transportation" + description: "Parking and road tolls" + + - name: "Transportation:Parking & Tolls:Parking" + parent: "Transportation:Parking & Tolls" + description: "Street parking, parking meters, car parks" + + - name: "Transportation:Parking & Tolls:Tolls" + parent: "Transportation:Parking & Tolls" + description: "E-tag, toll roads, M1, M2, etc." + + - name: "Transportation:Public Transport" + parent: "Transportation" + description: "Buses, trains, trams, ferries" + + - name: "Transportation:Public Transport:Opal/Myki Card" + parent: "Transportation:Public Transport" + description: "Prepaid transport cards" + + - name: "Transportation:Public Transport:Tickets" + parent: "Transportation:Public Transport" + description: "Single tickets, day passes" + + - name: "Transportation:Rideshare & Taxis" + parent: "Transportation" + description: "Uber, Didi, taxis" + + # ============================================================ + # HEALTHCARE + # ============================================================ + - name: "Healthcare" + parent: null + description: "Medical and health expenses" + + - name: "Healthcare:Medical Services" + parent: "Healthcare" + description: "Doctor visits and medical care" + + - name: "Healthcare:Medical Services:GP & Specialists" + parent: "Healthcare:Medical Services" + description: "General practitioner, specialist doctors" + + - name: "Healthcare:Medical Services:Tests & Pathology" + parent: "Healthcare:Medical Services" + description: "Blood tests, x-rays, scans, pathology" + + - name: "Healthcare:Medical Services:Hospital & Emergency" + parent: "Healthcare:Medical Services" + description: "Hospital visits, emergency care, ambulance" + + - name: "Healthcare:Dental" + parent: "Healthcare" + description: "Dental care" + + - name: "Healthcare:Dental:General Dental" + parent: "Healthcare:Dental" + description: "Check-ups, cleaning, fillings" + + - name: "Healthcare:Dental:Orthodontics" + parent: "Healthcare:Dental" + description: "Braces, Invisalign, orthodontic treatment" + + - name: "Healthcare:Pharmacy" + parent: "Healthcare" + description: "Pharmacy and medications" + + - name: "Healthcare:Pharmacy:Prescriptions" + parent: "Healthcare:Pharmacy" + description: "PBS prescriptions, scripts" + + - name: "Healthcare:Pharmacy:Over the Counter" + parent: "Healthcare:Pharmacy" + description: "Non-prescription medicines, first aid" + + - name: "Healthcare:Allied Health" + parent: "Healthcare" + description: "Other health services" + + - name: "Healthcare:Allied Health:Physiotherapy" + parent: "Healthcare:Allied Health" + description: "Physio, exercise physiology" + + - name: "Healthcare:Allied Health:Psychology & Counselling" + parent: "Healthcare:Allied Health" + description: "Psychologist, counsellor, mental health" + + - name: "Healthcare:Allied Health:Other Therapies" + parent: "Healthcare:Allied Health" + description: "Chiro, osteo, massage, acupuncture" + + - name: "Healthcare:Optical" + parent: "Healthcare" + description: "Eye care, glasses, contacts" + + - name: "Healthcare:Health Insurance" + parent: "Healthcare" + description: "Private health insurance premiums" + + # ============================================================ + # PERSONAL CARE & APPEARANCE + # ============================================================ + - name: "Personal Care" + parent: null + description: "Personal grooming and care" + + - name: "Personal Care:Hair & Beauty" + parent: "Personal Care" + description: "Hair and beauty services" + + - name: "Personal Care:Hair & Beauty:Haircuts & Styling" + parent: "Personal Care:Hair & Beauty" + description: "Barber, hairdresser, hair treatments" + + - name: "Personal Care:Hair & Beauty:Beauty Services" + parent: "Personal Care:Hair & Beauty" + description: "Nails, waxing, facials, beauty treatments" + + - name: "Personal Care:Toiletries & Cosmetics" + parent: "Personal Care" + description: "Personal hygiene products" + + - name: "Personal Care:Toiletries & Cosmetics:Skincare & Cosmetics" + parent: "Personal Care:Toiletries & Cosmetics" + description: "Makeup, skincare, fragrances" + + - name: "Personal Care:Toiletries & Cosmetics:Personal Hygiene" + parent: "Personal Care:Toiletries & Cosmetics" + description: "Shampoo, soap, deodorant, dental care" + + - name: "Clothing & Footwear" + parent: null + description: "Clothes and shoes" + + - name: "Clothing & Footwear:Adults" + parent: "Clothing & Footwear" + description: "Adult clothing and shoes" + + - name: "Clothing & Footwear:Kids" + parent: "Clothing & Footwear" + description: "Children's clothing and shoes" + + - name: "Clothing & Footwear:Accessories" + parent: "Clothing & Footwear" + description: "Bags, wallets, jewellery, watches" + + # ============================================================ + # ENTERTAINMENT & RECREATION + # ============================================================ + - name: "Entertainment & Recreation" + parent: null + description: "Entertainment and leisure" + + - name: "Entertainment & Recreation:Subscriptions" + parent: "Entertainment & Recreation" + description: "Streaming and digital services" + + - name: "Entertainment & Recreation:Subscriptions:Streaming Video" + parent: "Entertainment & Recreation:Subscriptions" + description: "Netflix, Stan, Disney+, Binge" + + - name: "Entertainment & Recreation:Subscriptions:Streaming Music" + parent: "Entertainment & Recreation:Subscriptions" + description: "Spotify, Apple Music, YouTube Music" + + - name: "Entertainment & Recreation:Subscriptions:Gaming" + parent: "Entertainment & Recreation:Subscriptions" + description: "PlayStation Plus, Xbox Game Pass, etc." + + - name: "Entertainment & Recreation:Subscriptions:News & Publications" + parent: "Entertainment & Recreation:Subscriptions" + description: "Newspapers, magazines, digital subscriptions" + + - name: "Entertainment & Recreation:Fitness & Sport" + parent: "Entertainment & Recreation" + description: "Fitness and sports activities" + + - name: "Entertainment & Recreation:Fitness & Sport:Gym Membership" + parent: "Entertainment & Recreation:Fitness & Sport" + description: "Gym, fitness classes, personal training" + + - name: "Entertainment & Recreation:Fitness & Sport:Sports & Activities" + parent: "Entertainment & Recreation:Fitness & Sport" + description: "Sports clubs, equipment, registration fees" + + - name: "Entertainment & Recreation:Events & Outings" + parent: "Entertainment & Recreation" + description: "Events and activities" + + - name: "Entertainment & Recreation:Events & Outings:Movies & Cinema" + parent: "Entertainment & Recreation:Events & Outings" + description: "Movie tickets, cinema" + + - name: "Entertainment & Recreation:Events & Outings:Concerts & Theatre" + parent: "Entertainment & Recreation:Events & Outings" + description: "Live music, theatre, performances" + + - name: "Entertainment & Recreation:Events & Outings:Sports Events" + parent: "Entertainment & Recreation:Events & Outings" + description: "AFL, NRL, cricket, sports tickets" + + - name: "Entertainment & Recreation:Hobbies" + parent: "Entertainment & Recreation" + description: "Hobby-related expenses" + + - name: "Entertainment & Recreation:Books & Media" + parent: "Entertainment & Recreation" + description: "Books, audiobooks, magazines, DVDs" + + - name: "Entertainment & Recreation:Gaming" + parent: "Entertainment & Recreation" + description: "Video games, board games, gaming gear" + + # ============================================================ + # EDUCATION & DEVELOPMENT + # ============================================================ + - name: "Education" + parent: null + description: "Education and learning" + + - name: "Education:School" + parent: "Education" + description: "Primary and secondary school" + + - name: "Education:School:School Fees" + parent: "Education:School" + description: "Tuition fees, private school fees" + + - name: "Education:School:School Uniforms" + parent: "Education:School" + description: "Uniforms, sports gear" + + - name: "Education:School:Excursions & Activities" + parent: "Education:School" + description: "School camps, excursions, activities" + + - name: "Education:Tertiary Education" + parent: "Education" + description: "University, TAFE, higher education" + + - name: "Education:Tertiary Education:Tuition Fees" + parent: "Education:Tertiary Education" + description: "HECS, course fees, semester fees" + + - name: "Education:Tertiary Education:Textbooks & Materials" + parent: "Education:Tertiary Education" + description: "Textbooks, course materials, stationery" + + - name: "Education:Courses & Training" + parent: "Education" + description: "Professional development, short courses" + + - name: "Education:Tutoring" + parent: "Education" + description: "Private tutoring, coaching" + + # ============================================================ + # KIDS & FAMILY + # ============================================================ + - name: "Kids & Family" + parent: null + description: "Child-related expenses" + + - name: "Kids & Family:Childcare & Education" + parent: "Kids & Family" + description: "Childcare services" + + - name: "Kids & Family:Childcare & Education:Daycare" + parent: "Kids & Family:Childcare & Education" + description: "Long day care, family day care" + + - name: "Kids & Family:Childcare & Education:Before/After School Care" + parent: "Kids & Family:Childcare & Education" + description: "OOSH, vacation care" + + - name: "Kids & Family:Activities" + parent: "Kids & Family" + description: "Kids activities and sports" + + - name: "Kids & Family:Activities:Sports" + parent: "Kids & Family:Activities" + description: "Kids sports, swimming lessons, team fees" + + - name: "Kids & Family:Activities:Music & Arts" + parent: "Kids & Family:Activities" + description: "Music lessons, art classes, dance" + + - name: "Kids & Family:Toys & Entertainment" + parent: "Kids & Family" + description: "Toys, games, kid entertainment" + + - name: "Kids & Family:Baby Supplies" + parent: "Kids & Family" + description: "Nappies, formula, baby products" + + - name: "Kids & Family:Pocket Money & Allowances" + parent: "Kids & Family" + description: "Kids pocket money, allowances" + + # ============================================================ + # FINANCIAL SERVICES + # ============================================================ + - name: "Financial Services" + parent: null + description: "Banking and financial costs" + + - name: "Financial Services:Bank Fees" + parent: "Financial Services" + description: "Banking fees and charges" + + - name: "Financial Services:Bank Fees:Account Fees" + parent: "Financial Services:Bank Fees" + description: "Monthly account fees, transaction fees" + + - name: "Financial Services:Bank Fees:ATM Fees" + parent: "Financial Services:Bank Fees" + description: "ATM withdrawal fees, foreign ATM fees" + + - name: "Financial Services:Interest & Finance Charges" + parent: "Financial Services" + description: "Interest and finance costs" + + - name: "Financial Services:Interest & Finance Charges:Credit Card Interest" + parent: "Financial Services:Interest & Finance Charges" + description: "Credit card interest charges" + + - name: "Financial Services:Interest & Finance Charges:Loan Interest" + parent: "Financial Services:Interest & Finance Charges" + description: "Personal loan interest, other loan costs" + + - name: "Financial Services:Accounting & Tax" + parent: "Financial Services" + description: "Accountant, tax agent, bookkeeping" + + # ============================================================ + # INSURANCE + # ============================================================ + - name: "Insurance" + parent: null + description: "Insurance premiums (non-health, non-vehicle)" + + - name: "Insurance:Life & Income Protection" + parent: "Insurance" + description: "Life insurance and income protection" + + - name: "Insurance:Life & Income Protection:Life Insurance" + parent: "Insurance:Life & Income Protection" + description: "Life insurance premiums" + + - name: "Insurance:Life & Income Protection:Income Protection" + parent: "Insurance:Life & Income Protection" + description: "Income protection, TPD, trauma insurance" + + - name: "Insurance:Pet Insurance" + parent: "Insurance" + description: "Pet insurance premiums" + + - name: "Insurance:Travel Insurance" + parent: "Insurance" + description: "Travel insurance, overseas coverage" + + - name: "Insurance:Other Insurance" + parent: "Insurance" + description: "Other insurance policies" + + # ============================================================ + # SHOPPING & HOUSEHOLD + # ============================================================ + - name: "Shopping" + parent: null + description: "General retail and household" + + - name: "Shopping:Household Items" + parent: "Shopping" + description: "Household goods and supplies" + + - name: "Shopping:Household Items:Furniture" + parent: "Shopping:Household Items" + description: "Furniture, beds, sofas, tables" + + - name: "Shopping:Household Items:Appliances" + parent: "Shopping:Household Items" + description: "Fridges, washing machines, electronics" + + - name: "Shopping:Household Items:Homewares" + parent: "Shopping:Household Items" + description: "Kitchen items, bedding, décor, storage" + + - name: "Shopping:Household Items:Cleaning Supplies" + parent: "Shopping:Household Items" + description: "Cleaning products, laundry detergent" + + - name: "Shopping:General Retail" + parent: "Shopping" + description: "Department stores and misc purchases" + + - name: "Shopping:Electronics" + parent: "Shopping" + description: "Computers, phones, tablets, tech" + + - name: "Shopping:Hardware & DIY" + parent: "Shopping" + description: "Bunnings, hardware, DIY supplies" + + # ============================================================ + # GIFTS & DONATIONS + # ============================================================ + - name: "Gifts & Donations" + parent: null + description: "Gifts and charitable giving" + + - name: "Gifts & Donations:Gifts" + parent: "Gifts & Donations" + description: "Birthday, Christmas, special occasion gifts" + + - name: "Gifts & Donations:Charitable Donations" + parent: "Gifts & Donations" + description: "Charity donations, sponsorships" + + # ============================================================ + # PETS + # ============================================================ + - name: "Pets" + parent: null + description: "Pet-related expenses" + + - name: "Pets:Food & Supplies" + parent: "Pets" + description: "Pet food, litter, supplies" + + - name: "Pets:Veterinary" + parent: "Pets" + description: "Vet visits, medications, surgery" + + - name: "Pets:Grooming & Boarding" + parent: "Pets" + description: "Grooming, pet sitting, boarding kennels" + + # ============================================================ + # TRAVEL & HOLIDAYS + # ============================================================ + - name: "Travel & Holidays" + parent: null + description: "Travel and holiday expenses" + + - name: "Travel & Holidays:Accommodation" + parent: "Travel & Holidays" + description: "Hotels, Airbnb, holiday rentals" + + - name: "Travel & Holidays:Flights & Transport" + parent: "Travel & Holidays" + description: "Airfares and transport" + + - name: "Travel & Holidays:Flights & Transport:Airfares" + parent: "Travel & Holidays:Flights & Transport" + description: "Domestic and international flights" + + - name: "Travel & Holidays:Flights & Transport:Car Hire" + parent: "Travel & Holidays:Flights & Transport" + description: "Rental cars, car hire" + + - name: "Travel & Holidays:Activities & Tours" + parent: "Travel & Holidays" + description: "Tours, attractions, activities" + + - name: "Travel & Holidays:Holiday Spending" + parent: "Travel & Holidays" + description: "Meals, shopping, misc while on holiday" + + # ============================================================ + # GOVERNMENT & ADMIN + # ============================================================ + - name: "Government & Fees" + parent: null + description: "Government charges and official fees" + + - name: "Government & Fees:Fines & Penalties" + parent: "Government & Fees" + description: "Fines and late fees" + + - name: "Government & Fees:Fines & Penalties:Traffic Fines" + parent: "Government & Fees:Fines & Penalties" + description: "Speeding, parking, traffic infringements" + + - name: "Government & Fees:Fines & Penalties:Other Fines" + parent: "Government & Fees:Fines & Penalties" + description: "Library fines, other penalties" + + - name: "Government & Fees:Licences & Registration" + parent: "Government & Fees" + description: "Licences and registrations" + + - name: "Government & Fees:Licences & Registration:Driver Licence" + parent: "Government & Fees:Licences & Registration" + description: "Licence renewal, learner's permit" + + - name: "Government & Fees:Licences & Registration:Professional Registration" + parent: "Government & Fees:Licences & Registration" + description: "Trade licences, professional registrations" + + - name: "Government & Fees:Legal & Professional" + parent: "Government & Fees" + description: "Legal fees, solicitors, conveyancing" + + # ============================================================ + # DEBT & SAVINGS + # ============================================================ + - name: "Debt Payments" + parent: null + description: "Loan and debt repayments" + + - name: "Debt Payments:Personal Loans" + parent: "Debt Payments" + description: "Personal loan repayments" + + - name: "Debt Payments:Credit Cards" + parent: "Debt Payments" + description: "Credit card payments" + + - name: "Debt Payments:BNPL" + parent: "Debt Payments" + description: "Afterpay, Zip Pay, buy now pay later" + + - name: "Debt Payments:Other Debt" + parent: "Debt Payments" + description: "Other debt repayments" + + # ============================================================ + # TRANSFERS & OTHER + # ============================================================ + - name: "Transfers & Adjustments" + parent: null + description: "Account transfers and movements" + + - name: "Transfers & Adjustments:Savings Transfers" + parent: "Transfers & Adjustments" + description: "Transfers to savings accounts" + + - name: "Transfers & Adjustments:Investment Contributions" + parent: "Transfers & Adjustments" + description: "Super contributions, shares, investments" + + - name: "Transfers & Adjustments:Internal Transfers" + parent: "Transfers & Adjustments" + description: "Transfers between own accounts" + + - name: "Uncategorised" + parent: null + description: "Transactions not yet categorised" + +rules: + # ============================================================ + # COMMON GROCERY STORES (Australia) + # ============================================================ + - type: category + name: Woolworths → Groceries + patterns: [Woolworths, WOOLWORTHS] + category: Food & Dining > Groceries + confidence: 95 + + - type: category + name: Coles → Groceries + patterns: [Coles, COLES] + category: Food & Dining > Groceries + confidence: 95 + + - type: category + name: Aldi → Groceries + patterns: [Aldi, ALDI] + category: Food & Dining > Groceries + confidence: 95 + + - type: category + name: IGA → Groceries + patterns: [IGA] + category: Food & Dining > Groceries + confidence: 95 + +labels: [] + +tax_tracking: + detailed_expense_tracking: true + receipt_tracking_enabled: true + +alerts: [] + +dependencies: + requires: [] + conflicts_with: ["minimal", "standard"] + +metadata: + created: "2025-11-23" + version: "1.0.0" + author: "Agent Smith" + priority: 0 + category_count: 186 diff --git a/skills/agent-smith/assets/templates/archive/minimal.yaml.archived b/skills/agent-smith/assets/templates/archive/minimal.yaml.archived new file mode 100644 index 0000000..f6b140a --- /dev/null +++ b/skills/agent-smith/assets/templates/archive/minimal.yaml.archived @@ -0,0 +1,121 @@ +name: Minimal Foundation +layer: foundation +description: | + Simple, broad category structure for basic expense tracking. + Best for people who prefer simplicity and don't need detailed breakdowns. + + 20 top-level categories covering essential expense areas. + +categories: + # Income + - name: "Income" + parent: null + description: "All income sources" + + # Housing & Home + - name: "Housing" + parent: null + description: "Rent, mortgage, rates, home expenses" + + - name: "Utilities" + parent: null + description: "Electricity, gas, water, internet, phone" + + # Food + - name: "Food & Dining" + parent: null + description: "Groceries, restaurants, takeaway" + + # Transportation + - name: "Transportation" + parent: null + description: "Fuel, public transport, vehicle costs" + + # Health + - name: "Healthcare" + parent: null + description: "Medical, dental, pharmacy, Medicare gap" + + # Personal & Lifestyle + - name: "Personal Care" + parent: null + description: "Haircuts, cosmetics, toiletries" + + - name: "Clothing" + parent: null + description: "Clothes, shoes, accessories" + + - name: "Entertainment" + parent: null + description: "Movies, streaming, hobbies, recreation" + + - name: "Education" + parent: null + description: "School fees, courses, textbooks" + + # Financial + - name: "Insurance" + parent: null + description: "Health, car, home, life insurance" + + - name: "Banking & Fees" + parent: null + description: "Bank fees, account charges, ATM fees" + + - name: "Debt Payments" + parent: null + description: "Loan repayments, credit card payments" + + # Discretionary + - name: "Shopping" + parent: null + description: "General retail, online shopping, household items" + + - name: "Gifts & Donations" + parent: null + description: "Presents, charity donations" + + - name: "Pets" + parent: null + description: "Pet food, vet, supplies" + + # Special + - name: "Travel & Holidays" + parent: null + description: "Flights, accommodation, holiday expenses" + + - name: "Subscriptions" + parent: null + description: "Streaming, memberships, recurring services" + + # Other + - name: "Government & Fees" + parent: null + description: "Rates, fines, registration, licences" + + - name: "Uncategorised" + parent: null + description: "Transactions not yet categorised" + +rules: [] + # No rules in foundation - rules come from primary/living/additional templates + +labels: [] + # No labels in foundation + +tax_tracking: + basic_expense_tracking: true + +alerts: [] + +dependencies: + requires: [] + conflicts_with: ["standard", "comprehensive"] + note: "Foundation templates are mutually exclusive - choose only one" + +metadata: + created: "2025-11-23" + version: "1.0.0" + author: "Agent Smith" + priority: 0 # Lowest priority - applied first + category_count: 20 diff --git a/skills/agent-smith/assets/templates/archive/single.yaml.archived b/skills/agent-smith/assets/templates/archive/single.yaml.archived new file mode 100644 index 0000000..3e023f9 --- /dev/null +++ b/skills/agent-smith/assets/templates/archive/single.yaml.archived @@ -0,0 +1,65 @@ +name: Single Person +layer: living +description: | + Managing finances independently without shared household expenses. + Adds simple rules for common single-person expense patterns. + + Note: Categories are provided by Foundation template. This template adds + only rules to help categorize common single-person expenses. + +categories: [] + # No special categories needed - Foundation provides Housing, Utilities, Groceries, etc. + # Living templates add labels and rules, not categories. + +rules: + - id: rent-payment + pattern: "rent|rental.*payment|real.*estate" + category: "Rent/Mortgage" + confidence: high + description: "Detect rent payments" + + - id: electricity-bill + pattern: "electricity|power.*bill|energy.*australia" + category: "Electricity" + confidence: high + description: "Detect electricity bills" + + - id: gas-bill + pattern: "gas.*bill|natural.*gas" + category: "Gas" + confidence: high + description: "Detect gas bills" + + - id: water-bill + pattern: "water.*bill|water.*rates" + category: "Water" + confidence: high + description: "Detect water bills" + + - id: internet-phone + pattern: "internet|telstra|optus|vodafone|phone.*bill|mobile" + category: "Internet & Phone" + confidence: high + description: "Detect internet and phone bills" + + - id: groceries + pattern: "woolworths|coles|aldi|iga|grocery" + category: "Groceries" + confidence: high + description: "Detect grocery shopping" + +tax_tracking: {} + +alerts: [] + +labels: [] + +dependencies: + requires: [] + conflicts_with: ["shared-joint", "shared-hybrid", "separated-parents", "sharehouse"] + +metadata: + created: "2025-11-22" + version: "1.0.0" + author: "Agent Smith" + priority: 2 diff --git a/skills/agent-smith/assets/templates/archive/standard.yaml.archived b/skills/agent-smith/assets/templates/archive/standard.yaml.archived new file mode 100644 index 0000000..5ad90b5 --- /dev/null +++ b/skills/agent-smith/assets/templates/archive/standard.yaml.archived @@ -0,0 +1,361 @@ +name: Standard Foundation +layer: foundation +description: | + Balanced category structure with 1-2 levels of hierarchy. + Best for most people - detailed enough for insights, simple enough to maintain. + + 45 categories with logical groupings for common Australian expenses. + +categories: + # ============================================================ + # INCOME + # ============================================================ + - name: "Income" + parent: null + description: "All income sources" + + - name: "Income:Employment" + parent: "Income" + description: "Salary, wages, bonuses" + + - name: "Income:Government Benefits" + parent: "Income" + description: "Centrelink, Family Tax Benefit, Child Support" + + - name: "Income:Other" + parent: "Income" + description: "Gifts, refunds, miscellaneous income" + + # ============================================================ + # HOUSING + # ============================================================ + - name: "Housing" + parent: null + description: "Home-related expenses" + + - name: "Housing:Rent or Mortgage" + parent: "Housing" + description: "Rent payments or mortgage repayments" + + - name: "Housing:Rates & Levies" + parent: "Housing" + description: "Council rates, water rates, strata levies" + + - name: "Housing:Maintenance & Repairs" + parent: "Housing" + description: "Home repairs, maintenance, improvements" + + - name: "Housing:Home Insurance" + parent: "Housing" + description: "Home and contents insurance" + + # ============================================================ + # UTILITIES + # ============================================================ + - name: "Utilities" + parent: null + description: "Essential household services" + + - name: "Utilities:Electricity" + parent: "Utilities" + description: "Electricity bills" + + - name: "Utilities:Gas" + parent: "Utilities" + description: "Gas bills" + + - name: "Utilities:Water" + parent: "Utilities" + description: "Water bills" + + - name: "Utilities:Internet & Phone" + parent: "Utilities" + description: "Internet, mobile, landline" + + # ============================================================ + # FOOD & DINING + # ============================================================ + - name: "Food & Dining" + parent: null + description: "Food and beverage expenses" + + - name: "Food & Dining:Groceries" + parent: "Food & Dining" + description: "Supermarket, grocery shopping" + + - name: "Food & Dining:Restaurants" + parent: "Food & Dining" + description: "Dining out, cafes" + + - name: "Food & Dining:Takeaway & Delivery" + parent: "Food & Dining" + description: "Takeaway, food delivery services" + + # ============================================================ + # TRANSPORTATION + # ============================================================ + - name: "Transportation" + parent: null + description: "Transport and vehicle expenses" + + - name: "Transportation:Fuel" + parent: "Transportation" + description: "Petrol, diesel" + + - name: "Transportation:Public Transport" + parent: "Transportation" + description: "Trains, buses, trams, ferries, Opal/Myki" + + - name: "Transportation:Vehicle Maintenance" + parent: "Transportation" + description: "Repairs, servicing, tyres" + + - name: "Transportation:Registration & Insurance" + parent: "Transportation" + description: "Rego, CTP, car insurance" + + - name: "Transportation:Parking & Tolls" + parent: "Transportation" + description: "Parking fees, tolls, e-tags" + + - name: "Transportation:Rideshare & Taxis" + parent: "Transportation" + description: "Uber, taxis, rideshare" + + # ============================================================ + # HEALTHCARE + # ============================================================ + - name: "Healthcare" + parent: null + description: "Medical and health expenses" + + - name: "Healthcare:Medical" + parent: "Healthcare" + description: "GP visits, specialists, Medicare gap" + + - name: "Healthcare:Dental" + parent: "Healthcare" + description: "Dentist, orthodontist" + + - name: "Healthcare:Pharmacy & Prescriptions" + parent: "Healthcare" + description: "Medications, pharmacy items, PBS" + + - name: "Healthcare:Health Insurance" + parent: "Healthcare" + description: "Private health insurance premiums" + + - name: "Healthcare:Other Health" + parent: "Healthcare" + description: "Physio, chiro, optical, allied health" + + # ============================================================ + # PERSONAL & LIFESTYLE + # ============================================================ + - name: "Personal Care" + parent: null + description: "Personal grooming and care" + + - name: "Personal Care:Hair & Beauty" + parent: "Personal Care" + description: "Haircuts, salons, beauty treatments" + + - name: "Personal Care:Toiletries & Cosmetics" + parent: "Personal Care" + description: "Personal hygiene products, cosmetics" + + - name: "Clothing & Footwear" + parent: null + description: "Clothes, shoes, accessories" + + - name: "Entertainment & Recreation" + parent: null + description: "Entertainment, hobbies, recreation" + + - name: "Entertainment & Recreation:Streaming & Subscriptions" + parent: "Entertainment & Recreation" + description: "Netflix, Spotify, Stan, gaming subscriptions" + + - name: "Entertainment & Recreation:Hobbies & Activities" + parent: "Entertainment & Recreation" + description: "Sports, gym, clubs, hobbies" + + - name: "Entertainment & Recreation:Events & Outings" + parent: "Entertainment & Recreation" + description: "Movies, concerts, sports events, activities" + + # ============================================================ + # EDUCATION & DEVELOPMENT + # ============================================================ + - name: "Education" + parent: null + description: "Education expenses" + + - name: "Education:School Fees & Costs" + parent: "Education" + description: "School fees, uniforms, excursions" + + - name: "Education:Courses & Training" + parent: "Education" + description: "TAFE, uni, online courses, professional development" + + - name: "Education:Books & Supplies" + parent: "Education" + description: "Textbooks, stationery, learning materials" + + # ============================================================ + # FINANCIAL + # ============================================================ + - name: "Financial Services" + parent: null + description: "Banking, fees, and financial costs" + + - name: "Financial Services:Bank Fees" + parent: "Financial Services" + description: "Account fees, ATM fees, transaction charges" + + - name: "Financial Services:Interest & Charges" + parent: "Financial Services" + description: "Credit card interest, loan fees" + + - name: "Insurance" + parent: null + description: "Insurance premiums (non-health, non-vehicle)" + + - name: "Insurance:Life Insurance" + parent: "Insurance" + description: "Life, income protection, TPD" + + - name: "Insurance:Other Insurance" + parent: "Insurance" + description: "Pet insurance, travel insurance, other" + + # ============================================================ + # DISCRETIONARY + # ============================================================ + - name: "Shopping" + parent: null + description: "General retail and household items" + + - name: "Shopping:Household Items" + parent: "Shopping" + description: "Furniture, appliances, homewares" + + - name: "Shopping:General Retail" + parent: "Shopping" + description: "Department stores, online shopping, misc purchases" + + - name: "Gifts & Donations" + parent: null + description: "Gifts and charitable giving" + + - name: "Pets" + parent: null + description: "Pet food, vet, grooming, supplies" + + # ============================================================ + # TRAVEL + # ============================================================ + - name: "Travel & Holidays" + parent: null + description: "Travel and holiday expenses" + + - name: "Travel & Holidays:Accommodation" + parent: "Travel & Holidays" + description: "Hotels, Airbnb, holiday rentals" + + - name: "Travel & Holidays:Flights & Transport" + parent: "Travel & Holidays" + description: "Airfares, car hire, transfers" + + # ============================================================ + # KIDS (if applicable) + # ============================================================ + - name: "Kids & Family" + parent: null + description: "Child-related expenses" + + - name: "Kids & Family:Childcare" + parent: "Kids & Family" + description: "Daycare, before/after school care, vacation care" + + - name: "Kids & Family:Activities & Sports" + parent: "Kids & Family" + description: "Kids sports, music lessons, activities" + + - name: "Kids & Family:Other Kid Expenses" + parent: "Kids & Family" + description: "Toys, birthday parties, kid-specific costs" + + # ============================================================ + # GOVERNMENT & ADMIN + # ============================================================ + - name: "Government & Fees" + parent: null + description: "Government charges and official fees" + + - name: "Government & Fees:Fines & Penalties" + parent: "Government & Fees" + description: "Traffic fines, parking fines, late fees" + + - name: "Government & Fees:Licences & Registration" + parent: "Government & Fees" + description: "Driver licence, professional registrations" + + # ============================================================ + # OTHER + # ============================================================ + - name: "Transfers & Adjustments" + parent: null + description: "Account transfers, savings, investments" + + - name: "Uncategorised" + parent: null + description: "Transactions not yet categorised" + +rules: + # ============================================================ + # COMMON GROCERY STORES (Australia) + # ============================================================ + - type: category + name: Woolworths → Groceries + patterns: [Woolworths, WOOLWORTHS] + category: Food & Dining > Groceries + confidence: 95 + + - type: category + name: Coles → Groceries + patterns: [Coles, COLES] + category: Food & Dining > Groceries + confidence: 95 + + - type: category + name: Aldi → Groceries + patterns: [Aldi, ALDI] + category: Food & Dining > Groceries + confidence: 95 + + - type: category + name: IGA → Groceries + patterns: [IGA] + category: Food & Dining > Groceries + confidence: 95 + +labels: [] + +tax_tracking: + basic_expense_tracking: true + +alerts: [] + +dependencies: + requires: [] + conflicts_with: ["minimal", "comprehensive"] + +metadata: + created: "2025-11-23" + version: "1.0.0" + author: "Agent Smith" + priority: 0 + category_count: 65 + recommended: true diff --git a/skills/agent-smith/assets/templates/foundation/personal-living.json b/skills/agent-smith/assets/templates/foundation/personal-living.json new file mode 100644 index 0000000..36d78c6 --- /dev/null +++ b/skills/agent-smith/assets/templates/foundation/personal-living.json @@ -0,0 +1,349 @@ +{ + "name": "Foundation: Personal Living", + "description": "Core personal expense categories for everyday living, aligned with ATO guidance", + "layer": "foundation", + "priority": 0, + "applies_to": ["all"], + "ato_aligned": true, + "categories": [ + { + "name": "Income", + "parent": null, + "description": "All income sources", + "ato_section": "Income" + }, + { + "name": "Salary/Wages", + "parent": "Income", + "description": "Employment income from salary or wages", + "ato_section": "Item 1" + }, + { + "name": "Other Income", + "parent": "Income", + "description": "Income not covered by other categories", + "ato_section": "Item 24" + }, + { + "name": "Interest Income", + "parent": "Income", + "description": "Interest from bank accounts and investments", + "ato_section": "Item 10" + }, + { + "name": "Food & Dining", + "parent": null, + "description": "Food and meal expenses" + }, + { + "name": "Groceries", + "parent": "Food & Dining", + "description": "Supermarket and grocery shopping" + }, + { + "name": "Restaurants", + "parent": "Food & Dining", + "description": "Dining out at restaurants" + }, + { + "name": "Cafes & Takeaway", + "parent": "Food & Dining", + "description": "Coffee shops and takeaway food" + }, + { + "name": "Housing & Utilities", + "parent": null, + "description": "Housing costs and utilities" + }, + { + "name": "Rent/Mortgage", + "parent": "Housing & Utilities", + "description": "Rent or mortgage payments" + }, + { + "name": "Electricity", + "parent": "Housing & Utilities", + "description": "Electricity bills" + }, + { + "name": "Gas", + "parent": "Housing & Utilities", + "description": "Gas bills" + }, + { + "name": "Water", + "parent": "Housing & Utilities", + "description": "Water bills" + }, + { + "name": "Internet & Phone", + "parent": "Housing & Utilities", + "description": "Internet and phone services" + }, + { + "name": "Home Maintenance", + "parent": "Housing & Utilities", + "description": "Repairs and maintenance for your home" + }, + { + "name": "Transportation", + "parent": null, + "description": "Transport and vehicle expenses" + }, + { + "name": "Fuel", + "parent": "Transportation", + "description": "Petrol and diesel for personal vehicles" + }, + { + "name": "Public Transport", + "parent": "Transportation", + "description": "Buses, trains, trams, ferries" + }, + { + "name": "Vehicle Registration", + "parent": "Transportation", + "description": "Vehicle registration and CTP insurance" + }, + { + "name": "Vehicle Maintenance", + "parent": "Transportation", + "description": "Car servicing and repairs" + }, + { + "name": "Parking & Tolls", + "parent": "Transportation", + "description": "Parking fees and road tolls" + }, + { + "name": "Healthcare & Insurance", + "parent": null, + "description": "Medical expenses and insurance" + }, + { + "name": "Medical", + "parent": "Healthcare & Insurance", + "description": "Doctor visits and medical expenses" + }, + { + "name": "Dental", + "parent": "Healthcare & Insurance", + "description": "Dental care expenses" + }, + { + "name": "Pharmacy", + "parent": "Healthcare & Insurance", + "description": "Prescription and over-the-counter medications" + }, + { + "name": "Health Insurance", + "parent": "Healthcare & Insurance", + "description": "Private health insurance premiums" + }, + { + "name": "Life Insurance", + "parent": "Healthcare & Insurance", + "description": "Life and income protection insurance" + }, + { + "name": "Personal & Lifestyle", + "parent": null, + "description": "Personal care and lifestyle expenses" + }, + { + "name": "Clothing & Footwear", + "parent": "Personal & Lifestyle", + "description": "Clothing and shoes for personal use" + }, + { + "name": "Personal Care", + "parent": "Personal & Lifestyle", + "description": "Haircuts, cosmetics, toiletries" + }, + { + "name": "Entertainment & Recreation", + "parent": "Personal & Lifestyle", + "description": "Entertainment, hobbies, and recreation" + }, + { + "name": "Fitness & Wellness", + "parent": "Personal & Lifestyle", + "description": "Gym memberships, fitness activities, wellness" + }, + { + "name": "Gifts & Donations", + "parent": "Personal & Lifestyle", + "description": "Gifts and charitable donations (donations may be tax deductible)", + "ato_section": "D9" + }, + { + "name": "Shopping", + "parent": null, + "description": "Online shopping and retail purchases" + }, + { + "name": "Online Services", + "parent": "Shopping", + "description": "Online payment services and digital purchases" + }, + { + "name": "Banking & Fees", + "parent": null, + "description": "Banking fees and charges" + }, + { + "name": "Bank Fees", + "parent": "Banking & Fees", + "description": "Account keeping fees and transaction fees" + }, + { + "name": "Interest Charges", + "parent": "Banking & Fees", + "description": "Interest on personal loans and credit cards" + }, + { + "name": "Transfers", + "parent": "Banking & Fees", + "description": "Transfers between accounts" + } + ], + "rules": [ + { + "name": "groceries-supermarkets", + "payee_pattern": "woolworths|coles|aldi|iga|foodland|costco|harris farm|fruit market|drakes|supa.*iga|ritchies|foodworks|friendly grocer", + "category": "Groceries", + "confidence": 0.95 + }, + { + "name": "restaurants-dining", + "payee_pattern": "restaurant|bistro|steakhouse|italian|chinese|thai|indian|japanese|korean|vietnamese|cafe.*restaurant", + "category": "Restaurants", + "confidence": 0.90 + }, + { + "name": "cafes-coffee", + "payee_pattern": "cafe|coffee|starbucks|gloria jeans|mccafe|donut king|boost juice", + "category": "Cafes & Takeaway", + "confidence": 0.90 + }, + { + "name": "fast-food-takeaway", + "payee_pattern": "mcdonald|kfc|hungry jack|domino|pizza hut|subway|nando|red rooster|grill'd|guzman|schnitz", + "category": "Cafes & Takeaway", + "confidence": 0.95 + }, + { + "name": "fuel-petrol", + "payee_pattern": "shell|bp|caltex|ampol|7-eleven|united.*petrol|metro.*petrol|mobil|esso", + "category": "Fuel", + "confidence": 0.95 + }, + { + "name": "electricity-providers", + "payee_pattern": "agl|origin|energy australia|red energy|alinta|simply energy|powershop|momentum energy|click energy|sumo|dodo.*power|lumo|people.*energy|diamond.*energy", + "category": "Electricity", + "confidence": 0.95 + }, + { + "name": "gas-providers", + "payee_pattern": "agl.*gas|origin.*gas|energy australia.*gas|simply energy.*gas|sumo.*gas", + "category": "Gas", + "confidence": 0.90 + }, + { + "name": "water-providers", + "payee_pattern": "water.*corporation|sydney.*water|yarra.*valley.*water|sa.*water|icon.*water|unitywater|hunter.*water|city west.*water", + "category": "Water", + "confidence": 0.95 + }, + { + "name": "internet-telco", + "payee_pattern": "telstra|optus|vodafone|tpg|iinet|aussie.*broadband|dodo|belong|internode|southern.*phone|exetel|spintel|tangerine|superloop|mate.*communicate", + "category": "Internet & Phone", + "confidence": 0.95 + }, + { + "name": "public-transport", + "payee_pattern": "opal|myki|go card|translink|metro.*trains|bus.*service|citylink", + "category": "Public Transport", + "confidence": 0.95 + }, + { + "name": "parking-tolls", + "payee_pattern": "secure.*parking|wilson.*parking|toll|e-tag|linkt|citylink|eastlink|go via", + "category": "Parking & Tolls", + "confidence": 0.95 + }, + { + "name": "pharmacy-chemist", + "payee_pattern": "chemist|pharmacy|priceline|terry white|amcal|blooms|soul pattinson|discount.*drug", + "category": "Pharmacy", + "confidence": 0.95 + }, + { + "name": "health-insurance", + "payee_pattern": "bupa|medibank|hcf|nib|ahm|health.*fund|health.*insurance", + "category": "Health Insurance", + "confidence": 0.95 + }, + { + "name": "gym-fitness", + "payee_pattern": "gym|fitness|anytime.*fitness|goodlife|f45|jetts|snap.*fitness|crossfit|yoga|pilates", + "category": "Fitness & Wellness", + "confidence": 0.90 + }, + { + "name": "entertainment-streaming", + "payee_pattern": "netflix|spotify|disney|stan|amazon.*prime|apple.*music|youtube.*premium|paramount|binge", + "category": "Entertainment & Recreation", + "confidence": 0.95 + }, + { + "name": "entertainment-cinema", + "payee_pattern": "hoyts|event.*cinema|village.*cinema|reading.*cinema|movie.*ticket", + "category": "Entertainment & Recreation", + "confidence": 0.95 + }, + { + "name": "clothing-retail", + "payee_pattern": "myer|david jones|target|kmart|big w|uniqlo|h&m|zara|cotton on|rebel.*sport|nike|adidas", + "category": "Clothing & Footwear", + "confidence": 0.85 + }, + { + "name": "personal-care-services", + "payee_pattern": "hair.*salon|barber|hairdresser|beauty|nail.*salon|spa|massage", + "category": "Personal Care", + "confidence": 0.90 + }, + { + "name": "bank-fees", + "payee_pattern": "account.*fee|monthly.*fee|transaction.*fee|atm.*fee|overdraft.*fee|international.*transaction.*fee", + "category": "Bank Fees", + "confidence": 0.95 + }, + { + "name": "transfers-generic", + "payee_pattern": "transfer|bpay|osko", + "category": "Transfers", + "confidence": 0.80 + }, + { + "name": "paypal-generic", + "payee_pattern": "PAYPAL", + "category": "Online Services", + "confidence": 0.60, + "labels": ["$LABEL_GENERIC_PAYPAL"] + } + ], + "labels": [], + "name": "Foundation: Personal Living", + "layer": "foundation", + "metadata": { + "version": "1.0.0", + "priority": 0, + "created": "2025-11-25", + "ato_alignment": "2024-25 tax year", + "recommended_for": ["new_users", "migration_users"] + } +} diff --git a/skills/agent-smith/assets/templates/living/README.md b/skills/agent-smith/assets/templates/living/README.md new file mode 100644 index 0000000..e393955 --- /dev/null +++ b/skills/agent-smith/assets/templates/living/README.md @@ -0,0 +1,15 @@ +# Living Arrangement Templates + +Choose ONE template that matches how you manage household finances. + +## Available Templates + +- `single.yaml` - Managing finances alone +- `shared-joint.yaml` - Partner/spouse, pooled income, joint accounts +- `shared-hybrid.yaml` - Some joint accounts, some separate +- `separated-parents.yaml` - Child support, shared custody expenses +- `sharehouse.yaml` - Splitting bills with roommates + +## YAML Schema + +Same structure as primary templates, with `layer: living`. diff --git a/skills/agent-smith/assets/templates/living/separated-parents.yaml b/skills/agent-smith/assets/templates/living/separated-parents.yaml new file mode 100644 index 0000000..2353270 --- /dev/null +++ b/skills/agent-smith/assets/templates/living/separated-parents.yaml @@ -0,0 +1,114 @@ +name: Separated/Divorced Parents +layer: living +description: | + Managing finances with child support obligations and shared custody expenses. + Tracks child-related spending for tax and legal documentation. + +categories: [] + # No special categories needed - use standard expense categories + # Labels indicate child-related expenses and which parent paid + +rules: + - id: child-support-payment + pattern: "child.*support|CSA.*payment|maintenance.*payment" + # No category override - transactions should be categorized as Transfer or similar + confidence: high + description: "Label child support payments" + labels: ["Child Support", "Child Support Paid"] + + - id: child-support-received + pattern: "child.*support.*received|CSA.*deposit" + # No category override - transactions should be categorized as Transfer or Income + confidence: high + description: "Label child support receipts" + labels: ["Child Support", "Child Support Received"] + + - id: kids-activities + pattern: "sport|swimming|dance|music.*lessons|scouts|karate" + # No category override - use standard Entertainment/Recreation category + confidence: medium + description: "Label children's activity expenses" + labels: ["Kids Expense"] + + - id: kids-medical + pattern: "pediatric|child.*doctor|dentist.*kids|orthodontist|therapy.*child" + # No category override - use standard Medical/Health category + confidence: medium + description: "Label children's medical expenses" + labels: ["Kids Expense", "Medical"] + + - id: kids-education + pattern: "school.*fees|uniform.*school|textbook|excursion|tuckshop" + # No category override - use standard Education category + confidence: high + description: "Label education-related expenses" + labels: ["Kids Expense", "Education"] + +tax_tracking: + child_support_documentation: true + custody_expense_tracking: true + +alerts: + - type: child_support_reconciliation + schedule: monthly + message: "Reconcile child support payments and custody expenses" + + - type: ato_documentation_reminder + schedule: annual + before_date: "06-15" + message: "EOFY - compile child-related expenses for tax return" + +labels: + - name: "Child Support" + description: "Child support payment or receipt" + color: "skyblue" + auto_apply: false + + - name: "Custody Period" + description: "Expense during custody period" + color: "lightpurple" + auto_apply: false + + - name: "Shared Child Expense" + description: "Child expense split with ex-partner" + color: "coral" + auto_apply: false + + - name: "Contributor: {parent_a_name}" + description: "Paid by {parent_a_name}" + color: "orange" + auto_apply: false + requires_configuration: true + configuration_prompt: "Enter name for Parent A:" + + - name: "Contributor: {parent_b_name}" + description: "Paid by {parent_b_name}" + color: "cyan" + auto_apply: false + requires_configuration: true + configuration_prompt: "Enter name for Parent B:" + + - name: "Kids: {child_1_name}" + description: "Expense for {child_1_name}" + color: "pink" + auto_apply: false + requires_configuration: true + configuration_prompt: "Enter name for first child:" + + - name: "Kids: {child_2_name}" + description: "Expense for {child_2_name}" + color: "lightgreen" + auto_apply: false + requires_configuration: true + configuration_prompt: "Enter name for second child:" + +dependencies: + requires: [] + conflicts_with: ["single", "shared-joint", "sharehouse"] + # Note: Can be combined with shared-hybrid for divorced parents now living with new partner + +metadata: + created: "2025-11-22" + version: "1.0.0" + author: "Agent Smith" + priority: 2 diff --git a/skills/agent-smith/assets/templates/living/shared-hybrid.yaml b/skills/agent-smith/assets/templates/living/shared-hybrid.yaml new file mode 100644 index 0000000..fa2a16a --- /dev/null +++ b/skills/agent-smith/assets/templates/living/shared-hybrid.yaml @@ -0,0 +1,73 @@ +name: Shared Household - Hybrid Finances +layer: living +description: | + Living with partner/spouse with mix of joint and separate accounts. + Some expenses shared (bills, groceries), some kept separate (personal spending). + +categories: [] + # No special categories needed - use standard expense categories + # Account indicates if shared, labels indicate who paid + +rules: + - id: shared-expense-labeling + pattern: ".*" + # No category override - use existing categorization + # Just apply labels based on account and contributor + confidence: high + split_percentage: 50 + description: "Label shared expenses with contributor info" + labels: ["Shared Expense"] + +tax_tracking: + expense_splitting_enabled: true + default_split_ratio: 0.5 + +alerts: + - type: split_expense_reconciliation + schedule: monthly + message: "Time to reconcile shared expenses with partner" + +labels: + - name: "Shared Expense" + description: "Expense split with partner" + color: "purple" + auto_apply: false + + - name: "Contributor: {partner_a_name}" + description: "Paid by {partner_a_name}" + color: "orange" + auto_apply: false + requires_configuration: true + configuration_prompt: "Enter name for Partner A:" + + - name: "Contributor: {partner_b_name}" + description: "Paid by {partner_b_name}" + color: "cyan" + auto_apply: false + requires_configuration: true + configuration_prompt: "Enter name for Partner B:" + + - name: "Personal: {partner_a_name}" + description: "{partner_a_name} personal spending" + color: "lightorange" + auto_apply: false + requires_configuration: true + configuration_prompt: "Enter name for Partner A:" + + - name: "Personal: {partner_b_name}" + description: "{partner_b_name} personal spending" + color: "lightcyan" + auto_apply: false + requires_configuration: true + configuration_prompt: "Enter name for Partner B:" + +dependencies: + requires: [] + conflicts_with: ["single", "shared-joint", "sharehouse"] + # Note: Can be combined with separated-parents for new relationships after divorce + +metadata: + created: "2025-11-22" + version: "1.0.0" + author: "Agent Smith" + priority: 2 diff --git a/skills/agent-smith/assets/templates/primary/README.md b/skills/agent-smith/assets/templates/primary/README.md new file mode 100644 index 0000000..987e76c --- /dev/null +++ b/skills/agent-smith/assets/templates/primary/README.md @@ -0,0 +1,51 @@ +# Primary Income Templates + +Choose ONE template that matches your main source of income. + +## Available Templates + +- `payg-employee.yaml` - Salary/wage earner +- `sole-trader.yaml` - ABN holder, contractor, quarterly BAS +- `small-business.yaml` - Business owner with employees +- `retiree.yaml` - Superannuation/pension income +- `student.yaml` - Minimal income, government payments, HECS + +## YAML Schema + +```yaml +name: Template Name +layer: primary +description: | + Multi-line description of this template. + +categories: + - name: "Category Name" + parent: null # or "Parent Category Name" + description: "Category purpose" + +rules: + - id: unique-rule-id + pattern: "regex pattern" + category: "Target Category" + confidence: high|medium|low + description: "What this rule does" + +tax_tracking: + bas_enabled: true|false + gst_method: cash|accrual + # ... other tax config + +alerts: + - type: alert_type + schedule: quarterly|monthly + message: "Alert message" + +dependencies: + requires: [] + conflicts_with: ["other-template-id"] + +metadata: + created: "YYYY-MM-DD" + version: "1.0.0" + priority: 1 +``` diff --git a/skills/agent-smith/assets/templates/primary/payg-employee.yaml b/skills/agent-smith/assets/templates/primary/payg-employee.yaml new file mode 100644 index 0000000..d1a1712 --- /dev/null +++ b/skills/agent-smith/assets/templates/primary/payg-employee.yaml @@ -0,0 +1,112 @@ +name: PAYG Employee +layer: primary +description: | + Salary or wage earner with tax withheld by employer. + Suitable for standard employment situations with work-related expense deductions. + +categories: + - name: "Salary/Wages" + parent: null + description: "Employment income from salary or wages" + + - name: "PAYG Tax Withheld" + parent: null + description: "Tax withheld from salary by employer" + + - name: "Work Expenses" + parent: null + description: "Work-related expenses that may be tax deductible" + + - name: "Work Expenses:Uniforms" + parent: "Work Expenses" + description: "Uniforms, protective clothing, laundry" + + - name: "Work Expenses:Tools & Equipment" + parent: "Work Expenses" + description: "Tools and equipment required for work" + + - name: "Work Expenses:Vehicle" + parent: "Work Expenses" + description: "Vehicle expenses for work travel (excl. commuting)" + + - name: "Work Expenses:Self-Education" + parent: "Work Expenses" + description: "Study directly related to current employment" + +labels: + - name: "Tax Deductible" + description: "Work-related expense claimable on tax return" + color: "green" + auto_apply: false + + - name: "Requires Receipt" + description: "Receipt required for ATO substantiation" + color: "yellow" + auto_apply: false + + - name: "Work Expense" + description: "Work-related expense" + color: "purple" + auto_apply: true + +rules: + - id: salary-payment + pattern: "salary|wage.*payment|payroll|fortnightly.*pay" + category: "Salary/Wages" + confidence: high + description: "Detect regular salary/wage payments" + + - id: payg-tax + pattern: "PAYG.*tax|tax.*withheld|ATO.*payment" + category: "PAYG Tax Withheld" + confidence: high + description: "Detect PAYG tax withholding" + + - id: uniform-expense + pattern: "uniform|workwear|protective.*clothing|laundry.*work" + category: "Work Expenses:Uniforms" + confidence: medium + description: "Detect uniform and protective clothing expenses" + labels: ["Tax Deductible", "Work Expense"] + + - id: work-tools + pattern: "tools?|equipment|laptop.*work|computer.*work" + category: "Work Expenses:Tools & Equipment" + confidence: medium + description: "Detect work tool and equipment purchases" + labels: ["Tax Deductible", "Requires Receipt", "Work Expense"] + + - id: work-vehicle + pattern: "fuel.*work|parking.*work|tolls.*work|uber.*work" + category: "Work Expenses:Vehicle" + confidence: low + description: "Detect work-related vehicle expenses (requires verification)" + labels: ["Tax Deductible", "Requires Receipt", "Work Expense"] + +tax_tracking: + bas_enabled: false + payment_summary_reconciliation: true + work_expense_threshold: 300 + logbook_required: false + +alerts: + - type: work_expense_threshold + trigger: annual_total_exceeds + threshold: 300 + category: "Work Expenses" + message: "Work expenses exceed $300 - ensure you have receipts for all claims" + + - type: eofy_reminder + schedule: annual + before_date: "06-15" + message: "EOFY approaching - gather payment summary and work expense receipts" + +dependencies: + requires: [] + conflicts_with: ["sole-trader", "small-business"] + +metadata: + created: "2025-11-22" + version: "1.0.0" + author: "Agent Smith" + priority: 1 diff --git a/skills/agent-smith/assets/templates/primary/sole-trader.yaml b/skills/agent-smith/assets/templates/primary/sole-trader.yaml new file mode 100644 index 0000000..7026171 --- /dev/null +++ b/skills/agent-smith/assets/templates/primary/sole-trader.yaml @@ -0,0 +1,141 @@ +name: Sole Trader / Contractor +layer: primary +description: | + ABN holder running a business as a sole trader or independent contractor. + Includes quarterly BAS obligations and GST tracking. + +categories: + - name: "Business Income" + parent: null + description: "Income from ABN-related business activities" + + - name: "Business Expenses" + parent: null + description: "Tax-deductible business expenses" + + - name: "Business Expenses:Office Supplies" + parent: "Business Expenses" + description: "Stationery, software, subscriptions" + + - name: "Business Expenses:Travel" + parent: "Business Expenses" + description: "Business travel and accommodation" + + - name: "Business Expenses:Home Office" + parent: "Business Expenses" + description: "Home office expenses (percentage allocation)" + + - name: "Business Expenses:Professional Development" + parent: "Business Expenses" + description: "Training, courses, professional memberships" + + - name: "Business Expenses:Marketing" + parent: "Business Expenses" + description: "Advertising, website, business cards" + + - name: "GST Collected" + parent: "Business Income" + description: "GST component of business income" + + - name: "GST Paid" + parent: "Business Expenses" + description: "GST component of business expenses" + +labels: + - name: "Tax Deductible" + description: "Business expense claimable on tax return" + color: "green" + auto_apply: false + + - name: "GST Applicable" + description: "Includes GST component for BAS" + color: "blue" + auto_apply: true + + - name: "Business Use" + description: "Business-related expense or income" + color: "purple" + auto_apply: true + + - name: "Home Office" + description: "Home office percentage claim" + color: "brown" + auto_apply: false + + - name: "Input Tax Credit" + description: "Eligible for GST credit on BAS" + color: "darkblue" + auto_apply: false + +rules: + - id: abn-payment-detection + pattern: "ABN.*payment|invoice.*paid|client.*payment|contractor.*payment" + category: "Business Income" + confidence: high + description: "Detect ABN payments from clients" + labels: ["Business Use", "GST Applicable"] + + - id: home-office-percentage + pattern: "electricity|internet|rent|mortgage.*interest" + category: "Business Expenses:Home Office" + confidence: medium + percentage: 20 + description: "Allocate home expenses to business use" + requires_user_confirmation: true + labels: ["Tax Deductible", "Business Use", "Home Office"] + + - id: office-supplies + pattern: "officeworks|staples|adobe|microsoft.*365|canva|software" + category: "Business Expenses:Office Supplies" + confidence: high + description: "Detect office supply and software purchases" + labels: ["Tax Deductible", "Business Use", "GST Applicable"] + + - id: professional-development + pattern: "course|training|conference|webinar|udemy|coursera|linkedin.*learning" + category: "Business Expenses:Professional Development" + confidence: medium + description: "Detect professional development expenses" + labels: ["Tax Deductible", "Business Use", "GST Applicable"] + + - id: marketing-expense + pattern: "google.*ads|facebook.*ads|instagram.*ads|domain.*registration|web.*hosting|vistaprint" + category: "Business Expenses:Marketing" + confidence: high + description: "Detect marketing and advertising expenses" + labels: ["Tax Deductible", "Business Use", "GST Applicable"] + +tax_tracking: + bas_enabled: true + bas_frequency: quarterly + gst_method: cash + instant_asset_writeoff: true + instant_asset_threshold: 20000 + home_office_percentage: 20 + +alerts: + - type: quarterly_bas_reminder + schedule: quarterly + before_days: 14 + message: "BAS due in 14 days - ensure all invoices and expenses are recorded" + + - type: instant_asset_threshold + trigger: transaction_over_threshold + threshold: 20000 + message: "Purchase over $20k - may require depreciation schedule instead of instant write-off" + + - type: gst_registration_threshold + trigger: annual_income_exceeds + threshold: 75000 + category: "Business Income" + message: "Business income approaching $75k - GST registration may be required" + +dependencies: + requires: [] + conflicts_with: ["payg-employee", "small-business"] + +metadata: + created: "2025-11-22" + version: "1.0.0" + author: "Agent Smith" + priority: 1 diff --git a/skills/agent-smith/pyproject.toml b/skills/agent-smith/pyproject.toml new file mode 100644 index 0000000..1cac2bd --- /dev/null +++ b/skills/agent-smith/pyproject.toml @@ -0,0 +1,110 @@ +[tool.black] +line-length = 100 +target-version = ['py310', 'py311', 'py312'] +include = '\.pyi?$' +extend-exclude = ''' +/( + # directories + \.eggs + | \.git + | \.hg + | \.mypy_cache + | \.tox + | \.venv + | build + | dist +)/ +''' + +[tool.mypy] +python_version = "3.10" +warn_return_any = true +warn_unused_configs = true +disallow_untyped_defs = true +disallow_incomplete_defs = true +check_untyped_defs = true +no_implicit_optional = true +warn_redundant_casts = true +warn_unused_ignores = true +warn_no_return = true +warn_unreachable = true +strict_equality = true + +[[tool.mypy.overrides]] +module = "tests.*" +disallow_untyped_defs = false + +[[tool.mypy.overrides]] +module = "claude_agent_sdk.*" +ignore_missing_imports = true + +[tool.pytest.ini_options] +testpaths = ["tests"] +python_files = ["test_*.py"] +python_classes = ["Test*"] +python_functions = ["test_*"] +addopts = "-v --strict-markers --tb=short" +markers = [ + "unit: Unit tests", + "integration: Integration tests requiring API access", + "slow: Tests that take significant time" +] + +[build-system] +requires = ["setuptools>=45", "wheel", "setuptools_scm[toml]>=6.2"] +build-backend = "setuptools.build_meta" + +[project] +name = "agent-smith" +version = "1.4.1" +description = "Intelligent financial management skill for Claude Code with PocketSmith API integration" +readme = "README.md" +requires-python = ">=3.10" +license = {text = "MIT"} +authors = [ + {name = "Your Name", email = "your.email@example.com"} +] +keywords = ["pocketsmith", "finance", "ai", "claude-code", "financial-management"] +classifiers = [ + "Development Status :: 3 - Alpha", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", +] +dependencies = [ + "requests>=2.31.0", + "python-dateutil>=2.8.2", + "python-dotenv>=1.0.0", + "pyyaml>=6.0.3", + "claude-agent-sdk>=0.1.0", +] + +[project.optional-dependencies] +dev = [ + "pytest>=7.4.0", + "pytest-cov>=4.1.0", + "black>=23.7.0", + "flake8>=6.1.0", + "mypy>=1.5.0", + "ipython>=8.14.0", +] + +[project.urls] +Homepage = "https://github.com/slamb2k/agent-smith" +Repository = "https://github.com/slamb2k/agent-smith" +Issues = "https://github.com/slamb2k/agent-smith/issues" + +[dependency-groups] +dev = [ + "types-pyyaml>=6.0.12.20250915", + "types-python-dateutil>=2.9.0", + "types-requests>=2.32.0", +] + +[tool.setuptools.packages.find] +where = ["."] +include = ["scripts*"] +exclude = ["tests*", "docs*", "build*", "ai_docs*", "data*", "logs*", "reports*", "backups*"] diff --git a/skills/agent-smith/pytest.ini b/skills/agent-smith/pytest.ini new file mode 100644 index 0000000..683f83b --- /dev/null +++ b/skills/agent-smith/pytest.ini @@ -0,0 +1,13 @@ +[pytest] +testpaths = tests +python_files = test_*.py +python_classes = Test* +python_functions = test_* +addopts = + -v + --strict-markers + --tb=short +markers = + unit: Unit tests + integration: Integration tests requiring API access + slow: Tests that take significant time diff --git a/skills/agent-smith/references/LESSONS_LEARNED.md b/skills/agent-smith/references/LESSONS_LEARNED.md new file mode 100644 index 0000000..1a6c928 --- /dev/null +++ b/skills/agent-smith/references/LESSONS_LEARNED.md @@ -0,0 +1,327 @@ +# Lessons Learned from PocketSmith Migration + +**Date:** 2025-11-23 +**Source:** build/ directory reference materials (now archived) + +This document captures key insights from a previous PocketSmith category migration project that informed Agent Smith's design. + +--- + +## Table of Contents + +1. [API Quirks and Workarounds](#api-quirks-and-workarounds) +2. [Category Hierarchy Best Practices](#category-hierarchy-best-practices) +3. [Transaction Categorization Patterns](#transaction-categorization-patterns) +4. [Merchant Name Normalization](#merchant-name-normalization) +5. [User Experience Lessons](#user-experience-lessons) + +--- + +## API Quirks and Workarounds + +### Category Rules API Limitations + +**Issue:** PocketSmith API does not support updating or deleting category rules. +- GET `/categories/{id}/category_rules` works +- POST works (create only) +- PUT/PATCH/DELETE return 404 errors + +**Impact:** Rules created via API cannot be modified programmatically. + +**Agent Smith Solution:** Hybrid rule engine with local rules for complex logic, platform rules for simple keywords only. + +### Transaction Migration 500 Errors + +**Issue:** Bulk transaction updates sometimes fail with 500 Internal Server Errors. + +**Root Cause:** Likely API rate limiting or server-side stability issues. + +**Agent Smith Solution:** +- Implement rate limiting (0.1-0.5s delay between requests) +- Batch processing with progress tracking +- Retry logic with exponential backoff +- Always backup before bulk operations + +### Special Characters in Category Names + +**Issue:** Using "&" in category names causes 422 Unprocessable Entity errors. + +**Workaround:** Replace "&" with "and" in all category names. + +**Example:** +- ❌ "Takeaway & Food Delivery" → 422 error +- ✅ "Takeaway and Food Delivery" → Success + +### Use PUT instead of PATCH + +**Issue:** PATCH for transaction updates is unreliable in PocketSmith API. + +**Solution:** Always use PUT for transaction updates. + +```python +# ✅ Correct +response = requests.put( + f'https://api.pocketsmith.com/v2/transactions/{txn_id}', + headers=headers, + json={'category_id': category_id} +) + +# ❌ Avoid (unreliable) +response = requests.patch(...) +``` + +--- + +## Category Hierarchy Best Practices + +### Parent-Child Structure + +**Recommendation:** Use 2-level hierarchy maximum. +- 12-15 parent categories for broad grouping +- 2-5 children per parent for specific tracking +- Avoid 3+ levels (PocketSmith UI gets cluttered) + +**Example Structure:** +``` +Food & Dining (parent) +├── Groceries +├── Restaurants +├── Takeaway and Food Delivery +└── Coffee Shops +``` + +### Duplicate Category Detection + +**Problem:** Duplicate categories accumulate over time, causing confusion. + +**Solution:** Before creating categories, check for existing matches: +1. Flatten nested category structure +2. Check both exact matches and case-insensitive matches +3. Check for variations (e.g., "Takeaway" vs "Takeaways") + +**Agent Smith Implementation:** Category validation in health check system. + +### Consolidation Strategy + +**Insight:** Merging duplicate categories is risky: +- Requires migrating all associated transactions +- Transaction updates can fail (500 errors) +- Better to prevent duplicates than merge later + +**Agent Smith Approach:** Template-based setup with validation prevents duplicates upfront. + +--- + +## Transaction Categorization Patterns + +### Pattern Matching Complexity + +**Observation:** Transaction categorization evolved through multiple rounds: +- Round 1: Simple keyword matching (60% coverage) +- Round 2: Pattern matching with normalization (80% coverage) +- Round 3: User clarifications + edge cases (90% coverage) +- Round 4: Manual review of exceptions (95% coverage) + +**Lesson:** Need both automated rules AND user override capability. + +**Agent Smith Solution:** Tiered intelligence modes (Conservative/Smart/Aggressive) with confidence scoring. + +### Confidence-Based Auto-Apply + +**Insight:** Not all matches are equal: +- High confidence (95%+): Auto-apply safe (e.g., "WOOLWORTHS" → Groceries) +- Medium confidence (70-94%): Ask user (e.g., "LS DOLLI PL" → Coffee?) +- Low confidence (<70%): Always ask (e.g., "Purchase At Kac" → ???) + +**Agent Smith Implementation:** +```python +if confidence >= 90: # Smart mode threshold + apply_automatically() +elif confidence >= 70: + ask_user_for_approval() +else: + skip_or_manual_review() +``` + +### Dry-Run Mode is Critical + +**Lesson:** Always preview before bulk operations. + +**Pattern from migration:** +```python +class BulkCategorizer: + def __init__(self, dry_run=True): # Default to dry-run! + self.dry_run = dry_run + + def categorize_transactions(self): + if self.dry_run: + # Show what WOULD happen + return preview + else: + # Actually execute + return results +``` + +**Agent Smith Implementation:** All bulk operations support `--mode=dry_run` flag. + +--- + +## Merchant Name Normalization + +### Common Payee Patterns + +**Observations from transaction data:** + +1. **Location codes:** "WOOLWORTHS 1234" → "WOOLWORTHS" +2. **Legal suffixes:** "COLES PTY LTD" → "COLES" +3. **Country codes:** "UBER AU" → "UBER" +4. **Transaction codes:** "PURCHASE NSWxxx123" → "PURCHASE" +5. **Direct debit patterns:** "DIRECT DEBIT 12345" → "DIRECT DEBIT" + +**Agent Smith Patterns:** +```python +LOCATION_CODE_PATTERN = r"\s+\d{4,}$" +SUFFIX_PATTERNS = [ + r"\s+PTY\s+LTD$", + r"\s+LIMITED$", + r"\s+LTD$", + r"\s+AU$", +] +``` + +### Merchant Variation Grouping + +**Problem:** Same merchant appears with multiple names: +- "woolworths" +- "WOOLWORTHS PTY LTD" +- "Woolworths 1234" +- "WOOLWORTHS SUPERMARKETS" + +**Solution:** Learn canonical names from transaction history. + +**Agent Smith Implementation:** `MerchantNormalizer.learn_from_transactions()` in scripts/utils/merchant_normalizer.py:101-130 + +--- + +## User Experience Lessons + +### Backups are Non-Negotiable + +**Critical Lesson:** ALWAYS backup before mutations. + +**Migration practice:** +```python +def categorize_transactions(self): + # Step 1: Always backup first + self.backup_transactions() + + # Step 2: Then execute + self.apply_changes() +``` + +**Agent Smith Policy:** Automatic backups before all mutation operations, tracked in backups/ directory. + +### Progress Visibility Matters + +**Problem:** Long-running operations feel broken without progress indicators. + +**Solution:** Show progress every N iterations: +```python +for i, txn in enumerate(transactions, 1): + # Process transaction + + if i % 100 == 0: + print(f"Progress: {i}/{total} ({i/total*100:.1f}%)") +``` + +**Agent Smith Implementation:** All batch operations show real-time progress. + +### Manual Cleanup is Inevitable + +**Reality Check:** Even after 5+ rounds of automated categorization, ~5% of transactions needed manual review. + +**Reasons:** +- Genuinely ambiguous merchants ("Purchase At Kac" = gambling) +- One-off transactions (unique payees) +- Data quality issues (missing/incorrect payee names) + +**Agent Smith Approach:** Make manual review easy with health check reports showing uncategorized transactions. + +### Weekly Review Habit + +**Post-migration recommendation:** Review recent transactions weekly for first month. + +**Why:** Helps catch: +- Miscategorized transactions +- New merchants needing rules +- Changes in spending patterns + +**Agent Smith Feature:** Smart alerts with weekly budget reviews (Phase 7). + +--- + +## Implementation Timelines + +### Migration Timeline (Reality vs Plan) + +**Planned:** 35 minutes total +**Actual:** 3+ hours over multiple days + +**Breakdown:** +- Category structure migration: 10 minutes (as planned) +- Rule recreation: 20 minutes (10 minutes planned - API limitations doubled time) +- Transaction categorization Round 1: 30 minutes +- Transaction categorization Round 2: 45 minutes +- Transaction categorization Round 3: 60 minutes +- Manual cleanup and verification: 90 minutes + +**Lesson:** Budget 3-5x estimated time for data migration projects. + +**Agent Smith Design:** Incremental onboarding (30-60 minutes initial setup, ongoing refinement). + +--- + +## Key Takeaways for Agent Smith + +### What We Built Better + +1. **Hybrid Rule Engine:** Local + Platform rules overcome API limitations +2. **Confidence Scoring:** Tiered auto-apply based on pattern strength +3. **Merchant Intelligence:** Learned normalization from transaction history +4. **Health Checks:** Proactive detection of category/rule issues +5. **Template System:** Pre-built rule sets prevent common mistakes + +### What We Avoided + +1. **Manual rule migration** - Templates and import/export instead +2. **Duplicate categories** - Validation and health checks +3. **Bulk update failures** - Rate limiting, retry logic, batching +4. **Lost context** - Comprehensive backups with metadata +5. **User fatigue** - Incremental categorization, not all-at-once + +### Core Principles + +✅ **Backup before mutations** +✅ **Dry-run before execute** +✅ **Progress visibility** +✅ **Confidence-based automation** +✅ **User choice over forced automation** +✅ **Learn from transaction history** +✅ **Graceful degradation** (LLM fallback when rules don't match) + +--- + +## Reference + +**Original Materials:** Archived from `build/` directory (removed 2025-11-23) + +**Full backup available at:** `../budget-smith-backup-20251120_093733/` + +**See Also:** +- [Agent Smith Design](2025-11-20-agent-smith-design.md) - Complete system design +- [Unified Rules Guide](../guides/unified-rules-guide.md) - Rule engine documentation +- [Health Check Guide](../guides/health-check-guide.md) - Health scoring system + +--- + +**Last Updated:** 2025-11-23 diff --git a/skills/agent-smith/references/design.md b/skills/agent-smith/references/design.md new file mode 100644 index 0000000..e873ba8 --- /dev/null +++ b/skills/agent-smith/references/design.md @@ -0,0 +1,1324 @@ +# Agent Smith - Complete Design Specification + +**Design Date:** 2025-11-20 +**Status:** Approved +**Version:** 1.0 + +--- + +## Executive Summary + +**Agent Smith** is an intelligent financial management skill for Claude Code that provides comprehensive PocketSmith API integration with advanced AI-powered analysis, rule management, tax intelligence, and scenario planning. + +**Name Origin:** "Agent Smith" combines the PocketSmith platform reference with the Matrix's AI agent - a fitting metaphor for an intelligent assistant managing your financial matrix. + +**Key Value Proposition:** +- Transform PocketSmith from a passive tracking tool into an active financial intelligence system +- Reduce manual financial admin time by 60-80% through intelligent automation +- Provide proactive insights, alerts, and optimization recommendations +- Ensure Australian tax compliance with ATO-aligned intelligence +- Enable sophisticated financial scenario modeling and forecasting + +--- + +## Table of Contents + +1. [Core Architecture](#core-architecture) +2. [Directory Structure](#directory-structure) +3. [Hybrid Rule Engine](#hybrid-rule-engine) +4. [Tax Intelligence Module](#tax-intelligence-module) +5. [Scenario Analysis Engine](#scenario-analysis-engine) +6. [Subagent Orchestration](#subagent-orchestration) +7. [Slash Commands](#slash-commands) +8. [Additional Features](#additional-features) +9. [Health Check System](#health-check-system) +10. [Configuration](#configuration) +11. [Implementation Roadmap](#implementation-roadmap) + +--- + +## Core Architecture + +### Three-Tier System + +**1. API Integration Layer** +- Handles all PocketSmith API communication +- Rate limiting and retry logic +- Response caching (7-day TTL) +- Error handling and fallback strategies +- Automatic backup before mutations + +**2. Intelligence Engine** +- **Hybrid Rule Engine:** Platform-native + enhanced local rules +- **Tax Intelligence:** 3-tier system (Reference, Smart, Full) +- **Scenario Analysis:** Historical, projections, optimization, tax planning +- **AI Categorization:** Tiered intelligence modes (Conservative, Smart, Aggressive) +- **Pattern Learning:** Performance tracking and rule evolution + +**3. Orchestration Layer** +- Smart subagent conductor +- Decision tree for delegation vs. direct handling +- Parallel processing for bulk operations +- Context preservation in main skill +- Result aggregation and synthesis + +### Philosophy + +**Hybrid Approach:** +- Quick single-shot operations for simple tasks +- Deep conversational sessions for complex workflows +- User choice: always provide recommended mode but allow override +- Context preservation through intelligent subagent orchestration + +**AI Intelligence Levels:** +- **Conservative:** User approval required for all actions +- **Smart:** Auto-apply high-confidence (≥90%), ask for medium (70-89%) +- **Aggressive:** Auto-apply ≥80% confidence, ask for 50-79% +- User can override per operation + +--- + +## Directory Structure + +``` +~/.claude/skills/agent-smith/ +├── agent-smith.md # Main skill file (invocation point) +├── .env.sample # API key configuration template +├── .gitignore # Protect sensitive data +├── README.md # Skill documentation +├── INDEX.md # Master directory index +│ +├── ai_docs/ # Documentation for Claude subagents +│ ├── INDEX.md # Document catalog with descriptions +│ ├── pocketsmith-api-documentation.md +│ ├── category-optimization-guide.md +│ ├── ato-tax-guidelines.md +│ ├── rule-engine-architecture.md +│ └── subagent-protocols.md +│ +├── backups/ # Recent backups (30-day retention) +│ ├── INDEX.md # Latest backups with descriptions +│ ├── YYYY-MM-DD_HHMMSS/ # Timestamped backup sets +│ └── archive/ # Older backups (compressed) +│ ├── INDEX.md # Archived backup catalog +│ └── YYYY-MM/ # Monthly archives (.tar.gz) +│ +├── data/ # Working data & persistent state +│ ├── INDEX.md # Current state files & purpose +│ ├── config.json # User preferences, modes, tax level +│ ├── rule_metadata.json # Rule tracking & performance metrics +│ ├── platform_rules.json # PocketSmith native rules created +│ ├── local_rules.json # Enhanced local rule engine +│ ├── session_state.json # Current session context +│ ├── alerts/ +│ │ ├── alert_rules.json +│ │ ├── alert_history.json +│ │ └── alert_templates.json +│ ├── tax/ +│ │ ├── INDEX.md +│ │ ├── ato_category_mappings.json +│ │ ├── deduction_rules.json +│ │ ├── thresholds.json +│ │ ├── cgt_register.json +│ │ └── substantiation_tracking.json +│ ├── scenarios/ +│ │ ├── INDEX.md +│ │ ├── saved_scenarios.json +│ │ ├── scenario_templates.json +│ │ └── scenario_results/ +│ ├── merchants/ +│ │ ├── INDEX.md +│ │ └── merchant_intelligence.json +│ ├── investments/ +│ │ ├── INDEX.md +│ │ ├── portfolio.json +│ │ ├── transactions.json +│ │ └── performance.json +│ ├── goals/ +│ │ ├── INDEX.md +│ │ └── financial_goals.json +│ ├── health/ +│ │ ├── INDEX.md +│ │ ├── health_scores.json +│ │ ├── recommendations.json +│ │ └── health_history/ +│ ├── audit/ +│ │ ├── INDEX.md +│ │ ├── transaction_changes.log +│ │ ├── category_changes.log +│ │ ├── rule_changes.log +│ │ └── api_activity.log +│ └── cache/ # API response cache (7-day TTL) +│ ├── INDEX.md # Cache inventory & freshness +│ └── *.json # Cached responses +│ +├── docs/ # Generated documentation +│ ├── INDEX.md # Recent docs & analyses +│ ├── operations/ # Recent operation logs (30 days) +│ │ ├── INDEX.md # Operation summaries +│ │ └── YYYY-MM-DD_*.md +│ ├── analyses/ # Recent analysis reports (90 days) +│ │ ├── INDEX.md # Analysis catalog +│ │ └── *.md +│ ├── guides/ # User guides (persistent) +│ │ └── INDEX.md +│ └── archive/ # Older docs (compressed) +│ ├── INDEX.md +│ └── YYYY-MM/ +│ +├── logs/ # Execution logs (14 days active) +│ ├── INDEX.md # Recent log summary +│ ├── api_calls.log # API interaction log +│ ├── operations.log # High-level operations +│ ├── errors.log # Error tracking +│ └── archive/ # Compressed historical logs +│ ├── INDEX.md +│ └── YYYY-MM.tar.gz +│ +├── reports/ # Multi-format output (90 days) +│ ├── INDEX.md # Recent reports catalog +│ ├── markdown/ +│ │ ├── INDEX.md +│ │ └── *.md +│ ├── data/ # CSV/JSON exports +│ │ ├── INDEX.md +│ │ └── *.{csv,json} +│ ├── interactive/ # HTML dashboards +│ │ ├── INDEX.md +│ │ └── *.html +│ ├── tax/ # Tax-ready formats (7-year retention) +│ │ ├── INDEX.md +│ │ └── YYYY-*.{pdf,xlsx} +│ └── archive/ # Older reports +│ ├── INDEX.md +│ └── YYYY-MM/ +│ +└── scripts/ # Python utilities & subagent tools + ├── INDEX.md # Script catalog & usage + ├── core/ # Core libraries (reusable) + │ ├── api_client.py # PocketSmith API wrapper + │ ├── rule_engine.py # Hybrid rule system + │ ├── tax_intelligence.py # Tax analysis module + │ ├── scenario_engine.py # Financial scenarios + │ └── archiver.py # Smart archiving engine + ├── operations/ # Specific operation scripts + │ ├── INDEX.md + │ ├── categorize.py + │ ├── analyze.py + │ ├── optimize_categories.py + │ └── generate_reports.py + ├── subagents/ # Subagent definitions + │ ├── categorization-agent.md + │ ├── analysis-agent.md + │ ├── reporting-agent.md + │ ├── tax-agent.md + │ ├── optimization-agent.md + │ └── scenario-agent.md + └── utils/ # Helper utilities + ├── INDEX.md + ├── backup.py + ├── validation.py + ├── formatters.py + └── index_updater.py # Auto-update INDEX.md files +``` + +### Smart Archiving Strategy + +**Retention Policies:** +- **Cache:** 7 days, auto-purge +- **Logs:** 14 days active, then compress to monthly archives +- **Backups:** 30 days recent, then monthly compressed archives +- **Operations docs:** 30 days, then archive +- **Analyses/Reports:** 90 days, then archive +- **Tax reports:** 7 years (ATO requirement) + +**Archiving Process:** +- Automatic after operations +- Compresses old files into monthly `.tar.gz` archives +- Updates INDEX.md in archive directories +- Manual archive/restore commands available + +**INDEX.md Auto-Update:** +- Every file creation/modification triggers index update +- Contains: filename, creation date, size, description, tags +- Enables LLM to quickly scan without reading all files +- Sorted by relevance (newest first, or by type) + +--- + +## Hybrid Rule Engine + +### Architecture + +**Two-Tier System:** +1. **Platform Rules** - PocketSmith native (via API) +2. **Local Rules** - Enhanced engine with advanced features + +**Platform Rules (PocketSmith Native):** +- Created via API for simple keyword patterns +- **Advantages:** Auto-apply to future transactions server-side +- **Limitations:** Keyword-only matching, no modification/deletion via API +- **Tracking:** Metadata stored in `data/platform_rules.json` + +**Local Rules (Enhanced Engine):** +- Stored in `data/local_rules.json` +- **Capabilities:** + - Regex pattern matching + - Multi-condition logic (amount ranges, date patterns, account filters) + - Confidence scoring (0-100%) + - Priority/precedence management + - Rule chaining (conditional rules) + - Negative patterns (exclusions) + - Statistical learning (accuracy tracking) + +### Rule Schema (Local) + +```json +{ + "rule_id": "uuid", + "name": "Woolworths Groceries", + "type": "local|platform|session", + "pattern": { + "payee_regex": "WOOLWORTHS.*", + "amount_range": {"min": null, "max": null}, + "account_ids": [], + "date_range": null, + "excludes": ["WOOLWORTHS PETROL"] + }, + "action": { + "category_id": 12345, + "confidence": 95, + "requires_approval": false + }, + "metadata": { + "created": "2025-11-20", + "created_by": "user|ai", + "last_modified": "2025-11-20", + "priority": 100, + "tags": ["groceries", "auto-categorize"] + }, + "performance": { + "matches": 150, + "applied": 148, + "user_overrides": 2, + "accuracy": 98.67, + "last_used": "2025-11-19" + } +} +``` + +### Intelligence Modes + +**1. Conservative Mode:** +- All rules require user approval before applying +- Best for: Initial setup, learning phase, high-stakes categorization + +**2. Smart Mode (Default):** +- Auto-apply rules with confidence ≥ 90% +- Ask for approval: 70-89% confidence +- Skip: < 70% confidence +- Best for: Most users, balanced automation + +**3. Aggressive Mode:** +- Auto-apply confidence ≥ 80% +- Ask for approval: 50-79% confidence +- Skip: < 50% confidence +- Best for: Experienced users, trusted rule sets + +### Session Rules + +- Temporary rules for one-off bulk operations +- Stored in `session_state.json`, not persisted by default +- User prompted: "Keep this rule for future use?" +- Useful for: Bulk categorization, experimentation + +### Rule Lifecycle + +1. **Creation:** AI suggests or user defines +2. **Validation:** Test against historical transactions (dry-run) +3. **Application:** Apply with chosen intelligence mode +4. **Tracking:** Record performance metrics +5. **Evolution:** Suggest refinements based on override patterns +6. **Archival:** Move low-performing rules to review queue + +### Platform Sync Strategy + +**Decision Logic:** +```python +if rule.is_simple_keyword() and not rule.has_exclusions(): + # Create via PocketSmith API + create_platform_rule(rule) + track_in_platform_rules_json(rule) +else: + # Keep local-only + store_in_local_rules_json(rule) +``` + +**Migration Tool:** +- Convert proven local rules to platform rules when possible +- Audit which rules are platform vs. local +- Bulk migration capability + +--- + +## Tax Intelligence Module + +### Three-Tier System + +**Configuration:** +- Environment variable: `TAX_INTELLIGENCE_LEVEL=reference|smart|full` +- Runtime override: `--tax-level=full` +- Interactive prompt when ambiguous + +--- + +### Level 1: Reference & Reporting + +**Capabilities:** +- Generate tax-ready expense summaries by category +- Map PocketSmith categories to ATO expense categories +- Basic GST tracking (GST paid on business purchases) +- Flag potential deductible expenses based on category +- Link to relevant ATO resources and guides +- Simple reports: "You spent $X on deductible categories" + +**Output:** +- Factual reporting with resource links +- No advice given +- CSV exports mapped to ATO tax return categories + +**Use Case:** Users who have accountants, just need organized data + +--- + +### Level 2: Smart Categorization Assistant + +**Everything from Level 1, PLUS:** + +**Advanced Detection:** +- Flag transactions likely deductible based on payee patterns +- Suggest expense splitting (mixed personal/business) +- Identify missing documentation requirements +- Track capital gains/losses events (asset purchases/sales) +- Calculate vehicle logbook percentages from fuel/service patterns +- Monitor common deduction thresholds ($300 receipt rule, etc.) +- Detect home office expense patterns +- Flag estimated tax obligations based on income patterns + +**Intelligent Suggestions:** +- "This $850 laptop purchase may be instantly deductible" +- "Detected 15 Uber rides to/from work - likely NOT deductible" +- "Mobile phone bill: consider 50/50 split for business deduction" + +**Capital Gains Tracking:** +- Detect asset purchase/sale pairs +- Calculate holding periods +- Flag CGT discount eligibility (> 12 months) +- Track cost base adjustments + +**Output:** Actionable insights with "consult your accountant" disclaimers + +**Use Case:** Most users, proactive tax optimization + +--- + +### Level 3: Full Compliance Suite + +**Everything from Levels 1 & 2, PLUS:** + +**Comprehensive Tax Management:** + +**Deduction Optimization:** +- Track deductions against ATO category limits and guidelines +- Suggest timing optimizations (prepay expenses before EOFY) +- Identify bundling opportunities +- Compare deduction methods (actual vs. standard rates) +- Monitor substantiation requirements by category + +**BAS & GST Management:** +- BAS-ready reports (quarterly/monthly) +- GST paid vs. collected tracking +- Input tax credit calculations +- PAYG installment tracking +- BAS reconciliation reports + +**Threshold Monitoring:** +- $300 substantiation threshold +- $75 taxi/Uber receipt requirements +- FBT thresholds +- Small business entity thresholds ($10M turnover) +- Instant asset write-off limits (currently $20,000) + +**Investment & CGT Intelligence:** +- Comprehensive CGT register +- Cost base tracking (purchase price + incidental costs) +- Dividend tracking (franked/unfranked) +- Foreign income detection +- Cryptocurrency transaction tracking +- Wash sale detection + +**Scenario Planning:** +- "Sell investment now vs. after 12 months - tax impact?" +- "Prepay insurance before EOFY - savings?" +- "You're approaching threshold X - implications" + +**Compliance Checks:** +- Cross-reference expenses against ATO audit triggers +- Identify unusual patterns +- Verify substantiation completeness +- Generate audit-ready documentation + +**Reports Generated:** +- Tax return schedule summaries (D1-D15) +- BAS worksheets +- CGT schedule +- Depreciation schedules +- Home office calculation worksheets +- Vehicle logbook summaries + +**Disclaimers:** +- All Level 3 outputs include: "This analysis is for informational purposes. Consult a registered tax agent for advice." +- Flags complex situations requiring professional review + +**Use Case:** Power users, small business owners, serious tax optimization + +--- + +### ATO Documentation Caching + +**Smart Documentation Strategy:** + +**Local Cache Structure:** +``` +ai_docs/tax/ +├── INDEX.md +├── cache_metadata.json +├── ato_guidelines/ +│ ├── motor_vehicle_expenses_2025.md +│ ├── home_office_deductions_2025.md +│ ├── capital_gains_tax_2025.md +│ └── instant_asset_writeoff_2025.md +├── legislation/ +│ ├── income_tax_rates_2024-25.json +│ ├── gst_rules.md +│ └── substantiation_requirements.md +└── archived/ + └── YYYY/ +``` + +**Cache Metadata:** +```json +{ + "document_id": "motor_vehicle_expenses_2025", + "source_url": "https://www.ato.gov.au/...", + "cached_date": "2025-11-01", + "last_verified": "2025-11-20", + "content_hash": "abc123...", + "refresh_policy": "monthly", + "expiry_date": "2025-12-01", + "version": "v2.1", + "change_log": [ + { + "date": "2025-11-15", + "change": "Updated instant asset write-off threshold to $20,000" + } + ] +} +``` + +**Smart Refresh Strategy:** + +1. **Automatic Checks:** + - Monthly refresh of all cached docs + - Pre-EOFY force refresh (May-June) + - Post-Budget alert (October) + +2. **On-Demand Verification:** + - Before generating tax reports: check for doc updates + - Compare cached vs. online versions + - Highlight changes to user + +3. **Integration with Tax Levels:** + - Level 1: Use cached docs, verify monthly + - Level 2: Verify before recommendations + - Level 3: Always verify freshness before compliance operations + +**Commands:** +- `refresh-tax-cache` - Force refresh +- `verify-tax-cache` - Check for updates +- `diff-tax-changes` - Show changes since last cache + +--- + +## Scenario Analysis Engine + +### Four Scenario Types + +**1. Historical Analysis** + +**What-If Replays:** +- "What if I had cut dining out by 30% in 2024?" +- "Show impact of eliminating subscription X" +- "What if I had sold investment Y in June vs. December?" + +**Trend Analysis:** +- Compare spending across periods (YoY, QoQ, MoM) +- Identify trending categories +- Seasonal pattern detection +- Anomaly detection + +**Comparative Scenarios:** +- Actual vs. Budget variance +- Category spending comparisons +- Account-level analysis + +--- + +**2. Future Projections** + +**Spending Forecasts:** +- Project based on historical patterns +- Seasonal adjustments +- Account for known upcoming changes +- Confidence intervals (optimistic/pessimistic/realistic) + +**Affordability Analysis:** +- "Can I afford a $500/month car payment?" +- "Impact of $15k annual expense on cash flow?" +- Cash flow projections (monthly surplus/deficit) + +**Goal Modeling:** +- "Save $20k by Dec 2026 - required monthly savings?" +- "Retire at 60 - monthly savings needed?" +- Investment growth projections + +**Algorithm:** +1. Analyze historical patterns (12-24 months) +2. Detect trends (increasing/decreasing categories) +3. Apply seasonal adjustments +4. Factor in inflation (configurable %) +5. Account for known future changes +6. Generate 3 scenarios: conservative/realistic/optimistic +7. Project forward 3/6/12/24 months + +--- + +**3. Optimization Engine** + +**AI-Suggested Opportunities:** + +**Subscription Analysis:** +- Detect recurring payments +- Identify unused/underutilized subscriptions +- Calculate consolidation savings +- Suggest alternatives + +**Category Trend Alerts:** +- Flag categories trending up >10% +- Identify unusual spending patterns +- Compare to peer benchmarks (optional) +- Suggest budget adjustments + +**Expense Rationalization:** +- Duplicate service detection +- Identify optimization opportunities +- Bundle opportunities + +**Tax Optimization:** +- Prepayment opportunities before EOFY +- Timing of asset sales (CGT optimization) +- Salary sacrifice recommendations +- Deduction maximization strategies + +--- + +**4. Tax Scenario Planning** + +**Pre-Purchase Analysis:** +- "Buy $25k equipment now vs. next FY - tax impact?" +- "Instant asset write-off vs. depreciation?" +- "Salary sacrifice $10k to super - net benefit?" + +**Income Timing:** +- "Defer $20k invoice to next FY - tax savings?" +- "Bonus timing optimization" +- "Capital gain timing (< or > 12 months)" + +**Deduction Optimization:** +- "Prepay 12 months insurance before EOFY - deductible?" +- "Extra super contribution - tax benefit?" +- "Bring forward expenses - impact?" + +**CGT Scenarios:** +- "Sell now (8 months held) vs. wait 4 months (CGT discount)" +- "Offset gains with losses - which assets?" +- "Distribute gains across financial years" + +--- + +## Subagent Orchestration + +### Orchestration Decision Tree + +```python +def should_delegate(operation): + """Decide if operation should use subagent""" + + # Always delegate + if operation.type in ['bulk_processing', 'deep_analysis', 'multi_period']: + return True + + # Check complexity + if operation.transaction_count > 100: + return True + + if operation.estimated_tokens > 5000: + return True + + # Check parallelization opportunity + if operation.can_parallelize: + return True + + # Simple queries stay in main context + return False +``` + +### Subagent Types + +**Specialized Workers:** +- `categorization-agent.md` - Transaction categorization +- `analysis-agent.md` - Financial analysis +- `reporting-agent.md` - Report generation +- `tax-agent.md` - Tax intelligence operations +- `optimization-agent.md` - Category/rule optimization +- `scenario-agent.md` - Scenario modeling + +### Processing Patterns + +**1. Parallel Processing:** +- Multi-period analysis (12 months → 12 parallel agents) +- Category-wise deep dives (top 5 categories → 5 agents) +- Bulk categorization (500 transactions → 5 batches → 5 agents) + +**2. Sequential Delegation:** +- Complex workflows requiring user approval between steps +- Each step's output feeds next step +- Main skill orchestrates and presents results + +**3. Smart Context Management:** + +**Main Skill Handles:** +- User preferences and configuration +- Session state +- High-level decision making +- User interaction and approvals +- Result aggregation + +**Subagents Handle:** +- Large data processing +- API-intensive operations +- Detailed analysis +- Report generation +- Rule application +- Complex calculations + +### Communication Protocol + +**Delegation Message Format:** +```markdown +You are a specialized {operation_type} agent for Agent Smith. + +CONTEXT: +- User: {user_id} +- Operation: {operation_description} +- Intelligence Mode: {conservative|smart|aggressive} +- Tax Level: {reference|smart|full} + +DATA: +{relevant_data_subset} + +REFERENCES: +- API Documentation: ai_docs/pocketsmith-api-documentation.md +- {operation_specific_docs} + +TASK: +{specific_instructions} + +OUTPUT FORMAT: +{expected_output_schema} + +CONSTRAINTS: +- Dry-run mode: {true|false} +- Maximum API calls: {limit} +- Backup before mutations: {true|false} +``` + +**Response Format:** +```json +{ + "status": "success|error|partial", + "operation": "categorization", + "summary": "Categorized 95/100 transactions", + "results": { + "categorized": 95, + "skipped": 5, + "rules_applied": 12, + "new_rules_suggested": 3 + }, + "details": {}, + "errors": [], + "recommendations": [], + "next_steps": [] +} +``` + +--- + +## Slash Commands + +### Command Structure + +``` +.claude/commands/ +├── agent-smith.md # Installation and onboarding +├── agent-smith-categorize.md # Transaction categorization +├── agent-smith-analyze.md # Financial analysis +├── agent-smith-report.md # Report generation +├── agent-smith-scenario.md # Scenario modeling +├── agent-smith-optimize.md # Optimization operations +├── agent-smith-tax.md # Tax intelligence +└── agent-smith-health.md # Health check +``` + +### Command Definitions + +**1. `/agent-smith` - Main Conversational Skill** +```markdown +Start a conversational Agent Smith session for complex multi-step operations. +Use for workflows involving multiple operations or guided assistance. +``` + +**2. `/agent-smith-categorize [--mode] [--period]`** +```markdown +Categorize uncategorized transactions with AI assistance. + +Arguments: + --mode=conservative|smart|aggressive Intelligence level (default: smart) + --period=YYYY-MM Target specific month/year + --account=ID Limit to specific account + --dry-run Preview without applying + +Examples: + /agent-smith-categorize + /agent-smith-categorize --mode=aggressive --period=2025-11 +``` + +**3. `/agent-smith-analyze [type] [--period]`** +```markdown +Run financial analysis on PocketSmith data. + +Arguments: + type: spending|trends|category|tax|insights + --period=YYYY-MM or YYYY + --category=ID + --compare=YYYY-MM + --tax-level=reference|smart|full + +Examples: + /agent-smith-analyze spending --period=2025 + /agent-smith-analyze trends --compare=2024 +``` + +**4. `/agent-smith-scenario [type] [description]`** +```markdown +Model financial scenarios: what-if, projections, optimization, tax planning. + +Arguments: + type: historical|projection|optimization|tax + description: Natural language scenario description + +Examples: + /agent-smith-scenario historical "What if I cut dining by 25% last year?" + /agent-smith-scenario projection "Can I afford $600/month car payment?" + /agent-smith-scenario tax "Buy $25k equipment before or after EOFY?" +``` + +**5. `/agent-smith-report [format] [--period]`** +```markdown +Generate comprehensive reports in various formats. + +Arguments: + format: summary|detailed|tax|custom + --period=YYYY-MM or YYYY + --output=markdown|csv|json|html|excel|all + --tax-level=reference|smart|full + +Examples: + /agent-smith-report summary --period=2025-Q4 + /agent-smith-report tax --period=2024-25 --tax-level=full +``` + +**6. `/agent-smith-optimize [target]`** +```markdown +AI-assisted optimization for categories, rules, or spending. + +Arguments: + target: categories|rules|spending|subscriptions + +Examples: + /agent-smith-optimize categories + /agent-smith-optimize rules +``` + +**7. `/agent-smith-tax [operation] [--period]`** +```markdown +Tax-focused analysis, deduction tracking, compliance reporting. + +Arguments: + operation: deductions|cgt|bas|eofy|scenario + --period=YYYY-YY + --level=reference|smart|full + +Examples: + /agent-smith-tax deductions --period=2024-25 + /agent-smith-tax eofy +``` + +**8. `/agent-smith-health [--full]`** +```markdown +Evaluate PocketSmith setup and get optimization recommendations. + +Arguments: + --full Complete deep analysis + --quick Fast essential checks + --category=area Specific area: categories|rules|tax|data + +Examples: + /agent-smith-health + /agent-smith-health --full +``` + +--- + +## Additional Features + +### 1. Smart Alerts & Notifications + +**Alert Types:** +- Budget alerts (overspending, trending) +- Tax alerts (thresholds, EOFY deadlines, CGT timing) +- Pattern alerts (new recurring charges, duplicates, unusual transactions) +- Optimization alerts (unused subscriptions, fee increases) + +**Scheduling:** +- Weekly spending summary +- Monthly budget review +- Quarterly trend analysis +- EOFY tax prep reminder (May) +- Post-budget cache refresh (October) + +### 2. Merchant Intelligence + +**Automated Payee Enrichment:** +- Detect payee variations automatically +- Group similar transactions +- Learn from user corrections +- Suggest canonical names + +**Merchant Insights:** +- Spending patterns by merchant +- Price trend tracking +- Optimization suggestions + +### 3. Receipt & Document Management + +**Integration with PocketSmith Attachments:** +- Flag transactions requiring receipts (>$300) +- Track missing documentation +- Generate substantiation reports +- OCR receipt data +- Auto-link receipts to transactions + +### 4. Multi-User & Shared Expense Tracking + +**Household Finance:** +- Track shared expenses +- Calculate settlement amounts +- Split transactions by custom ratios +- Generate "who owes whom" reports + +### 5. Investment Tracking + +**Portfolio Integration:** +- Link transactions to investment events +- Track cost basis +- Calculate unrealized gains/losses +- CGT optimization +- Dividend tracking +- Performance vs. benchmarks + +### 6. Cash Flow Forecasting + +**Intelligent Liquidity Management:** +- Predict future account balances +- Identify potential shortfalls +- Optimize payment timing +- Track recurring payments +- Model major purchase impact + +### 7. Goal Tracking + +**Financial Goals:** +- Emergency fund +- House deposit +- Debt payoff +- Investment targets +- Retirement savings + +**Progress Tracking:** +- Automatic updates +- On-track vs. behind alerts +- Required contribution adjustments +- Milestone celebrations + +### 8. Comparative Benchmarking + +**Anonymous Peer Comparison (Opt-In):** +- Compare spending to similar households +- Privacy-first (aggregated, anonymized) +- Configurable peer criteria + +### 9. Audit Trail + +**Complete Activity Log:** +- Every transaction modification +- Category structure changes +- Rule creation/updates +- Bulk operations +- Report generation + +**Benefits:** +- "Undo" capability +- Compliance tracking +- Troubleshooting +- Accountability + +### 10. Smart Backup & Recovery + +**Automated Protection:** +- Before every bulk operation +- Daily automatic backups (if changes made) +- Pre-migration snapshots +- Configurable retention + +**Recovery Tools:** +- List backups +- Preview backup contents +- Selective restore +- Full restore +- Diff between backup and current + +--- + +## Health Check System + +### Six Health Scores + +**1. Data Quality (0-100)** +- Categorization coverage +- Data completeness +- Data consistency + +**2. Category Structure (0-100)** +- Hierarchy optimization +- Category usage +- Tax alignment + +**3. Rule Engine (0-100)** +- Rule coverage +- Rule quality +- Rule completeness + +**4. Tax Readiness (0-100)** +- ATO compliance +- Tax category mapping +- EOFY preparation + +**5. Automation & Efficiency (0-100)** +- Agent Smith utilization +- PocketSmith feature usage +- Data entry efficiency + +**6. Overall Health** +- Composite of all scores +- Top 3 priorities identified +- Impact projections + +### Health Check Output + +``` +🏥 AGENT SMITH HEALTH CHECK - OVERALL +════════════════════════════════════════ + +Overall Score: 59/100 (Fair) + +Individual Scores: +├─ Data Quality: 72/100 ✅ Good +├─ Category Structure: 58/100 ⚠️ Needs Work +├─ Rule Engine: 45/100 ⚠️ Needs Improvement +├─ Tax Readiness: 68/100 ⚠️ Fair +└─ Automation: 52/100 ⚠️ Moderate + +🎯 TOP 3 PRIORITIES: +1. CREATE CATEGORY HIERARCHY (Highest Impact) +2. EXPAND RULE COVERAGE (Quick Win) +3. TAX COMPLIANCE FIXES (Risk Reduction) + +After completing: Projected score 96/100 +``` + +### Automated Health Monitoring + +**Periodic Checks:** +- Weekly quick health check +- Monthly full health analysis +- Pre-EOFY comprehensive check +- Post-major-operation validation + +**Proactive Alerts:** +- Health score changes +- New recommendations +- Declining tax readiness + +--- + +## Configuration + +### .env.sample + +```bash +# PocketSmith API Authentication +POCKETSMITH_API_KEY= + +# Agent Smith Configuration +TAX_INTELLIGENCE_LEVEL=smart # reference|smart|full +DEFAULT_INTELLIGENCE_MODE=smart # conservative|smart|aggressive +AUTO_BACKUP=true +AUTO_ARCHIVE=true +ALERT_NOTIFICATIONS=true + +# Tax Configuration (Australia) +TAX_JURISDICTION=AU +FINANCIAL_YEAR_END=06-30 # June 30 +GST_REGISTERED=false + +# Reporting Preferences +DEFAULT_REPORT_FORMAT=all # markdown|csv|json|html|excel|all +CURRENCY=AUD + +# Advanced +API_RATE_LIMIT_DELAY=100 # ms between calls +CACHE_TTL_DAYS=7 +SUBAGENT_MAX_PARALLEL=5 +``` + +### User Preferences (data/config.json) + +```json +{ + "user_id": 217031, + "tax_level": "smart", + "intelligence_mode": "smart", + "alerts_enabled": true, + "alert_preferences": { + "budget": true, + "tax": true, + "patterns": true, + "optimization": true, + "frequency": "weekly" + }, + "backup_before_mutations": true, + "auto_archive": true, + "default_report_formats": ["markdown", "csv", "html"], + "household": { + "enabled": false, + "members": [], + "split_method": "proportional" + }, + "benchmarking": { + "enabled": false, + "criteria": {} + } +} +``` + +--- + +## Implementation Roadmap + +### Phase 1: Foundation (Weeks 1-2) + +**Core Infrastructure:** +- ✅ Directory structure creation +- ✅ .env.sample and configuration files +- ✅ INDEX.md templates for all directories +- ✅ Python core libraries: + - api_client.py (PocketSmith API wrapper) + - archiver.py (smart archiving engine) + - index_updater.py (INDEX.md automation) + - backup.py (backup/restore utilities) + - validation.py (data validation) + +**Basic Functionality:** +- ✅ API authentication and basic queries +- ✅ Backup/restore system +- ✅ Archiving automation +- ✅ Logging infrastructure + +### Phase 2: Rule Engine (Weeks 3-4) + +**Hybrid Rule System:** +- ✅ Local rule engine implementation +- ✅ Platform rule tracking +- ✅ Rule performance metrics +- ✅ Intelligence mode implementation +- ✅ Session rules +- ✅ Rule validation and testing + +**Categorization:** +- ✅ Basic categorization workflow +- ✅ Batch categorization +- ✅ Rule suggestion engine +- ✅ Merchant normalization + +### Phase 3: Analysis & Reporting (Weeks 5-6) + +**Analysis Engine:** +- ✅ Spending analysis +- ✅ Trend detection +- ✅ Category analysis +- ✅ Pattern recognition + +**Multi-Format Reporting:** +- ✅ Markdown reports +- ✅ CSV/JSON exports +- ✅ HTML dashboards (interactive) +- ✅ Excel generation + +### Phase 4: Tax Intelligence (Weeks 7-8) + +**3-Tier Tax System:** +- ✅ Level 1: Reference & Reporting +- ✅ Level 2: Smart Categorization Assistant +- ✅ Level 3: Full Compliance Suite + +**ATO Integration:** +- ✅ Documentation caching +- ✅ Category mappings +- ✅ Deduction rules +- ✅ CGT register +- ✅ BAS preparation + +### Phase 5: Scenario Analysis (Weeks 9-10) + +**Scenario Engine:** +- ✅ Historical analysis +- ✅ Future projections +- ✅ Optimization engine +- ✅ Tax scenario planning + +**Advanced Analytics:** +- ✅ Cash flow forecasting +- ✅ Goal tracking +- ✅ Investment tracking + +### Phase 6: Orchestration & UX (Weeks 11-12) + +**Subagent System:** +- ✅ Subagent definitions +- ✅ Orchestration logic +- ✅ Parallel processing +- ✅ Result aggregation + +**Slash Commands:** +- ✅ All 8 slash commands +- ✅ Argument parsing +- ✅ Natural language integration +- ✅ Interactive workflows + +### Phase 7: Advanced Features (Weeks 13-14) + +**Additional Capabilities:** +- ✅ Smart alerts & notifications +- ✅ Merchant intelligence +- ✅ Document management +- ✅ Multi-user support +- ✅ Comparative benchmarking +- ✅ Audit trail + +### Phase 8: Health Check & Polish (Weeks 15-16) + +**Health Check System:** +- ✅ 6 health scores +- ✅ Recommendation engine +- ✅ Automated monitoring +- ✅ Guided setup workflow + +**Polish & Testing:** +- ✅ End-to-end testing +- ✅ Documentation completion +- ✅ Performance optimization +- ✅ User guides + +--- + +## Success Metrics + +**Efficiency Gains:** +- Reduce manual categorization time by 60-80% +- Auto-categorization rate: 70%+ (from ~5%) +- Financial admin time: 45 min/week → 10 min/week + +**Quality Improvements:** +- Health score: 95/100 average +- Categorization accuracy: 95%+ +- Tax compliance score: 90%+ + +**User Satisfaction:** +- All essential tax documents generated automatically +- Proactive optimization suggestions implemented +- Financial insights delivered weekly +- Zero missed tax deadlines/thresholds + +--- + +## Future Enhancements + +**v2.0 Potential Features:** +- Machine learning for transaction categorization +- Integration with other financial platforms +- Mobile app companion +- Real-time alerts via notifications +- Advanced visualizations and dashboards +- Multi-currency support enhancements +- Business expense separation automation +- Integration with accounting software (Xero, MYOB) +- Predictive budget adjustments +- AI financial advisor capabilities + +--- + +**End of Design Document** + +**Status:** Ready for implementation +**Next Steps:** +1. Review and approve design +2. Set up git worktree for isolated development +3. Create detailed implementation plan +4. Begin Phase 1: Foundation + +--- + +**Document Version:** 1.0 +**Last Updated:** 2025-11-20 +**Approved By:** [Pending] diff --git a/skills/agent-smith/references/health-check-guide.md b/skills/agent-smith/references/health-check-guide.md new file mode 100644 index 0000000..79b423e --- /dev/null +++ b/skills/agent-smith/references/health-check-guide.md @@ -0,0 +1,408 @@ +# Agent Smith Health Check Guide + +## Introduction + +The Agent Smith health check system provides a comprehensive assessment of your PocketSmith financial setup. It analyzes six key dimensions of your financial data management, identifies issues, and provides prioritized recommendations for improvement. + +**Why use health checks?** + +- **Proactive Issue Detection**: Catch problems before they affect your financial tracking +- **Continuous Improvement**: Track your setup quality over time with actionable metrics +- **Tax Readiness**: Ensure your categorization and data quality meet compliance requirements +- **Optimization Guidance**: Get specific recommendations to improve automation and accuracy + +--- + +## The Six Health Dimensions + +Agent Smith evaluates your PocketSmith setup across six weighted dimensions: + +### 1. Data Quality (25% weight) + +The foundation of accurate financial tracking. This dimension measures: + +| Metric | Description | Target | +|--------|-------------|--------| +| Uncategorized Rate | Percentage of transactions without categories | < 5% | +| Duplicate Detection | Potential duplicate transactions identified | 0 | +| Data Gaps | Missing transaction periods | None | +| Description Quality | Transactions with meaningful descriptions | > 90% | + +**Why it matters**: Poor data quality cascades into inaccurate reports, missed deductions, and unreliable budgets. + +### 2. Category Structure (20% weight) + +How well your category hierarchy is organized: + +| Metric | Description | Target | +|--------|-------------|--------| +| Category Depth | Optimal nesting (2-4 levels) | Balanced | +| Unused Categories | Categories with no transactions | < 10% | +| Unclassified Amounts | Money in catch-all categories | < 3% | +| Category Distribution | Even spread across categories | No outliers | + +**Why it matters**: A well-structured category system makes analysis meaningful and tax preparation straightforward. + +### 3. Rule Engine (15% weight) + +Effectiveness of your categorization rules: + +| Metric | Description | Target | +|--------|-------------|--------| +| Rule Coverage | Transactions matched by rules | > 80% | +| Rule Efficiency | Rules that actively match transactions | > 70% | +| Conflict Detection | Rules with overlapping patterns | 0 | +| Pattern Quality | Specificity of rule patterns | High | + +**Why it matters**: Strong rules reduce manual categorization work and ensure consistency. + +### 4. Tax Readiness (15% weight) + +Preparedness for tax reporting and compliance: + +| Metric | Description | Target | +|--------|-------------|--------| +| Tax Category Coverage | Deductible expenses properly categorized | > 95% | +| Business/Personal Split | Clear separation where required | Complete | +| Receipt Documentation | Transactions over $82.50 with receipts | 100% | +| GST Tracking | GST amounts recorded where applicable | Complete | + +**Why it matters**: Poor tax categorization means missed deductions and compliance risks. + +### 5. Automation (10% weight) + +Level of automated financial management: + +| Metric | Description | Target | +|--------|-------------|--------| +| Savings Automation | Automated transfers to savings | Active | +| Bill Scheduling | Recurring bills tracked | > 90% | +| Account Sync Freshness | Time since last sync | < 24 hours | +| Auto-categorization Rate | Transactions auto-categorized | > 85% | + +**Why it matters**: Automation reduces manual effort and prevents missed payments. + +### 6. Budget Alignment (15% weight) + +How well actual spending matches budgets: + +| Metric | Description | Target | +|--------|-------------|--------| +| Budget Variance | Difference from planned amounts | < 10% | +| Overspending Categories | Categories over budget | < 20% | +| Budget Coverage | Expenses covered by budgets | > 80% | +| Forecast Accuracy | Predicted vs actual spending | > 85% | + +**Why it matters**: Budget alignment indicates financial discipline and planning accuracy. + +--- + +## How to Run Health Checks + +### Using the Slash Command + +Run a health check using the Agent Smith command: + +``` +/agent-smith-health +``` + +### Command Options + +| Option | Description | Example | +|--------|-------------|---------| +| `full` | Complete analysis of all dimensions | `/agent-smith-health full` | +| `quick` | Fast check of critical metrics only | `/agent-smith-health quick` | +| `dimension` | Check specific dimension | `/agent-smith-health data-quality` | +| `compare` | Compare to previous check | `/agent-smith-health compare` | + +### What Happens During a Health Check + +1. **Data Collection**: Agent Smith queries your PocketSmith account +2. **Analysis**: Each dimension is evaluated against benchmarks +3. **Scoring**: Individual and overall scores are calculated +4. **Recommendations**: Prioritized action items are generated +5. **Report**: Results are displayed and optionally saved + +--- + +## Interpreting Scores + +### Score Ranges + +| Range | Rating | Meaning | +|-------|--------|---------| +| 90-100 | Excellent | Your setup is optimized and well-maintained | +| 70-89 | Good | Solid foundation with minor improvements possible | +| 50-69 | Needs Attention | Several areas require improvement | +| 0-49 | Critical | Significant issues affecting financial tracking | + +### Status Indicators + +Throughout health check results, you will see these status indicators: + +| Indicator | Meaning | +|-----------|---------| +| `[PASS]` | Metric meets or exceeds target | +| `[WARN]` | Metric is below target but not critical | +| `[FAIL]` | Metric requires immediate attention | + +### Dimension Breakdown + +Each dimension shows: +- **Score**: 0-100 for that dimension +- **Weight**: How much it contributes to overall score +- **Contribution**: Weighted points added to total +- **Status**: Overall health of that dimension + +--- + +## Understanding Recommendations + +Health checks generate prioritized recommendations to improve your score. + +### Priority Levels + +| Priority | Description | Action Timeframe | +|----------|-------------|------------------| +| **Critical** | Issues affecting data integrity or compliance | Immediate (today) | +| **High** | Significant impact on accuracy or efficiency | This week | +| **Medium** | Improvements for better organization | This month | +| **Low** | Nice-to-have optimizations | When convenient | + +### Effort Estimates + +Each recommendation includes an effort estimate: + +| Effort | Typical Time | Examples | +|--------|--------------|----------| +| **Quick Win** | < 15 minutes | Enable a setting, create one rule | +| **Moderate** | 15-60 minutes | Reorganize categories, review duplicates | +| **Significant** | 1-4 hours | Major category restructure, bulk updates | + +### Acting on Recommendations + +Recommendations follow this format: + +``` +[PRIORITY] Recommendation Title + Issue: What the problem is + Impact: Why it matters + Action: Specific steps to fix it + Effort: Time estimate +``` + +**Best practice**: Start with critical/quick-win items for maximum impact with minimum effort. + +--- + +## Automated Monitoring + +### Weekly Health Checks + +Agent Smith can run automated weekly health checks: + +- **Schedule**: Every Sunday at midnight (configurable) +- **Storage**: Results saved to `data/health/weekly/` +- **Comparison**: Automatic comparison to previous week + +### Score Drop Alerts + +Get notified when your health score changes significantly: + +| Alert Type | Trigger | Priority | +|------------|---------|----------| +| Critical Drop | Score falls below 50 | High | +| Significant Drop | Score drops > 15 points | Medium | +| Dimension Alert | Any dimension falls to Critical | High | +| Improvement | Score increases > 10 points | Info | + +### Configuring Alerts + +Set alert preferences in your environment or config: + +```bash +# .env +HEALTH_CHECK_ALERTS=true +HEALTH_CHECK_THRESHOLD=15 +``` + +Or in `data/config.json`: + +```json +{ + "healthCheck": { + "weeklyEnabled": true, + "alertOnDrop": true, + "dropThreshold": 15, + "notificationMethod": "summary" + } +} +``` + +--- + +## Example Output + +Here is a sample health check result: + +``` +================================================================================ + AGENT SMITH HEALTH CHECK + 2025-01-15 09:30 AM +================================================================================ + +OVERALL SCORE: 74/100 [GOOD] + +-------------------------------------------------------------------------------- +DIMENSION BREAKDOWN +-------------------------------------------------------------------------------- + + Data Quality [################----] 80/100 (25%) = 20.0 pts + Category Structure [###############-----] 75/100 (20%) = 15.0 pts + Rule Engine [############--------] 60/100 (15%) = 9.0 pts [WARN] + Tax Readiness [################----] 82/100 (15%) = 12.3 pts + Automation [##############------] 70/100 (10%) = 7.0 pts + Budget Alignment [##############------] 72/100 (15%) = 10.8 pts + +-------------------------------------------------------------------------------- +KEY METRICS +-------------------------------------------------------------------------------- + + [PASS] Uncategorized transactions: 3.2% (target: <5%) + [PASS] Duplicate transactions: 0 found + [WARN] Rule coverage: 68% (target: >80%) + [PASS] Tax categories mapped: 94% + [WARN] Budget variance: 12% (target: <10%) + +-------------------------------------------------------------------------------- +RECOMMENDATIONS (5) +-------------------------------------------------------------------------------- + + [CRITICAL] Quick Win + Create rules for top 10 uncategorized merchants + Issue: 15 merchants account for 60% of uncategorized transactions + Impact: Could improve rule coverage by 12% + Action: Run `/agent-smith-categorize analyze` to generate rules + Effort: 15 minutes + + [HIGH] Moderate + Review category "Other Expenses" + Issue: $2,340 in catch-all category this month + Impact: Affects reporting accuracy and tax deduction tracking + Action: Recategorize transactions or create more specific categories + Effort: 30 minutes + + [MEDIUM] Quick Win + Enable automatic account sync + Issue: Manual sync causing 2-3 day delays + Impact: Budgets and forecasts using stale data + Action: Enable daily sync in PocketSmith settings + Effort: 5 minutes + + [MEDIUM] Moderate + Reduce budget variance in "Dining Out" + Issue: Consistently 25% over budget + Impact: Unrealistic budget affecting financial planning + Action: Adjust budget or implement spending alerts + Effort: 15 minutes + + [LOW] Quick Win + Archive unused categories + Issue: 8 categories with no transactions in 6+ months + Impact: Clutters category picker, minor UX issue + Action: Review and archive or delete unused categories + Effort: 10 minutes + +-------------------------------------------------------------------------------- +TREND (Last 4 Weeks) +-------------------------------------------------------------------------------- + + Week 1: 68 ████████████████░░░░ + Week 2: 71 █████████████████░░░ (+3) + Week 3: 72 █████████████████░░░ (+1) + Week 4: 74 ██████████████████░░ (+2) <- Current + + Trend: Improving (+6 over 4 weeks) + +================================================================================ +Next scheduled check: 2025-01-22 00:00 +Run `/agent-smith-health compare` to see detailed changes +================================================================================ +``` + +--- + +## Troubleshooting + +### Common Issues + +#### "Unable to connect to PocketSmith" + +**Cause**: API key missing or invalid + +**Solution**: +1. Check `.env` file contains `POCKETSMITH_API_KEY` +2. Verify the key is valid at PocketSmith Developer Settings +3. Ensure no extra whitespace around the key + +#### "Health check taking too long" + +**Cause**: Large transaction history or slow API response + +**Solution**: +1. Use `/agent-smith-health quick` for faster results +2. Check your internet connection +3. Try again during off-peak hours + +#### "Scores seem inaccurate" + +**Cause**: Stale cached data or sync issues + +**Solution**: +1. Force sync your PocketSmith accounts +2. Clear Agent Smith cache: check `data/cache/` +3. Run a full health check: `/agent-smith-health full` + +#### "Recommendations don't apply to my situation" + +**Cause**: Generic recommendations may not fit all users + +**Solution**: +1. Adjust targets in `data/config.json` +2. Use `/agent-smith configure` to set your preferences +3. Dismiss inapplicable recommendations + +#### "Missing dimension scores" + +**Cause**: Insufficient data for analysis + +**Solution**: +1. Ensure you have at least 30 days of transaction history +2. Verify all accounts are synced +3. Check that categories are set up in PocketSmith + +### Getting Help + +If issues persist: + +1. Check `data/logs/` for error details +2. Run `/agent-smith-health --debug` for verbose output +3. Review the design documentation at `docs/design/` + +--- + +## Quick Reference + +| Task | Command | +|------|---------| +| Run full health check | `/agent-smith-health` | +| Quick check | `/agent-smith-health quick` | +| Check specific dimension | `/agent-smith-health data-quality` | +| Compare to last check | `/agent-smith-health compare` | +| View trends | `/agent-smith-health trends` | +| Configure alerts | `/agent-smith configure alerts` | + +--- + +*For more information, see the complete [Agent Smith Design Document](../design/2025-11-20-agent-smith-design.md).* diff --git a/skills/agent-smith/references/onboarding-guide.md b/skills/agent-smith/references/onboarding-guide.md new file mode 100644 index 0000000..c4efc00 --- /dev/null +++ b/skills/agent-smith/references/onboarding-guide.md @@ -0,0 +1,344 @@ +# Agent Smith Onboarding Guide + +Welcome to Agent Smith! This guide walks you through your first-time setup and helps you get the most out of your PocketSmith integration. + +## Before You Begin + +**Prerequisites:** +1. ✅ Agent Smith installed (see [INSTALL.md](../../INSTALL.md)) +2. ✅ PocketSmith account with API access +3. ✅ API key configured in `.env` file +4. ✅ Python 3.9+ and `uv` installed + +**Time Required:** 30-60 minutes (depending on transaction volume) + +--- + +## The Onboarding Journey + +Agent Smith's onboarding is an 8-stage interactive process that: +- Discovers your PocketSmith account structure +- Recommends and customizes rule templates +- Incrementally categorizes your transactions +- Shows measurable improvement with health scores + +### Quick Start + +```bash +# Launch the onboarding wizard +/agent-smith-onboard +``` + +Claude will guide you through each stage interactively. + +--- + +## Stage 1: Prerequisites Check + +**What happens:** +- Verifies Agent Smith installation +- Checks API key configuration +- Tests PocketSmith connection + +**If something is missing:** +- Follow the prompts to complete installation +- Refer to [INSTALL.md](../../INSTALL.md) for detailed setup + +**Time:** 2 minutes + +--- + +## Stage 2: Discovery + +**What happens:** +- Analyzes your PocketSmith account structure +- Counts accounts, categories, and transactions +- Identifies uncategorized transactions +- Calculates baseline health score + +**What you'll see:** +``` +✓ Connected as: your@email.com +✓ Accounts: 3 (Checking, Savings, Credit Card) +✓ Categories: 47 +✓ Transactions: 2,387 +✓ Uncategorized: 1,245 (52%) +✓ Date Range: Jan 2023 - Nov 2025 +✓ Baseline Health Score: 45/100 (Critical) +✓ Recommended Template: shared-household +``` + +**Time:** 5-10 minutes (depends on data volume) + +--- + +## Stage 3: Template Selection + +**What happens:** +- Shows 4 template options +- Recommends best fit based on discovery +- Applies selected template to `data/rules.yaml` + +**Templates:** + +| Template | Best For | Includes | +|----------|----------|----------| +| **Simple** | Single person, basic tracking | Common categories, essential rules | +| **Separated Families** | Child support, shared custody | Kids expenses, contributor tracking | +| **Shared Household** | Couples, roommates | Shared expense tracking, approval workflows | +| **Advanced** | Business owners, investors | Tax optimization, investment tracking, CGT | + +**What you'll do:** +- Review the recommendation +- Choose a template (or browse all) +- Confirm application + +**Time:** 3-5 minutes + +--- + +## Stage 4: Template Customization + +**What happens:** +- Guides you to customize the template for your needs + +**Customizations needed:** + +1. **Account Mapping** + - Template uses generic names like "Shared Bills", "Personal" + - Update to match your actual account names + +2. **Category Validation** + - Check if template categories exist in PocketSmith + - Create missing categories or map to existing ones + +3. **Merchant Localization** + - Template has Australian merchants (WOOLWORTHS, COLES) + - Update for your region (SAFEWAY, KROGER, etc.) + +**How to customize:** +- Edit `data/rules.yaml` manually (for now) +- Future versions will have interactive customization tool + +**Example:** +```yaml +# Before (template) +- type: category + patterns: [WOOLWORTHS, COLES] + category: Food & Dining > Groceries + +# After (customized for US) +- type: category + patterns: [SAFEWAY, KROGER, WHOLE FOODS] + category: Food & Dining > Groceries +``` + +**Time:** 10-20 minutes + +--- + +## Stage 5: Intelligence Mode Selection + +**What happens:** +- Configure AI categorization behavior +- Set tax intelligence level + +**Categorization Mode:** + +| Mode | Auto-Apply Threshold | Best For | +|------|---------------------|----------| +| Conservative | 100% (manual approval all) | First-time setup, learning | +| **Smart** (default) | ≥90% confidence | Most users, balanced | +| Aggressive | ≥80% confidence | High volume, trust AI | + +**Tax Intelligence Level:** + +| Level | Capabilities | Best For | +|-------|-------------|----------| +| Reference | ATO category mapping, basic reports | Users with accountants | +| **Smart** (default) | Deduction detection, thresholds | Most taxpayers | +| Full | BAS prep, compliance checks | Business owners, power users | + +**Time:** 2 minutes + +--- + +## Stage 6: Incremental Categorization + +**What happens:** +- Categorize transactions in manageable batches +- Start recent, expand to historical + +**Recommended Strategy:** + +1. **Current Month** (test rules on small dataset) + ```bash + uv run python scripts/operations/batch_categorize.py --mode=dry_run --period=2025-11 + uv run python scripts/operations/batch_categorize.py --mode=apply --period=2025-11 + ``` + +2. **Last 3 Months** (validate at scale) + ```bash + uv run python scripts/operations/batch_categorize.py --mode=apply --period=2025-09:2025-11 + ``` + +3. **Full Backfill** (complete the archive) + ```bash + uv run python scripts/operations/batch_categorize.py --mode=apply --period=2023-01:2025-11 + ``` + +**After Each Batch:** +- Review results (matched, auto-applied, needs review) +- Approve medium-confidence suggestions +- Agent Smith learns new rules from your corrections + +**Time:** 20-60 minutes (depends on volume and mode) + +--- + +## Stage 7: Health Check & Progress + +**What happens:** +- Run post-categorization health check +- Show before/after improvement +- Identify remaining priorities + +**What you'll see:** +``` +═══════════════════════════════════════════════ +AGENT SMITH HEALTH CHECK - PROGRESS REPORT +═══════════════════════════════════════════════ + +Baseline (before): 45/100 (Critical) +Current: 78/100 (Good) ⬆ +33 points + +Improvements: +• Data Quality: 42 → 88 (+46) ✅ +• Rule Engine: 15 → 72 (+57) ✅ +• Category Structure: 58 → 81 (+23) ✅ + +Remaining priorities: +1. Review tax category mappings +2. Add 3 more rules for recurring merchants +3. Create budgets for top 5 categories +``` + +**Time:** 5 minutes + +--- + +## Stage 8: Ongoing Usage + +**What happens:** +- Receive guidance on regular Agent Smith usage +- Get quick reference for common operations + +**Daily/Weekly:** +```bash +/agent-smith-categorize --mode=smart --period=2025-11 +``` + +**Monthly:** +```bash +/agent-smith-analyze spending --period=2025-11 +/agent-smith-health --quick +``` + +**Quarterly:** +```bash +/agent-smith-tax deductions --period=2024-25 +``` + +**Annual (EOFY):** +```bash +/agent-smith-tax eofy +``` + +**Time:** 2 minutes + +--- + +## Troubleshooting + +### Onboarding Interrupted + +If onboarding is interrupted, your progress is saved in `data/onboarding_state.json`. + +**Resume:** +```bash +/agent-smith-onboard +``` + +Claude will detect saved state and offer to resume from where you left off. + +**Start Over:** +```bash +uv run python -c "from scripts.onboarding.state import OnboardingState; OnboardingState().reset()" +/agent-smith-onboard +``` + +### Discovery Fails + +**Problem:** "Error during discovery: ..." + +**Solutions:** +- Check `.env` has valid `POCKETSMITH_API_KEY` +- Verify PocketSmith account has API access enabled +- Check internet connection to api.pocketsmith.com + +### Template Customization Unclear + +**Problem:** Not sure how to customize `data/rules.yaml` + +**Solutions:** +- Review [Unified Rules Guide](unified-rules-guide.md) for YAML syntax +- Check [Example Files](../examples/) for patterns +- Start with dry-run to test rules before applying + +### Categorization Too Slow + +**Problem:** Batch categorization taking too long + +**Solutions:** +- Use smaller date ranges (1 month at a time) +- Switch to "Aggressive" mode for faster auto-apply +- Run in background with progress monitoring + +--- + +## Next Steps + +After completing onboarding: + +1. **Set Up Alerts** + - Weekly budget reviews + - Monthly trend analysis + - Tax deadline reminders + +2. **Create Budgets** + - Use health check recommendations + - Focus on top spending categories + - Track vs. budget monthly + +3. **Optimize Rules** + - Review rule performance metrics + - Add rules for recurring merchants + - Refine confidence scores + +4. **Explore Advanced Features** + - Scenario analysis + - Tax optimization + - Investment tracking + +--- + +## Getting Help + +- **Documentation:** [docs/](../INDEX.md) +- **API Reference:** [ai_docs/pocketsmith-api-documentation.md](../../ai_docs/pocketsmith-api-documentation.md) +- **Health Check Guide:** [health-check-guide.md](health-check-guide.md) +- **GitHub Issues:** [github.com/slamb2k/agent-smith/issues](https://github.com/slamb2k/agent-smith/issues) + +--- + +**Welcome to Agent Smith! Let's transform your PocketSmith into an intelligent financial system.** diff --git a/skills/agent-smith/references/pocketsmith-api.md b/skills/agent-smith/references/pocketsmith-api.md new file mode 100644 index 0000000..bd882e0 --- /dev/null +++ b/skills/agent-smith/references/pocketsmith-api.md @@ -0,0 +1,293 @@ +# PocketSmith API Documentation (Offline Reference) + +**API Version:** v2.0 +**Base URL:** `https://api.pocketsmith.com/v2` +**Documentation Source:** https://developers.pocketsmith.com/ +**Last Updated:** 2025-11-16 + +--- + +## Table of Contents + +1. [Introduction](#introduction) +2. [Authentication](#authentication) + - [Developer Keys](#developer-keys-personal-tools) + - [OAuth 2.0](#oauth-20-multi-user-apps) +3. [API Reference](#api-reference) + - [Users](#users) + - [Institutions](#institutions) + - [Accounts](#accounts) + - [Transaction Accounts](#transaction-accounts) + - [Transactions](#transactions) + - [Categories](#categories) + - [Budgeting](#budgeting) + - [Supporting Resources](#supporting-resources) +4. [Common Topics](#common-topics) + - [Pagination](#pagination) + - [Error Handling](#error-handling) +5. [Changelog](#changelog) +6. [Support](#support) + +--- + +## Introduction + +The PocketSmith API is freely available to all developers without restrictions. The platform welcomes developers to build tools and integrations using their services. + +**Developer Hub:** https://developers.pocketsmith.com/ + +--- + +## Authentication + +PocketSmith provides two authentication methods depending on your use case. + +### Developer Keys (Personal Tools) + +For building personal tools like dashboard widgets or transaction importers, use developer keys. + +**Configuration:** +- Manage keys in: Settings > Security within your PocketSmith account +- **Header:** `X-Developer-Key` +- **Access:** Persistent API access to your own account + +**Example Request:** +```bash +curl --header "X-Developer-Key: YOUR_KEY_HERE" \ + https://api.pocketsmith.com/v2/me +``` + +**Supported Languages:** +- Shell (curl) +- Node.js +- JavaScript +- PHP +- Python + +### OAuth 2.0 (Multi-User Apps) + +To create applications that other PocketSmith users can access, you'll need to use OAuth 2.0. + +**Setup Process:** + +1. **Register your application** by contacting the team at [email protected] +2. **Provide details** about yourself and your planned integration +3. **Receive credentials:** `client_id` and `client_secret` upon approval +4. **Implement authentication** using the OAuth integration guide + +**OAuth Flow:** +- Standard OAuth 2.0 authorization code flow +- Detailed integration instructions available in the OAuth documentation section + +--- + +## API Reference + +The PocketSmith API v2.0 is organized around the following resource categories: + +### Users + +**Endpoints:** +- Get authorised user +- Get user by ID +- Update user information + +**Example - Get the Authorised User:** +``` +GET https://api.pocketsmith.com/v2/me +``` + +**Purpose:** Gets the user that corresponds to the access token used in the request. + +**Authentication Required:** Yes (Header-based credentials) + +--- + +### Institutions + +Manage financial institutions connected to user accounts. + +**Operations:** +- Create institution +- Read institution details +- Update institution information +- Delete institution +- List all institutions within a user account + +--- + +### Accounts + +Complete account management functionality. + +**Operations:** +- Get account details +- Update account information +- Delete account +- Create new account +- Manage account ordering within users +- List accounts by institution + +--- + +### Transaction Accounts + +Transaction accounts are the specific accounts where transactions are recorded. + +**Operations:** +- Get transaction account details +- Update transaction account +- List transaction accounts by user + +--- + +### Transactions + +Complete transaction lifecycle management with multi-context querying. + +**Query Contexts:** +- By user +- By account +- By category +- By transaction account + +**Operations:** +- Create transactions within transaction accounts +- Read transaction details +- Update transactions +- Delete transactions +- Query and filter transactions + +--- + +### Categories + +Manage and organize transaction categories. + +**Operations:** +- Category management and organization +- List user-specific categories +- Create category rules +- Update categories +- Delete categories + +--- + +### Budgeting + +Budget management and analysis features. + +**Features:** +- Budget retrieval and summaries +- Trend analysis +- Forecast cache management + +--- + +### Supporting Resources + +Additional resources for comprehensive financial data management: + +- **Events** - Manage financial events +- **Attachments** - Attach files to transactions +- **Labels** - Label and tag transactions +- **Saved Searches** - Save frequently used search queries +- **Currencies** - Handle multi-currency support +- **Time Zones** - Manage timezone settings + +--- + +## Common Topics + +### Pagination + +The API uses pagination for endpoints that return multiple records. + +**Implementation Details:** +- Refer to the pagination documentation section for page size limits and navigation +- Response headers typically include pagination metadata + +### Error Handling + +The API returns standard HTTP status codes. + +**Common Status Codes:** +- `200 OK` - Successful request +- `400 Bad Request` - Invalid request parameters +- `401 Unauthorized` - Authentication failure +- `403 Forbidden` - Insufficient permissions +- `404 Not Found` - Resource not found +- `500 Internal Server Error` - Server error + +**Error Response Format:** +Detailed error handling documentation available at: https://developers.pocketsmith.com/docs + +--- + +## Changelog + +### v2.0 - Welcome to the new PocketSmith developer hub +**Posted:** Almost 7 years ago by Regan McEntyre + +The development team announced an updated documentation portal: "We've given our developer documentation a bit of a spruce up. Come on in and check it out, and let us know what you think!" + +**Current Status:** +- API Version 2.0 is the current stable version +- Interactive API documentation powered by OpenAPI 3 specification + +--- + +## Support + +**Contact the Development Team:** +- **Email:** [email protected] + +**Resources:** +- **Interactive API Reference:** https://developers.pocketsmith.com/reference +- **Complete Guides:** https://developers.pocketsmith.com/docs +- **Changelog:** https://developers.pocketsmith.com/changelog + +--- + +## Quick Start Guide + +1. **For Personal Tools:** + ```bash + # Get your developer key from Settings > Security + curl --header "X-Developer-Key: YOUR_KEY_HERE" \ + https://api.pocketsmith.com/v2/me + ``` + +2. **For Multi-User Applications:** + - Email [email protected] to register your app + - Implement OAuth 2.0 flow once approved + +3. **Explore the API:** + - Start with the `/me` endpoint to verify authentication + - Review the resource categories that match your use case + - Test endpoints using the interactive reference + +--- + +## Additional Notes + +**OpenAPI Specification:** +The API documentation is built using OpenAPI 3, which means: +- Interactive testing tools available in the web interface +- Machine-readable API specifications +- Auto-generated client libraries possible + +**Rate Limiting:** +Check the full documentation for any rate limiting policies. + +**Best Practices:** +- Always handle errors gracefully +- Use pagination for large datasets +- Cache responses where appropriate +- Follow OAuth 2.0 best practices for multi-user apps + +--- + +**End of Documentation** + +For the most up-to-date information and interactive API testing, visit: https://developers.pocketsmith.com/ diff --git a/skills/agent-smith/references/unified-rules-guide.md b/skills/agent-smith/references/unified-rules-guide.md new file mode 100644 index 0000000..858c0d7 --- /dev/null +++ b/skills/agent-smith/references/unified-rules-guide.md @@ -0,0 +1,1810 @@ +# Unified Rules Guide - Categories & Labels + +## Overview + +Agent Smith uses a **unified YAML rule system** that handles both transaction categorization and labeling in a single, easy-to-read file. + +**Key Features:** +- YAML format - Easy to read and edit +- Two-phase execution - Categories first, then labels +- Pattern matching - Regex patterns with exclusions +- Confidence scoring - 0-100% confidence for auto-apply logic +- Smart labeling - Context-aware labels (account, category, amount) +- LLM fallback - AI categorization when rules don't match +- Template system - Pre-built rule sets for common household types + +## Table of Contents + +1. [Quick Start](#quick-start) +2. [Rule Types](#rule-types) +3. [Execution Flow](#execution-flow) +4. [Intelligence Modes](#intelligence-modes) +5. [LLM Integration](#llm-integration) +6. [Advanced Patterns](#advanced-patterns) +7. [Best Practices](#best-practices) +8. [Operational Modes](#operational-modes) +9. [Update Strategies](#update-strategies) +10. [Template System](#template-system) +11. [Migration Guide](#migration-guide) +12. [Troubleshooting](#troubleshooting) + +## Quick Start + +### 1. Choose a Template + +Start with a pre-built template that matches your household type: + +```bash +uv run python scripts/setup/template_selector.py +``` + +Available templates: +- **Simple** - Single person, no shared expenses +- **Separated Families** - Divorced/separated parents with shared custody +- **Shared Household** - Couples, roommates, or families +- **Advanced** - Business owners, investors, complex finances + +### 2. Customize Your Rules + +Edit `data/rules.yaml` to match your specific needs: + +```yaml +rules: + # Add your first category rule + - type: category + name: Coffee → Dining Out + patterns: [STARBUCKS, COSTA, CAFE] + category: Food & Dining > Dining Out + confidence: 95 + + # Add your first label rule + - type: label + name: Personal Coffee + when: + categories: [Dining Out] + accounts: [Personal] + labels: [Discretionary, Personal] +``` + +### 3. Test Your Rules + +Always test before applying to real transactions: + +```bash +# Dry run - preview what would happen +uv run python scripts/operations/batch_categorize.py --mode=dry_run --period=2025-11 + +# Validate - see what would change on existing categorizations +uv run python scripts/operations/batch_categorize.py --mode=validate --period=2025-11 + +# Apply - actually categorize transactions +uv run python scripts/operations/batch_categorize.py --mode=apply --period=2025-11 +``` + +### 4. Review and Refine + +Check the results and refine your rules: + +```bash +# See categorization summary +/agent-smith-analyze spending --period=2025-11 + +# Check uncategorized transactions +/agent-smith-categorize --mode=smart --show-uncategorized +``` + +## Rule Types + +### Category Rules + +Categorize transactions based on payee patterns, amounts, and accounts. + +**Full Syntax:** + +```yaml +- type: category + name: Rule Name (for logging/display) + patterns: [PATTERN1, PATTERN2, PATTERN3] # OR logic + exclude_patterns: [EXCLUDE1, EXCLUDE2] # Optional + category: Category > Subcategory + confidence: 95 # 0-100% + accounts: [Account1, Account2] # Optional filter + amount_operator: ">" # Optional: >, <, >=, <=, ==, != + amount_value: 100.00 # Required if amount_operator set +``` + +**Field Descriptions:** + +| Field | Required | Type | Description | +|-------|----------|------|-------------| +| `type` | Yes | String | Must be "category" | +| `name` | Yes | String | Descriptive name for logs (e.g., "WOOLWORTHS → Groceries") | +| `patterns` | Yes | List[String] | Payee keywords to match (case-insensitive, OR logic) | +| `category` | Yes | String | Category to assign (can include parent: "Parent > Child") | +| `confidence` | No | Integer | Confidence score 0-100% (default: 90) | +| `exclude_patterns` | No | List[String] | Patterns to exclude from match | +| `accounts` | No | List[String] | Only match transactions in these accounts | +| `amount_operator` | No | String | Amount comparison: >, <, >=, <=, ==, != | +| `amount_value` | No | Number | Amount threshold (required if operator set) | + +**Examples:** + +```yaml +# Basic pattern matching +- type: category + name: WOOLWORTHS → Groceries + patterns: [WOOLWORTHS, COLES, ALDI] + category: Food & Dining > Groceries + confidence: 95 + +# With exclusions (exclude UBER EATS from UBER) +- type: category + name: UBER → Transport + patterns: [UBER] + exclude_patterns: [UBER EATS] + category: Transport + confidence: 90 + +# Account-specific rule +- type: category + name: Work Laptop Purchase + patterns: [APPLE STORE, MICROSOFT STORE] + accounts: [Work Credit Card] + category: Work > Equipment + confidence: 90 + +# Amount-based rule (large purchases) +- type: category + name: Large Electronics + patterns: [JB HI-FI, HARVEY NORMAN] + category: Shopping > Electronics + confidence: 85 + amount_operator: ">" + amount_value: 500 +``` + +### Label Rules + +Apply labels to transactions based on their category, account, amount, or categorization status. + +**Full Syntax:** + +```yaml +- type: label + name: Label Rule Name + when: + categories: [Category1, Category2] # Optional (OR logic) + accounts: [Account1, Account2] # Optional (OR logic) + amount_operator: ">" # Optional + amount_value: 100.00 # Required if operator set + uncategorized: true # Optional (true to match uncategorized) + labels: [Label1, Label2, Label3] +``` + +**Important:** All `when` conditions must match (AND logic), but values within each list use OR logic. + +**Field Descriptions:** + +| Field | Required | Type | Description | +|-------|----------|------|-------------| +| `type` | Yes | String | Must be "label" | +| `name` | Yes | String | Descriptive name for logs | +| `when` | Yes | Object | Conditions that must ALL match | +| `when.categories` | No | List[String] | Match if category contains any of these (OR) | +| `when.accounts` | No | List[String] | Match if account name contains any of these (OR) | +| `when.amount_operator` | No | String | Amount comparison: >, <, >=, <=, ==, != | +| `when.amount_value` | No | Number | Amount threshold | +| `when.uncategorized` | No | Boolean | Match uncategorized transactions (true/false) | +| `labels` | Yes | List[String] | Labels to apply when conditions match | + +**Examples:** + +```yaml +# Category-based labeling +- type: label + name: Tax Deductible Work Expenses + when: + categories: [Work, Professional Development, Home Office] + labels: [Tax Deductible, ATO: D1] + +# Account-based labeling +- type: label + name: Shared Household Expense + when: + accounts: [Shared Bills, Joint Account] + labels: [Shared Expense, Needs Reconciliation] + +# Combined conditions (category AND account) +- type: label + name: Personal Coffee Spending + when: + categories: [Dining Out] + accounts: [Personal] + labels: [Discretionary, Personal] + +# Amount-based labeling +- type: label + name: Large Purchase Flag + when: + amount_operator: ">" + amount_value: 500 + labels: [Large Purchase, Review Required] + +# Flag uncategorized transactions +- type: label + name: Needs Categorization + when: + uncategorized: true + labels: [Uncategorized, Needs Review] + +# Multi-condition (category AND account AND amount) +- type: label + name: Large Shared Grocery Trip + when: + categories: [Groceries] + accounts: [Shared Bills] + amount_operator: ">" + amount_value: 200 + labels: [Shared Expense, Large Purchase, Needs Approval] +``` + +## Execution Flow + +The unified rule engine uses **two-phase execution** to ensure labels can depend on categories assigned in the same run. + +### Phase 1: Categorization + +1. Iterate through all category rules in order +2. For each transaction, find the FIRST matching rule +3. Apply the category and confidence score +4. **Short-circuit:** Stop at first match (no further category rules evaluated) +5. Update transaction with matched category for Phase 2 + +**Rule Order Matters!** Specific rules should come before general rules. + +### Phase 2: Labeling + +1. Using the transaction (now with category from Phase 1) +2. Check ALL label rules +3. Apply labels from EVERY matching rule (additive) +4. Deduplicate and sort labels + +**All Matches Applied!** Unlike categories, ALL matching label rules are applied. + +### Example Execution + +Transaction: `WOOLWORTHS` in `Shared Bills` account, amount `-$127.50` + +**Phase 1 - Category Rules:** + +```yaml +# Rule 1 matches! +- type: category + name: WOOLWORTHS → Groceries + patterns: [WOOLWORTHS] + category: Food & Dining > Groceries + confidence: 95 + +# Rule 2 would also match but is NOT evaluated (short-circuit) +- type: category + name: All Food Purchases + patterns: [WOOLWORTHS, COLES, RESTAURANT] + category: Food + confidence: 80 +``` + +**Result after Phase 1:** Category = "Food & Dining > Groceries", Confidence = 95 + +**Phase 2 - Label Rules:** + +```yaml +# Rule 1 matches (category: Groceries, account: Shared Bills) +- type: label + name: Shared Grocery Expense + when: + categories: [Groceries] + accounts: [Shared Bills] + labels: [Shared Expense, Essential] + +# Rule 2 matches (amount > 100) +- type: label + name: Large Purchase + when: + amount_operator: ">" + amount_value: 100 + labels: [Large Purchase, Review] + +# Rule 3 does NOT match (category doesn't contain "Dining Out") +- type: label + name: Discretionary Dining + when: + categories: [Dining Out] + labels: [Discretionary] +``` + +**Final Result:** +- Category: Food & Dining > Groceries +- Confidence: 95 +- Labels: Essential, Large Purchase, Review, Shared Expense (sorted, deduplicated) + +## Intelligence Modes + +Agent Smith has three intelligence modes that control auto-apply behavior based on confidence scores. + +### Conservative Mode + +**Never auto-applies** - always asks user for confirmation. + +```yaml +Confidence Level: ANY +Action: Ask user for approval +Use when: Learning the system, want full control +``` + +Example: +``` +Transaction: STARBUCKS -$6.50 +Rule match: "Dining Out" (95% confidence) +→ [Ask User] Apply category "Dining Out"? + [Yes] [No] [Edit] +``` + +### Smart Mode (Default) + +**Balanced approach** - auto-applies high confidence, asks for medium, skips low. + +```yaml +Confidence ≥ 90%: Auto-apply without asking +Confidence 70-89%: Ask user for approval (LLM validates first) +Confidence < 70%: Skip (don't categorize) +``` + +Example: +``` +Transaction: UBER -$25.00 +Rule match: "Transport" (95% confidence) +→ [Auto-applied] Category: Transport + +Transaction: UBER MEDICAL CENTRE -$80 +Rule match: "UBER → Transport" (75% confidence) +→ [LLM Validates] This looks like medical, not transport +→ [Suggests] Medical & Healthcare (90% confidence) +→ [Auto-applied] Category: Medical & Healthcare +``` + +### Aggressive Mode + +**More permissive** - auto-applies medium-high confidence, asks for medium-low. + +```yaml +Confidence ≥ 80%: Auto-apply without asking +Confidence 50-79%: Ask user for approval +Confidence < 50%: Skip (don't categorize) +``` + +Example: +``` +Transaction: ACME WIDGETS -$245.00 +Rule match: "Business Supplies" (82% confidence) +→ [Auto-applied] Category: Business Supplies +``` + +### Setting the Mode + +**In command:** +```bash +/agent-smith-categorize --mode=smart +``` + +**In environment (.env):** +```bash +DEFAULT_INTELLIGENCE_MODE=smart +``` + +**In code:** +```python +from scripts.workflows.categorization import CategorizationWorkflow + +workflow = CategorizationWorkflow( + client=client, + mode="smart" # conservative, smart, or aggressive +) +``` + +## LLM Integration + +When rule-based categorization fails, Agent Smith falls back to AI-powered categorization using Claude. + +### Fallback Categorization + +When no rule matches, Agent Smith asks the LLM to suggest a category. + +**Flow:** + +1. No category rule matches transaction +2. Build LLM prompt with: + - Full category hierarchy + - Transaction details (payee, amount, date) + - Intelligence mode guidance +3. LLM suggests category with confidence and reasoning +4. Apply intelligence mode thresholds: + - High confidence → Auto-apply (or ask in conservative mode) + - Medium confidence → Ask user + - Low confidence → Skip + +**Example:** + +``` +Transaction: ACME WIDGETS LTD -$245.00 +No rule match +→ [LLM] Analyzing transaction... +→ [LLM] Suggests: Business Supplies (85% confidence) + Reasoning: "ACME WIDGETS appears to be a business supplier based on + naming convention and typical transaction amount." +→ [Smart Mode] 85% is above ask threshold (70%) but below auto (90%) +→ [Ask User] Apply category "Business Supplies"? + [Yes] [No] [Create Rule] +``` + +### Validation + +Medium-confidence rule matches (70-89% in smart mode) are validated by the LLM to catch edge cases. + +**Flow:** + +1. Rule matches with medium confidence +2. Build validation prompt with: + - Transaction details + - Suggested category + - Rule confidence +3. LLM responds: CONFIRM or REJECT + - CONFIRM: Can upgrade confidence → auto-apply + - REJECT: Suggests alternative category +4. Apply validated result + +**Example:** + +``` +Transaction: UBER MEDICAL CENTRE -$80 +Rule match: "UBER → Transport" (75% confidence) +→ [LLM] Validating categorization... +→ [LLM] REJECT - This appears to be a medical facility, not transport + Suggests: Medical & Healthcare (90% confidence) +→ [Smart Mode] 90% ≥ auto-apply threshold +→ [Auto-applied] Category: Medical & Healthcare +``` + +### Learning from LLM Results + +After the LLM categorizes transactions, Agent Smith offers to create rules for future use. + +**Flow:** + +1. LLM categorizes N transactions with same merchant +2. Detect pattern: Same payee → Same category +3. Suggest rule creation +4. User approves, edits, or declines +5. If approved: Add rule to `data/rules.yaml` + +**Example:** + +``` +LLM categorized 12 "ACME WIDGETS" transactions as "Business Supplies" + +Suggested rule: + - type: category + name: ACME WIDGETS → Business Supplies + patterns: [ACME WIDGETS] + category: Business Supplies + confidence: 90 + +[Create Rule] [Edit Rule] [Decline] + +→ User selects [Create Rule] +→ Rule added to data/rules.yaml +→ Future ACME WIDGETS transactions auto-categorized (90% confidence) +``` + +## Advanced Patterns + +### Cross-Category Labels + +Apply the same label to multiple categories: + +```yaml +# Tax deductible categories +- type: label + name: ATO Tax Deductible + when: + categories: [Work, Professional Development, Home Office, Software] + labels: [Tax Deductible, ATO: D1] + +# Large purchases across all categories +- type: label + name: Large Purchase Alert + when: + amount_operator: ">" + amount_value: 500 + labels: [Large Purchase, Review Required] +``` + +### Account-Based Workflows + +Different labels for same category in different accounts: + +```yaml +# Same category rule for all accounts +- type: category + name: Transport + patterns: [UBER, LYFT, TAXI] + category: Transport + confidence: 90 + +# Personal transport +- type: label + name: Personal Transport + when: + categories: [Transport] + accounts: [Personal] + labels: [Personal, Discretionary] + +# Work transport (reimbursable) +- type: label + name: Work Transport + when: + categories: [Transport] + accounts: [Work, Personal] # Can be from either account + amount_operator: ">" + amount_value: 20 # But large amounts suggest work trips + labels: [Work Related, Reimbursable] +``` + +### Shared Household Expense Tracking + +Track who paid for shared expenses: + +```yaml +# Shared groceries +- type: category + name: Shared Groceries + patterns: [WOOLWORTHS, COLES] + accounts: [Shared Bills, Joint Account] + category: Food & Dining > Groceries + confidence: 95 + +- type: label + name: Shared Essential + when: + categories: [Groceries] + accounts: [Shared Bills, Joint Account] + labels: [Shared Expense, Essential, Needs Reconciliation] + +# Large shared purchases need approval +- type: label + name: Needs Approval + when: + accounts: [Shared Bills, Joint Account] + amount_operator: ">" + amount_value: 150 + labels: [Needs Approval, Review Required] +``` + +### Tax Deductible Tracking + +Flag potential tax deductions with ATO codes: + +```yaml +# Work-related expenses +- type: label + name: Work Deduction - D1 + when: + categories: [Work, Office Supplies, Professional Development] + labels: [Tax Deductible, ATO: D1, Work-related other expenses] + +# Home office expenses +- type: label + name: Home Office Deduction - D2 + when: + categories: [Home Office, Internet, Phone] + labels: [Tax Deductible, ATO: D2, Home office expenses] + +# Large deductions requiring substantiation +- type: label + name: Requires Receipt (>$300) + when: + labels: [Tax Deductible] # Note: This won't work! Labels can't check labels + amount_operator: ">" + amount_value: 300 + labels: [Substantiation Required, Keep Receipt] +``` + +**Important:** Label rules cannot check for other labels. Use categories or accounts instead. + +### Uncategorized Transaction Management + +Flag and prioritize uncategorized transactions: + +```yaml +# Flag all uncategorized +- type: label + name: Needs Categorization + when: + uncategorized: true + labels: [Uncategorized, Needs Review] + +# High-priority uncategorized (large amounts) +- type: label + name: High Priority Uncategorized + when: + uncategorized: true + amount_operator: ">" + amount_value: 100 + labels: [Uncategorized, High Priority, Urgent Review] + +# Uncategorized in shared account +- type: label + name: Uncategorized Shared Expense + when: + uncategorized: true + accounts: [Shared Bills, Joint Account] + labels: [Uncategorized, Shared Account, Needs Approval] +``` + +## Best Practices + +### 1. Order Rules Specific → General + +Rules are evaluated in order. Put specific rules first: + +```yaml +# ✓ GOOD: Specific first +- type: category + name: UBER EATS → Dining Out + patterns: [UBER EATS] + category: Food & Dining > Dining Out + confidence: 95 + +- type: category + name: UBER → Transport + patterns: [UBER] + category: Transport + confidence: 90 + +# ✗ BAD: General first (UBER catches UBER EATS) +- type: category + name: UBER → Transport + patterns: [UBER] + category: Transport + confidence: 90 + +- type: category + name: UBER EATS → Dining Out # Never reached! + patterns: [UBER EATS] + category: Food & Dining > Dining Out + confidence: 95 +``` + +**Fix with exclusions:** + +```yaml +- type: category + name: UBER → Transport + patterns: [UBER] + exclude_patterns: [UBER EATS] + category: Transport + confidence: 90 +``` + +### 2. Use Visual Grouping + +Group related rules with comments for easy scanning: + +```yaml +# ═══════════════════════════════════════════════════════════ +# GROCERIES WORKFLOW +# ═══════════════════════════════════════════════════════════ + +- type: category + name: Groceries + patterns: [WOOLWORTHS, COLES, ALDI] + category: Food & Dining > Groceries + confidence: 95 + +- type: label + name: Essential Spending + when: + categories: [Groceries] + labels: [Essential, Needs] + +- type: label + name: Shared Groceries + when: + categories: [Groceries] + accounts: [Shared Bills] + labels: [Shared Expense, Reconciliation] + +# ═══════════════════════════════════════════════════════════ +# TRANSPORT WORKFLOW +# ═══════════════════════════════════════════════════════════ + +- type: category + name: Rideshare + patterns: [UBER, LYFT] + exclude_patterns: [UBER EATS] + category: Transport + confidence: 90 +``` + +### 3. Start with High Confidence + +Begin with rules you're certain about (95%+): + +```yaml +# High confidence - very specific merchants +- type: category + name: WOOLWORTHS → Groceries + patterns: [WOOLWORTHS] + category: Food & Dining > Groceries + confidence: 95 + +- type: category + name: AGL → Utilities + patterns: [AGL] + category: Bills > Utilities + confidence: 95 +``` + +Add medium-confidence rules (80-90%) later as you verify: + +```yaml +# Medium confidence - could be ambiguous +- type: category + name: Amazon Purchases + patterns: [AMAZON] + category: Shopping + confidence: 80 # Could be books, electronics, groceries, etc. +``` + +### 4. Test with Dry Run + +Always test before applying to real transactions: + +```bash +# Preview what would happen without making changes +uv run python scripts/operations/batch_categorize.py \ + --mode=dry_run \ + --period=2025-11 \ + --limit=50 + +# See what would change on existing categorizations +uv run python scripts/operations/batch_categorize.py \ + --mode=validate \ + --period=2025-11 +``` + +Review the output carefully before running with `--mode=apply`. + +### 5. Version Control Your Rules + +Commit `data/rules.yaml` to git to track evolution: + +```bash +# After adding/modifying rules +git add data/rules.yaml +git commit -m "rules: add coffee shop categorization with personal label" + +# View history +git log --oneline data/rules.yaml + +# Compare versions +git diff HEAD~1 data/rules.yaml +``` + +### 6. Review Rule Performance Regularly + +Check rule accuracy monthly: + +```bash +# Analyze categorization coverage +/agent-smith-analyze rules --period=last-month + +# See which rules are matching most often +/agent-smith-analyze rules --sort=matches + +# Find low-accuracy rules +/agent-smith-analyze rules --min-accuracy=80 +``` + +Refine rules that have low accuracy or aren't matching as expected. + +### 7. Use Templates as Starting Points + +Don't start from scratch - use a template: + +```bash +uv run python scripts/setup/template_selector.py +``` + +Then customize by: +1. Updating merchant names for your region (e.g., WOOLWORTHS → KROGER) +2. Adjusting account names to match your PocketSmith setup +3. Adding your specific categories +4. Fine-tuning confidence scores based on your data + +### 8. Document Complex Rules + +Add comments explaining non-obvious rules: + +```yaml +# Complex rule: UBER is transport UNLESS it's UBER EATS or during work hours +# Work hours trips from Personal account are likely work-related (reimbursable) +- type: category + name: UBER Transport (Excluding Food Delivery) + patterns: [UBER] + exclude_patterns: [UBER EATS, UBER EATS MARKETPLACE] + category: Transport + confidence: 90 + +# Note: Work-related UBER trips need manual review for reimbursement +# They'll get the "Reimbursable" label from the account-based rule below +``` + +## Operational Modes + +The batch processor supports three operational modes for safe rule testing and application. + +### DRY_RUN Mode + +**Purpose:** Preview what would happen without making any changes. + +**Use when:** +- Testing new rules +- Checking rule coverage +- Seeing potential categorizations before committing + +**Example:** + +```bash +uv run python scripts/operations/batch_categorize.py \ + --mode=dry_run \ + --period=2025-11 +``` + +**Output:** + +``` +DRY RUN MODE - No changes will be made + +Transaction #12345: WOOLWORTHS -$127.50 + → Would categorize as: Food & Dining > Groceries (95% confidence) + → Would apply labels: [Essential, Shared Expense] + +Transaction #12346: STARBUCKS -$6.50 + → Would categorize as: Food & Dining > Dining Out (90% confidence) + → Would apply labels: [Discretionary, Personal] + +Transaction #12347: ACME WIDGETS -$245.00 + → No rule match + → Would request LLM categorization + +Summary: + Would categorize: 2/3 transactions (66.7%) + LLM fallback needed: 1 transaction + No changes made (DRY RUN) +``` + +### VALIDATE Mode + +**Purpose:** Show what would CHANGE on transactions that already have categories. + +**Use when:** +- Checking if new rules conflict with existing categorizations +- Planning to update categories with better rules +- Auditing categorization accuracy + +**Example:** + +```bash +uv run python scripts/operations/batch_categorize.py \ + --mode=validate \ + --period=2025-11 +``` + +**Output:** + +``` +VALIDATE MODE - Showing potential changes + +Transaction #12345: WOOLWORTHS -$127.50 + Current: Food (80% confidence) + New: Food & Dining > Groceries (95% confidence) + Change: Category would be updated ✓ + +Transaction #12346: STARBUCKS -$6.50 + Current: Food & Dining > Dining Out (90% confidence) + New: Food & Dining > Dining Out (90% confidence) + Change: No change (same category) + +Transaction #12347: UBER -$25.00 + Current: Dining Out (user-assigned) + New: Transport (90% confidence from rule) + Change: Category would be REPLACED (was user-assigned!) + +Summary: + Would update: 2 transactions + Already correct: 1 transaction + Would replace user assignments: 1 transaction ⚠️ + No changes made (VALIDATE) +``` + +### APPLY Mode + +**Purpose:** Actually apply categorizations and labels to transactions. + +**Use when:** +- Ready to commit changes after testing with DRY_RUN/VALIDATE +- Processing new uncategorized transactions +- Updating categorizations with improved rules + +**Example:** + +```bash +uv run python scripts/operations/batch_categorize.py \ + --mode=apply \ + --period=2025-11 \ + --update-strategy=skip_existing +``` + +**Output:** + +``` +APPLY MODE - Making changes to PocketSmith + +Transaction #12345: WOOLWORTHS -$127.50 + ✓ Categorized as: Food & Dining > Groceries (95%) + ✓ Labels applied: [Essential, Shared Expense] + +Transaction #12346: STARBUCKS -$6.50 + ⊘ Skipped (already categorized) + +Transaction #12347: ACME WIDGETS -$245.00 + → Requesting LLM categorization... + ? Suggested: Business Supplies (85% confidence) + [A]ccept [E]dit [S]kip [C]reate Rule +``` + +## Update Strategies + +Control how the batch processor handles transactions that already have categories. + +### SKIP_EXISTING (Default) + +Only process uncategorized transactions. Leave existing categorizations unchanged. + +**Use when:** +- Processing new transactions +- Don't want to override user-assigned categories +- Preserving manual categorization work + +```bash +uv run python scripts/operations/batch_categorize.py \ + --mode=apply \ + --update-strategy=skip_existing +``` + +**Behavior:** +- Uncategorized → Apply rules +- Already categorized → Skip +- User-assigned → Skip + +### REPLACE_ALL + +Replace ALL categorizations, even if they were user-assigned. + +**Use when:** +- Rebuilding all categorizations from scratch +- Confident new rules are better than old assignments +- Fixing systemic categorization errors + +**⚠️ Warning:** This will override user-assigned categories! + +```bash +uv run python scripts/operations/batch_categorize.py \ + --mode=apply \ + --update-strategy=replace_all +``` + +**Behavior:** +- Uncategorized → Apply rules +- Already categorized → Replace with rule result +- User-assigned → Replace with rule result (loses user intent!) + +### UPGRADE_CONFIDENCE + +Replace categorization ONLY if new rule has higher confidence. + +**Use when:** +- Improving categorizations with better rules +- Keeping high-confidence assignments +- Upgrading low-confidence auto-categorizations + +```bash +uv run python scripts/operations/batch_categorize.py \ + --mode=apply \ + --update-strategy=upgrade_confidence +``` + +**Behavior:** +- Uncategorized → Apply rules +- Lower confidence → Replace with higher confidence rule +- Higher confidence → Keep existing +- User-assigned (confidence: 100%) → Never replaced + +**Example:** + +``` +Transaction: WOOLWORTHS -$50 +Current: Food (80% confidence from old rule) +New: Food & Dining > Groceries (95% confidence from new rule) +→ REPLACED (95% > 80%) + +Transaction: STARBUCKS -$6 +Current: Dining Out (95% confidence) +New: Dining Out (90% confidence from new rule) +→ KEPT (95% > 90%) +``` + +### REPLACE_IF_DIFFERENT + +Replace categorization if the category NAME differs. + +**Use when:** +- Fixing miscategorized transactions +- Migrating to a new category structure +- Correcting category hierarchies + +```bash +uv run python scripts/operations/batch_categorize.py \ + --mode=apply \ + --update-strategy=replace_if_different +``` + +**Behavior:** +- Uncategorized → Apply rules +- Same category → Keep existing +- Different category → Replace with rule result +- User-assigned → Still replaced if different! + +**Example:** + +``` +Transaction: WOOLWORTHS -$50 +Current: Food +New: Food & Dining > Groceries +→ REPLACED (different category name) + +Transaction: STARBUCKS -$6 +Current: Dining Out +New: Dining Out +→ KEPT (same category) +``` + +## Template System + +Agent Smith provides pre-built rule templates for common household types. Templates are stored in `data/templates/` and can be applied to create your `data/rules.yaml`. + +### Available Templates + +#### 1. Simple - Single Person + +**File:** `data/templates/simple.yaml` + +**Best for:** +- Single person households +- No shared expenses +- Basic income and expense tracking + +**Includes:** +- Income categorization (salary, wages) +- Essential expenses (groceries, utilities, rent) +- Discretionary spending (dining out, entertainment) +- Transport categories +- Basic labels (Essential, Discretionary, Large Purchase) +- Uncategorized flagging + +**Example rules:** + +```yaml +# Income +- type: category + patterns: [SALARY, WAGES, EMPLOYER] + category: Income > Salary + confidence: 95 + +# Essential groceries +- type: category + patterns: [WOOLWORTHS, COLES, ALDI] + category: Food & Dining > Groceries + confidence: 95 + +- type: label + when: + categories: [Groceries, Utilities, Rent] + labels: [Essential] +``` + +#### 2. Separated Families + +**File:** `data/templates/separated-families.yaml` + +**Best for:** +- Divorced or separated parents +- Shared custody arrangements +- Child support tracking +- Kids' expense management + +**Includes:** +- Kids' expense categories (school, activities, clothing, medical) +- Child support tracking +- Contributor labels (Parent A, Parent B) +- Reimbursement workflows +- School term and vacation labels +- Medical and education receipts flagging + +**Example rules:** + +```yaml +# Child expenses +- type: category + patterns: [SCHOOL, UNIFORM, SCHOOL FEES] + category: Kids > Education + confidence: 90 + +- type: label + when: + categories: [Kids] + labels: [Child Expense, Needs Documentation] + +# Child support tracking +- type: label + when: + patterns: [CHILD SUPPORT] + labels: [Child Support, Parent B Contribution] + +# Shared kid expenses requiring reimbursement +- type: label + when: + categories: [Kids] + amount_operator: ">" + amount_value: 50 + labels: [Needs Reimbursement, Split 50/50] +``` + +#### 3. Shared Household + +**File:** `data/templates/shared-household.yaml` + +**Best for:** +- Couples living together +- Roommates sharing expenses +- Families with joint accounts + +**Includes:** +- Shared vs personal expense separation +- Contributor tracking (Person A, Person B) +- Approval workflows (large purchases, discretionary spending) +- Reconciliation labels +- Essential vs discretionary labeling +- Account-based routing (Shared Bills, Personal accounts) + +**Example rules:** + +```yaml +# Shared essential expenses +- type: category + patterns: [WOOLWORTHS, COLES] + accounts: [Shared Bills, Joint Account] + category: Food & Dining > Groceries + confidence: 95 + +- type: label + when: + categories: [Groceries] + accounts: [Shared Bills] + labels: [Shared Expense, Essential, Monthly Reconciliation] + +# Approval workflow for large shared purchases +- type: label + when: + accounts: [Shared Bills] + amount_operator: ">" + amount_value: 150 + labels: [Needs Approval, Review Required] + +# Personal vs shared distinction +- type: label + when: + accounts: [Personal, PersonA Account, PersonB Account] + labels: [Personal, Individual] +``` + +#### 4. Advanced + +**File:** `data/templates/advanced.yaml` + +**Best for:** +- Business owners +- Investors and traders +- Complex financial situations +- Tax optimization focus + +**Includes:** +- Business expense categories (with ATO codes) +- Investment tracking (shares, crypto, property) +- Tax deductible flagging (work, home office, professional development) +- Capital gains tracking +- Substantiation requirements ($300 threshold) +- Instant asset write-off flagging +- GST tracking +- Business vs personal separation + +**Example rules:** + +```yaml +# Business expenses +- type: category + patterns: [OFFICE, STATIONERY, SUPPLIES] + accounts: [Business, Work] + category: Work > Office Supplies + confidence: 90 + +- type: label + when: + categories: [Work, Home Office, Professional Development] + labels: [Tax Deductible, ATO: D1, Business Expense] + +# Investment purchases +- type: category + patterns: [COMMSEC, SELFWEALTH, STAKE] + category: Investments > Share Purchase + confidence: 90 + +- type: label + when: + categories: [Investments] + labels: [CGT Event, Track Cost Base] + +# Substantiation requirements +- type: label + when: + labels: [Tax Deductible] + amount_operator: ">" + amount_value: 300 + labels: [Receipt Required, ATO Substantiation] +``` + +### Applying a Template + +**Interactive selection:** + +```bash +uv run python scripts/setup/template_selector.py +``` + +**Output:** + +``` +══════════════════════════════════════════════════════════════════ +Agent Smith - Rule Template Setup +══════════════════════════════════════════════════════════════════ + +Available templates: + +1. Simple - Single Person + Basic categories for individual financial tracking + Best for: Single person, no shared expenses + +2. Separated Families + Kids expenses, child support, contributor tracking + Best for: Divorced/separated parents with shared custody + +3. Shared Household + Shared expense tracking with approval workflows + Best for: Couples, roommates, or families + +4. Advanced + Tax optimization and investment management + Best for: Business owners, investors, complex finances + +Select template (1-4): 3 + +Applying template: Shared Household +Backed up existing rules to data/rules.yaml.backup +✓ Template applied successfully! + +Next steps: +1. Review data/rules.yaml and customize for your needs +2. Update merchant patterns for your region +3. Adjust account names to match your PocketSmith setup +4. Run: /agent-smith-categorize --mode=dry-run to test +``` + +**Programmatic usage:** + +```python +from scripts.setup.template_selector import TemplateSelector + +selector = TemplateSelector() + +# List templates +templates = selector.list_templates() +for key, info in templates.items(): + print(f"{info['name']}: {info['description']}") + +# Apply template +selector.apply_template("shared-household", backup=True) +``` + +### Customizing Templates + +After applying a template: + +1. **Update merchant patterns** for your region: + ```yaml + # Template (Australian) + patterns: [WOOLWORTHS, COLES, ALDI] + + # Customize (US) + patterns: [KROGER, SAFEWAY, WHOLE FOODS] + ``` + +2. **Adjust account names** to match your PocketSmith: + ```yaml + # Template + accounts: [Shared Bills, Joint Account] + + # Your setup + accounts: [Joint Checking, Household Card] + ``` + +3. **Add your specific categories**: + ```yaml + # Add new rules + - type: category + name: Pet Expenses + patterns: [VET, PET STORE, PETBARN] + category: Pets > Veterinary + confidence: 90 + ``` + +4. **Fine-tune confidence scores** based on your data: + ```yaml + # Start conservative + confidence: 70 + + # After validation, increase + confidence: 90 + ``` + +## Migration Guide + +### From Platform Rules to Unified YAML + +If you have existing platform rules created via the PocketSmith API, you can migrate them to the unified YAML format. + +**See:** [Platform to Local Rules Migration Guide](platform-to-local-migration.md) + +**Quick summary:** + +1. Export platform rules to JSON +2. Convert to unified YAML format +3. Test with dry run +4. Disable platform rules (keep for backup) +5. Enable unified rules + +**Migration script:** + +```bash +uv run python scripts/migrations/migrate_platform_to_local.py \ + --output=data/rules.yaml \ + --backup +``` + +### Adding Labels to Existing Rules + +If you have category rules and want to add labels: + +1. Keep all existing category rules as-is +2. Add label rules at the bottom +3. Test with dry run to see labels applied +4. Apply with `--update-strategy=skip_existing` to avoid re-categorizing + +**Example:** + +```yaml +# Existing category rules (don't change) +- type: category + name: WOOLWORTHS → Groceries + patterns: [WOOLWORTHS] + category: Groceries + confidence: 95 + +# NEW: Add label rules +- type: label + name: Essential Spending + when: + categories: [Groceries] + labels: [Essential, Needs] + +- type: label + name: Large Grocery Trip + when: + categories: [Groceries] + amount_operator: ">" + amount_value: 150 + labels: [Large Purchase] +``` + +Run with: +```bash +uv run python scripts/operations/batch_categorize.py \ + --mode=apply \ + --update-strategy=skip_existing \ + --period=2025-11 +``` + +This will: +- Skip already categorized transactions (no re-categorization) +- Apply new labels to all transactions (even already categorized ones) + +## Troubleshooting + +### Rule Not Matching + +**Symptom:** Rule should match but doesn't. + +**Check:** + +1. **Pattern case sensitivity** - Patterns are case-insensitive, but spacing matters: + ```yaml + # Won't match "UBEREATS" (no space) + patterns: [UBER EATS] + + # Better: account for variations + patterns: [UBER EATS, UBEREATS] + ``` + +2. **Exclusion patterns blocking** - Check if an exclusion is preventing the match: + ```yaml + - type: category + patterns: [UBER] + exclude_patterns: [UBER EATS, MEDICAL] # Blocks "UBER MEDICAL" + category: Transport + ``` + +3. **Account filter too restrictive** - Transaction might be in a different account: + ```yaml + # Only matches transactions in "Personal" account + accounts: [Personal] + + # Check transaction's actual account name + ``` + +4. **Amount condition incorrect** - Verify the amount operator and value: + ```yaml + amount_operator: ">" + amount_value: 100 + # Won't match transactions ≤ $100 + ``` + +5. **Rule order** - A previous rule might have matched first (short-circuit): + ```yaml + # General rule matches first! + - patterns: [UBER] + category: Transport + + # Specific rule never reached + - patterns: [UBER EATS] + category: Dining Out # Dead code! + ``` + +**Debug with test script:** + +```bash +# Test specific payee +uv run python scripts/operations/test_rules.py \ + --payee="EXACT PAYEE NAME" \ + --account="Account Name" \ + --amount=127.50 \ + --debug +``` + +**Output:** + +``` +Testing transaction: + Payee: EXACT PAYEE NAME + Account: Account Name + Amount: $127.50 + +Checking category rules... + ✗ Rule 1 "WOOLWORTHS → Groceries": Pattern mismatch + ✗ Rule 2 "UBER → Transport": Pattern mismatch + ✗ Rule 3 "CAFE → Dining Out": Pattern mismatch + +No category match found. + +Checking label rules... + (skipped - no category assigned) + +Result: No categorization +``` + +### Multiple Rules Matching + +**Symptom:** Worried about multiple rules matching the same transaction. + +**This is expected!** Category rules use short-circuit (first match wins), label rules accumulate all matches. + +**For category rules:** + +```yaml +# Only the FIRST matching rule applies +- patterns: [UBER EATS] + category: Dining Out + # ✓ This matches UBER EATS + +- patterns: [UBER] + category: Transport + # ✗ Never reached for UBER EATS (already matched above) +``` + +**For label rules:** + +```yaml +# ALL matching rules apply (additive) +- type: label + when: + categories: [Groceries] + labels: [Essential] + # ✓ Matches + +- type: label + when: + amount_operator: ">" + amount_value: 100 + labels: [Large Purchase] + # ✓ Also matches + +# Result: [Essential, Large Purchase] +``` + +**Fix unwanted category matches** by adjusting rule order or using exclusions. + +**Control label accumulation** by making conditions more specific: + +```yaml +# Too broad - applies to ALL transactions +- type: label + when: + amount_operator: ">" + amount_value: 0 + labels: [Has Amount] # Not useful! + +# Better - specific categories only +- type: label + when: + categories: [Groceries, Dining Out] + amount_operator: ">" + amount_value: 100 + labels: [Large Food Purchase] +``` + +### Labels Not Applying + +**Symptom:** Label rule should match but labels aren't applied. + +**Check:** + +1. **Category must be assigned first** - Labels depend on Phase 1 categorization: + ```yaml + # Label requires category "Groceries" + - type: label + when: + categories: [Groceries] + labels: [Essential] + + # But transaction wasn't categorized in Phase 1 + # → Label rule won't match + ``` + + **Fix:** Ensure a category rule matches the transaction first. + +2. **When conditions too restrictive** - All conditions must match (AND logic): + ```yaml + - type: label + when: + categories: [Groceries] # Must match + accounts: [Shared Bills] # AND must match + amount_operator: ">" # AND must match + amount_value: 100 + labels: [Large Shared Grocery] + + # Won't match if ANY condition fails + ``` + +3. **Uncategorized flag incorrect** - Can't combine with other conditions: + ```yaml + # This won't work as expected + - type: label + when: + uncategorized: true + categories: [Groceries] # Contradiction! Can't be both uncategorized and have a category + labels: [Invalid] + ``` + + **Fix:** Use `uncategorized: true` alone or with accounts/amount only. + +4. **Labels can't check labels** - You can't reference other labels in conditions: + ```yaml + # This WON'T work - no way to check existing labels + - type: label + when: + labels: [Tax Deductible] # Not supported! + amount_operator: ">" + amount_value: 300 + labels: [Substantiation Required] + ``` + + **Fix:** Use categories or accounts as conditions instead. + +**Debug:** + +```bash +uv run python scripts/operations/test_rules.py \ + --payee="WOOLWORTHS" \ + --account="Shared Bills" \ + --amount=127.50 \ + --category="Groceries" \ + --debug +``` + +### Confidence Scores Unclear + +**Symptom:** Not sure what confidence score to use. + +**Guidelines:** + +| Confidence | When to Use | Example | +|------------|-------------|---------| +| 95-100% | Exact merchant match, no ambiguity | WOOLWORTHS → Groceries | +| 85-94% | Very likely but minor ambiguity | AMAZON → Shopping (could be many subcategories) | +| 75-84% | Likely but context-dependent | UBER → Transport (unless UBER EATS) | +| 70-74% | Moderate confidence, needs validation | Generic patterns like "MARKET" | +| < 70% | Low confidence, probably shouldn't auto-apply | Broad patterns | + +**Smart mode thresholds:** +- ≥ 90%: Auto-apply +- 70-89%: Ask user (with LLM validation) +- < 70%: Skip + +**Start high (95%), reduce if:** +- LLM frequently suggests different category +- User frequently overrides +- Pattern matches too broadly + +### LLM Not Being Used + +**Symptom:** Expected LLM fallback but it's not happening. + +**Possible causes:** + +1. **Rule matched** - LLM only used when NO rule matches: + ``` + Transaction: ACME WIDGETS + Rule match: "Generic Business" pattern [WIDGETS] (75%) + → Rule applied, LLM not needed + ``` + + **Fix:** Remove overly broad rules if you want LLM to handle edge cases. + +2. **Categories not provided** - LLM needs category list: + ```python + workflow.categorize_transaction( + transaction=txn, + available_categories=None # ← LLM can't suggest without categories! + ) + ``` + + **Fix:** Pass `available_categories` from PocketSmith API. + +3. **Conservative mode + low confidence** - Conservative never auto-applies: + ``` + Mode: Conservative + LLM suggests: Business Supplies (85%) + → Asks user (doesn't auto-apply) + ``` + + This is expected! Conservative always asks. + +### Performance Issues + +**Symptom:** Batch categorization is slow with many rules. + +**Optimizations:** + +1. **Reduce rule count** - Consolidate similar patterns: + ```yaml + # Before: 3 rules + - patterns: [WOOLWORTHS] + category: Groceries + - patterns: [COLES] + category: Groceries + - patterns: [ALDI] + category: Groceries + + # After: 1 rule + - patterns: [WOOLWORTHS, COLES, ALDI] + category: Groceries + ``` + +2. **Use account filters** - Skip irrelevant transactions early: + ```yaml + # Check account BEFORE pattern matching + - patterns: [WORK PATTERN] + accounts: [Work Credit Card] # Skips 90% of transactions + category: Work Expenses + ``` + +3. **Order by frequency** - Put most common rules first: + ```yaml + # Most frequent transaction (groceries) - check first + - patterns: [WOOLWORTHS, COLES] + category: Groceries + + # Less frequent - check later + - patterns: [RARE MERCHANT] + category: Rare Category + ``` + +4. **Limit batch size** - Process in smaller chunks: + ```bash + # Instead of processing all at once + uv run python scripts/operations/batch_categorize.py --period=2025 + + # Process month by month + uv run python scripts/operations/batch_categorize.py --period=2025-01 + uv run python scripts/operations/batch_categorize.py --period=2025-02 + # etc. + ``` + +## Examples + +See `docs/examples/` for complete example YAML files: + +- **basic-rules.yaml** - Simple category and label rules +- **advanced-patterns.yaml** - Complex rules with exclusions, amounts, accounts +- **household-workflow.yaml** - Complete shared household setup +- **tax-deductible.yaml** - Tax optimization rules with ATO codes +- **migration-example.yaml** - Migrated from platform rules + +## Further Reading + +- **[Platform to Local Migration Guide](platform-to-local-migration.md)** - Migrate existing platform rules to unified YAML +- **[Backup and Restore Guide](backup-and-restore-guide.md)** - Smart backup system with activity-specific rollbacks +- **[Health Check Guide](health-check-guide.md)** - PocketSmith setup health evaluation +- **[Design Document](../design/2025-11-20-agent-smith-design.md)** - Complete Agent Smith architecture + +## Support + +For questions or issues: +1. Check this guide's troubleshooting section +2. Review example files in `docs/examples/` +3. Check template files in `data/templates/` +4. Refer to design documentation +5. Create an issue in the repository + +--- + +**Last Updated:** 2025-11-22 +**Version:** 1.0.0