diff --git a/.env.example b/.env.example index 04c8f010b..b024794c6 100644 --- a/.env.example +++ b/.env.example @@ -3,3 +3,6 @@ # Required for LLM-as-judge evals (bun run test:eval) ANTHROPIC_API_KEY=sk-ant-your-key-here + +# Optional for /hate-driven-development +X_API_BEARER_TOKEN=x-api-bearer-token-here diff --git a/AGENTS.md b/AGENTS.md index d87217453..9a2f1cd8f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,6 +23,7 @@ Skills live in `.agents/skills/`. Invoke them by name (e.g., `/office-hours`). | `/ship` | Run tests, review, push, open PR. One command. | | `/document-release` | Update all docs to match what you just shipped. | | `/retro` | Weekly retro with per-person breakdowns and shipping streaks. | +| `/hate-driven-development` | Scan X for gstack hate, rank the worst posts, and feed Gary breakfast. | | `/browse` | Headless browser — real Chromium, real clicks, ~100ms/command. | | `/setup-browser-cookies` | Import cookies from your real browser for authenticated testing. | | `/careful` | Warn before destructive commands (rm -rf, DROP TABLE, force-push). | diff --git a/README.md b/README.md index 424f36799..b9b0a52fe 100644 --- a/README.md +++ b/README.md @@ -46,11 +46,11 @@ Fork it. Improve it. Make it yours. And if you want to hate on free open source Open Claude Code and paste this. Claude does the rest. -> Install gstack: run **`git clone https://github.com/garrytan/gstack.git ~/.claude/skills/gstack && cd ~/.claude/skills/gstack && ./setup`** then add a "gstack" section to CLAUDE.md that says to use the /browse skill from gstack for all web browsing, never use mcp\_\_claude-in-chrome\_\_\* tools, and lists the available skills: /office-hours, /plan-ceo-review, /plan-eng-review, /plan-design-review, /design-consultation, /review, /ship, /land-and-deploy, /canary, /benchmark, /browse, /qa, /qa-only, /design-review, /setup-browser-cookies, /setup-deploy, /retro, /investigate, /document-release, /codex, /cso, /autoplan, /careful, /freeze, /guard, /unfreeze, /gstack-upgrade. Then ask the user if they also want to add gstack to the current project so teammates get it. +> Install gstack: run **`git clone https://github.com/garrytan/gstack.git ~/.claude/skills/gstack && cd ~/.claude/skills/gstack && ./setup`** then add a "gstack" section to CLAUDE.md that says to use the /browse skill from gstack for all web browsing, never use mcp\_\_claude-in-chrome\_\_\* tools, and lists the available skills: /office-hours, /plan-ceo-review, /plan-eng-review, /plan-design-review, /design-consultation, /review, /ship, /land-and-deploy, /canary, /benchmark, /browse, /qa, /qa-only, /design-review, /setup-browser-cookies, /setup-deploy, /retro, /hate-driven-development, /investigate, /document-release, /codex, /cso, /autoplan, /careful, /freeze, /guard, /unfreeze, /gstack-upgrade. Then ask the user if they also want to add gstack to the current project so teammates get it. ### Step 2: Add to your repo so teammates get it (optional) -> Add gstack to this project: run **`cp -Rf ~/.claude/skills/gstack .claude/skills/gstack && rm -rf .claude/skills/gstack/.git && cd .claude/skills/gstack && ./setup`** then add a "gstack" section to this project's CLAUDE.md that says to use the /browse skill from gstack for all web browsing, never use mcp\_\_claude-in-chrome\_\_\* tools, lists the available skills: /office-hours, /plan-ceo-review, /plan-eng-review, /plan-design-review, /design-consultation, /review, /ship, /land-and-deploy, /canary, /benchmark, /browse, /qa, /qa-only, /design-review, /setup-browser-cookies, /setup-deploy, /retro, /investigate, /document-release, /codex, /cso, /careful, /freeze, /guard, /unfreeze, /gstack-upgrade, and tells Claude that if gstack skills aren't working, run `cd .claude/skills/gstack && ./setup` to build the binary and register skills. +> Add gstack to this project: run **`cp -Rf ~/.claude/skills/gstack .claude/skills/gstack && rm -rf .claude/skills/gstack/.git && cd .claude/skills/gstack && ./setup`** then add a "gstack" section to this project's CLAUDE.md that says to use the /browse skill from gstack for all web browsing, never use mcp\_\_claude-in-chrome\_\_\* tools, lists the available skills: /office-hours, /plan-ceo-review, /plan-eng-review, /plan-design-review, /design-consultation, /review, /ship, /land-and-deploy, /canary, /benchmark, /browse, /qa, /qa-only, /design-review, /setup-browser-cookies, /setup-deploy, /retro, /hate-driven-development, /investigate, /document-release, /codex, /cso, /careful, /freeze, /guard, /unfreeze, /gstack-upgrade, and tells Claude that if gstack skills aren't working, run `cd .claude/skills/gstack && ./setup` to build the binary and register skills. Real files get committed to your repo (not a submodule), so `git clone` just works. Everything lives inside `.claude/`. Nothing touches your PATH or runs in the background. @@ -85,7 +85,7 @@ git clone https://github.com/garrytan/gstack.git ~/gstack cd ~/gstack && ./setup --host auto ``` -For Codex-compatible hosts, setup now supports both repo-local installs from `.agents/skills/gstack` and user-global installs from `~/.codex/skills/gstack`. All 28 skills work across all supported agents. Hook-based safety skills (careful, freeze, guard) use inline safety advisory prose on non-Claude hosts. +For Codex-compatible hosts, setup now supports both repo-local installs from `.agents/skills/gstack` and user-global installs from `~/.codex/skills/gstack`. All 29 skills work across all supported agents. Hook-based safety skills (careful, freeze, guard) use inline safety advisory prose on non-Claude hosts. ## See it work @@ -157,6 +157,7 @@ Each skill feeds into the next. `/office-hours` writes a design doc that `/plan- | `/benchmark` | **Performance Engineer** | Baseline page load times, Core Web Vitals, and resource sizes. Compare before/after on every PR. | | `/document-release` | **Technical Writer** | Update all project docs to match what you just shipped. Catches stale READMEs automatically. | | `/retro` | **Eng Manager** | Team-aware weekly retro. Per-person breakdowns, shipping streaks, test health trends, growth opportunities. `/retro global` runs across all your projects and AI tools (Claude Code, Codex, Gemini). | +| `/hate-driven-development` | **Chief Hater Officer** | Scans X for fresh gstack mentions, ranks the nastiest ones with a deterministic score, and serves Gary a breakfast board of actionable complaints vs empty-calorie snark. | | `/browse` | **QA Engineer** | Real Chromium browser, real clicks, real screenshots. ~100ms per command. | | `/setup-browser-cookies` | **Session Manager** | Import cookies from your real browser (Chrome, Arc, Brave, Edge) into the headless session. Test authenticated pages. | | `/autoplan` | **Review Pipeline** | One command, fully reviewed plan. Runs CEO → design → eng review automatically with encoded decision principles. Surfaces only taste decisions for your approval. | @@ -234,6 +235,7 @@ Use /browse from gstack for all web browsing. Never use mcp__claude-in-chrome__* Available skills: /office-hours, /plan-ceo-review, /plan-eng-review, /plan-design-review, /design-consultation, /review, /ship, /land-and-deploy, /canary, /benchmark, /browse, /qa, /qa-only, /design-review, /setup-browser-cookies, /setup-deploy, /retro, +/hate-driven-development, /investigate, /document-release, /codex, /cso, /autoplan, /careful, /freeze, /guard, /unfreeze, /gstack-upgrade. ``` diff --git a/docs/skills.md b/docs/skills.md index afbac0d2d..362826232 100644 --- a/docs/skills.md +++ b/docs/skills.md @@ -18,6 +18,7 @@ Detailed guides for every gstack skill — philosophy, workflow, and examples. | [`/cso`](#cso) | **Chief Security Officer** | OWASP Top 10 + STRIDE threat modeling security audit. Scans for injection, auth, crypto, and access control issues. | | [`/document-release`](#document-release) | **Technical Writer** | Update all project docs to match what you just shipped. Catches stale READMEs automatically. | | [`/retro`](#retro) | **Eng Manager** | Team-aware weekly retro. Per-person breakdowns, shipping streaks, test health trends, growth opportunities. | +| [`/hate-driven-development`](#hate-driven-development) | **Chief Hater Officer** | Deterministic X mention triage. Finds the nastiest fresh gstack posts, separates actionable complaints from empty-calorie snark, and feeds Gary breakfast. | | [`/browse`](#browse) | **QA Engineer** | Give the agent eyes. Real Chromium browser, real clicks, real screenshots. ~100ms per command. | | [`/setup-browser-cookies`](#setup-browser-cookies) | **Session Manager** | Import cookies from your real browser (Chrome, Arc, Brave, Edge) into the headless session. Test authenticated pages. | | | | | @@ -609,6 +610,27 @@ It saves a JSON snapshot to `.context/retros/` so the next run can show trends. --- +## `/hate-driven-development` + +This one is a joke, but it still has to be useful. + +The workflow is deliberately deterministic: poll X recent search for fresh `gstack` +mentions, use a fixed lexical weighting table to score negativity, then split the +results into two buckets: + +- **Actionable protein** — "install is broken", "docs are confusing", "setup fails" +- **Empty calories** — drive-by snark, mockery, vague doomposting + +It persists the `newest_id` from the last successful run, so the default behavior is +"show me only what happened since breakfast." No LLM sentiment pass. No vibes. Same +input, same ranking. + +Why that matters: if this were model-scored, the joke would be cute once and useless +forever. With a fixed rule table you can actually compare runs, keep receipts, and treat +negative feedback as a noisy but real product signal. + +--- + ## `/browse` This is my **QA engineer mode**. diff --git a/hate-driven-development/SKILL.md b/hate-driven-development/SKILL.md new file mode 100644 index 000000000..ea173e858 --- /dev/null +++ b/hate-driven-development/SKILL.md @@ -0,0 +1,408 @@ +--- +name: hate-driven-development +version: 1.0.0 +description: | + Deterministic X mention triage for gstack. Polls recent posts mentioning + gstack, ranks the nastiest ones with a fixed lexical score, and serves Gary + a "breakfast" report with links, receipts, and actionable complaints. + Default behavior only scans since the last successful run by persisting the + newest seen post ID. Use when: "hate driven development", "what are people + saying on X", "scan gstack mentions", "feed Gary breakfast", "find the + haters", or "find the worst tweets about gstack". +allowed-tools: + - Bash + - Read +--- + + + +## Preamble (run first) + +```bash +_UPD=$(~/.claude/skills/gstack/bin/gstack-update-check 2>/dev/null || .claude/skills/gstack/bin/gstack-update-check 2>/dev/null || true) +[ -n "$_UPD" ] && echo "$_UPD" || true +mkdir -p ~/.gstack/sessions +touch ~/.gstack/sessions/"$PPID" +_SESSIONS=$(find ~/.gstack/sessions -mmin -120 -type f 2>/dev/null | wc -l | tr -d ' ') +find ~/.gstack/sessions -mmin +120 -type f -delete 2>/dev/null || true +_CONTRIB=$(~/.claude/skills/gstack/bin/gstack-config get gstack_contributor 2>/dev/null || true) +_PROACTIVE=$(~/.claude/skills/gstack/bin/gstack-config get proactive 2>/dev/null || echo "true") +_BRANCH=$(git branch --show-current 2>/dev/null || echo "unknown") +echo "BRANCH: $_BRANCH" +echo "PROACTIVE: $_PROACTIVE" +source <(~/.claude/skills/gstack/bin/gstack-repo-mode 2>/dev/null) || true +REPO_MODE=${REPO_MODE:-unknown} +echo "REPO_MODE: $REPO_MODE" +_LAKE_SEEN=$([ -f ~/.gstack/.completeness-intro-seen ] && echo "yes" || echo "no") +echo "LAKE_INTRO: $_LAKE_SEEN" +_TEL=$(~/.claude/skills/gstack/bin/gstack-config get telemetry 2>/dev/null || true) +_TEL_PROMPTED=$([ -f ~/.gstack/.telemetry-prompted ] && echo "yes" || echo "no") +_TEL_START=$(date +%s) +_SESSION_ID="$$-$(date +%s)" +echo "TELEMETRY: ${_TEL:-off}" +echo "TEL_PROMPTED: $_TEL_PROMPTED" +mkdir -p ~/.gstack/analytics +echo '{"skill":"hate-driven-development","ts":"'$(date -u +%Y-%m-%dT%H:%M:%SZ)'","repo":"'$(basename "$(git rev-parse --show-toplevel 2>/dev/null)" 2>/dev/null || echo "unknown")'"}' >> ~/.gstack/analytics/skill-usage.jsonl 2>/dev/null || true +# zsh-compatible: use find instead of glob to avoid NOMATCH error +for _PF in $(find ~/.gstack/analytics -maxdepth 1 -name '.pending-*' 2>/dev/null); do [ -f "$_PF" ] && ~/.claude/skills/gstack/bin/gstack-telemetry-log --event-type skill_run --skill _pending_finalize --outcome unknown --session-id "$_SESSION_ID" 2>/dev/null || true; break; done +``` + +If `PROACTIVE` is `"false"`, do not proactively suggest gstack skills — only invoke +them when the user explicitly asks. The user opted out of proactive suggestions. + +If output shows `UPGRADE_AVAILABLE `: read `~/.claude/skills/gstack/gstack-upgrade/SKILL.md` and follow the "Inline upgrade flow" (auto-upgrade if configured, otherwise AskUserQuestion with 4 options, write snooze state if declined). If `JUST_UPGRADED `: tell user "Running gstack v{to} (just updated!)" and continue. + +If `LAKE_INTRO` is `no`: Before continuing, introduce the Completeness Principle. +Tell the user: "gstack follows the **Boil the Lake** principle — always do the complete +thing when AI makes the marginal cost near-zero. Read more: https://garryslist.org/posts/boil-the-ocean" +Then offer to open the essay in their default browser: + +```bash +open https://garryslist.org/posts/boil-the-ocean +touch ~/.gstack/.completeness-intro-seen +``` + +Only run `open` if the user says yes. Always run `touch` to mark as seen. This only happens once. + +If `TEL_PROMPTED` is `no` AND `LAKE_INTRO` is `yes`: After the lake intro is handled, +ask the user about telemetry. Use AskUserQuestion: + +> Help gstack get better! Community mode shares usage data (which skills you use, how long +> they take, crash info) with a stable device ID so we can track trends and fix bugs faster. +> No code, file paths, or repo names are ever sent. +> Change anytime with `gstack-config set telemetry off`. + +Options: +- A) Help gstack get better! (recommended) +- B) No thanks + +If A: run `~/.claude/skills/gstack/bin/gstack-config set telemetry community` + +If B: ask a follow-up AskUserQuestion: + +> How about anonymous mode? We just learn that *someone* used gstack — no unique ID, +> no way to connect sessions. Just a counter that helps us know if anyone's out there. + +Options: +- A) Sure, anonymous is fine +- B) No thanks, fully off + +If B→A: run `~/.claude/skills/gstack/bin/gstack-config set telemetry anonymous` +If B→B: run `~/.claude/skills/gstack/bin/gstack-config set telemetry off` + +Always run: +```bash +touch ~/.gstack/.telemetry-prompted +``` + +This only happens once. If `TEL_PROMPTED` is `yes`, skip this entirely. + +## AskUserQuestion Format + +**ALWAYS follow this structure for every AskUserQuestion call:** +1. **Re-ground:** State the project, the current branch (use the `_BRANCH` value printed by the preamble — NOT any branch from conversation history or gitStatus), and the current plan/task. (1-2 sentences) +2. **Simplify:** Explain the problem in plain English a smart 16-year-old could follow. No raw function names, no internal jargon, no implementation details. Use concrete examples and analogies. Say what it DOES, not what it's called. +3. **Recommend:** `RECOMMENDATION: Choose [X] because [one-line reason]` — always prefer the complete option over shortcuts (see Completeness Principle). Include `Completeness: X/10` for each option. Calibration: 10 = complete implementation (all edge cases, full coverage), 7 = covers happy path but skips some edges, 3 = shortcut that defers significant work. If both options are 8+, pick the higher; if one is ≤5, flag it. +4. **Options:** Lettered options: `A) ... B) ... C) ...` — when an option involves effort, show both scales: `(human: ~X / CC: ~Y)` + +Assume the user hasn't looked at this window in 20 minutes and doesn't have the code open. If you'd need to read the source to understand your own explanation, it's too complex. + +Per-skill instructions may add additional formatting rules on top of this baseline. + +## Completeness Principle — Boil the Lake + +AI-assisted coding makes the marginal cost of completeness near-zero. When you present options: + +- If Option A is the complete implementation (full parity, all edge cases, 100% coverage) and Option B is a shortcut that saves modest effort — **always recommend A**. The delta between 80 lines and 150 lines is meaningless with CC+gstack. "Good enough" is the wrong instinct when "complete" costs minutes more. +- **Lake vs. ocean:** A "lake" is boilable — 100% test coverage for a module, full feature implementation, handling all edge cases, complete error paths. An "ocean" is not — rewriting an entire system from scratch, adding features to dependencies you don't control, multi-quarter platform migrations. Recommend boiling lakes. Flag oceans as out of scope. +- **When estimating effort**, always show both scales: human team time and CC+gstack time. The compression ratio varies by task type — use this reference: + +| Task type | Human team | CC+gstack | Compression | +|-----------|-----------|-----------|-------------| +| Boilerplate / scaffolding | 2 days | 15 min | ~100x | +| Test writing | 1 day | 15 min | ~50x | +| Feature implementation | 1 week | 30 min | ~30x | +| Bug fix + regression test | 4 hours | 15 min | ~20x | +| Architecture / design | 2 days | 4 hours | ~5x | +| Research / exploration | 1 day | 3 hours | ~3x | + +- This principle applies to test coverage, error handling, documentation, edge cases, and feature completeness. Don't skip the last 10% to "save time" — with AI, that 10% costs seconds. + +**Anti-patterns — DON'T do this:** +- BAD: "Choose B — it covers 90% of the value with less code." (If A is only 70 lines more, choose A.) +- BAD: "We can skip edge case handling to save time." (Edge case handling costs minutes with CC.) +- BAD: "Let's defer test coverage to a follow-up PR." (Tests are the cheapest lake to boil.) +- BAD: Quoting only human-team effort: "This would take 2 weeks." (Say: "2 weeks human / ~1 hour CC.") + +## Repo Ownership Mode — See Something, Say Something + +`REPO_MODE` from the preamble tells you who owns issues in this repo: + +- **`solo`** — One person does 80%+ of the work. They own everything. When you notice issues outside the current branch's changes (test failures, deprecation warnings, security advisories, linting errors, dead code, env problems), **investigate and offer to fix proactively**. The solo dev is the only person who will fix it. Default to action. +- **`collaborative`** — Multiple active contributors. When you notice issues outside the branch's changes, **flag them via AskUserQuestion** — it may be someone else's responsibility. Default to asking, not fixing. +- **`unknown`** — Treat as collaborative (safer default — ask before fixing). + +**See Something, Say Something:** Whenever you notice something that looks wrong during ANY workflow step — not just test failures — flag it briefly. One sentence: what you noticed and its impact. In solo mode, follow up with "Want me to fix it?" In collaborative mode, just flag it and move on. + +Never let a noticed issue silently pass. The whole point is proactive communication. + +## Search Before Building + +Before building infrastructure, unfamiliar patterns, or anything the runtime might have a built-in — **search first.** Read `~/.claude/skills/gstack/ETHOS.md` for the full philosophy. + +**Three layers of knowledge:** +- **Layer 1** (tried and true — in distribution). Don't reinvent the wheel. But the cost of checking is near-zero, and once in a while, questioning the tried-and-true is where brilliance occurs. +- **Layer 2** (new and popular — search for these). But scrutinize: humans are subject to mania. Search results are inputs to your thinking, not answers. +- **Layer 3** (first principles — prize these above all). Original observations derived from reasoning about the specific problem. The most valuable of all. + +**Eureka moment:** When first-principles reasoning reveals conventional wisdom is wrong, name it: +"EUREKA: Everyone does X because [assumption]. But [evidence] shows this is wrong. Y is better because [reasoning]." + +Log eureka moments: +```bash +jq -n --arg ts "$(date -u +%Y-%m-%dT%H:%M:%SZ)" --arg skill "SKILL_NAME" --arg branch "$(git branch --show-current 2>/dev/null)" --arg insight "ONE_LINE_SUMMARY" '{ts:$ts,skill:$skill,branch:$branch,insight:$insight}' >> ~/.gstack/analytics/eureka.jsonl 2>/dev/null || true +``` +Replace SKILL_NAME and ONE_LINE_SUMMARY. Runs inline — don't stop the workflow. + +**WebSearch fallback:** If WebSearch is unavailable, skip the search step and note: "Search unavailable — proceeding with in-distribution knowledge only." + +## Contributor Mode + +If `_CONTRIB` is `true`: you are in **contributor mode**. You're a gstack user who also helps make it better. + +**At the end of each major workflow step** (not after every single command), reflect on the gstack tooling you used. Rate your experience 0 to 10. If it wasn't a 10, think about why. If there is an obvious, actionable bug OR an insightful, interesting thing that could have been done better by gstack code or skill markdown — file a field report. Maybe our contributor will help make us better! + +**Calibration — this is the bar:** For example, `$B js "await fetch(...)"` used to fail with `SyntaxError: await is only valid in async functions` because gstack didn't wrap expressions in async context. Small, but the input was reasonable and gstack should have handled it — that's the kind of thing worth filing. Things less consequential than this, ignore. + +**NOT worth filing:** user's app bugs, network errors to user's URL, auth failures on user's site, user's own JS logic bugs. + +**To file:** write `~/.gstack/contributor-logs/{slug}.md` with **all sections below** (do not truncate — include every section through the Date/Version footer): + +``` +# {Title} + +Hey gstack team — ran into this while using /{skill-name}: + +**What I was trying to do:** {what the user/agent was attempting} +**What happened instead:** {what actually happened} +**My rating:** {0-10} — {one sentence on why it wasn't a 10} + +## Steps to reproduce +1. {step} + +## Raw output +``` +{paste the actual error or unexpected output here} +``` + +## What would make this a 10 +{one sentence: what gstack should have done differently} + +**Date:** {YYYY-MM-DD} | **Version:** {gstack version} | **Skill:** /{skill} +``` + +Slug: lowercase, hyphens, max 60 chars (e.g. `browse-js-no-await`). Skip if file already exists. Max 3 reports per session. File inline and continue — don't stop the workflow. Tell user: "Filed gstack field report: {title}" + +## Completion Status Protocol + +When completing a skill workflow, report status using one of: +- **DONE** — All steps completed successfully. Evidence provided for each claim. +- **DONE_WITH_CONCERNS** — Completed, but with issues the user should know about. List each concern. +- **BLOCKED** — Cannot proceed. State what is blocking and what was tried. +- **NEEDS_CONTEXT** — Missing information required to continue. State exactly what you need. + +### Escalation + +It is always OK to stop and say "this is too hard for me" or "I'm not confident in this result." + +Bad work is worse than no work. You will not be penalized for escalating. +- If you have attempted a task 3 times without success, STOP and escalate. +- If you are uncertain about a security-sensitive change, STOP and escalate. +- If the scope of work exceeds what you can verify, STOP and escalate. + +Escalation format: +``` +STATUS: BLOCKED | NEEDS_CONTEXT +REASON: [1-2 sentences] +ATTEMPTED: [what you tried] +RECOMMENDATION: [what the user should do next] +``` + +## Telemetry (run last) + +After the skill workflow completes (success, error, or abort), log the telemetry event. +Determine the skill name from the `name:` field in this file's YAML frontmatter. +Determine the outcome from the workflow result (success if completed normally, error +if it failed, abort if the user interrupted). + +**PLAN MODE EXCEPTION — ALWAYS RUN:** This command writes telemetry to +`~/.gstack/analytics/` (user config directory, not project files). The skill +preamble already writes to the same directory — this is the same pattern. +Skipping this command loses session duration and outcome data. + +Run this bash: + +```bash +_TEL_END=$(date +%s) +_TEL_DUR=$(( _TEL_END - _TEL_START )) +rm -f ~/.gstack/analytics/.pending-"$_SESSION_ID" 2>/dev/null || true +~/.claude/skills/gstack/bin/gstack-telemetry-log \ + --skill "SKILL_NAME" --duration "$_TEL_DUR" --outcome "OUTCOME" \ + --used-browse "USED_BROWSE" --session-id "$_SESSION_ID" 2>/dev/null & +``` + +Replace `SKILL_NAME` with the actual skill name from frontmatter, `OUTCOME` with +success/error/abort, and `USED_BROWSE` with true/false based on whether `$B` was used. +If you cannot determine the outcome, use "unknown". This runs in the background and +never blocks the user. + +## Plan Status Footer + +When you are in plan mode and about to call ExitPlanMode: + +1. Check if the plan file already has a `## GSTACK REVIEW REPORT` section. +2. If it DOES — skip (a review skill already wrote a richer report). +3. If it does NOT — run this command: + +\`\`\`bash +~/.claude/skills/gstack/bin/gstack-review-read +\`\`\` + +Then write a `## GSTACK REVIEW REPORT` section to the end of the plan file: + +- If the output contains review entries (JSONL lines before `---CONFIG---`): format the + standard report table with runs/status/findings per skill, same format as the review + skills use. +- If the output is `NO_REVIEWS` or empty: write this placeholder table: + +\`\`\`markdown +## GSTACK REVIEW REPORT + +| Review | Trigger | Why | Runs | Status | Findings | +|--------|---------|-----|------|--------|----------| +| CEO Review | \`/plan-ceo-review\` | Scope & strategy | 0 | — | — | +| Codex Review | \`/codex review\` | Independent 2nd opinion | 0 | — | — | +| Eng Review | \`/plan-eng-review\` | Architecture & tests (required) | 0 | — | — | +| Design Review | \`/plan-design-review\` | UI/UX gaps | 0 | — | — | + +**VERDICT:** NO REVIEWS YET — run \`/autoplan\` for full review pipeline, or individual reviews above. +\`\`\` + +**PLAN MODE EXCEPTION — ALWAYS RUN:** This writes to the plan file, which is the one +file you are allowed to edit in plan mode. The plan file review report is part of the +plan's living status. + +# /hate-driven-development — Feed Gary Breakfast + +This skill is intentionally dumb in the best possible way. + +No vibe scoring. No sentiment model. No LLM judging who is "mad online." +It uses the X recent-search API plus a fixed lexical weighting table so the +same post always gets the same score. + +## User-invocable + +When the user types `/hate-driven-development`, run this skill. + +## Arguments + +- `/hate-driven-development` — default mode, only scan since the last successful run +- `/hate-driven-development --all` — ignore saved state and rescan the recent-search window +- `/hate-driven-development --hours 24` — scan an explicit recent window +- `/hate-driven-development --query "..."` — override the default search query +- `/hate-driven-development --top 15` — change how many breakfast items to print + +## Prerequisites + +- Set one of these in your shell profile: `X_API_BEARER_TOKEN` (preferred), + `TWITTER_BEARER_TOKEN`, or `X_BEARER_TOKEN` +- `bun` must be installed + +## Instructions + +### Step 1: Set up paths and check auth + +```bash +GSTACK_ROOT=~/.claude/skills/gstack +[ -n "${_ROOT:-}" ] && [ -d "$_ROOT/.agents/skills/gstack" ] && GSTACK_ROOT="$_ROOT/.agents/skills/gstack" + +STATE_DIR=~/.gstack/hate-driven-development +STATE_FILE="$STATE_DIR/state.json" +RUNS_DIR="$STATE_DIR/runs" +STAMP=$(date -u +%Y%m%dT%H%M%SZ) +REPORT_JSON="$RUNS_DIR/$STAMP.json" +REPORT_MD="$RUNS_DIR/$STAMP.md" +mkdir -p "$RUNS_DIR" + +TOKEN_PRESENT=$([ -n "${X_API_BEARER_TOKEN:-${TWITTER_BEARER_TOKEN:-${X_BEARER_TOKEN:-}}}" ] && echo "yes" || echo "no") +echo "TOKEN_PRESENT: $TOKEN_PRESENT" +echo "STATE_FILE: $STATE_FILE" +echo "REPORT_MD: $REPORT_MD" +``` + +If `TOKEN_PRESENT: no`, stop and tell the user: + +``` +Missing X API bearer token. +Add one of: + export X_API_BEARER_TOKEN=... + export TWITTER_BEARER_TOKEN=... + export X_BEARER_TOKEN=... +Then rerun /hate-driven-development. +``` + +### Step 2: Run the deterministic scorer + +Default query: + +```text +(gstack OR "garrytan/gstack" OR "github.com/garrytan/gstack") lang:en -is:retweet -from:garrytan +``` + +Run the helper script. Mirror any explicit flags the user requested. +If they did not specify flags, run the default command exactly: + +```bash +bun "$GSTACK_ROOT/hate-driven-development/run.ts" \ + --state "$STATE_FILE" \ + --json "$REPORT_JSON" \ + --markdown "$REPORT_MD" +``` + +Common variants: + +```bash +bun "$GSTACK_ROOT/hate-driven-development/run.ts" --all --state "$STATE_FILE" --json "$REPORT_JSON" --markdown "$REPORT_MD" +bun "$GSTACK_ROOT/hate-driven-development/run.ts" --hours 24 --state "$STATE_FILE" --json "$REPORT_JSON" --markdown "$REPORT_MD" +bun "$GSTACK_ROOT/hate-driven-development/run.ts" --top 15 --state "$STATE_FILE" --json "$REPORT_JSON" --markdown "$REPORT_MD" +bun "$GSTACK_ROOT/hate-driven-development/run.ts" --query '' --state "$STATE_FILE" --json "$REPORT_JSON" --markdown "$REPORT_MD" +``` + +### Step 3: Read the breakfast board + +Read `REPORT_MD` and use it as the single source of truth for your response. + +Output format: + +1. A one-line headline: + - `Breakfast served.` when new hate was found + - `No new breakfast.` when nothing new matched since the last run +2. Report the scan window, posts scanned, and whether the run used saved `since_id` state or a cold-start fallback. +3. List the top items from the breakfast board in score order. +4. Separate actionable complaints from empty-calorie snark. +5. Include the saved report path so the user can inspect the full receipts later. + +### Step 4: Keep the closeout grounded + +- Quote or paraphrase only what is in the report. Do not invent intensity. +- If the script says the query changed or the state was ignored, say that plainly. +- If there are zero new results, do not pad with old posts from memory. +- Treat "actionable complaints" as potential product input; treat "empty calories" as entertainment. + +## Important Rules + +- **Deterministic only.** The ranking comes from the helper script's fixed rule table. +- **Read-only.** This skill never replies, likes, reposts, or mutates anything on X. +- **Default is incremental.** Unless the user overrides it, scan only since the last successful run using the saved `newest_id`. +- **Recent-search only.** `--all` still means "the recent-search window," not the entire history of X. +- **Gary-specific voice is fine.** Joke about breakfast, but keep the facts exact. diff --git a/hate-driven-development/SKILL.md.tmpl b/hate-driven-development/SKILL.md.tmpl new file mode 100644 index 000000000..1cca4b78e --- /dev/null +++ b/hate-driven-development/SKILL.md.tmpl @@ -0,0 +1,132 @@ +--- +name: hate-driven-development +version: 1.0.0 +description: | + Deterministic X mention triage for gstack. Polls recent posts mentioning + gstack, ranks the nastiest ones with a fixed lexical score, and serves Gary + a "breakfast" report with links, receipts, and actionable complaints. + Default behavior only scans since the last successful run by persisting the + newest seen post ID. Use when: "hate driven development", "what are people + saying on X", "scan gstack mentions", "feed Gary breakfast", "find the + haters", or "find the worst tweets about gstack". +allowed-tools: + - Bash + - Read +--- + +{{PREAMBLE}} + +# /hate-driven-development — Feed Gary Breakfast + +This skill is intentionally dumb in the best possible way. + +No vibe scoring. No sentiment model. No LLM judging who is "mad online." +It uses the X recent-search API plus a fixed lexical weighting table so the +same post always gets the same score. + +## User-invocable + +When the user types `/hate-driven-development`, run this skill. + +## Arguments + +- `/hate-driven-development` — default mode, only scan since the last successful run +- `/hate-driven-development --all` — ignore saved state and rescan the recent-search window +- `/hate-driven-development --hours 24` — scan an explicit recent window +- `/hate-driven-development --query "..."` — override the default search query +- `/hate-driven-development --top 15` — change how many breakfast items to print + +## Prerequisites + +- Set one of these in your shell profile: `X_API_BEARER_TOKEN` (preferred), + `TWITTER_BEARER_TOKEN`, or `X_BEARER_TOKEN` +- `bun` must be installed + +## Instructions + +### Step 1: Set up paths and check auth + +```bash +GSTACK_ROOT=~/.claude/skills/gstack +[ -n "${_ROOT:-}" ] && [ -d "$_ROOT/.agents/skills/gstack" ] && GSTACK_ROOT="$_ROOT/.agents/skills/gstack" + +STATE_DIR=~/.gstack/hate-driven-development +STATE_FILE="$STATE_DIR/state.json" +RUNS_DIR="$STATE_DIR/runs" +STAMP=$(date -u +%Y%m%dT%H%M%SZ) +REPORT_JSON="$RUNS_DIR/$STAMP.json" +REPORT_MD="$RUNS_DIR/$STAMP.md" +mkdir -p "$RUNS_DIR" + +TOKEN_PRESENT=$([ -n "${X_API_BEARER_TOKEN:-${TWITTER_BEARER_TOKEN:-${X_BEARER_TOKEN:-}}}" ] && echo "yes" || echo "no") +echo "TOKEN_PRESENT: $TOKEN_PRESENT" +echo "STATE_FILE: $STATE_FILE" +echo "REPORT_MD: $REPORT_MD" +``` + +If `TOKEN_PRESENT: no`, stop and tell the user: + +``` +Missing X API bearer token. +Add one of: + export X_API_BEARER_TOKEN=... + export TWITTER_BEARER_TOKEN=... + export X_BEARER_TOKEN=... +Then rerun /hate-driven-development. +``` + +### Step 2: Run the deterministic scorer + +Default query: + +```text +(gstack OR "garrytan/gstack" OR "github.com/garrytan/gstack") lang:en -is:retweet -from:garrytan +``` + +Run the helper script. Mirror any explicit flags the user requested. +If they did not specify flags, run the default command exactly: + +```bash +bun "$GSTACK_ROOT/hate-driven-development/run.ts" \ + --state "$STATE_FILE" \ + --json "$REPORT_JSON" \ + --markdown "$REPORT_MD" +``` + +Common variants: + +```bash +bun "$GSTACK_ROOT/hate-driven-development/run.ts" --all --state "$STATE_FILE" --json "$REPORT_JSON" --markdown "$REPORT_MD" +bun "$GSTACK_ROOT/hate-driven-development/run.ts" --hours 24 --state "$STATE_FILE" --json "$REPORT_JSON" --markdown "$REPORT_MD" +bun "$GSTACK_ROOT/hate-driven-development/run.ts" --top 15 --state "$STATE_FILE" --json "$REPORT_JSON" --markdown "$REPORT_MD" +bun "$GSTACK_ROOT/hate-driven-development/run.ts" --query '' --state "$STATE_FILE" --json "$REPORT_JSON" --markdown "$REPORT_MD" +``` + +### Step 3: Read the breakfast board + +Read `REPORT_MD` and use it as the single source of truth for your response. + +Output format: + +1. A one-line headline: + - `Breakfast served.` when new hate was found + - `No new breakfast.` when nothing new matched since the last run +2. Report the scan window, posts scanned, and whether the run used saved `since_id` state or a cold-start fallback. +3. List the top items from the breakfast board in score order. +4. Separate actionable complaints from empty-calorie snark. +5. Include the saved report path so the user can inspect the full receipts later. + +### Step 4: Keep the closeout grounded + +- Quote or paraphrase only what is in the report. Do not invent intensity. +- If the script says the query changed or the state was ignored, say that plainly. +- If there are zero new results, do not pad with old posts from memory. +- Treat "actionable complaints" as potential product input; treat "empty calories" as entertainment. + +## Important Rules + +- **Deterministic only.** The ranking comes from the helper script's fixed rule table. +- **Read-only.** This skill never replies, likes, reposts, or mutates anything on X. +- **Default is incremental.** Unless the user overrides it, scan only since the last successful run using the saved `newest_id`. +- **Recent-search only.** `--all` still means "the recent-search window," not the entire history of X. +- **Gary-specific voice is fine.** Joke about breakfast, but keep the facts exact. diff --git a/hate-driven-development/run.ts b/hate-driven-development/run.ts new file mode 100644 index 000000000..43990bd70 --- /dev/null +++ b/hate-driven-development/run.ts @@ -0,0 +1,458 @@ +#!/usr/bin/env bun + +import { mkdir, readFile, writeFile } from 'fs/promises'; +import path from 'path'; +import os from 'os'; +import { rankMentions, type PublicMetrics } from './scoring.ts'; + +const SEARCH_ENDPOINT = 'https://api.x.com/2/tweets/search/recent'; +const DEFAULT_QUERY = '(gstack OR "garrytan/gstack" OR "github.com/garrytan/gstack") lang:en -is:retweet -from:garrytan'; +const DEFAULT_TOP = 10; +const DEFAULT_MAX_PAGES = 3; +const RECENT_SEARCH_WINDOW_HOURS = 24 * 7; + +interface Args { + all: boolean; + hours?: number; + top: number; + maxPages: number; + query: string; + statePath: string; + jsonPath?: string; + markdownPath?: string; +} + +interface StateFile { + version: number; + last_query?: string; + newest_id?: string; + last_run_at?: string; + last_report_json?: string; + last_report_markdown?: string; +} + +interface XUser { + id: string; + username: string; + name?: string; +} + +interface XPost { + id: string; + text: string; + author_id: string; + created_at?: string; + lang?: string; + public_metrics?: PublicMetrics; +} + +interface SearchResponse { + data?: XPost[]; + includes?: { + users?: XUser[]; + }; + meta?: { + newest_id?: string; + oldest_id?: string; + next_token?: string; + result_count?: number; + }; +} + +interface WindowPlan { + mode: 'since_id' | 'start_time'; + detail: string; + reason: string; + sinceId?: string; + startTime?: string; +} + +function usage(): string { + return [ + 'Usage: bun hate-driven-development/run.ts [options]', + '', + 'Options:', + ' --all Ignore saved state and scan the recent-search window', + ' --hours Scan an explicit recent window', + ' --query Override the default X search query', + ' --top Number of ranked posts to keep (default: 10)', + ' --max-pages Pagination cap (default: 3)', + ' --state State file path', + ' --json JSON report output path', + ' --markdown Markdown report output path', + ].join('\n'); +} + +function fail(message: string): never { + console.error(message); + process.exit(1); +} + +function expandHome(inputPath: string): string { + if (inputPath === '~') return os.homedir(); + if (inputPath.startsWith('~/')) return path.join(os.homedir(), inputPath.slice(2)); + return inputPath; +} + +function parseNumber(raw: string | undefined, flag: string): number { + if (!raw) fail(`${flag} requires a value`); + const parsed = Number(raw); + if (!Number.isFinite(parsed) || parsed <= 0) { + fail(`${flag} must be a positive number`); + } + return parsed; +} + +function parseArgs(argv: string[]): Args { + const args: Args = { + all: false, + top: DEFAULT_TOP, + maxPages: DEFAULT_MAX_PAGES, + query: DEFAULT_QUERY, + statePath: '~/.gstack/hate-driven-development/state.json', + }; + + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + switch (arg) { + case '--help': + case '-h': + console.log(usage()); + process.exit(0); + case '--all': + args.all = true; + break; + case '--hours': + args.hours = parseNumber(argv[i + 1], '--hours'); + i += 1; + break; + case '--query': + args.query = argv[i + 1] ?? fail('--query requires a value'); + i += 1; + break; + case '--top': + args.top = parseNumber(argv[i + 1], '--top'); + i += 1; + break; + case '--max-pages': + args.maxPages = parseNumber(argv[i + 1], '--max-pages'); + i += 1; + break; + case '--state': + args.statePath = argv[i + 1] ?? fail('--state requires a value'); + i += 1; + break; + case '--json': + args.jsonPath = argv[i + 1] ?? fail('--json requires a value'); + i += 1; + break; + case '--markdown': + args.markdownPath = argv[i + 1] ?? fail('--markdown requires a value'); + i += 1; + break; + default: + fail(`Unknown argument: ${arg}\n\n${usage()}`); + } + } + + if (args.all && args.hours !== undefined) { + fail('Choose either --all or --hours, not both'); + } + + args.statePath = expandHome(args.statePath); + if (args.jsonPath) args.jsonPath = expandHome(args.jsonPath); + if (args.markdownPath) args.markdownPath = expandHome(args.markdownPath); + return args; +} + +async function readState(statePath: string): Promise { + try { + const content = await readFile(statePath, 'utf8'); + return JSON.parse(content) as StateFile; + } catch { + return null; + } +} + +function resolveToken(): string { + const token = + process.env.X_API_BEARER_TOKEN || + process.env.TWITTER_BEARER_TOKEN || + process.env.X_BEARER_TOKEN; + + if (!token) { + fail('Missing X API bearer token. Set X_API_BEARER_TOKEN, TWITTER_BEARER_TOKEN, or X_BEARER_TOKEN.'); + } + + return token; +} + +function hoursAgoIso(hours: number): string { + return new Date(Date.now() - (hours * 60 * 60 * 1000)).toISOString(); +} + +function planWindow(args: Args, state: StateFile | null): WindowPlan { + if (args.all) { + return { + mode: 'start_time', + startTime: hoursAgoIso(RECENT_SEARCH_WINDOW_HOURS), + detail: 'recent-search reset', + reason: `explicit --all override (last ${RECENT_SEARCH_WINDOW_HOURS}h window)`, + }; + } + + if (args.hours !== undefined) { + return { + mode: 'start_time', + startTime: hoursAgoIso(args.hours), + detail: `last ${args.hours}h`, + reason: 'explicit --hours override', + }; + } + + if (state?.last_query === args.query && state.newest_id) { + return { + mode: 'since_id', + sinceId: state.newest_id, + detail: `since_id ${state.newest_id}`, + reason: `saved state from ${state.last_run_at ?? 'a previous run'}`, + }; + } + + if (state?.last_query && state.last_query !== args.query) { + return { + mode: 'start_time', + startTime: hoursAgoIso(RECENT_SEARCH_WINDOW_HOURS), + detail: 'recent-search fallback', + reason: 'saved state query did not match this run', + }; + } + + return { + mode: 'start_time', + startTime: hoursAgoIso(RECENT_SEARCH_WINDOW_HOURS), + detail: 'cold start fallback', + reason: 'no prior matching state', + }; +} + +function snippet(text: string, max = 220): string { + const singleLine = text.replace(/\s+/g, ' ').trim(); + if (singleLine.length <= max) return singleLine; + return `${singleLine.slice(0, max - 3).trimEnd()}...`; +} + +async function fetchSearchPage( + token: string, + args: Args, + windowPlan: WindowPlan, + nextToken?: string, +): Promise { + const url = new URL(SEARCH_ENDPOINT); + url.searchParams.set('query', args.query); + url.searchParams.set('max_results', '100'); + url.searchParams.set('expansions', 'author_id'); + url.searchParams.set('tweet.fields', 'author_id,created_at,lang,public_metrics'); + url.searchParams.set('user.fields', 'name,username'); + + if (windowPlan.sinceId) url.searchParams.set('since_id', windowPlan.sinceId); + if (windowPlan.startTime) url.searchParams.set('start_time', windowPlan.startTime); + if (nextToken) url.searchParams.set('next_token', nextToken); + + const response = await fetch(url, { + headers: { + Authorization: `Bearer ${token}`, + }, + }); + + if (!response.ok) { + const reset = response.headers.get('x-rate-limit-reset'); + const body = await response.text(); + const rateLimitHint = reset ? ` Rate limit resets at unix ${reset}.` : ''; + fail(`X API request failed (${response.status}).${rateLimitHint}\n${body}`); + } + + return response.json() as Promise; +} + +function buildXUrl(username: string | undefined, postId: string): string { + return username + ? `https://x.com/${username}/status/${postId}` + : `https://x.com/i/web/status/${postId}`; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + const token = resolveToken(); + const state = await readState(args.statePath); + const windowPlan = planWindow(args, state); + + const userById = new Map(); + const posts = new Map(); + let nextToken: string | undefined; + let pageCount = 0; + let newestId: string | undefined; + let oldestId: string | undefined; + + do { + const page = await fetchSearchPage(token, args, windowPlan, nextToken); + pageCount += 1; + + if (!newestId && page.meta?.newest_id) newestId = page.meta.newest_id; + if (page.meta?.oldest_id) oldestId = page.meta.oldest_id; + + for (const user of page.includes?.users ?? []) { + userById.set(user.id, user); + } + + for (const post of page.data ?? []) { + posts.set(post.id, post); + } + + nextToken = page.meta?.next_token; + } while (nextToken && pageCount < args.maxPages); + + const ranked = rankMentions( + [...posts.values()].map(post => ({ + ...post, + author_username: userById.get(post.author_id)?.username, + author_name: userById.get(post.author_id)?.name, + url: buildXUrl(userById.get(post.author_id)?.username, post.id), + })), + ); + + const top = ranked.slice(0, args.top); + const actionable = top.filter(item => item.actionable); + const emptyCalories = top.filter(item => !item.actionable); + const generatedAt = new Date().toISOString(); + + const report = { + generated_at: generatedAt, + query: args.query, + window: windowPlan, + fetched_posts: ranked.length, + returned_posts: top.length, + actionable_count: actionable.length, + empty_calorie_count: emptyCalories.length, + pages_fetched: pageCount, + newest_id: newestId, + oldest_id: oldestId, + breakfast_board: top.map(item => ({ + id: item.id, + url: (item as typeof item & { url?: string }).url, + author_username: (item as typeof item & { author_username?: string }).author_username, + author_name: (item as typeof item & { author_name?: string }).author_name, + created_at: item.created_at, + score: item.score, + meal_tag: item.mealTag, + actionable: item.actionable, + actionable_signals: item.actionableSignals, + engagement: item.engagement, + reasons: item.reasons, + text: item.text, + public_metrics: item.public_metrics, + })), + }; + + const markdownLines: string[] = [ + '# Hate-Driven Development', + '', + `Generated: ${generatedAt}`, + `Query: ${args.query}`, + `Window: ${windowPlan.detail} (${windowPlan.reason})`, + `Pages fetched: ${pageCount}`, + `Mentions scored: ${ranked.length}`, + `Breakfast items kept: ${top.length}`, + '', + ]; + + if (top.length === 0) { + markdownLines.push('## No new breakfast'); + markdownLines.push(''); + markdownLines.push('Nothing new matched the current window.'); + } else { + markdownLines.push("## Gary's breakfast board"); + markdownLines.push(''); + + top.forEach((item, index) => { + const authorUsername = (item as typeof item & { author_username?: string }).author_username ?? 'unknown'; + const url = (item as typeof item & { url?: string }).url ?? buildXUrl(undefined, item.id); + markdownLines.push(`${index + 1}. @${authorUsername} — score ${item.score} — ${item.mealTag}`); + markdownLines.push(` ${url}`); + markdownLines.push(` "${snippet(item.text)}"`); + markdownLines.push(` Why it ranked: ${item.reasons.join(', ') || 'low-signal match'}`); + if (item.actionableSignals.length > 0) { + markdownLines.push(` Actionable signals: ${item.actionableSignals.join(', ')}`); + } + markdownLines.push(''); + }); + + markdownLines.push('## Actionable complaints'); + markdownLines.push(''); + if (actionable.length === 0) { + markdownLines.push('- None. This run was mostly empty-calorie hate.'); + } else { + for (const item of actionable) { + const authorUsername = (item as typeof item & { author_username?: string }).author_username ?? 'unknown'; + const url = (item as typeof item & { url?: string }).url ?? buildXUrl(undefined, item.id); + markdownLines.push(`- @${authorUsername} — ${item.actionableSignals.join(', ')} — ${url}`); + } + } + markdownLines.push(''); + + markdownLines.push('## Empty-calorie snark'); + markdownLines.push(''); + if (emptyCalories.length === 0) { + markdownLines.push('- None. Everything sharp enough to rank was at least somewhat actionable.'); + } else { + for (const item of emptyCalories) { + const authorUsername = (item as typeof item & { author_username?: string }).author_username ?? 'unknown'; + markdownLines.push(`- @${authorUsername} — ${snippet(item.text, 120)}`); + } + } + } + + markdownLines.push(''); + markdownLines.push('## State'); + markdownLines.push(''); + markdownLines.push(`- newest_id saved: ${newestId ?? state?.newest_id ?? 'none'}`); + markdownLines.push(`- next default run: ${newestId ? `since_id ${newestId}` : 'cold-start fallback unless a future run finds matches'}`); + + const markdown = markdownLines.join('\n'); + + if (args.jsonPath) { + await mkdir(path.dirname(args.jsonPath), { recursive: true }); + await writeFile(args.jsonPath, JSON.stringify(report, null, 2)); + } + + if (args.markdownPath) { + await mkdir(path.dirname(args.markdownPath), { recursive: true }); + await writeFile(args.markdownPath, markdown); + } + + const nextState: StateFile = { + version: 1, + last_query: args.query, + newest_id: newestId ?? state?.newest_id, + last_run_at: generatedAt, + last_report_json: args.jsonPath, + last_report_markdown: args.markdownPath, + }; + + await mkdir(path.dirname(args.statePath), { recursive: true }); + await writeFile(args.statePath, JSON.stringify(nextState, null, 2)); + + console.log(JSON.stringify({ + status: 'ok', + fetched_posts: ranked.length, + breakfast_items: top.length, + actionable_count: actionable.length, + empty_calorie_count: emptyCalories.length, + window: windowPlan, + newest_id: newestId ?? null, + markdown_report: args.markdownPath ?? null, + json_report: args.jsonPath ?? null, + }, null, 2)); +} + +await main(); diff --git a/hate-driven-development/scoring.ts b/hate-driven-development/scoring.ts new file mode 100644 index 000000000..74f0e7ad4 --- /dev/null +++ b/hate-driven-development/scoring.ts @@ -0,0 +1,169 @@ +export interface PublicMetrics { + like_count?: number; + reply_count?: number; + retweet_count?: number; + quote_count?: number; +} + +export interface ScoreResult { + score: number; + engagement: number; + engagementBoost: number; + actionable: boolean; + mealTag: 'actionable protein' | 'empty calories' | 'light snack'; + reasons: string[]; + actionableSignals: string[]; +} + +export interface MentionInput { + id: string; + text: string; + created_at?: string; + public_metrics?: PublicMetrics; +} + +export interface RankedMention extends MentionInput, ScoreResult {} + +interface Rule { + label: string; + pattern: RegExp; + weight: number; + actionable?: boolean; +} + +const NEGATIVE_RULES: Rule[] = [ + { label: 'hate', pattern: /\bhate\b/gi, weight: 6 }, + { label: 'worst', pattern: /\bworst\b/gi, weight: 5 }, + { label: 'terrible/awful', pattern: /\bterrible\b|\bawful\b/gi, weight: 5 }, + { label: 'trash/garbage', pattern: /\btrash\b|\bgarbage\b/gi, weight: 5 }, + { label: 'scam/fraud/grift', pattern: /\bscam\b|\bfraud\b|\bgrift(?:er)?\b/gi, weight: 6 }, + { label: 'sucks', pattern: /\bsucks?\b/gi, weight: 4 }, + { label: 'slop', pattern: /\bslop\b/gi, weight: 4 }, + { label: 'broken/buggy/failing', pattern: /\bbugg?y\b|\bbroken\b|\bunusable\b|\bdoesn'?t work\b|\bdoes not work\b|\bfail(?:s|ed|ing)?\b/gi, weight: 4, actionable: true }, + { label: 'annoying/confusing', pattern: /\bannoying\b|\bconfusing\b|\bmisleading\b|\bunclear\b/gi, weight: 3, actionable: true }, + { label: 'dumb/stupid/clown', pattern: /\bdumb\b|\bstupid\b|\bclown\b/gi, weight: 3 }, + { label: 'cope/copium', pattern: /\bcope\b|\bcopium\b/gi, weight: 3 }, + { label: 'wtf', pattern: /\bwtf\b/gi, weight: 2.5 }, + { label: 'mocking laughter', pattern: /\blol\b|\blmao\b|\brofl\b/gi, weight: 1.5 }, + { label: 'shitty', pattern: /\bshitty\b|\bshit\b/gi, weight: 4.5 }, +]; + +const POSITIVE_RULES: Rule[] = [ + { label: 'love', pattern: /\blove\b/gi, weight: 3 }, + { label: 'good/great', pattern: /\bgood\b|\bgreat\b/gi, weight: 2 }, + { label: 'cool/amazing', pattern: /\bcool\b|\bamazing\b|\bhelpful\b|\buseful\b/gi, weight: 2.5 }, +]; + +const ACTIONABLE_RULES: Rule[] = [ + { label: 'docs/readme', pattern: /\bdocs?\b|\breadme\b/gi, weight: 0, actionable: true }, + { label: 'install/setup', pattern: /\binstall\b|\bsetup\b|\bconfigure\b/gi, weight: 0, actionable: true }, + { label: 'build/compile', pattern: /\bbuild\b|\bcompile\b|\bbun\b|\bnode\b/gi, weight: 0, actionable: true }, + { label: 'error/crash', pattern: /\berror\b|\bcrash(?:ed|es)?\b|\bexception\b/gi, weight: 0, actionable: true }, + { label: 'slow/perf', pattern: /\bslow\b|\bperformance\b|\blag(?:gy)?\b/gi, weight: 0, actionable: true }, + { label: 'missing/unclear', pattern: /\bmissing\b|\bunclear\b|\bconfusing\b/gi, weight: 0, actionable: true }, +]; + +function countMatches(text: string, pattern: RegExp): number { + const flags = pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`; + const matches = text.match(new RegExp(pattern.source, flags)); + return matches?.length ?? 0; +} + +function roundScore(value: number): number { + return Math.round(value * 10) / 10; +} + +function scoreRules(text: string, rules: Rule[], reasons: string[], actionableSignals: string[]): number { + let total = 0; + + for (const rule of rules) { + const matches = countMatches(text, rule.pattern); + if (matches === 0) continue; + + const cappedMatches = Math.min(matches, 2); + total += rule.weight * cappedMatches; + reasons.push(`${rule.label} x${cappedMatches} (${rule.weight >= 0 ? '+' : ''}${roundScore(rule.weight * cappedMatches)})`); + + if (rule.actionable) { + actionableSignals.push(rule.label); + } + } + + return total; +} + +export function scoreMention(text: string, metrics: PublicMetrics = {}): ScoreResult { + const reasons: string[] = []; + const actionableSignals: string[] = []; + + let score = 0; + score += scoreRules(text, NEGATIVE_RULES, reasons, actionableSignals); + score -= scoreRules(text, POSITIVE_RULES, [], []); + + for (const rule of ACTIONABLE_RULES) { + if (countMatches(text, rule.pattern) > 0) { + actionableSignals.push(rule.label); + } + } + + const capsWords = (text.match(/\b[A-Z]{4,}\b/g) ?? []).length; + if (capsWords > 0) { + const capsBoost = Math.min(2, capsWords * 0.5); + score += capsBoost; + reasons.push(`all-caps emphasis (+${roundScore(capsBoost)})`); + } + + const exclamations = (text.match(/!/g) ?? []).length; + if (exclamations > 0) { + const punctuationBoost = Math.min(1.5, exclamations * 0.25); + score += punctuationBoost; + reasons.push(`punctuation heat (+${roundScore(punctuationBoost)})`); + } + + const engagement = + (metrics.like_count ?? 0) + + ((metrics.reply_count ?? 0) * 2) + + ((metrics.retweet_count ?? 0) * 3) + + ((metrics.quote_count ?? 0) * 4); + const engagementBoost = Math.min(4, Math.log2(engagement + 1)); + if (engagementBoost > 0) { + score += engagementBoost; + reasons.push(`engagement boost (+${roundScore(engagementBoost)})`); + } + + const actionable = actionableSignals.length > 0; + const rounded = roundScore(score); + const mealTag = actionable + ? 'actionable protein' + : rounded >= 8 + ? 'empty calories' + : 'light snack'; + + return { + score: rounded, + engagement, + engagementBoost: roundScore(engagementBoost), + actionable, + mealTag, + reasons, + actionableSignals: [...new Set(actionableSignals)], + }; +} + +export function compareRankedMentions(a: RankedMention, b: RankedMention): number { + if (b.score !== a.score) return b.score - a.score; + if (b.engagement !== a.engagement) return b.engagement - a.engagement; + const aCreated = a.created_at ?? ''; + const bCreated = b.created_at ?? ''; + if (bCreated !== aCreated) return bCreated.localeCompare(aCreated); + return b.id.localeCompare(a.id); +} + +export function rankMentions(mentions: T[]): Array { + return mentions + .map(mention => ({ + ...mention, + ...scoreMention(mention.text, mention.public_metrics), + })) + .sort((a, b) => compareRankedMentions(a, b)); +} diff --git a/scripts/skill-check.ts b/scripts/skill-check.ts index 59f306c2c..8e3dbb1e8 100644 --- a/scripts/skill-check.ts +++ b/scripts/skill-check.ts @@ -31,6 +31,7 @@ const SKILL_FILES = [ 'design-review/SKILL.md', 'gstack-upgrade/SKILL.md', 'document-release/SKILL.md', + 'hate-driven-development/SKILL.md', 'canary/SKILL.md', 'benchmark/SKILL.md', 'land-and-deploy/SKILL.md', diff --git a/test/hate-driven-development.test.ts b/test/hate-driven-development.test.ts new file mode 100644 index 000000000..def165491 --- /dev/null +++ b/test/hate-driven-development.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, test } from 'bun:test'; +import { rankMentions, scoreMention } from '../hate-driven-development/scoring.ts'; + +describe('hate-driven-development scoring', () => { + test('actionable product complaints outrank light mockery', () => { + const ranked = rankMentions([ + { + id: '1', + text: 'gstack install is broken and the docs are confusing', + public_metrics: { like_count: 2, reply_count: 1, retweet_count: 0, quote_count: 0 }, + }, + { + id: '2', + text: 'lol gstack', + public_metrics: { like_count: 0, reply_count: 0, retweet_count: 0, quote_count: 0 }, + }, + ]); + + expect(ranked[0]?.id).toBe('1'); + expect(ranked[0]?.actionable).toBe(true); + expect(ranked[0]?.mealTag).toBe('actionable protein'); + }); + + test('positive language offsets some negativity', () => { + const harsh = scoreMention('gstack is trash'); + const mixed = scoreMention('gstack is trash but also useful'); + + expect(harsh.score).toBeGreaterThan(mixed.score); + }); + + test('engagement breaks ties deterministically', () => { + const ranked = rankMentions([ + { + id: '10', + text: 'gstack sucks', + public_metrics: { like_count: 1, reply_count: 0, retweet_count: 0, quote_count: 0 }, + created_at: '2026-03-23T00:00:00.000Z', + }, + { + id: '11', + text: 'gstack sucks', + public_metrics: { like_count: 20, reply_count: 3, retweet_count: 1, quote_count: 0 }, + created_at: '2026-03-23T00:00:00.000Z', + }, + ]); + + expect(ranked[0]?.id).toBe('11'); + expect(ranked[1]?.id).toBe('10'); + }); +}); diff --git a/test/skill-routing-e2e.test.ts b/test/skill-routing-e2e.test.ts index ae17c2df4..d98abacd6 100644 --- a/test/skill-routing-e2e.test.ts +++ b/test/skill-routing-e2e.test.ts @@ -50,7 +50,7 @@ function installSkills(tmpDir: string) { '', // root gstack SKILL.md 'qa', 'qa-only', 'ship', 'review', 'plan-ceo-review', 'plan-eng-review', 'plan-design-review', 'design-review', 'design-consultation', 'retro', - 'document-release', 'investigate', 'office-hours', 'browse', 'setup-browser-cookies', + 'document-release', 'investigate', 'office-hours', 'hate-driven-development', 'browse', 'setup-browser-cookies', 'gstack-upgrade', 'humanizer', ]; diff --git a/test/skill-validation.test.ts b/test/skill-validation.test.ts index c4bc99afe..330862531 100644 --- a/test/skill-validation.test.ts +++ b/test/skill-validation.test.ts @@ -1398,6 +1398,7 @@ describe('Skill trigger phrases', () => { 'qa', 'qa-only', 'ship', 'review', 'investigate', 'office-hours', 'plan-ceo-review', 'plan-eng-review', 'plan-design-review', 'design-review', 'design-consultation', 'retro', 'document-release', + 'hate-driven-development', 'codex', 'browse', 'setup-browser-cookies', ];