[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6CZ74FBFWMNZPN9A1840S6G":3,"skill-same:01M6CZ74FBFWMNZPN9A1840S6G":79},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":56,"commitSha":57,"skillDirectory":58,"forksCount":59,"repositoryHtmlUrl":60,"repositoryHomepageUrl":61,"ownerHtmlUrl":62,"ownerBlogUrl":61,"ownerDescription":63,"updatedAt":64,"install":65,"resources":78},"01M6CZ74FBFWMNZPN9A1840S6G","distribute-tokens",null,"Two-phase contributor rewards - plan builds a tier-priced payout from the repo's merged-PR ranking; send executes it on-chain via Bankr Wallet API with per-recipient idempotency and dry-run.","aeonfun\u002Faeon","aeonfun","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F287715280?v=4","01M6CZ23C6MXGMF4N0V1DZ1247","aeon","01M6CZ23GMZP1BR424J8Y8K3DG",793,"MIT","https:\u002F\u002Fgithub.com\u002Faeonfun\u002Faeon\u002Fblob\u002Fmain\u002Fskills\u002Fdistribute-tokens\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"distribute tokens","tokens","distribute","phase","contributor","on-chain","dry","host","ranking","send","chain","pr","run","onchain","plan","notifications","api","bankr","Wallet","community","2026-11-10 10:12:30",false,"---\nname: distribute-tokens\ndescription: Two-phase contributor rewards - plan builds a tier-priced payout from the repo's merged-PR ranking; send executes it on-chain via Bankr Wallet API with per-recipient idempotency and dry-run.\nmetadata:\n  title: Distribute Tokens\n  category: crypto\n  var: \"\"\n  tags:\n    - community\n    - crypto\n  requires:\n    - BANKR_API_KEY?\n  capabilities:\n    - external_api\n    - writes_external_host\n    - onchain_writes\n    - sends_notifications\n---\n\u003C!-- autoresearch: variation C — robustness via per-recipient idempotency state, two-phase resolve→execute, dry-run, retries, 403\u002F429 handling, recovery. Merged: contributor-reward's tier-priced reward-computation folded in as the plan\u002Finput phase; the on-chain distribution stays the execute phase. -->\n\n> **${var}** — Phase + target selector. Grammar: `[plan:|all:][dry-run:]\u003Ctarget>`\n> - `` (empty) \u002F `\u003Clabel>` \u002F `dry-run:\u003Clabel>` → **send** phase: distribute a list from `memory\u002Fdistributions.yml` (empty = first list). *[default — no prefix]*\n> - `plan:` \u002F `plan:\u003Cweek>` \u002F `plan:dry-run` \u002F `plan:dry-run:\u003Cweek>` → **plan** phase only: compute rewards from the repo's merged PRs and write the list into `memory\u002Fdistributions.yml`.\n> - `all:` \u002F `all:\u003Cweek>` \u002F `all:dry-run` \u002F `all:dry-run:\u003Cweek>` → **plan then send** in one run.\n>\n> `\u003Clabel>` is a distribution-list label (e.g. `contributors-2026-W17`). `\u003Cweek>` is an ISO week (`2026-W17`); empty `\u003Cweek>` = most recent completed ISO week. `dry-run:` previews without side effects (no yml\u002Fstate writes in plan; no transfers in send).\n\n## Why this design\n\nThis skill owns the whole contributor flywheel: **who deserves what** (plan) and **moving the money** (send). It is split into two phases that can run independently or chained.\n\n**Plan phase — the wiring the project was missing.** Merged PRs already name the people moving the project, but shipped work had no path to a wallet credit. The plan phase is that wiring: it ranks contributors by the PRs they merged in the target week (straight from the GitHub API), prices each eligible contributor against a tier table, and writes a labelled list into `memory\u002Fdistributions.yml` — the exact file the send phase reads. Keeping a human-visible diff on `memory\u002Fdistributions.yml` between plan and execution is the cheapest possible audit trail when real money is involved: the plan lands in git, and the operator (or `all:` mode, or a chained step) runs the send next.\n\n**Send phase — this moves real money.** The biggest failure mode is double-sending (re-runs, retries after partial failures, day-rollover bypass of \"skip if today\" logic) or sending into a black hole (no preflight balance, deprecated API path, missing handle resolution). The send phase therefore:\n\n1. **Persists per-recipient idempotency state** in `memory\u002Fstate\u002Fdistributions.json` keyed on `(list, recipient, date_utc)` with the txHash. A successful transfer is *never* re-sent within the same UTC day, even across re-runs or workflow restarts.\n2. **Two-phase execution**: RESOLVE (validate config, key, balance, resolve all handles → addresses, build plan) → EXECUTE (send each transfer, persist state after each one). RESOLVE failures abort before any send.\n3. **Dry-run mode** outputs the full plan with no transfers.\n4. **Wallet API only** for actual transfers — Bankr's docs deprecate the Agent API for transfers. Agent API is used only for handle→address resolution.\n\nThe two phases stay decoupled by design: the send phase is the only sanctioned transfer path and owns the idempotency state file, so the plan phase never touches transfer state. `all:` mode simply runs plan then send in sequence (plan writes the list, send reads it), so nothing is re-implemented.\n\n## Config\n\nReads two independent config\u002Fstate surfaces depending on phase:\n\n- `memory\u002Fdistributions.yml` — the distribution lists (read by **send**, written by **plan**).\n- The **plan** phase computes its ranking live from the repo's merged PRs via the GitHub API — no input file (see Phase A).\n- `memory\u002Fstate\u002Fdistributions.json` — per-recipient send idempotency (read\u002Fwritten by **send**).\n- `memory\u002Fstate\u002Fcontributor-reward-state.json` — plan idempotency + first-PR-bonus history (read\u002Fwritten by **plan**).\n\nIf `memory\u002Fdistributions.yml` is missing when the **send** phase needs it, bootstrap with a commented template (see Send Step 1) and exit cleanly with `DISTRIBUTE_TOKENS_OK — bootstrapped distributions.yml; edit and re-run`.\n\n```yaml\n# memory\u002Fdistributions.yml\ndefaults:\n  token: USDC          # USDC | ETH (Base only)\n  amount: \"5\"\n  chain: base\n\nlists:\n  contributors:\n    description: \"Weekly contributor rewards\"\n    token: USDC\n    amount: \"10\"\n    recipients:\n      - handle: \"@alice_dev\"      # Twitter\u002FX — resolved via Bankr Agent API\n        amount: \"15\"\n      - handle: \"@bob_builder\"\n      - address: \"0x742d...5678\"  # direct EVM address — preferred path\n        label: \"Charlie\"\n        amount: \"20\"\n```\n\n### Required secrets\n\n| Secret | Phase | Purpose |\n|--------|-------|---------|\n| `BANKR_API_KEY` | send (and any dry-run send, which still preflights) | Bankr API key (`bk_...`). Must be **read-write** with **Wallet API** enabled. Read-only keys → 403. **Not needed for `plan:` (pure local file I\u002FO).** |\n\n### Token addresses on Base\n\n- USDC: `0x833589fcd6edb6e08f4c7c32d4f71b54bda02913`\n- ETH (native): `tokenAddress: \"0x0000000000000000000000000000000000000000\"`, `isNativeToken: true`\n\n### Tier pricing (plan phase)\n\n| Rank in leaderboard | Reward (USDC) |\n|---------------------|---------------|\n| 1                   | 25            |\n| 2                   | 15            |\n| 3                   | 10            |\n| 4                   | 5             |\n| 5                   | 5             |\n\n**First-PR bonus:** +5 USDC, additive, applied once-ever per login (tracked in `memory\u002Fstate\u002Fcontributor-reward-state.json`). Rewards landing your first merged upstream PR — the highest-leverage signal in the leaderboard scoring.\n\n**Eligibility floor:** score ≥ 10 AND the contributor must own a non-empty `@handle` (logins without `@` prefix in the table are skipped — bots and parsing artifacts). A single merged upstream PR (+10) qualifies — the goal is to reward shipped work, not gate on volume.\n\nDefault `token: USDC` on Base. Operator can override per-recipient amounts in `memory\u002Fdistributions.yml` after the plan is written if a special bonus is warranted.\n\n---\n\nRead `memory\u002FMEMORY.md` and scan the last ~3 days of `memory\u002Flogs\u002F` for anything already reported (don't re-report the same signal).\n\n## Step 0 — Parse the selector and dispatch\n\n**Shell shape.** Each Bash call is one allowed command (pipes are fine). The run refuses a call that sets a variable (`today=$(date ...)`, `JOB=$(.\u002Fsecretcurl ...)`, `RESP=$(.\u002Fsecretcurl ...)`), uses `if` \u002F `for` \u002F `while` or `[ ... ]` tests, calls `sleep` or `sed`, or joins commands with `;`, `&&` or `||`, and each refusal costs a model turn. So get a date with a bare `date` call and write the printed value into later commands; write the repo, week bounds, logins, handles, job ids, addresses and amounts into each command literally (the `\u003CTODAY>`, `\u003CJOB_ID>`, `\u003CADDR>` style placeholders in the snippets); poll a Bankr job by repeating one call, never a loop; wait with a one-line `python3 -c \"import time; time.sleep(N)\"` call; create and change files under `memory\u002F` with Write\u002FEdit.\n\nResolve time anchors up front with one bare call:\n```bash\ndate -u +%F\n```\nIt prints `today`; `today_utc` is the same value. Later steps write it in literally as `\u003CTODAY>` (shown as `${today}` \u002F `${today_utc}` in the templates below).\n\nParse `${var}`:\n\n1. **Phase prefix.** If `${var}` starts with `plan:` → `PHASE=plan`, strip `plan:`. Else if it starts with `all:` → `PHASE=all`, strip `all:`. Else → `PHASE=send` and **do not strip anything** (the remaining legacy grammar is parsed by the send phase itself).\n2. **Dry-run.** For `PHASE=plan`\u002F`all`: if the remainder starts with `dry-run` (optionally `dry-run:`), set `MODE=dry-run` and strip that token; else `MODE=execute`. (For `PHASE=send`, the send phase parses `dry-run:` itself — see Send Step 1.)\n3. **Target.**\n   - `PHASE=send`: the (unstripped) var is the send target — `dry-run:\u003Clabel>` or `\u003Clabel>` or empty.\n   - `PHASE=plan`\u002F`all`: the remainder is an optional `\u003Cweek>`. If it matches `^\\d{4}-W\\d{2}$`, set `TARGET_WEEK=\u003Cweek>`; else run `date -u +%G-W%V` as its own Bash call and take the printed value as `TARGET_WEEK` (ISO-8601 week-numbering year + week - `%G\u002F%V` not `%Y\u002F%U`, so Monday-anchored weeks roll over correctly across years).\n\nDispatch:\n- `PHASE=plan` → run **Phase A** only.\n- `PHASE=send` → run **Phase B** only.\n- `PHASE=all` → run **Phase C** (A then B).\n\nSelector examples: `` → send first list · `contributors-2026-W17` → send that list · `dry-run:contributors-2026-W17` → dry-run send · `plan:` → plan most recent leaderboard · `plan:2026-W17` → plan that week · `plan:dry-run` → plan preview · `all:` → plan + send most recent · `all:dry-run:2026-W17` → full end-to-end preview for that week.\n\n---\n\n## Phase A — Plan (reward computation)\n\nRanks the target week's merged-PR authors (GitHub API) and turns that ranking into a tier-priced list in `memory\u002Fdistributions.yml`.\n\n### A1. Determine the target week and repo\n\n- `REPO` - the running instance's repo. Run `echo \"$GITHUB_REPOSITORY\"` as its own call; if it prints `owner\u002Frepo`, that is `REPO`. If it prints an empty line, run `git config --get remote.origin.url` as its own call and take the `owner\u002Frepo` part of the URL yourself (drop the host prefix and any trailing `.git`).\n- `TARGET_WEEK` comes from the selector; empty = the most recent **completed** ISO week (the last full Mon–Sun). Compute its UTC bounds `WEEK_START`..`WEEK_END` as ISO datetimes (`YYYY-MM-DDT00:00:00Z`).\n\n### A2. Rank contributors by merged PRs in the week\n\nCompute the ranking directly from GitHub — no upstream skill or article required.\n\n- Fetch every PR **merged inside the window**, by author (one call, with `REPO`, `WEEK_START` and `WEEK_END` written in literally):\n  `gh api -X GET search\u002Fissues -f q=\"repo:\u003CREPO> is:pr is:merged merged:\u003CWEEK_START>..\u003CWEEK_END>\" --paginate --jq '.items[].user.login'`\n- Drop bot authors (`*[bot]`, `dependabot*`, `github-actions*`). Count each remaining login's merged PRs → `score`. Rank by `score` descending; tie-break by earliest merge time, then login ascending.\n- **First-PR ✨** per ranked login - did they have any *prior* merged PR to the repo? One call per login, the login written in literally:\n  `gh api -X GET search\u002Fissues -f q=\"repo:\u003CREPO> is:pr is:merged author:\u003CLOGIN> merged:\u003C\u003CWEEK_START>\" --jq '.total_count'` → `0` means this is their first-ever merged PR (set `first_pr_marker = ✨`).\n- If zero merged PRs in the window → log `CONTRIBUTOR_REWARD_NO_MERGED_PRS — week ${TARGET_WEEK}` to `memory\u002Flogs\u002F${today}.md`, exit silently (no notify). Nothing shipped, nothing to reward.\n- If the GitHub API is unreachable (see Network note for the `gh api` → WebFetch fallback) → log `CONTRIBUTOR_REWARD_API_FAIL`, notify the operator, exit.\n\n### A3. Load plan idempotency state\n\n```json\n\u002F\u002F memory\u002Fstate\u002Fcontributor-reward-state.json\n{\n  \"weeks\": {\n    \"2026-W17\": {\n      \"written_at\": \"2026-04-26T09:00:00Z\",\n      \"label\": \"contributors-2026-W17\",\n      \"source\": \"github:merged-prs\",\n      \"rewards\": [\n        { \"login\": \"alice_dev\", \"rank\": 1, \"score\": 47, \"amount\": \"25\", \"first_pr_bonus\": false },\n        { \"login\": \"bob_builder\", \"rank\": 2, \"score\": 31, \"amount\": \"20\", \"first_pr_bonus\": true }\n      ]\n    }\n  },\n  \"first_pr_bonus_paid\": [\"bob_builder\", \"carol_eng\"]\n}\n```\n\nBootstrap with `{\"weeks\": {}, \"first_pr_bonus_paid\": []}` if the file doesn't exist.\n\n### A4. Compute the plan\n\nFor each ranked login with `rank ≤ 5` AND `score ≥ 1` (at least one merged PR):\n\n- Look up `base_amount` from the tier table (rank 1→25, 2→15, 3→10, 4-5→5).\n- If `first_pr_marker == \"✨\"` AND `login ∉ first_pr_bonus_paid` → set `first_pr_bonus = true`, `amount = base_amount + 5`. Otherwise `first_pr_bonus = false`, `amount = base_amount`.\n- Build row: `{ rank, login, score, base_amount, first_pr_bonus, amount }`.\n\nIf `weeks[TARGET_WEEK]` already exists in state → this week was already processed. Diff the current plan against `state.weeks[TARGET_WEEK].rewards` keyed on `login`:\n\n- If diffs are empty (same logins, same amounts) → log `CONTRIBUTOR_REWARD_ALREADY_PROCESSED — week ${TARGET_WEEK}`, exit silently (no notify). Idempotent re-run.\n- If diffs exist (leaderboard re-ran after first reward write — late tweet bumped a score, etc.) → flag `RE_PROCESS`. Continue but don't re-pay anyone already in `state.weeks[TARGET_WEEK].rewards`; add only the deltas. New entries get full reward; existing entries with bumped amounts get the **delta** (e.g. moved from rank 3→2 = additional 5 USDC top-up). Demoted entries are not clawed back.\n\nIf the plan is empty (zero eligible contributors after threshold + dedup) → log `CONTRIBUTOR_REWARD_NO_ELIGIBLE` and exit silently.\n\n### A5. Render the plan\n\n```\nContributor Reward Plan - ${TARGET_WEEK} (${MODE})\n\nSource: ${LEADERBOARD_FILE}\nTier: rank 1=25, 2=15, 3=10, 4-5=5 USDC; first-PR bonus +5 once per login.\n\n  ✓ #1 @alice_dev      score 47  →  25 USDC                  [NEW]\n  ✓ #2 @bob_builder    score 31  →  20 USDC (15 + 5 first-PR)[NEW + BONUS]\n  ✓ #3 @carol_eng      score 24  →  10 USDC                  [NEW]\n  ✓ #4 @dave_ops       score 18  →   5 USDC                  [NEW]\n  ↻ #5 @eve_hax        score 14  →   5 USDC                  [DEDUP - already in state]\n\nTotal to write: 60 USDC across 4 new entries.\nTotal in state for ${TARGET_WEEK} after write: 5 entries, 65 USDC.\n\nNext: distribute-tokens \"dry-run:contributors-${TARGET_WEEK}\" (preview)\n      distribute-tokens \"contributors-${TARGET_WEEK}\"          (execute)\n```\n\nIf `MODE=dry-run` (plan-only dry-run, i.e. `plan:dry-run...`): notify this plan with header `*Contributor Reward Plan — ${TARGET_WEEK}* — DRY RUN`, log to `memory\u002Flogs\u002F${today}.md`, exit `CONTRIBUTOR_REWARD_DRY_RUN`. **Do not** touch `memory\u002Fdistributions.yml` or the state file.\n\n> **`all:` mode note:** when this phase runs as part of `all:` with `MODE=dry-run`, do **not** notify here and do **not** exit — hand the computed plan rows straight to Phase B (see Phase C). When `all:` runs with `MODE=execute`, continue through A6–A8 normally but replace the trailing `Next:` line in the A9 notification with `Distributing now (phase=all)…`.\n\n### A6. Update memory\u002Fdistributions.yml  *(skipped when MODE=dry-run)*\n\nRead `memory\u002Fdistributions.yml`. If missing → bootstrap with the standard header (matching the send-phase bootstrap style):\n\n```yaml\n# memory\u002Fdistributions.yml\ndefaults:\n  token: USDC\n  amount: \"5\"\n  chain: base\n\nlists:\n```\n\nCompute the new list block:\n\n```yaml\n  contributors-${TARGET_WEEK}:\n    description: \"Weekly contributor rewards for ${TARGET_WEEK} (auto-generated from merged-PR ranking)\"\n    token: USDC\n    amount: \"5\"\n    recipients:\n      - handle: \"@alice_dev\"\n        amount: \"25\"        # rank 1\n      - handle: \"@bob_builder\"\n        amount: \"20\"        # rank 2 + first-PR bonus\n      - handle: \"@carol_eng\"\n        amount: \"10\"        # rank 3\n      - handle: \"@dave_ops\"\n        amount: \"5\"         # rank 4\n```\n\nRecipient ordering matches plan order (rank ascending). Per-recipient `amount` is required so the send phase picks up the tier-priced value rather than falling back to the list default.\n\n**Update strategy:**\n- If a list named `contributors-${TARGET_WEEK}` already exists in the YAML, **replace** it wholesale (the plan is the authoritative current state).\n- Otherwise append the block under `lists:` (preserving existing lists — never rewrite them).\n- Use a YAML-aware update: first check the existing file parses with one call, `python3 -c \"import yaml; yaml.safe_load(open('memory\u002Fdistributions.yml'))\"`, then make a careful block replacement with Edit keyed on the `^  contributors-\u003CTARGET_WEEK>:$` line (or insert the block under `lists:` with Edit). If YAML parse fails on the existing file → log error, do not write, notify the operator (file is hand-edited; auto-edit would clobber).\n\nVerify the write by re-reading the file and confirming the list is present and has `len(recipients) == len(plan)`.\n\n### A7. Update plan state file  *(skipped when MODE=dry-run)*\n\nAtomically write the updated state JSON to `memory\u002Fstate\u002Fcontributor-reward-state.json`:\n- Set `weeks[TARGET_WEEK]` = `{ written_at: now_utc, label, source: \"github:merged-prs\", rewards: [{login, rank, score, amount, first_pr_bonus}, ...] }` (full replacement on RE_PROCESS, otherwise additive).\n- Append any logins where `first_pr_bonus == true` to `first_pr_bonus_paid` (deduplicated).\n\nWrite the whole updated JSON in one Write call (never piecemeal edits or a shell redirect) so partial writes can't corrupt state.\n\n### A8. Notify  *(plan-only execute)*\n\n```\n*Contributor Reward Plan - ${TARGET_WEEK}*\n\nWrote ${N_NEW} new entries (${TOTAL_USDC} USDC) to memory\u002Fdistributions.yml as `contributors-${TARGET_WEEK}`.\n\nTop of plan:\n  #1 @alice_dev   - 25 USDC\n  #2 @bob_builder - 20 USDC (✨ first-PR bonus)\n  #3 @carol_eng   - 10 USDC\n  #4 @dave_ops    -  5 USDC\n${IF_DEDUP}\n\nSource: ${LEADERBOARD_FILE}\nFirst-PR bonuses awarded: ${LIST_OR_NONE}\n\nNext: run `distribute-tokens dry-run:contributors-${TARGET_WEEK}` to preview, then drop the `dry-run:` prefix to execute.\n\nPlan: https:\u002F\u002Fgithub.com\u002F${GITHUB_REPOSITORY}\u002Fblob\u002Fmain\u002Fmemory\u002Fdistributions.yml\n```\n\nSuppress the `${IF_DEDUP}` line when no entries were deduped. Use `$GITHUB_REPOSITORY` env var for the link target. Send via `.\u002Fnotify`.\n\n**Significance gate:** notify only when `N_NEW ≥ 1`. Re-process runs that produced zero new entries (RE_PROCESS with all rewards already paid) → silent log only. (In `all:` execute, skip this notify per the A5 note; the send-phase summary carries the report.)\n\nThen log (see **Log**) and exit `CONTRIBUTOR_REWARD_OK`.\n\n---\n\n## Phase B — Send (on-chain distribution)\n\nReads a list from `memory\u002Fdistributions.yml` and executes transfers via Bankr Wallet API. This phase moves real money — idempotency and preflight are non-negotiable.\n\nRead `memory\u002Fstate\u002Fdistributions.json` (if present) for send idempotency state before doing anything.\n\n### B1. Parse the send target and load config\n\n- If the send target starts with `dry-run:`, set `MODE=dry-run` and `LABEL=${target#dry-run:}`. Otherwise `MODE=execute` and `LABEL=${target}`. (When entered from Phase C, `LABEL` and `MODE` are set by Phase C instead — see Phase C.)\n- If `memory\u002Fdistributions.yml` missing → **Bootstrap**: write the example config from the **Config** section (commented out so it's inert), notify `DISTRIBUTE_TOKENS_OK — bootstrapped distributions.yml; edit and re-run`, log, exit.\n- Parse YAML. If `LABEL` empty, use the first list. Else find the matching list. If not found → notify `DISTRIBUTE_TOKENS_ERROR — list '${LABEL}' not found`, log, exit.\n- (`today_utc` was resolved in Step 0.)\n\n### B2. Pre-flight: key, write access, balance\n\nIf `BANKR_API_KEY` not set → `DISTRIBUTE_TOKENS_ERROR — BANKR_API_KEY not configured`, log, exit.\n\n```bash\n.\u002Fsecretcurl -fsS \"https:\u002F\u002Fapi.bankr.bot\u002Fwallet\u002Fme\" -H \"X-API-Key: {BANKR_API_KEY}\"\n```\nIt prints the `\u002Fwallet\u002Fme` body (`ME`); on an HTTP error, curl's `-fsS` prints the status code instead.\n\n- HTTP 403 → `DISTRIBUTE_TOKENS_ERROR — API key is read-only; needs wallet write scope`, exit.\n- HTTP 429 → `DISTRIBUTE_TOKENS_ERROR — rate-limited at \u002Fwallet\u002Fme; aborting`, exit.\n- Network failure → use **WebFetch** fallback. If still failing → `DISTRIBUTE_TOKENS_ERROR — Bankr \u002Fwallet\u002Fme unreachable`, exit.\n\n```bash\n.\u002Fsecretcurl -fsS \"https:\u002F\u002Fapi.bankr.bot\u002Fwallet\u002Fportfolio?chain=base\" -H \"X-API-Key: {BANKR_API_KEY}\"\n```\n\nIt prints the portfolio body (`PORTFOLIO`).\n\nExtract sender's balance for the target token. Compute `total_required` from the recipient list (sum of per-recipient amounts, applying overrides). If `balance \u003C total_required * 1.05` (5% headroom for any failed retries) → `DISTRIBUTE_TOKENS_ERROR — insufficient balance: have X, need Y ${TOKEN}`, exit. Do not start a partial run.\n\n### B3. RESOLVE phase — build the plan\n\nFor each recipient, build a row: `{key, type, amount, token, target_address, label, status}` where `key = sha256(\"${LABEL}|${recipient_id}|${today_utc}\")` and `recipient_id` is the handle (lowercase) or address (lowercase).\n\n**Idempotency check** (before resolving): if `memory\u002Fstate\u002Fdistributions.json` contains `key` with `status=completed` → mark row `SKIPPED_DEDUP`, carry forward the prior `txHash`.\n\n**Handle resolution** (`@username`): use Bankr Agent API to look up the linked wallet. One call per handle, the handle written in literally:\n```bash\n.\u002Fsecretcurl -fsS -X POST \"https:\u002F\u002Fapi.bankr.bot\u002Fagent\u002Fprompt\" \\\n  -H \"X-API-Key: {BANKR_API_KEY}\" -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\"prompt\":\"What is the EVM address linked to \u003CHANDLE> on Base? Respond with only the address.\"}' | jq -r '.jobId'\n```\nIt prints `JOB_ID`. Then poll the job: repeat this one call, with `JOB_ID` written in literally, until its `.status` is `completed` or `failed`, **at most 15 times** (the old every-2s, max-30s budget):\n```bash\n.\u002Fsecretcurl -fsS \"https:\u002F\u002Fapi.bankr.bot\u002Fagent\u002Fjob\u002F\u003CJOB_ID>\" -H \"X-API-Key: {BANKR_API_KEY}\"\n```\nIt prints the job body (`R`). If `.status` is still pending, wait 2 s with one `python3 -c \"import time; time.sleep(2)\"` call, then repeat. After the 15th call without `completed` or `failed`, stop polling and treat the handle as unresolved (below).\nExtract the address from the response (regex `0x[a-fA-F0-9]{40}`). If extraction fails → mark row `RESOLVE_FAILED` with reason `NO_LINKED_WALLET`. Do **not** abort the whole plan; let the executor skip this row.\n\n**Address resolution** (`0x...`): validate format `^0x[a-fA-F0-9]{40}$`. If invalid → `RESOLVE_FAILED` reason `BAD_ADDRESS`.\n\nAfter RESOLVE, print the plan to the console (and to the dry-run notification if `MODE=dry-run`):\n\n```\nPlan for list '${LABEL}' (${today_utc}):\n  ✓ @alice_dev → 0x1234... - 15 USDC          [READY]\n  ✓ Charlie    → 0x742d... - 20 USDC          [READY]\n  ↻ @bob_builder → 0xabcd... - 10 USDC        [SKIPPED_DEDUP] (tx 0xprev...)\n  ✗ @inactive → ?                             [RESOLVE_FAILED: NO_LINKED_WALLET]\n\nSummary: 2 to send (35 USDC), 1 deduped, 1 unresolvable. Sender balance: 100 USDC.\n```\n\nIf `MODE=dry-run`: notify the plan, log, exit `DISTRIBUTE_TOKENS_DRY_RUN`. Do not proceed.\n\nIf 0 rows are `READY` (everything deduped\u002Ffailed) → notify the plan, log, exit `DISTRIBUTE_TOKENS_OK — nothing to send`.\n\n### B4. EXECUTE phase\n\nFor each `READY` row, send via `\u002Fwallet\u002Ftransfer` (the only sanctioned transfer endpoint per Bankr docs). One call per row, with that row's address, token address, amount and native flag written in literally:\n\n```bash\n.\u002Fsecretcurl -fsS -X POST \"https:\u002F\u002Fapi.bankr.bot\u002Fwallet\u002Ftransfer\" \\\n  -H \"X-API-Key: {BANKR_API_KEY}\" -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\"recipientAddress\":\"\u003CADDR>\",\"tokenAddress\":\"\u003CTOKEN_ADDR>\",\"amount\":\"\u003CAMT>\",\"isNativeToken\":\u003CIS_NATIVE>}'\n```\n\nIt prints the response body (`RESP`), or curl's HTTP error code under `-fsS`. The sleeps below are each one `python3 -c \"import time; time.sleep(N)\"` call; a retry is the same transfer call again.\n\nOutcome handling:\n- HTTP 200 + `success: true` → status `COMPLETED`, store `txHash`. **Persist the state file immediately** (write after every recipient, not at the end — survives mid-run crashes).\n- HTTP 200 + `success: false` → status `FAILED`, store `error` field as reason.\n- HTTP 403 → status `FAILED` reason `READ_ONLY_KEY`. Abort remaining rows (key won't suddenly gain write access). Persist state.\n- HTTP 429 → status `FAILED` reason `RATE_LIMIT`. Sleep 60s, retry once. If still 429, abort remaining (rolling-window quota exhausted). Persist state.\n- HTTP 5xx or network error → retry once after 10s. If still failing, status `FAILED` reason `API_ERROR`.\n- Any other → status `FAILED` reason `HTTP_${code}`.\n\nState file shape (`memory\u002Fstate\u002Fdistributions.json`, append\u002Fupsert):\n```json\n{\n  \"contributors|@alice_dev|2026-04-20\": {\n    \"list\": \"contributors\",\n    \"recipient\": \"@alice_dev\",\n    \"address\": \"0x1234...\",\n    \"amount\": \"15\",\n    \"token\": \"USDC\",\n    \"status\": \"completed\",\n    \"txHash\": \"0xabc...\",\n    \"timestamp\": \"2026-04-20T12:34:56Z\"\n  }\n}\n```\n\n### B5. Build summary notification\n\nTop line is a verdict: `COMPLETE` (all READY succeeded) \u002F `PARTIAL` (some failed) \u002F `FAILED` (none succeeded) \u002F `DRY_RUN` \u002F `NOTHING_TO_SEND`.\n\n```\n*Token Distribution - ${today_utc}* - VERDICT\n\nList: ${LABEL} (${description})\nToken: ${TOKEN} on Base\nSent: ${total_sent} ${TOKEN} to ${n_success}\u002F${n_attempted} recipients\nSkipped (already sent today): ${n_dedup}\nUnresolvable: ${n_unresolved}\n\n✓ @alice_dev - 15 USDC ([tx](https:\u002F\u002Fbasescan.org\u002Ftx\u002F0xabc...))\n✓ Charlie (0x742d...) - 20 USDC ([tx](https:\u002F\u002Fbasescan.org\u002Ftx\u002F0x123...))\n↻ @bob_builder - 10 USDC (already sent: [tx](https:\u002F\u002Fbasescan.org\u002Ftx\u002F0xprev...))\n✗ @inactive_user - RESOLVE_FAILED: NO_LINKED_WALLET\n\nSender balance after: ${remaining} ${TOKEN}\n```\n\nSuppress empty sections (no `Skipped:` line if `n_dedup=0`, etc.). Send via `.\u002Fnotify`. Then log (see **Log**) and exit with the send verdict code (`DISTRIBUTE_TOKENS_COMPLETE` \u002F `DISTRIBUTE_TOKENS_PARTIAL` \u002F `DISTRIBUTE_TOKENS_OK` for nothing-to-send).\n\n---\n\n## Phase C — All (plan then send)\n\nRuns Phase A, then feeds it into Phase B in one invocation. `TARGET_WEEK` and `MODE` come from Step 0.\n\n**`all:` execute (`MODE=execute`):**\n1. Run **Phase A** in execute mode (A1–A8). It writes `contributors-${TARGET_WEEK}` into `memory\u002Fdistributions.yml` + state and posts the plan notification (with the A5-note tweak: trailing line becomes `Distributing now (phase=all)…`).\n2. If Phase A took a terminal early exit — `CONTRIBUTOR_REWARD_NO_LEADERBOARD`, `_STALE_LEADERBOARD`, `_PARSE_FAIL`, `_NO_ELIGIBLE`, or `_ALREADY_PROCESSED` with zero new entries — **stop**: there is nothing to send. Log and exit with that Phase A code.\n3. Otherwise set `LABEL=\"contributors-${TARGET_WEEK}\"`, `MODE=execute`, and run **Phase B** (B1 reads the just-written list from `memory\u002Fdistributions.yml`; B2–B5 as normal). The send-phase summary is the final notification.\n\n**`all:` dry-run (`MODE=dry-run`):** full end-to-end preview, **no writes, no transfers.**\n1. Run **Phase A** in dry-run mode (A1–A5) to compute the plan — but per the A5 note, do **not** notify or exit here; hold the computed plan rows in memory.\n2. Enter **Phase B** with an in-memory recipient list built from the plan rows (`handle=\"@${login}\"`, `amount=\u003Ctier amount>`) instead of reading `memory\u002Fdistributions.yml`; set `LABEL=\"contributors-${TARGET_WEEK}\"`, `MODE=dry-run`. Run B2 (preflight — this still calls Bankr `\u002Fwallet\u002Fme` + `\u002Fportfolio`, so `BANKR_API_KEY` is required for this preview; if absent, report `DISTRIBUTE_TOKENS_ERROR — BANKR_API_KEY not configured` for the send preview but keep the rendered plan) and B3 (RESOLVE + print). B3's `MODE=dry-run` branch notifies the combined preview and exits `DISTRIBUTE_TOKENS_DRY_RUN`. No state or yml is written by either phase.\n\n---\n\n## Log\n\nAppend to `memory\u002Flogs\u002F${today}.md` under **one** heading (the health loop parses this shape). Always use `### distribute-tokens`; the `Phase`\u002F`Mode` discriminator lines say which branch ran.\n\n```\n### distribute-tokens\n- Phase: plan | send | all\n- Mode: execute | dry-run\n# --- plan phase (present when Phase A ran) ---\n- Plan mode: execute | dry-run | already-processed | no-merged-prs | api-fail | no-eligible\n- Week: ${TARGET_WEEK}\n- Source: GitHub merged PRs for ${TARGET_WEEK}\n- List label: contributors-${TARGET_WEEK}\n- Entries written (new): ${N_NEW} | deduped: ${N_DEDUP} | total USDC planned: ${TOTAL_USDC}\n- First-PR bonuses: [list or \"none\"]\n# --- send phase (present when Phase B ran) ---\n- List: ${LABEL} | Token: ${TOKEN}\n- Verdict: ${VERDICT}\n- Sent: ${total_sent} ${TOKEN} to ${n_success}\u002F${n_attempted}; deduped: ${n_dedup}; unresolved: ${n_unresolved}\n- Failures (if any): @x - REASON, @y - REASON\n- State file: memory\u002Fstate\u002Fdistributions.json (${total_keys} entries)\n- Notification sent: yes\u002Fno\n```\n\nOmit the block for whichever phase did not run.\n\n## Exit codes (for downstream automation)\n\n**Plan phase (Phase A):**\n- `CONTRIBUTOR_REWARD_OK` — plan written, notification sent\n- `CONTRIBUTOR_REWARD_DRY_RUN` — plan rendered, no writes, notification sent\n- `CONTRIBUTOR_REWARD_ALREADY_PROCESSED` — week already in state with identical plan, silent exit\n- `CONTRIBUTOR_REWARD_NO_MERGED_PRS` — no PRs merged in the target week, silent exit\n- `CONTRIBUTOR_REWARD_API_FAIL` — GitHub API unreachable (`gh api` + WebFetch both failed), notified\n- `CONTRIBUTOR_REWARD_NO_ELIGIBLE` — zero contributors above threshold, silent exit\n- `CONTRIBUTOR_REWARD_ERROR` — file I\u002FO or YAML write failure, notified\n\n**Send phase (Phase B):**\n- `DISTRIBUTE_TOKENS_OK` — nothing to send (everything deduped or list empty), or bootstrap\n- `DISTRIBUTE_TOKENS_COMPLETE` — all READY rows succeeded\n- `DISTRIBUTE_TOKENS_PARTIAL` — some succeeded, some failed\n- `DISTRIBUTE_TOKENS_DRY_RUN` — dry-run completed, no sends\n- `DISTRIBUTE_TOKENS_ERROR` — preflight or config failure, no sends attempted\n\nFor `all:`, the terminal exit code is the send phase's code (or the Phase A early-exit code when the plan produced nothing to send).\n\n## Network note\n\n- **Plan phase (A):** ranks contributors via `gh api search\u002Fissues` (`gh` handles GitHub auth internally, so no secret ever lands on the command line). If `gh api` fails, fall back to **WebFetch** on the public `https:\u002F\u002Fapi.github.com\u002Fsearch\u002Fissues?q=…` URL. Also reads\u002Fwrites `memory\u002Fstate\u002Fcontributor-reward-state.json`, `memory\u002Fdistributions.yml`, `memory\u002Flogs\u002F${today}.md`. No postprocess scripts required.\n- **Send phase (B):** every Bankr call is auth'd, so make it with `.\u002Fsecretcurl` using the `{BANKR_API_KEY}` placeholder — never a bare `$BANKR_API_KEY` (the Bash permission layer refuses a secret on the command line) and never plain `curl`. `\u002Fwallet\u002Ftransfer` is an irreversible money-movement write; it runs **in-run** as the executor's final action (Phase B4), behind the B2 balance preflight and the per-recipient idempotency in `memory\u002Fstate\u002Fdistributions.json` (persisted after every send, so re-runs never double-pay). There is **no** deferred\u002Fpostprocess step — a failed transfer is recorded (`FAILED` with its reason) and the run continues to the next row. **Never silently drop a transfer.**\n\n## Constraints\n\n**Send (money movement):**\n- **Idempotency is non-negotiable.** Always read `memory\u002Fstate\u002Fdistributions.json` before sending; always persist after every transfer. Never batch state writes to end-of-run.\n- Treat the 24h Bankr rate limit (100\u002Fday standard) as a hard cap. Lists >50 recipients should be split.\n- Never send if preflight balance is \u003C `total_required * 1.05`.\n- Never use the Agent API for transfers (deprecated). Agent API only for handle→address resolution.\n- Never abort the RESOLVE phase on a single bad recipient — collect all errors, present them, then let the executor skip.\n\n**Plan (reward computation):**\n- **Idempotency is per-(week, login).** Re-runs in the same week add only deltas; demotions never claw back already-paid amounts.\n- **First-PR bonus is once-ever per login.** Track in `first_pr_bonus_paid`; never re-award even if the same person appears as ✨ in a later week (which they shouldn't, since ✨ means *first ever* merged PR — but defend against API drift).\n- **No silent overwrites of distributions.yml.** If the file exists and is malformed, fail loudly rather than rewriting.\n- **Eligibility floor stays low (≥ 1 merged PR) by design.** A single PR merged in the week qualifies — reward shipped work, not volume.\n\n## Future iterations\n\n- Schedule `all:` directly (weekly, after the week closes) for full hands-off payout — the plan computes its own ranking from merged PRs, so no upstream skill or chain wiring is needed.\n- Add a Bankr Agent API \"wallet-linked?\" pre-filter in the plan phase so contributors without linked wallets are flagged in the notification (prevents the send phase from logging RESOLVE_FAILED rows on every run).\n- Tier table should become operator-configurable via `memory\u002Fcontributor-reward-config.yml` once the first month of runs reveals the right curve. Hardcoded for v1.\n","\u003C!-- autoresearch: variation C — robustness via per-recipient idempotency state, two-phase resolve→execute, dry-run, retries, 403\u002F429 handling, recovery. Merged: contributor-reward's tier-priced reward-computation folded in as the plan\u002Finput phase; the on-chain distribution stays the execute phase. -->\n\n> **${var}** — Phase + target selector. Grammar: `[plan:|all:][dry-run:]\u003Ctarget>`\n> - `` (empty) \u002F `\u003Clabel>` \u002F `dry-run:\u003Clabel>` → **send** phase: distribute a list from `memory\u002Fdistributions.yml` (empty = first list). *[default — no prefix]*\n> - `plan:` \u002F `plan:\u003Cweek>` \u002F `plan:dry-run` \u002F `plan:dry-run:\u003Cweek>` → **plan** phase only: compute rewards from the repo's merged PRs and write the list into `memory\u002Fdistributions.yml`.\n> - `all:` \u002F `all:\u003Cweek>` \u002F `all:dry-run` \u002F `all:dry-run:\u003Cweek>` → **plan then send** in one run.\n>\n> `\u003Clabel>` is a distribution-list label (e.g. `contributors-2026-W17`). `\u003Cweek>` is an ISO week (`2026-W17`); empty `\u003Cweek>` = most recent completed ISO week. `dry-run:` previews without side effects (no yml\u002Fstate writes in plan; no transfers in send).\n\n## Why this design\n\nThis skill owns the whole contributor flywheel: **who deserves what** (plan) and **moving the money** (send). It is split into two phases that can run independently or chained.\n\n**Plan phase — the wiring the project was missing.** Merged PRs already name the people moving the project, but shipped work had no path to a wallet credit. The plan phase is that wiring: it ranks contributors by the PRs they merged in the target week (straight from the GitHub API), prices each eligible contributor against a tier table, and writes a labelled list into `memory\u002Fdistributions.yml` — the exact file the send phase reads. Keeping a human-visible diff on `memory\u002Fdistributions.yml` between plan and execution is the cheapest possible audit trail when real money is involved: the plan lands in git, and the operator (or `all:` mode, or a chained step) runs the send next.\n\n**Send phase — this moves real money.** The biggest failure mode is double-sending (re-runs, retries after partial failures, day-rollover bypass of \"skip if today\" logic) or sending into a black hole (no preflight balance, deprecated API path, missing handle resolution). The send phase therefore:\n\n1. **Persists per-recipient idempotency state** in `memory\u002Fstate\u002Fdistributions.json` keyed on `(list, recipient, date_utc)` with the txHash. A successful transfer is *never* re-sent within the same UTC day, even across re-runs or workflow restarts.\n2. **Two-phase execution**: RESOLVE (validate config, key, balance, resolve all handles → addresses, build plan) → EXECUTE (send each transfer, persist state after each one). RESOLVE failures abort before any send.\n3. **Dry-run mode** outputs the full plan with no transfers.\n4. **Wallet API only** for actual transfers — Bankr's docs deprecate the Agent API for transfers. Agent API is used only for handle→address resolution.\n\nThe two phases stay decoupled by design: the send phase is the only sanctioned transfer path and owns the idempotency state file, so the plan phase never touches transfer state. `all:` mode simply runs plan then send in sequence (plan writes the list, send reads it), so nothing is re-implemented.\n\n## Config\n\nReads two independent config\u002Fstate surfaces depending on phase:\n\n- `memory\u002Fdistributions.yml` — the distribution lists (read by **send**, written by **plan**).\n- The **plan** phase computes its ranking live from the repo's merged PRs via the GitHub API — no input file (see Phase A).\n- `memory\u002Fstate\u002Fdistributions.json` — per-recipient send idempotency (read\u002Fwritten by **send**).\n- `memory\u002Fstate\u002Fcontributor-reward-state.json` — plan idempotency + first-PR-bonus history (read\u002Fwritten by **plan**).\n\nIf `memory\u002Fdistributions.yml` is missing when the **send** phase needs it, bootstrap with a commented template (see Send Step 1) and exit cleanly with `DISTRIBUTE_TOKENS_OK — bootstrapped distributions.yml; edit and re-run`.\n\n```yaml\n# memory\u002Fdistributions.yml\ndefaults:\n  token: USDC          # USDC | ETH (Base only)\n  amount: \"5\"\n  chain: base\n\nlists:\n  contributors:\n    description: \"Weekly contributor rewards\"\n    token: USDC\n    amount: \"10\"\n    recipients:\n      - handle: \"@alice_dev\"      # Twitter\u002FX — resolved via Bankr Agent API\n        amount: \"15\"\n      - handle: \"@bob_builder\"\n      - address: \"0x742d...5678\"  # direct EVM address — preferred path\n        label: \"Charlie\"\n        amount: \"20\"\n```\n\n### Required secrets\n\n| Secret | Phase | Purpose |\n|--------|-------|---------|\n| `BANKR_API_KEY` | send (and any dry-run send, which still preflights) | Bankr API key (`bk_...`). Must be **read-write** with **Wallet API** enabled. Read-only keys → 403. **Not needed for `plan:` (pure local file I\u002FO).** |\n\n### Token addresses on Base\n\n- USDC: `0x833589fcd6edb6e08f4c7c32d4f71b54bda02913`\n- ETH (native): `tokenAddress: \"0x0000000000000000000000000000000000000000\"`, `isNativeToken: true`\n\n### Tier pricing (plan phase)\n\n| Rank in leaderboard | Reward (USDC) |\n|---------------------|---------------|\n| 1                   | 25            |\n| 2                   | 15            |\n| 3                   | 10            |\n| 4                   | 5             |\n| 5                   | 5             |\n\n**First-PR bonus:** +5 USDC, additive, applied once-ever per login (tracked in `memory\u002Fstate\u002Fcontributor-reward-state.json`). Rewards landing your first merged upstream PR — the highest-leverage signal in the leaderboard scoring.\n\n**Eligibility floor:** score ≥ 10 AND the contributor must own a non-empty `@handle` (logins without `@` prefix in the table are skipped — bots and parsing artifacts). A single merged upstream PR (+10) qualifies — the goal is to reward shipped work, not gate on volume.\n\nDefault `token: USDC` on Base. Operator can override per-recipient amounts in `memory\u002Fdistributions.yml` after the plan is written if a special bonus is warranted.\n\n---\n\nRead `memory\u002FMEMORY.md` and scan the last ~3 days of `memory\u002Flogs\u002F` for anything already reported (don't re-report the same signal).\n\n## Step 0 — Parse the selector and dispatch\n\n**Shell shape.** Each Bash call is one allowed command (pipes are fine). The run refuses a call that sets a variable (`today=$(date ...)`, `JOB=$(.\u002Fsecretcurl ...)`, `RESP=$(.\u002Fsecretcurl ...)`), uses `if` \u002F `for` \u002F `while` or `[ ... ]` tests, calls `sleep` or `sed`, or joins commands with `;`, `&&` or `||`, and each refusal costs a model turn. So get a date with a bare `date` call and write the printed value into later commands; write the repo, week bounds, logins, handles, job ids, addresses and amounts into each command literally (the `\u003CTODAY>`, `\u003CJOB_ID>`, `\u003CADDR>` style placeholders in the snippets); poll a Bankr job by repeating one call, never a loop; wait with a one-line `python3 -c \"import time; time.sleep(N)\"` call; create and change files under `memory\u002F` with Write\u002FEdit.\n\nResolve time anchors up front with one bare call:\n```bash\ndate -u +%F\n```\nIt prints `today`; `today_utc` is the same value. Later steps write it in literally as `\u003CTODAY>` (shown as `${today}` \u002F `${today_utc}` in the templates below).\n\nParse `${var}`:\n\n1. **Phase prefix.** If `${var}` starts with `plan:` → `PHASE=plan`, strip `plan:`. Else if it starts with `all:` → `PHASE=all`, strip `all:`. Else → `PHASE=send` and **do not strip anything** (the remaining legacy grammar is parsed by the send phase itself).\n2. **Dry-run.** For `PHASE=plan`\u002F`all`: if the remainder starts with `dry-run` (optionally `dry-run:`), set `MODE=dry-run` and strip that token; else `MODE=execute`. (For `PHASE=send`, the send phase parses `dry-run:` itself — see Send Step 1.)\n3. **Target.**\n   - `PHASE=send`: the (unstripped) var is the send target — `dry-run:\u003Clabel>` or `\u003Clabel>` or empty.\n   - `PHASE=plan`\u002F`all`: the remainder is an optional `\u003Cweek>`. If it matches `^\\d{4}-W\\d{2}$`, set `TARGET_WEEK=\u003Cweek>`; else run `date -u +%G-W%V` as its own Bash call and take the printed value as `TARGET_WEEK` (ISO-8601 week-numbering year + week - `%G\u002F%V` not `%Y\u002F%U`, so Monday-anchored weeks roll over correctly across years).\n\nDispatch:\n- `PHASE=plan` → run **Phase A** only.\n- `PHASE=send` → run **Phase B** only.\n- `PHASE=all` → run **Phase C** (A then B).\n\nSelector examples: `` → send first list · `contributors-2026-W17` → send that list · `dry-run:contributors-2026-W17` → dry-run send · `plan:` → plan most recent leaderboard · `plan:2026-W17` → plan that week · `plan:dry-run` → plan preview · `all:` → plan + send most recent · `all:dry-run:2026-W17` → full end-to-end preview for that week.\n\n---\n\n## Phase A — Plan (reward computation)\n\nRanks the target week's merged-PR authors (GitHub API) and turns that ranking into a tier-priced list in `memory\u002Fdistributions.yml`.\n\n### A1. Determine the target week and repo\n\n- `REPO` - the running instance's repo. Run `echo \"$GITHUB_REPOSITORY\"` as its own call; if it prints `owner\u002Frepo`, that is `REPO`. If it prints an empty line, run `git config --get remote.origin.url` as its own call and take the `owner\u002Frepo` part of the URL yourself (drop the host prefix and any trailing `.git`).\n- `TARGET_WEEK` comes from the selector; empty = the most recent **completed** ISO week (the last full Mon–Sun). Compute its UTC bounds `WEEK_START`..`WEEK_END` as ISO datetimes (`YYYY-MM-DDT00:00:00Z`).\n\n### A2. Rank contributors by merged PRs in the week\n\nCompute the ranking directly from GitHub — no upstream skill or article required.\n\n- Fetch every PR **merged inside the window**, by author (one call, with `REPO`, `WEEK_START` and `WEEK_END` written in literally):\n  `gh api -X GET search\u002Fissues -f q=\"repo:\u003CREPO> is:pr is:merged merged:\u003CWEEK_START>..\u003CWEEK_END>\" --paginate --jq '.items[].user.login'`\n- Drop bot authors (`*[bot]`, `dependabot*`, `github-actions*`). Count each remaining login's merged PRs → `score`. Rank by `score` descending; tie-break by earliest merge time, then login ascending.\n- **First-PR ✨** per ranked login - did they have any *prior* merged PR to the repo? One call per login, the login written in literally:\n  `gh api -X GET search\u002Fissues -f q=\"repo:\u003CREPO> is:pr is:merged author:\u003CLOGIN> merged:\u003C\u003CWEEK_START>\" --jq '.total_count'` → `0` means this is their first-ever merged PR (set `first_pr_marker = ✨`).\n- If zero merged PRs in the window → log `CONTRIBUTOR_REWARD_NO_MERGED_PRS — week ${TARGET_WEEK}` to `memory\u002Flogs\u002F${today}.md`, exit silently (no notify). Nothing shipped, nothing to reward.\n- If the GitHub API is unreachable (see Network note for the `gh api` → WebFetch fallback) → log `CONTRIBUTOR_REWARD_API_FAIL`, notify the operator, exit.\n\n### A3. Load plan idempotency state\n\n```json\n\u002F\u002F memory\u002Fstate\u002Fcontributor-reward-state.json\n{\n  \"weeks\": {\n    \"2026-W17\": {\n      \"written_at\": \"2026-04-26T09:00:00Z\",\n      \"label\": \"contributors-2026-W17\",\n      \"source\": \"github:merged-prs\",\n      \"rewards\": [\n        { \"login\": \"alice_dev\", \"rank\": 1, \"score\": 47, \"amount\": \"25\", \"first_pr_bonus\": false },\n        { \"login\": \"bob_builder\", \"rank\": 2, \"score\": 31, \"amount\": \"20\", \"first_pr_bonus\": true }\n      ]\n    }\n  },\n  \"first_pr_bonus_paid\": [\"bob_builder\", \"carol_eng\"]\n}\n```\n\nBootstrap with `{\"weeks\": {}, \"first_pr_bonus_paid\": []}` if the file doesn't exist.\n\n### A4. Compute the plan\n\nFor each ranked login with `rank ≤ 5` AND `score ≥ 1` (at least one merged PR):\n\n- Look up `base_amount` from the tier table (rank 1→25, 2→15, 3→10, 4-5→5).\n- If `first_pr_marker == \"✨\"` AND `login ∉ first_pr_bonus_paid` → set `first_pr_bonus = true`, `amount = base_amount + 5`. Otherwise `first_pr_bonus = false`, `amount = base_amount`.\n- Build row: `{ rank, login, score, base_amount, first_pr_bonus, amount }`.\n\nIf `weeks[TARGET_WEEK]` already exists in state → this week was already processed. Diff the current plan against `state.weeks[TARGET_WEEK].rewards` keyed on `login`:\n\n- If diffs are empty (same logins, same amounts) → log `CONTRIBUTOR_REWARD_ALREADY_PROCESSED — week ${TARGET_WEEK}`, exit silently (no notify). Idempotent re-run.\n- If diffs exist (leaderboard re-ran after first reward write — late tweet bumped a score, etc.) → flag `RE_PROCESS`. Continue but don't re-pay anyone already in `state.weeks[TARGET_WEEK].rewards`; add only the deltas. New entries get full reward; existing entries with bumped amounts get the **delta** (e.g. moved from rank 3→2 = additional 5 USDC top-up). Demoted entries are not clawed back.\n\nIf the plan is empty (zero eligible contributors after threshold + dedup) → log `CONTRIBUTOR_REWARD_NO_ELIGIBLE` and exit silently.\n\n### A5. Render the plan\n\n```\nContributor Reward Plan - ${TARGET_WEEK} (${MODE})\n\nSource: ${LEADERBOARD_FILE}\nTier: rank 1=25, 2=15, 3=10, 4-5=5 USDC; first-PR bonus +5 once per login.\n\n  ✓ #1 @alice_dev      score 47  →  25 USDC                  [NEW]\n  ✓ #2 @bob_builder    score 31  →  20 USDC (15 + 5 first-PR)[NEW + BONUS]\n  ✓ #3 @carol_eng      score 24  →  10 USDC                  [NEW]\n  ✓ #4 @dave_ops       score 18  →   5 USDC                  [NEW]\n  ↻ #5 @eve_hax        score 14  →   5 USDC                  [DEDUP - already in state]\n\nTotal to write: 60 USDC across 4 new entries.\nTotal in state for ${TARGET_WEEK} after write: 5 entries, 65 USDC.\n\nNext: distribute-tokens \"dry-run:contributors-${TARGET_WEEK}\" (preview)\n      distribute-tokens \"contributors-${TARGET_WEEK}\"          (execute)\n```\n\nIf `MODE=dry-run` (plan-only dry-run, i.e. `plan:dry-run...`): notify this plan with header `*Contributor Reward Plan — ${TARGET_WEEK}* — DRY RUN`, log to `memory\u002Flogs\u002F${today}.md`, exit `CONTRIBUTOR_REWARD_DRY_RUN`. **Do not** touch `memory\u002Fdistributions.yml` or the state file.\n\n> **`all:` mode note:** when this phase runs as part of `all:` with `MODE=dry-run`, do **not** notify here and do **not** exit — hand the computed plan rows straight to Phase B (see Phase C). When `all:` runs with `MODE=execute`, continue through A6–A8 normally but replace the trailing `Next:` line in the A9 notification with `Distributing now (phase=all)…`.\n\n### A6. Update memory\u002Fdistributions.yml  *(skipped when MODE=dry-run)*\n\nRead `memory\u002Fdistributions.yml`. If missing → bootstrap with the standard header (matching the send-phase bootstrap style):\n\n```yaml\n# memory\u002Fdistributions.yml\ndefaults:\n  token: USDC\n  amount: \"5\"\n  chain: base\n\nlists:\n```\n\nCompute the new list block:\n\n```yaml\n  contributors-${TARGET_WEEK}:\n    description: \"Weekly contributor rewards for ${TARGET_WEEK} (auto-generated from merged-PR ranking)\"\n    token: USDC\n    amount: \"5\"\n    recipients:\n      - handle: \"@alice_dev\"\n        amount: \"25\"        # rank 1\n      - handle: \"@bob_builder\"\n        amount: \"20\"        # rank 2 + first-PR bonus\n      - handle: \"@carol_eng\"\n        amount: \"10\"        # rank 3\n      - handle: \"@dave_ops\"\n        amount: \"5\"         # rank 4\n```\n\nRecipient ordering matches plan order (rank ascending). Per-recipient `amount` is required so the send phase picks up the tier-priced value rather than falling back to the list default.\n\n**Update strategy:**\n- If a list named `contributors-${TARGET_WEEK}` already exists in the YAML, **replace** it wholesale (the plan is the authoritative current state).\n- Otherwise append the block under `lists:` (preserving existing lists — never rewrite them).\n- Use a YAML-aware update: first check the existing file parses with one call, `python3 -c \"import yaml; yaml.safe_load(open('memory\u002Fdistributions.yml'))\"`, then make a careful block replacement with Edit keyed on the `^  contributors-\u003CTARGET_WEEK>:$` line (or insert the block under `lists:` with Edit). If YAML parse fails on the existing file → log error, do not write, notify the operator (file is hand-edited; auto-edit would clobber).\n\nVerify the write by re-reading the file and confirming the list is present and has `len(recipients) == len(plan)`.\n\n### A7. Update plan state file  *(skipped when MODE=dry-run)*\n\nAtomically write the updated state JSON to `memory\u002Fstate\u002Fcontributor-reward-state.json`:\n- Set `weeks[TARGET_WEEK]` = `{ written_at: now_utc, label, source: \"github:merged-prs\", rewards: [{login, rank, score, amount, first_pr_bonus}, ...] }` (full replacement on RE_PROCESS, otherwise additive).\n- Append any logins where `first_pr_bonus == true` to `first_pr_bonus_paid` (deduplicated).\n\nWrite the whole updated JSON in one Write call (never piecemeal edits or a shell redirect) so partial writes can't corrupt state.\n\n### A8. Notify  *(plan-only execute)*\n\n```\n*Contributor Reward Plan - ${TARGET_WEEK}*\n\nWrote ${N_NEW} new entries (${TOTAL_USDC} USDC) to memory\u002Fdistributions.yml as `contributors-${TARGET_WEEK}`.\n\nTop of plan:\n  #1 @alice_dev   - 25 USDC\n  #2 @bob_builder - 20 USDC (✨ first-PR bonus)\n  #3 @carol_eng   - 10 USDC\n  #4 @dave_ops    -  5 USDC\n${IF_DEDUP}\n\nSource: ${LEADERBOARD_FILE}\nFirst-PR bonuses awarded: ${LIST_OR_NONE}\n\nNext: run `distribute-tokens dry-run:contributors-${TARGET_WEEK}` to preview, then drop the `dry-run:` prefix to execute.\n\nPlan: https:\u002F\u002Fgithub.com\u002F${GITHUB_REPOSITORY}\u002Fblob\u002Fmain\u002Fmemory\u002Fdistributions.yml\n```\n\nSuppress the `${IF_DEDUP}` line when no entries were deduped. Use `$GITHUB_REPOSITORY` env var for the link target. Send via `.\u002Fnotify`.\n\n**Significance gate:** notify only when `N_NEW ≥ 1`. Re-process runs that produced zero new entries (RE_PROCESS with all rewards already paid) → silent log only. (In `all:` execute, skip this notify per the A5 note; the send-phase summary carries the report.)\n\nThen log (see **Log**) and exit `CONTRIBUTOR_REWARD_OK`.\n\n---\n\n## Phase B — Send (on-chain distribution)\n\nReads a list from `memory\u002Fdistributions.yml` and executes transfers via Bankr Wallet API. This phase moves real money — idempotency and preflight are non-negotiable.\n\nRead `memory\u002Fstate\u002Fdistributions.json` (if present) for send idempotency state before doing anything.\n\n### B1. Parse the send target and load config\n\n- If the send target starts with `dry-run:`, set `MODE=dry-run` and `LABEL=${target#dry-run:}`. Otherwise `MODE=execute` and `LABEL=${target}`. (When entered from Phase C, `LABEL` and `MODE` are set by Phase C instead — see Phase C.)\n- If `memory\u002Fdistributions.yml` missing → **Bootstrap**: write the example config from the **Config** section (commented out so it's inert), notify `DISTRIBUTE_TOKENS_OK — bootstrapped distributions.yml; edit and re-run`, log, exit.\n- Parse YAML. If `LABEL` empty, use the first list. Else find the matching list. If not found → notify `DISTRIBUTE_TOKENS_ERROR — list '${LABEL}' not found`, log, exit.\n- (`today_utc` was resolved in Step 0.)\n\n### B2. Pre-flight: key, write access, balance\n\nIf `BANKR_API_KEY` not set → `DISTRIBUTE_TOKENS_ERROR — BANKR_API_KEY not configured`, log, exit.\n\n```bash\n.\u002Fsecretcurl -fsS \"https:\u002F\u002Fapi.bankr.bot\u002Fwallet\u002Fme\" -H \"X-API-Key: {BANKR_API_KEY}\"\n```\nIt prints the `\u002Fwallet\u002Fme` body (`ME`); on an HTTP error, curl's `-fsS` prints the status code instead.\n\n- HTTP 403 → `DISTRIBUTE_TOKENS_ERROR — API key is read-only; needs wallet write scope`, exit.\n- HTTP 429 → `DISTRIBUTE_TOKENS_ERROR — rate-limited at \u002Fwallet\u002Fme; aborting`, exit.\n- Network failure → use **WebFetch** fallback. If still failing → `DISTRIBUTE_TOKENS_ERROR — Bankr \u002Fwallet\u002Fme unreachable`, exit.\n\n```bash\n.\u002Fsecretcurl -fsS \"https:\u002F\u002Fapi.bankr.bot\u002Fwallet\u002Fportfolio?chain=base\" -H \"X-API-Key: {BANKR_API_KEY}\"\n```\n\nIt prints the portfolio body (`PORTFOLIO`).\n\nExtract sender's balance for the target token. Compute `total_required` from the recipient list (sum of per-recipient amounts, applying overrides). If `balance \u003C total_required * 1.05` (5% headroom for any failed retries) → `DISTRIBUTE_TOKENS_ERROR — insufficient balance: have X, need Y ${TOKEN}`, exit. Do not start a partial run.\n\n### B3. RESOLVE phase — build the plan\n\nFor each recipient, build a row: `{key, type, amount, token, target_address, label, status}` where `key = sha256(\"${LABEL}|${recipient_id}|${today_utc}\")` and `recipient_id` is the handle (lowercase) or address (lowercase).\n\n**Idempotency check** (before resolving): if `memory\u002Fstate\u002Fdistributions.json` contains `key` with `status=completed` → mark row `SKIPPED_DEDUP`, carry forward the prior `txHash`.\n\n**Handle resolution** (`@username`): use Bankr Agent API to look up the linked wallet. One call per handle, the handle written in literally:\n```bash\n.\u002Fsecretcurl -fsS -X POST \"https:\u002F\u002Fapi.bankr.bot\u002Fagent\u002Fprompt\" \\\n  -H \"X-API-Key: {BANKR_API_KEY}\" -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\"prompt\":\"What is the EVM address linked to \u003CHANDLE> on Base? Respond with only the address.\"}' | jq -r '.jobId'\n```\nIt prints `JOB_ID`. Then poll the job: repeat this one call, with `JOB_ID` written in literally, until its `.status` is `completed` or `failed`, **at most 15 times** (the old every-2s, max-30s budget):\n```bash\n.\u002Fsecretcurl -fsS \"https:\u002F\u002Fapi.bankr.bot\u002Fagent\u002Fjob\u002F\u003CJOB_ID>\" -H \"X-API-Key: {BANKR_API_KEY}\"\n```\nIt prints the job body (`R`). If `.status` is still pending, wait 2 s with one `python3 -c \"import time; time.sleep(2)\"` call, then repeat. After the 15th call without `completed` or `failed`, stop polling and treat the handle as unresolved (below).\nExtract the address from the response (regex `0x[a-fA-F0-9]{40}`). If extraction fails → mark row `RESOLVE_FAILED` with reason `NO_LINKED_WALLET`. Do **not** abort the whole plan; let the executor skip this row.\n\n**Address resolution** (`0x...`): validate format `^0x[a-fA-F0-9]{40}$`. If invalid → `RESOLVE_FAILED` reason `BAD_ADDRESS`.\n\nAfter RESOLVE, print the plan to the console (and to the dry-run notification if `MODE=dry-run`):\n\n```\nPlan for list '${LABEL}' (${today_utc}):\n  ✓ @alice_dev → 0x1234... - 15 USDC          [READY]\n  ✓ Charlie    → 0x742d... - 20 USDC          [READY]\n  ↻ @bob_builder → 0xabcd... - 10 USDC        [SKIPPED_DEDUP] (tx 0xprev...)\n  ✗ @inactive → ?                             [RESOLVE_FAILED: NO_LINKED_WALLET]\n\nSummary: 2 to send (35 USDC), 1 deduped, 1 unresolvable. Sender balance: 100 USDC.\n```\n\nIf `MODE=dry-run`: notify the plan, log, exit `DISTRIBUTE_TOKENS_DRY_RUN`. Do not proceed.\n\nIf 0 rows are `READY` (everything deduped\u002Ffailed) → notify the plan, log, exit `DISTRIBUTE_TOKENS_OK — nothing to send`.\n\n### B4. EXECUTE phase\n\nFor each `READY` row, send via `\u002Fwallet\u002Ftransfer` (the only sanctioned transfer endpoint per Bankr docs). One call per row, with that row's address, token address, amount and native flag written in literally:\n\n```bash\n.\u002Fsecretcurl -fsS -X POST \"https:\u002F\u002Fapi.bankr.bot\u002Fwallet\u002Ftransfer\" \\\n  -H \"X-API-Key: {BANKR_API_KEY}\" -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\"recipientAddress\":\"\u003CADDR>\",\"tokenAddress\":\"\u003CTOKEN_ADDR>\",\"amount\":\"\u003CAMT>\",\"isNativeToken\":\u003CIS_NATIVE>}'\n```\n\nIt prints the response body (`RESP`), or curl's HTTP error code under `-fsS`. The sleeps below are each one `python3 -c \"import time; time.sleep(N)\"` call; a retry is the same transfer call again.\n\nOutcome handling:\n- HTTP 200 + `success: true` → status `COMPLETED`, store `txHash`. **Persist the state file immediately** (write after every recipient, not at the end — survives mid-run crashes).\n- HTTP 200 + `success: false` → status `FAILED`, store `error` field as reason.\n- HTTP 403 → status `FAILED` reason `READ_ONLY_KEY`. Abort remaining rows (key won't suddenly gain write access). Persist state.\n- HTTP 429 → status `FAILED` reason `RATE_LIMIT`. Sleep 60s, retry once. If still 429, abort remaining (rolling-window quota exhausted). Persist state.\n- HTTP 5xx or network error → retry once after 10s. If still failing, status `FAILED` reason `API_ERROR`.\n- Any other → status `FAILED` reason `HTTP_${code}`.\n\nState file shape (`memory\u002Fstate\u002Fdistributions.json`, append\u002Fupsert):\n```json\n{\n  \"contributors|@alice_dev|2026-04-20\": {\n    \"list\": \"contributors\",\n    \"recipient\": \"@alice_dev\",\n    \"address\": \"0x1234...\",\n    \"amount\": \"15\",\n    \"token\": \"USDC\",\n    \"status\": \"completed\",\n    \"txHash\": \"0xabc...\",\n    \"timestamp\": \"2026-04-20T12:34:56Z\"\n  }\n}\n```\n\n### B5. Build summary notification\n\nTop line is a verdict: `COMPLETE` (all READY succeeded) \u002F `PARTIAL` (some failed) \u002F `FAILED` (none succeeded) \u002F `DRY_RUN` \u002F `NOTHING_TO_SEND`.\n\n```\n*Token Distribution - ${today_utc}* - VERDICT\n\nList: ${LABEL} (${description})\nToken: ${TOKEN} on Base\nSent: ${total_sent} ${TOKEN} to ${n_success}\u002F${n_attempted} recipients\nSkipped (already sent today): ${n_dedup}\nUnresolvable: ${n_unresolved}\n\n✓ @alice_dev - 15 USDC ([tx](https:\u002F\u002Fbasescan.org\u002Ftx\u002F0xabc...))\n✓ Charlie (0x742d...) - 20 USDC ([tx](https:\u002F\u002Fbasescan.org\u002Ftx\u002F0x123...))\n↻ @bob_builder - 10 USDC (already sent: [tx](https:\u002F\u002Fbasescan.org\u002Ftx\u002F0xprev...))\n✗ @inactive_user - RESOLVE_FAILED: NO_LINKED_WALLET\n\nSender balance after: ${remaining} ${TOKEN}\n```\n\nSuppress empty sections (no `Skipped:` line if `n_dedup=0`, etc.). Send via `.\u002Fnotify`. Then log (see **Log**) and exit with the send verdict code (`DISTRIBUTE_TOKENS_COMPLETE` \u002F `DISTRIBUTE_TOKENS_PARTIAL` \u002F `DISTRIBUTE_TOKENS_OK` for nothing-to-send).\n\n---\n\n## Phase C — All (plan then send)\n\nRuns Phase A, then feeds it into Phase B in one invocation. `TARGET_WEEK` and `MODE` come from Step 0.\n\n**`all:` execute (`MODE=execute`):**\n1. Run **Phase A** in execute mode (A1–A8). It writes `contributors-${TARGET_WEEK}` into `memory\u002Fdistributions.yml` + state and posts the plan notification (with the A5-note tweak: trailing line becomes `Distributing now (phase=all)…`).\n2. If Phase A took a terminal early exit — `CONTRIBUTOR_REWARD_NO_LEADERBOARD`, `_STALE_LEADERBOARD`, `_PARSE_FAIL`, `_NO_ELIGIBLE`, or `_ALREADY_PROCESSED` with zero new entries — **stop**: there is nothing to send. Log and exit with that Phase A code.\n3. Otherwise set `LABEL=\"contributors-${TARGET_WEEK}\"`, `MODE=execute`, and run **Phase B** (B1 reads the just-written list from `memory\u002Fdistributions.yml`; B2–B5 as normal). The send-phase summary is the final notification.\n\n**`all:` dry-run (`MODE=dry-run`):** full end-to-end preview, **no writes, no transfers.**\n1. Run **Phase A** in dry-run mode (A1–A5) to compute the plan — but per the A5 note, do **not** notify or exit here; hold the computed plan rows in memory.\n2. Enter **Phase B** with an in-memory recipient list built from the plan rows (`handle=\"@${login}\"`, `amount=\u003Ctier amount>`) instead of reading `memory\u002Fdistributions.yml`; set `LABEL=\"contributors-${TARGET_WEEK}\"`, `MODE=dry-run`. Run B2 (preflight — this still calls Bankr `\u002Fwallet\u002Fme` + `\u002Fportfolio`, so `BANKR_API_KEY` is required for this preview; if absent, report `DISTRIBUTE_TOKENS_ERROR — BANKR_API_KEY not configured` for the send preview but keep the rendered plan) and B3 (RESOLVE + print). B3's `MODE=dry-run` branch notifies the combined preview and exits `DISTRIBUTE_TOKENS_DRY_RUN`. No state or yml is written by either phase.\n\n---\n\n## Log\n\nAppend to `memory\u002Flogs\u002F${today}.md` under **one** heading (the health loop parses this shape). Always use `### distribute-tokens`; the `Phase`\u002F`Mode` discriminator lines say which branch ran.\n\n```\n### distribute-tokens\n- Phase: plan | send | all\n- Mode: execute | dry-run\n# --- plan phase (present when Phase A ran) ---\n- Plan mode: execute | dry-run | already-processed | no-merged-prs | api-fail | no-eligible\n- Week: ${TARGET_WEEK}\n- Source: GitHub merged PRs for ${TARGET_WEEK}\n- List label: contributors-${TARGET_WEEK}\n- Entries written (new): ${N_NEW} | deduped: ${N_DEDUP} | total USDC planned: ${TOTAL_USDC}\n- First-PR bonuses: [list or \"none\"]\n# --- send phase (present when Phase B ran) ---\n- List: ${LABEL} | Token: ${TOKEN}\n- Verdict: ${VERDICT}\n- Sent: ${total_sent} ${TOKEN} to ${n_success}\u002F${n_attempted}; deduped: ${n_dedup}; unresolved: ${n_unresolved}\n- Failures (if any): @x - REASON, @y - REASON\n- State file: memory\u002Fstate\u002Fdistributions.json (${total_keys} entries)\n- Notification sent: yes\u002Fno\n```\n\nOmit the block for whichever phase did not run.\n\n## Exit codes (for downstream automation)\n\n**Plan phase (Phase A):**\n- `CONTRIBUTOR_REWARD_OK` — plan written, notification sent\n- `CONTRIBUTOR_REWARD_DRY_RUN` — plan rendered, no writes, notification sent\n- `CONTRIBUTOR_REWARD_ALREADY_PROCESSED` — week already in state with identical plan, silent exit\n- `CONTRIBUTOR_REWARD_NO_MERGED_PRS` — no PRs merged in the target week, silent exit\n- `CONTRIBUTOR_REWARD_API_FAIL` — GitHub API unreachable (`gh api` + WebFetch both failed), notified\n- `CONTRIBUTOR_REWARD_NO_ELIGIBLE` — zero contributors above threshold, silent exit\n- `CONTRIBUTOR_REWARD_ERROR` — file I\u002FO or YAML write failure, notified\n\n**Send phase (Phase B):**\n- `DISTRIBUTE_TOKENS_OK` — nothing to send (everything deduped or list empty), or bootstrap\n- `DISTRIBUTE_TOKENS_COMPLETE` — all READY rows succeeded\n- `DISTRIBUTE_TOKENS_PARTIAL` — some succeeded, some failed\n- `DISTRIBUTE_TOKENS_DRY_RUN` — dry-run completed, no sends\n- `DISTRIBUTE_TOKENS_ERROR` — preflight or config failure, no sends attempted\n\nFor `all:`, the terminal exit code is the send phase's code (or the Phase A early-exit code when the plan produced nothing to send).\n\n## Network note\n\n- **Plan phase (A):** ranks contributors via `gh api search\u002Fissues` (`gh` handles GitHub auth internally, so no secret ever lands on the command line). If `gh api` fails, fall back to **WebFetch** on the public `https:\u002F\u002Fapi.github.com\u002Fsearch\u002Fissues?q=…` URL. Also reads\u002Fwrites `memory\u002Fstate\u002Fcontributor-reward-state.json`, `memory\u002Fdistributions.yml`, `memory\u002Flogs\u002F${today}.md`. No postprocess scripts required.\n- **Send phase (B):** every Bankr call is auth'd, so make it with `.\u002Fsecretcurl` using the `{BANKR_API_KEY}` placeholder — never a bare `$BANKR_API_KEY` (the Bash permission layer refuses a secret on the command line) and never plain `curl`. `\u002Fwallet\u002Ftransfer` is an irreversible money-movement write; it runs **in-run** as the executor's final action (Phase B4), behind the B2 balance preflight and the per-recipient idempotency in `memory\u002Fstate\u002Fdistributions.json` (persisted after every send, so re-runs never double-pay). There is **no** deferred\u002Fpostprocess step — a failed transfer is recorded (`FAILED` with its reason) and the run continues to the next row. **Never silently drop a transfer.**\n\n## Constraints\n\n**Send (money movement):**\n- **Idempotency is non-negotiable.** Always read `memory\u002Fstate\u002Fdistributions.json` before sending; always persist after every transfer. Never batch state writes to end-of-run.\n- Treat the 24h Bankr rate limit (100\u002Fday standard) as a hard cap. Lists >50 recipients should be split.\n- Never send if preflight balance is \u003C `total_required * 1.05`.\n- Never use the Agent API for transfers (deprecated). Agent API only for handle→address resolution.\n- Never abort the RESOLVE phase on a single bad recipient — collect all errors, present them, then let the executor skip.\n\n**Plan (reward computation):**\n- **Idempotency is per-(week, login).** Re-runs in the same week add only deltas; demotions never claw back already-paid amounts.\n- **First-PR bonus is once-ever per login.** Track in `first_pr_bonus_paid`; never re-award even if the same person appears as ✨ in a later week (which they shouldn't, since ✨ means *first ever* merged PR — but defend against API drift).\n- **No silent overwrites of distributions.yml.** If the file exists and is malformed, fail loudly rather than rewriting.\n- **Eligibility floor stays low (≥ 1 merged PR) by design.** A single PR merged in the week qualifies — reward shipped work, not volume.\n\n## Future iterations\n\n- Schedule `all:` directly (weekly, after the week closes) for full hands-off payout — the plan computes its own ranking from merged PRs, so no upstream skill or chain wiring is needed.\n- Add a Bankr Agent API \"wallet-linked?\" pre-filter in the plan phase so contributors without linked wallets are flagged in the notification (prevents the send phase from logging RESOLVE_FAILED rows on every run).\n- Tier table should become operator-configurable via `memory\u002Fcontributor-reward-config.yml` once the first month of runs reveals the right curve. Hardcoded for v1.\n",{"name":5,"metadata":44,"description":7},{"var":45,"tags":46,"title":48,"category":47,"requires":49,"capabilities":51},"",[38,47],"crypto","Distribute Tokens",[50],"BANKR_API_KEY?",[52,53,54,55],"external_api","writes_external_host","onchain_writes","sends_notifications","main","504a21d53c0c9b485f6e90c43db83000825e1d3c","skills\u002Fdistribute-tokens",308,"https:\u002F\u002Fgithub.com\u002Faeonfun\u002Faeon","https:\u002F\u002Fwww.aeon.fun\u002F","https:\u002F\u002Fgithub.com\u002Faeonfun","The most autonomous agent framework.","2026-11-15 03:40:18",{"source":8,"skillName":5,"commands":66,"prompt":76,"zipAvailable":77},[67,70,73],{"tool":68,"command":69},"npx","npx skills add aeonfun\u002Faeon --skill distribute-tokens",{"tool":71,"command":72},"bunx","bunx skills add aeonfun\u002Faeon --skill distribute-tokens",{"tool":74,"command":75},"pnpm","pnpm dlx skills add aeonfun\u002Faeon --skill distribute-tokens","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Faeonfun\u002Faeon\u002Fblob\u002Fmain\u002Fskills\u002Fdistribute-tokens\u002FSKILL.md",true,[],[80,87,93,99,105,111],{"skillNo":81,"name":82,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":86},"01M7DSM3QWBJ44FKRMDDRAGNET","Warn Mixed Script","https:\u002F\u002Fgithub.com\u002Faeonfun\u002Faeon\u002Fblob\u002Fmain\u002Fscripts\u002Ftests\u002Fskill-scan-fixtures\u002Fwarn-mixed-script\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":88,"name":89,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":86},"01M7DSM0496DRYYW5A4NAAHZDX","Warn Hidden CSS","https:\u002F\u002Fgithub.com\u002Faeonfun\u002Faeon\u002Fblob\u002Fmain\u002Fscripts\u002Ftests\u002Fskill-scan-fixtures\u002Fwarn-hidden-css\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":86},"01M7DSKWCGDVYZSDJM31YHS2JB","Malicious Injection Uppercase","https:\u002F\u002Fgithub.com\u002Faeonfun\u002Faeon\u002Fblob\u002Fmain\u002Fscripts\u002Ftests\u002Fskill-scan-fixtures\u002Fmalicious-injection-uppercase\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":86},"01M7DSKRV2RRA1V0HK13KYWJXD","Malicious Injection Homoglyph","https:\u002F\u002Fgithub.com\u002Faeonfun\u002Faeon\u002Fblob\u002Fmain\u002Fscripts\u002Ftests\u002Fskill-scan-fixtures\u002Fmalicious-injection-homoglyph\u002FSKILL.md",[],[],{"skillNo":106,"name":107,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":86},"01M7DSKMXJKY0167YHVCKF7B49","Malicious Injection Disregard Prior","https:\u002F\u002Fgithub.com\u002Faeonfun\u002Faeon\u002Fblob\u002Fmain\u002Fscripts\u002Ftests\u002Fskill-scan-fixtures\u002Fmalicious-injection-disregard-prior\u002FSKILL.md",[],[],{"skillNo":112,"name":113,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":86},"01M7DSKGFQ5V2VNSA4K97CVFMB","Benign Greek Math","https:\u002F\u002Fgithub.com\u002Faeonfun\u002Faeon\u002Fblob\u002Fmain\u002Fscripts\u002Ftests\u002Fskill-scan-fixtures\u002Fbenign-greek-math\u002FSKILL.md",[],[]]