next-role / backend
AGENTS.md62 starsChanged 56 days agoMITView on GitHub
Python 3.13 backend. Built on LangChain / LangGraph / DeepAgents for the career-agent workflow. ruff (with select = ["ALL"]) and ty are strict — sometimes a rule is wrong for the situation. Try a real fix first. If it still won't pass after a couple of honest attempts, suppress narrowly on the offending line: Suppress one line at a time. Don't blanket-disable a rule in pyproject.toml to make a single error go away. Everything under server/ (api, runtime, runtime_postgres, grpc_common,…
- Reads credentials
- Installs packages
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository23 other files it gives its agents.
- AGENTS.mdAGENTS.md
- analytics/AGENTS.mdAGENTS.md
- frontend/AGENTS.mdAGENTS.md
- agent-browserSkill
- archify-reviewSkill
- archifySkill
- commitSkill
- drawio-skillSkill
- frontend-designSkill
- qualitySkill
- upgrade-backend-depsSkill
- upgrade-frontend-depsSkill
- write-prdSkill
- agent-browserSkill
- archify-reviewSkill
- archifySkill
- commitSkill
- drawio-skillSkill
- frontend-designSkill
- qualitySkill
- upgrade-backend-depsSkill
- upgrade-frontend-depsSkill
- write-prdSkill
The file
We split this AGENTS.md into the rules it gives an agent
6 rules. About 0 are common, 2 are distinctive, and 4 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.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- could be automatic: a setting could enforce it
- Very specific: line 45
One source module → can have multiple test files: when concerns are unrelated: split as test_<module>_<concern>.py (e.g., …
- Very specific: line 47
Default (fast unit tests only): cd backend && uv run pytest
- Distinctive: line 53
Add or update the matching test at the mirrored path when you create or modify code.
- Very specific: line 54
Must be fast and deterministic.
- Distinctive: line 56
Run at least the matching test file to confirm green before reporting work as done.
- Very specific: line 58
Use for code whose behavior depends on the live DB/Redis/HTTP — pgvector queries, real transactions, multi-statement flows.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md 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.
Files
backend/AGENTS.md
Python 3.13 backend. Built on LangChain / LangGraph / DeepAgents for the career-agent workflow.
Tooling
- Package manager:
uvonly. Useuv add <pkg>/uv add --dev <pkg>; neverpip install. - Run a script:
uv run <cmd>(e.g.,uv run python -m app,uv run pytest). - Lint:
uv run ruff check --fix(or let pre-commit do it). - Format:
uv run ruff format. - Type check:
uv run ty check— this isastral-sh/ty, notmypyorpyright. Pre-commit gates on it. - Tests: see Testing below.
Style
- Line length: 100 (ruff). Matches the frontend; keep them in sync.
- Ruff config selects
ALLwith targeted ignores inpyproject.toml. Read the ignore list before assuming a rule is off — most are on. Notably enforced: docstrings (D), security (S), complexity (C901, max 10), naming (N), type-annotations (ANN). - Underscore-prefixed names are allowed unused (
dummy-variable-rgx). - Per-file:
__init__.pyallowsF401(re-exports); notebooks allowD100.
Last-resort suppressions
ruff (with select = ["ALL"]) and ty are strict — sometimes a rule is wrong for the situation. Try a real fix first. If it still won't pass after a couple of honest attempts, suppress narrowly on the offending line:
- Ruff:
# noqa: <CODE>with the specific code from the error (e.g.,# noqa: SLF001for private-member access). Never bare# noqa. - Ty (type check):
# type: ignore # noqa: PGH003— the# noqa: PGH003keeps ruff from complaining about the blanket type-ignore.
Suppress one line at a time. Don't blanket-disable a rule in pyproject.toml to make a single error go away.
Server packages
Everything under server/ (api, runtime, runtime_postgres, grpc_common, core_server) is the agent server — the platform that serves the LangGraph Server API and runs the agents. Design, topology, and maintenance notes live in ARCHITECTURE.md. House rules:
- Infrastructure, not product: fix bugs surgically; don't refactor casually — this code is stable plumbing that the whole product sits on, and churn here has outsized blast radius.
- Relaxed quality gates by design: a scoped
per-file-ignoresblock inpyproject.tomlturns off the noisy stylistic rule families for these dirs; ty excludes them ([tool.ty.src]).agents/andtests/keep the full strict bar — don't let server-package leniency leak there. server/grpc_common/proto/is generated — never hand-edit, lint, or format it (excluded in the top-level[tool.ruff] excludeAND the pre-commit hooks'exclude:— both are required; seeARCHITECTURE.md§10). Regenerate only withgrpcio-tools==1.80.0.- Import gotcha:
server.api.configrequiresREDIS_URI(andDATABASE_URI/POSTGRES_URI) at import time — any script or test importing server modules needs those env vars set, even if unused. - No mirrored unit tests for these dirs — the correctness bar is the e2e contract (
tests/server/test_smoke.pyintegration tests + the frontend round-trip), not internals.
Testing
Current phase: unit tests + integration tests against the local DB. LLM evals are deferred (slow + costly). When you create or modify code, write or update unit tests by default, and add integration tests when the code's value lives in real DB/Redis/HTTP behavior (e.g., pgvector queries, transaction semantics, connection pooling). Do not create
@pytest.mark.evaltests — that marker exists for future use only.
- Layout:
backend/tests/mirrorsbackend/agents/(soagents/analytics_agent/hastests/analytics_agent/). A source fileagents/<pkg>/<module>.pyhas its tests attests/<pkg>/test_<module>.py(e.g.,agents/career_agent/tools.py→tests/career_agent/test_tools.py). No__init__.pyneeded — pytest runs in--import-mode=importlib, so test subdirectories are plain folders. - One source module → can have multiple test files when concerns are unrelated: split as
test_<module>_<concern>.py(e.g.,test_tools_parsing.py,test_tools_search.py). Don't pile everything into one giant test file. - Run (from
backend/—testpaths = ["tests"]is relative):- Default (fast unit tests only):
cd backend && uv run pytest - Single file:
cd backend && uv run pytest tests/career_agent/test_tools.py - Single test: append
::test_function_nameto the file path - Integration tests:
cd backend && uv run pytest -m integration(assumes the local stack is up) - Unit + integration together:
cd backend && uv run pytest -m 'not eval'
- Default (fast unit tests only):
- Unit tests (the default, untagged):
- Add or update the matching test at the mirrored path when you create or modify code.
- Must be fast and deterministic. Mock external dependencies (
unittest.mock.patch). - Don't assert on raw LLM output — it's non-deterministic. Mock the model client and assert on the surrounding logic: what gets passed in, how the response is parsed, error handling. Real LLM evaluation belongs in an eval suite (deferred).
- Run at least the matching test file to confirm green before reporting work as done. Run the full default suite for cross-cutting changes.
- Integration tests (tagged
@pytest.mark.integration):- Use for code whose behavior depends on the live DB/Redis/HTTP — pgvector queries, real transactions, multi-statement flows. Mocking these would lie.
- Connect to the local stack via
POSTGRES_URI/REDIS_URIfrom.env. Stack-up handling is in the root Local development section. - Tests must clean up after themselves (use a transaction that rolls back, or delete inserted rows in a fixture teardown). Don't pollute the dev DB.
- Skipped from the default run by
addopts = "... -m 'not integration and not eval'"inpyproject.toml. Run them manually with-m integrationwhen relevant; CI will run them later.
- Async:
asyncio_mode = "auto"is set inpyproject.toml, so writeasync def test_...directly — no@pytest.mark.asynciodecorator needed. - Scoped fixtures: a
conftest.pyin a subpackage (e.g.,tests/career_agent/conftest.py) is only loaded for tests under it. Keep package-specific fixtures there instead of bloatingtests/conftest.py. Don't create emptyconftest.pyupfront — wait until a fixture is shared.
Deferred: LLM evals
@pytest.mark.eval is declared in pyproject.toml and excluded from the default run. It's for future LLM evaluation tests (slow, costly, non-deterministic). Until eval work begins, the marker should not appear in code.
Local database
- Postgres 18 + pgvector via
docker compose up postgres. Connection:POSTGRES_URIin.env; local port is${POSTGRES_LOCAL_PORT}(default5449). Driver ispsycopg(psycopg3). - Schema is owned by
backend/storage/migrations/(versioned SQL), applied by the backend at container startup under a Redis lock — don't write or expect Alembic/SQLModel migrations of your own.backend/init.sqlonly enables thevectorextension at first volume creation. - To understand the schema, query the live DB via the
next-role-postgresMCP (@bytebase/dbhub). Default schema ispublic. Prefer it over reading source: list tables → describe the ones relevant to the task. Don't shell intopsql.
Local object storage
- SeaweedFS (S3-compatible) via docker compose (
object-storeservice, S3 API on${OBJECT_STORE_LOCAL_PORT}, filer UI on${OBJECT_STORE_UI_LOCAL_PORT}). Binary artifact prefixes (/upload/,/tailored_resume/,/interview_battlecard/) live here as objects underusers/<scope>/career_agent/<area>/<relpath>—<scope>is the authenticated identity in multi-user mode anddefaultsingle-user (see the Authentication section +scope.py). The mapping isagents/career_agent/object_storage.py, shared by the agent'sObjectStoreBackendroutes and the files HTTP API (agents/files_api.py, mounted viaLANGGRAPH_HTTP). - Config:
OBJECT_STORE_*in.env— never reuseAWS_*(those are live Bedrock creds). In the cloud, pointOBJECT_STORE_*at S3 / GCS / Azure (obstorespeaks all three). - Testing: unit tests run against
obstore.store.MemoryStore(no emulator needed);@pytest.mark.integrationtests hit the compose SeaweedFS via the host-side endpoint from.env. - rendercv renders in a throwaway scratch dir (see
render_resume_pdfintools.py+render_scratch.py): a hostTemporaryDirectoryunderSANDBOX_PROVIDER=local, a dir inside the remote sandbox undere2b. The.pdfand.typoutputs are published to/tailored_resume/in the object store; no artifact ever lives in the repo tree.
Authentication & per-user scoping (multi-user, opt-in)
Off by default (LANGGRAPH_AUTH unset → the vendored server's noop auth, single-user). When set, the server activates its custom-auth framework and enforces per-user isolation. See .env.example for the enable steps and the full three-PR history in git log (phases 1–4).
- AuthN + authZ handlers:
backend/agents/auth.py(auth = Auth()).@auth.authenticateverifies the frontend's Better Auth bearer JWT against its JWKS — EdDSA pinned (never trust the tokenalg),iss/audchecked; uses theauthorizationparam (notrequest, which breaks WebSocket scopes).@auth.on.*stampmetadata.owner+ return{"owner": id}(threads/runs/crons), deny assistant writes, rewrite store namespaces to the identity, and a global default-deny fails closed. - The enforcement gap this closed: the vendored ops layer ships auth filters on request protos, but the native
core_serverservicers used to ignore them.server/core_server/_filters.pytranslatesAuthFilterprotos → parameterized JSONB predicates (values always bound viaJsonb, never interpolated; keys are trusted server-authored literals); it's wired into threads/runs/crons/assistants Get/Search/Count/Patch/Delete/Copy. When you touch a servicer query, keep the filter clause — unowned rows must stayNOT_FOUND. Highest-risk sites:ThreadsServicerImpl.Stream(ownership pre-check before subscribing) andRunsServicerImpl.Create(thread_filters/assistant_filters). - Artifact areas are a registry (
object_storage.AREA_ROOTS): each area name maps to the agent whose key space it lives in, so/upload/lands underusers/<scope>/career_agent/and the analytics agent's/charts/underusers/<scope>/analytics_agent/. The same mapping is the files-API allowlist. Adding an area means one entry there plus the route in that agent'sagents.py. - Per-user storage (
backend/agents/career_agent/scope.py): resolves identity at call time from the run config (configurable.langgraph_auth_user).kv_namespace(area)prepends the identity only when present (single-user keeps the original 2-tuple — nodefaultsegment);object_scope(identity)maps tousers/<id|default>/career_agent. The object-key builders inobject_storage.pytake ascope; the agent backend auto-resolves it, the files API passesrequest.user.identity. - Dual-mode invariant: with
LANGGRAPH_AUTHunset, every filter clause collapses to""and every namespace/key falls back to its single-user form — the SQL and storage layout must stay byte-for-byte the pre-auth behavior. Test both modes. - Boot guard:
REQUIRE_AUTH=true+ noLANGGRAPH_AUTHraises at config import (cloud safety net). - Tests:
server/core_server/_filters.pyneedsserver.*importable — pytestpythonpath = ["..", "."]. Server packages otherwise keep the e2e-contract bar (no mirrored unit tests);_filters.pyis the exception (pure, injection-safety-critical → unit-tested intests/server/test_filters.py). Scope + files-API-auth tests live undertests/career_agent/test_scope.pyandtests/test_files_api_auth.py.
Library docs
For tasks involving the LangChain ecosystem (LangChain, LangGraph, LangSmith) or the LlamaIndex ecosystem (LlamaIndex, LlamaCloud, LlamaParse, LlamaExtract, LlamaSplit, LlamaClassify), use the dedicated MCP servers in addition to Context7:
mcp__docs-langchain__*— LangChain / LangGraph / LangSmithmcp__llama-index-docs__*— LlamaIndex family
Gotchas
- LLM provider keys (OpenAI / Anthropic / Google / AWS / Tavily) come from
.envviapydantic-settingsandpython-dotenv. Don't hardcode. langchainis on the v1 line (>=1.2); APIs differ from older v0.x snippets you may see online.
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
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.

