agentleFS
isabelle-barpisabelle-barp/agent-brain/skills/stack-gcp/SKILL.md

stack-gcp

Skill0 starsChanged 5 months agoApache-2.0View on GitHub

Google Cloud implementation patterns for agents working in projects whose docs/TECH_STACK.md lists `gcp`. Load when implementing, testing, reviewing, or deploying code on this stack.

  • Reads credentials

The file

We split this skill into the rules it gives an agent

5 rules. About 0 are common, 1 is distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    The Task enum is the single dispatch registry: Every task type appears once in the enum and once in the queue config.

    line 44
  2. Very specific:

    OIDC-authenticated push targets: Every httpRequest task carries oidcToken: { serviceAccountEmail, audience }.

    line 47
  3. Distinctive:

    Stateless: No in-memory session/cache that matters across requests.

    line 52
  4. Very specific:

    All rows must pass before commit per .claude/rules/LIVE_VALIDATION.md.

    line 111
  5. Very specific:

    Read-only gcloud command set for the deploy-monitor agent's post-deploy passes.

    line 115

≈ “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

Stack: Google Cloud Platform

Grounded in host-gcp's Cloud Tasks worker architecture; broader sections seeded from best practice — refine via repository-discovery.

When this applies

Detection markers (any of):

  • docs/TECH_STACK.md ## Detected stacks lists gcp
  • Dependencies: @google-cloud/* (tasks, pubsub, storage, secret-manager, firestore), firebase-admin
  • Files: firebase.json, app.yaml, cloudbuild.yaml, Terraform with the google provider
  • gcloud invocations in CI pipelines; GOOGLE_APPLICATION_CREDENTIALS in env config

Implementation patterns

Credentials (non-negotiable)

  • Application Default Credentials only. Cloud workloads get identity from their attached service account; local dev from gcloud auth application-default login. Client constructors take NO explicit credentials.
  • Never a key file in the repo — no committed JSON keys, no GOOGLE_APPLICATION_CREDENTIALS pointing at a tracked file, no key material in .env examples. A key-file path appearing in spec or code is a review BLOCKER.
  • Secret Manager wired through the config layer (ConfigService or equivalent), resolved at boot — services read config keys, never call Secret Manager mid-request.

Cloud Tasks discipline (the dispatch pattern)

One typed wrapper service is the ONLY dispatcher — no inline CloudTasksClient usage in feature code. The wrapper is the seam for tests and the single place queue routing lives:

export enum Task {
  CATEGORIZE = "categorize",
  INSIGHT_GENERATE = "insight-generate",
}

const QUEUE_CONFIG: Record<Task, { queue: string; url: string }> = {
  [Task.CATEGORIZE]: { queue: "categorize", url: "/categories/task/categorize" },
  [Task.INSIGHT_GENERATE]: { queue: "insight-generate", url: "/insights/tasks/generate" },
};

// Dispatch is always typed against the payload DTO:
await this.taskService.createTask<CategorizeTaskDto>(Task.CATEGORIZE, payload, scheduleDate);

Rules:

  • The Task enum is the single dispatch registry. Every task type appears once in the enum and once in the queue config. A createTask call with a string literal instead of an enum member is a defect.
  • Typed payload DTOs validated at the worker boundary. The dispatcher serializes a DTO; the worker handler re-validates it (class-validator/Zod) before acting. The HTTP body is untrusted input even when "we" sent it — schema drift between dispatcher and worker versions is the real failure mode.
  • Handlers are idempotent. Cloud Tasks is at-least-once delivery. Dedupe by deterministic task name (tasks/<idempotency-key> — Cloud Tasks rejects duplicate names) or by an idempotency key inside the payload checked against the DB. A handler that double-applies on redelivery is a BLOCKER.
  • OIDC-authenticated push targets. Every httpRequest task carries oidcToken: { serviceAccountEmail, audience }; the worker endpoint verifies the token. No unauthenticated task endpoints, ever.
  • Retry/backoff and rate limits are queue-level config (retryConfig.maxAttempts, minBackoff/maxBackoff, rateLimits.maxDispatchesPerSecond/maxConcurrentDispatches) — declared in IaC per queue, never improvised per call. A handler must not implement its own retry loop on top of the queue's.
  • scheduleTime is the delay mechanism — no setTimeout-style sleeping inside handlers.

Cloud Run service discipline

  • Stateless. No in-memory session/cache that matters across requests; instances are killed and scaled freely.
  • Concurrency-aware. Code runs with concurrency > 1 per instance — no global mutable per-request state, connection pools sized for it.
  • min-instances for cold-start-sensitive paths (task workers with tight deadlines, user-facing latency budgets). Accept scale-to-zero only where cold starts are tolerable.
  • Listen on PORT from env; shut down gracefully on SIGTERM (drain in-flight handlers before exit).

Pub/Sub vs Cloud Tasks (choice criterion)

  • Cloud Tasks: targeted work — one named consumer, scheduled/delayed execution, per-queue rate control, explicit task identity for dedupe. Default for async pipelines (categorization, insights, exports).
  • Pub/Sub: fan-out broadcast — multiple independent subscribers reacting to one event, no per-message scheduling. Choosing Pub/Sub for single-consumer pipeline steps adds ordering and dedupe burden for nothing; state the criterion in the spec when introducing either.

Multi-tenant orientation

  • Tenant id travels inside the payload DTO — the worker must never infer tenant from ambient state. Handlers re-establish tenant context from the payload before touching data.
  • Per-tenant rate limits at queue level where isolation matters: a dedicated queue per tenant (or tenant tier) when one tenant's burst must not starve others. Justify the cost — per-tenant queues multiply infrastructure (see Spec validation).

IaC for queues and services

  • Queues, Cloud Run services, IAM bindings, and Pub/Sub topics are Terraform (or scripted gcloud) — no console drift. A queue that exists in prod but not in IaC is a finding.
  • Dead-letter strategy declared per queue: where exhausted tasks go (DLQ topic, alerting on maxAttempts exhaustion) — silence on final failure is not a strategy.

Testing on this stack

Per .claude/rules/TESTING_INTEGRATION.md, adapted to managed-cloud reality — never real cloud in tests:

  • Unit: mock the CloudTasksClient at the service seam. The typed task wrapper IS the seam — feature tests inject { provide: TaskService, useValue: { createTask: jest.fn() } } and assert dispatch contracts against the enum registry:
expect(createTaskMock).toHaveBeenCalledWith(Task.SUBSCRIPTION_CHANGED, {
  subscriptionId, tenantId,
});
  • Integration: emulators where they exist — Pub/Sub and Firestore have official emulators; run them via Testcontainers (gcloud beta emulators ... images) per suite.
  • Cloud Tasks has NO official emulator. Two sanctioned substitutes: a community gRPC emulator for local dev (the host-gcp pattern — CloudTasksClient({ servicePath, port, sslCreds: insecure }) behind an isCloud flag), and HTTP-level fakes in tests: stub the push endpoint, invoke the handler route directly with the serialized DTO.
  • Assert idempotency by double-delivery: POST the same task body to the handler twice in one test, assert the second delivery is a no-op (same final state, no duplicate side effects). This is the at-least-once contract test — mandatory for every new handler.
  • Worker-boundary validation gets its own negative test: malformed payload → 400, never a half-executed handler.
  • Shared discipline unchanged: tests own their data (R-TESTI-04), tests clean up (R-TESTI-05), concurrency ACs fire parallel deliveries (R-TESTI-02).

Spec validation checks

Stack-specific checks the spec validators delegate here:

CheckSeverity
Async flows declare idempotency strategy for at-least-once delivery (named task or payload key)BLOCKER
Credentials/key-file paths in spec or code (committed JSON keys, GOOGLE_APPLICATION_CREDENTIALS → tracked file)BLOCKER
New task types added to the dispatch enum registry + queue config (no string-literal dispatch)BLOCKER
Queue retry/backoff/max-attempts stated for new pipelinesWARNING
Cost-amplifying per-tenant resources (queues, services, topics) carry explicit justificationWARNING
Dead-letter/alerting strategy stated for exhausted tasksWARNING

Live validation commands

R-VAL-02 matrix adapted to GCP — exact invocations live in docs/DEV_SETUP.md; obligations:

CheckTypical shape
Apply IaC to the dev project (queues, services, IAM)terraform apply / scripted gcloud target per DEV_SETUP
Smoke with read-only gcloudgcloud tasks queues list / describe <queue>, gcloud run services list — new queue/service exists with declared retry config
Double-deliver a task in dev (or emulated push)dispatch twice / replay the push request; observe idempotent outcome in data + logs
Run integration tests (emulators + HTTP fakes)affected test target per DEV_SETUP

All rows must pass before commit per .claude/rules/LIVE_VALIDATION.md.

Deployment monitoring (deploy-monitor)

Read-only gcloud command set for the deploy-monitor agent's post-deploy passes. Every command is read/list/describe/tail — a mutating verb (deploy, update, delete, set-traffic) is forbidden in this context. Exact --project/--region flags resolve from docs/DEV_SETUP.md.

PassTypical shape
Health — service/revision statusgcloud run services list / describe <svc> (Ready conditions, traffic split); gcloud run revisions list --service <svc> (revision age, serving %)
Errors — since last deploygcloud logging read 'resource.type=cloud_run_revision AND severity>=ERROR' with a --freshness window scoped to the deploy; diff error signatures vs the prior revision's window — a signature absent before the deploy is a rollback signal
Errors — aggregatedError Reporting summary where enabled (gcloud beta error-reporting events list)
Async — queue backloggcloud tasks queues describe <queue> (depth, oldest-task age); inspect the dead-letter target per queue config — DLQ growth since deploy is evidence
Alerting existsuptime checks / alert policies via gcloud monitoring (uptime list-configs, policies list) — NO alert policy on a production service is a WARNING finding

Rollback recommendation shape — emitted for the USER to run; the agent never executes it:

gcloud run services update-traffic <svc> --to-revisions <prev-revision>=100

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.