caucus 0.2.0__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. caucus-0.2.2/.github/workflows/evidence-snapshot.yml +73 -0
  2. {caucus-0.2.0 → caucus-0.2.2}/PKG-INFO +1 -1
  3. {caucus-0.2.0 → caucus-0.2.2}/config.example.yaml +11 -2
  4. {caucus-0.2.0 → caucus-0.2.2}/examples/trading-robinhood/README.md +27 -11
  5. caucus-0.2.2/examples/trading-robinhood/com.example.caucus.plist +25 -0
  6. caucus-0.2.2/examples/trading-robinhood/config.yaml +72 -0
  7. caucus-0.2.2/examples/trading-robinhood/news_evidence.py +64 -0
  8. caucus-0.2.2/examples/trading-robinhood/run-caucus.sh +24 -0
  9. {caucus-0.2.0 → caucus-0.2.2}/pyproject.toml +1 -1
  10. {caucus-0.2.0 → caucus-0.2.2}/src/caucus/__init__.py +1 -1
  11. {caucus-0.2.0 → caucus-0.2.2}/src/caucus/cli.py +11 -11
  12. {caucus-0.2.0 → caucus-0.2.2}/src/caucus/config.py +35 -2
  13. caucus-0.2.2/src/caucus/notify.py +66 -0
  14. {caucus-0.2.0 → caucus-0.2.2}/tests/test_briefing.py +3 -1
  15. caucus-0.2.2/tests/test_notify.py +111 -0
  16. {caucus-0.2.0 → caucus-0.2.2}/uv.lock +1 -1
  17. caucus-0.2.0/examples/trading-robinhood/config.yaml +0 -39
  18. {caucus-0.2.0 → caucus-0.2.2}/.github/codex/prompts/review.md +0 -0
  19. {caucus-0.2.0 → caucus-0.2.2}/.github/codex/review-config.json +0 -0
  20. {caucus-0.2.0 → caucus-0.2.2}/.github/codex/review-rules.md +0 -0
  21. {caucus-0.2.0 → caucus-0.2.2}/.github/codex/scripts/build-review-prompt.mjs +0 -0
  22. {caucus-0.2.0 → caucus-0.2.2}/.github/codex/scripts/normalize-review-output.mjs +0 -0
  23. {caucus-0.2.0 → caucus-0.2.2}/.github/codex/scripts/post-review.cjs +0 -0
  24. {caucus-0.2.0 → caucus-0.2.2}/.github/pull_request_template.md +0 -0
  25. {caucus-0.2.0 → caucus-0.2.2}/.github/workflows/ci.yml +0 -0
  26. {caucus-0.2.0 → caucus-0.2.2}/.github/workflows/codex-review.yml +0 -0
  27. {caucus-0.2.0 → caucus-0.2.2}/.github/workflows/keep-codex-auth-fresh.yml +0 -0
  28. {caucus-0.2.0 → caucus-0.2.2}/.github/workflows/release.yml +0 -0
  29. {caucus-0.2.0 → caucus-0.2.2}/.gitignore +0 -0
  30. {caucus-0.2.0 → caucus-0.2.2}/AGENT_SETUP.md +0 -0
  31. {caucus-0.2.0 → caucus-0.2.2}/DISCLAIMER.md +0 -0
  32. {caucus-0.2.0 → caucus-0.2.2}/LICENSE +0 -0
  33. {caucus-0.2.0 → caucus-0.2.2}/README.md +0 -0
  34. {caucus-0.2.0 → caucus-0.2.2}/SPEC.md +0 -0
  35. {caucus-0.2.0 → caucus-0.2.2}/examples/trading-robinhood/evidence.sample.json +0 -0
  36. {caucus-0.2.0 → caucus-0.2.2}/examples/trading-robinhood/import_campaigns.py +0 -0
  37. {caucus-0.2.0 → caucus-0.2.2}/examples/trading-robinhood/mcp.example.json +0 -0
  38. {caucus-0.2.0 → caucus-0.2.2}/src/caucus/backends.py +0 -0
  39. {caucus-0.2.0 → caucus-0.2.2}/src/caucus/briefing.py +0 -0
  40. {caucus-0.2.0 → caucus-0.2.2}/src/caucus/engine.py +0 -0
  41. {caucus-0.2.0 → caucus-0.2.2}/src/caucus/evidence.py +0 -0
  42. {caucus-0.2.0 → caucus-0.2.2}/src/caucus/intents.py +0 -0
  43. {caucus-0.2.0 → caucus-0.2.2}/src/caucus/record.py +0 -0
  44. {caucus-0.2.0 → caucus-0.2.2}/tests/test_cli.py +0 -0
  45. {caucus-0.2.0 → caucus-0.2.2}/tests/test_config.py +0 -0
  46. {caucus-0.2.0 → caucus-0.2.2}/tests/test_engine.py +0 -0
  47. {caucus-0.2.0 → caucus-0.2.2}/tests/test_evidence.py +0 -0
  48. {caucus-0.2.0 → caucus-0.2.2}/tests/test_intents.py +0 -0
  49. {caucus-0.2.0 → caucus-0.2.2}/tests/test_record.py +0 -0
@@ -0,0 +1,73 @@
1
+ name: Evidence snapshot
2
+
3
+ # GitHub's traffic API retains only 14 days of views/clones — this weekly
4
+ # snapshot preserves adoption history (stars, forks, traffic, referrers, PyPI
5
+ # downloads) as append-only JSONL on the 'evidence' branch.
6
+
7
+ on:
8
+ schedule:
9
+ - cron: "0 8 * * 1"
10
+ workflow_dispatch:
11
+
12
+ permissions:
13
+ contents: write
14
+
15
+ jobs:
16
+ snapshot:
17
+ name: Capture adoption metrics
18
+ runs-on: ubuntu-latest
19
+ timeout-minutes: 10
20
+ steps:
21
+ - name: Checkout evidence branch (create if absent)
22
+ uses: actions/checkout@v5
23
+ with:
24
+ ref: main
25
+ fetch-depth: 1
26
+
27
+ - name: Switch to evidence branch
28
+ shell: bash
29
+ run: |
30
+ if git fetch origin evidence:evidence 2>/dev/null; then
31
+ git checkout evidence
32
+ else
33
+ git checkout --orphan evidence
34
+ git rm -rfq . 2>/dev/null || true
35
+ fi
36
+
37
+ - name: Capture snapshot
38
+ shell: bash
39
+ env:
40
+ GH_TOKEN: ${{ github.token }}
41
+ run: |
42
+ repo="$GITHUB_REPOSITORY"
43
+ date=$(date -u +%Y-%m-%d)
44
+ repo_json=$(gh api "repos/$repo")
45
+ views=$(gh api "repos/$repo/traffic/views" 2>/dev/null || echo '{}')
46
+ clones=$(gh api "repos/$repo/traffic/clones" 2>/dev/null || echo '{}')
47
+ referrers=$(gh api "repos/$repo/traffic/popular/referrers" 2>/dev/null || echo '[]')
48
+ pypi=$(curl -fsS "https://pypistats.org/api/packages/caucus/recent" 2>/dev/null || echo '{}')
49
+ jq -cn \
50
+ --arg date "$date" \
51
+ --argjson repo "$repo_json" \
52
+ --argjson views "$views" \
53
+ --argjson clones "$clones" \
54
+ --argjson referrers "$referrers" \
55
+ --argjson pypi "$pypi" \
56
+ '{date: $date,
57
+ stars: $repo.stargazers_count,
58
+ forks: $repo.forks_count,
59
+ open_issues: $repo.open_issues_count,
60
+ views: {count: $views.count, uniques: $views.uniques},
61
+ clones: {count: $clones.count, uniques: $clones.uniques},
62
+ referrers: $referrers,
63
+ pypi_recent: $pypi.data}' >> adoption.jsonl
64
+ tail -1 adoption.jsonl
65
+
66
+ - name: Commit snapshot
67
+ shell: bash
68
+ run: |
69
+ git config user.name "github-actions[bot]"
70
+ git config user.email "github-actions[bot]@users.noreply.github.com"
71
+ git add adoption.jsonl
72
+ git commit -m "Evidence snapshot $(date -u +%Y-%m-%d)"
73
+ git push origin evidence
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: caucus
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Your AI agents, deliberating on the record. MCP-grounded multi-agent consensus with recorded dissent and an auditable decision log.
5
5
  Project-URL: Repository, https://github.com/srinath-jukanti/caucus
6
6
  Author: Srinath Jukanti
@@ -46,5 +46,14 @@ panel:
46
46
  # - "Which open intent, if any, is due for action today?"
47
47
  # - "Any risks that warrant deviating from the standing plans?"
48
48
 
49
- # Delivery: run after the briefing renders, with the markdown path as argument.
50
- # notify_command: bash send_briefing.sh
49
+ # Delivery after the briefing renders. Email credentials come from the NAMED
50
+ # environment variables — never put secrets in this file.
51
+ # notify:
52
+ # type: email # Gmail-friendly SMTP defaults
53
+ # to: you@example.com
54
+ # address_env: GMAIL_ADDRESS # env var holding the sending address
55
+ # password_env: GMAIL_APP_PASSWORD
56
+ # ...or run anything executable with the briefing path as its argument:
57
+ # notify:
58
+ # type: command
59
+ # command: bash send_briefing.sh
@@ -30,22 +30,38 @@ The sample evidence is fictional. The default backend is the locally
30
30
  authenticated Claude Code CLI; add `--backend openai --model llama3.1
31
31
  --base-url http://localhost:11434/v1` to run fully local via Ollama.
32
32
 
33
- ## Live — ground the panel in your broker
33
+ ## Live — the full reference deployment, step by step
34
34
 
35
- 1. Copy `mcp.example.json` to `mcp.json` and complete authentication per your
36
- MCP provider's documentation (for Robinhood, the agentic trading MCP).
37
- 2. Copy `config.yaml` from this directory to the repository root (it is
38
- gitignored there) and adjust the watchlist subjects to your own.
39
- 3. Deliberate:
35
+ Everything below is configuration; no code changes are required.
36
+
37
+ 1. **Install**: `uv tool install caucus` (from PyPI).
38
+ 2. **Broker MCP**: copy `mcp.example.json` to `mcp.json`; run one interactive
39
+ `claude` session with it to complete the provider's authentication.
40
+ 3. **Config**: copy `config.yaml` and `news_evidence.py` from this directory
41
+ into your working directory; set `notify.to` to your address and export
42
+ `GMAIL_ADDRESS`/`GMAIL_APP_PASSWORD` (a Gmail app password).
43
+ 4. **Standing plans**: record your cadenced builds/trims and trigger rules —
44
+ they are injected into every deliberation as evidence:
40
45
 
41
46
  ```bash
42
- uv run caucus deliberate "Trim the QQQ position toward its target this week?"
47
+ caucus intents add "ACME build" --direction build --target 5% \
48
+ --pacing "weekly on dips" --cadence-days 7
49
+ caucus intents add "XYZ exit at breakeven" --direction trim \
50
+ --target "exit full position" --notes "sell all at cost basis 114.94"
43
51
  ```
44
52
 
45
- Each analyst can now call the allowed read-only tools quotes, historicals,
46
- portfolio state and cite what it fetched as evidence. Tool output is
47
- covered by Caucus's system-level data-not-instructions guard; only
48
- **read-only** tools are allowed in this example by design.
53
+ 5. **Run**: `caucus briefing` the agenda's four standing questions are
54
+ deliberated in order, the briefing is rendered and emailed, and every
55
+ decision (with dissent) lands in the hash-chained log.
56
+ 6. **Schedule**: `mkdir -p ~/caucus-live/logs` first (launchd opens its log
57
+ path before the script runs), then adapt `run-caucus.sh` (secrets from an
58
+ env file) and either the launchd template `com.example.caucus.plist`
59
+ (macOS) or the cron line in its comments (Linux).
60
+
61
+ Each analyst calls the allowed read-only tools — quotes, historicals,
62
+ portfolio, option chains, scans — and cites what it fetched as evidence.
63
+ Tool output is covered by Caucus's system-level data-not-instructions guard;
64
+ only **read-only** tools are allowed in this example by design.
49
65
 
50
66
  ## Guardrails carried over from the reference system
51
67
 
@@ -0,0 +1,25 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <!-- launchd template (macOS): copy to ~/Library/LaunchAgents/com.example.caucus.plist,
4
+ adjust the script path and times, then:
5
+ launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.example.caucus.plist
6
+ On Linux, use cron instead:
7
+ 15 8,14 * * 1-5 CAUCUS_DIR=$HOME/caucus-live bash $HOME/caucus-live/run-caucus.sh -->
8
+ <plist version="1.0">
9
+ <dict>
10
+ <key>Label</key>
11
+ <string>com.example.caucus</string>
12
+ <key>ProgramArguments</key>
13
+ <array>
14
+ <string>/bin/bash</string>
15
+ <string>/Users/YOURUSER/caucus-live/run-caucus.sh</string>
16
+ </array>
17
+ <key>StartCalendarInterval</key>
18
+ <array>
19
+ <dict><key>Hour</key><integer>8</integer><key>Minute</key><integer>15</integer></dict>
20
+ <dict><key>Hour</key><integer>14</integer><key>Minute</key><integer>45</integer></dict>
21
+ </array>
22
+ <key>StandardErrorPath</key>
23
+ <string>/Users/YOURUSER/caucus-live/logs/launchd.err</string>
24
+ </dict>
25
+ </plist>
@@ -0,0 +1,72 @@
1
+ # Trading example configuration — a faithful copy of the reference deployment.
2
+ # Copy to your working directory as config.yaml; requires mcp.json (see
3
+ # mcp.example.json) for live broker grounding.
4
+
5
+ log: decisions.jsonl
6
+
7
+ # Standing plans (cadenced builds/trims, trigger rules) — create with
8
+ # 'caucus intents add', e.g.:
9
+ # caucus intents add "ACME build" --direction build --target 5% \
10
+ # --pacing "weekly on dips" --cadence-days 7
11
+ intents: intents.db
12
+
13
+ evidence_sources:
14
+ # Keyless news/macro feeds (Fed press RSS, Hacker News, Polymarket);
15
+ # per-feed tolerant — a dead feed becomes a note, never a blocked briefing.
16
+ - name: news-macro
17
+ command: python3 news_evidence.py
18
+ timeout_seconds: 60
19
+ # Pattern for deterministic indicators: compute MAs/momentum/regime in
20
+ # plain code from your own price cache and print JSON evidence items —
21
+ # the panel reasons over numbers it did not produce.
22
+ # - name: quant-snapshot
23
+ # command: python3 snapshot_evidence.py
24
+ # timeout_seconds: 30
25
+
26
+ backend:
27
+ type: claude
28
+ mcp_config: mcp.json
29
+ # Read-only tools ONLY — this deployment deliberates and records, never trades.
30
+ allowed_tools:
31
+ - mcp__robinhood-trading__get_equity_quotes
32
+ - mcp__robinhood-trading__get_equity_historicals
33
+ - mcp__robinhood-trading__get_portfolio
34
+ - mcp__robinhood-trading__get_equity_positions
35
+ - mcp__robinhood-trading__get_index_quotes
36
+ - mcp__robinhood-trading__get_option_chains
37
+ - mcp__robinhood-trading__get_option_instruments
38
+ - mcp__robinhood-trading__get_option_quotes
39
+ - mcp__robinhood-trading__get_scans
40
+ - mcp__robinhood-trading__run_scan
41
+ - mcp__robinhood-trading__get_earnings_calendar
42
+
43
+ panel:
44
+ - name: macro
45
+ charge: >-
46
+ Assess the macro and market regime relevant to the question. Use the
47
+ news/macro evidence and fetch current quotes rather than assuming;
48
+ state which signals support or undermine the proposal.
49
+ - name: momentum
50
+ charge: >-
51
+ Evaluate trend and momentum from recent historicals; judge against
52
+ moving-average position and price behavior, not narrative.
53
+ - name: risk-officer
54
+ charge: >-
55
+ Argue the downside. Quantify what a bad outcome costs given current
56
+ position sizes (fetch them), concentration, and liquidity. Oppose
57
+ anything that breaches prudent sizing or deviates from standing
58
+ intents without strong cause. For options, insist collateral is
59
+ computed from cash plus liquid reserves, never literal cash alone.
60
+
61
+ # The standing questions every 'caucus briefing' run answers, in order.
62
+ agenda:
63
+ - "Given the open intents, live positions, and current prices: which intent, if any, is due for its next action today, and what exactly should be done?"
64
+ - "Does the current market regime, the news, or any position behavior warrant a defensive action (hedge, trim, or pausing an intent) beyond the standing plans?"
65
+ - "Income: is there an attractive cash-secured put or covered call this run? Use live option chains (~30-45 DTE, ~0.25 delta) on names held or gladly owned per the intents; size against available collateral; skip any name within 14 days of earnings."
66
+ - "Opportunity scan: screen today's market movers for at most one new candidate consistent with the intents and regime; drop anything illiquid or junk-quality. If nothing qualifies, say so plainly."
67
+
68
+ # Delivery — Gmail-friendly SMTP; credentials come from the environment
69
+ # variables GMAIL_ADDRESS and GMAIL_APP_PASSWORD (never from this file).
70
+ notify:
71
+ type: email
72
+ to: you@example.com
@@ -0,0 +1,64 @@
1
+ """Evidence source: keyless news/macro feeds, per-feed tolerant.
2
+
3
+ Always exits 0 with valid JSON — a dead feed becomes a note, not a failure,
4
+ so one outage never blocks the briefing.
5
+ """
6
+
7
+ import json
8
+ import re
9
+ import urllib.request
10
+
11
+ ITEMS = []
12
+
13
+
14
+ def fetch(url, timeout=10):
15
+ req = urllib.request.Request(url, headers={"User-Agent": "caucus-evidence/1.0"})
16
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
17
+ return resp.read().decode("utf-8", "replace")
18
+
19
+
20
+ def add(source, ref, content):
21
+ ITEMS.append({"source": source, "ref": str(ref), "content": str(content)[:400]})
22
+
23
+
24
+ try:
25
+ xml = fetch("https://www.federalreserve.gov/feeds/press_all.xml")
26
+ titles = re.findall(r"<title>(.*?)</title>", xml)[1:6]
27
+ dates = re.findall(r"<pubDate>(.*?)</pubDate>", xml)[:5]
28
+ for title, date in zip(titles, dates):
29
+ add("fed-press", date, title)
30
+ except Exception as err:
31
+ add("fed-press", "unavailable", "Fed press feed fetch failed: " + str(err))
32
+
33
+ try:
34
+ hn = json.loads(
35
+ fetch(
36
+ "https://hn.algolia.com/api/v1/search_by_date?query=semiconductor%20OR%20NVDA%20OR%20AI%20chips&tags=story&hitsPerPage=5"
37
+ )
38
+ )
39
+ for hit in hn.get("hits", [])[:5]:
40
+ title = str(hit.get("title"))
41
+ points = str(hit.get("points"))
42
+ add("hackernews", hit.get("created_at", ""), title + " (" + points + " pts)")
43
+ except Exception as err:
44
+ add("hackernews", "unavailable", "HN fetch failed: " + str(err))
45
+
46
+ try:
47
+ markets = json.loads(
48
+ fetch(
49
+ "https://gamma-api.polymarket.com/markets?closed=false&active=true&order=volumeNum&ascending=false&limit=30"
50
+ )
51
+ )
52
+ kept = 0
53
+ for market in markets:
54
+ question = str(market.get("question", ""))
55
+ if kept < 5 and re.search(r"fed|fomc|cpi|inflation|rate", question, re.I):
56
+ prices = str(market.get("outcomePrices"))
57
+ add("polymarket", question[:60], "active market, implied prices " + prices)
58
+ kept += 1
59
+ if kept == 0:
60
+ add("polymarket", "no-matches", "no active Fed/CPI/inflation markets in top 30 by volume")
61
+ except Exception as err:
62
+ add("polymarket", "unavailable", "Polymarket fetch failed: " + str(err))
63
+
64
+ print(json.dumps(ITEMS))
@@ -0,0 +1,24 @@
1
+ #!/bin/bash
2
+ # Headless scheduled Caucus briefing — the reference deployment's launcher.
3
+ # Adjust CAUCUS_DIR and ENVF, then schedule with cron or the launchd template.
4
+ set -uo pipefail
5
+
6
+ CAUCUS_DIR="${CAUCUS_DIR:-$HOME/caucus-live}"
7
+ ENVF="${CAUCUS_ENV_FILE:-$CAUCUS_DIR/.env}"
8
+
9
+ cd "$CAUCUS_DIR" || exit 1
10
+ export PATH="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:$PATH"
11
+
12
+ # Secrets stay in an env file (never in config.yaml): the Claude Code OAuth
13
+ # token for headless runs and the SMTP credentials for the email notifier.
14
+ for var in CLAUDE_CODE_OAUTH_TOKEN GMAIL_ADDRESS GMAIL_APP_PASSWORD; do
15
+ value=$(grep -E "^${var}=" "$ENVF" 2>/dev/null | head -1 | cut -d= -f2-)
16
+ [ -n "$value" ] && export "$var"="$value"
17
+ done
18
+
19
+ mkdir -p logs
20
+ TS=$(date +%Y%m%d-%H%M)
21
+ caucus briefing >> "logs/run-${TS}.log" 2>&1
22
+ RC=$?
23
+ echo "$(date '+%Y-%m-%d %H:%M:%S') rc=${RC}" >> logs/run-history.log
24
+ exit $RC
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "caucus"
3
- version = "0.2.0"
3
+ version = "0.2.2"
4
4
  description = "Your AI agents, deliberating on the record. MCP-grounded multi-agent consensus with recorded dissent and an auditable decision log."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -1,3 +1,3 @@
1
1
  """Caucus — AI agents deliberating on the record."""
2
2
 
3
- __version__ = "0.2.0"
3
+ __version__ = "0.2.2"
@@ -207,16 +207,14 @@ def briefing(
207
207
  ) -> None:
208
208
  """Deliberate every agenda subject from the config and render one briefing.
209
209
 
210
- Writes OUT (markdown) and its .json sibling, then runs the configured
211
- notify_command with the markdown path as its argument — email scripts,
212
- webhooks, anything executable.
210
+ Writes OUT (markdown) and its .json sibling, then delivers it via the
211
+ configured notifier 'email' (SMTP, Gmail-friendly, credentials from
212
+ env vars) or 'command' (any executable, briefing path as argument).
213
213
  """
214
- import shlex
215
- import subprocess
216
-
217
214
  from caucus.briefing import run_agenda
218
215
  from caucus.config import Config, ConfigError
219
216
  from caucus.engine import Deliberation
217
+ from caucus.notify import NotifyError
220
218
 
221
219
  config_path = (
222
220
  config if config else Path("config.yaml") if Path("config.yaml").exists() else None
@@ -247,11 +245,13 @@ def briefing(
247
245
  for record in result.records:
248
246
  typer.echo(f"- {record.subject[:70]} → {record.decision[:90]} ({record.confidence:.0%})")
249
247
 
250
- if loaded.notify_command:
251
- completed = subprocess.run(f"{loaded.notify_command} {shlex.quote(str(out))}", shell=True)
252
- if completed.returncode != 0:
253
- typer.echo(f"notify command exited {completed.returncode}", err=True)
254
- raise typer.Exit(1)
248
+ if loaded.notify is not None:
249
+ subject = f"[Caucus] briefing {result.generated_at[:10]} {len(result.records)} decisions"
250
+ try:
251
+ loaded.notify.send(subject, result.to_markdown(), attachment_path=out)
252
+ except NotifyError as err:
253
+ typer.echo(str(err), err=True)
254
+ raise typer.Exit(1) from err
255
255
  typer.echo("notified")
256
256
 
257
257
 
@@ -14,6 +14,7 @@ import yaml
14
14
  from caucus.backends import Backend, ClaudeCodeBackend, OpenAICompatibleBackend
15
15
  from caucus.engine import DEFAULT_PANEL, Analyst
16
16
  from caucus.evidence import EvidenceSource
17
+ from caucus.notify import CommandNotifier, EmailNotifier
17
18
 
18
19
 
19
20
  class ConfigError(ValueError):
@@ -28,7 +29,7 @@ class Config:
28
29
  intents: Path | None = None
29
30
  evidence_sources: list[EvidenceSource] = field(default_factory=list)
30
31
  agenda: list[str] = field(default_factory=list)
31
- notify_command: str | None = None
32
+ notify: EmailNotifier | CommandNotifier | None = None
32
33
 
33
34
  @classmethod
34
35
  def load(cls, path: Path) -> Config:
@@ -64,10 +65,14 @@ class Config:
64
65
  ):
65
66
  raise ConfigError("'agenda' must be a non-empty list of subject strings")
66
67
  config.agenda = agenda
68
+ if "notify" in raw and "notify_command" in raw:
69
+ raise ConfigError("use either 'notify' or 'notify_command', not both")
70
+ if "notify" in raw:
71
+ config.notify = _build_notifier(raw["notify"])
67
72
  if "notify_command" in raw:
68
73
  if not isinstance(raw["notify_command"], str) or not raw["notify_command"].strip():
69
74
  raise ConfigError("'notify_command' must be a non-empty string")
70
- config.notify_command = raw["notify_command"]
75
+ config.notify = CommandNotifier(command=raw["notify_command"])
71
76
  return config
72
77
 
73
78
 
@@ -100,6 +105,34 @@ def _build_backend(raw: object) -> Backend:
100
105
  raise ConfigError(f"unknown backend type {kind!r} (expected 'claude' or 'openai')")
101
106
 
102
107
 
108
+ def _build_notifier(raw: object) -> EmailNotifier | CommandNotifier:
109
+ if not isinstance(raw, dict):
110
+ raise ConfigError("'notify' must be a mapping with a 'type'")
111
+ kind = raw.get("type")
112
+ if kind == "email":
113
+ to = raw.get("to")
114
+ if not isinstance(to, str) or not to.strip():
115
+ raise ConfigError("email notify requires a string 'to' address")
116
+ options = {}
117
+ for key in ("smtp_host", "address_env", "password_env"):
118
+ if key in raw:
119
+ if not isinstance(raw[key], str) or not raw[key].strip():
120
+ raise ConfigError(f"'{key}' must be a non-empty string")
121
+ options[key] = raw[key]
122
+ if "smtp_port" in raw:
123
+ port = raw["smtp_port"]
124
+ if isinstance(port, bool) or not isinstance(port, int) or not 0 < port < 65536:
125
+ raise ConfigError("'smtp_port' must be a valid port number")
126
+ options["smtp_port"] = port
127
+ return EmailNotifier(to=to, **options)
128
+ if kind == "command":
129
+ command = raw.get("command")
130
+ if not isinstance(command, str) or not command.strip():
131
+ raise ConfigError("command notify requires a string 'command'")
132
+ return CommandNotifier(command=command)
133
+ raise ConfigError(f"unknown notify type {kind!r} (expected 'email' or 'command')")
134
+
135
+
103
136
  def _build_evidence_sources(raw: object) -> list[EvidenceSource]:
104
137
  if not isinstance(raw, list):
105
138
  raise ConfigError("'evidence_sources' must be a list")
@@ -0,0 +1,66 @@
1
+ """Notification: how a finished briefing reaches a human.
2
+
3
+ Config-driven, two kinds:
4
+ - email: SMTP (Gmail-friendly defaults) using stdlib smtplib. Credentials are
5
+ read from environment variables named in the config — never from the config
6
+ itself.
7
+ - command: run any executable with the briefing path as its argument.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import shlex
14
+ import smtplib
15
+ import subprocess
16
+ from dataclasses import dataclass
17
+ from email.mime.text import MIMEText
18
+ from pathlib import Path
19
+
20
+
21
+ class NotifyError(RuntimeError):
22
+ """Raised when a notification cannot be delivered."""
23
+
24
+
25
+ @dataclass
26
+ class EmailNotifier:
27
+ """SMTP delivery; defaults suit a Gmail account with an app password."""
28
+
29
+ to: str
30
+ smtp_host: str = "smtp.gmail.com"
31
+ smtp_port: int = 465
32
+ address_env: str = "GMAIL_ADDRESS"
33
+ password_env: str = "GMAIL_APP_PASSWORD"
34
+ smtp_factory: object | None = None # injectable for tests
35
+
36
+ def send(self, subject: str, body: str, attachment_path: Path | None = None) -> None:
37
+ address = os.environ.get(self.address_env)
38
+ password = os.environ.get(self.password_env)
39
+ if not address or not password:
40
+ raise NotifyError(
41
+ f"email notifier needs ${self.address_env} and ${self.password_env} set"
42
+ )
43
+ message = MIMEText(body, "plain", "utf-8")
44
+ message["Subject"] = subject
45
+ message["From"] = address
46
+ message["To"] = self.to
47
+ factory = self.smtp_factory or smtplib.SMTP_SSL
48
+ try:
49
+ with factory(self.smtp_host, self.smtp_port) as server:
50
+ server.login(address, password)
51
+ server.sendmail(address, [self.to], message.as_string())
52
+ except OSError as err:
53
+ raise NotifyError(f"email delivery failed: {err}") from err
54
+
55
+
56
+ @dataclass
57
+ class CommandNotifier:
58
+ """Runs a user-configured command with the briefing path appended."""
59
+
60
+ command: str
61
+
62
+ def send(self, subject: str, body: str, attachment_path: Path | None = None) -> None:
63
+ target = shlex.quote(str(attachment_path)) if attachment_path else ""
64
+ completed = subprocess.run(f"{self.command} {target}".strip(), shell=True)
65
+ if completed.returncode != 0:
66
+ raise NotifyError(f"notify command exited {completed.returncode}")
@@ -62,7 +62,9 @@ notify_command: bash send_briefing.sh
62
62
  )
63
63
  config = Config.load(path)
64
64
  assert config.agenda == ["Question one?", "Question two?"]
65
- assert config.notify_command == "bash send_briefing.sh"
65
+ from caucus.notify import CommandNotifier
66
+
67
+ assert config.notify == CommandNotifier(command="bash send_briefing.sh")
66
68
 
67
69
 
68
70
  @pytest.mark.parametrize(
@@ -0,0 +1,111 @@
1
+ from types import SimpleNamespace
2
+
3
+ import pytest
4
+
5
+ from caucus.config import Config, ConfigError
6
+ from caucus.notify import CommandNotifier, EmailNotifier, NotifyError
7
+
8
+
9
+ class FakeSMTP:
10
+ """Records logins and sends; usable as a context manager factory."""
11
+
12
+ instances = []
13
+
14
+ def __init__(self, host, port):
15
+ self.host, self.port = host, port
16
+ self.logins, self.sent = [], []
17
+ FakeSMTP.instances.append(self)
18
+
19
+ def __enter__(self):
20
+ return self
21
+
22
+ def __exit__(self, *args):
23
+ return False
24
+
25
+ def login(self, address, password):
26
+ self.logins.append((address, password))
27
+
28
+ def sendmail(self, sender, recipients, message):
29
+ self.sent.append(SimpleNamespace(sender=sender, recipients=recipients, message=message))
30
+
31
+
32
+ @pytest.fixture(autouse=True)
33
+ def reset_fake():
34
+ FakeSMTP.instances = []
35
+
36
+
37
+ def test_email_notifier_sends_via_smtp(monkeypatch):
38
+ monkeypatch.setenv("GMAIL_ADDRESS", "me@example.com")
39
+ monkeypatch.setenv("GMAIL_APP_PASSWORD", "app-pass")
40
+ notifier = EmailNotifier(to="you@example.com", smtp_factory=FakeSMTP)
41
+ notifier.send("subject line", "body text")
42
+ server = FakeSMTP.instances[0]
43
+ assert server.host == "smtp.gmail.com"
44
+ assert server.logins == [("me@example.com", "app-pass")]
45
+ sent = server.sent[0]
46
+ assert sent.recipients == ["you@example.com"]
47
+ assert "subject line" in sent.message
48
+
49
+
50
+ def test_email_notifier_requires_env(monkeypatch):
51
+ monkeypatch.delenv("GMAIL_ADDRESS", raising=False)
52
+ monkeypatch.delenv("GMAIL_APP_PASSWORD", raising=False)
53
+ notifier = EmailNotifier(to="you@example.com", smtp_factory=FakeSMTP)
54
+ with pytest.raises(NotifyError, match="GMAIL_ADDRESS"):
55
+ notifier.send("s", "b")
56
+ assert FakeSMTP.instances == []
57
+
58
+
59
+ def test_command_notifier_runs_and_fails_loudly(tmp_path):
60
+ marker = tmp_path / "ran.txt"
61
+ CommandNotifier(command=f"touch {marker}").send("s", "b")
62
+ assert marker.exists()
63
+ with pytest.raises(NotifyError, match="exited 3"):
64
+ CommandNotifier(command="exit 3").send("s", "b")
65
+
66
+
67
+ def test_config_parses_email_notifier(tmp_path):
68
+ path = tmp_path / "config.yaml"
69
+ path.write_text(
70
+ """
71
+ notify:
72
+ type: email
73
+ to: you@example.com
74
+ address_env: MY_FROM
75
+ password_env: MY_PASS
76
+ smtp_port: 587
77
+ """
78
+ )
79
+ notify = Config.load(path).notify
80
+ assert isinstance(notify, EmailNotifier)
81
+ assert notify.to == "you@example.com"
82
+ assert notify.address_env == "MY_FROM"
83
+ assert notify.smtp_port == 587
84
+
85
+
86
+ def test_config_legacy_notify_command_still_works(tmp_path):
87
+ path = tmp_path / "config.yaml"
88
+ path.write_text("notify_command: bash send.sh\n")
89
+ notify = Config.load(path).notify
90
+ assert isinstance(notify, CommandNotifier)
91
+ assert notify.command == "bash send.sh"
92
+
93
+
94
+ @pytest.mark.parametrize(
95
+ "text",
96
+ [
97
+ "notify: email\n",
98
+ "notify:\n type: email\n",
99
+ "notify:\n type: email\n to: ''\n",
100
+ "notify:\n type: email\n to: a@b.c\n smtp_port: -5\n",
101
+ "notify:\n type: email\n to: a@b.c\n smtp_port: true\n",
102
+ "notify:\n type: command\n",
103
+ "notify:\n type: slack\n",
104
+ "notify:\n type: command\n command: x\nnotify_command: y\n",
105
+ ],
106
+ )
107
+ def test_config_rejects_invalid_notify(tmp_path, text):
108
+ path = tmp_path / "config.yaml"
109
+ path.write_text(text)
110
+ with pytest.raises(ConfigError):
111
+ Config.load(path)
@@ -34,7 +34,7 @@ wheels = [
34
34
 
35
35
  [[package]]
36
36
  name = "caucus"
37
- version = "0.2.0"
37
+ version = "0.2.2"
38
38
  source = { editable = "." }
39
39
  dependencies = [
40
40
  { name = "pyyaml" },
@@ -1,39 +0,0 @@
1
- # Trading example configuration — copy to the repository root as config.yaml.
2
- # Requires mcp.json (see mcp.example.json) for live broker grounding.
3
-
4
- log: decisions.jsonl
5
-
6
- backend:
7
- type: claude
8
- mcp_config: mcp.json
9
- # Read-only tools ONLY — this example deliberates, it never trades.
10
- allowed_tools:
11
- - mcp__robinhood-trading__get_equity_quotes
12
- - mcp__robinhood-trading__get_equity_historicals
13
- - mcp__robinhood-trading__get_portfolio
14
- - mcp__robinhood-trading__get_equity_positions
15
-
16
- panel:
17
- - name: macro
18
- charge: >-
19
- Assess the macro and market regime relevant to the question. Fetch
20
- current quotes and index levels rather than assuming; state which
21
- regime signals support or undermine the proposal.
22
- - name: momentum
23
- charge: >-
24
- Evaluate trend and momentum. Fetch recent historicals; judge the
25
- proposal against moving-average position and recent price behavior,
26
- not narrative.
27
- - name: risk-officer
28
- charge: >-
29
- Argue the downside. Quantify what a bad outcome costs given current
30
- position sizes (fetch them), concentration, and liquidity. Oppose
31
- anything that breaches prudent sizing even if the thesis is good.
32
-
33
- # The standing questions every briefing run answers ('caucus briefing').
34
- agenda:
35
- - "Given the open intents, live positions, and current prices: which intent, if any, is due for its next action today, and what exactly should be done?"
36
- - "Does current market regime or any position's behavior warrant a defensive action (hedge, trim, or pause of an intent) beyond the standing plans?"
37
-
38
- # Delivery hook — receives the rendered briefing path as its argument.
39
- # notify_command: bash /path/to/send_briefing.sh
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes