Catalogue
The primitives coding agents keep getting subtly wrong.
Every card is a reusable implementation pattern with provenance, review status and usage — not anonymous generated boilerplate. Preview the metadata for free; retrieve the verified bytes by MCP or from the console.
268 verified primitives · 10 languages
typescript
111 cardsAgent generated file allowlist
A reusable path allowlist validator that normalizes paths, blocks traversal, and checks against configurable regex rules.
Smoke utility 1783581595333
A trivial string normalization utility that trims and lowercases input, reusable and harmless.
Agent tool timeout wrapper
A generic reusable timeout wrapper that races a promise against a setTimeout-based rejection, clearing the timer afterward.
Pagination window validator
A reusable utility that validates pagination limit and offset values against integer and boundary constraints, returning an ok/reason result.
Agent search miss record
A TypeScript type definition and factory function to create a search-miss record with a normalized query and timestamp.
Search query intent expander
A pure utility function that takes a search query string and returns an expanded list of related search terms via keyword matching.
Agent context pack trim
A reusable utility that trims and packs string parts into an array without exceeding a maximum character count.
Structured error shape
Defines a StructuredError type and a helper factory function to construct standardized error objects with optional request_id.
Jittered delay milliseconds
Calcule un délai de retry avec backoff exponentiel plafonné et jitter aléatoire.
Retry budget state
A reusable retry-budget helper function that determines whether another retry attempt is allowed based on attempt limits and elapsed time.
Sensitive key redactor
A reusable recursive function that redacts values of sensitive-named keys in objects/arrays for safe logging.
Agent reusable output detector
A utility function that determines if a text output looks reusable by checking for generic keywords (like 'function', 'export', 'class') while excluding project-specific terms (like 'my company', 'private key').
Repo task fingerprint
A pure utility function that builds a deterministic fingerprint string by combining sorted top-level directory roots with a normalized task string.
Agent action confirmation gate
A reusable utility that flags whether an action requires confirmation by checking for destructive, write, or network operations against known dangerous command patterns.
Agent task risk classifier
A reusable function that classifies agent task risk as low/medium/high based on keyword matching in the input string.
Test pack to checklist
A small helper that converts a test pack's case names into checklist items with a 'pending' status. It is tightly coupled to a project-specific domain shape (pack/cases/status), making it bespoke glue rather than reusable commodity code.
Policy checklist result
A reusable utility function that aggregates policy checklist results, returning overall pass status and names of failed items.
Reusable asset manifest validator
A generic validation function checking that an asset object has a name string, a steps/changes/cases array, and a license string. It is reusable, benign commodity code with no ties to a specific project.
Runbook step status updater
Utility function to update the status of a matching runbook step in an array.
Diagnostic signature matcher
A utility function that maps error message text to standardized diagnostic identifiers by checking for keyword substrings.
Should ask user before action
A reusable helper that determines whether a given action should require user confirmation by matching it against sensitive operation keywords via regex.
Agent handoff summary
A small utility function that builds a handoff summary object from done, changed, and verification arrays plus a generation timestamp.
Agent workflow completion score
A small utility function computing the completion fraction of workflow steps based on their status.
Next.js route file detector
A pure helper function that checks if a given path is a Next.js app-router route file via a regular expression.
Exported function names
A utility that parses source code text with a regex to return a list of exported function names.
Import specifier extractor
Extracts unique import module specifiers from source code using a regex and returns them as an array.
Workspace fingerprint
A reusable utility that computes a workspace fingerprint (file count and unique sorted top-level directories) from a list of file paths.
Rollback note builder
A small utility function that returns a structured rollback note object containing a list of files and a rollback command (with a default fallback message).
Command execution plan
A helper that flags shell commands requiring approval by matching risky patterns like deploy, rm, sudo, and curl-pipe; purely analytical with no execution.
Agent review checklist
A reusable helper function that returns a review checklist, adding extra items when risk is not low.
Dependency diff summary
Computes a diff summary of dependency version maps, listing added, removed, and changed entries.
License allowlist check
A reusable utility function that returns whether a given license identifier is included in an allowlist of permissive open-source licenses.
Minimal SBOM component
A small utility function that builds a reusable SBOM component object from name, version, and type parameters.
Retrieve budget guard
A reusable pure function that validates whether a purchase is within budget by checking price is positive, within max spend, and affordable given wallet credits.
Corpus candidate priority
A reusable ranking/priority function that combines a score with trust tier, usage count (log-scaled), and a cost penalty to produce a candidate priority value.
Workflow pack builder
A reusable utility function that packs a workflow definition (name, steps, artifacts) into a structured object with pending statuses and a creation timestamp.
Suggest install command
A utility function that returns the appropriate install command string (pnpm/yarn/npm/bun) for a given package manager name.
Detect package manager
Detects the package manager (pnpm/yarn/npm/bun) based on the presence of lockfiles in a file list.
Infer framework from files
A helper function that infers a project's framework (Next.js, Vite, FastAPI, Go, Docker Compose) by checking for characteristic config files in a filename list.
Infer language from file path
A reusable helper that infers a programming language from a file path's extension using a static extension-to-language mapping.
Corpus query expansion
A query expansion utility that adds synonym terms to a search string based on a static synonym map.
Agent task intent classifier
A utility function that classifies an agent task into categories (testing, devops, security, api, debugging, implementation) based on keyword pattern matching in the input text.
Agent dependency manifest check
A utility function that checks whether a list of file paths includes any dependency manifest or lock files (package-lock.json, pnpm-lock.yaml, yarn.lock, requirements.txt, go.mod).
Agent todo from diff
A pure utility function that extracts added TODO lines from a git diff string.
Test command suggestion
A helper that suggests an appropriate test command (pytest, npm test, go test) based on file extensions present in a list.
Agent artifact manifest
A small utility that creates an artifact manifest object containing a name, sorted file list, and generation timestamp.
Filesystem path inside root
A reusable utility function that verifies a target path is contained within a given root directory to prevent path traversal.
Env file safety check
A reusable utility function that returns true only if a given path does NOT match patterns for sensitive files like .env files or secrets/credentials directories, serving as a safety check.
No secret in patch check
A reusable utility function that checks whether a given text contains common secret patterns (OpenAI keys, AWS access keys, private keys, Slack tokens) via regex matching.
Agent savings observation
A utility function that calculates token savings between a baseline and actual value, returning saved tokens and savings rate.
Corpus retrieve decision
A small business-logic predicate that decides whether to retrieve a corpus based on a score threshold and wallet/price credit comparison. It is project-specific glue tied to a credits/wallet domain rather than a reusable commodity utility.
Corpus search result scorer
A simple search result scoring function that counts query term matches in title/summary and adds a bonus for language matches.
Prompt budget splitter
A utility function that divides a total token count into system/context/task/output budget portions using fixed ratios.
Context pack builder
A reusable utility function that selects files up to a maximum character limit and returns them with a total character count.
Patch risk estimate
A reusable utility function that estimates patch risk by counting files matching sensitive-keyword patterns (auth, billing, crypto, etc.) and returning high/medium/low.
Unified diff hunk count
Counts the number of hunks in a unified diff by counting lines starting with '@@'.
Unified diff changed files
A reusable utility that extracts the list of changed file paths from a git diff string by matching '+++ b/' lines.
Select relevant files by keywords
A utility function that selects and ranks file paths based on keyword relevance scoring, returning the top N matches.
Repo file extension summary
A reusable utility that tallies file extensions from a list of paths, returning a count map keyed by lowercase extension (or 'none').
Dangerous shell command detector
A reusable utility function that detects potentially dangerous shell commands via regex pattern matching, returning a boolean.
Agent command allowlist
A generic reusable helper that validates whether a command's first word is in a given allowlist array.
MCP error result
A helper function that returns a structured MCP error response containing a JSON-serialized error message and optional hint.
MCP tool descriptor builder
A small helper defining a JsonSchema type and an mcpTool factory function returning an object with name, description, and inputSchema.
Safe JSON response parse
A generic helper that safely parses a fetch Response body as JSON, returning null on empty or invalid content.
Corpus reuse savings estimate
Utility function estimating tokens and seconds saved based on code and generated character counts.
Agent context budget gate
A utility function estimating whether text fits within a token budget based on approximate character-to-token ratio.
Agent tool call envelope
A small helper that wraps a tool call name and arguments into an envelope object with an ISO timestamp.
API contract status assertion
A reusable helper function that asserts an HTTP Response has the expected status code, throwing an error with the response body otherwise.
Vitest table test helper
A generic table-driven test utility that runs a callback for each case in an array, naming each test via JSON.stringify.
SQL where builder
A reusable helper that builds a parameterized SQL WHERE clause from a filters object, skipping empty values and returning the SQL string with bound values.
Constant time string compare
A reusable constant-time string equality helper using Node's crypto.timingSafeEqual with a length guard.
IP block key
A reusable utility that normalizes an IPv4 or IPv6 address into its subnet block key (/24 or /64) for grouping/rate-limiting purposes.
Origin allowlist check
A reusable utility function that checks whether a given origin string is present in an allowlist, safely handling null/invalid inputs.
Parse integer range
A reusable helper that validates and clamps an integer value within a min/max range, with a fallback for non-integers.
Normalize email address
A reusable utility function that normalizes an email address by trimming and lowercasing it.
Require string field
A generic reusable validation function that returns an error message if a specified field is not a non-empty string.
Zod-like validation result
A reusable generic TypeScript object validation helper returning a discriminated union result type.
Express JSON error handler
A reusable JSON error-handling middleware that responds with an appropriate HTTP status and sanitized error message.
Express request id middleware
A reusable request-ID middleware that reads or generates an x-request-id and sets it on the request object and response header.
Express async handler
A reusable async middleware wrapper for Express-style handlers that forwards rejected promises to the next() error handler.
React async state hook
A reusable React custom hook (useAsyncState) that manages loading, data, and error state for an async function with proper cleanup.
React local storage state hook
A reusable generic React hook (useLocalStorageState) that persists component state to localStorage and reads it back on initialization.
React debounce hook
A generic, reusable React hook that debounces a value with a configurable delay.
Normalize slug path
A reusable utility function that normalizes a string into a URL-safe slug path.
Safe redirect path
A reusable helper that validates a redirect path, returning a fallback unless the input is a safe relative path (starts with single slash, not protocol-relative).
Password policy check
A reusable password policy validator that enforces minimum length, mixed case, and numeric requirements.
Agent retrieval receipt
A small utility function that builds a retrieval receipt object with metadata and a current timestamp.
MCP tool result text
A reusable utility that wraps a value into an MCP-style text content result object, JSON-stringifying non-string inputs.
Vitest fetch mock
A reusable helper that mocks globalThis.fetch in Vitest tests, returning a configurable JSON Response with a given status code — a drop-in fetch mock for Vitest test suites.
Transaction helper
Generic reusable transaction helper that wraps a callback in begin/commit/rollback logic with proper error handling.
Env schema validator
A reusable utility that validates the presence of required environment variables and returns them, throwing an error if any are missing.
API pagination response
A generic pagination utility function that returns a page of items with a next cursor and count.
Cursor pagination params
A reusable cursor-based pagination helper that safely parses and clamps limit and cursor values from URL query parameters.
Idempotency key builder
A utility function that builds an idempotency key by normalizing and joining array parts with colons.
Require bearer auth guard
A reusable helper that validates a Bearer authorization header against an expected token, throwing 'Unauthorized' on mismatch.
Bearer token extractor
A Bearer token extractor: a reusable utility function that parses the Bearer token from an HTTP Authorization header, returning the token string or null.
Next.js POST body parser
A generic reusable helper that validates content-type and parses a JSON request body into a typed object.
Next.js JSON route handler
A minimal API route handler returning a JSON status object with the current timestamp, typical of a health/status endpoint tied to a specific project's framework.
health check response
A TypeScript helper that constructs a health-check response object with status, ok flag, checks map, and timestamp.
create token bucket limiter
A reusable rate-limiting utility implementing a sliding-window token bucket keyed by string identifiers.
redact log payload
A reusable utility that recursively redacts sensitive fields from objects/arrays before logging.
keyBy (index array by key)
A generic keyBy utility that converts an array into a Record keyed by a chosen property.
tryCatch (Result wrapper)
A generic Result<T> type and tryCatch helper that wraps a promise, returning either a success value or an error object. Reusable commodity utility with no project-specific coupling.
assertNever (exhaustiveness check)
A reusable TypeScript 'assertNever' helper for exhaustive type checking that throws an error for unexpected values.
omit keys from object
A generic 'omit' utility that returns a copy of an object excluding the specified keys.
safe JSON parse
A generic safeJsonParse utility that parses JSON and returns a fallback on failure.
Password hashing with scrypt (zero-dep, self-describing format)
Reusable password hashing/verification utility built on Node's crypto scrypt with a self-describing hash format and constant-time comparison.
Keyset (cursor-based) pagination helper
Generic opaque-cursor keyset pagination utility with encode/decode helpers and a reusable paginateByCursor function.
Generic HMAC-SHA256 webhook signature verification (constant-time, replay guard)
A reusable, provider-agnostic HMAC-SHA256 webhook signature verification utility with optional timestamp-based replay protection.
HS256 JWT sign + verify (zero dependency, constant-time)
A reusable HS256 JWT signing and verification utility with constant-time signature comparison and exp/nbf validation.
Retry with exponential backoff and full jitter
A reusable async retry helper implementing exponential backoff with full jitter, configurable via options with custom shouldRetry/onRetry callbacks.
javascript
66 cardsGroup files by top folder
A reusable utility function that counts files grouped by their top-level folder derived from splitting each path on '/'.
Read git status porcelain
Parses git status --porcelain text output into an array of {status, path} objects.
Recommended package test script
A small utility that returns the preferred test script name from a package's scripts, checking 'test', 'test:unit', then 'vitest'.
Parse package scripts
A reusable utility that extracts the scripts field from a package.json object or string, with type checks and a safe fallback to an empty object.
Extract fenced code blocks
Extracts fenced code blocks (with their info string and content) from a markdown string using a regex.
Append file section once
A reusable utility function that idempotently appends a heading and section to a content string only if the heading is not already present.
Insert text before marker
A generic string utility that inserts text before a specified marker within a string, throwing an error if the marker is not found.
Apply simple text replacement patch
A reusable helper that performs a single string replacement on content, throwing an error if the search text is not found.
Parse duration milliseconds
A utility function that parses duration strings like '5s' or '10m' into milliseconds.
URL safe base64 encode
A reusable utility function that encodes input to URL-safe base64 (base64url) format.
Verify signed cookie value
A reusable utility function that verifies HMAC-signed cookies using SHA256 and a constant-time comparison to extract and validate the signed value.
Signed cookie value
A reusable utility function that signs a cookie value with HMAC-SHA256 using a provided secret and appends the base64url signature.
Exponential moving average
A reusable utility function that computes an exponential moving average from a previous value and next value with a configurable alpha smoothing factor.
Content security policy header
A reusable helper that builds a restrictive Content Security Policy header string.
Prompt token budget estimate
A generic utility function estimating prompt token count from text length.
SQLite upsert statement
A reusable helper that generates a parameterized SQLite INSERT ... ON CONFLICT DO UPDATE (upsert) SQL string from table, columns, and conflict column.
CORS preflight response
A reusable helper function that returns a 204 CORS preflight Response with configurable allowed origin and standard headers.
Webhook HMAC verifier
A reusable HMAC-SHA256 signature verification helper using constant-time comparison.
safe shell arg quote
A reusable utility function that safely quotes/escapes a string value for shell command usage using standard POSIX single-quote escaping.
run command with timeout
Fonction réutilisable exécutant une commande enfant de manière sécurisée (shell:false), avec timeout et capture de sortie.
poll until condition
A generic reusable polling helper that repeatedly invokes a check function at intervals until it succeeds or a timeout is reached.
HTTP JSON request
A reusable async helper that performs a JSON fetch request with configurable method, headers, body, and a timeout using AbortController.
retry async with jitter
A reusable async retry helper implementing exponential backoff with jitter over a configurable number of attempts.
create TTL cache
A reusable TTL (time-to-live) cache factory using a Map, with get/set/clear methods that expire entries after a configurable duration.
JSON lines encode
Reusable utility functions to encode and decode JSON Lines (JSONL) format.
stable JSON stringify
A stable JSON stringify utility that recursively serializes values with sorted object keys for deterministic output.
require environment variables
A utility function that reads and validates required environment variables, returning their values or throwing an error listing missing ones.
parse CLI flags
A reusable CLI argument parser that converts argv into an object, handling --key=value, --key value, boolean flags, and positional args with camelCase key conversion.
pipe (left-to-right compose)
A generic pipe/compose utility that chains functions together, passing each result as input to the next.
uuid v4
A reusable UUID v4 generator that prefers the native crypto.randomUUID API and falls back to a Math.random-based implementation.
random integer in range
A reusable utility function returning a random integer between min and max inclusive.
round to decimals
A reusable utility function that rounds a numeric value to a given number of decimal places using a standard floating-point correction technique.
sum and average
Reusable math helper functions: sum and average of a number array.
partition
A reusable utility function that splits an array into passing and failing elements based on a predicate.
countBy
A reusable utility function that counts array elements grouped by a computed key, returning a tally object.
sortBy (by key or fn)
A reusable utility that returns a sorted copy of an array based on a key or accessor function.
isEqual (deep equality)
A recursive deep-equality utility function comparing two values/objects for structural equality.
mapValues
A reusable utility function that creates a new object by applying a transformation function to each value of the input object.
pickBy (filter object by predicate)
A generic reusable utility function (pickBy) that returns a new object containing only the key-value pairs that satisfy a given predicate.
deep merge
A generic recursive deepMerge function combining two objects, with nested object merging.
get (deep path access)
A reusable 'get' utility that safely accesses nested object properties via a dot-path or key array, returning a fallback when undefined.
word count
A reusable utility function that counts the number of words in a string by matching non-whitespace sequences.
snakeCase
A reusable string utility function that converts strings to snake_case formatting.
camelCase
A reusable utility function that converts hyphen/underscore/space-separated strings to camelCase.
capitalize
A reusable utility function that capitalizes the first character of a string.
once (call a function a single time)
A reusable 'once' higher-order function that wraps a function so it executes only once and caches its result.
is valid email
A reusable email validation utility that checks if a string matches a basic email format using a regular expression.
format number (thousands)
A reusable utility function that formats a number according to a given locale using Intl.NumberFormat.
range
A reusable utility function that generates an array of numbers from start to end with a given step, supporting both ascending and descending ranges.
shuffle array (Fisher-Yates)
A generic Fisher-Yates array shuffle function that returns a shuffled copy of the input array.
time ago (relative time)
A reusable 'time ago' formatting helper that converts a date into a French relative time string (e.g., 'il y a 5 min').
truncate string
A generic, reusable string truncation helper that shortens text to a maximum length and appends a suffix (default ellipsis).
escape HTML
A reusable HTML-escaping utility that converts special characters (&, <, >, ", ') into their corresponding HTML entities.
deep clone
A reusable deepClone function that uses structuredClone when available, otherwise recursively clones arrays and objects.
fetch with timeout
A reusable utility function that wraps fetch with a configurable timeout using AbortController.
copy to clipboard
A reusable clipboard copy helper with a textarea fallback for non-secure contexts.
toast notification
A reusable toast notification function that displays styled, auto-dismissing messages in a fixed corner container.
groupBy
A generic groupBy utility that groups array items into an object keyed by a function-derived key.
clamp
A reusable clamp utility function that constrains a value within a min/max range.
Format bytes to human readable (JavaScript)
A JavaScript byte-formatting helper that converts numeric byte values into human-readable units (B, KB, MB, etc.).
uniqueBy
A reusable utility function that removes duplicate items from an array based on a key extracted by a provided function.
chunk array
A reusable array chunking utility that splits an array into subarrays of a specified size, with validation that size is at least 1.
slugify
A reusable slugify utility that normalizes a string into a URL-friendly slug by stripping diacritics, lowercasing, and replacing non-alphanumeric characters with hyphens.
sleep
A reusable sleep utility that returns a Promise resolving after a specified number of milliseconds.
throttle
A generic throttle higher-order function that limits how often the wrapped function can be invoked within a given interval.
debounce
A generic, reusable debounce higher-order function that delays invocation of a callback until after a configurable wait period.
python
55 cardsPython pagination window validator
Validates pagination limit/offset against configurable bounds, returning a status dict.
Python context pack trim
A utility function that filters and truncates a list of text parts to stay within a specified character limit.
Python structured error shape
A reusable helper function that builds a structured error dictionary with code, message, retryable flag, and optional request_id.
Python jittered delay milliseconds
A reusable utility function computing jittered exponential backoff delays in milliseconds for retry logic.
Python sensitive key redactor
A reusable recursive utility that redacts values of sensitive-named keys in nested dict/list structures using a regex match.
Python repo task fingerprint
A pure string utility that builds a fingerprint from file path roots and a normalized task string; no security concerns and reusable in nature.
Python agent task risk classifier
A function that classifies task risk (high/medium/low) based on presence of sensitive keywords in input text.
Python policy checklist result
A generic helper that checks a list of items for a 'passed' flag and returns aggregate pass/fail status.
Python test pack checklist
A pure utility function that transforms a list of names into checklist dictionaries with a default 'pending' status.
Python diagnostic signature matcher
A reusable helper function that maps error message text to known diagnostic category labels via substring matching.
Python command execution plan
A function that builds an execution plan marking commands as requiring approval if they match risky patterns via regex.
Python license allowlist check
A reusable utility function that checks whether a given license name is within an allowlist of permissive licenses (defaulting to common OSS licenses).
Python infer language from path
A helper function that infers a programming language from a file path's extension using a lookup dictionary, defaulting to 'text'.
Python expand corpus query
A query expansion helper that augments search terms using a static synonym dictionary, returning a sorted, space-joined string.
Python classify agent task
A reusable utility function that classifies agent task descriptions into categories (testing, devops, security, api, implementation) based on keyword regex matching.
Python corpus result score
A generic relevance-scoring function that counts query term matches in a result's title/summary and boosts the score for matching language.
Python token budget estimate
A reusable utility function that estimates token count from text length using a rough characters-per-token heuristic.
Python context pack builder
A utility function that packs file contents into a selection constrained by a maximum character budget, returning the selected files and total character count.
Python dangerous command detector
A reusable helper function that checks whether a command string matches patterns of known dangerous shell operations.
Python command allowlist
A reusable helper that returns True if the first word of a command string is present in a given allowlist.
Python patch risk estimate
A reusable utility that estimates patch risk by counting how many file names match risk-related keywords (auth, billing, crypto, etc.).
Python changed files from diff
A small utility that extracts changed file paths from a git-style diff string by parsing '+++ b/' lines. This is generic, reusable commodity code with no malicious characteristics.
Pytest monkeypatch env required
A reusable pytest test helper that sets environment variables via the monkeypatch fixture from provided keyword arguments.
Pytest JSON response assert
A reusable test assertion helper that validates a response's status code and JSON content-type before returning its parsed body.
Python dataclass to dict clean
A reusable helper that converts a dataclass or mapping to a dict, removing keys with None values.
Python cursor pagination SQL
A reusable pagination helper that generates a cursor-based SQL query string and parameter list for a given table, ordering by created_at descending with a limit.
Python HMAC verifier
A reusable HMAC-SHA256 signature verification function that safely compares signatures using constant-time comparison.
FastAPI request id middleware
A reusable request-ID middleware that propagates an existing x-request-id header or generates a new UUID and sets it on the response.
FastAPI pagination response
A generic pagination utility that returns a dictionary with a limited item slice, count, and next cursor.
Pytest temporary env
A reusable context manager for temporarily overriding environment variables and restoring their original values on exit.
Subprocess capture with timeout
A generic, reusable helper function wrapping subprocess.run to execute a command and capture its output with a configurable timeout and working directory.
Atomic file write
A reusable atomic file-write utility that writes text to a temp file then atomically replaces the target path.
SQLite dict rows
A small reusable helper that creates a SQLite connection with dict-like row access.
Pydantic pagination model
A reusable Pydantic Pagination model with a bounded limit (1-100, default 25) and optional cursor field.
FastAPI bearer dependency
A reusable FastAPI dependency function that checks for a Bearer token in the Authorization header, raising a 401 if missing, and returns the token string.
FastAPI health route
A reusable FastAPI router exposing a /health endpoint that returns an OK status and current UTC timestamp.
parse JSON lines
Reusable utility functions to parse and encode JSON Lines format text.
retry function with backoff
A reusable retry utility that retries a callable with exponential backoff plus random jitter, re-raising the last error after exhausting attempts.
redact dictionary secrets
A recursive function that redacts secret-like values in nested dicts/lists based on key name matching.
read env required
A reusable helper that reads required environment variables and raises a RuntimeError listing any that are missing.
clamp
A reusable utility function that clamps a numeric value to a given [low, high] range.
merge dicts (deep)
A reusable recursive deep-merge function that combines two dictionaries, recursing into nested dict values and overriding others.
safe divide
A reusable utility function that safely divides two numbers, returning a default value when the denominator is zero.
unique preserving order
A generic utility function that removes duplicate items from a list while preserving their original order.
camel to snake case
A reusable utility function that converts camelCase strings to snake_case using regular expressions.
is valid email
A reusable utility function that validates whether a string matches a basic email format using a compiled regex.
deep get (nested dict access)
A reusable helper function that safely navigates nested dictionary structures using a dot-delimited path string or key list, returning a default value if any key is missing.
memoize (decorator)
A reusable memoization decorator that caches function results by their positional arguments.
timed (decorator)
A reusable timing decorator that measures and prints how long a wrapped function takes to execute.
group_by
A generic group_by helper that groups items into a dictionary by a key function. Reusable commodity utility with no security concerns.
format bytes (human readable)
A Python helper to format bytes to human readable units: converts a numeric byte value into a human-readable string with appropriate unit suffixes (B, KB, MB, etc.).
flatten nested list
A reusable recursive utility to flatten nested lists/tuples into a flat list.
slugify
A reusable slugify utility that normalizes a string to ASCII and converts it to a URL-friendly slug.
chunked
A reusable helper that divides an iterable into fixed-size chunks, raising ValueError if size is below 1.
retry with exponential backoff
A generic reusable retry utility function that retries a callable with exponential backoff before re-raising the last exception.
markdown
13 cardsRunbook dependency update failure
A generic documentation runbook describing steps to diagnose and fix dependency update failures.
Policy agent external command safety
A markdown policy document outlining safety guidelines for how an agent should handle external commands (read-only preference, approval for writes, secret handling, logging intent, stopping on repeated failures).
Diagnostic memory leak in worker
A generic markdown troubleshooting checklist for diagnosing memory leaks in worker jobs (heap tracking, cache checks, closing listeners/timers).
Diagnostic rate limit loop
A generic markdown troubleshooting guide for diagnosing and mitigating rate-limit (HTTP 429) loops, offering reusable best-practice advice.
Runbook flaky test triage
A generic runbook documenting a six-step process for triaging and fixing flaky tests, applicable to any project.
Agent preflight checklist
A generic markdown preflight checklist listing safety and best-practice steps for a coding agent.
Agent proof bundle template
A reusable markdown template for documenting an agent's task proof bundle (task, artifacts, tests, security checks, rollback, approval).
Security policy secret handling
A markdown security policy document outlining best practices for handling secrets (environment variables, redaction, rotation, fake test values).
Security policy webhook verification
Documentation of general webhook signature verification and security best practices, reusable and benign.
Diagnostic CORS preflight failure
A generic markdown checklist for diagnosing and fixing CORS preflight (OPTIONS) failures with standard best-practice recommendations.
Diagnostic Docker healthcheck failing
A generic troubleshooting guide listing steps to diagnose a failing Docker healthcheck (exec into container, check binding, auth, start_period, logs).
Diagnostic Next.js hydration mismatch
Documentation explaining common causes of Next.js hydration mismatches and generic diagnostic steps, with no code execution or malicious content.
Runbook database migration rollback
A generic operational runbook/checklist for rolling back a failed database migration, applicable to any project.
go
6 cardsGo environment required
A reusable helper function that fetches a required environment variable and returns an error if it is unset.
Go request id middleware
A reusable Go HTTP middleware that propagates the X-Request-Id header from request to response for request tracing.
Go JSON decode body
A reusable helper function that decodes a JSON HTTP request body into a target value, closing the body afterward.
Go JSON response helper
A generic reusable helper that writes a JSON response with a given HTTP status code to an http.ResponseWriter.
Go bearer middleware
A reusable Go HTTP middleware that enforces Bearer token authentication by comparing the Authorization header to an expected token.
Go HTTP health handler
A Go HTTP handler function that responds to health check requests with a JSON payload containing an 'ok' flag and the current UTC timestamp.
json
5 cardsPatch recipe add retry budget
A JSON feature specification for adding a retry budget (max attempts, max elapsed time, transient-error retries, cancellation handling) with associated test cases.
Agent reusable task manifest schema
A reusable JSON metadata schema template for cataloging code snippets with fields for licensing, risk, and verification status.
Proof schema reusable artifact
A generic JSON metadata template describing an artifact with fields like ID, title, license, content hash, retrieval date, source, and revocation status. It is a reusable data structure with no logic or side effects.
Patch recipe add API pagination
A JSON change-plan describing standard API pagination features (safe limit, cursor, deterministic ordering, next_cursor/count, tests) with no malicious indicators.
Patch recipe add request id middleware
Metadata describing a reusable request-ID tracing middleware that propagates an x-request-id header and logs it.
yaml
4 cardsTest pack rate limited API client
YAML test case definitions for a generic rate-limited API client covering retry logic, backoff, max attempts, and log redaction of authorization headers.
Test pack webhook endpoint
A YAML test-case specification listing scenarios for a webhook endpoint (signature verification, idempotency, unknown event handling, persistence-gated responses). It is descriptive glue tied to a specific project's webhook implementation rather than reusable commodity code.
GitHub Actions Docker build
A reusable CI workflow that builds a Docker image on push without pushing it to a registry.
Docker compose app with healthcheck
A Docker Compose YAML defining a Node.js app service with a working directory, startup command, and a local HTTP health check.
bash
4 cardsAtomic symlink deploy
A reusable bash function performing atomic symlink deployment by creating a temporary symlink and atomically renaming it to the target.
Docker compose health wait
A reusable bash helper that waits up to ~2 minutes for a Docker container to report a 'healthy' status.
Wait for HTTP 200
A reusable bash helper function that polls a given HTTP URL with curl, retrying a configurable number of times until it succeeds or times out.
Strict shell script header
A generic, reusable bash script prologue setting strict mode and an error trap for line-number reporting.
sql
3 cardsAudit log table generic SQL
SQL schema defining an audit_log table with actor/action/target fields and two indexes for querying by actor or target over time.
API keys table migration
SQL schema creating an api_keys table with hashed key storage and a user index.
Cursor pagination query
A parameterized SQL query implementing keyset/cursor pagination over an 'items' table, ordered by created_at descending with a limit.
dockerfile
1 cardsSearch before generating
Start with the behavior, language and constraints your agent needs. A strong match should reduce implementation and review work; a weak match should be rejected rather than forced into the codebase.
Inspect the proof
Check provenance, license, scan date, examples, tests and revocation status before retrieval. The catalogue exposes those signals so reusable code remains attributable and auditable.
Adapt and verify
Retrieval is the starting point, not the release gate. Adapt the primitive to local interfaces, run its proof pack and preserve the receipt so the next agent can understand what was reused, why it matched and which assumptions still belong to the surrounding repository.
What a verified primitive is — and is not
A primitive is deliberately smaller than a product feature. It solves a narrow recurring problem — validating an input, protecting a fetch, handling a retry, or recording a proof — while leaving the surrounding application in control. That narrow scope makes the artifact easier to inspect, test and adapt than a large block of generated code with unclear assumptions.
Verification does not mean that a snippet can be copied blindly. It means the repository can see where the pattern came from, what license and scan date apply, which examples or tests support it, and whether the artifact has been revoked. The consuming agent still has to compare interfaces, runtime versions, threat models and failure behavior with the codebase it is changing.
A useful retrieval therefore begins with constraints rather than a familiar function name. Search for the behavior you need, reject near matches when they miss an important constraint, then run the local proof pack after adaptation. This keeps reuse honest: it saves repeated reasoning without turning an old implementation into an authority it has not earned.