Skip to main content
Glama
195440

gibwork-sentinel-mcp

by 195440
README.md
# Gibwork MCP Sentinel (`gibwork-mcp-sentinel`)

> **Autonomous AI Agent & Maintainer Pre-Flight Guardrail, On-Chain Solana Vault Verifier, and Risk-Adjusted EV Router for [Gibwork](https://gib.work)**  
> Built for the **Gibwork Developer Hackathon Bounty (`1052f22d-3f87-4b1d-b0d7-71a60679e7fa`)** using `@gibwork/sdk` (`v0.2.0`), compatible with `@gibwork/cli` (`v0.2.4`) & `@gibwork/mcp` (`v0.3.1`), and anchored directly to Solana Mainnet Escrow Program `BzYr7tV2ycbQU5bXc5LGpVTfQsbs7jUcrd1DhW4ma65y`.

[![Node.js >= 22](https://img.shields.io/badge/node-%3E%3D22.0.0-brightgreen)](https://nodejs.org)
[![Gibwork SDK](https://img.shields.io/badge/%40gibwork%2Fsdk-0.2.0-6E56CF)](https://www.npmjs.com/package/@gibwork/sdk)
[![Solana Mainnet](https://img.shields.io/badge/Solana-Mainnet%20Verified-14F195)](https://explorer.solana.com/address/BzYr7tV2ycbQU5bXc5LGpVTfQsbs7jUcrd1DhW4ma65y)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)

---

## 1. Executive Summary & Use Case (Non-Web-App Developer Tooling)

**What problem does `gibwork-mcp-sentinel` solve?**

As AI coding agents (Claude Code, Codex, Cursor) and autonomous bounty hunters increasingly interact with [Gibwork](https://gib.work) via `@gibwork/sdk`, `@gibwork/cli`, and `@gibwork/mcp`, they face **four critical operational blind spots** when operating outside a browser:

1. **Discovery Pool vs. On-Chain Vault Solvency Drift**:  
   As documented in `@gibwork/sdk`, `tasks.listAvailable` reports `asset.amount` as *"the original reward pool, not remaining funds"*, while public indexer feeds (`api.gib.work/explore`) can lag behind on-chain payouts. For example, on Solana Mainnet (`2026-10-21`), task `48b29af8-6516-43cd-8407-0247497c0f9a` lists a `150 USDC` pool via SDK discovery, but its on-chain SPL Vault (`6YfKgkQkmyBhj1XfFDko4FKMmbRKYBHkPpYqeJFPgvhc`) holds only **`60 USDC`** after 90 approved payouts, with **189 pending submissions** competing for the last 60 slots (`315%` queue saturation). Similarly, task `d321ae8f-34f0-4c2f-b6ef-af7773d096ba` reports `400 CREDITS` on `api.gib.work/explore`, while its on-chain Token-2022 vault (`7TAPbWNikpJbQFzpzkwWfyRaWtKpyGi9kVPbGfk3KQtc`) holds **`200 CREDITS`** of a non-liquid token with a permanent delegate.
2. **Paid Submission Fee (`0.15 USDC`) & Eligibility Gate Waste**:  
   Every Gibwork work submission costs a **`0.15 USDC` participation fee** (`submissions.prepareCreate` / `submitCreate`). Agents that submit blindly without checking Discord role requirements (`requiredDiscordRoleIds`), X/Twitter verification (`allowOnlyVerifiedTwitterAccountSubmissions`), or queue saturation waste both compute and USDC participation fees.
3. **Silent Deliverable Link Stripping under `@gibwork/sdk` HTML Sanitization**:  
   `@gibwork/sdk` normalizes submission content through `sanitize-html` (`1–50,000` Unicode chars, strict `<a href="https://...">` transformation rules). Raw Markdown links `[repo](https://...)` or malformed relative links submitted by CLI scripts render as unclickable text or get stripped into `<span>` elements during reviewer inspection.
4. **Multi-Window Agent Swarm Collisions & Ambiguous Submit Recovery**:  
   When developers run multiple AI agent terminals concurrently, agents can accidentally claim the same bounty twice or double-pay the `0.15 USDC` fee if a network timeout triggers `GibworkAmbiguousSubmitError`.

**How `gibwork-mcp-sentinel` solves it (Pure Terminal CLI + MCP Server, Zero Web UI):**

- **Cross-Layer Vault & EV Radar (`gibwork-sentinel radar` / `sentinel_scan_ev`)**: Queries `@gibwork/sdk` (`tasks.listAvailable` + `tasks.get`), `api.gib.work/explore`, and Solana Mainnet (`BzYr7tV2ycbQU5bXc5LGpVTfQsbs7jUcrd1DhW4ma65y` 99-byte Escrow State PDA + `["vault", escrowState]` SPL/Token-2022 Vault PDA) to rank every open bounty by **Net Expected Value (EV)**, **Remaining Payout Slots**, and **Queue Coverage**.
- **Deep Forensic Escrow Audit (`gibwork-sentinel audit <taskId>` / `sentinel_audit_bounty`)**: Decodes the 99-byte Anchor Escrow State account on Solana Mainnet, verifies PDA bump seeds, fetches live vault transaction history, checks Discord/Twitter gates, and verifies worker wallet SOL/USDC readiness.
- **Pre-Flight Deliverable Contract & HTML Sanitization Guard (`gibwork-sentinel preflight` / `sentinel_preflight_deliverable`)**: Converts Markdown deliverables into `@gibwork/sdk`-compliant HTML, verifies all 6 mandatory submission gates, and generates a deterministic RFC-4122 UUIDv4 `idempotencyKey` (`sha256(taskId + walletAddress + htmlPayload)`) plus a `@gibwork/cli`-compatible `work.json` payload.
- **Multi-Window POSIX Atomic Lock & Idempotent Recovery Ledger (`gibwork-sentinel claim` / `sentinel_claim_lock` / `sentinel_prepare_submission`)**: Coordinates concurrent terminal workers via POSIX `mkdir` atomic locks and persists pre-prepare recovery records compatible with `@gibwork/sdk`'s `submissions.prepareCreate` / `getIntent` workflow.

---

## 2. Demo Video, Screenshots & Exported Artifacts

### Demo Video (Screen Recording of Setup -> Execution -> Output)
- **MP4 Demo Video URL**: [`docs/screenshots/demo-workflow.mp4`](https://github.com/195440/gibwork-mcp-sentinel/raw/main/docs/screenshots/demo-workflow.mp4)

### Terminal Screenshots (Live Solana Mainnet + `@gibwork/sdk` v0.2.0 Execution)

#### Screenshot 1: `gibwork-sentinel radar` — Cross-Layer Solana Mainnet Vault & Risk-Adjusted EV Router
![gibwork-sentinel radar](./docs/screenshots/01-sentinel-radar.png)

#### Screenshot 2: `gibwork-sentinel audit 1052f22d-3f87-4b1d-b0d7-71a60679e7fa` — On-Chain Escrow & Vault Forensics
![gibwork-sentinel audit](./docs/screenshots/02-sentinel-audit.png)

#### Screenshot 3: `gibwork-sentinel preflight` & Automated Protocol Test Suite (`npm test`)
![gibwork-sentinel preflight](./docs/screenshots/03-sentinel-preflight.png)

### Exported Deliverable Artifacts (in [`./artifacts/`](./artifacts/))
| Artifact File | Description |
| :--- | :--- |
| [`artifacts/live-mainnet-radar.json`](./artifacts/live-mainnet-radar.json) | Full JSON output of `gibwork-sentinel radar` across all 5 open Gibwork bounties on Solana Mainnet |
| [`artifacts/hackathon-bounty-audit.json`](./artifacts/hackathon-bounty-audit.json) | Deep on-chain & `@gibwork/sdk` forensic audit of `1052f22d-3f87-4b1d-b0d7-71a60679e7fa` |
| [`artifacts/preflight-validation.json`](./artifacts/preflight-validation.json) | Pre-flight contract check, link verification, and deterministic UUIDv4 `idempotencyKey` report |
| [`artifacts/work-submission-payload.json`](./artifacts/work-submission-payload.json) | Ready-to-submit `@gibwork/cli` & `@gibwork/sdk` `work.json` payload (`content` + `idempotencyKey`) |
| [`artifacts/sentinel-audit-report.md`](./artifacts/sentinel-audit-report.md) | Exported Markdown executive audit report generated by `gibwork-mcp-sentinel` |

---

## 3. Gibwork Toolset Integration (`@gibwork/sdk`, `@gibwork/mcp`, `@gibwork/cli`)

| Gibwork Component | Version | How `gibwork-mcp-sentinel` Integrates It |
| :--- | :--- | :--- |
| **`@gibwork/sdk` (`@gibwork/sdk/node`)** | `0.2.0` | Uses `createGibworkClient({ privateKey, production: true })` and `createKeypairSigner` for Ed25519 wallet-authenticated calls to `tasks.listAvailable`, `tasks.get`, `submissions.prepareCreate`, and `submissions.getIntent` against `https://sdk.gib.work`. |
| **`@gibwork/cli` Interoperability** | `0.2.4` | Generates `@gibwork/cli`-compatible `work.json` payloads (`{ content, idempotencyKey, referral, mediaIds }`) with deterministic RFC-4122 UUIDv4 keys for direct use with `gibwork submission create <task-id> --from work.json --recovery-file attempt.json`. |
| **`@gibwork/mcp` Complementarity** | `0.3.1` | Ships `gibwork-sentinel-mcp`, an MCP server over stdio exposing 6 pre-flight analytics & guardrail tools (`sentinel_scan_ev`, `sentinel_audit_bounty`, `sentinel_preflight_deliverable`, `sentinel_claim_lock`, `sentinel_prepare_submission`, `sentinel_reconcile_intent`) designed to run alongside `@gibwork/mcp`. |
| **Solana Mainnet Escrow Program** | `BzYr7tV2...ma65y` | Decodes the 99-byte Anchor Escrow State PDA (`["escrow", maker, uuid16]`, UUID at byte offset `72`) and verifies the SPL/Token-2022 Vault PDA (`["vault", escrowState]`) directly via `@solana/web3.js`. |

---

## 4. Setup & Usage Instructions

### Prerequisites
- **Node.js**: `>= 22.0.0` (required by `@gibwork/sdk`)
- **Solana Wallet Keypair** *(Optional for read-only discovery/audit; required for wallet-bound operations)*: Supports standard Solana CLI JSON byte arrays (`[1,2,3,...]`), base58 private keys, or PKCS#8 Ed25519 JSON keyfiles. If omitted during read-only commands (`radar`, `audit`, `preflight`), Sentinel automatically generates an ephemeral Ed25519 keypair to authenticate discovery requests against `https://sdk.gib.work`.

### Installation

```bash
git clone https://github.com/195440/gibwork-mcp-sentinel.git
cd gibwork-mcp-sentinel
npm install
```

### Environment Variables

| Variable | Required | Description |
| :--- | :---: | :--- |
| `GIBWORK_KEYPAIR_PATH` | Optional (Read) / Required (Write) | Path to your Solana keypair JSON file (e.g. `~/.config/solana/id.json`). Never logged or transmitted. |
| `SOLANA_PRIVATE_KEY` | Optional | Alternative to `GIBWORK_KEYPAIR_PATH`: base58 string or JSON byte array `[...]`. |
| `GIBWORK_ENVIRONMENT` | Optional | `production` (default) or `stage`. Routes `@gibwork/sdk` requests with `x-gibwork-environment: prod`. |
| `GIBWORK_RPC_URL` | Optional | Custom Solana Mainnet RPC URL (defaults to `https://api.mainnet-beta.solana.com`). |

### Running the CLI Commands

#### 1. Scan & Rank All Open Gibwork Bounties by On-Chain Vault Solvency & Net EV
```bash
node ./bin/gibwork-sentinel.mjs radar
# Or output structured JSON:
node ./bin/gibwork-sentinel.mjs radar --json --output ./artifacts/live-mainnet-radar.json
```

#### 2. Deep Forensic Audit of a Single Bounty (Escrow PDA + Vault PDA + Queue + Wallet Readiness)
```bash
node ./bin/gibwork-sentinel.mjs audit 1052f22d-3f87-4b1d-b0d7-71a60679e7fa \
  --wallet JE4JnH1Y8tYcBhhRKcTL6iqFW6xyhcsmAPsWNdapUWpg
```

#### 3. Validate Deliverable Contract & Emit `@gibwork/cli`-Compatible `work.json`
```bash
node ./bin/gibwork-sentinel.mjs preflight 1052f22d-3f87-4b1d-b0d7-71a60679e7fa \
  --file ./README.md \
  --wallet JE4JnH1Y8tYcBhhRKcTL6iqFW6xyhcsmAPsWNdapUWpg \
  --work-out ./artifacts/work-submission-payload.json
```

#### 4. Acquire or Release Multi-Window Atomic Claim Lock
```bash
node ./bin/gibwork-sentinel.mjs claim 1052f22d-3f87-4b1d-b0d7-71a60679e7fa --worker worker-gibwork
node ./bin/gibwork-sentinel.mjs claim 1052f22d-3f87-4b1d-b0d7-71a60679e7fa --release
```

#### 5. Run the Automated Unit & Protocol Test Suite
```bash
npm test
```

#### 6. Regenerate Live Mainnet Artifacts
```bash
npm run demo
```

---

## 5. Connecting `gibwork-sentinel-mcp` to Claude Code, Codex, or Cursor

Add `gibwork-sentinel-mcp` to your MCP client configuration (`~/.cursor/mcp.json` or `.claude.json`):

```json
{
  "mcpServers": {
    "gibwork-sentinel": {
      "command": "node",
      "args": ["/absolute/path/to/gibwork-mcp-sentinel/bin/gibwork-sentinel-mcp.mjs"],
      "env": {
        "GIBWORK_ENVIRONMENT": "production",
        "GIBWORK_KEYPAIR_PATH": "/absolute/path/to/solana-keypair.json"
      }
    }
  }
}
```

### Exposed MCP Tools
| MCP Tool Name | Purpose |
| :--- | :--- |
| `sentinel_scan_ev` | Cross-layer scan (`@gibwork/sdk` + `api.gib.work/explore` + Solana Mainnet Vault PDA) ranked by Net EV |
| `sentinel_audit_bounty` | Deep forensic audit of one bounty's 99-byte Escrow State PDA, Vault balance, transactions, and gates |
| `sentinel_preflight_deliverable` | Validates Markdown/HTML deliverable against `@gibwork/sdk` rules and emits deterministic UUIDv4 `idempotencyKey` |
| `sentinel_claim_lock` | Multi-window POSIX-atomic task lock (`acquire` / `release`) for concurrent AI agent fleets |
| `sentinel_prepare_submission` | Persists recovery state and prepares (or dry-runs) a `@gibwork/sdk` submission intent safely |
| `sentinel_reconcile_intent` | Reconciles an existing submission intent via local ledger and `submissions.getIntent` |

---

## 6. Sample Output (Real Solana Mainnet Run — `2026-10-21`)

```text
$ gibwork-sentinel audit 1052f22d-3f87-4b1d-b0d7-71a60679e7fa --wallet JE4JnH1Y8tYcBhhRKcTL6iqFW6xyhcsmAPsWNdapUWpg

==========================================================================================================
  GIBWORK SENTINEL FORENSIC AUDIT — Gibwork Developer Hackathon Bounty
==========================================================================================================
  Task UUID            : 1052f22d-3f87-4b1d-b0d7-71a60679e7fa
  Gibwork URL          : https://gib.work/bounties/1052f22d-3f87-4b1d-b0d7-71a60679e7fa
  Creator              : @gibwork (ID: 70b7628d-cf0b-4f5b-b8df-f7f687d3b057, Rating: 100)
  Created / Deadline   : 2026-09-08T18:26:43.726Z -> 2026-10-30T04:00:00.000Z
  Sentinel Verdict     : GATED_HIGH_EV_CLAIM (Score: 88/100, Net EV: +51.77 USDC)
----------------------------------------------------------------------------------------------------------
  [1] ON-CHAIN SOLANA MAINNET ESCROW & VAULT VERIFICATION
      Program ID       : BzYr7tV2ycbQU5bXc5LGpVTfQsbs7jUcrd1DhW4ma65y
      Escrow State PDA : CPoj222pQE9TTqd8DuXC4Q57dGKgRbXXX9EpTDGhmKfz (bump=254, 99 bytes)
      SPL Vault PDA    : 9Nw5KFDj2vZsBJnQiYpKxpr9K2P1UkJGooLX9MtPWaEd (bump=255, verified=true)
      Maker Authority  : CdJBwL9X16QaSJgjVayX3xvGwEmYenrzSE4UqywX1BN
      Token Mint       : EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v (HIGH_TRUST_SPL_USDC)
      Listed Pool      : 1000 USDC
      Live Vault Bal   : 1000 USDC (1000000000 base units)
      Pool Drift       : 0 USDC disbursed | Explore API Drift: 0 USDC
----------------------------------------------------------------------------------------------------------
  [2] QUEUE PRESSURE, PAYOUT CAPACITY & GATE ANALYSIS
      Min Submission   : 50 USDC
      Remaining Slots  : 20 minimum payouts supported by live vault
      Submissions      : 12 pending | 0 approved | 0 rejected
      Queue Coverage   : 1.667x slots/pending (60% saturation)
      Discord Gate     : Guild=1004566368475164683 | Roles=["1546941199859060768"]
      Identity Gates   : VerifiedOnly=false | TwitterVerifiedOnly=false
----------------------------------------------------------------------------------------------------------
  [3] WORKER WALLET READINESS & RECENT VAULT TRANSACTIONS
      Worker Wallet    : JE4JnH1Y8tYcBhhRKcTL6iqFW6xyhcsmAPsWNdapUWpg (file:~/.config/gibwork/solana-wallet.json)
      Wallet Balances  : 0 SOL | 0 USDC (0.15 USDC fee ready: false)
      Vault Tx         : kCeLQApVyWGuS61fNXSTde5C8Tow834aM7FE8vaStgXM5CwYodFvZRGXqRwBec4ybv8eUvPG1pykjpsVNvae8bV (Slot 445406190, 2026-09-08T18:26:43.000Z, CONFIRMED)
==========================================================================================================
```

For full technical details on the 99-byte Escrow State PDA layout, EV scoring mathematics, and idempotent recovery state machine, see [`docs/architecture.md`](./docs/architecture.md).