agentleFS
jtarorehjtaroreh/agystack/skills/cloud-swarm/SKILL.md

cloud-swarm

Skill142 starsChanged 9 days agoMITView on GitHub

Fan out more than 8 parallel workers across Google Cloud Run for large exploration sweeps, races, gauntlets, and coverage matrices. For 8 or fewer workers use a local `invoke_subagent` fan-out. For agents that collaborate on a shared board use Antigravity's built-in /swarm.

  • Reads credentials
  • Commits and pushes

The file

We split this skill into the rules it gives an agent

5 rules. About 0 are common, 2 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Before launching cloud swarms, match the model to the project's Model Garden enablement status:

    line 36
  2. Very specific:

    Create a manifest JSON array at <appDataDir>/brain/<conversation-id>/scratch/swarm-<slug>/manifest.json.

    line 51
  3. Distinctive:

    Run active pre-flight validation to ensure credentials, git remotes, model endpoints, and GCS buckets are reachable before spinning up …

    line 72
  4. Very specific:

    When coordinating asynchronously, pass --no-wait to cloud_dispatch.py to prevent blocking the agent turn:

    line 91
  5. Very specific:

    If a worker drops out or fails to report, proceed with N-1 and note the dropout explicitly.

    line 131

≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Cloud Swarm

Fan out more than 8 parallel workers across Google Cloud Run. Workers cover separate slices or race the same brief. The parent coordinator waits, aggregates, and returns one consolidated report.

Start

Open a todolist with one entry per phase before launching anything.

  1. Frame
  2. Fan out
  3. Aggregate
  4. Report

Phase A: Frame

  1. State the done predicate and the deliverable artifact or report.
  2. Choose the shape: partition into slices, race N workers on identical briefs, or mix both. For a race, declare first pass, rank all, or best-of.
  3. Set N. N is total workers.
  4. Pick worker model from swarm workers in ~/.gemini/config/plugins/agystack/agystack-models.md (default: flash).
  5. Execution routing:
    • For 8 or fewer workers (and unless agystack-runtime.json specifies "runtime": "cloud-run"), use local invoke_subagent fan-out (see skills/poteto-mode/references/antigravity-tools.md).
    • For more than 8 workers or when agystack-runtime.json specifies "runtime": "cloud-run", use Cloud Run dispatch.
  6. Exact SHAs and measurement method. When workers verify or measure commits, name the exact SHAs in each brief. When a worker measures performance or counts, also name the method (sample count, what one sample is, and execution order). Require every worker to echo both in its result.

Phase B: Fan out (Cloud Run Dispatch)

Cloud Run swarms enable parallel execution across dozens or hundreds of container tasks.

Model Selection & Friction Tiers:

Before launching cloud swarms, match the model to the project's Model Garden enablement status:

TierModelsEndpoint TypeFrictionSetup Required
Tier 1: Native MaaSgemini-4-neon, gemini-4-argon, gemini-4-hydrogen, gemini-3.8-flash, deepseek-v4.1-flashGlobal ServerlessZeroInstant via existing ADC / project IAM
Tier 2: Gated Partner MaaSclaude-3-7-sonnet, claude-3-5-sonnet, claude-3-opusRegional ServerlessLow / One-TimeConsole agreement click-through required
Tier 3: Dedicated GPUglm-5-3-flash, llama-3.3-70bDedicated EndpointHighDedicated 8x H100/B200 GPU instance provisioning

Quota & Auth Prerequisites:

  • Paid Tier API Key or Vertex AI: Cloud Run swarms require either a paid Google AI Studio tier (Pay-as-you-go / Tier 1+) or verified Vertex AI permissions (roles/aiplatform.user on the target project). Free-tier API keys (5 RPM) are prohibited as parallel container workers will immediately exhaust quota and fail.
  • Git Authentication: A valid GitHub token (gh auth token or GH_TOKEN / GITHUB_TOKEN) with repository clone access. Under the zero-push architecture, cloud containers do not require git push access.

Dispatch Workflow:

  1. Prepare Task Manifest: Create a manifest JSON array at <appDataDir>/brain/<conversation-id>/scratch/swarm-<slug>/manifest.json. The manifest supports both autonomous agent coding ("type": "agent", default) and direct command execution ("type": "command" for sweeps/benchmarks), along with optional "verify_command" and "candidate_files":
    [
      {
        "task_index": 0,
        "type": "agent",
        "branch": "worker-0",
        "brief": "Implement hypothesis A in src/ordering/mod.rs and verify with test suite.",
        "verify_command": "cargo test --release",
        "candidate_files": ["src/ordering/mod.rs"]
      },
      {
        "task_index": 1,
        "type": "command",
        "command": "python3 evaluate_slice.py --slice 0..50"
      }
    ]
  2. Execute Active Pre-Flight Check: Run active pre-flight validation to ensure credentials, git remotes, model endpoints, and GCS buckets are reachable before spinning up compute:
    python3 "${AGYSTACK_DISPATCH_SCRIPT:-$(find -L "$HOME/.gemini/config/plugins/agystack" ".agents/plugins/agystack" "skills/cloud-swarm/scripts" -name cloud_dispatch.py 2>/dev/null | head -n 1)}" --preflight --gcs-bucket <bucket> --model gemini-3.8-flash --vertex
    (Pre-flight runs automatically by default during dispatch unless --no-preflight is specified.)
  3. Launch the Swarm & Stream Real-Time Milestones: Launch cloud dispatch CLI with unbuffered streaming and fail-fast candidate evaluation:

    python3 "${AGYSTACK_DISPATCH_SCRIPT:-$(find -L "$HOME/.gemini/config/plugins/agystack" ".agents/plugins/agystack" "skills/cloud-swarm/scripts" -name cloud_dispatch.py 2>/dev/null | head -n 1)}" \
      --manifest <manifest-path> \
      --tasks <N> \
      --gcs-bucket <bucket> \
      --model gemini-3.8-flash \
      --vertex

    Pass --vertex to enable Vertex AI mode (IAM / ADC authentication) instead of Google AI Studio API key. When agystack-runtime.json specifies "auth_mode": "vertex", workers authenticate via Google Cloud IAM/ADC without requiring GEMINI_API_KEY. Concurrency (default 16) and fail-fast zero retries (--max-retries=0) are configured directly on the Cloud Run job template during /setup-agystack (setup_runtime.py).

    Asynchronous Coordination & Detached Monitoring: When coordinating asynchronously, pass --no-wait to cloud_dispatch.py to prevent blocking the agent turn:

    # Dispatch asynchronously and return execution handle immediately
    python3 "${AGYSTACK_DISPATCH_SCRIPT:-$(find -L "$HOME/.gemini/config/plugins/agystack" ".agents/plugins/agystack" "skills/cloud-swarm/scripts" -name cloud_dispatch.py 2>/dev/null | head -n 1)}" \
      --manifest <manifest-path> \
      --tasks <N> \
      --gcs-bucket <bucket> \
      --no-wait
    
    # Harvest and rank candidate patches from an existing session without launching compute
    python3 "${AGYSTACK_DISPATCH_SCRIPT:-$(find -L "$HOME/.gemini/config/plugins/agystack" ".agents/plugins/agystack" "skills/cloud-swarm/scripts" -name cloud_dispatch.py 2>/dev/null | head -n 1)}" \
      --harvest-session <session_id> --gcs-bucket <bucket> --baseline-score <float>
    
    # Attach to a running execution to stream milestones and harvest upon completion
    python3 "${AGYSTACK_DISPATCH_SCRIPT:-$(find -L "$HOME/.gemini/config/plugins/agystack" ".agents/plugins/agystack" "skills/cloud-swarm/scripts" -name cloud_dispatch.py 2>/dev/null | head -n 1)}" \
      --wait-execution <execution_name> --session <session_id> --gcs-bucket <bucket>

    The dispatcher automatically executes pre-flight checks, retrieves GH_TOKEN via gh auth token, executes the Cloud Run Job, streams real-time unbuffered [MILESTONE] execution progress directly to stdout as events occur, and aggregates final candidate patches into a ranked summary report. Dispatchers and coordinators must never block passively on buffered command execution.

    Observability, Loop Alarms & In-Flight Steering:

    • Task-Attributed Milestones: Workers emit streaming stdout milestones formatted as [MILESTONE] [TASK <i>] [PHASE: <phase>] <detail>, standardizing progress tracking and capturing internal SDK lifecycle events.
    • Loop Alarms (StagnancyTracker): Non-destructive repetitiveness detection alerts on 3 consecutive identical tool invocations ([ALARM] [TASK <i>] [POTENTIAL_LOOP]) and injects warnings into model context without terminating execution.
    • Conversational Mailbox Steering Protocol: Orchestrators steer in-flight workers asynchronously via structured GCS mailbox envelopes (MailboxEnvelope) stored under swarms/<session_id>/tasks/task-<i>/inbox/<seq>_steer.json.
      • Monotonic Sequences & Idempotency: Envelopes carry strictly monotonic sequence numbers (0001_steer.json). Workers acknowledge envelopes (status=acknowledged) and record processed sequence numbers in _seen_steer_seqs to guarantee idempotent delivery without duplicate execution across reconnects or retries.
      • GCS Timeout Resilience & Retry Logic: Storage messenger operations employ exponential backoff retry loops (retry_gcs_operation) to handle transient network timeouts and connection resets when interacting with Cloud Storage.
      • Session Mailbox Cleanup: Upon session completion, cleanup_session purges ephemeral mailbox envelopes (cleanup_mailboxes) across worker inboxes and outboxes while preserving task shadow transcripts.
    • CLI Steering Commands:
      • Directed Steering: python3 cloud_dispatch.py steer --task <index> --instruction "<text>" [--session <id>] [--gcs-bucket <bucket>]
      • Broadcast Steering: python3 cloud_dispatch.py steer --task all --instruction "<text>" [--session <id>] [--gcs-bucket <bucket>] delivers steering instructions to every worker in the swarm session.
      • Dedicated Utility: python3 steer_cloud_task.py --task <index|all> --instruction "<text>" [--session <id>] [--gcs-bucket <bucket>] [--abort] wraps steering calls with structured validation (validating task indices, non-empty instructions, monotonic sequences, and bounds checking with exit code 1 on out-of-range targets).
      • Standardized Log Output: Steering tools emit [STEER] Instruction delivered to task-<index> mailbox in GCS.
    • In-Flight Redirection & Hook Interception:
      • Workers poll their GCS inboxes inside the agent's pre-tool execution hook (pre_tool_call_decide).
      • Dynamic Focus Adaptation: General instructions emit [MILESTONE] [TASK <i>] [PHASE: STEER_APPLIED] <instruction> and inject custom context into the LLM prompt via HookResult(allow=True, custom_context=instruction).
      • Immediate Abort Directives: Instructions starting with ABORT or CANCEL emit [MILESTONE] [TASK <i>] [PHASE: ABORT_REQUESTED] <instruction> and cleanly terminate execution via HookResult(allow=False, error_message=...).
      • Dashboard Reflection: SwarmDashboardWriter captures steering dispatches to display STEER_PENDING: <instruction> under Active Phase / Tool and clears the pending status once STEER_APPLIED is acknowledged.
    • Subprocess Timeout Guards: Shell command execution and verification scripts are bounded by explicit environment timeouts (COMMAND_TIMEOUT, VERIFY_TIMEOUT), preventing hanging processes from stalling container lifecycle.

Every brief stands alone. Include goal, scope, exact slice or race arm, exact SHAs and measurement method when applicable, verification command, and expected report format ([STATUS: PASS], [STATUS: ISSUES], or [STATUS: BLOCKED] with evidence). A worker that can prove a defect reports [STATUS: ISSUES] and lists every issue it can prove, not only the first.

If a worker drops out or fails to report, proceed with N-1 and note the dropout explicitly.

Phase C: Aggregate & Early Harvest

  1. cloud_dispatch.py automatically harvests candidate patches from GCS into .slices/<session_id>/task-<i>/ and displays candidate patch file locations in the execution summary.
  2. SHA and measurement-method echo gate. Inspect terminal results and drop any result that omits the exact SHAs or measurement method named in its brief. Respawn or re-dispatch that slice once. After a second miss, record a gap. A gap never counts as a pass. For coverage sweeps, every required slice needs a result.
  3. Apply the selection rule declared up front (first pass, rank all, or best-of): rank candidates by score delta descending. Do not paste raw worker dumps.
  4. Candidate Integration Protocol: Apply the winning patch.diff to a local worktree (git apply .slices/<session_id>/task-<i>/patch.diff), run local verification, and commit. If verified, re-baseline and evaluate subsequent candidates sequentially. Never merge or compose multiple candidate patches simultaneously without intermediate verification (principle-sequence-verifiable-units).
  5. Build a compact result table, one-line evidenced issues, and explicit gaps or N-1 dropouts.

Phase D: Report

Return one consolidated in-chat report with the table, issue one-liners, gaps or dropouts, and the race rule when used.

Cloud Run Swarm Invariants

Cloud Run swarms orchestrate massive parallel worker execution across container instances:

  1. Mandatory Pre-Flight Quota & Auth Check: Cloud Run swarms must verify model availability and paid/unmetered quota tier before spinning up containers. Free-tier API keys (5 RPM) are prohibited. The dispatcher must verify that credentials can sustain the swarm workload without rate-limiting before incurring compute overhead.
  2. Model Endpoint Scoping: Google hosts Gemini 3 series models (gemini-3.8-flash, gemini-3.7-flash, etc.) exclusively on the global Vertex AI endpoint (aiplatform.googleapis.com with locations/global). Regional endpoints return HTTP 404 for Gemini 3.x. Always route Gemini 3.x requests to global and supply the X-Goog-User-Project header.
  3. Patch-over-GCS Candidate Delivery & Ghost Commit Prohibition: Cloud workers operate under a zero-push architecture and must never push to git remote branches directly. When execution yields a verified PASS with candidate source modifications outside bootstrap scaffolding, workers generate a patch.diff and upload run artifacts (score.json, patch.diff, results.tsv) directly to GCS under swarms/<session_id>/task-<i>/. The coordinator harvests patches from GCS, ranks candidate solutions by score delta, and applies the winning patch.diff locally. Cloud workers must never upload unverified infrastructure scaffolding or error-state changes as candidate patches.
  4. Active Liveness & Non-Blocking Monitoring (Cloud Run Swarms Only): Applies strictly to external detached jobs (cloud_dispatch.py --no-wait) monitored via background CLI tasks. This NEVER applies to native local Antigravity subagents (invoke_subagent), which must follow the event-driven reactive wakeup invariant (zero polling). Swarm dispatchers must never block synchronously on buffered command execution (subprocess.run with --wait and capture_output=True). The parent coordinator must maintain an active heartbeat schedule (every 60-120s), polling Cloud Run execution conditions, streaming milestone logs, and checking git remotes. Never remain passive behind a monolithic background task.
  5. Straggler Independence & Early Candidate Harvesting: Speculative candidate swarms must configure zero retries (--max-retries=0) so broken hypotheses fail fast. Coordinators monitor Cloud Run task completion and inspect storage manifests (gs://<bucket>/swarms/<session_id>/task-*). As soon as a candidate achieves a verified score win, the coordinator harvests the patch and advances it immediately rather than waiting for slow or hanging stragglers.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.