A Python Playbook for Trustworthy AI-Agent Harnesses

How to adapt the Trust Pyramid and harness engineering to Python back ends, data-science pipelines, and Streamlit—with enforceable boundaries, data contracts, runtime verification, and a staged legacy-modernization plan.

A developer checks an AI coding-agent workflow against repository and test evidence.

Source basis: Lauren Tan’s public AI Engineer CODE 2026 talk and Ryan Lopopolo’s and OpenAI’s public writing and interviews on harness engineering. This edition translates and formats the supplied Chinese manuscript. Reported throughput, reversal, and token figures come from talks, interviews, or case studies; they are not independent audits or causal estimates. Check tool capabilities and experimental flags against the versions your team actually uses.

Key takeaways

  • Reliable agent work depends less on longer prompts than on machine-checkable architecture boundaries, data and type contracts, repeatable verification, and permission limits.
  • Tan’s Trust Pyramid and Lopopolo’s harness engineering both shift leverage from line-by-line authorship toward the environment, context, and feedback loops. Their examples do not establish that “zero human review” is broadly safe.
  • Python back ends can use dependency layers, static checks, contract tests, and observability; data-science workflows can use reactive notebooks and DataFrame schemas; Streamlit apps can use AppTest, stable widget keys, and a local Agent API for verification.
  • Modernize legacy systems in stages: isolate and establish behavioral baselines, ratchet down existing debt, apply deterministic migrations, then review evidence. Do not ask agents to rewrite everything before a verification net exists.

What the public sources show

Tan’s talk describes a trust-oriented engineering environment in which repository structure, lint rules, runtime checks, and formal methods constrain agent behavior. The numbers in the talk are practitioner-reported, not an independently audited benchmark. OpenAI’s engineering post likewise describes an internal harness experiment and its team’s self-reported operating model. A ZenML case study and interviews add further throughput and long-running-task figures; none establish that the same results will transfer to other teams.

The Python recommendations below are an engineering mapping of those ideas, not a report that one Python organization has validated a single standard stack. In particular, marimo’s notebook reproducibility percentages are vendor-published summaries citing earlier research, and Streamlit labels its Agent API experimental.

Practical implications

  • First identify which errors architecture, types, schemas, or tests can prevent deterministically; reserve human attention for judgments those checks cannot encode.
  • Select feedback tools for the failure modes of each layer instead of copying one organization’s exact toolchain.
  • Preserve reproducible inputs, versioned rules, and independent checks at every stage. Automation can reduce review load, but it does not replace permission governance or accountable ownership.

Limitations

Reported productivity metrics are self-reported and drawn from different teams, periods, and sources; they should not be compared as if they came from a controlled trial. Tool behavior and APIs change quickly, and some features discussed here are experimental or backend-specific. The recommendations are starting points, not substitutes for checking local compatibility, performance, security, and domain requirements.

The common logic: the Trust Pyramid and harness engineering

Lauren Tan, a principal engineer at SpaceXSI (known as Potato), argues that as agents increase the volume of proposed changes, the engineering task becomes building an environment in which their work can be trusted. Her talk describes reported production volumes—including 3,000 pull requests in a month by Tan and about 11,000 across the team—and a reversal rate around 0.5% after sustained environment work. These are first-party figures, not independent outcome measurements. Tan also relays another practitioner’s report that roughly 70% of daily tokens went to verification, saying it matched her own experience. The repository itself is a major input to agents: workarounds and deprecated patterns can be copied as if they were standards. Her examples include directory boundaries, lint rules that constrain risky APIs, and limiting product-code comments that can become stale rationalizations for fragile fixes [1].

Ryan Lopopolo’s OpenAI harness experiment reaches a related conclusion: engineers control the context supplied to models and the feedback produced by tools. OpenAI’s engineering post reports that the team built an internal product in an estimated one-tenth the time of manual implementation and merged roughly 1,500 pull requests over five months, averaging about 3.5 PRs per engineer per day with three engineers driving Codex [2, 12]. Separate interviews and case studies report later figures such as 70 PRs per engineer per week and a 60-hour task consuming hundreds of millions of tokens [2, 25]. Those accounts describe different snapshots and should not be combined into a causal model-performance comparison.

Layer Tan’s Trust Pyramid Lopopolo’s harness engineering Python, data science, and Streamlit mapping
Code and static boundaries Physical directory boundaries, Dune framework rules, and custom linting [1] One-way dependencies and a single provider boundary for cross-cutting concerns [12] Enforce module layers and public interfaces; prefer explicit schemas to free-form imports and bare dictionaries [3]
Runtime and formal verification Feature maps, dedicated CLIs, CDP debugging, TLA+, Lean, and UI property tests [1] Isolated per-worktree instances, CDP interaction, and temporary observability stacks [12] Let agents inspect ASGI/WSGI responses, reactive data kernels, or headless app trees and errors [7]
Prose and context Keep AGENTS.md and skills for judgments that cannot be encoded [1] A roughly 100-line AGENTS.md map points to versioned docs, plans, and repair runbooks [2, 12] Keep a concise project map and put repair guidance in actionable lint errors [2]
Entropy and review Clean the codebase and inner feedback loop before expanding automation [1] Encode “golden principles” and use background cleanup tasks to limit drift [12] Ratchet down legacy violations and automate dead-code and documentation cleanup [11]

These models have limits. Lopopolo has described long-term architectural consistency across years as unresolved and argued that temporary orchestration scaffolding should give way to durable product knowledge, contracts, and tests [30]. Neither approach makes human accountability obsolete.

Practitioners who add useful perspectives

Python’s dynamic language features and data science’s exploratory workflows make it unwise to copy a “zero human review” pattern mechanically. Five practitioner perspectives complement the core ideas:

Practitioner Contribution Practical lesson for Python, data science, or Streamlit
Boris Cherny (Anthropic) [13, 32] Verification loops, human alignment during planning, and parallel independent workspaces Use separate checkouts for independent tasks; lock intent in a plan, then edit and verify; use tagged unions to make invalid states harder to represent.
Dexter Horthy (HumanLayer) [14, 35] Brownfield work, R.P.I. (Research–Plan–Implement), and intentional context compaction Match planning depth to rework cost and keep long sessions from accumulating misleading context.
Mitchell Hashimoto (HashiCorp) [15] Harness design, focused background work, and learning from every agent mistake Prefer a small number of high-confidence tasks early; turn recurring mistakes into checks or precise project rules.
Samuel Colvin (Pydantic) [16, 38] Validation, structured observability, and the Monty sandboxed Python interpreter Validate data at I/O boundaries, trace calls with OpenTelemetry/Logfire, and isolate generated scripts where appropriate.
Trevor Manz and Eric Ma (marimo) [17–19] Reactive notebooks and agent-accessible data-science workflows Prefer one idea per iteration, observable state, and review views that expose the relevant data.

Cherny’s multi-window asynchronous approach and Hashimoto’s preference for a single high-confidence background task mark opposite ends of a concurrency tradeoff. Mature infrastructure can support parallel work on independent modules; a legacy system without a sound test net benefits from a more restrained pace [13, 15].

An implementation map for three Python stacks

Python back ends: dependency contracts and API testing

Python permits arbitrary imports, so agents fixing a defect can easily create reverse or circular dependencies [26]. Start with a one-way layering model—such as types → config → repository → service → runtime → API—and route cross-cutting concerns such as authentication and database connections through explicit providers [12]. The Rust-based tach tool can declare module boundaries, allowed dependencies, and public interfaces in tach.toml [3]. Import Linter offers layers, forbidden, independence, and protected contracts in pyproject.toml; exhaustive checks can prevent ungoverned top-level packages [4]. One community benchmark on a roughly 20,000-line Django project reported reducing Import Linter runtime from 0.250 to 0.167 seconds by excluding type-checking imports—a project-specific result, not a universal speed guarantee [4].

Fast feedback matters: checks that take many minutes invite timeouts and workarounds [20]. Combine a fast formatter and single-file linter such as Ruff with project-wide dead-code and dependency checks such as Vulture, Skylos, and deptry. A Skylos team comparison reported that Ruff’s unused-import/local-variable rules found only two of six seeded dead-code cases in one Flask sample, while cross-file tools found five; treat this as a vendor’s test, not a general benchmark [29]. Python teams can also evaluate mypy, Pyright/basedpyright, ty, Pyrefly, and Zuban against their repository and CI constraints [5, 46, 47].

For runtime feedback, Schemathesis can derive property-based API tests from OpenAPI and exercise ASGI or WSGI applications in memory. It generates boundary and stateful requests, checks for unhandled server errors, and validates response schemas [10, 27, 48, 49]. Combine this with Pydantic validation at inputs and OpenTelemetry/Logfire traces. If agents execute generated Python scripts, a constrained runtime such as Monty may provide an additional isolation boundary [16, 38].

Data science: reactive notebooks and DataFrame contracts

Jupyter’s .ipynb format mixes code with rendered outputs in JSON, while cells can run out of order and mutate shared state. marimo cites a study of GitHub notebooks reporting that more than 75% did not execute top-to-bottom and 96% did not reproduce; these are older research findings repeated on a vendor page, not a current census [9].

marimo stores notebooks as ordinary Python and builds a deterministic reactive execution graph from variable dependencies. Its marimo check catches some notebook-specific mistakes before execution [9, 37]. PEP 723 inline dependencies and sandboxing can help pin environments; pytest can collect notebook tests, while marimo pair provides an agent scratchpad attached to a live kernel and marimo-lens supports human review [17–19, 51–53, 63].

A second defense is replacing assumptions about DataFrame columns with explicit schemas. Pandera’s DataFrameModel and validation decorators can check structure and statistical assumptions between pipeline stages; lazy validation aggregates failure cases to help locate bad rows [6]. Its optional Narwhals backend can target several dataframe engines, but backend availability, type coercion, and lazy execution behavior must be checked for the version in use [54, 55]. For critical feature calculations and model metrics, snapshot tests such as Syrupy can detect silent numeric drift on a standard test set [56].

Streamlit: separated logic and headless, data-level checks

Streamlit’s single Python-script model reduces some front-end/back-end glue, but each widget interaction reruns the script. That can cause repeated uncached queries, tangled st.session_state, and unstable widgets without keys [57–59]. Keep domain logic and schemas in a core/ package and UI code in pages/; enforce the boundary so core modules cannot import Streamlit [3]. Streamlit’s version-matched skills can guide coding agents toward native components, caching, fragments, and supported APIs [28, 60].

Add AST or lint rules requiring stable, unique key= values for interactive widgets and validate every form or parameter in Python. Browser-side required constraints are not a server-side security boundary: the Agent API can submit requests without a browser [8].

For CI, use streamlit.testing.v1.AppTest to set secrets, query parameters, and session state; exercise buttons, selectors, and page navigation; and assert there was no exception and that displayed values are correct [7, 61, 62]. During local development, Streamlit’s experimental Agent API can expose a structured page tree, table/chart data, and exceptions at /_stcore/agent/mcp; keep it local unless the app’s data access and side effects have been reviewed [8]. Add CDP or Playwright screenshots only when custom components or visual layout require them.

Trust layer Python back end Data-science pipeline Streamlit application
Architecture tach or Import Linter contracts Separate ingestion, cleaning, feature, and model packages; reactive .py notebooks Keep core/ independent of Streamlit and isolate page rendering [3]
Static/data contracts Ruff plus dead-code/dependency tools; type checkers; Pydantic marimo check; Pandera schemas and, when suitable, Narwhals AST rules for widget keys and server-side validation [6, 8]
Runtime evidence Schemathesis, pytest, OpenTelemetry/Logfire, sandboxing [10, 16] Notebook tests, numeric snapshots, live-kernel exploration [17, 52, 56] AppTest and local experimental Agent API [7, 8]
Context and upkeep Concise AGENTS.md map, docs, repair runbooks [2] Document a preferred engine and iteration conventions [18] Use Streamlit’s version-matched skills and component/key checklist [28, 60]

A phased playbook for legacy Python, data science, and Streamlit systems

A repository with little test coverage, circular imports, stale notebooks, or a thousand-line app.py should not be handed to an agent for a wholesale rewrite. Migration experience warns that models may handle mechanical language upgrades but miss cross-module coupling and implicit business or compliance rules such as financial rounding and risk definitions [21]. A safer program uses four stages over roughly four weeks, with R.P.I. and an explicit ratchet built into the loop [14].

Stage 0: Isolate the workspace and create a concise map

  1. Move from browser copy-and-paste to a terminal workflow that can inspect files, run scripts, and make HTTP requests. Give parallel tasks separate Git worktrees and a one-command environment setup [15].
  2. Keep the root AGENTS.md under roughly 100 lines as a routing index for tests, lint, typing, and startup commands. Put architecture and active plans in versioned docs/ and docs/exec-plans/ files [2, 12].
  3. Add stack-specific skills and code-indexing tools only where they help: Streamlit’s skills, marimo-pair for notebook work, and code graphs or ast-grep for large legacy repositories [18, 28, 64].

Stage 1: Map dependencies and create a behavioral safety net

  1. Follow R.P.I. (Research → Plan → Implement): first inspect the real code and call graph in a read-only pass; capture findings, file paths, and acceptance criteria in a plan; then implement in a fresh work context to reduce context contamination [14].
  2. Without changing business logic, add characterization tests: Schemathesis against existing service entry points, frozen data and pytest/Syrupy snapshots for analysis pipelines, and initial AppTest.from_file() checks for Streamlit apps [7, 10, 21, 56].

Stage 2: Ratchet existing debt and weed the garden

  1. Establish a type-checking baseline (for example, basedpyright --writebaseline) so legacy errors can be recorded while new or changed code faces strict checks [11].
  2. Add a pattern ratchet, such as baseline init and baseline ratchet, to cap legacy anti-patterns and required-file gaps; use deptry to catch undeclared or unused dependencies [5, 23].
  3. Record the existing dependency graph. Configure tach or Import Linter contracts, explicitly isolate known legacy cycles, and warn on new unmatched exceptions [3, 4].
  4. Run Ruff and a cross-file dead-code tool in dry-run mode, then remove verified dead functions and obsolete scripts so agents do not imitate them [1, 29].

Stage 3: Deterministic AST changes and bottom-up modularization

  1. Use AST-based transforms for structural changes—symbol renames, import moves, and syntax migrations—and LLMs for semantic changes. Test both positive and negative cases for each ast-grep rule [22].
  2. Split modules in dependency order, preferably in independent worktrees: extract pure functions and Pydantic contracts first. Have a human specify high-rework changes involving pricing, risk, or database schemas before handing implementation to agents [20, 21].
  3. Modernize notebooks and Streamlit deliberately: convert selected .ipynb assets to marimo, add Pandera checks at important transformations, move business logic out of UI scripts, add stable widget keys, and verify each page locally with AppTest or the Agent API [3, 7, 51].
  4. Make every custom lint or structural-test failure explain the violated rule, the recommended replacement, and the relevant design document. A CI failure should give agents enough context to repair the cause rather than merely hide the symptom [2].

Stage 4: Continuous cleanup and evidence-led review

  1. Only after the fast checks are stable, automate outer-loop cleanup: scan for duplication, tighten ratchet limits as counts fall, detect stale documentation, and propose small, quickly reviewable changes [1, 12].
  2. Shift human review from raw diffs toward structured evidence: contract-test coverage and traces for services, notebook views and numeric snapshots for data science, and AppTest results plus actual returned data for Streamlit. Keep humans responsible for system boundaries, permissions, and long-term architecture [1, 7, 10, 56].

The goal is not to eliminate people from software engineering. It is to reduce the need for repeated manual correction by making good behavior easier to verify and bad behavior harder to repeat. In Python systems especially, the right harness is the one that turns hidden state, implicit schemas, accidental dependencies, and unsafe side effects into explicit contracts with fast, inspectable feedback.

References

  1. All Code Is Slop (Except Mine) | AI Engineer CODE 2026, https://ai.engineer/code/2026/talks/lauren-tan
  2. Zero Human-Written Code: Harness Engineering for Autonomous AI, https://www.zenml.io/llmops-database/zero-human-written-code-harness-engineering-for-autonomous-ai-agents-at-scale
  3. tach - PyPI, https://pypi.org/project/tach/0.1.9/
  4. Enforcing Modular Boundaries with Import Linter in Python | Kokonatt, https://www.kokonatt.com/blog/modular-boundaries-import-linter/
  5. Pyrefly - fast Python type checker and language server - LinuxLinks, https://www.linuxlinks.com/pyrefly-python-type-checker/
  6. Introduction - pandera documentation - Read the Docs, https://pandera.readthedocs.io/en/latest/
  7. st.testing.v1.AppTest - Streamlit Docs, https://docs.streamlit.io/1.65.0/develop/api-reference/app-testing/st.testing.v1.apptest
  8. Agent-accessible apps - Streamlit Docs, https://docs.streamlit.io/develop/concepts/ai-agents/agent-access
  9. The best AI agent for Jupyter notebooks - Marimo, https://marimo.io/features/best-agent-for-jupyter
  10. Schemathesis Tutorial: OpenAPI Fuzzing & Contract Testing, https://qaskills.sh/blog/api-contract-testing-schemathesis-guide
  11. baseline - basedpyright, https://docs.basedpyright.com/latest/benefits-over-pyright/baseline/
  12. Harness engineering: leveraging Codex in an agent-first world, https://openai.com/index/harness-engineering/
  13. Boris Cherny's Claude Code Tips — How He Actually Uses It (142+, https://howborisusesclaudecode.com/
  14. No Vibes Allowed: Solving Hard Problems in Complex Codebases, https://www.youtube.com/watch?v=rmvDxxNubIg
  15. My AI Adoption Journey - Mitchell Hashimoto, https://mitchellh.com/writing/my-ai-adoption-journey
  16. Validation, AI Agents, Logfire Observability - Pydantic Docs, https://pydantic.dev/docs/
  17. Marimo pair – Reactive Python notebooks as environments for agents, https://news.ycombinator.com/item?id=47678844
  18. Agent-assisted data science with marimo notebooks - Eric Ma, https://ericmjl.github.io/blog/2026/10/14/agent-assisted-data-science-with-marimo/
  19. How Marimo Pair Teaches AI Agents to Use Notebooks ... - YouTube, https://www.youtube.com/watch?v=lbkhOacWX-Y
  20. Harness Engineering for Coding Agents: What It Is (2026) - Agentastic, https://www.agentastic.dev/harness-engineering
  21. AI Agents for Legacy Code Modernization — The Developer's Week, https://amux.io/guides/legacy-code-modernization-ai-agents/
  22. AI-Assisted Codebase Migration at Scale: Automating the Upgrades, https://tianpan.co/blog/2026/04/17/ai-codebase-migration-agents-scale
  23. stewartjarod/baseline: Enforce architectural decisions AI coding, https://github.com/stewartjarod/baseline
  24. AI Engineer Code Summit 2026 Recordings, https://ai.engineer/code/2026
  25. How PMs Ship 100K Lines of Cod… - The Growth Podcast, https://podcasts.apple.com/us/podcast/how-pms-ship-100k-lines-of-code-at-openai-with/id1763555775?i=1000769555393
  26. Harness Engineering — What I tried out? | by Onaopemipo Oluborode, https://medium.com/towardsdev/harness-engineering-what-i-tried-out-06cc4dfbfc93
  27. Testing Python Apps - Schemathesis, https://schemathesis.readthedocs.io/en/stable/guides/python-apps/
  28. Build with coding agents - Streamlit Docs, https://docs.streamlit.io/develop/concepts/ai-agents/coding-agents
  29. Does Ruff Detect Dead Code? What It Finds and What It Misses, https://skylos.dev/blog/ruff-dead-code
  30. Ryan Lopopolo: Bio, Work & Ideas - AI Engineer, https://ai.engineer/speakers/ryan-lopopolo
  31. Ryan Lopopolo - Latent Space, https://latent.space/wiki/ryan-lopopolo/
  32. Boris Cherny: Bio, Work & Ideas - AI Engineer, https://ai.engineer/speakers/boris-cherny
  33. Boris Cherny — Innovator Profile - Engatica, https://engatica.com/innovators/boris-cherny/
  34. How the Creator of Claude Code Actually Uses It - DEV Community, https://dev.to/a_shokn/how-the-creator-of-claude-code-actually-uses-it-32df
  35. A software factory needs pressure in both directions - AI Engineer, https://ai.engineer/code/2026/talks/dexter-horthy
  36. The Definitive Guide to Agent Harness Engineering - Medium, https://engineeratheart.medium.com/the-definitive-guide-to-agent-harness-engineering-5f5edf25fd73
  37. marimo | a next-generation Python notebook, https://marimo.io/
  38. ️Monty: the ultrafast Python interpreter by Agents for Agents, https://music.youtube.com/podcast/nxnQl4AcqFg
  39. I built agentcanvas: turn your Pydantic AI + Logfire traces into an, https://www.reddit.com/r/PydanticAI/comments/1u3srey/i_built_agentcanvas_turn_your_pydantic_ai_logfire/
  40. Grounded Agentic Analysis in Reactive Notebooks with marimo-lens, https://arxiv.org/abs/2609.19839
  41. Tach - A Python tool to enforce dependencies - Reddit, https://www.reddit.com/r/Python/comments/1ihl5fy/tach_a_python_tool_to_enforce_dependencies/
  42. GitHub - tach-org/tach: A Python tool to visualize + enforce, https://github.com/tach-org/tach
  43. Tach - enforce dependencies and interfaces in Python projects, https://www.linuxlinks.com/tach-enforce-dependencies-interfaces-python-projects/
  44. tach module boundaries and import-linter contracts, run in the test, https://github.com/112345brian/knowledge/issues/36
  45. pyproject-fmt - PyPI, https://pypi.org/project/pyproject-fmt/
  46. Python type hints for production: mypy, pyright and real-world patterns, https://dev.to/ayinedjimi-consultants/python-type-hints-for-production-mypy-pyright-and-real-world-patterns-45ec
  47. Zuban - fast Python type checker and language server - LinuxLinks, https://www.linuxlinks.com/zuban-fast-python-type-checker-language-server/
  48. Using Hypothesis and Schemathesis to Test FastAPI - TestDriven.io, https://testdriven.io/blog/fastapi-hypothesis/
  49. Quick Start Guide - Schemathesis - Read the Docs, https://schemathesis.readthedocs.io/en/stable/quick-start/
  50. OpenTelemetry FastAPI Tutorial: Get GREAT App Performance NOW!, https://www.youtube.com/watch?v=m28TTogdcbk
  51. GitHub - marimo-team/marimo: A reactive notebook for Python, https://github.com/marimo-team/marimo
  52. pytest - marimo, https://docs.marimo.io/guides/testing/pytest/
  53. Data Validation with Pandera in Python - Towards Data Science, https://towardsdatascience.com/data-validation-with-pandera-in-python-f07b0f845040/
  54. Pandera: Going Beyond Pandas Data Validation - SciPy Proceedings, https://proceedings.scipy.org/articles/gerudo-f2bc6f59-010
  55. One validation engine, many dataframes: Pandera's new Narwhals, https://www.union.ai/blog-post/one-validation-engine-many-dataframes-panderas-new-narwhals-backend
  56. Syrupy (syrupy-project/syrupy) - Context7, https://context7.com/syrupy-project/syrupy
  57. Build with AI agents - Streamlit Docs, https://docs.streamlit.io/develop/concepts/ai-agents
  58. Why Streamlit, https://docs.streamlit.io/get-started/why-streamlit
  59. Basic concepts of Streamlit, https://docs.streamlit.io/get-started/fundamentals/main-concepts
  60. streamlit skills - Streamlit Docs, https://docs.streamlit.io/develop/api-reference/cli/skills
  61. st.testing.v1.AppTest - Streamlit Docs, https://docs.streamlit.io/develop/api-reference/app-testing/st.testing.v1.apptest
  62. Beyond the basics of app testing - Streamlit Docs, https://docs.streamlit.io/develop/concepts/app-testing/beyond-the-basics
  63. Python notebooks with AI - Marimo, https://marimo.io/features/feat-ai
  64. codegraph-ast-grep - BrowserAct SkillHub - 100000+ AI Agent Skills, https://skills.browseract.com/skills/stark-ai-de-agent-skills-codegraph-ast-grep
  65. Ratchets in software development (2021) - Hacker News, https://news.ycombinator.com/item?id=46814340