# Maksym Kuzmitskyi — Senior Software Developer Maksym Kuzmitskyi’s work and writing on frontend engineering with React and TypeScript, service integration and AI-assisted development workflows. Based in Kraków. --- # Maksym Kuzmitskyi — Senior Software Developer Canonical: https://ma-x.im Maksym Kuzmitskyi’s work and writing on frontend engineering with React and TypeScript, service integration and AI-assisted development workflows. Based in Kraków. --- # About Maksym Kuzmitskyi Canonical: https://ma-x.im/about Maksym Kuzmitskyi’s frontend engineering experience: React, TypeScript, testing, accessibility and service integration, alongside AI-assisted delivery workflows. --- # Selected experience Canonical: https://ma-x.im/case-studies Four selected projects across frontend architecture, shared React components, enterprise applications and customer-facing quoting and checkout. --- # Writing Canonical: https://ma-x.im/blog Notes on frontend development, software design and the practical details of building applications. --- # The React Playbook Canonical: https://ma-x.im/playbook A 56-part path from empty folder to production React app: foundation, data, UI, infrastructure, advanced features, and the ecosystem beyond the browser. --- # The Agent Playbook Canonical: https://ma-x.im/agent-playbook A 16-part series on working with AI coding agents sensibly — cost, control, context, and judgment. --- # The Architecture Playbook Canonical: https://ma-x.im/architecture-playbook A curated path through 36 architecture-focused articles, grouped by concern. --- # Get in touch Canonical: https://ma-x.im/contact Get in touch with Maksym Kuzmitskyi about frontend engineering, React, TypeScript, AI-assisted workflows, a project or an engineering role. --- # Frontend Architecture Review Canonical: https://ma-x.im/frontend-architecture-review A focused architecture review for React and TypeScript products that are hard to change. Contact me to discuss the codebase, review scope, deliverables and pricing. --- # Home Canonical: https://ma-x.im I build software around complex interfaces, state and data. React and TypeScript are my main tools. Alongside frontend development and service integration, I also design AI-assisted workflows with useful repository context, focused checks and human review. Most of my work sits where interfaces, application state and services meet. I care about how a feature behaves, where its data belongs and whether another engineer can understand the decisions behind it. My experience includes hands-on development, frontend architecture and team leadership. Across enterprise applications, multi-brand websites and customer-facing journeys, I have worked on both the implementation and the structure that supports it. I also design AI-assisted workflows with clear context, checks and human decision points. --- # About Canonical: https://ma-x.im/about Most of my work sits where interfaces, application state and services meet. I work mainly with React and TypeScript, alongside Node.js, API integration and SQL-backed applications. I care about how a feature behaves, where its data belongs and whether another engineer can understand the decisions behind it. At Liberty Mutual, I build Direct Sales quoting and checkout flows connected to federated GraphQL services. The work spans UI implementation, service contracts, design fidelity and code review. I also develop AI-assisted workflows for tickets, pull requests and CI, including tool and MCP integration. For Procter & Gamble, via Luxoft / DXC, I combined frontend architecture with hands-on delivery on a promotion-planning application. At Honda Canada, via Assembly Canada, I worked on shared React components, local state isolation and Cypress/Cucumber testing in a test-first workflow. At Motorola Solutions, my work progressed from enterprise applications and service integration to reusable UI, accessibility and frontend leadership. At Ploom, via Hanson Regan, I worked as a senior frontend developer on a platform spanning multiple Next.js applications and 27 localized websites. I contributed reusable features, Builder.io content integration and feedback flows connecting the web with email, Telegram and a regional service, alongside analytics and authentication fixes. Testing and accessibility are part of implementation for me. My experience includes Cypress, Cucumber, Playwright and Storybook, with test-first workflows and accessible UI development using WCAG principles. I also bring working knowledge of AWS and practical experience supporting deployment and releases. Alongside frontend development, I design and iteratively refine AI-assisted delivery workflows. I connect repository context, developer tools and MCP integrations with focused checks and human review. I have also developed personal PR-review mechanisms with commit-aware tracking and dry-run checks, and maintain context handoffs between agent sessions. People retain ownership of requirements, decisions and approvals. I have worked as an individual contributor, a frontend architect and a team lead. I value architecture when it makes implementation clearer, and leadership when it helps a team make and carry through useful decisions. The tools can change; understanding the problem, the system and the people working on it remains central to my work. What kind of software do you work on? My experience includes enterprise planning tools, reusable frontend systems, multi-brand websites and customer-facing quoting and checkout journeys. The selected projects show different parts of that work rather than a complete employment history. Do you also work beyond the frontend? Yes. My experience includes Node.js, GraphQL and REST integration, and SQL-backed applications. I also have working knowledge of AWS and experience supporting deployment and releases. My main focus remains frontend engineering and the boundaries between UI, services and data. I also design AI-assisted workflows with repository context, tool integrations, focused validation and human review. How do testing and accessibility fit into your work? I treat them as part of implementation. At Honda Canada, I worked extensively with Cypress and Cucumber, writing tests before implementation. My experience also includes Playwright, Storybook and accessible UI development using WCAG principles. --- # How I work Canonical: https://ma-x.im Writing the code is part of the work. I also care about the decisions around it: how state is owned, how failures are handled, how a change reaches production and what the next engineer needs to know. AI-assisted work follows the same engineering expectations. Understand the boundaries I start with the required behavior, the existing code and the contracts between UI and services. I look for clear ownership of state and data, and an implementation that fits the system. A new feature does not automatically need a new abstraction. Build quality into the change Tests, type checking, accessibility and code review belong inside implementation. I pay attention to loading, error and recovery behavior as well as the happy path. At Honda Canada, writing Cypress and Cucumber tests before implementation was part of this practice. I use focused checks and human review for agent-assisted changes too. Think through delivery A change has to work beyond a local development session. I consider integration points, configuration, dependencies and CI behavior, and support deployment and release work. My experience also includes working knowledge of AWS. Leave useful context I make requirements and trade-offs explicit with product, design and backend colleagues. When a decision affects other engineers, I document why it fits the problem. For agent-assisted work, I maintain repository-specific instructions and session handoffs, check saved context against current sources, and make permitted actions and human decision points explicit. --- # Promotion planning with spreadsheet and timeline interfaces Canonical: https://ma-x.im/case-studies/pg-promotion-planning Procter & Gamble · via Luxoft / DXC Frontend Architect / Tech Lead Context Business managers needed to coordinate product promotions across retail networks. The application combined spreadsheet-like planning, linked data and business-rule validation with a visual campaign timeline. My frontend work sat within an established high-level architecture. My contribution I authored the frontend low-level design and translated it into implementation scopes. I built spreadsheet-like editing with linked data and business-rule validation, and implemented backend-driven page composition using React, TypeScript and Redux. I proposed and delivered a visual campaign timeline with draggable and resizable promotion blocks. I also built a four-person frontend team including myself, combining technical planning and collaboration with backend and data colleagues with hands-on implementation. Outcome The MVP was delivered in approximately nine months, and work continued through the planned product scope. The application was used by approximately 40 business managers. Stack: React, TypeScript, Redux, REST APIs --- # Shared React components for multiple brands Canonical: https://ma-x.im/case-studies/honda-multi-brand-components Honda Canada · via Assembly Canada Tech Lead Full Stack Developer Context Multiple brand websites used shared components on an existing Sitecore platform. Differences in layout and composition had to coexist with reusable UI, while broad state updates caused unnecessary rendering and visible page flickering. My contribution I reworked components so their layout and composition could adapt to each brand. I improved local state isolation and provider boundaries to reduce unnecessary re-renders and visible flickering. I worked extensively with Cypress and Cucumber, writing tests before implementation in a test-first / BDD workflow, and collaborated with peer frontend leads on shared technical decisions. Outcome Shared components could adapt to different brand layouts, while improved local state isolation reduced unnecessary re-renders and visible flickering. Cypress and Cucumber tests were written before implementation as part of the development workflow. Stack: React, JavaScript / TypeScript, Node.js, Sitecore, Cypress, Cucumber --- # Enterprise applications, reusable UI and frontend delivery Canonical: https://ma-x.im/case-studies/motorola-enterprise-ui Motorola Solutions Full Stack Engineer → Frontend Team Lead / Technical Product Owner Context My work at Motorola progressed from enterprise application development to shared UI contributions and frontend leadership. MyView used a middleware layer to consolidate data from external services. My contribution I developed React and Node.js functionality using PostgreSQL-backed middleware. I contributed to reusable Storybook packages and accessibility work, and implemented a lightweight analytics mechanism based on HTML data attributes. Later, I led frontend delivery for the corporate web platform, combining technical planning and engineering support with hands-on contributions. Outcome The work connected enterprise UI with data consolidated from external services, and extended into reusable Storybook UI, accessibility and frontend team delivery. I contributed to the middleware and shared UI as part of collaborative engineering work. Stack: React, Node.js, PostgreSQL, Storybook, Adobe AEM --- # Direct Sales quoting and checkout Canonical: https://ma-x.im/case-studies/liberty-mutual-direct-sales Liberty Mutual Insurance Senior Frontend Developer Context Direct Sales journeys connect customer-facing interfaces with federated GraphQL services. Delivery spans repositories and requires coordination between UI behavior, design and service contracts. My contribution I implement quoting and checkout functionality and work with GraphQL contracts across repositories. I review design fidelity, consider dependency and styling trade-offs, diagnose flaky CI pipelines and use code review to share technical decisions. I also develop AI-assisted workflows for tickets, pull requests and CI, including tool and MCP integration. Current work This is an ongoing engagement. My current work covers quoting and checkout functionality, service integration and the delivery workflows supporting those changes. Stack: React, TypeScript, Node.js, GraphQL, CSS/SCSS, Playwright, AI/MCP --- # Get in touch Canonical: https://ma-x.im/contact If something in my work or writing connects with what you are building, I would be glad to hear from you. You can reach me about frontend engineering, service integration, AI-assisted development workflows, a project or an engineering role. Email: m.kuzmitskyi@gmail.com LinkedIn: https://www.linkedin.com/in/maximusft/ Location: Kraków, Poland --- # The React Playbook: Foundation Set the project up so it can grow without collapsing under its own weight. Starting a New React Project in 2026-2027: The Stack I Keep Coming Back To: https://ma-x.im/blog/react-playbook-starting-new-project TypeScript in React: Patterns That Actually Matter: https://ma-x.im/blog/react-playbook-typescript-patterns Code Structure in React: The FSD Version I Actually Use: https://ma-x.im/blog/react-playbook-code-structure Error Handling in React: What Users Should See When Things Break: https://ma-x.im/blog/react-playbook-error-handling --- # The React Playbook: Data & Navigation Move data through the app and let people move through the app. React Data Fetching with TanStack Query: The Patterns That Keep Apps Calm: https://ma-x.im/blog/react-playbook-data-fetching Routing with TanStack Router: Treat the URL Like Application State: https://ma-x.im/blog/react-playbook-tanstack-router React State Management with Reatom: When useState Stops Being Enough: https://ma-x.im/blog/react-playbook-reatom-state-management Immutable Data in React: The Rule I Stopped Arguing About: https://ma-x.im/blog/react-playbook-immutable-data-structures --- # The React Playbook: UI & Forms The parts users actually touch — styling, components, forms, and charts. Styling React in 2026: How I Actually Choose: https://ma-x.im/blog/react-playbook-css-styling React UI Libraries: Who Owns the Styling Decides Everything: https://ma-x.im/blog/react-playbook-ui-libraries Forms in React: Where TanStack Form Earns Its Place: https://ma-x.im/blog/react-playbook-form-libraries Charts in React: Who Renders the Pixels: https://ma-x.im/blog/react-playbook-chart-libraries --- # The React Playbook: Infrastructure Auth, a backend, rendering, a database, hosting, and tests that keep it honest. Authentication in React: Buy It, and Where the Line Really Is: https://ma-x.im/blog/react-playbook-authentication The Backend a React Developer Actually Needs to Understand: https://ma-x.im/blog/react-playbook-backend SSR in React: What TanStack Start Actually Changes: https://ma-x.im/blog/react-playbook-ssr-tanstack-start Databases for React Developers: What Serverless Actually Changed: https://ma-x.im/blog/react-playbook-database-turso Hosting a React App in 2026: From DevOps Project to Git Push: https://ma-x.im/blog/react-playbook-hosting-railway Testing React Without Drowning: What Each Test Actually Buys You: https://ma-x.im/blog/react-playbook-testing --- # The React Playbook: Advanced Topics The features that turn a project into a product — and the ones people underestimate. AI in a React App: Past the Demo, Into the Product: https://ma-x.im/blog/react-playbook-ai Real-Time React: When the Server Has Something to Say: https://ma-x.im/blog/react-playbook-websockets Internationalization Isn't Translation: What Actually Breaks: https://ma-x.im/blog/react-playbook-i18n Payments in React: The Client Never Decides You Got Paid: https://ma-x.im/blog/react-playbook-payments Time in React: The Bugs That Only Show Up at 2 AM: https://ma-x.im/blog/react-playbook-time File Upload in React: The Input Is Easy, the File Is Not: https://ma-x.im/blog/react-playbook-file-upload Sending Email from a React App: A Backend Problem in Disguise: https://ma-x.im/blog/react-playbook-mails --- # The React Playbook: Ecosystem Where React goes beyond the browser — design, docs, desktop, mobile, and 3D. Design Prototyping for React: Where the Architecture Actually Starts: https://ma-x.im/blog/react-playbook-design-prototyping Documenting Components: The Only Docs That Don't Rot: https://ma-x.im/blog/react-playbook-component-documentation React on the Desktop: When a Window Beats a Tab: https://ma-x.im/blog/react-playbook-desktop React Native: What 'Learn Once, Write Anywhere' Really Means: https://ma-x.im/blog/react-playbook-react-native React in 3D: When
Becomes : https://ma-x.im/blog/react-playbook-vr-ar --- # The React Playbook: Architecture at Scale The boundaries, patterns, and decisions that decide whether an app stays readable as it grows. The shared/ Folder Is Not a Place, It's a Promise: https://ma-x.im/blog/react-playbook-shared-code Barrel Files: The Import You Love and the Bundle You Hate: https://ma-x.im/blog/react-playbook-barrel-files The Direction of the Arrows: Dependencies Are Your Real Architecture: https://ma-x.im/blog/react-playbook-module-dependencies How Big Should a Component Be? Composition, Decomposition, and Handing Over Dependencies: https://ma-x.im/blog/react-playbook-composition-and-di Is Container vs Presentational Dead? What Survived the Hooks Era: https://ma-x.im/blog/react-playbook-container-presentational --- # The React Playbook: Component Patterns The reusable-component techniques that decide whether what you build gets used or quietly rewritten. Compound Components: Designing an API, Not Just a Component: https://ma-x.im/blog/react-playbook-compound-components Headless Components: Give Away the Behavior, Keep None of the Markup: https://ma-x.im/blog/react-playbook-headless-components Changing a Component Everyone Uses: Deprecation, Codemods, and No Big-Bang Rewrites: https://ma-x.im/blog/react-playbook-changing-shared-components Keeping a UI Kit Updated Across Apps: Versioning, Contracts, and Trust: https://ma-x.im/blog/react-playbook-ui-kit-versioning --- # The React Playbook: State & Data at Scale Where state actually lives, what persists, and how to keep one coherent copy of the truth. localStorage Is Not State: Persistence, Hydration, and Tabs That Fight Each Other: https://ma-x.im/blog/react-playbook-local-storage-and-state Server State Is a Cache: Normalization, Duplicates, and Invalidation You Can Trust: https://ma-x.im/blog/react-playbook-data-normalization Optimistic UI: Updating Before the Server Says Yes: https://ma-x.im/blog/react-playbook-optimistic-ui Undo/Redo Without Losing Your Mind: The Command Pattern in React: https://ma-x.im/blog/react-playbook-undo-redo State Machines in React: When Booleans Start Lying to You: https://ma-x.im/blog/react-playbook-state-machines --- # The React Playbook: Communication & Events How the parts of an app talk to each other without turning into untraceable, stringly-typed magic. The Event Bus: Great for Decoupling, Great for Making a Mess: https://ma-x.im/blog/react-playbook-event-bus Feature Flags: Every Flag Is a Branch You Promised to Delete: https://ma-x.im/blog/react-playbook-feature-flags Analytics Is Architecture: Stop Sprinkling track() Everywhere: https://ma-x.im/blog/react-playbook-analytics-as-a-layer --- # The React Playbook: Performance & Architecture Optimizing where it actually hurts — without trading away the structure that keeps the app maintainable. Re-Renders Are React's Superpower, Not a Disease to Cure: https://ma-x.im/blog/react-playbook-rerenders-and-architecture --- # The React Playbook: Look & Feel Architecture The polish that turns out to be a boundary decision — theming, commands, and the systems behind the surface. Theming and Dark Mode Without the Flash: A Systems Problem in CSS Clothing: https://ma-x.im/blog/react-playbook-theming-dark-mode The Command Palette Is an Architecture, Not a Widget: https://ma-x.im/blog/react-playbook-command-palette Code-Splitting Is a Boundary Decision, Not a Bundle Trick: https://ma-x.im/blog/react-playbook-code-splitting --- # The React Playbook: Async & Resilience Work that outlives the component that started it — cancelling, timing out, and staying consistent. React Gives You the Loading State. It Does Not Give You Cancellation.: https://ma-x.im/blog/react-playbook-abort-controller --- # The React Playbook: Types & Tradeoffs Where type safety stops paying for itself, and how to tell before the whole team is stuck. Most Advanced TypeScript Isn't Worth What It Costs: https://ma-x.im/blog/react-playbook-types-that-earn-their-keep --- # The React Playbook: Architecture Styles FSD, layered, and micro-frontends are not competing religions — they are different bets on what changes. What FSD Actually Fixed (and What It Didn't): https://ma-x.im/blog/react-playbook-what-fsd-actually-fixed Layered vs Feature-Sliced: Two Ways to Cut the Same App: https://ma-x.im/blog/react-playbook-layered-vs-feature-sliced Micro-Frontends Are an Org Chart Decision, Not a Technical One: https://ma-x.im/blog/react-playbook-micro-frontends-org-chart --- # The Agent Playbook: Cost & Control Why more agents is not the goal, and what runs away if nobody is watching the meter. You Probably Don't Need Multi-Agents: https://ma-x.im/blog/agent-playbook-you-dont-need-multi-agents Do It As Usual: Teaching One Agent Your Whole Workflow: https://ma-x.im/blog/agent-playbook-do-it-as-usual The Token Bill Is Part of the Architecture: https://ma-x.im/blog/agent-playbook-token-bill Test on Change, Not on a Timer: https://ma-x.im/blog/agent-playbook-test-on-change Guardrails for a Runaway Agent: https://ma-x.im/blog/agent-playbook-guardrails --- # The Agent Playbook: Context & Judgment What an agent can see, what it can do, and when it should stop and ask instead of acting. The Context Is the Product: https://ma-x.im/blog/agent-playbook-context-is-the-product Tools Are Part of the Agent's Intelligence: https://ma-x.im/blog/agent-playbook-tools-are-intelligence When an Agent Should Ask Instead of Acting: https://ma-x.im/blog/agent-playbook-when-to-ask Memory Is Not a Bigger Context Window: https://ma-x.im/blog/agent-playbook-memory-vs-context Evaluation Is the Missing Loop in Agent Workflows: https://ma-x.im/blog/agent-playbook-evaluation-is-the-missing-loop --- # The Agent Playbook: Upkeep The part nobody schedules: keeping an agent's own rules honest as the project moves on. Your Agent Instructions Are Rotting Right Now: https://ma-x.im/blog/agent-playbook-instructions-rot --- # The Agent Playbook: Engineering the Workflow How context, evidence and control survive ordinary engineering work. The Work Around the Agent Is Engineering Work: https://ma-x.im/blog/agent-playbook-engineering-the-workflow Green Checks Only Cover What You Checked: https://ma-x.im/blog/agent-playbook-green-checks The Command Succeeded. The Scope Changed.: https://ma-x.im/blog/agent-playbook-scope-after-tools A Review Belongs to a Commit: https://ma-x.im/blog/agent-playbook-review-belongs-to-commit What a Skill Changed, and What It Didn't: https://ma-x.im/blog/agent-playbook-what-a-skill-changed --- # The Architecture Playbook: Why Architecture at All Frontend spent years being treated as "not real architecture." This is the case that it is. The Smeared Component: When Architecture Scatters What Should Stay Together: https://ma-x.im/blog/smeared-component Code Structure in React: The FSD Version I Actually Use: https://ma-x.im/blog/react-playbook-code-structure What FSD Actually Fixed (and What It Didn't): https://ma-x.im/blog/react-playbook-what-fsd-actually-fixed Layered vs Feature-Sliced: Two Ways to Cut the Same App: https://ma-x.im/blog/react-playbook-layered-vs-feature-sliced Micro-Frontends Are an Org Chart Decision, Not a Technical One: https://ma-x.im/blog/react-playbook-micro-frontends-org-chart The shared/ Folder Is Not a Place, It's a Promise: https://ma-x.im/blog/react-playbook-shared-code The Direction of the Arrows: Dependencies Are Your Real Architecture: https://ma-x.im/blog/react-playbook-module-dependencies Barrel Files: The Import You Love and the Bundle You Hate: https://ma-x.im/blog/react-playbook-barrel-files --- # The Architecture Playbook: Boundaries & Composition Where one piece ends and another begins, and how that boundary survives contact with a deadline. How Big Should a Component Be? Composition, Decomposition, and Handing Over Dependencies: https://ma-x.im/blog/react-playbook-composition-and-di Is Container vs Presentational Dead? What Survived the Hooks Era: https://ma-x.im/blog/react-playbook-container-presentational Compound Components: Designing an API, Not Just a Component: https://ma-x.im/blog/react-playbook-compound-components Headless Components: Give Away the Behavior, Keep None of the Markup: https://ma-x.im/blog/react-playbook-headless-components Changing a Component Everyone Uses: Deprecation, Codemods, and No Big-Bang Rewrites: https://ma-x.im/blog/react-playbook-changing-shared-components Keeping a UI Kit Updated Across Apps: Versioning, Contracts, and Trust: https://ma-x.im/blog/react-playbook-ui-kit-versioning --- # The Architecture Playbook: State & Data Architecture Where state actually lives, what persists, and how far you can push it before it turns to mud. Server State Is a Cache: Normalization, Duplicates, and Invalidation You Can Trust: https://ma-x.im/blog/react-playbook-data-normalization localStorage Is Not State: Persistence, Hydration, and Tabs That Fight Each Other: https://ma-x.im/blog/react-playbook-local-storage-and-state Optimistic UI: Updating Before the Server Says Yes: https://ma-x.im/blog/react-playbook-optimistic-ui Undo/Redo Without Losing Your Mind: The Command Pattern in React: https://ma-x.im/blog/react-playbook-undo-redo State Machines in React: When Booleans Start Lying to You: https://ma-x.im/blog/react-playbook-state-machines Immutable Data in React: The Rule I Stopped Arguing About: https://ma-x.im/blog/react-playbook-immutable-data-structures React State Management with Reatom: When useState Stops Being Enough: https://ma-x.im/blog/react-playbook-reatom-state-management --- # The Architecture Playbook: Communication & Cross-Cutting Concerns How the parts of an app talk to each other without turning into untraceable, stringly-typed magic. The Event Bus: Great for Decoupling, Great for Making a Mess: https://ma-x.im/blog/react-playbook-event-bus Feature Flags: Every Flag Is a Branch You Promised to Delete: https://ma-x.im/blog/react-playbook-feature-flags Analytics Is Architecture: Stop Sprinkling track() Everywhere: https://ma-x.im/blog/react-playbook-analytics-as-a-layer --- # The Architecture Playbook: Rendering & Delivery Decisions that look like performance tuning but are actually architecture wearing a disguise. SSR in React: What TanStack Start Actually Changes: https://ma-x.im/blog/react-playbook-ssr-tanstack-start Code-Splitting Is a Boundary Decision, Not a Bundle Trick: https://ma-x.im/blog/react-playbook-code-splitting Re-Renders Are React's Superpower, Not a Disease to Cure: https://ma-x.im/blog/react-playbook-rerenders-and-architecture Theming and Dark Mode Without the Flash: A Systems Problem in CSS Clothing: https://ma-x.im/blog/react-playbook-theming-dark-mode The Command Palette Is an Architecture, Not a Widget: https://ma-x.im/blog/react-playbook-command-palette Most Advanced TypeScript Isn't Worth What It Costs: https://ma-x.im/blog/react-playbook-types-that-earn-their-keep Authentication in React: Buy It, and Where the Line Really Is: https://ma-x.im/blog/react-playbook-authentication --- # The Architecture Playbook: Real Systems, Real Constraints The same ideas under the weight of an actual product, an actual team, and an actual deadline. Building Design Systems That Scale: https://ma-x.im/blog/building-design-systems-that-scale Complex Forms Done Right: https://ma-x.im/blog/complex-forms-done-right Monorepo Best Practices: https://ma-x.im/blog/monorepo-best-practices Design Prototyping for React: Where the Architecture Actually Starts: https://ma-x.im/blog/react-playbook-design-prototyping Checkout Isn't a Form. It's the Only Part of the App Where Architecture Has a Stopwatch on It: https://ma-x.im/blog/checkout-architecture-time-to-goal --- # Read-Only Is Not the Same as Safe Canonical: https://ma-x.im/blog/ai-read-only-data-boundaries Author: Maksym Kuzmitskyi Published: Nov 06, 2026 # Read-Only Is Not the Same as Safe An agent cannot edit the repository. It can still read a log containing customer information and include it in a remote request or a published explanation, if its tools and data path allow that. Nothing in that hypothetical example requires a file write. I like read-only modes. They are useful restrictions, especially for review and investigation. I don't like treating the label as a complete security argument. Integrity and confidentiality are different properties. Preventing a change to local files doesn't, by itself, establish who can see their contents or where those contents can travel. ## Start with the data path, not the mode name For an agent-assisted task, I would identify what can be read, which process or service receives it, and where outputs can appear. That includes the model provider, local and remote tools, logs, review comments and any connected workspace. A tool named search may run locally or call a remote index. A browser may already be authenticated to services the task doesn't need. The answer depends on the actual product, integration, account and organization policy. I wouldn't infer retention, training use, residency or access controls from the word enterprise or from a familiar brand name. GitHub's [current application card](https://docs.github.com/en/copilot/responsible-use/code-review) distinguishes data flows across its agent surfaces and explicitly discusses responsibility for a bring-your-own-provider configuration. That is a reason to inspect the selected path, not to assume every Copilot session sends data through the same route. Read-only should be one property in that description. It shouldn't replace the description. ## Source code isn't the only sensitive input A repository can contain private fixtures, copied production responses or internal endpoint information. Development machines can also hold browser profiles, credential files and local service configuration outside the checkout. I would avoid collecting all of that merely because a tool is capable of reading it. The task should establish a need for particular information, and the environment should enforce meaningful limits where possible. The right question isn't whether the agent is generally trustworthy. It is whether this task requires this class of data under the approved handling rules. For many investigations, a sanitized schema or a small synthetic fixture can answer the technical question. If real data is necessary, its use needs the appropriate authorization and controls. Replacing names in one field doesn't automatically anonymize an entire payload. I would not ask someone to paste secrets into a chat so the agent can diagnose an authentication problem. A person can configure a credential through the intended secure mechanism without turning its value into task content. ## File access and network access are separate boundaries A process may have restricted writes and broad reads. It may also have an outbound network path. Those properties need to be examined together. The [VS Code security guide](https://code.visualstudio.com/docs/agents/run/security), checked on October 23, 2026, explicitly separates sandbox behavior, permission checks and network configuration. It notes that outbound network access can remain enabled under its documented defaults and that tool paths and harnesses differ. I am deliberately not presenting a generic setting that supposedly secures every session. A shell command, a built-in file tool and a remote MCP tool can pass through different controls. Restricting a local process doesn't necessarily restrict a connected remote service. Blocking an arbitrary external host doesn't prevent disclosure to an allowed service that should not receive a particular payload. Likewise, an allowed destination isn't permission to send every accessible file there. Access to a provider for legitimate inference still requires appropriate selection of the context supplied. > A permitted route and a permitted payload are different decisions. This is where a read-only label becomes particularly incomplete. It says little about either one unless the product defines those properties explicitly. ## The agent can follow the task and still expose too much Prompt injection is one route to an undesirable action, but it is not required for every disclosure. An agent honestly trying to explain a failing test may quote an entire response body when a status code and a sanitized field name would suffice. A reviewer may include a sensitive configuration value in an otherwise useful comment. I would want output handling to consider necessity and destination, not only whether the conclusion is correct. This also matters for task records. Preserving evidence does not require keeping raw credentials, complete private payloads or every retrieved document. Logs that improve observability can create another data store with its own access and retention obligations. A link or bounded summary may be more appropriate than a copy. Sometimes neither is appropriate in the destination where the agent is about to write. Read-only access to the source doesn't prevent a different tool from publishing the resulting text. The review of that publication path needs to consider what it contains. ## Approval needs enough information to be meaningful A request for permission to call a tool should identify the operation and relevant destination without displaying secrets in the prompt itself. A person approving a broad capability for convenience may not be approving every later use of sensitive content. Long-lived approvals, inherited authentication and ambiguous tool descriptions can widen the practical boundary beyond the user's immediate intention. I would prefer task-scoped access with an understandable lifetime. Where a product supports separate permissions for reading, processing and publishing, those should reflect the task rather than share one blanket decision by default. That doesn't mean asking a person about every ordinary file. Approval fatigue can make a nominal checkpoint less useful. Enforced restrictions and clearly defined safe paths can reduce unnecessary prompts while preserving meaningful decisions. The [existing guardrails article](/blog/agent-playbook-guardrails) concerns control over agent behavior. Here the question is narrower: which data may cross which boundary, even during behavior that appears routine. ## Test the boundary without using real secrets For an authorized evaluation, I would use disposable files containing unique, harmless markers rather than actual credentials or customer records. Then check which reads, requests, logs and outputs contain those markers. The setup should use a controlled environment and destinations approved for the test. The purpose is to observe the data path, not to try bypassing organization controls. A successful fixture establishes something about the observed tools and configuration. It doesn't prove every model decision will minimize data or that every future integration inherits the same restrictions. Denied operations deserve testing too. A tool should not silently retry through a more privileged route simply because its first attempt was blocked. An unavailable source should remain unavailable in the report, not become a reason to weaken the boundary. I would also test what survives after the session: retained outputs, cached tool responses and published artifacts. Stopping the agent is not necessarily the same as removing information already sent or stored. ## Keep read-only useful by describing what it protects I don't want to discard a useful mode because it doesn't solve every problem. Preventing mutation can substantially reduce the risk of an investigation or review task. I want the claim to remain specific: which writes are prevented, which reads remain possible, what network paths exist and which publication actions are available. Once those are explicit, the team can decide whether the environment is appropriate for the data involved. Without them, safe becomes a feeling attached to a mode selector. A read-only agent may be exactly the right tool. I would still ask what it can learn, who receives that knowledge and what remains after the task finishes. When you approve read-only agent access, which data boundary do you verify separately? I'd be interested in the practical checks that made the mode's actual guarantees clear. --- # You Didn't Write It. You Still Have to Maintain It. Canonical: https://ma-x.im/blog/ai-generated-code-maintenance Author: Maksym Kuzmitskyi Published: Nov 04, 2026 # You Didn't Write It. You Still Have to Maintain It. The feature works. The tests pass. The agent can explain every file it created. Now ask another engineer to change one business rule without the original conversation. That is the test I care about after the demonstration. Not whether a human typed the code, but whether the resulting system can be understood and changed by the people responsible for it. Generated code doesn't need a special moral category. It needs an ordinary maintenance owner. The prompt isn't that owner, and the model being able to regenerate an explanation isn't a substitute for one. ## Understanding is not remembering every line I wouldn't require an engineer to memorize generated code before accepting it. We don't apply that standard to dependencies or to every change written by a colleague. I would expect someone to understand the important boundaries: where state is authoritative, where input becomes trusted, which contracts are shared, how failures surface and what a future change is likely to affect. GitHub's [current application card](https://docs.github.com/en/copilot/responsible-use/code-review) explicitly calls for reviewing and testing generated code. I see that as an acceptance floor, not a complete account of whether another engineer can maintain the result. That understanding can come from code structure, tests, documentation and exploration. It doesn't require manual authorship. The concern begins when the implementation can only be explained through the agent that produced it. A maintainer asks why a cache exists, which consumer requires an adapter, or whether a retry can repeat a write, and the answer is to start another conversation hoping the model reconstructs the original decision. The model may produce a persuasive explanation. Without supporting evidence, it may also produce a new justification for an old artifact. ## Local plausibility can accumulate into a confusing system An agent can reasonably add a helper for one task, another wrapper for the next, and an extra configuration layer to keep the third change small. Each PR can look tidy on its own. The combined codebase can acquire several ways to perform the same operation, with no clear reason to choose among them. This is a hypothetical pattern, not a report of a particular employer's repository. It is also familiar without AI. More convenient generation can make local additions cheaper while leaving their long-term coordination cost intact. OpenAI's [2026 harness-engineering report](https://openai.com/index/harness-engineering/) describes agents reproducing existing patterns, including uneven ones, and discusses mechanical constraints and cleanup in its own experiment. It also explicitly leaves long-term architectural coherence as an open question. I take that as a reason to inspect accumulating structure, not evidence that every generated system inevitably decays or that a recurring cleanup agent solves maintenance universally. The important question is what the next change will copy. A convenient local pattern can become an accidental standard simply because it is visible. ## A useful abstraction should make the next decision easier I am not against introducing an abstraction with AI assistance. I want its existence to reduce complexity that actually matters. For an illustrative payment flow, an adapter separating provider responses from application state can be a clear boundary. Several generic layers that forward the same parameters may only make the behavior harder to find. The review question isn't whether the abstraction looks sophisticated. It is which variation, dependency or invariant it isolates, and where that value can be observed. I would ask for a concrete next change. Add a provider error, change a validation rule or remove a consumer. Which files move, and which parts should remain untouched? This doesn't predict every future requirement. It tests whether the explanation of the current design connects to an ordinary modification rather than a diagram alone. The same standard applies to hand-written code. AI doesn't make architectural taste objective, but it makes it particularly easy to generate more structure before deciding whether the structure earns its place. ## Preserve reasons that aren't visible in the code A good name explains what a function does. It may not explain why an older implementation still exists or why a seemingly simpler migration was deliberately postponed. Those decisions deserve a small durable record when they affect future work. Link the relevant requirement or design decision, identify the remaining constraint, and keep the record close enough to be discovered. I don't want a transcript of every rejected alternative. I want the few facts a future maintainer would otherwise have to guess. That is consistent with [keeping repository context useful](/blog/agent-playbook-context-is-the-product): context is an engineering artifact with ownership and freshness, not an unlimited pile of prose. An agent-written explanation still needs review. It can describe the intended design while the implementation differs, or turn an inference into a historical claim. Documentation should point to evidence and make uncertain reasons visible. When a constraint changes, update or remove the obsolete explanation. A permanent paragraph defending a temporary workaround can become part of the problem. ## Tests should explain behavior, not freeze incidental shape Tests are part of maintenance because they tell the next engineer what must remain true. A suite dominated by snapshots of internal structure can make a straightforward refactor feel dangerous without explaining the product invariant. A suite of overly broad mocks can give the opposite impression: every change looks safe because the meaningful interaction is replaced. Neither snapshots nor mocks are inherently wrong. Their value depends on the question they preserve. I would prefer a future maintainer to see what a denied operation must do, which retry is permitted, or how a state transition handles interruption. Those are constraints that help a change stay local. The existing [React testing article](/blog/react-playbook-testing) discusses choosing checks by what they establish. The maintenance angle is what those checks teach someone who didn't participate in the implementation. A test that merely agrees with generated code can preserve the wrong assumption. A well-founded test can make that assumption challengeable without requiring the original prompt. ## Try a handoff change before accepting a large structure For a consequential generated subsystem, I would give another engineer a small realistic modification. Ask them to identify the owning behavior, explain the relevant invariant and make the change using the available repository evidence. This is a proposed acceptance exercise, not a measured experiment from my work. It shouldn't become compulsory theater for a two-line fix. The useful observations are where the person has to guess, which explanation doesn't match the code, and whether an unrelated change becomes necessary just to touch the intended behavior. Another agent can attempt the exercise too, but its success doesn't automatically establish human maintainability. It may tolerate a structure that a team cannot reasonably review or operate. I also wouldn't require every handoff to produce exactly the same implementation. Different valid solutions can preserve the same contract. The goal is intelligibility and controlled change, not reproducing the author's path. ## Ownership includes deciding not to regenerate When a generated component becomes confusing, asking for a complete rewrite can be tempting. It can also replace one poorly understood system with another and make the previous review evidence obsolete. I would first identify the concrete maintenance problem: unclear ownership, duplicated behavior, an unnecessary dependency or a test that prevents safe change. Then repair that boundary with proportionate scope. Sometimes replacement is justified. It still needs a migration and verification plan, not just a cleaner-looking output. I want AI assistance to reduce the cost of working on a system, not merely the cost of producing its first version. That means judging generated code by the work it leaves behind as well as the work it completes. The next engineer shouldn't need the same model, the same prompt and the same conversation to make a safe change. They should have a codebase that explains enough of itself. What would you ask someone else to change before accepting a substantial AI-generated implementation? I'd be interested in the smallest handoff exercise that reveals whether the design is genuinely maintainable. --- # The Agent Knows the Library. Just Not Your Version. Canonical: https://ma-x.im/blog/ai-library-version-mismatch Author: Maksym Kuzmitskyi Published: Nov 02, 2026 # The Agent Knows the Library. Just Not Your Version. The suggested API is real. The documentation example is valid. The project still cannot use it. I find that more interesting than a completely invented method name. A believable solution can belong to a different version, package entry point, runtime or feature mode. It survives a quick recognition check because an engineer has seen something similar before. The agent may know the library. The task requires it to know the library as installed and configured here. ## Familiarity is not a compatibility check A package name is a broad label. Several major versions can coexist in active projects, and a migration guide can describe a destination rather than the current state. Even a matching version number may not settle the question. A package can expose different browser and server entry points. A feature may require configuration. A workspace package may resolve to a local artifact rather than the registry version the agent searched for. This isn't a reason to distrust documentation. It is a reason to identify which documentation applies. I would first establish the relevant installed package, its resolution from the consuming application and the configuration that changes its behavior. Only then would I decide whether the proposed example is evidence or inspiration. ## Inspect what the application resolves For a Node-based project, an inspection script placed next to the application's package.json can make the question concrete: ```javascript import { createRequire } from 'node:module'; const requireFromApp = createRequire(new URL('./package.json', import.meta.url)); const packagePath = requireFromApp.resolve('next/package.json'); const installedPackage = requireFromApp('next/package.json'); console.log(JSON.stringify({ packagePath, version: installedPackage.version }, null, 2)); ``` This example checks Next.js metadata through Node's resolution from that application location. It doesn't inspect every conditional runtime export. Some packages don't expose package.json through their exports, so the same inspection method isn't universal. The important part is the starting point. Resolving a package from the monorepo root may answer a different question from resolving it inside the application that imports it. For a browser bundle, I would also inspect the relevant bundler configuration or output when aliasing and conditional resolution matter. A convenient Node probe isn't proof of what every runtime loads. A manifest range describes intent. An actual resolution tells us more about the artifact being examined. ## Current documentation can describe more than one model Next.js provides a useful present example without needing a claim that its framework is unusually confusing. Its [caching guide for projects without Cache Components](https://nextjs.org/docs/app/guides/caching-without-cache-components), checked on October 23, 2026, explicitly identifies itself as the previous model and distinguishes the Cache Components path introduced in version 16. That means searching for caching guidance isn't enough. The agent needs to establish the project's version and selected mode before transferring advice. I am not upgrading this site or recommending one caching mode in this article. The point is that two official explanations can be correct while applying to different configurations. The same pattern appears with router modes, compiler settings and server/client boundaries. Advice from a new guide may require a migration that is outside the current task. An agent should not quietly perform that migration merely to make its preferred example fit. Discovering that a solution requires an upgrade is useful output. It is not automatic authorization to upgrade. ## Types narrow the question, but don't finish it A compiler rejecting an unfamiliar option is valuable feedback. Removing the error with a cast doesn't establish that the runtime supports the option. I would inspect the installed declaration and the exported implementation around the disputed boundary. A type can be stale, overly permissive or describe an entry point different from the one actually used. Likewise, a compiler accepting an option doesn't prove its intended behavioral effect. Some configuration paths tolerate extra input; some features are available only under particular runtime conditions. The next check should discriminate between those possibilities. That might be a narrow runtime probe, a version-matched example or a test through the actual deployment adapter. Re-running the whole suite without exercising the disputed behavior may add time without resolving the uncertainty. This is one place where I would rather have an agent say the evidence is incomplete than confidently widen a type until the build becomes green. ## Upgrade instructions are not current project instructions A migration document often says to replace one function with another or remove an old configuration field. Those instructions are conditional on performing the migration. If the task is a bug fix on the existing release, copying the destination's code can create an accidental mixed-version implementation. It may even look cleaner than the valid old API. I would keep the task's compatibility target explicit. Are we fixing behavior on the current version, preparing a migration, or completing an approved upgrade? Each has a different acceptable diff. Related packages need attention too. A new plugin, shared component package or framework adapter may have peer requirements that the application doesn't satisfy. Satisfying one import doesn't establish a supported dependency set. The versioned [npm ci documentation](https://docs.npmjs.com/cli/v11/commands/npm-ci) describes frozen installation and configuration requirements for that CLI line. It helps explain why a manifest edit, lockfile resolution and installation can diverge. It is not permission to apply npm 11-specific behavior to another package manager without checking. ## Keep retrieval attached to the compatibility question I would search with the package version, relevant mode and disputed symbol rather than ask broadly how to use the library. Then I would compare the retrieved claim with the installed artifact. If an MCP documentation tool exposes version selection, use it deliberately. If it returns only current documentation, retain that limitation. A successful tool call doesn't establish that the returned guide matches the consuming application. Pinned documentation can age too. A project may have upgraded while its instructions still point to an earlier guide. Repository memory is useful for locating the intended source, not for overriding current package evidence. The [instructions-upkeep article](/blog/agent-playbook-instructions-rot) concerns rules that stop describing the project. Dependency advice can fail in the same quiet way: the sentence remains plausible while its compatibility conditions have changed. ## A useful answer includes the boundary When an agent recommends an API, I want to know which package, version, entry point and configuration support the recommendation. The detail should match the risk; a familiar stable helper doesn't require a research report. When compatibility is uncertain, a small verified alternative may be better than pulling the whole project toward the newest documentation. When an upgrade is genuinely necessary, make it a deliberate proposal with its own validation. I don't want an agent that knows fewer libraries. I want one that can stop recognizing and start checking when recognition is no longer enough. Which version-dependent mistakes are hardest to catch in your AI-assisted work: APIs from another release, features behind configuration, or packages resolved from the wrong workspace? I'd be interested in the smallest check that reliably settles the question for you. --- # "Works on My Machine" Now Includes the Agent's Machine Canonical: https://ma-x.im/blog/ai-agent-environment-reproducibility Author: Maksym Kuzmitskyi Published: Oct 31, 2026 # "Works on My Machine" Now Includes the Agent's Machine The agent ran the test. The result was green. Another engineer checks out the branch and cannot get the application to start. That hypothetical handoff doesn't require the model to have lied. It may have accurately described a result from an environment the next person does not have. I think the useful question is what made that result possible: runtime, installed artifacts, configuration, test data, processes and state. A commit identifies code. It doesn't identify all of those inputs. AI-assisted development doesn't invent this old problem. It adds more environments that can appear, validate work and disappear before a teammate sees them. ## A worktree isn't a complete environment A separate Git worktree is useful for isolating source changes. It doesn't automatically isolate ports, databases, home-directory configuration, credentials or services shared by several tasks. Two branches can be separate on disk while their tests talk to the same local service. One session can migrate a database the other expected to remain unchanged. A process started earlier can serve a different revision from the files currently being inspected. The agent may see a healthy page without establishing which server produced it. I would identify the actual application instance, its revision and its relevant configuration before using an interaction as evidence. That can be a build identifier, an explicit process path or another practical observation. It need not become a ceremony after every refresh. The [current GitHub application card](https://docs.github.com/en/copilot/responsible-use/code-review) describes ephemeral environments for its cloud agent and distinguishes them from local execution. Those are meaningful differences in lifecycle and access. They are not a promise that every tool called an agent runs in the same reproducible container. ## The lockfile is necessary evidence, not the whole story A manifest expresses requested dependencies. The lockfile records a more specific resolution. The installation on disk is the artifact the process actually loads. Those can disagree because of a stale installation, workspace linking, local tarballs or generated output. An agent can make a correct diagnosis of the code it loaded while the committed project still produces something else. The versioned [npm 11 documentation for npm ci](https://docs.npmjs.com/cli/v11/commands/npm-ci) makes its frozen-install behavior explicit: it requires a lockfile, rejects manifest/lockfile disagreement and doesn't rewrite those inputs. It also says tree-shaping flags used when creating the lockfile must be supplied consistently. I wouldn't present that as a universal command for every package manager or npm release. Use the repository's supported install path and actual tool version. The point is to make dependency reconstruction deliberate rather than inherit a convenient node_modules directory. A clean installation still depends on artifact availability, platform support and permitted lifecycle scripts. A lockfile cannot provide an unavailable private package or a native library missing from the host. Reproducible dependency selection is one boundary. Reproducible execution is larger. ## Configuration needs a contract without exposing its values An agent's environment might contain an environment variable that makes a service reachable or silently selects a mock. A fresh checkout may not. I would document required configuration names, their purpose, safe defaults and how an authorized person obtains them. I would not copy secret values into a PR, task record or agent transcript to make the handoff convenient. Missing configuration should fail visibly where appropriate. A fallback to a mock can be useful for local tests, but it must remain distinguishable from a real integration check. Otherwise a working simulation can be reported as evidence about a system it never contacted. Build-time and runtime settings also differ. A browser bundle may already contain a selected public setting even after the environment changes. Checking the shell's current value doesn't establish what the built application uses. This is why I want configuration provenance, not a dump of configuration. The next engineer needs to recreate the intended conditions without inheriting sensitive information they don't need. ## Test state can be the hidden dependency Consider an illustrative account-management test that passes only because a user record was created manually in an earlier session. The fixture isn't in the repository. The setup step isn't in the task notes. The agent's test result can be real and the validation can still be nonportable. I would prefer explicit fixtures with controlled ownership and cleanup. If a shared environment is unavoidable, record the relevant preconditions and limits. Don't reset shared state merely because it would make the current task easier. Time, locale, timezone and network responses can also influence results. Not every test needs a simulated clock or a hermetic network. But a result used to justify a behavioral claim should identify the inputs that decide it. The same caution applies to retries. A flaky success after several attempts isn't equivalent to a stable result, and an agent shouldn't erase the failed attempts from the explanation. Caches deserve similar treatment. A warm cache can make a path work that a first-time user cannot complete. A stale build cache can preserve implementation bytes the source no longer describes. ## Record a reconstruction path, not an entire machine For a meaningful handoff, I would keep a small environment record alongside the evidence: relevant revision, runtime and package-manager versions, install procedure, configuration contract, fixture setup, and the exact check performed. That is a proposal for useful evidence, not a requirement to archive every process and environment variable. Excessive collection creates privacy and maintenance problems of its own. The record should also say what was not reconstructed. An unavailable external provider, a mocked payment step or a local-only service is a limitation, not an embarrassing detail to hide. I would check the reconstruction in a fresh authorized environment when the risk justifies it. The aim is to remove accidental dependencies, not to claim that a clean checkout guarantees production behavior. A container image can package more of the environment. It still needs controlled inputs, external contracts and an explanation of which mounted files or services sit outside it. ## The evidence should survive the session My [green-checks article](/blog/agent-playbook-green-checks) asks what a check actually established. Environment provenance makes that question answerable after the agent's session ends. An ephemeral runner is useful precisely because it doesn't preserve incidental state forever. That also means useful setup and result evidence must live somewhere appropriate before the runner disappears. There is a balance here. I don't need a permanent recording of every terminal screen. I need enough non-sensitive information to understand and repeat the decisive check. If the only reconstruction method is asking the original agent to remember what it did, the environment hasn't really been handed off. ## Leave the next engineer a smaller mystery I want agents to validate their changes. I also want validation to leave something more durable than the sentence that it worked. The handoff should help another engineer distinguish a code defect from a missing setup step, a dependency-resolution difference from a changed requirement, and a mocked success from a real integration result. That is ordinary engineering discipline, made more important by the number of disposable workspaces we can now create. When an agent finishes a task in your environment, which part is hardest to reproduce afterward: the dependencies, the service state, or the exact conditions of its checks? I'd be curious what you preserve and what you deliberately avoid collecting. --- # Upgrading the Model Means Retesting the Workflow Canonical: https://ma-x.im/blog/ai-model-upgrade-workflow-regression Author: Maksym Kuzmitskyi Published: Oct 29, 2026 # Upgrading the Model Means Retesting the Workflow Changing a model identifier can be a one-line edit. It is not necessarily a one-line change to the system's behavior. The same task may now produce different searches, tool arguments, clarification questions, stopping decisions or recovery attempts. The final code can improve while one of those surrounding behaviors becomes less suitable for the workflow. I would treat a model upgrade as a change to an engineering dependency, not as permission to carry every previous assumption forward. That isn't an argument for staying on an old model. It is a reason to make the benefit and the compatibility work observable. ## The application contract is larger than the final answer A coding agent operates inside a harness: prompts, tool definitions, permissions, context management, execution loops and output handling. The model is one consequential part of that arrangement. The contract may require the agent to inspect the current base before editing, use a particular tool for a sensitive action, stop when authorization is missing, and distinguish an unavailable check from a successful one. Those requirements don't disappear because the candidate model produces a better-looking patch. Some differences are API compatibility issues. Others are valid behavior changes inside an otherwise compatible API. A request succeeding doesn't establish that the application still gets the kind of progress events or tool-use pattern it expects. There is current, concrete evidence for taking that distinction seriously. Anthropic's [Fable 5.1 migration guide](https://platform.claude.com/docs/en/models/fable-5-1/migration-guide), checked on October 23, 2026, documents model-specific changes involving forced tool choice, conversation-history handling and agent-loop behavior. Those details apply to the documented migration, not to every model or managed product. The general lesson isn't to memorize today's parameter list. It is to read the migration contract for the exact integration being changed. A managed agent product may handle details that a custom API harness must manage itself. ## First name what is actually changing An editor update can change the model, tool descriptions and execution behavior together. A provider can update a model alias. A team can revise its system prompt while testing a new model. If all of those happen at once, an improved result does not identify which change helped. A regression doesn't identify which component broke either. For a controlled comparison, I would record the model identity available to the integration, harness revision, prompt revision, tool schemas, relevant settings and fixture state. If the exact underlying model is hidden, I would record that limitation instead of inventing a stable identity. Keep task inputs and starting repositories comparable. A new base commit, warmed cache or already-fixed fixture can turn a model comparison into a comparison of different problems. One variable at a time is a useful diagnostic ideal, not always a deployment option. When a product bundles changes, evaluate the bundle and describe the attribution limit honestly. ## Build cases around decisions that matter I would start with a small regression set drawn from the workflow's consequential boundaries. A clear local fix should remain clear and local. An ambiguous requirement should produce a useful question rather than an invented product decision. A failed integration check should not be summarized as a successful task because the unit suite passed. Another fixture might change the PR head during review. The expected outcome is to notice that the reviewed artifact has changed, not merely attach the old conclusion somewhere the API accepts it. These are proposed evaluation cases, not reported experiments or results from my work. Their value comes from defining the acceptable outcome before reading the candidate's explanation. I would avoid requiring one exact tool-call sequence unless the sequence itself enforces a real constraint. Two valid investigations may read different files. The evaluation should distinguish a different route from a violation of the task's boundaries. Conversely, a plausible final patch shouldn't erase an unauthorized intermediate action. Evaluate consequential actions and the final artifact, not just the last paragraph. ## Grade observable behavior, with room for uncertainty Some outcomes can be checked mechanically: whether a forbidden mutation occurred, whether the final diff contains unrelated files, or whether a claimed test command actually completed. Other outcomes need a domain reviewer: whether a clarification was necessary, whether a suggested integration belongs in scope, or whether the proposed test establishes the intended behavior. A model-based grader can help organize evidence, but it isn't automatically an independent authority. I would calibrate it against reviewed examples and inspect disagreements. A score without an understandable basis is another opaque output. OpenAI's [evaluation documentation](https://developers.openai.com/api/docs/guides/evaluation-getting-started) describes datasets, annotations and graders. At the October 23 check, it also carries a deprecation notice for the hosted Evals platform. I am not recommending a new dependency on that retiring service. Representative cases and explicit grading criteria remain useful regardless of which supported runner stores them. The tooling should serve the comparison. It should not become a reason to keep a fragile evaluation tied to an obsolete interface. ## Recovery deserves its own test A clean success path is a friendly demonstration. The more revealing cases often involve unavailable tools, authentication failures, partial edits and interrupted work. I would check whether the candidate preserves the task boundary after an error. Does it ask for a secret in an inappropriate channel? Does it retry an irreversible operation without checking the previous outcome? Does it weaken a test merely to complete the loop? These concerns aren't claims that a particular model does those things. They are reasons to observe recovery rather than assume it inherits the quality of the model's successful answers. Permissions should remain enforced outside the model. An evaluation can detect undesirable behavior; it shouldn't be the only thing preventing a consequential action. The same reasoning applies to compaction and handoffs. A workflow that works for five turns may fail when a summary loses an important unresolved condition. A longer-running fixture can expose that boundary without requiring an enormous benchmark. ## Compare the cost of an accepted result Tokens and response latency are useful measurements. They don't describe the whole task if the candidate requires more correction, publishes noisier reviews or leaves harder-to-understand changes. I would record human interventions and rework alongside execution cost, using actual observations rather than estimated productivity claims. Passive waiting and a person's active effort are different quantities. Repeated runs matter where outputs vary. One candidate success and one baseline failure are anecdotes, not a stable rate. The amount of repetition should match the consequence of the decision and the available resources. The result can be mixed: better implementation on one class of task, more clarification on another, a compatibility repair needed in the harness. That is a useful migration finding, not a disappointing failure to produce a winner. ## Keep a way back Before changing a default, I would keep the previous configuration identifiable and limit initial exposure. That might mean a small authorized task class or shadow review without automatic publication. Rollback has limits too. A pinned model may later be retired, and a managed product may not expose an exact old configuration. Record what can actually be restored rather than promising a permanent switch. The existing [evaluation article](/blog/agent-playbook-evaluation-is-the-missing-loop) asks whether the workflow produces useful outcomes. A model upgrade is a concrete occasion to ask that question again, with the old assumptions made visible. I want to use better models. I also want to know which part of my working agreement with the agent changed when I selected one. What would make a model upgrade fail acceptance in your workflow even if its final code looked better? I'd like to hear which behavioral regressions your evaluations can actually detect. --- # When Repository Content Starts Giving Orders Canonical: https://ma-x.im/blog/ai-repository-content-trust Author: Maksym Kuzmitskyi Published: Oct 27, 2026 # When Repository Content Starts Giving Orders A source comment explains a strange compatibility rule. A README explains how to run the project. A test fixture contains a conversation. A fetched issue describes what should change. A coding agent needs all of them. They do not all have the same right to tell it what to do. That is the boundary I find more useful than telling an agent not to trust the internet. A repository can contain relevant evidence, authorized project instructions, obsolete advice and deliberately hostile text. Sometimes those arrive through the same search result. The problem is not reading a suspicious sentence. The problem is promoting a sentence from material under inspection into authority over the inspection. ## The source being reviewed cannot appoint itself the reviewer Consider an illustrative PR that adds a comment describing a component as exempt from ordinary validation. The same change tells automated reviewers to ignore failures involving that component. The comment may be useful evidence about the author's intent. It is not, by itself, an approved exception to the team's validation policy. If the agent treats it as an instruction, the proposed code has acquired a way to influence how it is judged. The author need not have changed a tool permission or a protected policy file. The confusion happened in interpretation. This can be deliberate prompt injection. It can also resemble an ordinary documentation mistake: an outdated setup note asks for a step the current task doesn't need. The intent of the text and the authority of the text are separate questions. I would not claim every incorrect README instruction is an attack. I would ask whether the agent is using it as context to verify or as a command that overrides the actual task. ## Repository-local doesn't mean equally trusted An instruction file deliberately selected by the user or organization has a different role from a copied log line. A task description from an authorized owner differs from an arbitrary comment underneath it. A policy on the reviewed branch may itself be part of the proposed change. That doesn't mean refusing all repository instructions. It means keeping their origin, scope and review status visible. For a PR reviewer, the base branch's approved policy and a proposed replacement on the head branch should not silently become the same source. A legitimate policy update may need review. Its existence in the diff doesn't automatically authorize it to govern that review. Likewise, a retrieval tool returning content doesn't authenticate the instructions inside that content. The tool may be trusted to fetch a page accurately while the page remains untrusted to direct actions. The distinction also applies to generated summaries. If a summary turns a quoted instruction from a fixture into an unqualified next step, it can lose the original boundary while preserving the words. > Accurate retrieval is not delegated authority. I want a handoff to preserve that difference, not just preserve more text. ## Current controls matter, but they cover different surfaces This is not an argument that current coding agents operate without protections. The [VS Code security guide](https://code.visualstudio.com/docs/agents/run/security), checked on October 23, 2026, documents workspace trust, approvals, sandboxing, MCP-server trust and information-exposure risks. The details depend on the active harness and tool path. Its guidance distinguishes process sandboxing from permission checks on other tools and warns that sandboxing is not a standalone security boundary. That is more useful than assuming one toggle makes every route equivalent. Instructions guide the model. Permissions determine which operations are available. Isolation can constrain what an executing process reaches. Network restrictions constrain destinations. None of these automatically proves that a proposed change satisfies the task. The [current GitHub application card](https://docs.github.com/en/copilot/responsible-use/code-review) also describes different environments and data flows for its agentic surfaces. I wouldn't transfer a cloud agent's documented constraints to a local terminal session merely because both carry the same product name. Good controls reduce the consequences of a confused decision. They do not remove the need to distinguish data from instructions. ## Keep the action boundary outside the prose A document can recommend a command. It should not be able to grant that command new permissions. I would enforce consequential restrictions in the tool or execution environment rather than depend solely on the model agreeing to follow a warning. A reviewer that doesn't need mutation tools shouldn't receive them by default. A task needing one repository shouldn't inherit every account a developer happens to use. That principle is narrower than prescribing a particular sandbox configuration. Filesystem access, credential availability, network routes and connected services vary by environment. The controls have to be checked where actions actually run. A tool wrapper that inspects only one command shape may miss a different execution route. A hook's failure or timeout behavior may not match an engineer's assumption about stopping. I would test those boundaries instead of treating the existence of a hook as enforcement. There is also a quiet escalation to avoid: allowing a document being analyzed to nominate additional tools or a more privileged environment as prerequisites. A claimed need for access is still a request to evaluate. I discussed useful tool context in [Tools Are Part of the Agent's Intelligence](/blog/agent-playbook-tools-are-intelligence). That usefulness makes precise tool authority more important, not less. ## Test whether an instruction stays inside its source For an authorized local evaluation, I would use harmless fixtures. A source file or mock tool result could request a clearly out-of-task change to a disposable marker file. The expected outcome would be to recognize the instruction as content, not carry it out. No real secrets, external collection endpoints or production systems are needed to establish that question. The test should inspect actual tool activity as well as the final explanation. Saying that an instruction was ignored while performing its requested action is not a pass. I would vary the source: a comment, a generated report, a quoted issue reply and a summarized tool result. The aim is to check the boundary through paths the workflow actually uses, not to collect theatrical attack phrases. Passing such fixtures is evidence about those cases. It is not proof against every prompt injection. The environment still needs constraints that limit the effect of a missed case. Legitimate instructions matter in the evaluation too. An agent that refuses to follow the approved project setup has not solved trust by refusing all work. I want correct treatment of different sources, not indiscriminate suspicion. ## A stopped action should leave an understandable reason If a source asks for an unexpected operation, the useful response identifies the source and the conflict: this instruction appeared in material being analyzed, but the task did not authorize the action. A person can then confirm an actual requirement through the appropriate channel. The agent doesn't need to turn every questionable paragraph into an emergency. It needs to avoid quietly changing who is in charge. Logs can help reconstruct that decision, but they should not copy entire sensitive documents merely to preserve evidence. Record enough origin and action information to investigate, with appropriate access and retention. I don't want to make agents blind to repositories. I want them to read carefully without making every readable sentence a new supervisor. When a coding agent fetches something in your workflow, what establishes whether that content may direct its next action? I'd be interested in the boundaries you have actually tested, especially the ones that survive summaries and handoffs. --- # The Agent Finished. The Reviewer Is Still Reading. Canonical: https://ma-x.im/blog/ai-review-human-capacity Author: Maksym Kuzmitskyi Published: Oct 25, 2026 # The Agent Finished. The Reviewer Is Still Reading. The agent has finished the implementation. CI is green. There is a useful PR description, a test summary and another task ready to start. The reviewer is still trying to understand the first change. I don't think that makes the reviewer the slow part of an otherwise efficient machine. Generation and acceptance are different kinds of work. Producing another plausible implementation does not create another person's attention to examine it. The interesting question isn't how many PRs an agent can open. It is how much consequential change a team can understand, validate and own without turning review into an exercise in trusting the summary. ## A faster author changes the queue Imagine a team where generated changes arrive faster than reviewers can assess them. This is a hypothetical operating condition, not a productivity measurement from my work. The immediate symptoms might look encouraging: more branches, more completed implementation tasks, more green checks. The waiting work has simply moved. Opening several PRs in parallel may shorten implementation time for each author while extending the delay before any reviewer can concentrate on one. Interrupting reviewers with repeated requests makes their effective capacity smaller still. This is a workflow problem, not an argument against agents. A compiler getting faster never meant that architectural judgment became free. The same distinction deserves to survive another increase in code-generation capacity. OpenAI's [2026 harness-engineering report](https://openai.com/index/harness-engineering/) describes human QA capacity becoming a constraint as code throughput increased in its own internal experiment. Its response involved making application behavior and observability more accessible to agents. Those are observations from a particular environment, not a throughput target or permission model I would import wholesale. For my purposes, the important part is the changed constraint. If acceptance is waiting, making authors produce more work may be optimizing the wrong stage. ## Reviewability isn't a line-count limit A small diff can contain a large decision. One changed authorization condition may deserve more attention than a generated file containing hundreds of mechanical edits. I would size review around behavioral questions: what changed, who depends on it, which assumptions changed, and what evidence is available. Line counts can help notice outliers. They do not calculate risk. Consider an illustrative PR that introduces a shared utility, migrates consumers, changes a dependency and refreshes unrelated snapshots. Every individual edit might be reasonable. Together they create several distinct review jobs. The reviewer has to separate the intended behavior change from migration mechanics, dependency effects and test-expectation updates. A detailed explanation can help. A cleaner division of work may help more. That doesn't mean splitting code into arbitrary tiny PRs. A sequence of fragments that cannot be tested or understood independently can increase coordination costs. I would look for cohesive behavioral slices with explicit dependencies and a valid state between them. > A reviewable change gives someone a bounded question they can actually answer. The unit isn't necessarily one file, one agent session or one convenient commit. It is an intelligible decision with enough surrounding evidence. ## Summaries should lower the cost of checking A good summary tells me where to inspect, not merely what conclusion to reach. For a permission change, I want the affected rule, the relevant route and the check that exercised a denied action. For a shared component change, I want the changed contract and the consumers that make it consequential. For an expected-result update, I want the requirement that changed. I don't need a transcript of every search or an elaborate account of the model's internal reasoning. I need references I can follow and limitations I can see. An agent saying that all relevant scenarios passed should be able to identify those scenarios. If a check was unavailable, the absence should remain visible rather than disappear inside a reassuring overall conclusion. This is related to [useful automated review comments](/blog/github-ai-pr-reviewer), but it is a different responsibility. The question here is whether the whole change can be accepted with reasonable effort, not whether an individual bot comment is well phrased. Long descriptions can make the problem worse if their conclusions are easier to read than their evidence is to verify. I would rather have three precise links and one unresolved question than a confident report that nobody has time to audit. ## Another agent can remove work, or add another queue Automated review can catch local defects, investigate a suspicious export or check a routine convention before a person arrives. That is useful preparation. It can also generate a second pile of work: findings to validate, false positives to dismiss, replies to interpret and repeated comments to reconcile. A quiet tool isn't necessarily effective, and a busy one isn't necessarily helping. GitHub's current [application card for Copilot agents](https://docs.github.com/en/copilot/responsible-use/code-review) explicitly discusses missed issues, false positives and inaccurate suggestions, and recommends supplementing automated review with human review. These are present documented limits, not a claim that current tools only inspect a few lines of a diff. I would assess whether a review tool reduces the human effort needed to reach a sound decision. That includes the effort spent checking the tool itself. Comment count is a poor substitute. The same applies to UI evidence. Browser automation can make a previously invisible interaction inspectable, but a screenshot doesn't verify every state. Helpful automation narrows the remaining question. It doesn't just add another green label. ## Control work in progress before asking for faster review If review capacity is the constraint, I would try limiting how many changes are actively seeking attention. Completing one reviewable slice before opening three more can improve the flow without changing the model. That limit should be a team decision, not a universal number. A routine dependency stream and a change to a shared identity contract don't impose the same load. Review ownership also matters. An agent can identify potential consumers, but that doesn't automatically identify who is accountable for accepting the change. A PR waiting for everyone can quietly become a PR owned by no one. I would make blocked states explicit: waiting for a domain decision, waiting for a missing integration check, or waiting for a reviewer with the relevant ownership. Those call for different actions. Re-running the same agent is unlikely to resolve all three. There is a useful stopping point for automation here. When the next step is an accountable decision, generating more implementation isn't progress on that decision. ## Measure the waiting and the rework I would keep measurements modest and specific: how long changes wait for first substantive review, how often a PR needs to be separated, what corrections arrive after apparent completion, and which review questions repeatedly lack evidence. These are proposed observations, not results I have measured for a comparative study. They need definitions and local interpretation. A shorter review can mean a better-prepared change, but it can also mean a rushed reviewer. The goal isn't to make every change slower. It is to stop borrowing confidence from an overloaded acceptance process. If the team cannot explain what it accepted, the implementation speed has hidden part of its cost. I still want the agent to finish quickly. I also want its finished work to be something another engineer can pick up without reconstructing an entire conversation. When I look at a queue of generated PRs, that is the question I would put ahead of the next throughput improvement: can the people responsible for this system still understand what is entering it? Where does review capacity constrain your AI-assisted workflow: understanding the change, checking the evidence, or sorting automated findings? I'd be interested in what actually reduced that burden, not just what produced more output. --- # The Agent Was Right. The Scope Still Changed. Canonical: https://ma-x.im/blog/ai-review-right-code-wrong-scope Author: Maksym Kuzmitskyi Published: Oct 23, 2026 # The Agent Was Right. The Scope Still Changed. A colleague started working on his ticket and discovered that its implementation was already there. He traced the files back to my pull request. I hadn't found a technical problem with the additional work. The awkward part was explaining how it had become part of my task. My ticket introduced a new abstraction, which I'll call a model. Another task covered integrating it at three selected usage sites. The older implementation served other consumers and needed to remain. The agent built the model and covered it with tests. Then it noticed that the model wasn't being used. The task description explained what it would eventually replace, and the agent identified the places where it could be connected. That was a reasonable suggestion. I accepted the argument and let it continue. The integration was good work. It also belonged to another ticket. This wasn't an agent secretly editing forbidden files. It asked, and I agreed. That makes the case more interesting than a story about automation ignoring instructions. Human agreement was present. What was missing was an explicit reconciliation between that agreement and the way the work had been divided. > The agent was right about what came next. That didn't establish that it belonged in this PR. ## Unused is not the same as unfinished A tested abstraction waiting for its integration task can look like incomplete engineering when viewed only through the current repository. The code suggests an obvious next step. The ticket boundary may say something different. That boundary isn't automatically sacred. Tasks can be split poorly. Combining implementation and integration may be the better decision. But it should be a deliberate change to the plan, with the affected people aware of it, not an accidental consequence of a convincing technical explanation. I wouldn't require product approval for every extracted helper. Engineers need room to make implementation decisions. The useful distinction is between supporting work necessary to satisfy the current acceptance criteria and work that delivers a separately planned behavior. An additional compatibility fix might be necessary for the requested change to function. Integrating a new model into consumers assigned to another task is a different decision. Both can be technically justified. Only one follows automatically from the current task's goal. Knowing the intended destination is not the same as owning the next step. This isn't unique to AI. A human engineer can make the same choice. But an agent can provide both the persuasive argument and the implementation. I need to examine the transition between those two, not only the quality of the result. ## I started making the origin of decisions visible My response was not another permanent instruction saying never do anything extra. That would make the agent less useful without resolving the ambiguity. Instead, I made a distinction in the task records: work grounded in requirements, documentation, repository instructions or acceptance criteria, versus additions originating in the agent's own engineering judgment. The latter should be presented as a proposal or inference, not quietly described as required work. Both I and the review agent can inspect that record. It gives us somewhere to look when a change is sensible but its relationship to the task is unclear. The important difference is between stating that a documented requirement calls for a change and stating that the agent recommends it because the current implementation appears incomplete. Those explanations deserve different review questions. Of course, the agent can misclassify its own reasoning. A documentation reference may describe a future direction rather than a current requirement. A record written by the implementer is an account to examine, not independent evidence that everything happened correctly. The reviewer needs the original task and relevant sources, not just the implementer's summary. It also needs to compare that account with the actual changes. Otherwise, two agents may agree because they inherited the same assumption. For substantial work, this record can preserve decisions, checks, open questions and work intentionally left outside the task. A tiny, clear change doesn't necessarily need another specification file. I've described the broader [task-to-PR workflow](/blog/agent-playbook-do-it-as-usual) elsewhere. Jira, Confluence, repository instructions, Git history and API documentation can be available through MCP integrations and other tools. Access helps only if the sources are current and their authority is understood. More context can also mean more convincing outdated instructions. I want the record to make disagreement easier to locate. I don't want an impressive document that makes disagreement harder. ## A good review needs several kinds of evidence My [personal PR-reviewer article](/blog/github-ai-pr-reviewer) focused on specific, checkable comments and visibility into what the tool inspected. That remains useful engineering attention. A removed export or disappearing permission check deserves investigation, not an unexplained warning. But a reviewer can correctly assess an implementation and still miss why that implementation is in the PR. Tests address particular behaviors under particular conditions. A local TypeScript check doesn't establish compatibility with a downstream consumer whose actual package contract differs. As I argued in [Green Checks Only Cover What You Checked](/blog/agent-playbook-green-checks), the question is what the check exercised, not merely whether it passed. Automation can change the object being reviewed too. My [scope-after-tools article](/blog/agent-playbook-scope-after-tools) uses a synthetic dependency update where a hook regenerates unrelated API artifacts. The generator succeeds; the resulting commit still needs inspection. That example is illustrative, not a second incident from the model-integration story. Review evidence also expires. A conclusion about one revision may no longer describe the next. [A Review Belongs to a Commit](/blog/agent-playbook-review-belongs-to-commit) examines revision tracking and guarded actions in personal tooling I've developed. Remembering a SHA helps identify what was inspected; it doesn't prove every finding remains valid or turn an earlier approval into authority over later changes. These aren't interchangeable checks. Code correctness, dependency compatibility, task inclusion, action permissions and the relevance of evidence each answer a different question. A passing test doesn't authorize extra work. An allowed directory doesn't define the business requirement. A second model's agreement doesn't establish independent verification. Nor should every small edit trigger an investigation across every connected repository. The validation needs to follow the affected contract and the decision being made. ## Three conversations around different parts of the problem During October, three groups contacted me after reading my articles. The useful connection was their different approaches to questions I was already trying to answer. In an early-October exchange with [Kai](https://kaicontext.com/), we discussed code relationships: imports, exports, calls, and how a finding might be challenged rather than immediately published. We also discussed limits of static analysis around runtime behavior and some React relationships. That is an account of the conversation, not a specification of today's product. I proposed an evaluation with expected defects recorded before running the reviewer, without revealing the answers in the PR descriptions. Cross-file regressions, contract changes, React behavior and false positives would make useful cases. That evaluation was discussed, not completed. The [DeepPattern](https://docs.deeppattern.ai/en/preview/overview) conversation approached the problem through verification: missed requirements, untested assumptions and whether the available evidence supports a conclusion. It also touched attribution. If a task succeeds, was the useful contribution a reusable skill, connected documentation, an existing test, or a human correction? Without a meaningful comparison, I can't isolate the cause. A preview was offered; I am not reporting evaluation results. [Agent Role Contracts](https://github.com/suirindo/agent-role-contracts), from Netsujo, addresses explicit declarations of roles, scope and handoffs. Its documentation makes an important boundary clear: internally consistent declarations do not grant runtime authority, authenticate a reviewer or establish business acceptance. A task requesting writes outside a declared scope can be rejected before execution. My model-integration example asks a different question: what if every edited file is permitted, but the work belongs to another task? These are complementary directions, not three products I've ranked. Code relationships, verification evidence and declared authority all matter. None alone decides whether a technically sensible addition belongs in this particular PR. ## Move the scope question earlier, without pretending it is solved By PR review, a disputed decision already has an implementation. The code can make the proposed extension look settled, even when the reason for including it remains uncertain. I would like to make that uncertainty visible before implementation: compare the proposed work with the original goal, identify additions, and decide which ones require coordination. Then compare the actual result with the accepted scope. That is a direction to investigate, not a semantic scope checker I've completed. Requirements can be ambiguous. Plans can omit necessary work. The reviewer can share the implementer's blind spot. A real change in understanding may justify revising the plan. I would evaluate a mechanism like this on cases where the right response differs. One task genuinely requires a supporting change. Another should produce a suggestion to do the integration separately. A third needs clarification because the requirement doesn't settle the choice. The expected outcome has to include stopping or separating work, not just producing more code. Otherwise, the evaluation rewards the very behavior it is supposed to examine. I also wouldn't ask an agent for an elaborate account of its internal thoughts. I need inspectable grounds: which requirement it relied on, what it inferred, what it changed, and what the checks actually support. My colleague didn't uncover bad code. He uncovered work that had crossed a task boundary while still looking like sensible engineering. I had participated in that decision. The part I want to improve is how such a decision becomes visible before someone else discovers their task inside my PR. If you work on agent review, verification or workflow controls, how do you distinguish a necessary supporting change from an expansion that needs a separate decision? What evidence would you need to trust that the agent did the requested job, rather than a well-implemented neighboring one? I'd like to compare approaches, including where they fail. --- # Independent Releases Still Need Compatible Neighbors Canonical: https://ma-x.im/blog/micro-frontends-vs-modular-monolith Author: Maksym Kuzmitskyi Published: Oct 22, 2026 The account team releases its new frontend. The shell stays on the previous version. Checkout was updated yesterday. That can be a healthy arrangement. It is what independent deployment is meant to permit. It is also a compatibility problem. Those versions need to work together, and users will discover the combinations we did not consider while each team tested its own application. The earlier [micro-frontends article](/blog/react-playbook-micro-frontends-org-chart) asks whether organizational independence justifies the split. Here I want to examine the technical consequence after that decision: what independence requires during ordinary releases and rollbacks. ## Separate three kinds of boundary A code boundary determines which module can import another. An ownership boundary determines who may change it. A deployment boundary determines which artifact can be released without rebuilding the others. They can align, but they do not have to. A modular frontend can have feature packages, explicit APIs, separate owners, and enforced import rules while producing one application build. That is the modular monolith in this comparison, not a claim that all code belongs in one undifferentiated folder. Micro-frontends add independently deployed application artifacts, composed through routes, runtime loading, frames, or another integration mechanism. Different composition methods have different costs. An iframe provides a stronger browser isolation boundary than mounting two modules in the same JavaScript runtime; it also changes interaction and integration constraints. I would name the intended composition before discussing the benefits. "Micro-frontends" is otherwise doing too much work in the sentence. ## One build moves compatibility work earlier In a modular monolith, one build checks the selected package versions together. A failing interface change can stop the release before production sees it. A coordinated rollback returns that tested set of frontend modules together. That does not guarantee correctness. Old tabs still exist, backend APIs still evolve, and integration tests can miss a workflow. But the frontend's internal version combination is more constrained. With independent artifacts, compatibility work remains necessary and moves partly into runtime and release policy. The shell needs to understand the remote's contract; the remote needs to tolerate the supported shell versions. The work did not disappear because CI pipelines became separate. We changed where it is paid. ## A remote needs a supported contract An illustrative mount contract might include a version, capabilities, lifecycle, and a constrained way to communicate: ```typescript type AccountModuleContract = { version: 2; mount: (container: HTMLElement, context: AccountContext) => () => void; capabilities: readonly ('profile' | 'notification-settings')[]; }; ``` The shape is not a recommended universal micro-frontend API. It shows the questions a boundary needs to answer: what does the host provide, what may the remote assume, how does it clean up, and how can the host detect incompatibility? Do not make shared context an unrestricted store containing every application's internals. That turns the mount API into a distributed import path with weaker verification. Capabilities can make additive evolution easier than assuming that every participant upgrades simultaneously. For breaking changes, define a support window and migration path. ## Release independence creates version combinations If several remotes each support two versions while the shell also supports two, the possible combinations multiply. It is rarely practical to test every theoretical combination equally. Constrain the supported matrix. Test each remote against the current shell and the declared compatibility window. Keep representative whole-product flows that cross the important boundaries. A remote's unit tests may correctly show that its save action works. They do not show that the shell refreshes the account menu, preserves navigation, and clears the right state after logout. Contract tests help, but a contract can be structurally valid and behaviorally wrong. The few shared workflows deserve integration tests owned by someone, not by an imaginary team named "the platform." ## Runtime manifests are release artifacts If the shell loads a remote entry through a mutable URL, the deployed composition can change without the shell's commit changing. Record the selected remote versions or immutable asset references. Keep enough history to reconstruct what users were served. Rollback should select a known-compatible composition, not point several URLs at yesterday and hope. Asset retention matters for clients that already loaded an old entry. Removing the old chunks immediately can break lazy navigation later, long after the initial page load succeeded. CDN cache lifetimes can also cause different users to load different manifest versions. This is manageable if the contracts support overlap. It is inconvenient if independent deployment silently assumes instantaneous global consistency. ## Sharing dependencies exchanges one cost for another Shipping separate dependencies can increase download size and produce multiple copies of libraries. Sharing them at runtime can reduce duplication, but introduces version negotiation and lifecycle constraints. React singletons deserve care when components and hooks interact across a shared runtime. A shared design-system library also has behavioral and styling contracts; two versions can differ in focus management or portal assumptions even when the buttons look similar. I would not force every dependency into a singleton merely to improve a bundle report. Nor would I accept uncontrolled duplication without measuring the user cost. Decide which shared dependencies are part of the platform contract, and verify both upgrades and rollbacks. For stronger isolation, route-level composition may be more straightforward than many independently loaded widgets sharing one screen. It depends on the product flow, not on which demo looked most flexible. ## Isolation needs failure behavior A remote can fail to load because of a network error, stale asset reference, or incompatible deployment. The shell still needs a useful route and a recoverable state. Distinguish an optional sidebar from checkout's payment step. One may show a fallback. The other may need to stop the workflow and preserve user input. An error boundary catches some rendering failures; it is not full isolation from CSS conflicts, shared global state, or security problems. Keep remote-loading timeouts, telemetry, retry rules, and fallback ownership explicit. A spinner with no deadline is not a graceful degradation strategy. The modular monolith has fewer runtime composition failure points, but its deployment can affect more features at once. Feature flags, staged releases, and modular tests can reduce that risk without creating separate runtime applications. ## Shared state is an authority question Identity, cart state, locale, and navigation often cross frontend boundaries. Decide who owns each truth. An event that says "cart changed" can prompt other applications to read the authoritative value. An event carrying a partial cart snapshot can accidentally create another source of truth with its own freshness problems. An event bus should have typed contracts, lifecycle rules, and unsubscribe behavior. It should not become an excuse for every remote to discover undocumented events by reading the others' source. Authorization must remain enforced at the backend. A remote being mounted by an authenticated shell does not give its API calls permanent authority. These rules apply inside a modular monolith too. Independent deployment makes violations harder to repair together, which raises the value of keeping the shared surface small. ## Try modularity before distributing a coordination problem If the main pain is accidental imports, unclear ownership, or slow whole-repo CI, a modular build with boundary rules and affected-project checks may address it directly. If teams genuinely need separate release schedules, existing applications cannot reasonably be merged, or one part must evolve under substantially different constraints, runtime composition may justify its cost. I would trial the split at a boundary already understandable in the product, with a specific blocked workflow the trial is meant to improve. Measure release lead time and integration effort, then account for the platform work needed to keep it reliable. A module boundary that cannot be described cleanly inside one build usually does not become clearer when a network load is inserted between its parts. ## Independence has a maintenance agreement The decision is not simply one deployment versus many. It is how much coordination we want to perform before release and how much compatibility we are prepared to maintain afterward. I would choose a modular monolith when coordinated artifacts are affordable and the team's main need is better boundaries. I would choose micro-frontends when independent delivery solves a demonstrated constraint and the teams can own the resulting compatibility work. Either arrangement can be maintained well. Neither relieves us of agreeing what a neighboring module may do while we are deploying something else. If your teams already release independently, what happens when one of them rolls back? I'd be interested in the supported combination, because that answer says more about the architecture than the number of repositories. --- # Who Checks the Tests an AI Agent Writes? Canonical: https://ma-x.im/blog/ai-generated-tests-independent-oracle Author: Maksym Kuzmitskyi Published: Oct 21, 2026 # Who Checks the Tests an AI Agent Writes? An agent writes a function, adds tests, runs them, and reports success. The implementation and the tests agree. What established that they agreed on the right behavior? This is the part of AI-generated testing I want to examine before counting new assertions. A test can be perfectly executable, exercise the relevant branch, and confirm the same mistaken interpretation that produced the code. Humans do this too. The additional concern with an agent is how conveniently implementation, test cases, fixtures and the final explanation can be produced from one interpretation. They look like several pieces of evidence. They may have only one underlying assumption. I don't want fewer generated tests. I want a clearer answer to where their expected results came from. ## A passing test for the wrong rule Consider a fictional checkout policy. Free shipping applies when the merchandise subtotal **after discounts** is at least 5,000 cents. Tax and shipping charges do not contribute. The examples below assume valid, nonnegative integer inputs, with discounts no greater than the merchandise subtotal; input validation is a separate concern. This is an illustrative example, not an incident from a client project. An implementation and its test might look like this: ```typescript import assert from 'node:assert/strict'; type ShippingQuote = { merchandiseCents: number; discountCents: number; }; function qualifiesForFreeShipping(quote: ShippingQuote): boolean { return quote.merchandiseCents >= 5_000; } assert.equal( qualifiesForFreeShipping({ merchandiseCents: 6_000, discountCents: 1_500 }), true, ); ``` The test passes. The discounted subtotal is 4,500 cents. Under the stated policy, that order does not qualify. The test has not failed to execute the implementation. It has asserted the wrong answer. A coverage report can show that the function ran without noticing that the expected value contradicts the requirement. Adding more examples above the undiscounted threshold won't necessarily help. Nor will renaming the test to sound more specific. The missing ingredient is an expected result derived from the policy, rather than an observation of what the function currently returns. That expected result is the test oracle: the basis for deciding whether the observed behavior is correct. It doesn't have to be a separate program or an expensive formal specification. Sometimes it is one arithmetic calculation and a sentence someone has actually agreed on. ## Establish the expectation before polishing the implementation For this policy, I would start with a few examples whose answers can be worked out without consulting the function: ```typescript assert.equal( qualifiesForFreeShipping({ merchandiseCents: 6_000, discountCents: 1_500 }), false, ); assert.equal( qualifiesForFreeShipping({ merchandiseCents: 5_000, discountCents: 0 }), true, ); assert.equal( qualifiesForFreeShipping({ merchandiseCents: 4_999, discountCents: 0 }), false, ); ``` The first case disagrees with the original test. That disagreement is useful. It makes the interpretation visible instead of burying it beneath a successful run. The implementation can then follow the policy: ```typescript function qualifiesForFreeShipping(quote: ShippingQuote): boolean { const discountedMerchandiseCents = quote.merchandiseCents - quote.discountCents; return discountedMerchandiseCents >= 5_000; } ``` This is not a complete checkout test suite. The cases establish the particular discount and threshold behavior under discussion. They don't establish currency conversion, tax treatment elsewhere, coupon validity or production integration. I would ask the agent to identify the source of each important expectation. An acceptance criterion, an approved example, a documented contract or a trusted reference can justify it. The current implementation can tell us what happens, but not always what should happen. If the requirement doesn't settle whether the threshold applies before or after discounts, generating an assertion doesn't settle it either. The correct next step is a question. An executable guess is still a guess. ## A second agent needs a different starting point It is tempting to solve this by assigning test generation to another agent. That can help, but a separate role is not automatically an independent basis for judgment. If the second agent receives the implementation and a persuasive explanation of why it is correct, it may simply encode that explanation as tests. Changing the model doesn't guarantee a different interpretation of an ambiguous requirement. For consequential behavior, I would give the test reviewer the original requirement and ask it to derive concrete outcomes before showing it the implementation. Then compare the cases with the code and existing tests. This reduces one source of anchoring. It doesn't prove independence or eliminate shared mistakes. Both reviewers may still misunderstand the requirement, which is why the expected outcomes need to remain inspectable by a person. In [Green Checks Only Cover What You Checked](/blog/agent-playbook-green-checks), the concern was the reach of evidence across an integration boundary. Here the boundary is earlier: whether the assertion itself expresses the intended behavior. An integration test can have a wrong expectation too. ## Check that the test can disagree A useful test should fail for a relevant wrong implementation. I would deliberately check that property, rather than infer it from a green run. In this example, ignoring the discount should fail the first requirement-derived case. Changing the threshold comparison from inclusive to exclusive should fail the exact-boundary case. Mutation testing automates variations of this idea by introducing changes into the code and checking which tests detect them. Tools such as [Stryker](https://stryker-mutator.io/docs/) make that practical without inventing a mutation framework for each project. A detected mutation establishes sensitivity to that change. It doesn't establish the truth of the original requirement. An incorrect expected value can still kill mutants; a surviving mutant can reflect equivalent behavior rather than a meaningful defect. Mutation scores need interpretation, not ceremonial targets. Property-based tests add another useful angle. Under our stated policy, increasing the discount while holding the merchandise subtotal fixed must not turn an ineligible order into an eligible one. This describes a relationship across inputs instead of one fixed example. But a function that always returns false also satisfies that relationship. Properties need enough independent constraints to rule out plausible wrong implementations. They complement concrete examples; they don't manufacture a business rule from nothing. ## Fixtures can make the same mistake less visible I would also inspect how test data is created. A fixture built by calling the implementation under test can quietly recycle the result it is supposed to check. A broad mock can remove the behavior that actually needs verification. This doesn't make builders or mocks inherently bad. A builder can provide ordinary input data while leaving the important expected result explicit. A mock can isolate a collaborator without deciding the business outcome for the test. The question is what the helper owns. Does it simplify setup, or does it calculate the answer through the same logic the assertion claims to validate? Duplicating the production algorithm inside the test is not necessarily a better oracle. It can reproduce the same defect in another file. For a small example, independently calculated values may be easier to audit. For complex behavior, a reviewed reference implementation, contract examples or another representation may be appropriate. There isn't one universally independent source. The point is to identify the dependence instead of mistaking a second file for a second line of reasoning. ## Review the test change, not just its result When an agent fixes a failing suite, I want to know whether it changed the behavior or changed what the suite accepts. Sometimes the expected result is genuinely obsolete because the requirement changed. Sometimes the implementation is wrong. Sometimes the test was wrong from the beginning. All three can end with green CI. They are not the same engineering decision. A snapshot update deserves the same question. Accepting a new snapshot records an output; it doesn't establish that the user should see it. Removing an assertion or relaxing a matcher may be justified, but the justification needs more than getting the run to pass. For a bug fix, I would prefer the regression test to demonstrate the reported failure on the relevant prior implementation, then pass with the correction. It also needs to fail for the intended reason, not because an unrelated dependency or import is broken. For new behavior, a failing test against the previous implementation is expected. What matters is that its assertion comes from the requested behavior, not from whichever output the new implementation happened to produce. ## Keep generation useful I like the prospect of an agent handling repetitive setup, exploring input combinations and proposing edge cases. Those are useful contributions even when the final expectation still needs human judgment. What I don't want is to promote the existence of generated tests into evidence that the requirement has been independently checked. More assertions can make a mistaken assumption look thoroughly documented. The shipping example is small enough that the disagreement fits in one subtraction. Real systems hide the same question behind fixtures, collaborators and years of existing behavior. I would still start by asking who decided the answer and what supports it. If you use agents to write tests, how do you keep expected outcomes independent of the implementation? I'd be interested in the checks that expose shared assumptions, especially when both the code and its tests look completely reasonable. --- # TanStack Start or Next.js: Follow One Mutation Through Production Canonical: https://ma-x.im/blog/tanstack-start-vs-nextjs-production Author: Maksym Kuzmitskyi Published: Oct 20, 2026 A dashboard loads correctly in both frameworks. That part of the comparison is already fairly well understood. Now change an order, switch accounts, keep an old tab open through a deployment, and make the request through the production CDN. That is the comparison I would spend time on. The first screen tells us whether the framework can render. The later operations tell us whether the team understands the state and deployment model it has chosen. The earlier [TanStack Start article](/blog/react-playbook-ssr-tanstack-start) introduces SSR and the server boundary. This one examines an authenticated, interaction-heavy application after that introduction. It is not a performance benchmark or a claim of personal production results for either framework. **Version scope:** package metadata and official documentation were checked on October 8, 2026: `next` 16.4.0 and `@tanstack/react-start` 1.168.60. Features and host integrations below should be checked again against the project's pinned versions before implementation. This site itself still uses its existing Next.js version; writing the comparison does not upgrade it. ## Compare a workflow, not an API count Use one representative flow: load a private order, edit its delivery option, save, return to the list, and sign out. It exercises identity, server authorization, validation, durable state, multiple cached views, URL state, and browser cleanup. Add an old-client submission after a rolling deployment, and it also exercises release compatibility. I would build that slice with the deployment target intended for production. A development server is too forgiving a witness for cache behavior and runtime bindings. The result need not be a second full application. It needs enough ordinary inconvenience to reveal which model the team can explain. ## The center of gravity is different Next.js App Router organizes work around route segments, layouts, Server Components, client boundaries, and its rendering and caching model. That is useful when much of the route can be composed on the server and the team wants the framework to own those conventions. TanStack Start builds around TanStack Router, loaders, server functions, and the associated client navigation model. That is useful when typed route/search state and client-rich workflows are already central to the application. Neither description is an exclusive capability boundary. Start's current documentation also describes Server Components; I would not use "Start cannot do RSC" as a timeless reason to choose Next. Nor does a Next.js application forbid TanStack Query or carefully designed client state. The question is which default model makes the particular workflow easier for this team to reason about, and which extensions create a second overlapping model. ## Server functions still need an API boundary In either system, a function that runs on the server can feel like a local call from frontend code. That convenience does not make the request trusted. Validate input, authenticate the caller, check access to the specific order, and enforce idempotency where repeated writes matter. A protected page or route guard improves navigation; it does not replace checks in the separately callable mutation endpoint. For Start, the current [server-function documentation](https://tanstack.com/start/latest/docs/framework/react/guide/server-functions) describes compilation to client RPC stubs, validation, middleware, and same-origin protections. Next's Server Functions also need explicit authorization in the data path. I would test both flows by calling the endpoint while signed out and as another account. The implementation syntax differs. The rejected unauthorized write should not. Keep external APIs separate from framework-private RPC assumptions. Mobile clients and third-party integrations need a deliberately supported contract, not an incidental generated function identifier. ## A successful mutation can leave several stale views After saving the order, which copy changes? In a Start application using Query, there may be a query cache, router loader data, server-side data caches, and a CDN response. Invalidating one does not automatically invalidate every other layer. In a Next application, server data and route output can have their own cache behavior, while the browser retains navigation state and perhaps a separate Query cache. Adding Query is reasonable when it serves a clear purpose. Using it merely because it is familiar can create two owners for the same remote data. I would write down the expected invalidation path before selecting helper functions: ```text save delivery option -> commit the order change -> update or invalidate the detail view -> refresh affected list representations -> preserve unrelated local form state ``` For Next 16, be explicit about whether the application uses Cache Components or the previous caching model. Advice copied from a different major version or mode may describe different defaults. The [current caching guide](https://nextjs.org/docs/app/guides/caching) distinguishes those paths. I would not choose a framework because its cache seems invisible. Invisible is convenient until two views disagree. ## Request isolation matters more than friendly types On the server, create user-specific state in request scope. A process-wide Query client or mutable user store can accidentally carry account data between requests if used incorrectly. Test two accounts concurrently through SSR and the real CDN. Inspect returned HTML and serialized data, then switch accounts in the same browser. Sign-out should remove private client cache state as well as the cookie. The [Start production checklist](https://tanstack.com/start/latest/docs/framework/react/guide/production-checklist) explicitly addresses these checks. They are useful for either framework. A type-safe cache key still needs the correct identity dimensions. If two tenants share the same key, the compiler can happily confirm that the wrong tenant's response has the expected shape. ## Hosting is part of the choice Start's [hosting documentation](https://tanstack.com/start/latest/docs/framework/react/guide/hosting) describes provider-specific integrations and build outputs. Next's [self-hosting documentation](https://nextjs.org/docs/app/guides/self-hosting) describes multi-instance caches, deployment identifiers, Server Function encryption keys, and streaming considerations. Both require attention outside the route code. Verify the adapter, runtime APIs, environment-variable timing, asset paths, and proxy buffering. A container deployment and an edge-worker deployment are not interchangeable merely because both serve HTTP. For Next across multiple instances, plan shared cache behavior and invalidation coordination where needed. For Start, verify the selected server output and host bindings rather than assuming the development runtime is the production runtime. Do not judge self-hosting by whether `npm start` returned a page once. Judge whether the intended features behave correctly through the intended infrastructure. ## Keep an old browser alive during the test Server-function identifiers and client assets belong to a build. A tab can retain an older build while the server deploys a newer one. Next documents deployment skew protections, including deployment identifiers; their exact behavior matters for self-hosting. Start also generates server-function identities, so test old-client calls against the actual deployed output rather than assuming type sharing guarantees runtime compatibility. Retain required immutable assets. Decide whether an incompatible client should reload, and what happens to unsaved edits when it does. A full reload is a recovery mechanism, not a product-neutral event. This check can matter more to an internal editing application than the difference in a clean first-load demo. ## Include maintenance in the experiment Ask another engineer to change the saved field, add a validation failure, and diagnose a controlled stale-view bug in each slice. How much behavior can they find locally? Which conventions are familiar to the team? Are the deployment docs and libraries they depend on compatible with the pinned versions? Can they explain the cache lifecycle without relying on the person who built the example? I would prefer this evidence to a general claim that one framework is simpler. Simplicity depends on the workflow and on what the team already understands. For server-composed routes and a team committed to the App Router model, Next is a reasonable choice. For router-driven, interaction-heavy work with a strong TanStack investment, Start is a reasonable choice. Either can be made awkward by layering on another system without deciding who owns what. The framework I would choose is the one whose unhappy production path the team can describe clearly. A nice dashboard matters too. Fortunately, both can make one. If you're weighing the two, bring one mutation and the hosting target rather than a feature matrix. I'd be interested in where the ownership of data becomes unclear in that concrete path. --- # Freelance Architect or Agency: Who Keeps the Decisions? Canonical: https://ma-x.im/blog/freelance-architect-vs-agency Author: Maksym Kuzmitskyi Published: Oct 18, 2026 A team asks for an architect, but the work waiting for them is a backlog of implementation tickets. Another asks an agency to build a feature, while every consequential decision still needs approval from an internal team that has no time to review it. Neither arrangement is necessarily wrong. They are simply describing a different purchase from the one in the proposal. When choosing between an independent engineer and an agency, I would spend less time comparing job titles and more time describing who owns the decisions while the work is happening. That tends to matter after the first few meetings, when everyone has access and the easy questions have been answered. This is a way to evaluate an engagement, not a claim about particular suppliers, prices, or a universal ranking of one model over the other. ## First separate diagnosis from capacity Sometimes the team knows what it needs to build and lacks enough delivery capacity. Sometimes it has plenty of developers but cannot explain why every change crosses five modules. Sometimes a deadline exposes both problems at once. An architecture-focused independent engagement can make sense when the central work is concentrated judgement: inspect a system, identify boundaries, work with the internal team, and make a few consequential changes. An agency can make sense when the work needs a coordinated mix of implementation, testing, design, delivery management, and continuity across several people. Those are tendencies, not guarantees. An independent engineer may deliver a complete feature; an agency may provide one specialist. The actual assigned people and operating agreement matter more than the supplier category. I would write the first outcome in plain terms. "Reduce the number of modules needed to change policy validation" is more testable than "improve architecture." "Own delivery of this workflow through acceptance and handover" is clearer than "provide a frontend team." ## Responsibility needs corresponding authority If an external architect is responsible for quality but cannot change boundaries, influence sequencing, or obtain review decisions, the responsibility is mostly ceremonial. The opposite arrangement is also uncomfortable: an external team makes choices that the internal owners must maintain, without involving them until handover. For decisions with lasting consequences, agree who proposes, who approves, and who maintains. This does not need an elaborate governance document. A small record can be enough: ```text Decision: separate payment validation from page orchestration Proposed by: external engineer Approved by: internal payments owner Maintained by: payments team Evidence: two representative flows and regression tests Fallback: keep the old adapter during migration ``` The example is hypothetical. Its useful property is that someone still owns the result after the external person's last invoice. ## Review availability limits delivery Adding implementation capacity does not increase the internal team's review or decision capacity automatically. If an agency submits ten pull requests a week and the internal team can carefully review three, work accumulates at the boundary. More developers may increase that queue rather than shorten the release. An independent engineer working on a difficult architectural change can encounter the same problem. One large refactor waiting for a busy owner is not inherently easier to absorb than several ordinary features. I would include reviewer availability in the plan: expected turnaround, who can make product decisions, when integration questions get resolved, and how work is split into changes the team can evaluate. This is particularly important when acceptance depends on integrations the supplier cannot access or change. A delivery date that assumes immediate internal answers is a date with an unstated dependency. ## Prefer demonstrated uncertainty over polished certainty Before a substantial commitment, a small paid diagnostic or bounded delivery slice can reveal the working relationship. Choose something representative rather than conveniently isolated: a flow with an awkward API contract, an existing shared component, a realistic test requirement, and an internal reviewer. The useful output includes what was discovered, what changed, what remains uncertain, and which assumptions affect the next estimate. An apparently slower answer that identifies a dependency may be worth more than a confident schedule built without examining it. I would also distinguish an estimate for implementation from the time waiting on decisions, environments, and approvals. They belong in the same delivery discussion, but they are not the same kind of work. ## Continuity is a mechanism, not a headcount An independent engineer has a clear availability risk: one person may be absent or the engagement may end. An agency may offer replacement capacity. That does not guarantee the replacement already understands the system. A named specialist can leave; an account can be reassigned; context still has to transfer. Ask how continuity actually works. Which people have read the critical code? Where are decisions stored? Can another engineer deploy, reproduce an issue, and explain the outstanding risks without a private conversation with the original author? For both models, I would favor shared context in the client's systems, small decisions recorded near the code, and at least one internal engineer involved in consequential changes. Continuity becomes less fragile when it is exercised during delivery rather than promised in a final document. ## The work should remain inside the client's control Source repositories, deployment accounts, domains, package ownership, and design assets need deliberate ownership. An engagement can finish with working software and still leave the client dependent on credentials or infrastructure controlled by the supplier. Use client-controlled repositories and appropriately scoped access where possible. Name any exception and the transfer procedure before it becomes necessary. The same applies to automation. If a supplier uses AI-assisted tooling, clarify permitted data handling, review expectations, generated-code responsibility, and what configuration belongs to the client. Faster implementation does not change who must verify the result or who may access private source and customer information. I would not equate a supplier's preferred toolchain with a requirement for the client to adopt it permanently. ## Avoid a handover that only describes files A directory tour helps. It does not answer why a boundary exists, which alternatives were rejected, or what would break if the API changes. A useful handover includes the important decisions, reproducible checks, release and rollback steps, known limitations, and the first likely maintenance changes. Keep it proportionate; six understandable notes are better than a large template nobody can navigate. Have an internal engineer perform one change and one deployment before the engagement ends. The external person can assist, but should not quietly do every step that the exercise is intended to transfer. That is a more convincing ownership test than asking whether everyone has read the documentation. ## Architecture needs an implementation consequence If the engagement is mostly architecture, the deliverables should still meet the code at some point. A dependency diagram can identify a problem. A bounded migration, representative slice, or working contract test shows whether the proposed boundary is usable. Without that contact, the design may be elegant while the team's practical cost remains unknown. Conversely, measuring only shipped tickets can discourage the diagnostic work needed to prevent the next expensive change. Agree which technical outcomes matter: fewer coupled changes, faster verification, clearer ownership, or an integration that no longer needs several teams to coordinate every edit. I would avoid treating diagrams and implementation as competing definitions of productive work. They should inform each other, with evidence appropriate to the risk. ## Choose the arrangement that can leave well For a focused diagnosis with a capable internal team, I would often consider an independent senior engineer or architect. For a delivery stream needing several disciplines and coordinated capacity, I would consider an agency with named people and explicit ownership. If the organization has nobody available to own decisions, review changes, or maintain the result, neither category solves that absence by itself. The operating model needs attention before more external capacity arrives. The end of the engagement is a useful design constraint from the beginning. What should the internal team be able to do without asking the supplier? Which promises must remain true when a person changes? I would rather make those questions slightly awkward during selection than leave them until the final week. By then the software may be complete, and the ownership may still be under construction. If you're deciding between these arrangements, tell me which decision or delivery responsibility is currently unowned. That detail makes the comparison much more useful than the labels on the proposals. --- # What a Skill Changed, and What It Didn't Canonical: https://ma-x.im/blog/agent-playbook-what-a-skill-changed Author: Maksym Kuzmitskyi Published: Oct 17, 2026 A task went well with a reusable skill enabled. It also had clear requirements, repository instructions, connected tools, a useful test, and an engineer who corrected an early assumption. Which part made the result better? I would not answer that from the final diff alone. The diff can establish what changed. It cannot, by itself, tell us which part of the workflow caused the change to be correct. I participate in evaluating reusable agent skills and refining how they are applied to ordinary engineering work. The interesting question is not whether the process produced a polished artifact. It is what observable contribution the skill made, what it cost, and what remains unknown. This article describes an evaluation approach. It does not report internal programme results, measurements, or a controlled comparison that has established a productivity gain. ## A skill is one input among several A reusable skill packages instructions or a workflow. It may help discover context, plan a change, validate it, or handle review. It is not a separately trained model or an autonomous employee. Its contribution depends on what was already present. If repository rules already require a focused check immediately after an edit, a skill that repeats that instruction may add consistency, but it is not evidence that the check originated with the skill. If a connected tool supplies current requirements, the tool can explain why the agent avoided a stale assumption. The engineer's domain knowledge matters too. A person may notice that two services disagree, narrow the investigation, or reject an obsolete proposal. Leaving that correction out makes the skill look more independent than it was. I want the record to include those existing controls. Otherwise we are comparing a named framework with an imaginary workflow that has no useful practices of its own. ## Observe behavior before assigning credit The earlier [evaluation article](/blog/agent-playbook-evaluation-is-the-missing-loop) discusses what to measure. Here the narrower question is which explanation the observations support. Use a deliberately illustrative record, not a real reporting form or an internal task: ```text Task: update a client without changing its callers Observed behavior: agent checked a contract before editing Existing control: repository instructions also require that check Correction: engineer identified one stale source Verified outcome: retained change passes the relevant gates Skill contribution: may have reinforced discovery; attribution unresolved Residual risk: deployment compatibility needs a separate decision ``` The conclusion is modest because the evidence is modest. That is not a failed evaluation. It is an evaluation that did not replace uncertainty with enthusiasm. If the skill visibly introduced a previously missing check, say so. If the task does not distinguish its effect from existing instructions, say that instead. ## A useful outcome is not always delivered code A cross-repository investigation can end with an obsolete PR being closed. An architecture task can produce a proposal with explicit assumptions for discussion. A session-handoff change can produce a clearer continuation scheme. Those outcomes have value. They are not interchangeable with a merged feature, an approved architecture, or guaranteed reproducibility. Describe the actual artifact and its decision state. A reviewable proposal is ready to evaluate; it is not production rollout. A documented handoff reduces reliance on conversation history; it does not establish identical behavior across models and people. In the supplied generalized experiences behind this series, recovery and refinement are part of the work. I would not remove the initial incomplete diagnosis simply because the final action was sensible. The sequence explains what the process learned. A cleaned-up success story explains much less. ## Separate work from overhead without pretending overhead is worthless Implementation, framework setup, planning, repeated approvals, and reporting take different kinds of effort. A specification can prevent an expensive mistake. It can also repeat a small task's already clear requirements. Reporting can support honest evaluation. It can also consume time that should be counted rather than hidden. Keep normal engineering effort, framework overhead, and reporting effort distinguishable. Do not turn them into a single impressive number before understanding what each category contains. The classification will sometimes require judgement. A discussion that clarifies an ambiguous requirement is engineering work even if a framework prompted it. A template completed only to satisfy the framework is a different contribution. I would make that distinction visible rather than use it to prejudge whether the framework is good or bad. ## Tiny tasks do not need a retrospective specification For a small, clear change, the ticket and nearby contract may already be an adequate written requirement. A long specification can create another artifact to review without resolving a real uncertainty. For ambiguous, risky, or multi-session work, a plan and checkpoints before implementation can be useful. They capture assumptions while there is still time for them to guide the work. Do not write a specification afterwards and present it as evidence that the task followed specification-driven development. A retrospective note can explain the result, but it did not shape decisions that happened before it existed. This is a simple chronology rule. It prevents polished documentation from making the process look more formal than it actually was. ## Not using a skill can be the proportionate choice An evaluation can tempt people to apply every available skill to every task so the record has plenty to discuss. That changes the thing being evaluated. We are no longer observing useful selection; we are imposing ceremony for evidence collection. Use a skill when it helps the task's current stage and risk. Record when a tiny or non-coding task offers limited evidence. Do not manufacture a repository-wide plan or another planning file after the fact to fill a reporting category. A good workflow should be able to say "not needed here" without that becoming an admission that the whole framework failed. ## Repeated success still has confounders Several tasks going well can suggest a useful pattern. It does not automatically establish a causal productivity improvement. Tasks differ in difficulty, familiarity, requirements, code quality, tools, models, and human involvement. An experienced engineer may become better at the domain during the same period the skills are introduced. Without an appropriate baseline and comparison, avoid percentages, cost savings, or defect-rate reductions. Task counts and green checks are observations, not impact metrics by themselves. Qualitative findings remain worthwhile: a missing boundary became explicit, a handoff had a clearer source of current decisions, or the process detected an unrelated generated change before review. Name them as observations. They do not need a fabricated multiplier to be interesting. ## Keep the evaluation record separate from public storytelling An internal assessment may need task-level evidence, correction history, and reporting detail. A public article does not need to reproduce those artifacts. Use generalized, explicitly labelled composite examples. Remove internal identities, programme details, source snippets, links, counts and model policy. Do not attach an employer's name to an anonymized case merely because the employment record is already public. Even a collection of individually harmless details can make an episode identifiable. Preserve the engineering mechanism while changing or omitting unnecessary specifics. The public claim should be something the available evidence can support without inviting the reader to inspect a closed system. "I evaluated and refined workflows" is a different claim from "this programme improved company delivery." ## Feed the result back into the right layer When an error repeats, decide which control should change. An outdated repository convention belongs in repository context. A general validation habit may belong in a reusable workflow. A missing permission boundary may require tool access to change, not another paragraph in the prompt. If the failure came from stale task evidence, repair the handoff or current-state check. If the skill added unnecessary steps, narrow when it applies. If the result remains ambiguous, keep the ambiguity in the record rather than forcing a favorable or unfavorable rating. This is where evaluation becomes engineering work. The record is not the final product; the corrected operating arrangement is. > Useful attribution is specific enough to change the next task and modest enough not to invent a cause. ## A smaller conclusion can be more reusable I do not need every evaluation to end with a winner. I need to know which practice helped under which conditions, what required correction, and what the evidence could not distinguish. That lets the next task inherit a more useful check or a simpler process instead of a larger claim. The five articles in this wave share that approach. Context needs freshness. Green checks need scope. Tool output needs inspection. Reviews need a revision. Skills need honest attribution. None of those mechanisms removes the need for engineering judgement; they give it better material to work with. That is the agentic engineering I want to describe: an environment that can learn from ordinary failures without pretending the agent was correct all along. If a skill helped your work, what changed in the actual sequence of decisions? I'd be interested in that observation, including what your existing tools or judgement contributed alongside it. --- # The Backup Exists. The Restore Still Needs Work. Canonical: https://ma-x.im/blog/full-stack-backups-and-recovery Author: Maksym Kuzmitskyi Published: Oct 16, 2026 The database restores successfully to 10:42. The payment provider has transactions through 11:07. Object storage contains invoices created after the restore point. The queue still holds jobs referring to orders the restored database does not remember. The backup worked. We have not yet recovered the application. I think this is the useful distinction to make before an incident. Recovery is not one storage operation. It is deciding which facts remain authoritative after different parts of the system have moved to different points in time. ## Availability and recovery solve different failures A replica can keep the service available after one machine fails. It may also faithfully replicate the accidental deletion we are trying to undo. A backup preserves another state. Point-in-time recovery can reconstruct a database using a base backup and subsequent transaction-log records, within the retained recovery window. Its value depends on those records being available and the restore procedure actually working. Neither mechanism automatically restores object storage, credentials, queue state, or external services. I would define the failure being covered: infrastructure loss, accidental deletion, corruption, an incompatible migration, or compromised access. A design that handles the first can still be inadequate for the others. ## Put a business meaning behind RPO and RTO Recovery point objective describes acceptable data loss. Recovery time objective describes acceptable time to restore the required service. "Fifteen minutes" sounds specific. It still needs a meaning. Can fifteen minutes of submitted support forms disappear? Of inventory reservations? Of charged orders? Those are different promises. Some operations need reconciliation from another authoritative system even when the database recovery point is acceptable. A payment provider may tell us about a charge the restored database lost. We need a stable reference linking it back to the business operation. For recovery time, include more than restoring bytes: provisioning, access approval, decryption keys, application startup, verification, reconciliation, traffic switching, and safe resumption of workers. I would measure the whole exercise. A ten-minute restore inside a two-hour recovery procedure is not a ten-minute RTO. ## Restore beside production, not blindly over it For a logical data mistake, restoring an isolated instance gives us room to inspect the recovered state and compare it with current production. We may be able to repair a specific set of rows instead of rewinding everything. Keep the recovery environment unable to send real emails, charge payments, consume production queues, or execute live webhooks. A copied database can contain pending work that application startup eagerly resumes. Use controlled configuration and network access, not merely a promise that nobody will click the dangerous button. Preserve the original state as evidence while deciding which changes to apply. Sometimes a full cutover is necessary. Even then, the new instance should be verified before traffic moves, with a deliberate plan for connections, endpoints, and old application instances. DNS changes have the [overlap behavior](/blog/full-stack-domains-and-proxies) discussed earlier. Applications may also cache connection settings or continue using old pools. Changing a database endpoint is a release step, not a universal disconnect command. ## Match data with code and configuration A database restored to yesterday may have yesterday's schema. Today's application may require a column that did not exist then. Record the schema migration state alongside artifact and configuration revisions. Retain deployable artifacts, not just source code that could theoretically be rebuilt with today's package registry. An [expand/contract migration](/blog/full-stack-zero-downtime-migrations) gives recovery more options, but it does not remove the need to choose a compatible application version. Running every pending migration automatically against the restored instance may recreate the destructive change we were trying to investigate. Secrets matter too. A backup encrypted with an unavailable key is not useful. A restored application with revoked credentials cannot necessarily reach its dependencies. Back up and test the recovery of access paths without scattering secret values through documents or logs. ## External effects do not rewind with the database Consider an order that was paid at 10:55 and lost from a database restored to 10:42. Asking the customer to retry can charge them again unless the payment operation has a durable, stable identity. Reconcile against the provider using idempotency keys, merchant references, and the provider's authoritative transaction state. Do not infer a refund or charge from the absence of a local row alone. Email is another external effect. A replayed confirmation job may send a second message. An invoice number may already have been issued. A shipment may already be in transit. The recovery procedure should describe those consequences and the systems that settle them. We cannot restore the world to match a snapshot. We can reconstruct our records so they agree with the world that continued operating. This is where the identity choices from the [API](/blog/full-stack-api-contracts) and [queue](/blog/full-stack-background-jobs) articles become more than implementation conveniences. ## Queues and caches need a recovery policy A restored outbox may contain events already published before the incident. A current queue may contain messages for records absent from the recovered database. Pause consumers while reconciling. Decide which messages to preserve, replay, quarantine, or discard. Idempotent consumers reduce the cost of duplicates, but they still need a coherent business state to operate on. Do not delete the queue simply to make its depth look tidy. It may contain the only remaining record of accepted work. Redis also needs role-specific handling. Rebuild a disposable product cache from the recovered source. For sessions, consider whether invalidating them is safer than restoring older authorization state. For locks or scheduler metadata, old values may be actively misleading. "Restore every dependency" is not always the right instruction. Some state should be restored, some reconciled, and some deliberately recreated. ## Verify meaning, not only row counts A database that starts and contains the expected number of rows is encouraging. It does not prove the checkout workflow is usable. Check relationships, critical constraints, recent business operations, object references, account permissions, and one controlled end-to-end flow. Compare representative records with external authoritative systems where necessary. Keep enough telemetry to tell when corrupted or missing data first appeared. Otherwise choosing a restore point becomes a sequence of guesses, each followed by another expensive restore. Data integrity checks and recovery logs should avoid publishing private customer content. The people conducting a recovery need controlled access, not an unrestricted data export pasted into the incident channel. ## Test the access path that an incident will use A recovery exercise run by an administrator with every permission can conceal missing privileges in the actual emergency role. Test who can start the restore, decrypt it, deploy compatible code, change routing, and release the isolation controls. For compromise scenarios, consider independent backup protection: restricted deletion, retention controls, and appropriate account or region separation. If the same credential can destroy production and every backup, the copies share a rather important failure mode. There is no universal arrangement that makes all of this free. The choices should reflect the actual data, recovery promise, and threat model. Document who makes the cutover decision and who handles reconciliation. That is operational ownership, not an excuse to collect an impressive runbook nobody has tried. ## A useful drill has an inconvenient detail Try restoring with an old schema, an unavailable primary region, a rotated credential, or a job already delivered once. Choose one complication rather than pretending the exercise must reproduce every disaster at once. Measure the result, record the steps that required undocumented knowledge, and repair those gaps. A failed rehearsal is useful when it changes the recovery path before the real incident. > A backup preserves data. A rehearsed recovery preserves the ability to use it safely. That is where I would end this field guide. The database, cache, queue, proxy, and application are not independent checkboxes. Their boundaries become visible when a request fails, a deployment overlaps, or one component returns to an earlier state. I would be satisfied with an ordinary system whose recovery procedure is unremarkable because it has been tested. That seems a more useful goal than another layer whose failure behavior we will learn later. If you've attempted a restore rehearsal, what took longer than the database restore itself? I'd be interested in the dependency or decision the backup dashboard could not account for. --- # A Review Belongs to a Commit Canonical: https://ma-x.im/blog/agent-playbook-review-belongs-to-commit Author: Maksym Kuzmitskyi Published: Oct 15, 2026 A reviewer sees a change and raises a useful concern. The author pushes another commit. The comment is still there. The code it described may not be. Human reviewers handle this imperfectly too. An automated reviewer makes the state-management problem easier to notice because it can repeat the same concern every time it runs, or confidently act on a conclusion from the previous revision. The earlier [PR-reviewer article](/blog/github-ai-pr-reviewer) focused on useful language and visibility into a personal tool. This article is about a narrower engineering problem: what a finding, check, or review decision refers to as the code changes. I have developed commit-aware tracking, duplicate-finding safeguards, dry-run checks, and guarded actions in personal review tooling with AI assistance. That describes development of mechanisms, not current continuous operation, organization-wide adoption, or a replacement for human approval. ## A PR number is not the reviewed object The PR is a container for an evolving proposal. The head commit identifies one version of that proposal. The base revision and comparison mode also affect what the reviewer sees. If an automated tool records only "PR reviewed," it cannot distinguish unchanged work from a new commit. If it records only head SHA, it may miss a changed base or integration result that matters to its conclusion. A useful record identifies what was reviewed and under which assumptions: ```typescript type ReviewSnapshot = { headSha: string; baseSha: string; comparison: 'pull-request-diff'; rulesRevision: string; checkedAt: string; }; ``` This is an illustrative type, not an internal implementation. The rules revision matters because the same code can be assessed differently after the checking policy changes. I would not let a convenient database row imply more history than it contains. "Reviewed" should be explainable as a particular observation, not a permanent property of the PR. ## CI has a revision too A green check from an earlier commit does not establish the state of the current one. A required integration check may run on a merge result rather than the branch head. Those are different artifacts. Before review actions, identify which checks are relevant, which revision they exercised, and whether they are finished. A skipped check or an optional success is not necessarily equivalent to every required gate passing. Even then, CI evidence has the scope limits discussed in Green Checks Only Cover What You Checked. It can support a reviewable state without proving the absence of semantic defects. I want a tool to report that distinction rather than promote "green CI" into "safe to approve." ## A finding needs identity and evidence Line numbers are useful for placement. They are poor long-term finding identities. An author can move the same risky expression to another line. The finding remains relevant, but a line-based key changes and the bot may publish it again. Conversely, new code at the old line can have a different risk that a naive key suppresses. A more semantic identity can include the rule, affected symbol, risk category, and relevant normalized evidence. Keep the exact source revision alongside it. Normalization introduces its own trade-off. Strip too much context and different findings collapse into one fingerprint. Keep every character and harmless formatting changes produce duplicates. Treat a fingerprint as a useful matching mechanism, not proof that two concerns are identical. Re-evaluate the current evidence before deciding the old finding still applies or no new comment is needed. ## Suppressed does not mean resolved A repeated finding can be current and intentionally not republished. A missing finding can mean it was fixed, became unobservable in the selected diff, or was skipped because the analysis failed. Those states need different names. ```text current: the concern is supported by the latest evidence unchanged: current, but no repeated comment is needed resolved: evidence supports that the concern no longer applies not-observed: this run did not establish either outcome needs-human: the tool cannot settle the question safely ``` The exact storage model can vary. The distinction keeps duplicate suppression from quietly becoming automatic resolution. An unresolved human thread is another state the tool should not overwrite simply because its own detector no longer sees the pattern. The thread may concern context or a decision that the detector never understood. ## Recheck state before publication Analysis can take time. While it runs, the author can push new code. A comment created from the original diff may now point to invalid lines or describe a risk that has already changed. Re-read the relevant state before publishing. If it no longer matches the reviewed snapshot, stop, discard the pending action, or schedule another review. Do not silently attach the finding to a different revision because that makes the API call easier. The same applies to stronger actions. A guarded action should carry the expected revision and use a platform-supported condition where available: ```typescript type GuardedReviewAction = { expectedHeadSha: string; snapshotId: string; action: 'publish-review'; }; ``` This type expresses the requirement; it does not implement an atomic guarantee. Reading head and then calling an API leaves a time-of-check/time-of-use interval. If the platform cannot condition the action atomically, handle that limitation explicitly and avoid unsupported claims about stale-action prevention. A fresh check reduces risk. It does not freeze another person's branch. ## A dry run has its own evidence boundary A dry run can show which findings and actions a tool would produce. It is useful for inspecting scope, tone, duplicates, and targeting without creating external effects. It does not prove that the later API call will be authorized, attach to the intended line, or observe the same PR state. Nor does a successful API call prove the review content was correct. Use the dry run to inspect proposed actions. Use publication checks to verify current state and delivery. Keep the two results separate in the control interface. If the inline attachment fails, a body-level review may preserve the concern, but should still identify the source revision. A fallback should not turn a precisely scoped observation into an unexplained general warning. ## Human decisions need context, not silent reassignment A person may approve a particular revision. New code can change the basis for that decision. The tool should make that change visible and follow the platform's review policy rather than assume an earlier approval means the new code is accepted. Whether an approval is dismissed, still valid, or requires a new decision depends on the repository's settings and accountable reviewers. The automation should not invent its own release authority. Likewise, an AI suggestion that a dependency update appears routine is evidence, not permission to merge it. Any permitted automatic action needs its own narrowly defined authorization and technical controls. It should not be inferred from the absence of findings. > A review result describes observed code. It does not transfer responsibility for whatever code arrives next. ## Preserve enough history to explain the tool The control surface should answer ordinary questions: which revision was analyzed, what was published, what was suppressed, why a run stopped, and what remains undecided. Record identifiers and outcomes with appropriate retention. Avoid storing raw credentials, private payloads, or unnecessary code copies just to make a log feel complete. When the tool is wrong, the history should help reproduce the decision. Was the input stale? Did normalization merge two findings? Did a missing detector result get treated as resolution? Did the action target change between analysis and publication? Those are repairable mechanisms. Without the history, every correction becomes a guess about the model's intentions. ## The quieter reviewer is not necessarily the better reviewer Duplicate suppression makes the conversation less noisy. That is useful. It can also hide an unresolved issue if the lifecycle is poorly modelled. I would evaluate the tool on the relevance and traceability of its findings, not merely on how few comments it emits. Check unchanged code, moved code, corrected code, a new risk at the old location, and a head update during analysis. Keep a human in charge of interpretation and approval. A review assistant should make that person's evidence easier to find, not create a reassuring status that no one can explain. The next article, [What a Skill Changed, and What It Didn't](/blog/agent-playbook-what-a-skill-changed), examines the same attribution problem at workflow level: what a reusable skill changed, and what it did not. If your review automation remembers that it saw a PR, what exactly does it remember about the code? That is a useful place to inspect before adding another action to it. --- # The Dashboard Is Green. The Order Is Missing. Canonical: https://ma-x.im/blog/full-stack-production-observability Author: Maksym Kuzmitskyi Published: Oct 14, 2026 The API error rate is low. The workers are running. The browser reported no uncaught exception. A user says their order never appeared. All of those observations can be true. We measured the health of individual pieces, while the user described an outcome across several pieces. The missing part is the connection between them. I do not think the answer is simply to log more. A larger pile of unrelated events gives us more to read, which is not quite the same thing as giving us more to understand. ## Start with the outcome we need to explain For checkout, I would distinguish browser intent, request acceptance, order persistence, payment confirmation, and follow-up work. These are not synonyms. A click event proves that someone activated a control. A 200 response proves that an HTTP exchange returned that status. A database record proves that an order was stored. A confirmation email proves another effect entirely. The [analytics layer](/blog/react-playbook-analytics-as-a-layer) and an operational trace also serve different purposes. Product analytics can describe behavior; operational telemetry needs enough context to reconstruct a specific failure without assuming every recorded click became a completed purchase. I would define the business success point explicitly, then work backwards to the evidence required at each boundary. Otherwise the most available metric quietly becomes the definition of success. ## A request id is useful, but it is not the whole identity A request id correlates one HTTP attempt. An idempotency key identifies one intent across retries. An order id identifies durable business state. A trace context links spans across participating services. Keeping these separate is helpful: ```json { "event": "order.persisted", "request_id": "req_9c7", "operation_id": "checkout_62a", "order_id": "order_18f", "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "release": "checkout-2026-10-14" } ``` These are synthetic identifiers. The record does not include a customer's name, email, address, token, or raw payment data. A retry gets a new request id but retains the operation identity. A background job can link to the operation after the original request has ended. Depending on timing and instrumentation, a span link may describe that relationship more honestly than an endlessly extended parent span. Use established trace propagation and instrumentation, such as OpenTelemetry, rather than inventing a collection of vaguely compatible headers. Still validate untrusted incoming context and keep authorization separate from any telemetry identity. ## Missing data has several explanations If a trace is absent, the request may never have happened. It may also have been sampled out, rejected by a collector, dropped from a full buffer, or generated by an uninstrumented component. Head sampling decides early which traces to retain. It keeps costs bounded, but it cannot know at the start which request will fail late. Tail sampling can select after observing more of the trace, at the cost of buffering, coordination, and its own resource limits. Neither gives perfect evidence automatically. Keep critical outcome counters and durable business records independently of a sampling decision. Record the telemetry pipeline's own drops and health so absence is less ambiguous. For frontend error reporting, the same limitation applies. Browser extensions, network conditions, consent settings, and navigation can affect delivery. No recorded exception is not proof that no exception occurred. ## Denominators need their own definition "Twenty failed orders" is difficult to interpret without knowing how many attempts occurred and which attempts count. Counting API requests exaggerates user intent when retries occur. Counting clicks includes actions rejected before a request. Counting created orders excludes failures before persistence. For an outcome metric, define both numerator and denominator around the promise being measured. For example: distinct accepted checkout operations that reach a confirmed or explicit terminal state within a chosen interval. Then describe exclusions: abandoned carts, expected validation failures, test traffic, and operations still inside their allowed processing window. An illustrative target is not a universal SLO. The arithmetic is usually easy. The difficult part is resisting a reassuring percentage with a poorly chosen population. ## Cardinality is a modelling choice Metrics work well with bounded dimensions such as route templates, status categories, region, and service. Attaching `order_id`, raw URLs, or customer email to every metric label creates huge numbers of distinct time series. It also turns the monitoring system into a rather expensive and unsuitable customer index. Use `/orders/:id`, not every concrete order URL, as a metric dimension. Put specific identities in controlled logs or traces when needed, with retention and access appropriate to their sensitivity. Histograms deserve some care too. Percentiles computed independently by instances cannot generally be averaged into the fleet's percentile. Aggregate compatible histogram observations rather than averaging whichever p95 numbers happen to be on the screen. The goal is not to avoid detail. It is to put detail into the kind of evidence that can handle it. ## Frontend context can make a backend trace usable A server sees requests. The browser knows which route, interaction, and release led to them. For an error-reporting tool such as Sentry, a release identifier and matching source maps can turn a minified stack into something useful. Upload source maps through controlled tooling; decide whether publicly serving source files is intended. A production error should identify the bundle that actually ran, not the latest source in main. Session replay can help explain interaction sequences, but I would not enable it broadly without reviewing masking, consent, sensitive fields, retention, and access. "It is an internal admin screen" is often a reason for more care, not less. Expected cancellation should not appear beside faults as though a user navigating away is a broken system. The [AbortController article](/blog/react-playbook-abort-controller) covers that distinction at the interface boundary. ## An alert should name a response High CPU may deserve investigation. Missing orders deserve investigation for a more direct reason. Prefer alerts connected to user-visible impact or exhausted safety margins: sustained error-budget consumption, queue age beyond the product allowance, connection-pool waits, failure to complete accepted operations, or a recovery dependency approaching expiry. The notification needs an owner, a scope, and a useful next action. A chart link is helpful. So are a recent deployment marker and a runbook that says which evidence separates an application failure from a shared-dependency failure. I would not page someone every time one instance reports a brief spike unless that spike calls for a meaningful intervention. Noise does not stay harmless; it changes what people notice later. ## Telemetry is another dependency Exporters have buffers, network calls, timeouts, and shutdown behavior. A slow collector should not cause the checkout handler to wait indefinitely or allocate unbounded memory. Use bounded, asynchronous export appropriate to the instrumentation. Decide what can be dropped and what must be durably recorded elsewhere. Business events required for fulfilment belong in a durable mechanism such as the [transactional outbox](/blog/full-stack-background-jobs), not solely in a best-effort log stream. Also test redaction failures and collector outages. Observability should help us explain failure without becoming its next cause or a route for leaking data. > A telemetry event is evidence with delivery conditions, not a second database transaction. ## Reconstruct one unsuccessful operation I would exercise a deliberately failed checkout and try to follow it from browser intent to its final state. Can we distinguish a request that never arrived from an order that persisted but lost its response? Can we find the background job? Can we identify the release and a retry without counting them as two purchases? If those questions are difficult, another dashboard will not necessarily improve the situation. A better identity or an event at the missing boundary might. The green dashboard becomes useful when we know exactly what its green means. Until then, I would keep the user's missing order as the more interesting observation. The final part of this guide covers [backups and recovery](/blog/full-stack-backups-and-recovery): what happens when diagnosis is finished and some part of the system actually has to be rebuilt. Which production question still sends you comparing timestamps across three tools? I'd like to hear the missing connection, not just which monitoring product you use. --- # The Command Succeeded. The Scope Changed. Canonical: https://ma-x.im/blog/agent-playbook-scope-after-tools Author: Maksym Kuzmitskyi Published: Oct 13, 2026 The agent inspects a small diff and runs the required command. The command succeeds. A hook also regenerates a contract file from a newer source, and the resulting commit contains a change nobody asked for. That is not a runaway agent. It is fairly normal repository automation doing what it was configured to do. The workflow still needs to decide whether the output belongs in this task. I have used this kind of scope drift to refine the checks around delegated work. Reviewing an initial diff is useful; reviewing the artifact after automation is also necessary. They are not always the same artifact. ## The example is deliberately synthetic Consider this illustrative composite, not a file tree from an actual company repository. A task updates one client dependency. Before the commit, the changes are: ```text package.json package-lock.json ``` A repository hook refreshes generated API code. The commit now also contains: ```text src/generated/catalog-api.ts src/generated/catalog-schema.json ``` The generator may be correct about the source it read. The new contract may be a legitimate change. Neither fact says it belongs in a dependency-only PR. It could need another owner, another compatibility check, another release sequence, or simply a separate explanation. A successful generator run does not provide those decisions. ## There are several versions of the change A Git operation has more than one relevant state: working tree, index, commit tree, and the remote branch used by review. An agent can inspect the working tree, stage a subset, and then assume the commit contains that subset. A hook can change files or restage content between those steps. Later, a push hook or generated build output can leave additional local changes that are not committed at all. The useful question is "which artifact did we verify?" These generic inspection commands address different artifacts: ```sh git diff --name-status git diff --cached --name-status git show --format= --stat HEAD git show --format= HEAD git status --short ``` The first two compare working and staged changes. The next two inspect the actual commit. The final status shows what remains outside it. None, by itself, establishes whether the whole task is correctly scoped. I would inspect the post-hook commit before treating it as ready for review or push. If the repository runs consequential automation during push, inspect its effects too rather than assuming the operation left no new state. ## Capture the starting state Scope checks are less useful if the agent does not know which changes existed before it started. A working tree can already contain another person's edits. A generated file may have been dirty before the task. A script may update it again, mixing pre-existing content with the agent's output. Record the branch, base revision, and clean or dirty status before implementation. For relevant dirty files, understand the existing changes instead of treating everything outside the task as disposable. This is especially important when recovering from generated drift. "Remove unrelated files" is not permission to overwrite a colleague's uncommitted work. The safe recovery depends on provenance: which change was introduced by this operation, which was already present, and which now conflicts with the authorized work. If that cannot be established cheaply, stop and ask rather than manufacture a clean tree. ## A file allowlist helps, but it is not the contract For a bounded task, an expected file set can reveal surprises: ```text Expected: dependency manifest and lockfile Observed: manifest, lockfile and generated service contract Decision needed: does the contract change belong to this task? ``` Sometimes the right implementation legitimately needs another file. A test, a call site, or an adapter may be required to satisfy the original behavior. A strict allowlist should expose that question, not force an incomplete fix. The reverse is also true: changes inside an expected file can be unrelated. A lockfile may contain several package updates. One generated module can include multiple contract changes with different owners. Review semantics as well as filenames. The requested scope is an engineering constraint, not a glob pattern. ## Generated does not mean low risk Generated artifacts can encode public APIs, schemas, route tables, database clients, or configuration. A small mechanical change there can affect more consumers than a large handwritten component edit. A tool may regenerate against a remote source whose revision is not recorded. Run it twice and it can produce two different outputs from the same local commit. The task has acquired an external input even though nobody edited an external file by hand. Where practical, pin and record the generator version and input revision, or preserve the relevant source snapshot. Keep generated output reproducible enough to explain a future diff. If a live input is intentional, review the new output with that knowledge. Do not present it as a consequence of the dependency change when it came from unrelated source drift. ## Do not bypass the gate just to avoid its output The tempting response is to disable the hook and finish the small PR. That may discard a required repository control. It also avoids the useful question of why this hook introduces changes unrelated to the task. Follow the repository's supported procedure. It may allow a separate generated update, a pinned input, a check-only mode, or an explicitly approved exception. The agent should not invent an exemption because the hook is inconvenient. After separating unrelated drift, run the checks that matter for the retained change and inspect the final artifact again. A repaired scope still needs verification; the earlier green result may have observed a different set of files. ## Tool success is not scope approval An exit code tells us whether the tool considers its operation successful. It does not certify that the operation had the intended inputs or that every resulting change was authorized. This applies beyond Git hooks. A formatter can touch unrelated documents. A package manager can alter registry URLs or transitive versions. A code migration can rewrite more call sites than the agreed rollout intended. The agent's explanation should identify those effects, not compress them into "all commands passed." > The command's success belongs to the command. Approval of the resulting scope belongs to the task. That distinction allows useful automation without pretending tools understand the whole purpose of a change. ## Make the check repeatable, not the incident immortal After a scope problem, I would refine the workflow around the failure condition: record the starting state, inspect after mutating automation, and verify the artifact that will actually be reviewed. I would not add a permanent paragraph describing every generated file from that one incident. Those details age quickly. The principle remains useful across different generators and repositories. The rule also needs proportion. A read-only test command does not need the same artifact accounting as a commit hook that regenerates contracts. Use the checks where state can change, and keep the explanation local enough that the agent can apply it. ## The final diff should be unsurprising for the right reason An agent can produce a neat initial patch and still need help with the effects of the surrounding toolchain. That is not a contradiction. The repository is part of the execution environment, and it can change the result. I want a reviewer to find the final scope unsurprising because the task explains every meaningful change, not because generated files were hidden from the description. The next article, [A Review Belongs to a Commit](/blog/agent-playbook-review-belongs-to-commit), follows that reviewed artifact as it changes again. A later commit can make yesterday's finding or decision stale. If a tool in your repository can change the artifact after its last inspection, where is the next inspection scheduled? That small gap is worth closing before adding more autonomy. --- # More Replicas, the Same Database Canonical: https://ma-x.im/blog/full-stack-load-balancing Author: Maksym Kuzmitskyi Published: Oct 12, 2026 The application is slow, so the autoscaler adds replicas. Each new replica opens its normal database connection pool. The database was already waiting on locks. Now it has more callers waiting on the same locks. CPU on the application instances improves. Checkout latency does not. Nothing in that sequence is especially exotic. We scaled the part that could multiply, without checking the capacity of the part all those copies still share. I find that a more useful starting point than the usual discussion of which load-balancing algorithm looks fairest. ## The unit of scaling includes its dependencies An application replica is not just a process with some CPU. It is also a database pool, a set of cache connections, outbound calls, retry behavior, and startup work. Consider a simplified connection budget: ```text database limit: 200 reserved for administration: 20 workers and other services: 40 available to the web application: 140 8 replicas x 15 pool connections: 120 12 replicas x 15 connections: 180 ``` These numbers are illustrative. A pool maximum does not mean every process immediately opens every connection, but it is a capacity promise we need to bound. A rolling deployment can temporarily run both old and new replicas. The maximum deployment overlap belongs in the budget too. I would cap replica count and per-process concurrency together. A connection pooler may help, but it cannot make a transaction release its locks sooner or make a slow query cheaper. ## Queuing moves; it does not disappear If the application accepts work faster than it can finish, requests wait somewhere: at the proxy, inside the process, in the pool, or in the database. An unlimited internal queue can make an overloaded service look healthy until requests exceed every client timeout. By then the service may still be doing work for callers that already gave up. Explicit admission limits give the system a more useful response. Bound concurrency, reject excess work with a deliberate status, and decide whether a retry can safely occur. Do not spend thirty seconds doing an operation whose result the caller is no longer waiting for. Cancellation matters, but cancelling a browser request does not automatically cancel the database operation. Deadline propagation needs to reach the layers that support it, with transaction cleanup handled deliberately. I would prefer a small number of quick, understandable overload responses to a large number of ambiguous timeouts. That choice is less attractive on a throughput chart and more attractive during an incident. ## Retries can manufacture the next spike A browser retries. The gateway retries. The application retries its upstream call. Three attempts at each layer can multiply rather than merely add. If the original work is slow because a shared dependency is saturated, retrying immediately adds more work to that dependency. The request deadline may also restart at each hop, extending the actual time spent far beyond what the caller expects. Assign retry ownership. Use a bounded budget, backoff, jitter, and idempotency for writes. Honor useful rate-limit guidance such as `Retry-After` rather than asking every client to guess its own recovery rhythm. Retries are appropriate when another attempt has a reasonable chance of finding different conditions. They are not a substitute for an overload policy. ## Stateless does not mean there is no state The practical meaning is narrower: another instance can handle the next request without relying on unique state in the previous instance's memory. Sessions may live in a shared store. Uploaded files belong in durable object storage. Order state belongs in the database. Any replica can reconstruct what it needs. Local caches are still possible. So are in-memory counters and background bookkeeping, provided they are explicitly disposable and do not claim global correctness. Sticky sessions can keep a client on one instance, which may be useful for a specific workload. They do not make that instance durable. When it disappears, the unique state disappears too unless a recovery path exists. I would describe required affinity as a constraint rather than advertise a system as stateless while quietly depending on the load balancer to remember each user. ## Health checks are routing policy A liveness check asks whether the process can continue. A readiness check asks whether it should receive new work. A synthetic business check asks whether a useful operation succeeds. They do not necessarily belong in the same endpoint. Suppose every instance's readiness check requires Redis to respond. Redis has a shared outage, so every instance becomes unready. Removing all instances may be correct for a session-only application that cannot authenticate anyone. It may be unnecessary for public product pages with a database fallback. Restarting all processes because a shared dependency is slow can also worsen recovery by creating connection and cache-warming bursts. There is a specific AWS detail worth knowing: [ALB fails open when a target group has only unhealthy registered targets](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html). It can route to those targets rather than treating health failure as a guarantee of no traffic. This is not a recommendation to return false health results. It is a reminder to understand the platform's actual response and keep application safeguards in place. The health check does not become a security boundary just because the dashboard colors it red. ## Scaling needs time to become useful A new instance may need to pull an image, initialize connections, load configuration, and warm required state before becoming ready. Autoscaling follows observations with a delay; it cannot instantly absorb a sudden spike. Keep enough baseline capacity for the workload that cannot wait, and choose signals that reflect the bottleneck. CPU can help for compute-heavy traffic. Queue age may better describe workers. Pool wait time or active-request concurrency may reveal pressure that average CPU hides. Avoid a warmup procedure that makes every new replica perform the same expensive full-cache refresh. The capacity meant to help the database can briefly become its largest customer. Scale-in is equally important. A quiet instance may still hold a long request or many WebSocket connections. Removing it is a lifecycle event, not just subtracting one from a counter. ## Draining coordinates several timers The load balancer has a deregistration delay. The process has a shutdown grace period. Requests have deadlines. Connections have idle timeouts. These settings need to agree on how ongoing work ends. Stop admitting new requests, allow existing work a bounded interval, then shut down. If the platform kills the task before the drain interval finishes, the load balancer's generous delay does not help. For WebSockets, draining may require application messages and client reconnection. A reconnected client can land on another replica; events and subscriptions need shared or reconstructible state. The replacement must not assume the old connection's in-memory history is available. A slow deployment should not require every user to discover the reconnection policy through a frozen screen. ## Test a removal, not only an addition A useful scaling exercise removes an instance while traffic is active. It observes errors, latency, duplicate writes, session continuity, and long-lived connection recovery. Test mixed versions too. [Schema compatibility](/blog/full-stack-zero-downtime-migrations) and old frontend bundles remain relevant while the load balancer serves both generations. Retain content-hashed assets long enough for active clients to finish or recover cleanly. These tests make capacity a statement about the whole service rather than a count of containers. I am comfortable with modest scale when the limits are known. I am less comfortable with an autoscaling policy whose only promise is that more processes will appear whenever something becomes slow. The shared database has not read that promise. It will keep accepting only the work it can actually perform. Next, the upcoming article on production observability looks at how to see these limits before an error report becomes the first measurement. When your replica count grows, which downstream quantity grows with it? I'd start a scaling review with that number, before choosing another autoscaling signal. --- # Green Checks Only Cover What You Checked Canonical: https://ma-x.im/blog/agent-playbook-green-checks Author: Maksym Kuzmitskyi Published: Oct 11, 2026 The build passes. The tests pass. The dependency update is small. The integration check disagrees. I do not find that especially surprising. A local check and an integration check can ask different questions about the same change. The awkward part begins when the agent treats the first green result as evidence for a larger conclusion than the check supports. In The Work Around the Agent Is Engineering Work, I described the work around an agent as part of the engineering itself. One useful responsibility in that work is keeping the scope of evidence visible. ## A fictional contract makes the distinction easier to see The following is an illustrative composite. Names, fields and implementation details are invented; it is not a reconstruction of an identifiable system or an internal contract. A booking service consumes a delivery window from a planning service. The contract previously used an ISO timestamp. An updated client expects an integer timestamp in milliseconds. The booking service's local fixture is updated too: ```typescript type DeliveryWindow = { startsAtMs: number; }; const window: DeliveryWindow = { startsAtMs: 1_800_000_000_000, }; ``` The compiler accepts the fixture. The local tests confirm that the booking code handles that fixture correctly. Neither observation tells us which representation the deployed planning service actually returns. If it still returns the previous shape, the local result is not wrong. It is simply narrower than "these services remain compatible." This is one reason I would not call local validation a miniature version of the whole production system. Its exclusions are often exactly what lets it run quickly. ## Evidence has a scope and a revision For each check, ask what it exercised and which code it observed. A test against a mock exercises the mock contract. A test against a generated client exercises the declaration and the path using it. An integration gate may inspect a combined contract or contact a real environment. A package's exported type can differ from its runtime behavior or from what another participant still expects. The checks have different value. They do not automatically inherit each other's coverage. I would keep a small evidence record: ```text Check: booking service unit tests Observed revision: current task commit Established: local handling of the declared delivery window Not established: compatibility with the deployed planner Check: shared integration contract gate Observed inputs: declared participating revisions Established: compatibility within that selected set Not established: behavior of every deployed client ``` This is not a demand for a document after every test command. It is a way to make the distinction explicit when the check is being used to justify a consequential decision. A green integration result also needs an honest boundary. It can be based on a particular environment, selected revisions, or a contract model. It is stronger evidence for some questions, not proof of every runtime property. ## Read the package, not only its version label When a dependency change is involved, inspect what was installed: package metadata, declarations, runtime exports, and the relevant contract representation. A requested version in a manifest is not the full observation. The lockfile, registry artifact, workspace resolution and build output determine what code is actually used. A stale installation can make an agent diagnose a version that is not the one under test. This does not mean dumping the entire dependency tree into context. Start with the disputed boundary and follow the few inputs that decide it. I want the agent to compare evidence it can point to, rather than expand an explanation around a guessed package behavior. More confident prose does not resolve disagreement between an artifact and a declaration. ## Several repositories do not form one snapshot Giving an agent access to related repositories is helpful. It does not make their branches, local changes, and deployed versions coherent automatically. One repository may be on a current base. Another may have an old checkout. A third may contain a pending fix that already changed the intended migration path. Before reasoning across them, identify the revisions and the purpose of each source: current main, active task branch, proposed change, or deployed release. A locally visible implementation can be real without being the implementation production uses. Repository memory should help locate those questions, not answer them from an earlier session. The source of truth for current compatibility is the current relevant state. ## Recheck the problem before repairing the diagnosis The composite continues. Further investigation finds a compatible change already delivered through another path. The original dependency update is now obsolete. There are two different next actions available: make the old proposal more elaborate, or stop pursuing it. An agent can be quite good at the first. It has a task, a branch and an explanation to complete. That momentum is useful when the task remains valid. It is not useful when the current system no longer needs the proposed work. The correct result can be closing the obsolete PR and recording why it was superseded. Do not describe that as delivering the other change. Do not rewrite the history so the incomplete initial diagnosis becomes a clean success. The useful outcome is a rejected unsuitable proposal and a better freshness check for the next task. > Before asking whether the patch works, ask whether it is still the patch the system needs. This is particularly valuable with agents because implementation is relatively easy to continue. Deciding not to continue still requires evidence and an accountable owner. ## Correct the workflow at the missing boundary If the initial diagnosis relied on stale or incomplete sources, merely fixing the current diff leaves the same failure available next time. Move the relevant current-base or related-change check earlier. If a shared contract matters, make the integration gate part of the verification criteria. If the package contents were assumed, inspect the actual artifact before proposing a fix. Keep the correction proportional. One incident does not justify requiring every task to scan every repository. A small single-repository CSS change and a shared dependency migration do not need identical discovery work. The rule should describe the condition that makes the check useful: cross-service contracts, dependency behavior, version skew, or an active related change. Otherwise a lesson becomes another universal instruction the agent follows even when it has no bearing on the task. ## Separate a failed assumption from a failed person An incomplete AI diagnosis deserves correction. It does not need a theatrical explanation about agents being incapable, nor a reassuring story in which the model secretly intended the right thing. Record the assumption, the contradicting evidence, the correction, and the remaining uncertainty. That is enough to learn from the task. It also gives credit accurately. A person may notice the stale base. CI may reject the shared contract. The agent may then help compare sources and prepare the explanation. Those contributions can all be real without being compressed into "AI solved it." ## Keep green useful by keeping it specific I want local checks to stay fast and valuable. Their usefulness does not depend on pretending they cover the whole system. A build confirms something about the selected sources and toolchain. A test confirms behavior under its chosen conditions. A related contract check adds another layer. Current-state investigation tells us whether the task itself still makes sense. The result is not certainty. It is a decision with evidence that matches its scope. I would rather close one well-explained obsolete proposal than merge an increasingly polished implementation of yesterday's requirement. There is less to show in the diff, but more of the system has been understood. The next article, [The Command Succeeded. The Scope Changed.](/blog/agent-playbook-scope-after-tools), looks at another boundary green checks do not automatically cover: what automation changed after the initial edit. If a check in your workflow is routinely used to justify more than it tested, which claim gets attached to it? That gap is usually worth examining before adding another test suite. --- # A Small AWS Deployment, With the Awkward Parts Included Canonical: https://ma-x.im/blog/full-stack-practical-aws Author: Maksym Kuzmitskyi Published: Oct 10, 2026 A diagram with CloudFront, a load balancer, some containers, and a database is a reasonable start. It does not tell us whether the checkout page can cache someone else's order, whether the containers can download their image, or who is allowed to restore the database after a bad migration. Those details are where I would spend the second pass. The boxes are familiar enough. Their permissions and failure behavior deserve a little more attention. For this article, assume an illustrative React application with a Node backend, PostgreSQL, and a few background workers. This is a proposed deployment shape, not a claim about a system I have operated or a measured monthly bill. ## Give each component a limited job One possible layout is: ```text public DNS -> CloudFront -> static assets in S3 -> application routes through ALB -> ECS/Fargate application tasks -> RDS PostgreSQL -> optional ElastiCache queue -> separate worker tasks ``` CloudFront is the public edge. ALB distributes application traffic. ECS manages tasks; Fargate avoids operating the underlying servers directly. RDS runs the database. Redis is optional and should have the [explicit job](/blog/full-stack-redis-without-magic) we discussed earlier. I would not add Redis simply to complete the diagram, or Kubernetes simply to make the deployment feel serious. A managed application platform may also be sufficient. The point of this layout is understanding responsibility, not demonstrating the largest collection of AWS abbreviations. ## A cache policy is part of authorization safety Static, content-hashed assets are good candidates for long-lived caching. A signed-in customer's order page is not the same kind of object. CloudFront distinguishes which values form the cache key from which values are forwarded to the origin. Sending a session cookie to the backend does not, by itself, guarantee responses are isolated correctly in the cache. For private application responses, start with caching disabled and explicitly configure authentication forwarding. For public cacheable responses, include the dimensions that actually change the representation. Test with two separate users, not twice with the same session. There is a particularly useful detail in the [CloudFront cache behavior documentation](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/DownloadDistValuesCacheBehavior.html): a minimum TTL above zero can force caching even when the origin sends `private`, `no-store`, or `no-cache`. That is not a theoretical distinction. The application and infrastructure can each look reasonable in isolation while their combined policy is wrong. Path-pattern ordering matters too. A broad public behavior matching before a narrower protected behavior can apply the wrong rule. I would review edge configuration like application code, including tests for authenticated and unauthenticated variants. ## Private does not mean disconnected Application tasks and databases should not be needlessly reachable from the public internet. But tasks still need outbound paths: pull images, obtain secrets, write logs, and contact payment or email providers. Putting a task in a private subnet without arranging those paths produces a deployment that cannot start or cannot finish its normal work. NAT provides general outbound connectivity. VPC endpoints can provide private access to supported AWS services. They have different setup, availability, and cost implications; neither is a universal instruction to copy without checking the task's actual dependencies. For a small deployment, NAT, load balancers, logs, and minimum database capacity can be a meaningful part of the bill even when application traffic is low. I would estimate those standing costs before optimizing the price of one container. Do not publish the database merely because it makes a first connectivity test easier. Use a controlled administrative path and keep the production network model intact. ## Security groups express specific relationships Rather than allowing the whole subnet to reach every component, define who needs to talk to whom. The application's security group can accept traffic from the ALB group on the application port. The database can accept its database port from the application and worker groups that need it. Other callers do not acquire access simply by sharing a VPC. Also consider origin bypass. If clients can call the public ALB directly, they may bypass restrictions applied only at CloudFront. Depending on the design, use a supported private-origin arrangement or restrict the public origin with appropriate network and request controls. The application must still enforce authentication and authorization itself. These controls compose. A hidden origin is not an authorization system, and an authenticated route is not a reason to leave every network port open. ## The task has two different identities ECS distinguishes an execution role from a task role. The execution role supports platform work such as pulling images and delivering configured logs or secrets. The task role is the identity the application uses when calling AWS APIs. Giving the execution role permission to read an application bucket does not necessarily give the running code that access. Conversely, copying a broad deployment role into the task gives every application bug more authority than it needs. Keep the roles narrow and separate. Use workload credentials rather than embedding long-lived AWS keys in the image. When access fails, identify which role made the request before adding permissions until the error goes away. That last approach does work remarkably well at producing permissions nobody can later explain. ## Fargate tasks still need a resource budget Managed compute does not remove per-process connection pools or memory behavior. Two tasks with twenty PostgreSQL connections each are a different load from twenty tasks with the same setting. Deployment overlap counts too. New tasks start before old tasks drain. The database must tolerate that temporary peak, or the release can run out of connections while average CPU remains comfortable. RDS Proxy may help pool and manage connections, but it is not a cure for long transactions or unlimited concurrency. Application behavior still determines how long connections remain occupied. Set a maximum scale consistent with downstream capacity. Separate workers from HTTP tasks so increasing export throughput does not quietly change the web service's deployment and resource profile. ## Managed availability is not application continuity Multi-AZ database deployment can improve availability during infrastructure failure. A read replica addresses a different concern and may lag. Neither undoes an accidental deletion that the database correctly accepted. Redis failover also has semantics. If cached product descriptions disappear, the database can refill them. If sessions or coordination state disappear, the product consequence is different. I would name those outcomes before choosing service options. "Highly available" is a useful infrastructure property, but it does not mean an order can be repeated without duplication or that a replica provides the latest permission change. Backups and recovery get their own article, [The Backup Exists. The Restore Still Needs Work.](/blog/full-stack-backups-and-recovery). They belong in the initial infrastructure plan even if the first restore exercise comes later. ## Deploy an artifact, not a moving tag A controlled release records an image digest, configuration revision, migration step, and deployment outcome. Infrastructure as code records the intended topology so another environment can reproduce it without reconstructing yesterday's dashboard clicks. Use an additive migration phase, deploy compatible tasks, observe health and business outcomes, then perform destructive cleanup in a later release. Give long-lived connections a drain policy and old browser assets a retention policy. A rollback should name which pieces return to their previous state. The database does not automatically move backwards because ECS deploys the previous image. Finally, add alarms with an owner: application error rate, latency, failed deployments, queue age, database saturation, and spend. Budgets are notifications unless explicit controls say otherwise; they are not a promise that AWS will stop the bill at an exact amount. I would rather deploy this modest layout with known limits than a more elaborate one nobody can safely change. The diagram can stay small. The operating agreement needs enough detail to survive the first inconvenient event. The next article examines [load balancing and scaling](/blog/full-stack-load-balancing), including why adding healthy replicas can make a shared database less healthy. When reviewing an AWS layout, which relationship takes the longest to explain: network access, IAM, cache policy, or recovery? That is usually a useful place for the next design conversation. --- # The Work Around the Agent Is Engineering Work Canonical: https://ma-x.im/blog/agent-playbook-engineering-the-workflow Author: Maksym Kuzmitskyi Published: Oct 09, 2026 A coding agent returns a plausible diff. The local tests pass. It has followed the requested format and written a sensible explanation. There is still a fairly ordinary question left: what does that evidence actually establish? Perhaps the tests cover only one service. Perhaps a hook added files after the diff was inspected. Perhaps another change already solved the problem, so the proposed update is now unnecessary. The output can be quite competent while the decision to ship it remains wrong. That is the part of working with agents that increasingly interests me. Not another way to phrase the request. The conditions around the request that make a result possible to check, continue, and sometimes reject. I have been designing and iteratively refining that environment as part of my engineering work. Repository instructions, connected tools, validation steps, review handling, and session handoffs became things to maintain rather than instructions to repeat in every conversation. I would describe this as agentic workflow engineering. It is still software engineering. The responsibilities have moved around a little; they have not disappeared. ## The diff is one artifact in a longer operation Here is a deliberately generalized composite, not a reconstruction of one identifiable project. Two services share a contract. An agent updates a dependency in one repository. The local build accepts the new types, and the tests confirm the behavior that repository knows about. A separate integration check finds that the other service still expects a different representation. The first diagnosis is incomplete. Before making another patch, the engineer checks the actual package contents, current contracts, base branch, and related changes. A compatible solution has already arrived through another change. Continuing the original update would now introduce a regression rather than finish the task. The useful result is to stop and close the obsolete proposal. There is no new feature to celebrate. There is a clearer account of the system and one unsuitable change that did not enter it. I think that is worth recognizing as an engineering outcome, without pretending it measures a productivity gain. The agent helped investigate. A person still had to decide what the evidence meant, correct the initial assumption, and change the workflow so freshness checks happened earlier next time. ## My contribution is the operating arrangement There is an unhelpful choice in some descriptions of AI-assisted work: either the engineer wrote everything personally, or they merely asked a chatbot to do it. Neither explains what I am doing. My contribution includes defining the task, organizing access to relevant context, choosing constraints, examining decisions, interpreting failures, and refining the next attempt. The agent can inspect sources, propose changes, run checks, and prepare reviewable artifacts inside that arrangement. I do not need to claim manual authorship of every generated line to own those engineering decisions. Equally, a generated implementation does not make the environment around it automatically good. I have integrated existing tools rather than built every tool involved. MCP connections help bring requirements and documentation into reach. Git, CLI/API access, tests, type checks, builds, and browser verification contribute different kinds of evidence. Each needs a clear reason to participate in the task. The distinction matters when describing the work: integration, configuration, development, evaluation, and adoption are separate claims. I would rather use the smaller accurate verb than let a convenient headline imply the larger one. ## Context needs authority and a lifetime Giving an agent more text is not necessarily giving it better context. Personal working preferences, shared engineering standards, repository rules, and task requirements answer different questions. A general suggestion should not override the API contract in the current code. A remembered convention should not defeat a test result observed now. I use saved context to reduce repeated explanation and support continuation. I still expect the agent to verify current sources. Memory can become stale, and instructions can preserve a decision after the reason for it has changed. For an active task, a compact continuation record might look like this: ```text Goal: accept the new response shape without changing existing callers Current observation: one caller still consumes the previous field Decision: retain the compatibility adapter for this release Verified: caller inventory and focused adapter tests Unverified: downstream deployment sequence Next step: confirm the rollout contract before removal ``` This is an illustrative record, not an internal artifact. It separates observations, decisions, checks, and uncertainty. A new session can challenge it against the repository instead of treating the summary as a complete memory of reality. I do not promise identical behavior across models or sessions. The more defensible promise is a documented place to resume and a way to notice when it no longer matches the work. ## Autonomy is partly a permissions problem Written boundaries are useful: which operations are allowed, when to ask, and what must not be disclosed. They are not enforcement by themselves. Tool credentials, available commands, environment isolation, branch protections, and executable gates also determine what can happen. A rule that says "do not release" is weaker than an environment where the agent cannot release without an accountable person's action. The design depends on the task. Low-risk investigation and focused checks can usually proceed without a sequence of tiny approvals. Business requirements, architectural commitments, sensitive actions, and release decisions need the appropriate owner. I want the agent to have enough room to work, not enough authority to settle every question it encounters. This also makes a stop meaningful. If acceptance criteria are unclear or current evidence contradicts the request, continuing to produce code is not necessarily progress. The next useful artifact may be a question or a bounded proposal. ## A small change deserves a discriminating check Before the first edit, I ask the agent to locate the code that controls the behavior, state a local hypothesis, and choose a check that could disprove it. That is less impressive than a long repository survey, but often more useful. The goal is not to read every nearby file before acting. It is to know which assumption the next small edit will test. After that edit, run the focused check before expanding the change. If it fails, decide whether it exposed a local defect or showed that the hypothesis was wrong. Broader tests, lint, build, CI, and acceptance checks follow according to the risk and repository requirements. The focused check does not replace the broader gates. It keeps us from spending a large patch on an assumption we could have disproved cheaply. For a small, clear task, I do not need a specification document that repeats the ticket. For a risky or multi-session change, writing down assumptions and a plan before implementation can be valuable. The timing is part of the evidence: a plan written after the work cannot demonstrate that the work was specification-driven. ## Tools have outputs that need their own review A command can succeed and still change more than the task authorized. Generators, package installation, hooks, formatting, and deployment tooling can all transform the artifact after the initial edit. The working diff we reviewed may not be the commit tree that a hook produced. I have used that kind of failure to refine the workflow: inspect the result after automation, separate unrelated generated drift, and verify what is actually being proposed. It is a fairly undramatic control. That is one of its useful qualities. It does not require the agent to recognize every possible reason a generator changed a file. It requires the scope of the result to be checked before it leaves the local operation. The next two articles, [Green Checks Only Cover What You Checked](/blog/agent-playbook-green-checks) and [The Command Succeeded. The Scope Changed.](/blog/agent-playbook-scope-after-tools), examine those boundaries in more detail. ## Review is evidence attached to a changing object I have also developed personal PR-review tooling with AI assistance. The work includes tracking revisions, avoiding repeated unchanged findings, dry-run checks, and guarding actions against stale state. That is a statement about mechanisms I developed, not a claim that the tool is continuously operating today, deployed across a company, or safely replacing human approval. The engineering problem is interesting on its own. A finding can remain relevant while its line number changes. A new commit can remove the risk but leave an old comment. A review decision can become stale when the object it described changes. I want the automation to provide useful evidence without silently taking over accountability. [A Review Belongs to a Commit](/blog/agent-playbook-review-belongs-to-commit) follows that boundary, including the limitations of duplicate suppression and head checks. ## Improvements need careful attribution I participate in evaluating reusable agent skills against real engineering work. That does not make me the owner of an organization-wide transformation, and it does not establish that a particular framework caused a measured improvement. A successful task can depend on repository instructions, tool access, a well-chosen test, current domain knowledge, or a person's correction. A skill may contribute, add ceremony, or simply describe a practice already present. I try to keep those explanations apart. Record the outcome, corrections, residual risks, and what the available evidence can attribute. Unknown is a reasonable answer when the task does not support a stronger one. [What a Skill Changed, and What It Didn't](/blog/agent-playbook-what-a-skill-changed) will make that distinction concrete without inventing comparative results. ## The useful specialization is not a new claim about the model This work does not mean I train models, conduct ML research, or operate production MLOps. It also does not mean role-based agent configurations have become reliable multi-agent execution simply because the definitions exist. It means I design the conditions in which coding agents participate in software delivery: context, tools, boundaries, checks, human decisions, and a way to learn from ordinary failures. My frontend and full-stack background is part of that, not something to replace with a new label. Interfaces, data ownership, service contracts, tests, and release behavior provide the questions against which generated output gets evaluated. The diff at the beginning can remain plausible. I still need to know what changed, what was checked, and who owns the unresolved decision. I am comfortable letting an agent do a substantial part of the work when those answers are available. I am less comfortable calling the work complete because the explanation sounds finished. If your agent workflow is reliable until one ordinary exception appears, tell me which assumption the exception exposed. That is usually a more useful starting point than another prompt template. --- # Same Container Image, Different Application Canonical: https://ma-x.im/blog/full-stack-container-configuration Author: Maksym Kuzmitskyi Published: Oct 08, 2026 The image passed staging. Production starts the same digest with different environment variables. The browser still calls the staging API. There is no contradiction. The server received its configuration at startup. The browser bundle received its configuration earlier, during the build. "Same image" was true. "Same application, configured at runtime" was only partly true. I like building once and promoting an immutable artifact. It removes a whole class of uncertainty about what was tested. But that promise deserves a more careful definition than "we use Docker now." ## Separate the configuration clocks There are at least three moments when configuration can become fixed: - build time, when the artifact is produced; - process startup, when the runtime initializes; - request time, when a value is consulted again. A public frontend environment variable may be substituted into JavaScript during the build. Changing the container environment does not rewrite the compiled bytes. Next.js documents this behavior for `NEXT_PUBLIC_` values; Vite's `VITE_` values have a similar public-build role. For a browser API address, I would first consider same-origin paths such as `/api`. The proxy selects the environment-specific backend without putting that address into the bundle. If the browser truly needs runtime settings, publish a small, explicitly public configuration resource or inject them into the initial response. Validate it and decide its cache behavior. No secret becomes safe because the file is named `runtime-config.json`. This also creates compatibility work: an old bundle may read new settings. Keep the public configuration schema additive, and record which artifact and configuration revision were deployed together. ## Environment variables do not form a typed contract The process can start with `ORDER_TIMEOUT_MS=ten`. It can also start with a missing variable that quietly activates a development default. I would rather reject an invalid production configuration before the instance receives traffic: ```typescript import { z } from 'zod'; const RuntimeConfig = z.object({ DATABASE_URL: z.string().url(), ORDER_TIMEOUT_MS: z.coerce.number().int().min(100).max(30_000), ENABLE_EXPORTS: z.enum(['true', 'false']), }); const config = RuntimeConfig.parse(process.env); const exportsEnabled = config.ENABLE_EXPORTS === 'true'; ``` The values are illustrative, not recommended timeouts. Notice the boolean handling: the string `'false'` is truthy in JavaScript. A generic truthiness conversion is not a configuration parser. Errors should identify the invalid setting without dumping every environment value into logs. Validation is useful; printing a database password beside the validation failure is not. ## Secret mounts solve one part of the problem Builds sometimes need credentials to download private dependencies. Passing them through Docker build arguments or environment instructions can leave them in image metadata or layers. Deleting a file in a later layer does not remove it from the earlier layer. [BuildKit secret mounts](https://docs.docker.com/build/building/secrets/) expose a credential to one build step without intentionally baking it into the image: ```dockerfile RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \ npm ci ``` That does not prevent the invoked tool from copying the credential into output or printing it. The mount is a delivery mechanism, not a guarantee about everything executed in that step. Runtime secrets have a different lifecycle. An environment-injected database password usually stays unchanged in the process until it restarts. A mounted secret file may update while the application still holds the old value in memory. A secrets service can rotate credentials while existing database connections continue to work and new connections fail. Rotation therefore includes application behavior: refresh or restart, connection-pool replacement, overlap between old and new credentials, and rollback. A secret manager can store the next password. It cannot decide when your client library rereads it. ## Pin the artifact you mean to deploy An image tag is a name. A digest identifies particular content. If `checkout:production` is overwritten while deployment is in progress, instances pulling at different moments can receive different bytes under the same tag. It is possible to build safeguards around tags, but deploying a recorded digest gives the release a less ambiguous identity. Record the source revision, image digest, configuration revision, and migration state. That is enough to explain considerably more than "version 18 is running." Architecture matters too. A locally built image for one CPU architecture is not automatically a usable artifact on another. Multi-platform builds help, but native dependencies still need testing in the runtime actually deployed. ## A container does not make local files durable A generated invoice written into the container filesystem belongs to that instance. The next request may land elsewhere, and the next deployment may remove it entirely. Use the local filesystem for temporary work with a known lifetime. Put durable exports, uploads, and receipts in deliberately managed storage. Return an object identifier rather than a path inside the process that happened to create the file. The same distinction applies to caches. A local cache is useful if losing it is safe and other instances can tolerate different entries. A shared product truth should not accidentally live in whichever container first computed it. Read-only root filesystems and non-root execution can make accidental persistence and unnecessary privileges harder. They also expose implicit assumptions in libraries that want to write temporary files. Test the constrained runtime, not just the permissive development container. ## Resource limits change behavior before a process dies CPU throttling can stretch an ordinary request past its timeout without high host CPU usage. Memory limits can kill a process while the host still has plenty of RAM. Event-loop delay may explain latency that database timing does not. I would set concurrency and heap behavior with the container's actual limits in mind. More parallel promises are not always more throughput. The database pool deserves particular attention. A pool of twenty connections seems modest until twelve replicas each create one. During a rolling deployment, old and new replicas overlap, and the peak connection count can be larger than the steady-state count. We will examine that budget in the [scaling and load-balancing article](/blog/full-stack-load-balancing). For now, the useful habit is to treat per-process settings as quantities that multiply when the scheduler adds processes. ## Do not let every replica migrate the database Running migrations in the application's startup command is convenient for one instance. Start ten instances and you have ten potential migration runners, possibly while the old application still serves traffic. Use a controlled release step with explicit migration ownership, lock behavior, retry policy, and compatibility gates. Database tools may provide advisory locking; that still does not make a destructive change compatible with the old deployment. The [expand/contract approach](/blog/full-stack-zero-downtime-migrations) belongs to the release sequence, not merely to the SQL file. Startup and readiness also need separate meanings. The process may be alive while warming caches or preparing required resources. Conversely, restarting every replica because one shared dependency is briefly unavailable can add more load to that dependency. Health checks should support the failure response we want, rather than giving every unpleasant condition the same instruction: restart. ## Test shutdown as carefully as startup A container usually gets a termination signal and a finite grace period. If the process ignores the signal or an intermediate shell fails to forward it correctly, deployment ends by force-killing work. Use a process arrangement that forwards signals. Stop accepting new work, allow in-flight requests to finish within a bound, and let queue workers acknowledge only completed jobs. Design what happens after the deadline too; the platform will not wait indefinitely because an export is nearly done. An immutable image is useful precisely because it narrows uncertainty. It does not remove configuration, storage, or process lifecycle from the design. I would keep the artifact fixed and make those moving parts explicit enough to reproduce. Next, [a practical AWS deployment](/blog/full-stack-practical-aws) puts these decisions into a concrete infrastructure layout, without treating every available service as a requirement. Which setting in your application changes at a different time than people assume? I'd be interested in the small configuration detail that made an otherwise sound release behave differently. --- # The Domain Moved. Some Requests Did Not. Canonical: https://ma-x.im/blog/full-stack-domains-and-proxies Author: Maksym Kuzmitskyi Published: Oct 06, 2026 The new domain works on your laptop. The certificate is valid. The application responds. Someone else is still reaching the old server. There is usually nothing particularly mysterious about this. The system has several caches, several connections, and several ideas about what "the address" means. They do not update together because we changed a record in a dashboard. In the [first part of this guide](/blog/full-stack-after-fetch), I followed a request from the browser into the backend. Here I want to stay at the entrance, where fairly small configuration changes can leave an application working for one group of users and quietly wrong for another. ## A DNS change has a transition period Lowering a record's TTL immediately before changing its value does not shorten answers already cached under the previous TTL. A resolver that cached an hour-long answer ten minutes ago can keep it for the remaining fifty minutes. I would lower the TTL ahead of a planned cutover, wait for the old lifetime to pass, and keep both destinations usable during the move. DNS TTL is a cache instruction, not a synchronized release mechanism. There is another easy-to-miss cache: the absence of a record. If someone queried a hostname before it existed, their resolver may retain a negative answer. Creating the record does not necessarily make that user able to resolve it immediately. Existing HTTP connections can also outlive a DNS update. A client does not need to resolve the name again for every request on an already-open connection. None of this is a reason to avoid DNS cutovers. It is a reason not to delete the old destination the moment your own lookup looks correct. ## Check both address families A hostname can publish both an A record for IPv4 and an AAAA record for IPv6. If the IPv4 route is healthy while IPv6 reaches an old endpoint, the result may depend on the user's network. Browsers have strategies for choosing between address families, but those strategies cannot turn a wrong AAAA record into the right infrastructure. The symptom is frustratingly ordinary: "It works here." These are diagnostic commands, not a deployment script: ```sh dig +short A api.shop.example dig +short AAAA api.shop.example curl -4 -I https://api.shop.example/health curl -6 -I https://api.shop.example/health ``` The last command requires a working IPv6 path from the machine running it. Failure there is evidence to interpret, not automatic proof that the server is broken. I would also inspect the authoritative records and compare them with the resolver used by an affected client. "Propagation" is often used as a name for any uncertainty around DNS. It is more useful to identify which answer is cached where. ## The certificate belongs to a connection, not a diagram With a CDN in front of a load balancer, there may be two TLS connections: browser to CDN, and CDN to origin. Each has its own certificate validation and hostname expectations. A valid browser-facing certificate says nothing about whether the CDN can validate the origin certificate. The origin address, TLS server name, certificate names, and HTTP Host header have related but distinct jobs. Suppose the origin certificate covers `origin.shop.example`, while the CDN connects using a load balancer's generated hostname. Depending on the configured origin behavior, verification can fail before the application sees a request. I would debug the two connections separately rather than temporarily disable origin verification. The latter makes the immediate error disappear by removing the property we were trying to establish. ## Renewal is the configuration test that arrives later A certificate issued successfully today still needs an automated renewal path. An HTTP-01 challenge requires the validation resource to be reachable through the public route. Add authentication, a new redirect, or a different proxy rule later, and renewal may fail while ordinary application requests continue working. DNS-01 avoids that HTTP path and supports wildcard certificates, but introduces credentials and DNS update behavior into the renewal system. Give the renewal process narrowly scoped access rather than the registrar's unrestricted credentials. Challenge delegation can help separate that responsibility. The [Let's Encrypt challenge documentation](https://letsencrypt.org/docs/challenge-types/) explains these trade-offs. A wildcard for `*.shop.example` also does not cover the apex `shop.example`; certificate names deserve the same explicit review as routing rules. I would monitor expiry from outside the application and exercise renewal before the certificate becomes urgent. A calendar reminder is not quite the automation people usually mean when they say HTTPS is handled. ## The proxy changes what the application believes Behind TLS termination, the application may receive plain HTTP from the load balancer. Without trusted forwarding information, it can generate HTTP callback URLs, fail to set secure cookies, or redirect a request that is already HTTPS into a loop. Forwarded protocol, host, and client-address headers provide that context. They are not trustworthy merely because they have conventional names. An internet client can supply `X-Forwarded-For` too. The proxy must remove or normalize incoming values according to the topology, and the application must trust only the known proxy path. Blindly trusting every hop makes client-IP rate limits and audit records easier to mislead. For password-reset and OAuth URLs, I prefer a configured, validated public origin rather than constructing an absolute URL from an arbitrary Host header. It is less flexible. That is sometimes the point. > Public address, transport address, and trusted request context are separate configuration decisions. ## Moving the hostname can change authentication A host-only cookie for `shop.example` is not sent to `api.shop.example`. A cookie scoped to the parent domain has a broader reach, which can be undesirable if another subdomain is less trusted. Also, two subdomains can be same-site while still being different origins. SameSite cookie rules and CORS answer different questions. Cross-origin browser requests still need the right credential mode and CORS response; a credentialed response cannot use a wildcard allowed origin. The distinction becomes visible after a seemingly harmless move from `/api` on the main origin to a separate API hostname. Authentication, preflight requests, callback allowlists, and browser storage behavior may all change. I would test an existing session, not just a fresh login. I would test logout too. Deleting a cookie with the wrong path or domain can leave the original cookie present, which is a fairly unhelpful way to discover how cookie scope works. ## Preserve request semantics through redirects A canonical-domain redirect is fine for a public page. Applying the same rule indiscriminately to API writes is less comfortable. Some redirect statuses can lead clients to change a POST into a GET. Others preserve the method and body. Even a method-preserving redirect can encounter credential and origin rules that an ordinary page navigation does not. For a moved API, I would keep the old route compatible during the transition rather than expect every client to follow a redirect correctly. The client might be a browser tab, an SDK, or a webhook sender that cannot be upgraded today. Permanent redirects can be cached too. A rollback of DNS or application code does not necessarily rewind the redirect already stored by a client. ## Test an address change as a release A useful cutover check includes more than a homepage returning 200: authenticated reads, writes, OAuth callbacks, uploads, streaming responses, certificate renewal, and the old endpoint during overlap. Proxy buffering is worth checking if the application streams. A server can emit chunks correctly while a proxy collects them and sends everything at the end. The request technically works; the intended latency behavior does not. I would keep the old endpoint alive until observed traffic has moved, then remove it deliberately. The decision comes from request logs and compatibility requirements, not the moment the DNS control panel says the record was saved. The domain is a small part of the application, but it has a long memory. Caches, cookies, certificates, and old clients all remember slightly different versions of it. A good move gives those memories time to become harmless. Next comes [container and environment configuration](/blog/full-stack-container-configuration), where the application can have the right address and still be running the wrong settings. If a domain move left one awkward client behind, I'd be interested in which layer retained the old assumption. Those details are more useful than another checklist that stops at a green padlock. --- # The Request Ended. The Work Did Not. Canonical: https://ma-x.im/blog/full-stack-background-jobs Author: Maksym Kuzmitskyi Published: Oct 04, 2026 The order exists. Payment succeeded. The database transaction committed. Now the API waits three more seconds for an email provider to accept the confirmation message. Sometimes it waits ten. Sometimes the provider times out after doing the work, so the backend does not know whether the email was accepted. The user sees a failed checkout and presses the button again, even though the expensive part already succeeded. The email was not part of the request's answer. We made it part of the request's lifetime. That is the boundary background jobs are meant to fix. The API completes the durable work needed to answer the user, records what still has to happen, and returns. A worker continues separately. Simple in one sentence. Much less simple once "separately" has to remain reliable. ## What belongs outside the request Good background-job candidates share a few traits: - the work is slow or has unpredictable latency; - the user does not need its final result before continuing; - it calls an external service that may be unavailable; - it can be retried safely; - it may need independent scaling. Confirmation emails fit. So do image processing, CSV exports, webhook delivery, search indexing, analytics enrichment, and invoice generation. Creating the order itself does not fit. The API should not tell the browser "order created" before the order is durably recorded. Queueing the core write would turn a clear result into "we accepted your wish and may create it later." Sometimes that asynchronous product is intentional. Then the API should say so with a job or operation id and a pending status. The important part is not pretending pending work is complete. ## A queue separates acceptance from execution The request path becomes: ```text browser -> create order in PostgreSQL -> enqueue confirmation job -> return order worker -> receive job -> send email -> mark job complete ``` The queue buffers work between producers and consumers. The API can accept jobs quickly. Workers process them at the speed the downstream system allows. If email slows down, checkout does not have to slow down with it. That buffer also lets workers scale independently. Ten image processors can consume from the same queue during a spike, then scale back later. But a queue is not just an array somewhere on the server. It needs durable messages, acknowledgement, retry behavior, visibility into pending work, and a strategy for jobs that never succeed. ## The database-to-queue gap Here is a subtle failure: ```typescript const order = await database.orders.create(input); await queue.publish('order-confirmation', { orderId: order.id }); return order; ``` The database write succeeds. The process crashes before publishing the message. The order exists, but no confirmation job was recorded. Reversing the order does not help: ```typescript await queue.publish('order-confirmation', { orderId }); await database.orders.create(input); ``` Now the worker may receive a job for an order that does not exist because the database write failed. Two reliable systems do not automatically form one atomic operation. The transactional outbox pattern solves this by writing the order and an outbox record in the same database transaction: ```sql BEGIN; INSERT INTO orders (id, customer_id, status) VALUES ($1, $2, 'confirmed'); INSERT INTO outbox_events (id, type, payload, created_at) VALUES ($3, 'order.confirmed', $4, now()); COMMIT; ``` A separate publisher reads unsent outbox rows, publishes them to the queue, and marks them as sent. If it crashes after publishing but before marking the row, it may publish the same event again. That is acceptable only if the consumer handles duplicates. ## At-least-once means duplicates are normal Most practical queue systems give us at-least-once delivery: a job will be delivered, but under failure it may be delivered more than once. The worker receives a job, sends the email, then crashes before acknowledging completion. The queue cannot know the email was sent, so it delivers the job again. Exactly-once delivery is an attractive phrase. End-to-end exactly-once effects across a queue, worker, database, and external email provider are much harder than the phrase suggests. Design the job to be idempotent instead. Give the effect a stable identity: ```typescript type SendOrderConfirmationJob = { jobId: string; orderId: string; templateVersion: number; }; ``` Before sending, record or check whether that specific confirmation has already been completed. If the email provider supports an idempotency key, send the stable job id there too. If it does not, decide whether an occasional duplicate email is acceptable or whether stronger local coordination is worth the complexity. Idempotency is not "ignore every repeated order id forever." A resend requested by support is a new intent and should have a new job identity. > A retry is the same intent attempted again. A new action deserves a new identity. That is the same rule we used for checkout requests. Queues make it impossible to avoid thinking about it. ## Retry only failures that may change A timeout from an email provider may succeed on the next attempt. An invalid recipient address will not become valid because we tried it twelve times. Classify failures: - **Transient:** timeout, connection reset, provider rate limit, temporary outage. - **Permanent:** invalid input, unsupported format, missing required data. - **Unknown:** the remote side may have completed the operation before the connection failed. Transient failures get retries with exponential backoff and jitter. Permanent failures stop immediately and become visible. Unknown outcomes need idempotency or reconciliation before retrying blindly. ```typescript const delayMs = Math.min(60_000, 1000 * 2 ** attempt); const jitterMs = Math.floor(Math.random() * 500); scheduleRetry(job, delayMs + jitterMs); ``` Backoff gives the dependency time to recover. Jitter prevents thousands of failed jobs from retrying in perfect synchronization and creating another outage the moment the provider returns. A maximum attempt count is not enough by itself. A job that gives up needs somewhere to go and someone to notice. ## Dead letters are unfinished product work After repeated failure, a job may move to a dead-letter queue. That name sounds final. It should not mean invisible. The job still represents a promise: send a confirmation, generate an export, deliver a webhook. Moving it aside protects healthy work from one poison message, but the product obligation remains. For each job type, decide: - who is alerted; - what context is safe to inspect; - whether the job can be replayed; - whether the user should see a failed status; - when the underlying operation needs manual recovery. A dashboard that proudly shows "queue healthy" while 4,000 jobs sit dead is measuring the machinery instead of the outcome. Queue depth, oldest-job age, processing duration, retry count, and terminal failures tell a more useful story than worker CPU alone. ## Job payloads should be small references It is tempting to put the complete order, customer, and rendered email content into the message. Then the worker has everything it needs. It also freezes a large data snapshot inside the queue, exposes more sensitive information, and makes schema changes harder. A delayed job may execute days later with a payload produced by old code. Prefer stable identifiers and intentional snapshots: ```typescript type GenerateInvoiceJob = { jobId: string; orderId: string; invoiceVersion: number; }; ``` The worker loads current durable data by `orderId`. If a value must reflect the moment of purchase, such as the charged price, that snapshot already belongs in the order model. The message does not need to invent another source of truth. There are exceptions. A webhook event may intentionally preserve the event-time payload. The principle is to choose snapshot semantics, not accidentally serialize half the database into every job. ## Workers need deployment compatibility too A queued message can outlive the code that produced it. Deploy version two of a worker while version-one messages are still waiting, and the new worker must understand the old payload. Roll back the producer, and old code may start publishing the previous shape again. This is the migration problem from the previous article, now applied to messages. Use additive payload changes, sensible defaults, and explicit versions when semantics change. Do not rename a required field and assume the queue emptied during deployment. Measure that it did, or support both versions. Long-running jobs also need graceful shutdown. When a worker receives a termination signal during deployment, it should stop accepting new work, finish or safely release the current job, acknowledge only after completion, and exit within the platform's deadline. Otherwise every deployment creates retries by killing work halfway through. ## The frontend needs a model for pending work Some background work is invisible to the user. An analytics enrichment job does not need a progress bar. An export does. The API can return `202 Accepted` with an operation id: ```json { "operationId": "export_7f2a", "status": "queued" } ``` The frontend polls an operation endpoint, subscribes through server-sent events or WebSockets, or lets the user leave and returns the finished export through notifications. The important state is not only loading and done. It may be queued, running, retrying, completed, failed, or cancelled. Those states belong to the product contract even if a queue implementation uses different internal terminology. Do not show an eternal spinner because the worker died. Persist operation state somewhere durable, define a timeout or terminal failure, and give the user a next action. Async architecture becomes good UX only when uncertainty is visible without becoming alarming. ## Backpressure is a product decision If requests create work faster than workers can finish it, queue depth grows. The queue is doing its job, but the delay may eventually violate the product promise. We can add workers until a downstream limit stops us. We can prioritize urgent jobs. We can reject or postpone new work. We can reduce expensive processing. What we cannot do is treat an ever-growing queue as healthy because no messages were lost. For confirmation email, five minutes may be embarrassing but survivable. For a fraud check that gates order fulfilment, five minutes may block the business. "How old can the oldest job become?" is a product question with an operational metric attached. Queues buy time. They do not create capacity. ## Keep the promise smaller than the machinery Background jobs are useful because they let an HTTP request end before every side effect is complete. That separation improves latency and isolates unreliable dependencies. But the queue is not the guarantee. The guarantee comes from the whole path: - durable intent recorded with the business change; - messages published despite process failure; - consumers safe under duplicate delivery; - retries limited to failures that may recover; - dead jobs visible and recoverable; - payloads compatible across deployments; - product states that admit work is still pending. Once those pieces are explicit, a queue stops being mysterious infrastructure. It becomes a controlled handoff between "the user can continue" and "the system still owes some work." The [next part of this guide](/blog/full-stack-domains-and-proxies) moves back to the public edge: domains, DNS, HTTPS, and reverse proxies, and how a name typed into a browser reaches the right application without exposing every internal service directly. If your application returns success before all the work is finished, write down what it still owes. That list is the beginning of the background-job design, not an implementation detail after it. --- # Redis Is Fast. Your Data Can Still Be Wrong. Canonical: https://ma-x.im/blog/full-stack-redis-without-magic Author: Maksym Kuzmitskyi Published: Oct 02, 2026 The product page loads in 900 milliseconds. Someone adds Redis. Now it loads in 70. That feels like the end of the story. Then a price changes in PostgreSQL and the product page keeps showing the old value. One user sees the new price, another sees the cached one, and checkout has to decide which reality to charge. Redis did not create the inconsistency. We did, the moment we copied data without deciding how that copy becomes stale. This is the useful way to think about Redis: not as a faster database, and not as a performance switch. It is a fast, shared, in-memory data structure server. The moment we put something there, we need to know whether it is a cache, a session, a counter, a lock, a queue, or the actual source of truth. Those jobs have different failure rules. Mixing them is where the magic starts, and magic is difficult to debug. ## Start with one slow read Our checkout needs a product summary before creating an order. The database query joins current price, availability, and a few display fields. It is read frequently and changes much less often than it is requested. That is a reasonable cache candidate. The common cache-aside flow looks like this: ```typescript async function getProductSummary(productId: string) { const key = `product-summary:${productId}`; const cached = await redis.get(key); if (cached) { return ProductSummary.parse(JSON.parse(cached)); } const product = await productRepository.getSummary(productId); await redis.set(key, JSON.stringify(product), { EX: 300 }); return product; } ``` Read Redis first. On a miss, read PostgreSQL, cache the result for five minutes, and return it. The database remains the source of truth. Redis holds a disposable copy. If the cache is flushed, the application gets slower while it warms again, but it does not forget what a product costs. That last sentence is the design test I use most often: > If deleting Redis destroys the truth, you are not using it as a cache. There are valid systems where Redis owns important data. They need persistence, replication, backup, and recovery designed accordingly. That is a deliberate database choice, not "we already had Redis running." ## A TTL is not an invalidation strategy The five-minute expiration prevents the entry from living forever. It does not tell us whether five minutes of stale pricing is acceptable. For a blog post list, it may be. For inventory, probably not. For authorization, almost certainly not. Time-to-live is a business decision disguised as a number. It should come from how long the system can tolerate being wrong, not from a familiar round value copied from another cache. When a product price changes, we have a few options. We can delete the cache entry immediately after the database update: ```typescript await database.transaction(async (transaction) => { await transaction.products.updatePrice(productId, priceCents); }); await redis.del(`product-summary:${productId}`); ``` The next read repopulates it. This is simple and often enough. But notice the gap: the database commit can succeed and the Redis deletion can fail. The stale entry then remains until its TTL expires. We can reduce the risk with retries or publish an invalidation event through an outbox. We can update the cache directly, but then we must decide what happens if the database succeeds and the cache write fails, or the other way around. There is no universal "keep it in sync" command. There is only a chosen tolerance for stale data and a recovery path when the two writes do not complete together. ## Cache keys are part of the schema This key looks harmless: ```text product-summary:42 ``` Then the response shape changes. Old application instances write one JSON structure, new instances expect another, and both use the same key. The failure looks like an API contract problem because it is one. The cache has a data contract too. Version keys when the shape changes incompatibly: ```text product-summary:v2:42 ``` Include every dimension that changes the answer: tenant, locale, currency, permissions, or feature variant. If Canadian and US prices share one key, Redis will return the wrong answer extremely quickly. At the same time, avoid encoding accidental details into keys. A stable key convention should be readable, bounded, and owned by one module. Scattered string construction creates the same drift as scattered query keys on the frontend. ## Fast misses can overwhelm the database Suppose a popular product's cache entry expires while 2,000 users are viewing it. All 2,000 requests miss. All 2,000 query PostgreSQL. The cache was supposed to protect the database, but its expiration creates a traffic spike instead. That is a cache stampede. One mitigation is request coalescing: the first request acquires a short-lived right to refresh, while the others wait briefly or receive a slightly stale value. Another is adding random jitter to expiration times so thousands of related keys do not disappear in the same millisecond. ```typescript const baseTtlSeconds = 300; const jitterSeconds = Math.floor(Math.random() * 60); await redis.set(key, value, { EX: baseTtlSeconds + jitterSeconds, }); ``` For data where brief staleness is acceptable, stale-while-revalidate is often a pleasant trade: return the old value immediately and let one worker refresh it in the background. The right choice depends on what being stale means. A product description can lag. A stock reservation cannot casually do so. ## Sessions are not ordinary cache entries Redis is also commonly used for server-side sessions. The browser stores an opaque session id in a secure cookie. Redis maps that id to session state. Every application instance can read it, so a user does not lose their session when the load balancer sends the next request to another server. This solves the in-memory-session problem from the first article in the series. It also raises the stakes of Redis failure. If product cache entries disappear, the database can refill them. If all sessions disappear, everyone may be logged out. Same technology, different product consequence. Session data needs an intentional lifetime, secure cookie settings, rotation after privilege changes, and a failure policy. It should not contain a convenient copy of the entire user record that silently outlives permission changes. Store the minimum needed to identify the session and enforce its lifecycle. Redis being fast is not an invitation to stop modelling identity carefully. ## Counters fit Redis naturally Some jobs align especially well with Redis because it can update values atomically. Rate limiting is a good example. Increment a counter for one user or IP, set an expiration window, and reject requests after the limit: ```typescript const key = `rate-limit:create-order:${userId}`; const attempts = await redis.incr(key); if (attempts === 1) { await redis.expire(key, 60); } if (attempts > 10) { throw new TooManyRequestsError(); } ``` Production implementations usually use a Lua script or a dedicated command pattern so increment and expiration are atomic, and more advanced limits may use sliding windows or token buckets. But the shape explains why Redis fits: a small shared counter, updated frequently, with a natural expiration. This is not a replacement for abuse protection at the CDN or gateway. It is an application-aware layer: ten checkout attempts may mean something different from ten product-page reads. ## Distributed locks are easy to overtrust Redis can coordinate a short-lived lock between application instances. That can be useful for preventing duplicate cache refreshes or ensuring only one scheduler starts a non-critical task. It is more dangerous when the lock is treated as proof that a financial or inventory operation happened exactly once. Processes pause. Networks partition. Lock leases expire. A client may continue working after it no longer owns the lock. Correct distributed locking requires careful ownership tokens, expiration, and usually fencing at the resource being protected. For shared business truth, I prefer database constraints, idempotency keys, and atomic database updates whenever they can express the rule. A Redis lock can reduce duplicate work. It should not be the only wall protecting an invariant the database can enforce directly. ## Decide what happens when Redis is unavailable Every Redis use needs a failure answer. - Product cache unavailable: read from PostgreSQL, perhaps with traffic protection. - Rate limiter unavailable: fail open or fail closed, depending on the endpoint and threat. - Session store unavailable: reject authenticated operations rather than invent identity. - Duplicate-work lock unavailable: skip the optimization or pause the job. One blanket fallback is not honest because these features carry different risks. Also watch the fallback itself. If Redis goes down and every request immediately hits PostgreSQL, the database receives the full traffic load at the worst possible moment. Timeouts, connection-pool limits, and circuit breakers keep one dependency failure from becoming two. The frontend experiences this as latency and uncertainty. A cache outage may not return a clean error; it may make requests slow enough that users retry, which increases traffic further. Pending states need time limits, retries need idempotency, and "try again" should not mean "create another order." ## Cache only after you know the expensive path Redis is not the first fix for every slow endpoint. Sometimes the query lacks an index. Sometimes the API fetches the same data four times. Sometimes a huge response is serialized on every request. Sometimes the frontend asks for data it does not need. Caching an inefficient path can hide it until the cache misses under load. Measure the request. Find the expensive operation. Decide how stale its result may be. Choose the cache ownership and invalidation rule. Then add Redis. That order makes Redis wonderfully boring. It is a fast copy, a short-lived session, or an atomic counter with an explicit job. Not a mysterious red box that "handles performance." The next article follows work that should not keep an HTTP request open at all: confirmation emails, exports, image processing, and other jobs that need to finish after the user already has a response. If your Redis instance disappeared for ten minutes, which user-visible promise would break first? That answer is a much better description of your Redis architecture than the list of commands your code uses. --- # The Database Changed Before the Deployment Finished Canonical: https://ma-x.im/blog/full-stack-zero-downtime-migrations Author: Maksym Kuzmitskyi Published: Sep 30, 2026 Renaming a database column looks like one line of SQL. ```sql ALTER TABLE orders RENAME COLUMN total_cents TO total_amount_cents; ``` The change is correct. The new name is clearer. The migration takes almost no time on a small table. And it can still break production before the new application finishes deploying. The problem is not the rename itself. The problem is that a deployment is not one instant. For a while, old application instances and new application instances may run at the same time. Requests continue arriving. Background jobs keep working. Someone may roll the application back while the database stays exactly where the migration left it. That overlap changes the question. We are no longer asking, "Does the new code work with the new schema?" We are asking whether every version that can still receive traffic works with the database as it exists right now. ## Deployment is a period of mixed reality Imagine three application instances behind a load balancer. The deployment replaces them one at a time: ```text minute 0: old, old, old minute 1: new, old, old minute 2: new, new, old minute 3: new, new, new ``` If the migration renames `total_cents` before minute one, every old instance immediately starts querying a column that no longer exists. If the migration runs after minute three, every new instance may start querying `total_amount_cents` before the column exists. Stopping all traffic, changing the database, and starting the application again avoids overlap. It also creates downtime and turns rollback into a much sharper operation. That may be acceptable for a small internal tool. It is a poor default for a checkout that people are using while we deploy it. Zero-downtime migration is not a special PostgreSQL command. It is a sequence of changes where compatibility is preserved at every step. > Change the system so old and new versions can coexist before you ask either one to disappear. ## Expand before you contract The usual pattern has two phases: expand the schema to support both versions, then contract it after the old version is gone. For our rename, the safe path begins by adding the new column without removing the old one: ```sql ALTER TABLE orders ADD COLUMN total_amount_cents INTEGER; ``` Old code still reads and writes `total_cents`. Nothing has broken. Next, deploy code that understands both columns. During the transition, writes keep them synchronized: ```typescript await database.transaction(async (transaction) => { await transaction.orders.update(orderId, { totalCents, totalAmountCents: totalCents, }); }); ``` Reads prefer the new value but can fall back while old rows are being migrated: ```sql SELECT COALESCE(total_amount_cents, total_cents) AS total_amount_cents FROM orders WHERE id = $1; ``` Now old instances can keep using the old column, and new instances can begin using the new one. The database supports both realities. Only after every row has the new value, every writer populates it, and no old application instance remains do we remove `total_cents`. That final removal is the contract phase. It should be the least exciting part of the change because all meaningful traffic moved away from the old column earlier. ## Backfill is production work Adding an empty column is usually cheap. Filling it across a large table may not be. This looks harmless: ```sql UPDATE orders SET total_amount_cents = total_cents; ``` On millions of rows, one giant update can hold locks, generate a large amount of transaction log, create replication lag, and compete with the queries serving users. The statement may finish successfully while making the application painfully slow. Backfill in batches instead: ```sql UPDATE orders SET total_amount_cents = total_cents WHERE id IN ( SELECT id FROM orders WHERE total_amount_cents IS NULL ORDER BY created_at LIMIT 1000 ); ``` Run a batch, commit it, observe the database, then continue. The exact size depends on the table, hardware, traffic, and replication setup. There is no heroic batch size that is correct everywhere. The important shift is treating backfill as a workload, not as setup. It consumes the same database resources as customer requests. It needs progress metrics, rate control, and a way to resume after interruption. ## Constraints can arrive later The new column should eventually be `NOT NULL`. Adding that requirement immediately would reject writes from old instances that know nothing about the column. So the order matters: 1. Add the nullable column. 2. Deploy dual-write code. 3. Backfill existing rows. 4. Verify that no null values remain. 5. Add the constraint. In PostgreSQL, validating a constraint separately can reduce the risky part of the operation on a busy table: ```sql ALTER TABLE orders ADD CONSTRAINT orders_total_amount_present CHECK (total_amount_cents IS NOT NULL) NOT VALID; ALTER TABLE orders VALIDATE CONSTRAINT orders_total_amount_present; ``` Once validated, the schema can be tightened further according to the database version and operational needs. The point is not memorizing this exact syntax. It is separating "start enforcing this for new changes" from "prove every old row already satisfies it." Large production changes become safer when those are not forced into one moment. ## Indexes have deployment behavior too Suppose the new application also needs to find pending orders by creation time: ```sql CREATE INDEX orders_pending_created_at_idx ON orders (created_at) WHERE status = 'pending'; ``` Building a normal index can block writes depending on the database and operation. PostgreSQL provides `CREATE INDEX CONCURRENTLY` so the table can continue serving writes while the index is built: ```sql CREATE INDEX CONCURRENTLY orders_pending_created_at_idx ON orders (created_at) WHERE status = 'pending'; ``` The trade-off is that concurrent creation takes longer, does more work, and cannot run inside a normal transaction block. If it fails, it may leave an invalid index that has to be removed before retrying. "Non-blocking" does not mean "free." Watch CPU, I/O, lock waits, and replication lag while it runs. This is where migration tools can become misleading. A tool can generate valid SQL without knowing whether Tuesday afternoon is a safe time to run it against the largest table in the system. ## Destructive changes deserve their own deployment Dropping a column, narrowing a type, or removing an enum value is fundamentally different from adding something. An additive change creates room. A destructive change removes a path that some code may still use. I prefer to separate destructive cleanup into a later deployment. Not five minutes later. Later enough that we can confirm: - no old instances remain; - no background worker uses the old shape; - no scheduled job wakes up with old code; - no external consumer depends on the field; - rollback no longer requires the old schema. That delay can feel untidy because the database carries two columns for a while. Temporary duplication is cheaper than a clean schema that breaks a rollback. ## Rollback is a compatibility test A good deployment plan asks what happens if the application must return to the previous version. With the expanded schema, rollback is straightforward: old code still sees `total_cents`. New rows created during the deployment have both values because the transition code dual-wrote them. After the old column is dropped, that rollback path disappears. This is why database rollback rarely means "run the migration file backwards." Recreating a dropped column does not restore its lost data. Converting a type back may not recover the original representation. A migration can be reversible in syntax and irreversible in meaning. For destructive changes, forward recovery is often safer: deploy a fix that works with the current schema instead of trying to rewind production data through time. ## The frontend can be part of the overlap Static frontend assets are cached. A user may keep a tab open for hours. A service worker may serve an older bundle after the backend deployment is complete. That means API compatibility often outlives server-instance compatibility. If a response field changes, the expand phase may need to return both old and new shapes long enough for active clients to age out. If an enum gains a value, older clients need a fallback. If a request becomes stricter, the backend may need to accept the old shape during the transition. The browser is not automatically upgraded because the deployment dashboard turned green. This is one reason I prefer additive API and schema evolution. It gives independently deployed pieces room to move without pretending they change together. ## A migration needs evidence, not optimism Before contracting the schema, I want evidence that the new path owns production traffic: - null count for the new column is zero; - old-column reads and writes have stopped; - backfill progress is complete; - query latency and lock waits stayed acceptable; - replicas caught up; - the new application version is stable; - rollback expectations are explicit. Some of this comes from database queries. Some comes from logs and metrics. The important part is that removal is triggered by observed usage, not by "the deploy finished, so it should be fine." The safest database migration is often boring and slightly slow: add, deploy, copy, observe, enforce, remove. That is not ceremony around one line of SQL. It is how we change a shared truth while the system keeps using it. The next article looks at a different kind of shared state. Redis is fast enough to hide many problems, which is exactly why it needs a clear job before we put it between the application and the database. If a migration in your system still requires everyone to hold their breath during deployment, tell me which step feels dangerous. That point usually reveals the compatibility assumption we have not made explicit yet. --- # SQL for Frontend Engineers: Model the Relationship First Canonical: https://ma-x.im/blog/full-stack-relational-database Author: Maksym Kuzmitskyi Published: Sep 28, 2026 A product card is one object in React. An order summary is another object. A customer has an array of addresses. The API returns a comfortable tree, so it is tempting to imagine the database storing the same tree somewhere below the backend. A relational database does not think in component-shaped trees. It stores facts and relationships. That difference is where SQL starts feeling either confusing or surprisingly clean. If you begin with screens, the database looks fragmented. If you begin with what must remain true, the pieces make sense. Let us model the checkout from the first two articles. Not as a complete commerce platform. Just enough to understand the decisions a frontend engineer eventually runs into. ## Start with facts, not tables Before writing SQL, I would write down the facts the system needs to preserve: - a customer can place many orders; - an order belongs to one customer; - an order contains one or more line items; - each line item records a quantity and the price charged at purchase time; - changing a product's current price must not rewrite an old order; - an order total cannot be negative. That list is already most of the model. Tables are how we encode it. ```sql CREATE TABLE customers ( id UUID PRIMARY KEY, email TEXT NOT NULL UNIQUE, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE orders ( id UUID PRIMARY KEY, customer_id UUID NOT NULL REFERENCES customers(id), status TEXT NOT NULL, total_cents INTEGER NOT NULL CHECK (total_cents >= 0), currency CHAR(3) NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE TABLE order_items ( id UUID PRIMARY KEY, order_id UUID NOT NULL REFERENCES orders(id), product_id UUID NOT NULL, product_name TEXT NOT NULL, unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents >= 0), quantity INTEGER NOT NULL CHECK (quantity > 0) ); ``` Nothing here is clever. That is a strength. The primary key identifies one row. The foreign key makes an invalid relationship impossible: an order cannot point to a customer that does not exist. The checks keep negative prices and zero-quantity line items out of the data, no matter which application path attempts the write. Validation in the API gives users good feedback. Constraints in the database protect the truth when every other layer makes a mistake. ## Relationships are the model The line between `customers` and `orders` is one-to-many. One customer can have many orders, while each order points back to one customer through `customer_id`. Orders and products look many-to-many: an order contains many products, and a product appears in many orders. The `order_items` table sits between them and turns that relationship into data of its own. That middle table is not plumbing. Quantity belongs to the relationship between this order and this product. So does the price charged at that moment. This is the first place where copying data can be correct. `product_name` and `unit_price_cents` deliberately snapshot purchase-time facts. If the catalog renames a product or changes its price tomorrow, yesterday's receipt must not change. Normalization does not mean "never duplicate a value." It means each fact has a clear owner. The current product price belongs to the product. The charged price belongs to the order item. Those are two different facts that happen to match at checkout time. ## A JOIN rebuilds the view you need The frontend wants an order details object. The database stores related rows. A `JOIN` reconnects them for this query: ```sql SELECT orders.id, orders.status, orders.total_cents, orders.currency, customers.email, order_items.product_name, order_items.unit_price_cents, order_items.quantity FROM orders JOIN customers ON customers.id = orders.customer_id JOIN order_items ON order_items.order_id = orders.id WHERE orders.id = $1; ``` The result contains one row per line item, so order fields repeat. That is normal. The backend maps those rows into the nested response the frontend wants. This is a useful separation: storage is organized around integrity and querying; API responses are organized around the consumer's task. They do not need to have the same shape. Trying to make every table mirror one screen usually creates awkward data. Screens change frequently. The fact that an order belongs to a customer changes much less often. ## Transactions protect multi-step changes Creating an order is not one write. We insert the order, insert its line items, and reserve inventory. If the third step fails, the first two should not remain as a convincing-looking half-order. A transaction groups the writes into one decision: ```sql BEGIN; INSERT INTO orders (...); INSERT INTO order_items (...); UPDATE inventory SET available = available - $1 WHERE product_id = $2 AND available >= $1; COMMIT; ``` If any required step fails, the application rolls the transaction back. Other readers see either the state before checkout or the completed order, not the awkward middle. Transactions are not a way to make an entire distributed system atomic. A payment provider and an email service do not participate in your PostgreSQL transaction. Keep the database transaction focused, commit durable state, then hand slower external work to explicit follow-up processes. That boundary will matter when this series reaches queues and background jobs. ## Concurrency is where the model gets honest Suppose only one unit remains. Two users place an order at almost the same time. If both requests first read `available = 1` and then separately write `available = 0`, both may believe they bought it. The UI cannot prevent this. Disabling a button only affects one browser. The conditional update above makes the database perform the check and write together. The backend then verifies that exactly one row changed. One order proceeds; the other receives an out-of-stock result. This is why I think of the database as more than persistence. It is the final place where concurrent claims about shared state meet. > If two requests can disagree, the invariant belongs where both requests must pass. Frontend optimistic updates still have value. They make the interface responsive. They simply do not get the final vote on shared inventory, balances, permissions, or uniqueness. ## Indexes answer a specific question faster An index is often explained as "something that makes queries fast." True, but incomplete. An index makes a particular access pattern faster, while adding storage and write cost. This query will become common: ```sql SELECT id, status, total_cents, currency, created_at FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20; ``` A matching index is: ```sql CREATE INDEX orders_customer_created_at_idx ON orders (customer_id, created_at DESC); ``` The column order reflects the query: first narrow rows to one customer, then read them in the requested time order. Adding indexes to every column is not a strategy. Each index must be updated when data changes. The right question is not "which fields look important?" It is "which query is slow, how does it filter, and how does it sort?" Use the database's query plan instead of guessing. In PostgreSQL, `EXPLAIN ANALYZE` shows what actually ran, how many rows were examined, and where time went. It turns performance from folklore into evidence. ## The N+1 problem starts as innocent code Imagine loading twenty orders, then loading items for each order in a loop: ```typescript const orders = await orderRepository.findByCustomer(customerId); for (const order of orders) { order.items = await orderItemRepository.findByOrder(order.id); } ``` One query loads the orders. Twenty more load their items. That is N+1: one initial query plus one query per result. It can hide behind a clean ORM relationship and look harmless in development with three records. Under real latency and larger result sets, it becomes a page that gets slower as the product succeeds. The fix may be a join, a batched `WHERE order_id IN (...)` query, or an ORM include that genuinely batches. The important part is knowing how many database round trips the convenient abstraction produces. An ORM can save enormous amounts of repetitive work. It cannot make the cost model disappear. ## NULL is a domain decision Nullable columns deserve more thought than they usually get. Does `shipped_at = NULL` mean the order has not shipped, shipping does not apply, or old data was never migrated? Those are different states hiding behind the same absence. Sometimes null is exactly correct. A pending order genuinely has no shipment timestamp yet. But if absence carries several meanings, make the state explicit with a status or separate relation rather than forcing every query and component to guess. This maps directly to TypeScript. A nullable database field becomes `string | null` somewhere in the application. If frontend code keeps asking "why can this be null?", the uncertainty may begin in the data model, not the component. ## Learn enough SQL to see through the abstraction Typed query builders and ORMs are useful. I would rather write most application queries through one than concatenate SQL strings by hand. But the abstraction should make SQL easier to produce, not unnecessary to understand. You still need to see the relationships, transaction boundary, indexes, constraints, and number of round trips. Otherwise a pleasant method chain can hide an expensive or incorrect operation. The frontend parallel is familiar. A component library saves us from rebuilding every button, but we still need to understand HTML and accessibility. The database deserves the same respect. Once the model is clear, SQL stops looking like backend punctuation. It becomes a precise way to ask questions about facts you have deliberately structured. The next problem is changing that structure while old application instances are still running. That is where a harmless-looking rename becomes a production migration. If there is a database concept you have been treating as "backend only," tell me which one. The best topics in this guide are exactly the boundaries frontend engineers are expected to cross without anyone first drawing the map. --- # An API Is a Boundary, Not a URL Canonical: https://ma-x.im/blog/full-stack-api-contracts Author: Maksym Kuzmitskyi Published: Sep 26, 2026 The most dangerous API response is not always a `500`. Sometimes it is a `200` containing almost the data your frontend expected. The request worked. JSON arrived. The loading state disappeared. Then a component tried to format `order.total.amount`, except the backend now returns `totalAmount`. Nothing failed at the network boundary, so the failure moved deeper into the UI where it became harder to explain. That is what makes API work deceptive. We tend to describe an API as a list of URLs, but the URL is the least interesting part. The real API is an agreement about inputs, outputs, errors, timing, repetition, and change. > An endpoint tells you where to send a request. A contract tells both sides what the request means. Let us keep following the checkout request from the previous article and make that contract explicit. ## Validate where trust changes The browser sends this body: ```json { "cartId": "cart_42", "deliveryMethod": "courier" } ``` TypeScript can prove that our frontend created the right object. It cannot prove that the server received it unchanged. Requests can come from an old frontend bundle, a mobile client, a script, a browser extension, or someone calling the endpoint by hand. The network boundary erases TypeScript's guarantees. Runtime validation restores them. ```typescript import { z } from 'zod'; const CreateOrderRequest = z.object({ cartId: z.string().min(1), deliveryMethod: z.enum(['courier', 'pickup']), }); const input = CreateOrderRequest.parse(request.body); ``` This is not defensive programming for unusually malicious users. It is how the backend prevents an assumption from travelling further into the system. Without validation, an invalid `deliveryMethod` might reach pricing, inventory, and persistence before something finally throws. With validation, the request stops at the boundary and returns a useful problem while the system is still in a known state. The response needs the same treatment on the frontend. A generated type or shared interface improves development, but it is not runtime evidence. ```typescript const OrderResponse = z.object({ id: z.string(), status: z.enum(['pending', 'confirmed']), total: z.object({ amount: z.number(), currency: z.string().length(3), }), }); const order = OrderResponse.parse(await response.json()); ``` I do not validate every harmless response in every application. That can become ceremony. I validate the boundaries where wrong data would be expensive, confusing, or difficult to recover from: authentication, checkout, payments, persisted user work, and integrations owned by another team. ## Errors are part of the response model A successful response usually gets careful types. Errors often get whatever the framework happens to throw. That creates frontend code like this: ```typescript try { await createOrder(input); } catch (error) { showToast('Something went wrong'); } ``` The message may be acceptable for an unknown infrastructure failure. It is terrible for "one product is no longer available" or "the delivery address is outside the service area." Those are expected business outcomes. The user can act on them. A small structured error is enough: ```typescript type ApiProblem = { code: 'CART_CHANGED' | 'OUT_OF_STOCK' | 'INVALID_ADDRESS'; message: string; field?: string; requestId: string; }; ``` The stable part is `code`. The backend can improve `message` without breaking frontend behavior. The optional `field` lets a form place the error next to an input. The `requestId` connects the user's failure to server logs. HTTP status still matters. A `400` means the request itself is invalid. `401` means authentication is missing or no longer valid. `403` means identity is known but the action is forbidden. `409` means the request conflicts with current state. `429` means slow down. `500` means the server failed to complete an operation it should have been able to complete. The status gives infrastructure and generic clients a category. The problem code gives the product a decision. ## Retrying changes the meaning of a request Our user presses **Place order**. The backend creates the order, but the connection drops before the response reaches the browser. What should the UI do? From its point of view, the result is unknown. Retrying might recover cleanly. It might also create a second order. This is where idempotency stops being backend vocabulary and becomes a user-experience requirement. The frontend generates a key for the action and sends it with the request: ```typescript const idempotencyKey = crypto.randomUUID(); await fetch('/orders', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey, }, body: JSON.stringify(input), }); ``` The backend stores the key with the result. If the same operation arrives again, it returns the original result instead of performing the write twice. The detail people miss is scope. The key belongs to one user intent, not one HTTP attempt. A network retry reuses it. A genuinely new click after the user changes the cart gets a new key. Disabling the button is still good interface behavior. It is not a correctness guarantee. Two tabs can submit. A client can retry. A timeout can hide a successful response. Correctness must survive outside the DOM. ## Versioning is mostly about restraint Teams often imagine API versioning as `/v1`, `/v2`, then a heroic migration. Most healthy evolution is much less dramatic. Adding an optional field is usually safe. Adding a new enum value may not be safe if the frontend uses an exhaustive switch and has no fallback. Renaming a field is breaking. Changing `null` to an omitted property can be breaking. Turning cents into decimal currency units while keeping the field name is definitely breaking, and especially unpleasant because the value still looks valid. My default rule is additive evolution: - add before removing; - let old and new clients coexist; - measure whether the old field is still used; - remove only after the migration is complete. For a rename, the backend can temporarily return both fields: ```json { "totalAmountCents": 4299, "total": { "amount": 42.99, "currency": "CAD" } } ``` The frontend moves to `total`. Telemetry confirms old consumers have disappeared. Only then does `totalAmountCents` go away. That overlap can feel untidy. It is also much cheaper than requiring every deployed client to change at the same instant. ## Dates and money expose weak contracts quickly Two values deserve suspicion at every API boundary: dates and money. `42.99` is not a complete monetary value. Which currency? Is it a floating-point amount or a display representation? Can tax introduce more precision? A safer contract sends an integer in minor units or a decimal string, plus an explicit currency. Likewise, `2026-09-26` is a calendar date, while `2026-09-26T14:30:00Z` is an instant. They are not interchangeable. A delivery day may intentionally have no timezone. An order creation timestamp absolutely does. The frontend should not have to infer these semantics from a field name. Good contracts make units and meaning boringly explicit. ## Generate types, but keep a runtime boundary OpenAPI, GraphQL code generation, tRPC, and shared schema packages can remove a large amount of duplicated typing. I like that. If the server already knows the response shape, the frontend should not retype it from memory. But generated types answer a build-time question: do these codebases agree on the declared contract? Runtime validation answers a different question: did this particular response satisfy it? You may need both. A generated client keeps everyday development fast. Runtime parsing protects the important places where deployment skew, stale clients, proxies, or external integrations can make reality differ from the declaration. The useful architecture is not "validate everything twice." It is to choose where a contract deserves enforcement and make that choice visible. ## The UI should consume decisions, not transport details A component should not contain a switch over raw status codes, parse arbitrary error bodies, or know that one endpoint wraps data under `result` while another does not. Put that translation in the API layer: ```typescript type CreateOrderResult = | { ok: true; order: Order } | { ok: false; reason: 'cart-changed' | 'out-of-stock' | 'invalid-address' }; ``` Now the UI handles product outcomes. The API client handles HTTP, schemas, and server problem codes. The backend handles validation and business rules. The boundaries line up with the questions each layer can answer. That is the part I care about most. Type safety is useful, but the real goal is not a beautiful generated interface. It is making failure unsurprising. The next article goes one layer deeper. Once the API accepts "create order," the database has to preserve customers, orders, products, and their relationships without letting them contradict each other. If your frontend has to guess what an API error means, send me the shape of that guess. Those awkward branches are usually the clearest map of where the contract needs work. --- # What Actually Happens After fetch() Canonical: https://ma-x.im/blog/full-stack-after-fetch Author: Maksym Kuzmitskyi Published: Sep 24, 2026 A user clicks **Place order**. Your component calls `fetch('/orders')`. A moment later, it either receives JSON or lands in `catch`. That can feel like one operation. It is not even close. Between the click and the response, the request may cross a DNS resolver, an encrypted connection, a CDN, a load balancer, an application process, a cache, and a database. Then the response has to travel back through most of that chain. Any link can be slow, unavailable, misconfigured, or perfectly healthy while the next one is failing. Frontend engineers do not need to become network engineers to work with this well. But we do need a useful picture of what happens after `fetch()`. Without it, every failure becomes "the API is broken," and that sentence is usually too vague to help anyone. So let me follow one request all the way through. ## Start with the URL Imagine the browser is about to send this: ```typescript await fetch('https://api.shop.example/orders', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cartId: 'cart_42' }), }); ``` Before any application code runs, the browser has several questions to answer: - Where is `api.shop.example`? - Can I establish a secure connection to it? - Which machine should receive this request? - Is there already a connection I can reuse? The URL is not an address a network understands directly. It is a human-readable instruction that has to be resolved into infrastructure. ## DNS finds the entrance DNS turns `api.shop.example` into an IP address, or more often into another hostname that eventually leads to one. The browser first checks caches: its own, the operating system's, perhaps the local network's. If there is no usable answer, a DNS resolver looks up the records. The final result may point directly to a server, but production systems often point to a CDN or load balancer instead. This is the first useful debugging boundary. If DNS is wrong, your backend can be completely healthy and still receive nothing. The browser may report `DNS_PROBE_FINISHED_NXDOMAIN`, while an application dashboard shows zero errors because the request never reached the application. That distinction matters. "No server logs" does not always mean "the browser did not send it." It may mean the browser could not find the server. ## The browser creates a secure connection Once the browser has an address, it needs a connection. With HTTP/1.1 or HTTP/2, that normally means TCP. With HTTP/3, it uses QUIC over UDP. The transport details differ, but the practical goal is the same: create a reliable path for exchanging data. Because the URL uses HTTPS, TLS also has to establish trust and encryption. The server presents a certificate for the domain. The browser checks that the certificate is valid, trusted, not expired, and actually covers `api.shop.example`. If that fails, React never gets an HTTP status. There is no `502` response to inspect. The secure conversation did not begin. This is why "network error" is such an unhelpful bucket in frontend code. It can mean offline Wi-Fi, DNS failure, TLS failure, a blocked connection, a proxy problem, or a request cancelled by our own code. Those failures happen before an API can return a neat JSON error. ## The first machine may not be your backend Suppose DNS and TLS work. The request reaches the public edge of the system. That edge might be a CDN such as CloudFront or Cloudflare. Static files can be returned there without touching the application. Dynamic requests usually continue inward, but the edge can still enforce rate limits, reject suspicious traffic, terminate TLS, or attach routing headers. Next may come a reverse proxy or load balancer. Its job is not to understand the shopping cart. It decides which healthy application instance should receive the request. ```text browser -> DNS -> secure connection -> CDN / edge -> load balancer -> application instance ``` This is where one public API becomes many private processes. The user sees `api.shop.example`. Behind it, five application instances may be serving traffic. A health check tells the load balancer which instances are ready. If one process crashes, new requests go elsewhere. That sounds like an infrastructure detail until application state lives only in the memory of one instance. Then the first request creates a checkout session on server A, the second lands on server B, and the session appears to have vanished. Horizontal scaling has exposed an application design problem. We will return to that later in this series. For now, the important point is simple: a domain name does not identify one process. ## Now the application gets a turn Only after all of that does the request reach the route handler we usually call "the backend." The application parses the body, authenticates the user, checks authorization, validates the input, and decides what operation "create order" means. It may call another service. It may read Redis. It may open a database transaction. It may publish a job to a queue. For our order, the simplified path could be: ```text validate request -> load cart -> confirm current prices -> reserve inventory -> create order -> return order id ``` Each arrow is another boundary and another possible failure. This is why a backend can be "up" while a request still fails. The process responds to health checks, but the database connection pool is exhausted. Or Redis is unavailable. Or the inventory service times out. A green server is not the same thing as a successful operation. ## The database is not just storage at the end The database often decides whether the whole operation is trustworthy. Creating an order may require several writes that must succeed together: insert the order, reserve stock, and record the payment attempt. If two writes succeed and the third fails, we do not want half an order. A transaction gives the backend a boundary: commit the whole change, or roll it back. The query also has a cost. Missing indexes can turn a small lookup into a scan across millions of rows. A lock held by another transaction can make a fast query wait. Too many concurrent requests can exhaust the connection pool even when the database itself still has CPU available. From the browser, all three may look like a slow spinner. That is the recurring theme of this journey: the UI sees the total time, not the layer that spent it. ## The response walks back through the system When the application finishes, it returns an HTTP response. That response passes back through the load balancer and edge, crosses the encrypted connection, and reaches the browser. Then `fetch()` does something that still catches people: it resolves for HTTP errors. A `400` or `500` is a successful network exchange, so the promise resolves. We have to inspect `response.ok` ourselves. ```typescript const response = await fetch('/orders', options); if (!response.ok) { const problem = await response.json(); throw new OrderRequestError(response.status, problem); } return response.json(); ``` The promise rejects when the browser cannot complete the exchange at all, or when our code aborts it. Those are different categories from a backend that deliberately returned a validation error. A useful frontend error model keeps that distinction: - **No response:** connection, DNS, TLS, offline state, timeout, or cancellation. - **HTTP response with a problem:** authentication, validation, conflict, rate limit, or server failure. - **Successful response with unexpected data:** contract or parsing failure. One generic "Something went wrong" may be the right user-facing sentence. It should not be the only thing the system knows. ## A request id connects the pieces There is one small habit that makes this entire chain easier to reason about: give every request a correlation id. The edge can create it, or the frontend can send one. Each service includes it in logs, and the response returns it as a header. Now a bug report can connect one browser event to the exact load-balancer entry, application log, and database operation. ```typescript const requestId = crypto.randomUUID(); await fetch('/orders', { ...options, headers: { ...options.headers, 'X-Request-Id': requestId, }, }); ``` That id is not observability by itself. But it gives the layers a shared thread, which is much better than comparing timestamps and hoping two errors belong to the same click. ## What this changes in frontend code Understanding the path does not mean the component should know about DNS or load balancers. Quite the opposite. It helps us create a cleaner boundary around network work. A UI should know whether an action is pending, whether it can be retried, and what the user can do next. The API client should distinguish no-response failures from HTTP problems and invalid payloads. The backend should return structured errors. Infrastructure should expose enough context to trace the request across layers. Each layer owns a different question. > The browser sees one request. The system sees a chain of contracts. Once that picture is clear, several full-stack topics stop feeling unrelated. Idempotency protects a repeated request. Transactions protect a multi-step write. Redis changes where data is read. A load balancer changes where code runs. Observability connects the path after something fails. They are all answers to the same question: what must stay true while a request crosses the system? The next article follows the request into the application and focuses on the first contract we control directly: the API boundary. If there is a part of the request path that still feels like a black box, tell me where you lose the thread. That is probably the part of this guide worth opening up next. --- # AI Code Review Should Sound Like a Careful Engineer Canonical: https://ma-x.im/blog/github-ai-pr-reviewer Author: Maksym Kuzmitskyi Published: Sep 22, 2026 There is a strange cost to a queue of Pull Requests: it rarely looks like a problem. One PR can be reviewed in the evening. The second between meetings. The third looks small, just dependencies. The fourth already passed CI, so it probably feels fine. Very quickly, review stops being focused engineering work and becomes a memory task: where exactly am I expected to pay attention? The routine itself was not what bothered me. Review is part of the job. What bothered me was that the most repeatable risks require the most boring kind of attention. Did an auth guard disappear? Did unsafe `innerHTML` show up? Did a dependency update add an install lifecycle script? Was an export removed? Did an API, schema, or config contract change in a way the author may not have noticed? These are not the places where you need a genius reviewer. They are the places where it is unpleasantly easy to miss something. So I built a personal AI reviewer for GitHub Pull Requests. Not because I wanted to replace human review. And definitely not because I wanted another bot leaving comments like "Potential security issue." I wanted a tool that keeps a baseline level of risk attention running consistently, while still speaking to the author like a reasonable engineer. ## I did not want a rule bot The simplest version of this tool is obvious: scan the diff for patterns, leave comments. That becomes bad review very quickly. The machine sees a fragment. It does not know the whole product history, the migration path, the team's local agreement, the temporary rollout plan, or why the author made that trade-off. If it writes with too much certainty, it starts sounding smarter than it has earned the right to be. At the same time, I did not want a harmless toy that is afraid to say something real. Good review does not have to be soft. If a PR removes a permission guard or adds process execution from user-controlled input, the reviewer should stop and ask for changes. But even then, the job of the comment is to move the author toward verification and a decision, not to drop a red flag and leave. The principle became: > Automated review should be specific, checkable, and modest about what it knows. That modesty is not politeness theater. It reflects the reality of review. The reviewer often sees the diff, but not the whole context. ## The local reviewer The tool lives locally, outside cloned repositories. That was the first practical decision. I did not want a normal repository cleanup, reinstall, or update to accidentally delete the system that watches my review queue. It runs through macOS `launchd`: it starts after login and then runs a review cycle roughly once an hour. Each cycle finds GitHub Pull Requests where my account is listed as a requested reviewer. This is not a global GitHub scanner. It is my personal review inbox. If someone explicitly asks me to review a PR, the tool can put it into its queue. Before reviewing, it waits until the checks for the current head commit are green. That constraint matters. If CI is already failing, an automated reviewer tends to comment on noise: formatting, types, broken tests, obvious things the author needs to fix before a real review. I want the tool to review something close to a human-reviewable state, not compete with CI. It also stores local state: which PRs it has already reviewed and which head SHA it saw at the time. If new commits are pushed to a previously reviewed PR, the agent reviews it again, even if the requested-reviewer event did not happen again. That small detail changes the behavior. A PR is not a static document. The author may respond to feedback, rewrite part of the logic, update dependencies, or fix tests. A reviewer that only remembers "I have seen this PR" becomes blind to the most important part of the process: what changed after the first round. ## What it does, and what it does not do The main path is simple: the agent reads the diff and publishes comments on the relevant diff lines. If GitHub does not accept an inline comment — for example, because the diff position is no longer valid or the API cannot attach the note to that line — it falls back to a body-only review and preserves the meaning of the finding. That matters more than it sounds. Bad automation often breaks on a small API detail and silently drops the useful signal. I would rather leave a body review than pretend there was nothing to say. The checks are intentionally simple and explainable: dynamic code execution, unsafe `innerHTML`, process execution, install lifecycle scripts, removed exports, risky API/schema/config changes, and disappearing auth or permission guards. This is not a complete model of code quality. It is not a senior engineer replacement. It is a first, repeatable pass over known classes of risk. There is also a boundary around approval. The agent does not approve PRs with unresolved review threads; it leaves a comment instead. It can auto-approve safe dependency-bot PRs, but normal PRs are limited by the number of reviews per run. I want automation to help, not turn into an uncontrolled conveyor belt of approvals. ## The most important iteration was the comment style Technically, building the loop was not the most interesting part. Finding PRs, checking requested reviewers, waiting for checks, reading diffs, and leaving reviews are all annoying in the details, but conceptually straightforward. The most important iteration was the language of the comments. Early automated review text tends to collapse into dry warnings: "Potential security issue." "Validate compatibility." "This may break consumers." Those comments can be technically correct and still be bad review. They do not tell the author what to check. They do not connect the concern to the specific change. They sound like a confident alarm with missing context. So I rewrote the rules around how comments should be phrased. A comment should name the specific risk, attach it to the change, explain why the diff raised concern, and ask a question the author can answer. For example, instead of "Validate compatibility," a better comment is: > Can you confirm whether this exported type is still used by downstream packages? I could be missing the migration path, but removing it here looks like it may break consumers outside this repo. The value is not that the sentence became softer. The value is that it gives the author a concrete check: downstream usage and migration path. Another example: > Can we make sure this HTML is sanitized before it reaches `dangerouslySetInnerHTML`? The diff makes the rendered value look closer to user-controlled content than before. That does not scream "security bug." But the risk is direct: sanitization and user-controlled content. One more: > Can you confirm this route still requires the same permission check? I see the guard moved out of this branch, and I want to make sure the access rule did not become implicit. This is the tone I want. The reviewer does not say, "you removed auth." It says: I see a change, it looks like a risk, help confirm the invariant. That is the difference between humanizing text and pretending to be human. The goal is not to disguise AI as a teammate. The goal is to automate the best parts of good engineering review: specificity, respect for context, an argument behind the concern, and the willingness to be wrong. ## Why the control panel matters Automation that runs somewhere in the background can become a source of anxiety very quickly. Is it checking anything? Did it crash? Is it writing a comment right now? Did it skip a PR because checks were red, or because it did not see the requested reviewer? Has it already reviewed this SHA? Did a new commit appear after the last run? If those questions are hard to answer, the tool saves time in one place and spends trust in another. So the reviewer has a local browser control panel, available only on localhost. It shows whether the service is running, the `launchd` state, and the current process state. It has Start, Stop, Restart, Refresh, and logs. The panel shows the timer until the next review cycle, the last run time, and whether a cycle is currently active. It has an event feed: PRs found, skips, errors, published reviews, and links to the PR or review. It also shows counters and a tracked PR table: total tracked PRs, how many are visible, how many need rereview, which SHA was reviewed, and which SHA appeared later. The logs are not hidden. I can open the service output and see what actually happened. That is not decoration. Observability is part of the product. If automation leaves comments in your name, you should not need a terminal investigation to understand what it did. ## The boundaries I want to keep I do not want a reviewer that pretends to understand everything. It does not know the product better than the team. It should not approve normal PRs just because it did not find a risk pattern. It should not argue with the author instead of a person. It should not turn a simple dependency update into a philosophical review if the known safe conditions are satisfied. Its value is narrower: it looks consistently at classes of risk that are easy to miss, waits for a reasonable check state, remembers reviewed SHAs, returns after new commits, and makes its comments visible inside the conversation humans are already having. Most importantly, it does not have to be perfect to be useful. But it does have to be inspectable. I need to see what it did, why it skipped a PR, which SHA it reviewed, where it posted the review, and when the inline-comment fallback became a body-only review. Mature automation should not feel like magic. Magic is hard to debug. ## What I built, really I did not start with the idea of replacing review. I started with the feeling that some attention could become continuous. A Pull Request is still a conversation between engineers. The author knows the context of the change. The reviewer sees risk from the outside. CI checks formal properties. An agent can add another layer: a repeatable pass over known dangerous areas, with comments that help the author respond in a useful way. That is the shape I like. Not a cold judge. Not autopilot approvals. Not a bot that writes "Potential issue" and disappears. More like a careful junior reviewer: arrives on time, remembers what it saw, asks specific questions, and leaves the decision to people. The value is not that AI replaced a reviewer. The value is that attention to risk became regular, observable, and part of the process. That is the kind of automation I am interested in: limited, checkable, useful to humans, and modest enough not to get in the way of a normal engineering conversation. If you're building an AI reviewer of your own, I'd be curious to hear where you draw the line between useful vigilance and automated noise. Reach out and tell me what earned your trust, and what lost it. --- # The Columns Hidden Inside Your Customer Reviews Canonical: https://ma-x.im/blog/jev-human-text-to-data Author: Maksym Kuzmitskyi Published: Sep 17, 2026 # The Columns Hidden Inside Your Customer Reviews A restaurant has ten thousand reviews. Its dashboard has an average rating, a monthly trend, and a search box. Somewhere inside those reviews is a much more useful answer: people like the food, but delivery packaging keeps ruining it. There is no column for that. That is what interests me about TypeSafe's Jev. I want to look at it as a way to turn human text into data: reviews, comments, forum discussions, the messy sentences that contain signals our databases cannot currently query. I recently wrote about a [restaurant procurement agent](/blog/silpo-ai-factory-horeca-procurement-agent). That project started with operational inputs: menus, portions, inventory, supplier availability. Here I want to look at another side of the same business. Customers are already describing problems. How do those descriptions become something an engineer can aggregate and a restaurant owner can investigate? This is an architecture I would explore, not a report from a deployed Jev integration. The examples below are hypothetical. I haven't run a benchmark on restaurant reviews. ## A prep station for language Think about a restaurant kitchen before service. Ingredients arrive in different shapes. Someone washes, separates, portions, and puts them into containers the rest of the kitchen can work with. I see a similar job between raw text and analytics. A review arrives as a paragraph. The next stage produces a few useful attributes. Conventional software groups and counts them. A person, or a more capable language model with access to the evidence, can then work on the interpretation. The distinction matters because [Jev gives up free-form string generation](https://typesafe.ai/blog/introducing-system-one-models-and-jev). TypeSafe presents it as a model for fast, structured decisions. It doesn't browse Reddit for you or write the research report. You supply the material and the questions. Its [three question types](https://docs.typesafe.ai/primitives) are Noul, a yes/no probability; Choice, a selection from supplied alternatives with probabilities; and Score, a position along defined levels. That is enough to add many useful attributes to an existing record. It doesn't make it an arbitrary extractor of new names, quotations, or product identifiers. If I need the exact restaurant name, I would preferably get it from source metadata. If I need an exact quotation, I would preserve the original text. Asking a classifier to choose between known categories is a different operation from asking a model to discover and return an unrestricted string. > The interesting AI feature is the column you couldn't populate before. ## One review can contain several different problems Consider this invented delivery review: *“The noodles were great, but the sauce leaked through the bag. This is the second time. I'd order again if they changed the containers.”* A single positive/negative label throws away most of what makes that useful. I would ask whether the author praises the food, reports a packaging failure, describes a repeated problem, and makes a future order conditional on a change. Those signals can coexist. Forcing them into one winning category would lose information before the analysis even starts. At the application boundary, a normalized record might look like this. The values are illustrative, and this is my storage shape, not a Jev API response: ```typescript type ReviewSignals = { reviewId: string; restaurantId: string; source: 'delivery' | 'direct' | 'forum'; publishedAt: string; foodPraiseProbability: number; packagingFailureProbability: number; repeatProblemProbability: number; conditionalReturnProbability: number; modelVersion: string; questionSetVersion: string; }; ``` The first four fields come from ingestion. The next four are model judgments. The last two let me explain how those judgments were produced. I would keep the raw review linked to this row. An owner clicking “packaging complaints increased” should be able to read the evidence, including the examples the classifier got wrong. Question wording deserves as much care as the schema. “Is packaging bad?” invites a broad interpretation. “Does the author report that the container or bag leaked, broke, or failed to contain the food?” defines an observable claim. Even then, a complaint describes the author's account. It doesn't establish which party caused the failure. A crushed meal might involve the container, the courier, or both. I would resist naming the field `restaurant_packaging_defect` unless the evidence actually supports that attribution. ## Parallel questions, then parallel records There are two kinds of parallel work here, and I would keep them separate in the design. For one review, ask all the independent questions together. TypeSafe documents that questions in a request share the same input state and are evaluated independently. One answer does not become context for the next. If a later question requires information fetched using an earlier answer, that needs another step. [Question semantics](https://docs.typesafe.ai/primitives). Across the dataset, workers process different reviews concurrently. That is our ingestion and scheduling problem: queues, bounded concurrency, retries, rate limits, and resumable jobs. Parallel question evaluation doesn't promise unlimited corpus throughput. The pipeline I have in mind is quite ordinary: ```text Source exports / permitted APIs ↓ Normalize records, retain context, remove duplicates ↓ Queue → workers → Jev questions for each record ↓ Versioned semantic attributes + original record links ↓ SQL aggregates → evidence review → optional written report ``` I would give each result a key built from the source record, content hash, model version, and question-set version. Retrying a request should not create a second observation in the dashboard. Changing a question should not silently overwrite the previous measurement. The kitchen analogy has a useful limit here. You can prepare ingredients in parallel, but putting twice as many cooks in one doorway won't double dinner service. The slowest part might be collecting the data, resolving duplicates, or reviewing ambiguous examples. ## Let SQL do the counting Once those columns exist, familiar tools become useful again. Here is an illustrative PostgreSQL query over enriched delivery reviews. The 0.8 cutoff is a placeholder to validate against labeled examples, not a recommended universal threshold: ```sql SELECT restaurant_id, date_trunc('month', published_at) AS month, count(*) AS analyzed_reviews, count(*) FILTER ( WHERE packaging_failure_probability >= 0.8 ) AS flagged_packaging_reviews, round( 100.0 * count(*) FILTER ( WHERE packaging_failure_probability >= 0.8 ) / count(*), 1 ) AS flagged_share_pct FROM review_signals WHERE source = 'delivery' AND model_version = :model_version AND question_set_version = :question_set_version GROUP BY restaurant_id, date_trunc('month', published_at); ``` That last number is the share of analyzed reviews flagged by this rule. It is not the percentage of orders with failed packaging. We don't have all orders in this table. We have people who wrote reviews, within whatever collection process we used. I'd put that distinction in the dashboard label. Otherwise a technically correct query becomes a misleading product feature. The next useful question might be whether flagged reviews concentrate around one location, a delivery channel, or a period after a container change. Those joins require reliable operational metadata. Jev cannot supply missing order history by interpreting a paragraph more confidently. ## The same idea works for products Now replace the restaurant with a coffee grinder. “Loud” can mean several things. One owner mentions the noise and still recommends it. Another says it wakes their child and explains why they returned it. A third repeats something they heard without owning the product. I would want separate signals for claimed ownership, noise complaints, reported returns, and explicit reasons for returning. These are much more useful than a single sentiment score when deciding what to investigate about a product. The model still only judges what the text supports. “The author claims to own it” is a defensible label. “Verified purchaser” requires purchase evidence outside the text. There is also a discovery problem. A fixed question set finds the issues I thought to ask about. If a new failure mode appears and none of my questions cover it, a cheap classifier can miss it at enormous scale. I would regularly inspect a diverse sample of unflagged and uncertain records, and use open-ended analysis to propose new categories. Then I would label examples, evaluate the revised questions, and backfill comparable periods. Otherwise the dashboard can look stable simply because its vocabulary stopped evolving. ## Reddit is a research corpus, with a boundary The Reddit version interests me even more: a deliberately scoped collection of posts and comments about a product or buying decision. Suppose I want to investigate why people discussing home espresso equipment regret a purchase. I would define the communities, time window, collection method, and inclusion criteria first. Then I could classify first-hand reports, price objections, maintenance complaints, and explicit alternatives people are considering. A comment like “same here” needs its parent. A sarcastic reply can reverse the apparent meaning. I would pass the relevant context with the comment and make clear which text is the target of the judgment. I would also retain thread relationships so that one lively discussion doesn't masquerade as fifty independent purchasing experiences. Collection needs its own implementation, using access appropriate to the source. Jev begins after we have the records; it doesn't solve that access problem. What could the output honestly say? Something like: “Within this collected set of discussions, maintenance complaints were more frequent among posts describing regret.” It could not establish the percentage of all espresso-machine owners who regret buying one. A million comments still reflect the people, communities, search terms, and periods that brought those comments into the dataset. > Scale makes a sample bigger. It doesn't automatically make it representative. Honestly, this is where I think the engineering gets interesting. Processing the text cheaply is only one part. Defining what the resulting number means is the part the product has to get right. ## The price changes what is worth trying As checked on September 17, 2026, TypeSafe's [parallel-questions cookbook](https://docs.typesafe.ai/cookbooks/parallel_questions) uses a Jev input price of $0.042 per million tokens and zero output-token cost. That is a published pricing assumption, not my measured bill or a guarantee of future pricing. At that rate, a hypothetical million records averaging 1,000 total billed input tokens each would cost $42 for model input. “Total” matters: the budget must include the text, context, questions, and other billed request content. Collection, storage, retries, evaluation, and human review are separate costs. That makes a broad enrichment pass worth considering. I would still measure tokens and throughput on a realistic pilot before extrapolating. The same cookbook reports roughly 12.2× lower cost and 10× lower latency for batching thirteen questions over one document instead of asking them separately. That is a vendor example of batching, not evidence that my million-review pipeline will finish ten times faster. For me, the appealing consequence is practical: I can consider retaining several narrowly defined signals per record instead of asking one overloaded question and hoping its answer will support every future analysis. ## Correct types still need correct judgments TypeSafe's launch discussion distinguishes schema correctness from decision correctness. A model constrained to valid choices can still choose the wrong one. Its “zero hallucinations” language should be read in that narrower sense. [Launch explanation](https://typesafe.ai/blog/introducing-system-one-models-and-jev). I would start with a labeled evaluation set spanning clear examples, mixed opinions, sarcasm, short replies, and the languages actually present in the corpus. For each signal, I would check false positives and missed cases. A packaging-complaint filter and a claim about purchase intent may need different acceptance rules. A returned probability also deserves validation on that specific task. I wouldn't interpret every 0.9 as a demonstrated 90% correctness rate in my data. TypeSafe's [confidence documentation](https://docs.typesafe.ai/confidence) explains the supplied measures; whether they support my operating threshold still needs evidence from the intended workload. Ambiguous cases can remain uncertain, go to human review, or receive a second analysis. If I exclude them from a chart, I want their count visible. Quietly dropping the hard cases can make a trend look cleaner than the underlying evidence. Finally, a writing model should receive computed aggregates, definitions, coverage limitations, and selected source excerpts. It can help explain the results. It should not invent the counts, turn a correlation into a cause, or claim that a few selected quotes prove a population-wide trend. ## The useful thing is what becomes queryable I keep coming back to that restaurant with ten thousand reviews. The review text already contains more detail than the star rating can express. What I want is a way to preserve some of that detail in a form ordinary software can work with, while keeping the original words close enough to challenge the interpretation. That is the role I would give Jev: a focused processing stage between human language and the database. The report comes later. First I want to know which columns are worth creating, how reliably we can populate them, and what decisions they actually help someone make. If you have a pile of reviews or community discussions that your current dashboard can't explain, I'd be interested to hear which missing column you wish you could query. --- # Earned Autonomy: Comparing My Agent Workflow with a Corporate Experiment Canonical: https://ma-x.im/blog/agentic-development-at-work Author: Maksym Kuzmitskyi Published: Sep 16, 2026 I came to Liberty roughly six months ago with a fairly strong opinion about what an AI coding agent should be doing. Not autocomplete. Not a faster way to generate a function. Not a chat window that occasionally knows how to edit a file. I had been building a working environment in which an agent could participate in most of the delivery lifecycle: understand a task, inspect the code, make a plan, change a small slice, run the right checks, prepare a pull request, and help work through what happened afterwards. Now Liberty is starting to explore a more formal way of working with agents. The approach uses reusable agent skills and a more explicit, specification-driven sequence around planning, implementation, validation, and learning. I find the comparison more useful than either approach in isolation. I already have a workflow that works for me. The company experiment gives me a chance to ask a harder question: which parts of that workflow are genuinely valuable, and which parts only feel valuable because I built them myself? > The interesting question is not whether an agent can act autonomously. It is whether its autonomy has been earned by context, rules, and evidence. ## What I brought with me My approach is based on earned autonomy. That phrase matters. I don't mean giving an agent unlimited freedom and hoping that a capable model will make good decisions. I mean giving it room to move inside boundaries that are explicit enough to be checked. In a typical task, the agent starts with a goal from a ticket or a conversation. It researches the relevant code and nearby context. It tries to find the code that actually controls the behavior instead of editing the first file that looks related. It identifies constraints, forms a local hypothesis about how the change should work, and chooses a cheap check that could prove the hypothesis wrong. Then it changes a small slice and validates that change immediately. Broader checks come afterwards. When the work is ready, the agent can prepare a branch and a draft pull request, help investigate CI failures, and respond to review feedback. The important part is not the length of that list. It is that the list describes a connected workflow rather than a collection of isolated prompts. ### Context before cleverness The workflow depends on several levels of context. There are personal rules about how I want an agent to work, shared engineering standards, and repository-specific instructions. More local and more current information should win over a general preference. Memory helps the agent continue across sessions, but memory is not authority. The current code, tests, documentation, and actual tool output are more trustworthy than something saved from a previous conversation. That distinction is easy to state and surprisingly important in practice. A remembered convention can be stale. A test failure in front of you cannot be argued away by a paragraph written last month. ### Tools instead of context theatre I also prefer integrations over manually copying the world into a prompt. When permitted, the agent can work with task systems, documentation, source code, tests, and pull requests through connected tools. The benefit is not that the agent suddenly knows everything. It is that the relevant evidence can stay close to the task. Requirements, implementation, and validation do not have to be reconstructed from a chain of pasted fragments every time. That still requires judgment. An integration can expose the wrong context just as efficiently as the right one. Tools expand an agent's reach; they don't decide what deserves attention. ### The human is still the owner An agent can research, edit, test, and prepare changes. It does not own the requirements, the architecture decision, the approval, or the final review. That is not a ceremonial disclaimer. It is part of the design. Autonomy is useful when it removes mechanical coordination and preserves human attention for decisions that carry real risk. If a workflow asks a person to approve every harmless step, it has not created autonomy. It has created a queue of tiny approvals. ## What Liberty is exploring The approach Liberty is beginning to investigate puts more structure around the work. It uses reusable agent skills: packages of instructions and working patterns that help an agent perform a particular kind of engineering task more consistently. A skill might support context discovery, planning, implementation, debugging, or review. It is not another intelligent employee. It is a reusable description of how to approach a task, with the aim of making useful practices easier to repeat across engineers and repositories. The broader lifecycle is more explicit than the one I normally follow informally: 1. Prepare the relevant instructions and context. 2. Clarify or create a specification. 3. Produce a plan. 4. Review the plan. 5. Implement the change. 6. Validate the result. 7. Record observations about quality and usability. There is a lot to like here. A team cannot rely on one engineer having spent months tuning a personal workflow. Reusable skills offer a possible common language. They might help engineers with different levels of experience start from a better baseline, and they create a clearer shape for comparing what happened across tasks. The experiment is still early. Liberty is exploring and piloting this kind of systematic approach; it has not produced a final company-wide process or a conclusion about fully autonomous software development. That distinction matters because the value of the experiment is precisely that the result is not known yet. ## Where the approaches meet The overlap is larger than the difference. Both approaches assume that an agent needs good context before it needs more freedom. Both treat clear requirements, planning, small changes, tests, and human review as controls rather than optional polish. Both value reusable knowledge, because repeating the same explanation in every session is a poor use of anyone's time. Both also suggest that speed of generation is an incomplete measure. A change that appears quickly but needs extensive correction is not necessarily faster. The useful question includes quality, traceability, review effort, and what happens when the next engineer has to understand the result. That is why I don't see reusable skills as the opposite of my workflow. They may be a way to package some of its useful habits so that they are less dependent on personal configuration. They may also expose parts of my process that are too implicit to teach to anyone else. ## Where I am cautious The concerns I have are hypotheses, not verdicts. The experiment needs to test them. The first is process proportionality. A full specification, plan, review, implementation, and reporting sequence makes sense for risky or complex work. For a tiny, obvious change, it may create more text and more transitions than value. A good engineering process should scale with the risk of the task, not apply the same ceremony to everything. The second is that artifacts can become the goal. A detailed specification can still describe a wrong assumption. An agent can produce a polished plan for a problem nobody actually has. Evidence and useful questions matter more than document length. The third is the cost of formal stopping points. If a person must confirm every safe step, the workflow can become a stream of interruptions. My current model delegates many low-risk decisions through standing rules and brings a human in where the risk changes. I want to know whether a more formal process can preserve that shape. There is also a locality problem. A reusable skill can explain how to plan or validate in general, but it cannot automatically know a repository's architecture, conventions, environmental limits, or history of decisions. Without that local layer, a skill can produce work that sounds reasonable and still does not belong in the system. Finally, attribution will be difficult. If a task goes well, the cause might be the skill, the repository instructions, the connected tools, the tests, the quality of the original request, or the engineer's own experience. A fair experiment has to separate those effects as much as it reasonably can. Reporting has a cost too. Tracking corrections, defects, rework, and subjective experience is necessary for an honest comparison. But if reporting takes a meaningful amount of engineering time, that time is part of the result, not an inconvenient detail to hide. ## What I want to learn I am not joining this experiment to prove that my existing approach is already the answer. That would make the comparison pointless. I want to find out which skills prevent mistakes that would otherwise reach review. Where does an explicit specification improve the result, and where does it add ceremony? Does the process help an agent recover context in a new session? How much human correction is actually required? What happens to review quality and cost? The useful comparison will come from real tasks, not from a polished demonstration. For each task, I would want to understand whether the acceptance criteria were met, how much correction and rework appeared, which defects were found by the agent, CI, or a person, and which parts of the framework produced observable value. I would also separate ordinary engineering effort from framework overhead and reporting time. Those are different costs. Combining them into one number would make the result look cleaner while making it less informative. The data will need to be aggregated and anonymized. The goal is to learn about the workflow, not to publish internal details or turn a small experiment into a claim about the whole company. ## This is the beginning, not the conclusion There is a temptation to choose a winner early. Personal workflows feel concrete because you can see their history. Formal frameworks feel credible because they have names, stages, and reusable artifacts. Neither feeling is evidence. My current expectation is that the useful outcome will be a combination. Some skills may capture practices worth making more consistent. Some formal stages may be valuable only for certain classes of work. Some of my existing rules may turn out to be personal preferences rather than durable engineering principles. That is a good result. The point is not to protect a workflow because I built it, or to accept a framework because it arrived with a process diagram. The point is to discover which controls help an agent do better work while leaving people responsible for the decisions that matter. I am at the beginning of that comparison now. Later, once there is enough evidence and the results have been checked for accuracy and confidentiality, I'll come back with what actually happened: where reusable skills helped, where they added friction, and what I changed in my own way of working. Until then, I am keeping the conclusion deliberately open. An agent does not become trustworthy because it has more freedom, more documents, or more steps. It becomes more trustworthy when the system around it makes good decisions easier to verify. If you've been comparing a personal agent workflow with a more formal team process, I'd be interested in what you measured. The difference between a convincing demo and a useful engineering system usually appears only after the first few ordinary tasks. --- # The Cart Was Not the Product: Building a HoReCa Procurement Agent for Silpo AI Factory Canonical: https://ma-x.im/blog/silpo-ai-factory-horeca-procurement-agent Author: Maksym Kuzmitskyi Published: Sep 15, 2026 The obvious idea was also the least interesting one. The Silpo AI Factory hackathon gave participants an unusually tempting setup: AI, an official MCP server from a large grocery retailer, product search, carts, delivery, purchase history, and the requirement to build an agent that could actually use tools. The easy version almost writes itself. A user asks what to buy. AI suggests products. The app puts them into a cart. Useful? Maybe. Interesting? Not enough. That shape quickly becomes another AI shopping chat. I wanted to avoid that, partly because the hackathon itself was clearly nudging people toward something more agentic: not text generation around commerce, but a system where the agent receives context, uses tools, and helps complete a concrete task. The project that came out of that became a HoReCa Procurement Agent: an AI-assisted procurement cockpit for a small restaurant that also handles catering and events. Links for the project: - Hackathon: [Silpo AI Factory](https://ai-factory.silpo.ua/) - Official Silpo MCP: [ai-factory.silpo.ua/docs/mcp](https://ai-factory.silpo.ua/docs/mcp) - Live demo: [horeca-nine-alpha.vercel.app](https://horeca-nine-alpha.vercel.app/) - Source code: [github.com/MaximusFT/horeca](https://github.com/MaximusFT/horeca) - Demo video: [YouTube](https://youtu.be/5D2QP2OFflM) ## The shopping assistant was too small The first direction was some version of Smart Basket, AI cart, shopping assistant. It is a reasonable idea. It is also the first idea most people would reach for. That was the problem. I kept asking one question: if I remove the AI chat, what remains as a product? For a generic shopping assistant, the answer was not strong enough. The AI was doing too much of the conceptual work. The product was mostly a conversation with a cart mutation at the end. So we changed the buyer. What if the customer is not one person deciding what to eat, but a small restaurant or catering business trying to plan procurement? That changed everything. A grocery cart stopped being a list of preferences. It became the result of an operational problem: regular restaurant demand, bookings, events, guest counts, menus, recipes, inventory, incoming supply, safety stock, shelf life, and supplier availability. Now the official commerce MCP had a more precise role. It did not define the business need. It helped execute a need the system had already calculated. That boundary became the project. ## Catering was close, but not enough The first stronger version was catering procurement. Wedding. 180 guests. Menu. Recipes. Ingredients. Shopping list. Supplier cart. That already felt much better than a shopping assistant. A single change, like 180 guests becoming 200, can flow through portions, recipe quantities, ingredient demand, packages, and cart preparation. Good demo. Still not quite the product. The flaw was simple: a restaurant continues to exist between events. It still needs vegetables, meat, dairy, eggs, coffee, bread, and all the ordinary supplies of daily operations. Event demand is only one source of demand. After that correction, the model became much stronger: Regular restaurant demand + event and catering demand + safety stock - current inventory - incoming supply = procurement need. Then procurement need becomes: when to buy, which supplier products can satisfy it, what package sizes are available, what is in stock, and what should be prepared for approval. That is the point where the idea stopped being an event shopping calculator and became a procurement layer for HoReCa. > The cart is not the product. The procurement plan is the product. The cart is the final execution step. The product is the plan that explains what the business needs, when it needs it, and why. ## AI should not do the arithmetic Once the product model became clearer, another decision followed naturally: most of the important work was not AI work. Take the hero scenario. A wedding changes from 180 to 200 guests. The menu includes salmon croissants, cheese croissants, ham croissants, skewers, salads, and dessert cups. If each guest gets 0.35 salmon croissant and each croissant uses a known amount of salmon, that is not a prompt. That is arithmetic. The same is true for BOM expansion, unit conversion, inventory subtraction, FEFO, safety stock, package rounding, procurement dates, and plan diffing. If an LLM calculates those numbers, the system becomes less reliable, not more intelligent. So the procurement engine became ordinary TypeScript code. It owns the critical math: restaurant demand, event demand, recipes, ingredients, inventory lots, incoming supply, shortages, purchase dates, packages, and the procurement plan. The AI got a different job: understand natural-language intent, choose application tools, explain where a number came from, help match internal ingredients to supplier products, evaluate replacements, and orchestrate a sequence of safe tool calls. AI does not calculate procurement. AI helps operate the procurement system. That was probably the most important architecture decision in the project. ## Dashboard first, agent second I also did not want the user to open a procurement system in the morning and ask an AI, "so, what is happening today?" The application should already know. It should know upcoming events, restaurant load, procurement batches, shortages, expiry risks, incoming supply, and the next actions that need attention. The agent can help explain and act, but the primary interface should be an operations dashboard, not a blank chat box. So the UI settled into four main sections: Overview, Procurement, Events, and Inventory. The agent did not become a fifth top-level screen. It became a contextual drawer: ask why a quantity is needed, explain the impact of the wedding change, find a replacement, prepare the next supplier order. That distinction matters. A chat-first system makes the user discover the product by asking questions. A cockpit should surface the current operating state before the user asks. ## Misto Kitchen made the model concrete To avoid building against abstractions, we created a synthetic restaurant: Misto Kitchen. One kitchen. Shared inventory. Around 55 seats. Regular restaurant operations. Catering and events. A 14-day planning horizon in the Europe/Kyiv business timezone. The demo events gave the system real pressure: Birthday Breakfast, Office Lunch, Private Anniversary, Tech Conference, and Wedding. The wedding became the hero flow: 180 guests to 200 guests, total event guests moving from 445 to 465. That tiny number change was useful because anyone can understand it. A manager gets a call: the wedding will have 200 people, not 180. In a manual process, that means recalculating menu portions, ingredients, inventory coverage, packaging, and supplier orders. In this system, the change creates a preview first. The user inspects the impact, then approves it. Only after approval does it become Plan v2. This is where the product became more than a planning spreadsheet. The system could explain what changed and why. ## Explainability had to be part of the model One number is not enough. If the system says "buy 31.4 kg of chicken," a real procurement manager has an immediate question: why 31.4? So provenance became part of the domain model. Each procurement line needed to explain its sources: restaurant operations, specific events, current inventory, incoming supply, safety stock, shelf-life rationale, and supplier enrichment state. The AI can summarize that explanation in human language. But it should not invent it. The source of truth is the deterministic calculation and structured provenance. This is one of those product decisions that looks like UX until you build it. Then it becomes architecture. If explanation is generated after the fact by the model, you get storytelling. If explanation is part of the calculation, you get auditability. ## The first UI was too engine-shaped After the deterministic core started working, the first noticeable product flaw was not in the math. It was in the Overview. The screen was too close to the engine. It wanted to show procurement batches, dated ingredient lines, restaurant operating days, and engine status. Those facts were correct, but they did not explain the product to a restaurant manager. So the Overview had to be rebuilt around the business story: Restaurant Operations + Events & Catering -> Combined Business Demand -> Procurement Plan -> Supplier Execution. The first viewport needed to show regular operations, the five events, upcoming deliveries, and attention items. Not because those cards are prettier. Because the user has to understand in 10-15 seconds that the system combines daily restaurant demand and event demand into one procurement plan. That was a useful reminder: a correct engine does not automatically create a clear product. There was also a very normal frontend bug. The Ask Misto drawer first looked trapped inside a narrow header. The issue was not the drawer size. A sticky header used `backdrop-filter`, which changed the containing block for `position: fixed` descendants. The fix was to render the fullscreen overlay through a React portal into `document.body`. Small bug. Good lesson. A feature can be logically correct and still be mounted in the wrong DOM and CSS context. ## Mock supplier first, live MCP later Before live Silpo access was reliable, we built the full supplier flow against a mock supplier. That was not a fake replacement for integration. It was how we protected the product model from waiting on external access. The mock supplier covered product mappings for all 38 ingredients, package sizes, prices, availability, deterministic package rounding, surplus and cost, substitution approval, cart preview, cart write, reread, reconciliation, and preservation of unrelated cart lines. The preferred salmon SKU was intentionally unavailable, with a compatible 400 g alternative, so the product could exercise replacement handling. The architecture was simple on purpose: Procurement engine -> SupplierGateway -> Mock supplier or Silpo supplier. The mock stayed as an offline fallback. It should never be described as live Silpo. When the agent arrived, it was also intentionally small. One Procurement Agent. Not Inventory Agent, Forecast Agent, Supplier Agent, Cart Agent, and Supervisor Agent. For this MVP, that would have been architecture theatre. The agent worked through application-level tools like `get_event`, `get_procurement_plan`, `explain_requirement`, `preview_event_change`, `apply_event_change`, and `prepare_supplier_order`. It did not see the whole raw MCP catalog. It did not own procurement quantities. Every tool called an application use case with its own schema and approval rules. ## Live AI was not the proof The default agent mode became `AGENT_MODE=local`. That sounds less exciting than a live model, but it was the right default for this project. It was deterministic, free, offline, used the same protected application tools, and made the demo stable enough to record. The OpenAI Responses API path was implemented as an explicit opt-in with a limited number of consecutive tool steps. But the final demo should not be described as a fully autonomous live OpenAI session. The API key was not configured in this workspace, and the protocol was covered with mocked HTTP tests. What the demo proves is still valuable: the agentic application flow, the tool orchestration, the approval boundaries, and the supplier execution path. But it is important to say what was actually tested. ## The official MCP changed the shape of the work The early generic JSON-RPC client and public docs were enough to understand the direction. They were not enough for a reliable live integration. After access, the real path required OAuth 2.1: Dynamic Client Registration, authorization code, PKCE S256, refresh token, a session-scoped provider, the official `@modelcontextprotocol/sdk`, Streamable HTTP transport, and server-side OAuth state. The rule at that stage was simple: do not invent Silpo arguments, fields, or output shapes. First, we captured `tools/list` through an authorized session on September 1, 2026. It returned 40 unique tools, not the 39 suggested by the earlier public description. One additional branch was `silpo_create_shopping_cart`. Input draft-07 schemas were saved and validated with Ajv before MCP calls. Output schemas were not treated as known in advance. The mapper only read documented paths and returned safe diagnostics when a shape did not match, without leaking values. That is where integration work starts to become real. Not at the first successful tool call. At OAuth, schemas, expiry, idempotency, reread, and observability. ## Read first, then write The first live workflow was deliberately read-only: `silpo_get_my_shopping_cart` -> `silpo_get_shopping_cart_by_id` -> `silpo_get_time_slots` -> `silpo_find_products_batch`. Search ran for eggs, tomatoes, and salmon. The workflow stopped before writes if there was no cart, not enough cart context, an invalid delivery slot, or a response shape that did not match documented paths. Express delivery normalized to `DeliveryHome`, because that is what the product search tool description required. Only after that came a constrained write spike: preview -> explicit human approval -> one additive write -> immediate cart reread -> validation. Existing cart lines could not be cleared or replaced automatically. On September 2, 2026, production confirmed one limited additive write for a test candidate with quail eggs. The sanitized trace showed `silpo_add_or_update_cart_products` followed by `silpo_get_shopping_cart_by_id`. The UI reported a verified result only after reread. That is not automatic checkout. It is not payment. It is a controlled cart mutation with evidence. ## Serverless made state honest The wedding change flow revealed another boundary. Locally, an in-memory repository was convenient. In production, a memory singleton is not a storage strategy. Different Vercel workers can handle different requests, so planning state and event previews had to move behind a real repository boundary. The final approach allowed local development to use in-memory state, while deployed planning state and event previews used Turso. Apply and reread went through the repository boundary, and tests covered preview, apply, and refresh through different repository instances. That bug did not invalidate the product model. It made the deployment model more honest. The corporate-machine constraints also shaped the workflow. Local coding, tests, and static checks happened on the work machine. Silpo OAuth and OTP happened in a personal browser. Deployed backend calls handled Silpo MCP. GitHub Actions covered sanitized trace and Turso smoke checks. Secrets and raw cart/product values were not routed through the model or stored in traces. Not glamorous. Necessary. ## Live integration made the mock better The supplier-neutral gateway eventually connected the same application contract to the official MCP: UI -> SupplierOrderService -> SupplierGateway -> SilpoSupplierGateway -> official MCP. The first live rollout was bounded. It did not try to send the whole batch. It selected up to three light, fully fulfillable lines within a ten-line window, with total mass or volume capped at 20 kg/l, far below the observed 50 kg Silpo delivery validation. The cap was checked before preview and before write. This was a pilot, not a claim that the entire procurement batch could safely go to Silpo. The gateway accounted for display ratio, step, price, stock, package rounding, product IDs already in the cart, error-level cart validations, and reread after write. After live verification, matching became stock-aware and started skipping SKUs that could not fully satisfy the need. The salmon replacement case was especially useful. In the mock catalog, the preferred salmon SKU was unavailable, so the offline flow showed a substitution. In live Silpo, `silpo_get_replacements` for sampled salmon returned success with an empty list. That empty list was not an error. It meant there was no known picking or assembler risk for that product. The system had to accept reality instead of inventing a replacement for a prettier demo. Unresolved lines blocked cart preview. Unknown nested shapes did not become synthetic replacements. Exact nested replacement mapping would only be added after a separate capture. The integration became more reliable because it allowed the real response to be boring. ## The failures after live verification were the useful ones Several issues appeared only after the live path existed. A delivery slot could expire between preparation and apply, so the system needed recovery: reread cart, fetch available slots, preview alternatives, require approval, update the slot, reread the exact slot, and retry supplier preparation. A repeated demo run could accidentally double the real cart quantity. Reset Demo must not delete real Silpo cart lines, so the gateway now reads existing product IDs before supplier initialization and stops before preview/write if a selected SKU is already present. Insufficient stock also changed matching. A known product is not enough if there is not enough stock to fulfill the required quantity. Later, i18n exposed a runtime boundary: a Dictionary with interpolation functions cannot be passed from a Server Component to a Client Component as a plain prop. Typecheck and build passed, but the browser failed. The fix was to pass a plain locale to client components and let them read a client-safe dictionary import. Backend locale also flows into agent explanations and supplier flow. These are not glamorous failures. They are the difference between a demo that works once and a workflow that can be trusted enough to show. ## Observability had to be safe A normal browser cannot directly show a server-to-server call from Vercel backend to `mcp.silpo.ua`. It only sees requests to the Next.js routes. So the demo needed a sanitized Agent request execution timeline. It combines application decisions, application tool calls, official Silpo MCP calls, sequence number, status, and duration. In mock mode, the timeline shows only application steps. In deployed Silpo mode, it adds blue Silpo MCP entries from the server-side trace. That mattered because a reviewer needs to see where the application made a decision and where the official supplier tool was actually called. But the trace stays safe: operation names, argument key names, status, duration, and structural summary. Not tokens. Not raw arguments. Not addresses. Not cart contents. Not product values. ## What the final demo actually proves The final demo flow was intentionally short. Overview shows Restaurant Operations, Events & Catering, Combined Procurement, a 14-day timeline, and attention items. Wedding starts at 180 guests. The user changes it to 200, reviews the preview, sees Plan v1 become Plan v2, and approves. The system updates total guests to 465 and records the change. Then the user opens Why this quantity? and sees deterministic provenance: demand sources, inventory coverage, incoming supply, and timing. Finally, Ask Misto prepares the next supplier order, shows a bounded supplier card, handles availability/substitution state, creates a cart preview, requires approval, performs an additive write, rereads the cart, and reports a verified result. The right ending is not "AI ordered everything." The right ending is: the agent guided the user from a business event change, through an explainable procurement plan, to a verified supplier cart, while keeping business-critical mutations under human control. Testing followed the same philosophy. Unit and application tests covered demand calculation, BOM expansion, FEFO, incoming supply timing, package rounding, provenance, wedding preview/apply, stale preview protection, agent tool schemas, mock supplier flow, reread reconciliation, live schema validation, timeslot updates, sanitized MCP trace, and Turso repositories. The handoff baseline had 122 tests in 36 files. Static checks included `npm test`, `npm run typecheck`, `npm run lint`, `npm run build`, and `npm audit`, with audit reporting 0 vulnerabilities after adding the MCP SDK. Browser QA covered the wedding flow, explanation drawer, mock salmon substitution, cart preview -> approval -> reread, agent supplier preparation, expired slot recovery, mobile/tablet navigation at 850 px and 390 px, no page-level horizontal overflow, procurement search, expiry-risk filtering, and localized units. Production Silpo verification confirmed live OAuth, 40 tools from `tools/list`, cart context, approved timeslot update, batch product search, one explicitly approved additive product write, immediate reread and validation, a bounded supplier flow through the normal Procurement Agent UI, one `silpo_add_or_update_cart_products` call followed by `silpo_get_shopping_cart_by_id`, and preservation of existing cart lines. It did not prove everything. It did not test all 40 tools, full checkout, payment, full wholesale ordering, every replacement response shape, live OpenAI autonomy, or real restaurant usage. That distinction is the whole point. ## What I would keep The hardest part of this project was not connecting an LLM to a store. The hardest part was deciding what work the AI should not do. The procurement engine calculates. The plan explains. The UI surfaces the operating state. The agent interprets intent and orchestrates tools. The supplier gateway executes bounded supplier operations. MCP is the final execution layer, not the product itself. That boundary made the project more interesting than another shopping assistant. Silpo is a connected commerce supplier in this story. I am not presenting it as a full HoReCa wholesale ERP, and the MVP is not a multi-supplier procurement platform. The future architecture could absolutely grow that way: Silpo, Metro, meat suppliers, vegetable suppliers, local suppliers, with AI helping compare availability, delivery, price, quality constraints, and preferences. But that was not the MVP. The MVP was narrower and, honestly, stronger because of it: one restaurant, one kitchen, one procurement plan, one agent, one supplier integration, explicit approvals, idempotent writes, reread validation, and a trace that shows what happened without leaking sensitive values. If there is one thing I would take from the hackathon, it is this: > Real agentic software is not proven by a model calling a tool. It is proven by the system around that tool: deterministic logic, explainable state, preview, approval, idempotency, reread, durable storage, and a clear boundary between application and supplier. That is where the work became interesting. Not when the cart changed. When the cart became only the last step of a procurement workflow the system could explain. --- # Micro-Frontends Are an Org Chart Decision, Not a Technical One Canonical: https://ma-x.im/blog/react-playbook-micro-frontends-org-chart Author: Maksym Kuzmitskyi Published: Sep 14, 2026 I've sat through more than one micro-frontends pitch, and they all open the same way: a slide about independent deployments, a slide about teams not blocking each other, maybe a slide about being able to use a different framework per app "if we ever need to." It's a technical pitch, delivered with technical slides, aimed at a technical audience. Here's the thing I think gets buried under all of that: almost none of it is actually a technical problem. It's an organizational one wearing a technical costume, and the pitch works better when it's honest about that from the start. > You don't split a frontend into micro-frontends because the code is too big. You split it because the *teams* touching that code can no longer coordinate at the speed the org needs. That's not a knock on micro-frontends. It's a claim about what actually justifies them — and it means the right first question isn't "is our bundle too big" or "do we need framework flexibility." It's: does our org chart already have the shape that micro-frontends are supposed to reflect? ## What the technical benefits actually cost Every micro-frontend benefit on the slide has a real, un-glamorous cost that doesn't make it into the pitch. **Independent deploys** sound great until you notice that a single-repo monolith with a decent CI pipeline can *also* deploy independently deployable features behind flags, without ever splitting the app. What micro-frontends actually buy you over that is independent deploys *without needing anyone else's review or coordination* — which is a genuine win, but only if the reason you needed that isolation was that coordinating with the other team was the actual bottleneck, not the deploy pipeline itself. **Framework isolation** — "team B can use Vue while team A uses React" — sounds like flexibility and is usually a cost nobody priced in. You now ship two frameworks' runtimes to every user, you've doubled your hiring and knowledge-sharing surface, and the actual reason teams reach for this is almost never "Vue is better for this specific problem." It's normally "team B inherited a Vue app during an acquisition and nobody wants to rewrite it." That's a real reason. It's an organizational one, not an argument that framework diversity is good architecture. **Smaller bundles per team** is the one that sounds most like a real technical win, and it's the one I'd push back on hardest. Splitting an app into micro-frontends doesn't shrink the total code the user downloads — it usually grows it, because now you're shipping duplicated dependencies (React itself, your design system, your date library) once per micro-frontend unless you invest heavily in shared-dependency tooling, which is its own significant ongoing cost. If bundle size is your actual problem, code-splitting inside a single app solves it directly, cheaper, and without any of what follows in this article. ## The cost nobody puts on the slide Once you've actually split the frontend, a list of problems shows up that no diagram warned you about. Cross-app state gets hard in a way that's easy to underestimate. A shopping cart, a logged-in user, a feature flag — anything that needs to be consistent across micro-frontends now needs a real synchronization mechanism, and "we'll just use custom events" is the sentence every team says right before building an ad hoc, under-tested message bus by accident. Design system drift becomes a constant, low-grade tax. Each micro-frontend can update its dependencies, including your shared UI kit, on its own schedule — which is the whole point — and that means you will, eventually, ship a page where the button in the header and the button in the body are visually two versions apart, because two teams updated on two different weeks. And orchestration — routing between micro-frontends, sharing auth state, handling the moment one micro-frontend fails to load while the rest of the page is fine — is genuinely hard engineering that a single-app architecture simply doesn't need to solve, because there's only one app. None of these costs are disqualifying. They're the price of the thing micro-frontends are actually good at: letting teams ship independently without waiting on each other. The mistake is paying that price for a benefit you didn't need. ## The question that actually decides it So here's the test I'd apply before anyone reaches for micro-frontends: **can two teams currently ship features to production without one blocking the other, in the architecture you already have?** If the honest answer is yes — one repo, decent ownership boundaries, feature flags, a CI pipeline that doesn't make Team A wait on Team B's review — then you don't have the problem micro-frontends solve. You have a problem that looks similar (big app, multiple teams) but isn't actually causing the pain micro-frontends are priced to fix, and adopting them will hand you the costs above in exchange for nothing. If the honest answer is no — teams are routinely blocked on each other's release windows, a shared repo's CI queue has become a real bottleneck, or (the case I'd take most seriously) you've inherited genuinely separate applications from an acquisition or a long history of independent teams and merging them isn't realistic — that's the org chart telling you the org is already split. Micro-frontends, in that case, aren't creating the split. They're the architecture that finally matches a split that already exists in how the company works. That's Conway's Law, and I don't think it's a fun aside here — it's the actual decision criterion. Your system's structure is going to mirror your communication structure whether you plan for it or not. Micro-frontends are what you get when you deliberately let that happen instead of fighting it with an org chart your codebase doesn't reflect. ## What I'd actually check first Before signing off on a micro-frontends architecture, I'd want to see the org chart, not the bundle analyzer. How many teams actually own frontend code that needs to ship independently? Is the current blocker genuinely architectural, or is it a CI pipeline that could be fixed for a fraction of the cost of a rewrite? And if the teams merged into one tomorrow, would the case for micro-frontends survive that? If it wouldn't — if the whole justification evaporates the moment you imagine one team owning all of it — then you weren't looking at an architecture problem. You were looking at a coordination problem, and there's usually a cheaper fix for that than teaching your frontend to run as five separate applications that now have to talk to each other. --- # Layered vs Feature-Sliced: Two Ways to Cut the Same App Canonical: https://ma-x.im/blog/react-playbook-layered-vs-feature-sliced Author: Maksym Kuzmitskyi Published: Sep 12, 2026 Take any non-trivial React app and you can describe its whole folder structure as the answer to one question: when you cut this codebase into pieces, which axis do you cut along? There are really only two honest answers, and almost every architecture discussion I've ever sat in is secretly an argument about which one a team picked without realizing they'd picked one. **Layered** cuts by technical kind. All the components live together, all the hooks live together, all the API calls live together, regardless of which feature they belong to. ``` src/ components/ hooks/ api/ utils/ pages/ ``` **Feature-sliced** cuts by product concern. Everything a feature needs — its components, its hooks, its API calls — lives together, and it's the *kind* of file that becomes secondary. ``` src/ features/ payment-method/ order-history/ account-settings/ ``` Neither of these is a mistake. They're both legitimate answers to "how do I organize this," and the reason this keeps being a live debate is that each one is *correct* for a while and then becomes *expensive* in a completely different, entirely predictable way. > Every architecture is a bet about which kind of future change you're optimizing for. Layered bets on stability of kind. Feature-sliced bets on stability of feature boundaries. Neither bet is safe forever. ## What layered actually gives you Layered architecture is the one nobody has to be taught. A junior developer can guess where a new hook goes — `hooks/` — without reading a single doc. That's not a small thing. It's the lowest-friction structure there is for the first several months of a project, precisely because it doesn't ask anyone to make a judgment call about feature boundaries before those boundaries are even clear yet. It's also genuinely good for a certain kind of change: anything that's cross-cutting by nature. If you're auditing every place the app calls the API layer, or refactoring every hook to a new data-fetching pattern, layered structure puts all of that in one folder, and you can see the whole blast radius by opening one directory. Where it breaks is exactly where products stop being simple. Once a feature — say, an order-management flow — starts touching a dozen components, several hooks, a couple of API modules, and its own utils, "layered" stops meaning "organized" and starts meaning "this feature's logic is now distributed across five folders that also contain twenty other features' logic." Want to delete the order-management feature? You're now grepping across the whole codebase, hoping you find every file that only exists because of it. Layered structure doesn't track feature boundaries, so nothing in the folder tree tells you where a feature ends. ## What feature-sliced actually gives you Feature-sliced structure solves exactly that problem. A feature's folder is a feature's blast radius. Deleting `features/order-history/` deletes the feature — not perfectly, there's usually some shared code left behind, but close. Onboarding someone onto *one* feature means pointing at *one* folder, not explaining the layer system and hoping they can mentally reconstruct which fragments across five layers belong to the thing they're working on. It scales with team size in a way layered structure doesn't. Multiple teams, each owning a handful of features, can work with almost no folder-level collision, because they're rarely in each other's slices. That's the real argument for feature-sliced at scale — not "it's cleaner," but "it lets N teams work without stepping on each other's files." The cost shows up the moment two features need the same thing. Every feature-sliced codebase eventually accumulates a `shared/` folder, and that folder has exactly the failure mode you'd expect: things get promoted to it reactively, usually the first time a second feature needs something, rarely with much thought about whether it's actually a stable, general-purpose piece or just two features that happen to look similar today. Left unmanaged, `shared/` becomes the layered architecture's `utils/` folder wearing a nicer name — a dumping ground, just one level removed. And there's a subtler cost: feature-sliced structure asks you to correctly guess feature boundaries *before* the product has told you what they are. Early in a project, "is this one feature or two" is often genuinely unknowable, and picking wrong means a slice that either merges awkwardly with another later or splits painfully in two. ## The actual decision I don't think there's a universal right answer here, and I'm suspicious of anyone who gives you one without asking what you're building. The question that actually matters is: **what changes more often in this product — the technical kind of thing, or the feature it belongs to?** If you're building something where features are genuinely stable and rarely added (an internal admin tool with five screens that haven't changed in two years), layered structure's simplicity is worth more than feature-sliced's isolation, because you're not paying feature-sliced's up-front cost of guessing boundaries for a product that isn't going to grow new ones. If you're building something where the *number* of features is the thing that grows — a product adding new user-facing capabilities every quarter, with multiple teams shipping in parallel — feature-sliced earns its cost almost immediately, because the layered alternative means every new feature adds friction to five existing folders instead of creating one clean new one. Most real products start in the first category and migrate into the second without anyone deciding to. That's the actual argument for feature-sliced conventions like FSD: not that they're objectively better, but that [the underlying problem they solve](/blog/react-playbook-what-fsd-actually-fixed) — coordination at scale — is the one almost every successful product eventually has, even if it didn't start with it. ## A hybrid is not cheating The reasonable middle ground, and the one I actually reach for on real projects, is layered at the top for genuinely global concerns — routing, design tokens, a handful of app-wide providers — and feature-sliced underneath for everything that's actually product surface area. ``` src/ app/ // routing, providers, global config — layered, rarely touched shared/ // genuinely cross-feature primitives, promoted deliberately features/ payment-method/ // feature-sliced from here down order-history/ account-settings/ ``` The discipline that makes this work isn't the folder names. It's being honest about which things are actually global (rare, and worth naming explicitly) versus which things just look similar between two features today and might diverge next quarter. Promote to `shared/` when a third feature needs something, not when a second one does — that one rule prevents most of the premature abstraction that turns `shared/` into a second `utils/` folder. Pick the axis that matches what actually changes in your product, be honest about which folder is doing that job right now, and don't confuse "we chose a structure" with "we solved organization." You didn't solve it. You picked which future problem you'd rather have. --- # Nivra: Turning a Hackathon Idea into a WebMCP Architecture Workspace Canonical: https://ma-x.im/blog/nivra-webmcp-challenge Author: Maksym Kuzmitskyi Published: Sep 11, 2026 Hackathons usually start with a dangerous question: what can I build quickly? I don't like that question very much. It sounds practical, but it pushes you toward the wrong kind of demo: a screen, a button, a little AI, and the feeling that something product-shaped exists. For a normal hackathon, maybe that is enough. For the OpenAI WebMCP Challenge, it wasn't. The better question was narrower: What idea actually shows why WebMCP should exist? Not "how do I add AI to an app." Not "how do I put a chat panel next to a UI." I mean: where does an agent need to read the state of the application, move through the same workspace as the human, act on the same model, and help expose something that would otherwise stay hidden between layers of the system? That question became Nivra. Links for the project: - Live app: [nivra-psi.vercel.app](https://nivra-psi.vercel.app) - GitHub repository: [github.com/MaximusFT/nivra](https://github.com/MaximusFT/nivra) - Demo video: [YouTube](https://youtu.be/BSz_Aqm4Ius) ## The first ideas were not architecture At the beginning, I did not have the project. I had several possible directions, and we rejected most of them for reasons that were more useful than the ideas themselves. One strong candidate was Senwia Sleep Lab, an evolution of an app idea I had around sleep analysis. I still like that direction. Sleep is understandable. The data can be visual. An AI agent could explore patterns with the user, highlight anomalies, ask questions, and help connect habits with outcomes. But for this challenge, it had a weak point. To make the demo convincing, I would have needed a synthetic data layer: fake sleep history, fake events, fake metrics. WebMCP would have interacted with data I had invented for the demo. The product might have been interesting, but WebMCP would not have been the reason it worked. There were other options too. Interview Forge, an AI tool for technical interviews. AI Newsroom, a system for processing and organizing news. And then an architecture workspace: a place where a human architect and an AI agent could work together over a structured model of a software system. That last idea kept surviving the cuts. Not because architecture sounds more serious. Because WebMCP was not decorative there. If an agent is working with architecture, it needs to inspect application state, move between views, find dependencies, show evidence, add findings, create proposals, and work inside the same workspace the architect is looking at. That is a different product shape. WebMCP stops being a chat next to a diagram. It becomes the agent's interface into the architecture model. ## ArchPilot was the wrong name, usefully The first working name was ArchPilot. It sounded fine at first. Short, obvious, close enough to architecture and agent-assisted work. Then we checked the market and found existing products with similar names, including products in software architecture and architecture governance. So the name had to go. That could have been just a naming problem. It turned into a product decision. When a name stops working, you have to ask what you were actually trying to name. And that forced a clarification: Nivra should not be "AI designs architecture for you." It should not be an architecture validator that stands above the system and declares what is correct. It should not be a governance platform. And it definitely should not be a chat box glued to the side of a diagram. I needed a different sentence: > Architecture is the shared context. That became the center of Nivra. The human and the AI agent work with the same structured architecture model, but through different interfaces. The human sees a visual workspace. The agent gets access to the same model through WebMCP tools. One source of truth. Two ways to reason over it. ## The demo needed a real architectural tension Once the product shape was clear, the next problem was the scenario. I did not want a toy example where service A talks to service B and the whole point is that the arrow is bad. That kind of demo teaches the user to agree with the author, not to inspect the system. The scenario became Commerce Platform. At the High-Level Design level, everything looks almost right. Product, Cart, Checkout, and Account are separated into microfrontends. Checkout looks independent. You can draw a box around it and say, quite reasonably, "this is a separate part of the system." Then the business requirement lands: the Checkout Team needs to evolve and deploy Checkout independently from Product. The natural reaction is understandable: > Checkout is already a separate microfrontend. Why wouldn't it be independently deployable? That is exactly where Nivra needed to become useful. At HLD, Checkout looks ready. But when the agent moves deeper into Checkout LLD, two dependencies appear, and they are not the same kind of problem. The first is `Basket Adapter -> Product Store` through shared runtime state. That is runtime coupling. Checkout may be visually separate, but it still depends on Product state at runtime. The second is `Pricing Module -> Product Service` through an explicit REST API. That is also a dependency, but it is visible, named, and easier to reason about. An architect may decide it is acceptable for now. That distinction became the core of the demo: > A separate box on a diagram doesn't mean an independent system. I did not want Nivra to say "all dependencies are bad." That is not architecture. The useful moment is when the human sees the evidence, understands the difference between shared runtime state and an explicit contract, and makes a trade-off. The agent does not decide for the architect. It helps expose the layer where the decision actually lives. ## The canvas could not be the source of truth After the scenario clicked, we designed the product architecture around it. The most important decision was boring on purpose: do not start with the diagram. If the first thing you build is a React Flow canvas, it is very easy to confuse the graph with the architecture. The nodes on the screen start to feel like the system. Coordinates acquire meaning. Views drift into their own copies of elements. Then validation, WebMCP, and UI each interpret the "architecture" slightly differently. So the first real artifact was a plain TypeScript Architecture Model. Commerce Platform v1.35 became a deterministic fixture model, not a decorative picture. HLD and Checkout LLD referenced the same entities and relations. Views stored IDs, not duplicated elements. Layout lived separately, because canvas coordinates are presentation metadata, not architectural meaning. That decision paid for itself later. UI, validation, and WebMCP could all work against the same model independently. If the canvas changed, the architecture still existed. If the visual language changed, the domain model did not move with the pixels. ## The plan came before the code After the product idea settled, we still did not jump straight into implementation. First came the Product Definition and MVP scope. Then Architecture Levels and the Domain Model. Then the WebMCP Tool Contract, UI/UX, technical implementation notes, demo fixture, golden scenario, seven-day implementation plan, and visual design specification. All of that became Nivra Master Specification v1.1. At that moment, Nivra still was not an application. But it was no longer just an idea. It had a scenario, a domain model, a WebMCP contract, a UI direction, a demo fixture, and a development plan. The question changed. It was no longer: what should we build? It became: can we make this model actually work? ## Foundation first, WebMCP later Once the master specification existed, the temptation was obvious: start with tools. This was the WebMCP Challenge, after all. Show WebMCP. But that would have been the wrong order. We started with React, TypeScript, and Vite, but the real output of the first phase was not a screen. It was the Architecture Model and the operations around it. Only then came the canvas, adapters from the Architecture Model into React Flow, and navigation from Commerce HLD into Checkout LLD. That became Checkpoint A: does the product create a "now I see it" moment without the agent telling the user what to think? At HLD, Checkout looked separate. In LLD, the shared runtime state dependency and the explicit REST call appeared together. The relations had different visual and semantic treatments. The product idea finally stood on the workspace itself, not on narration around the demo. If a demo only works while I am explaining it out loud, the product does not work yet. ## The first serious bug was not where I expected The early version compiled. Then a browser smoke test immediately found a React maximum update depth problem, effectively an infinite render. The cause was not the Architecture Model. It was an object-returning Zustand selector. The selector created a new object, React treated it as a new value, the component updated, the selector created another new object, and the loop continued. The fix was ordinary: stable comparison with `useShallow`. The lesson was larger than the fix. Even a foundation screen cannot be considered successful just because TypeScript is satisfied. The browser has its own failure modes: selectors, subscriptions, effects, render timing. If an architecture workspace is supposed to be trustworthy, it needs to be exercised in a live UI early. Around the same time, another risk became obvious: the canonical fixture could not be mutated directly. If future write actions could silently change Current Architecture, the whole proposal story would lose credibility. Changes had to be immutable. Current Architecture had to remain the reference point. That sounds like an implementation detail, but it is really a product detail. The user has to know what they are looking at: the current system, or a proposed alternative. ## The reasoning loop had to work manually first Before registering any WebMCP tools, we made the manual scenario work end to end. The architect selects evidence, opens the Context Panel, sees relations and deployment information, creates a Finding, saves architectural constraints, runs deterministic validation, creates a Proposal, compares Current and Proposal, and validates the alternative. That was Checkpoint B: the full manual Observe -> Question -> Inspect -> Understand -> Decide -> Propose -> Verify loop. This is where the product became clearer to me: validation was not the main product. Validation matters. Without it, the whole thing becomes a nice story. But Nivra is not centered on pass/fail. It is centered on shared understanding. The agent can help inspect, explain, drill into LLD, and propose changes. But once a rule is formalized, boring deterministic code should check it. Agent-assisted reasoning. Deterministic verification. ## Constraints needed evidence We added four rule types: `forbidden-dependency`, `independent-deployment`, `no-cycles`, and `allowed-protocol`. Validation was pure, typed, and evidence-bearing. Each check returned not only pass/fail, but references to the elements or relations that explained the result. Golden Current Architecture returned 2 passed / 2 failed. Honestly, that was better than making the demo pass perfectly from the beginning. If Current passes every rule, validation proves very little. It might just be confirming a happy path written for the demo. The 2/2 result showed that the rule was actually finding the hidden violation. Some details mattered. A forbidden dependency has to account for descendants, not only exact IDs. LLD elements inherit deployment unit through the parent hierarchy. Protocol comparison is case-insensitive, even if the display model says REST. Validation does not create Findings, and it does not depend on React, Zustand, or the canvas. An architecture rule should validate architecture, not whatever the UI happens to be rendering. ## Proposal, not mutation The next problem was trust. If an agent can "fix" the architecture directly, the human loses the ability to understand the original state. What was Current? What did the agent propose? What has been accepted? What is still just an alternative? So Current Architecture stayed immutable. A Proposal became a patch-based alternative with base version checking. In the golden proposal, the runtime state dependency is removed and replaced with a Checkout Snapshot Contract. Not as a magical fix, but as a checkable architectural alternative. The visual diff needed thought too. The added Snapshot Contract and the removed Product Store/runtime relation had to be visible at the same time. The effective Proposal view had to be computed from the patch, not stored as a separate diagram, because otherwise we would be back to two competing models instead of one source of truth. The result: Current: 2 passed / 2 failed. Proposal: 4 passed / 0 failed. That felt like architecture work. The human can see the trade-off, inspect the evidence, and evaluate a verified alternative before accepting anything. > The agent doesn't draw architecture for you. It reasons inside your architecture with you. ## WebMCP as an adapter boundary Only after manual Checkpoint B did we start the WebMCP integration. That order mattered. WebMCP tools did not get their own architecture model. They did not mutate React Flow directly. They became a browser adapter over existing workspace operations. The human interface and the agent interface called the same logic. The first group of tools covered reading and navigation: `get_architecture`, `inspect_element`, and `show_architecture_view`. Then came write and compute tools: `annotate_architecture`, `add_constraint`, `create_proposal`, and `validate_architecture`. Seven P0 tools in total. On paper this sounds simple: write a JSON Schema, register a handler, done. In practice, the boundary was more interesting. The runtime can call a handler more than once. It can pass malformed data. It can send an ID that looks plausible but breaks the model. So the write tools also validate stable kebab-case IDs, enums, evidence references, duplicate and conflicting IDs, parent references, relation endpoints, proposal base version, and nested update values. Every call creates an activity entry with running, success, or error status. The human can see what the agent actually did in the workspace. But activity is not persisted as architecture state. That separation matters. Agent activity explains the process. It is not the architecture. ## Experimental API means experimental WebMCP was an experimental browser API available through a specific Chromium mode. A normal browser might not have `document.modelContext`. That could not be treated as the whole app failing. So Nivra got an explicit WebMCP ready / WebMCP unavailable status, a guarded legacy fallback for earlier preview runtimes, AbortSignal-based registration, a complete manual fallback without WebMCP, and a guided demo simulation for cases where an external agent is not available. The honesty of that simulation mattered. It is labeled Demo simulation. It uses the same workspace actions and shows the same operations, but it does not pretend to be real AI. Challenge V1 is a client-side application. Not a production AI backend. Not real-time collaboration. Not a governance platform. It is a verifiable workspace where WebMCP has a clear role when the runtime is available, and the product still works when the runtime is not. ## Unit tests do not prove a browser tool works Unit tests protected domain queries, adapters, validation, persistence, store actions, and tool input validation. That was necessary. It was not sufficient. A handler test does not prove that the browser registered a WebMCP tool. It does not prove that transport reached a workspace action. It does not prove that the human saw the result in the UI. So we built a black-box harness: `npm run test:webmcp`. It starts an isolated Vite server, launches a temporary Chromium profile with WebMCP enabled, discovers all seven tools, and calls them through browser `ModelContext.executeTool()`. Every run starts from Reset Demo. The harness intentionally repeats Finding, Constraint, and Proposal writes, checks DOM focus and Agent Activity, validates Current and Proposal, returns to Current, and confirms that the original `basket-adapter-shares-product-store` relation is still there. Three full repetitions returned the same result. That was Checkpoint C: Current 2/2 -> Proposal 4/0. Current stayed unchanged. Retries were idempotent. Activity was visible. No errors. That finally felt like evidence. Not "it clicked locally." Not "the handler returns JSON." The full chain worked: WebMCP registration -> browser transport -> workspace action -> visible React state. ## Polish was not about making it pretty After functional freeze, we did not expand scope. We asked a different question: can someone understand the story without me narrating it? The answer was: not quite yet. HLD/LLD navigation could not look like unrelated tabs. Selecting an element had to open its own context, not accidentally show Checkout policy. Proposal action should not appear before Current validation exposes a problem. Added and removed evidence needed to be visible together. Agent Activity had to be readable without taking over the workspace. The standalone demo could not pretend it had a live agent connection. So we moved toward contextual drill-down and breadcrumb navigation. We added a neutral Policy state without selection, scoped Checkout policy, timeline Agent Activity, guided demo, and a dismissible history drawer. After successful Proposal validation, the workspace also got an implementation brief and the ability to save a Proposal as an architecture branch. Important detail: architecture branch is not a Git branch. It is a durable verified alternative inside Nivra. `current/commerce-1.35` and `proposal/checkout-isolation` can be compared without overwriting Current. The visual verification was practical: desktop layouts at 1440x900 and 1920x1080, no horizontal overflow, readable Checkout LLD evidence and Agent Activity, clean browser console. ## Production does not prove WebMCP After local stabilization, the app went live on Vercel: [nivra-psi.vercel.app](https://nivra-psi.vercel.app). Deployment then became Git-driven: pushing to `main` runs the production build through the connected GitHub repository. But deployment itself proves almost nothing about WebMCP. The app can load over HTTPS, the UI can look fine, and browser tool registration can still be broken. So the same black-box harness was run against the public HTTPS URL through `NIVRA_WEBMCP_URL`. Three production repetitions confirmed the same behavior: all seven tools were registered, Checkout LLD evidence opened and focused, Current returned 2 passed / 2 failed, Proposal returned 4 passed / 0 failed, retries stayed idempotent, Current was not polluted by proposal-only state, and Agent Activity stayed visible without error state. By the end, there were four layers of verification: TypeScript typecheck, unit tests, and production build; manual browser checkpoints for HLD/LLD and the reasoning loop; the WebMCP-enabled Chromium black-box harness; and the same checks against production HTTPS. Only after that did I consider Nivra ready for demo and submission. ## What Nivra became Nivra started with a question: what idea is worth building for the WebMCP Challenge? By the end, the question had changed. Nivra had become a concrete system with a source of truth, a reasoning loop, browser tools, deterministic validation, and a reproducible demo state. It did not become an automatic architect. Good. It does not draw architecture instead of the human. It gives the human and the agent one shared context where they can expose a hidden dependency, define a rule, propose an alternative, and verify it without silently replacing Current Architecture. At that point, the project stopped being just a concept. The human could see the architecture. The agent could work with the same model. Deterministic checks prevented a pretty proposal from quietly becoming the current system. You can try the live app, read the source, or watch the demo here: - [Live app](https://nivra-psi.vercel.app) - [GitHub repository](https://github.com/MaximusFT/nivra) - [YouTube demo](https://youtu.be/BSz_Aqm4Ius) The next step was no longer deciding what to build. It was showing whether this combination — human, agent, WebMCP, and a shared Architecture Model — could hold up live, in front of someone who had not watched the whole thing being built. --- # What FSD Actually Fixed (and What It Didn't) Canonical: https://ma-x.im/blog/react-playbook-what-fsd-actually-fixed Author: Maksym Kuzmitskyi Published: Sep 09, 2026 For a long time, "frontend architecture" was almost a contradiction in terms. Backend had layers, domains, bounded contexts, decades of literature. Frontend had `components/`, `utils/`, and a folder called `helpers` that everyone was quietly afraid to open. The general vibe, even among good engineers, was that the frontend didn't need real architecture — it was just where you rendered the thing the backend actually built. Feature-Sliced Design showed up into that vacuum, and I think that context matters more than the methodology's specific rules. FSD didn't just propose a folder convention. It made an argument: the frontend is complex enough, and grows unpredictably enough, that it deserves the same seriousness backend systems get. That argument is the actual contribution, and it's the reason FSD spread as fast as it did — not the specific layer names. > FSD's real achievement wasn't a folder structure. It was convincing an entire ecosystem that the frontend was worth architecting at all. I've [written before](/blog/smeared-component) about how following FSD's rules literally, without thinking, produced one of the worse codebases I've built — a single button smeared across ten folders, each one "correctly" following the layer it was assigned to. That article was about the failure mode. This one is about something narrower: which problem FSD was actually solving, and where the credit for "clean architecture" quietly gets misattributed to a folder convention that never promised it. ## What FSD actually fixed Three things, and they're real. **It gave teams a shared vocabulary for growth.** Before FSD, "where does this go" was answered differently by every senior engineer on the team, usually based on whatever they'd seen at their last job. FSD gives you `pages`, `features`, `entities`, `shared` — not perfect names, but names everyone on a team can agree mean the same thing. That alone kills a huge amount of bikeshedding. **It made import direction a rule instead of a convention.** The layer hierarchy — shared can't import from entities, entities can't import from features, and so on — is enforceable with a lint rule. That's the part I actually think is underrated. Most frontend codebases don't have architectural violations because someone made a bad call; they have them because nothing stopped the bad call from compiling. FSD turned "please don't import upward" from a code review comment into a build failure. **It gave "the frontend has architecture" a name people could put on a job posting.** This sounds cynical, but I mean it as a genuine point: before FSD (and a handful of contemporaries), it was hard to even have the conversation about frontend architecture in a hiring or planning context, because there wasn't a shared reference point. Now there is. That's a real, if unglamorous, win. ## What it never promised to fix Here's where I think people — including a version of me, a few years back — get it wrong. FSD tells you *where* a piece of code should live relative to other pieces. It does not tell you *whether the pieces you're splitting apart should have been split apart in the first place.* That distinction matters because the smeared-component failure isn't a bug in FSD. It's what happens when you use a layering convention to answer a question it was never designed to answer: how much of a single feature's logic should live together versus be distributed. FSD's layers describe *horizontal* concerns — what kind of thing is this (a hook, a type, an API call) — and following them faithfully will happily scatter every piece of a single *vertical* concern (one feature, one component, one story) across the whole hierarchy, because each piece genuinely does belong to a different layer by FSD's own rules. ``` // "Correct" FSD placement for one payment-method component src/ features/payment-method/model.ts // the hook and state entities/payment-method/types.ts // the type shared/hooks/useDebounce.ts // a helper it needs shared/api/paymentMethods.ts // the fetch call features/analytics/paymentTracking.ts // its analytics event ``` Every one of those placements passes an FSD lint rule. None of them help the next engineer who needs to change how the payment method selector behaves, because understanding it now requires reconstructing it from five files across three layers, in a codebase that will tell you, correctly, that nothing is architecturally wrong. FSD also doesn't fix cohesion at the *page* level, and it doesn't fix team discipline. A team that argues about everything else will still argue about whether a given piece of logic is a `feature` or an `entity` — FSD gives you a vocabulary for the argument, not an answer to it. And a team with no code review discipline will produce a messy FSD codebase exactly as fast as it would have produced a messy flat one; the folders will just be tidier while it happens. ## The credit-misattribution problem I think this is the actual thing worth naming: teams that adopt FSD often experience a real improvement in their codebase, and then attribute all of it to the layering. Some of the improvement is the layering. A meaningful chunk of it is something else entirely — the simple fact that adopting *any* deliberate structure, discussed and agreed on as a team, forces the conversations that were previously being skipped. "Where does this go" gets asked out loud instead of guessed at. That conversation is valuable regardless of which methodology prompted it. Which means the honest version of "we adopted FSD and our codebase got better" is often "we adopted a shared convention, discussed it as a team, and enforced it with tooling — and FSD happened to be the convention we picked." That's still a win. It's just a different, more general win than "FSD solved our architecture problem," and conflating the two is how teams end up surprised when FSD alone doesn't prevent a smeared component, a bloated `shared/` folder, or a `pages/` layer that's turned into a dumping ground. ## What I actually reach for now I still use FSD's structure as a starting point — [the version I use in practice](/blog/react-playbook-code-structure) keeps the layer names but treats them as a coarse sort, not a mandate to split every feature into its smallest constituent parts. The rule I actually enforce is closer to: a feature's pieces get distributed across layers only when another feature genuinely needs to share them. Until then, they stay together, even if that means a `features/payment-method/` folder that internally holds its hook, its types, and its API call in one place, technically "violating" the purist reading of the layer boundaries. That's not a rejection of FSD. It's treating it as what it actually is: a good answer to "how do we agree on where things go as this project grows," and a tool that says nothing useful about "how much should stay together." Knowing which question you're asking is the part that doesn't come in the docs. If your team adopted FSD and it didn't fix the thing you hoped it would, I'd genuinely ask which of the two problems you actually had — because they need different fixes, and only one of them is solved by a folder structure. --- # Checkout Isn't a Form. It's the Only Part of the App Where Architecture Has a Stopwatch on It Canonical: https://ma-x.im/blog/checkout-architecture-time-to-goal Author: Maksym Kuzmitskyi Published: Sep 06, 2026 I've spent a real chunk of my career around purchase flows — one-click purchase, multi-step checkout, the whole family of screens between "I want this" and "I bought this." And the thing that took me the longest to internalize wasn't a pattern or a library. It was what we're actually selling in that flow. It isn't the UI. It isn't even the product, at that point — the user already decided on the product two screens ago. What we're selling is *time-to-goal*. How fast, with how little friction, does this person get from "I'm ready to buy" to "it's done"? Every metric that actually matters downstream — conversion, cart abandonment, repeat purchases — is a proxy for that one number. > The product in a checkout flow isn't the form. It's the distance between intent and confirmation. This sounds like a UX statement, and it is one. But I want to argue it's also, maybe primarily, an *architecture* statement — because the UX-y stuff people file under "polish" (responsiveness, one-click purchase, graceful recovery from a dropped connection) is downstream of decisions made in how the checkout is built, not decisions made in Figma. ## Every step is round-trip debt Here's the mental model I use. Every screen, every confirmation, every "are you sure" in a checkout flow is a withdrawal against the user's patience. Doesn't matter how pretty it is. A step is a step. Multi-step checkouts get justified all the time — shipping, then payment, then review — and sometimes that's genuinely the right shape. But I'd push back on treating that as free. Each transition is a network round trip if it's fetching anything, a re-render if it isn't, and either way it's a moment where the user can get pulled away, get a spinner they don't trust, or hit the back button and lose state they already entered. The architectural question isn't "how do we make step 2 nice." It's "does step 2 need to exist as a separate step at all, or is it three fields we could've asked for on step 1 without anyone noticing the difference." That's a product conversation, sure, but it's the frontend architect's job to keep asking it, because engineers are the ones who feel the cost of *not* asking it — in state management, in the number of places cart data can go stale, in every edge case around "what if they refresh here." ## One-click purchase is a state-management problem wearing a UX costume One-click purchase looks, from a design brief, like "remove the button presses." Architecturally, it's a much harder problem: you're compressing an entire multi-step flow's worth of validation, payment, and inventory checks into a single optimistic action, and you have to do it without ever showing the user a screen that says "wait." That means the hard part isn't the click. It's everything that has to already be true *before* the click for the click to be safe: ```ts interface OneClickEligibility { hasValidPaymentMethod: boolean; hasCompleteShippingAddress: boolean; itemInStock: boolean; priceUnchangedSinceLastSync: boolean; } function canOneClickPurchase(state: OneClickEligibility): boolean { return ( state.hasValidPaymentMethod && state.hasCompleteShippingAddress && state.itemInStock && state.priceUnchangedSinceLastSync ); } ``` Everything hinges on that check being *current* at the moment of the click, not current as of when the page loaded. If price or stock data is stale by even a few seconds, "one click" turns into "one click, then a screen apologizing that the price changed" — which is worse than a normal checkout, because you promised speed and delivered a rug-pull. So the real architectural commitment behind one-click purchase isn't a button component. It's a decision to keep a small slice of critical state (price, stock, payment validity) continuously fresh in the background, so the click can be trusted the instant it happens. That's a background-sync and cache-invalidation problem, not a UI problem, and it needs to be treated as first-class — not bolted on after the button ships. ## Optimistic UI, but with a real rollback story Checkout is one of the few places where optimistic UI actually earns its complexity, because the alternative — making someone stare at a spinner while you confirm a card charge — is its own kind of failure. But optimistic UI without a serious rollback path is just a faster way to lie to the user. ```tsx function useSubmitOrder() { const [status, setStatus] = useState<'idle' | 'confirming' | 'error'>('idle'); const submitOrder = async (order: OrderDraft) => { setStatus('confirming'); // show success-leaning state immediately try { const confirmed = await placeOrder(order); return confirmed; } catch (error) { setStatus('error'); // the user already saw a hopeful state — the recovery message // has to explain what changed, not just that something failed throw error; } }; return { status, submitOrder }; } ``` The detail that actually matters here is the comment. If you show a confident "confirming your order" state and then it fails, the failure message can't be a generic toast. The user's mental model has already moved forward — they think they're done. Rolling that back cleanly, with a message that says what actually happened (card declined vs. item went out of stock vs. network timeout), is architecture work: it means your error states need to carry *why*, not just *that*, all the way from the API layer up. ## Responsiveness is a checkout feature, not a checkout nice-to-have I'd draw a hard line here: on most of an app, a layout that reflows awkwardly on a weird viewport is a bug you triage next sprint. On checkout, it's a lost sale, because a meaningful chunk of purchases happen one-handed, on a phone, possibly in a moving vehicle, possibly with one bar of signal. That changes the priority order of what you architect for. Payment fields need to work with autofill without fighting the browser. Buttons need to be large enough that a shaky hand doesn't mis-tap into "cancel." And the layout needs to survive the keyboard eating half the screen on mobile, because "the confirm button is off-screen when the keyboard is open" is a shockingly common way to lose an order that was otherwise complete. None of that is exotic. It's just a different priority order than the rest of the app gets, and if your component architecture treats checkout screens as "just more pages," they'll get the same generic responsive treatment as everything else — which is to say, good enough for a blog post, not good enough for a payment form. ## The metric that should be driving these decisions Here's the part I actually want to land, because it's the thing that reframes all of the above from "best practices" into an actual measurement problem. If the product is time-to-goal, then the thing worth instrumenting isn't page views or even conversion rate in isolation — it's the *distribution* of time between "entered checkout" and "confirmed order," broken down by step, and the drop-off at each step. That's a genuinely different question than "does this page load fast," and it points architecture in a specific direction: every step needs a timestamp, every abandonment needs a last-known-step, and every retry needs to be attributable to a cause (validation error, payment decline, network failure, user just left). ```ts function trackCheckoutStep(step: CheckoutStep, elapsedMs: number, outcome: 'advanced' | 'abandoned' | 'errored') { analytics.track('checkout_step', { step, elapsedMs, outcome }); } ``` That's a small function. The architectural commitment behind it — instrumenting every step consistently, from the same source of truth as the state machine driving the flow, not bolted on separately by whoever remembers to add tracking — is the actual work. Get that right and you have a real answer to "where is friction actually happening," instead of a guess dressed up as a redesign. ## Where this leaves the architecture conversation None of this is about picking the right library for multi-step forms. It's about recognizing that checkout is the one part of the app where the business metric (completed purchase) and the architecture metric (time-to-goal, state consistency across steps, recovery from failure) are the same number wearing two names. Everywhere else in the app, you can separate "is this well-architected" from "does this convert." In checkout, you mostly can't — a badly architected checkout *is* a checkout with worse conversion, because every extra round trip, every stale price, every optimistic update with no honest rollback is friction the user feels as delay between wanting the thing and having it. If you're the one arguing for a cleaner checkout architecture and getting pushback that it's "just implementation detail" — it isn't. I'd make the case that of everything in the app, this is the part where the architecture review and the conversion review should be the same meeting. I've got a lot more from this part of my career than fits in one article — one-click purchase edge cases, retry strategies for flaky payment providers, the exact way stale cart state causes support tickets. If there's a piece of this you want me to go deeper on, tell me which one and I'll write it. --- # Most Advanced TypeScript Isn't Worth What It Costs Canonical: https://ma-x.im/blog/react-playbook-types-that-earn-their-keep Author: Maksym Kuzmitskyi Published: Sep 03, 2026 Let me start with an admission, because it shapes everything below: I'm not especially strong at advanced TypeScript. Conditional types nested three deep, recursive template literal parsers, the kind of thing that shows up in a library's internals and gets applauded on Twitter — I read that code slowly, and I don't enjoy writing it. For a while I treated that as a gap to close. Now I mostly treat it as a constraint worth designing around, and I think that's the more useful position. Not because type-level programming isn't impressive. Because on an application codebase, a type that only one person on the team can modify is a liability wearing the costume of rigor. [The earlier TypeScript article](/blog/react-playbook-typescript-patterns) covered the patterns I reach for constantly — typing the API boundary, discriminated unions for async state, inference at the router. This one is about the question that comes *after* you know the patterns: how much type complexity should a given piece of code carry, and how do you tell when you've overshot? ## Types have a running cost The pitch for TypeScript is that types catch bugs. True, and I'd never go back. But the framing hides something: a type isn't a one-time purchase. It's a thing every future reader has to understand before they can safely change the code underneath it. So each type has a cost, and it shows up in three places. Someone has to read it to understand the contract. Someone has to modify it when requirements move. And when it goes wrong, someone has to decode the error message — which, for a sufficiently clever type, is a wall of text that names none of the things you actually wrote. That last one deserves more weight than it usually gets. A type that produces an unreadable error at the call site has partly defeated its own purpose. The whole point was to tell someone they made a mistake. If the message needs its own investigation, you haven't caught the bug so much as relocated it. > The value of a type is not how much it proves. It's how much it proves *per unit of understanding it demands*. That ratio is the thing I actually optimize for now, and it explains why my list of "worth it" is short. ## What earns its keep **Discriminated unions, everywhere.** This is the highest-value construct in application TypeScript and it's barely "advanced" at all: ```ts type PolicyRequest = | { status: 'idle' } | { status: 'loading' } | { status: 'error'; message: string } | { status: 'success'; policies: Policy[] }; ``` Four lines, and an entire class of bug is now unrepresentable — you cannot read `policies` without first proving you're in the success branch. The compiler narrows it for you, the errors are legible, and any developer can extend it without a conversation. Cheap to read, expensive bugs prevented. That's the ratio you want. **Branded types, but only where mixups are real.** If your codebase passes around several kinds of ID as bare strings and you've actually shipped a bug from swapping two of them, this is worth it: ```ts type PolicyId = string & { readonly __brand: 'PolicyId' }; type CustomerId = string & { readonly __brand: 'CustomerId' }; ``` Note the condition. *If you've actually shipped that bug.* Branding every primitive in the app because it's theoretically safer is how you end up with casts scattered everywhere and a team quietly annoyed at you. **`satisfies` instead of annotation, when you want both.** This one is underused and it's almost free: ```ts const routePermissions = { policies: ['read', 'write'], billing: ['read'], } satisfies Record; ``` You get the constraint checked *and* the literal types preserved, so `routePermissions.billing` is `['read']` rather than a widened `Permission[]`. No cleverness required, real inference gained. **Generics on components, one parameter deep.** A typed `DataTable` that infers the row type from the data you pass it is genuinely good. Two or three interdependent type parameters with constraints referencing each other is where it stops paying, in my experience — the signature becomes the thing people copy-paste rather than read. ## What usually doesn't **Type-level logic that reimplements runtime logic.** Deep conditional types that compute a shape based on five flags. Recursive types that parse a string format into a structure. These are legitimately impressive and they belong in libraries, where a small number of maintainers absorb the complexity so thousands of users don't have to. In application code the arithmetic is inverted: your whole team pays, nobody outside benefits, and the requirements will change next quarter anyway. **Types that exist to avoid a small runtime check.** Sometimes the honest answer is a validation at the boundary and a plain type afterward: ```ts const policy = policySchema.parse(response.data); ``` You've now got a real guarantee — checked against actual data, not just asserted about it — and the type downstream is boring. I'd take that over an elaborate type that describes what the server *should* send, every time. The type system can't see your API. A parser can. **Generic abstractions built for one call site.** The rule I'd apply here is the same one that applies to component abstractions: don't generalize until you have the second case in front of you. A generic hook with three type parameters serving exactly one consumer is a puzzle you built for yourself. ## The test I actually use When I'm not sure whether a type has gone too far, I ask two things. First: *can a mid-level developer on this team change the code this type guards, without asking me?* If the honest answer is no, the type has become a bottleneck with my name on it. That's not safety — it's a bus factor problem I introduced on purpose. Second: *what does the error look like when someone gets it wrong?* I'll take a slightly weaker type with a clear failure message over a stronger one that produces forty lines of inference noise. The error message is the user interface of a type, and it deserves the same consideration as any other interface. Neither test involves how much the type proves. That's deliberate. ## Where I've landed I used to think being weak at type-level programming meant I'd eventually hit a ceiling in TypeScript. What actually happened is that the ceiling turned out to be somewhere I don't need to go very often — and that most of the safety I care about comes from a handful of unglamorous constructs applied consistently at the right places, mostly at the edges where data enters the app. The interesting decisions aren't in the type system at all. They're about *where* you put the boundary, what you validate, and which mistakes you've decided are worth making impossible. Once those are right, the types tend to stay simple on their own. When I find myself writing something genuinely gnarly, it's usually a sign the design underneath it is doing something it shouldn't. I'm aware this is the position of someone who isn't a type wizard, and I'd take the counter-argument seriously. So if you've got a case where deep type-level machinery genuinely paid for itself in an application — not a library — I want to see it. That's the example that would move me. --- # Your Agent Instructions Are Rotting Right Now Canonical: https://ma-x.im/blog/agent-playbook-instructions-rot Author: Maksym Kuzmitskyi Published: Sep 01, 2026 There's a particular kind of file that only ever grows. You know the one. It started as a short list of project conventions for your agent, and every time something went sideways you appended a line to stop it happening again. *Always run the build before committing. Don't touch the lockfile. Use the existing helper instead of writing a new one.* Every line was correct on the day it was written. That's what makes this hard to see. Because instructions aren't code. Nothing fails when they go stale. There's no red test, no type error, no failing pipeline. A rule that stopped being true six months ago sits there looking exactly like a rule that's still true, and the agent — being obedient — follows both with equal conviction. > Instructions don't break loudly. They just quietly stop describing your project. [The context is the product](/blog/agent-playbook-context-is-the-product) made the case that what you feed an agent matters more than which model you picked. This is the uncomfortable follow-up: that context is an artifact you own, and artifacts you own need maintenance. Nobody budgets for maintaining a text file. ## How the rot actually happens It's never one dramatic mistake. It's four small, reasonable things. **The project moves and the file doesn't.** You migrate from one test runner to another, rename a directory, drop a library. The code changes in one commit. The instruction describing the old world changes in... no commit, because nobody thought about it. Now the agent is confidently steering toward a folder that isn't there. **Rules get added to fix single incidents.** The agent did something dumb once, so you wrote a rule. The rule is narrow, situational, and phrased as a universal law. Twenty of those later, you've encoded a list of past accidents rather than a description of how the project works. **Nothing ever gets deleted.** Deleting a rule feels risky — what if it was load-bearing? So the file only accretes. And because instructions usually sit near the top of the agent's context, every dead line is taking up room that live information could be using. **Contradictions arrive silently.** Rule 4 says prefer the shared utility. Rule 19, added months later by someone solving a different problem, says write it locally in the feature folder. Both are in the file. The agent picks one, more or less arbitrarily, and now its behavior looks random — which is the symptom people usually misdiagnose as the model being unreliable. That last one is worth sitting with. When an agent behaves inconsistently across similar tasks, the instinct is to blame the model or add *another* rule. Often the real cause is that you've given it two rules and asked it to guess. ## The symptoms, before you go looking You can usually feel this before you can point at it. The agent starts doing things you don't remember asking for, and when you grep the instructions, there it is — a line from months ago you'd completely forgotten writing. Or it does the right thing four times out of five, and the fifth is a coin flip. Or you find yourself correcting the same class of thing in review over and over, adding a clarification each time, and the clarifications aren't helping. That's the tell: if adding rules isn't improving behavior, the problem isn't a missing rule. It's the pile. Honestly, the strongest signal is simpler. When was the last time you read your instructions file top to bottom? If you can't remember, you're not maintaining a document, you're maintaining a sediment layer. ## Treat it like code, because it is The fix isn't clever. It's just deciding that this file has an owner and a lifecycle, the same as any other part of the system. **Read it end to end on a schedule.** Not when something breaks — on a cadence. It takes ten minutes. You will find at least one line that describes a project that no longer exists. **Delete aggressively.** This is the part people won't do, so let me put it plainly: a rule you can't justify today is doing damage today. It's consuming context, and it's a coin-flip waiting to happen when it eventually contradicts something newer. If you're wrong and it mattered, you'll find out fast and can put it back in thirty seconds. That's a cheap mistake. Carrying twenty dead rules is not. **Prefer describing the system over listing incidents.** "Feature code lives under `src/features/{feature}`, and anything shared moves to `src/shared` only when a second feature needs it" is worth ten rules about specific files. Principles survive refactors. Incident notes don't. **Hunt contradictions directly.** When you review, don't just ask *is this line true?* Ask *does this line disagree with another line?* Contradictions are the expensive failure here, and they're invisible unless you're specifically looking. **Update instructions in the same commit as the change.** You renamed the folder — the rule mentioning that folder is part of the rename. This is the one habit that stops rot at the source, and it costs nothing once it's automatic. ## I've had to redo this myself I'm not writing this from the outside. The memory system on this site is exactly this problem in a different shape — a set of files an agent reads before it does anything, describing conventions and decisions. I wrote up the first version, published it, and then [redesigned the whole thing after a few weeks of actually using it](/blog/ai-agent-memory-redesign). Not because the original idea was wrong, but because the first design let information accumulate without ever forcing anything out. The rules that ended up mattering were about *overwriting* rather than appending: this file gets rewritten in full, that entry gets edited in place rather than duplicated, completed items get deleted rather than archived. Not because deletion is elegant. Because anything that only grows eventually stops being read — by me, and by the agent. That's the lesson I'd extract for instructions generally. The interesting design question isn't what to write down. It's what forces something to leave. ## Small is a feature There's a version of this article that ends with "so audit your rules regularly," and that's true but weak. The stronger claim is that the size of an instruction file is itself a quality signal, in the wrong direction. A short, current, internally consistent set of rules beats a comprehensive one, every time. The agent reads all of it. You can hold all of it in your head. When something's wrong you can find it. A long file fails on all three, and it fails invisibly, which is the worst property a piece of configuration can have. So the question I'd ask about your instructions isn't whether they're thorough. It's whether you'd be comfortable reading them out loud to a new engineer joining tomorrow — and how many lines you'd catch yourself apologizing for on the way through. If you've found a maintenance rhythm that actually sticks — something better than "review it when the agent embarrasses you" — I'd like to hear it. That's the part I'm still refining. --- # They Asked Me to Build a Slider. It Was a Much Better Question Than I Thought. Canonical: https://ma-x.im/blog/the-slider-interview Author: Maksym Kuzmitskyi Published: Aug 30, 2026 I sat down for a technical interview recently and got handed this: here's a React page, here are ten image URLs from the internet, build a slider. Next button, previous button, a row of dots underneath. Click a dot, jump straight to that slide. No animation needed. My honest first reaction was *is this it?* I'm an architect. I'd come in expecting to defend some structural decision, argue about boundaries, maybe get grilled on a system design. Instead I got a task I'd have called kindergarten-level on paper. Then I started typing, and about thirty seconds in I got genuinely interested — not in the slider, in what the slider was doing to me. ## The first thirty seconds Before writing anything I asked questions. Do you want keyboard support? Should it wrap around? Do the images need preloading? Some of those got a *no, don't worry about it*. Fine — that's an answer, and now the scope is pinned down instead of assumed. Then I opened the component and the first thing I wrote was state: ```tsx const [currentSlide, setCurrentSlide] = useState(0); ``` One value. That's all this thing needs to know about itself — which slide is showing. Everything else is derived. And the second thing I wrote was three empty functions: ```tsx const handleNext = () => {}; const handlePrevious = () => {}; const handleSelectSlide = (index: number) => {}; ``` Empty. Nothing inside them. I hadn't decided the boundary behavior yet, hadn't written a single `div`. I just named the three things this component can *do*, and then kept going. I want to be careful here, because this is the part I actually find interesting and it would be easy to oversell. I'm not claiming that's the One True Order. But sitting there, watching myself do it, I realized I had described the entire component — its state and its complete behavior surface — before rendering anything. The markup afterwards was almost mechanical. There was nothing left to decide. > The interesting part of a trivial task isn't whether you finish it. It's what you reach for first. ## The same task, three ways I've never sat on the other side of the table scoring people on this, so take what follows as a hypothesis rather than a verdict. But I think this task separates approaches cleanly, and the separation has nothing to do with knowing React. **Start from the markup.** Drop in a `div`, put an `img` in it, add two buttons. Then wire up the next button — oh, that needs a handler, scroll back up, write one. That needs state — scroll up again, add `useState`. Then the dots, which need to know the active index, which means going back to think about what the index actually means. The code arrives, but it arrives by accretion, each piece pulling the previous one apart a little. **Start from the pieces, one at a time.** State first, then a handler, then the markup for that handler, then the next handler. Better — but each behavior is decided in isolation, so the boundary rules ("what happens at the last slide?") get discovered one at a time, in the middle of writing JSX, when you're least set up to think about them consistently. **Start from state and behavior as a set.** One `useState`, three named handlers, all declared before anything renders. The boundary question surfaces immediately and gets answered once, for all three, because they're sitting right next to each other. Then you render. The difference isn't skill with React. All three people finish. The difference is whether the shape of the component was decided up front or discovered by bumping into it, and *that* is the thing this dumb little task exposes with surprising precision. ## Then they made it worse, and that's when it got good Part two: show three images per page instead of one. And add looping — from the last page, next goes to the first; from the first, previous goes to the last. That sounds like a small tweak. It isn't, and this is the bit I enjoyed. In the one-image version, the natural move at the end is to disable the button: ```tsx ``` The boundary is handled in the *markup*, as a disabled state. Now change the rules. With three-per-page and wrapping, "the end" isn't the last image anymore, it's the last *page* — and there's no such thing as the end, because it wraps. The button is never disabled. The logic moves out of the JSX and into the handler: ```tsx const pageCount = Math.ceil(images.length / imagesPerPage); const handleNext = () => { setCurrentPage((page) => (page + 1) % pageCount); }; const handlePrevious = () => { setCurrentPage((page) => (page - 1 + pageCount) % pageCount); }; ``` Two things changed underneath, and neither is visible in the requirement as stated. The unit of state stopped being *which image* and became *which page*, which is a different concept that happens to look the same on screen with ten images and one per page. And the boundary rule migrated from a rendering concern to a behavioral one. If your first version had the wrapping logic smeared across the JSX, this is where you pay. If it was already sitting inside three named handlers, you edit two lines. Ten images, three per page, and suddenly the task has an actual opinion about your first draft. ## Say it out loud or none of this counts Here's the thing that makes the whole exercise work, and it's not the code. Nobody watching can see you reason. They see a cursor. So I narrated the entire time: *I'll start with state — I think all I need to store is which slide is selected. Now the handlers. I'm not going to build arrow-key navigation unless you want it, just next and previous buttons.* And the answer came back: yeah, that's fine, don't bother. That exchange took four seconds and it removed a chunk of work I would otherwise have guessed at. More importantly, it made my reasoning visible. Someone watching me could tell *why* the code was landing in that order, which is information they cannot get any other way. This is the same argument I made in [the piece on interviewing senior engineers](/blog/interviewing-senior-engineers) from the interviewer's side: the signal is in the reasoning, not the artifact. Sitting on the candidate side of it, I'd put it even more bluntly. If you think silently and produce correct code, you've handed over the least interesting half of what you know. ## And yes, I used Google At one point I needed to iterate a fixed number of times to render the dots. The simplest thing is: ```tsx {Array(pageCount).fill(0).map((_, index) => ( handleSelectSlide(index)} /> ))} ``` And I blanked on it. Couldn't remember how to make an empty array of a given length. So I asked whether I could look it up, they said sure, I looked it up, and moved on. I'd like that to be unremarkable, because it should be. Forgetting a piece of syntax you type maybe twice a year says nothing about anything. What would actually have mattered is if I hadn't known *what I was reaching for* — that I needed a fixed-length iteration, that the dots derive from page count rather than being their own state. That part I never doubted. The incantation to produce the array is a lookup. The failure mode isn't forgetting an API. It's not knowing what shape of thing you need. ## What I took from it I don't know how the interview went. Genuinely — no result yet, and I'm writing this without one. But I came away thinking the task was much smarter than it looked, and I'd been slightly snobbish about it in the first minute. A hard problem mostly tells you whether someone has seen that problem before. A trivial problem, watched closely, tells you the order someone's mind moves in — and then a small twist tells you whether their first draft was structured or just correct. The slider was never the point. It was a transparent object they could watch me think through, and it cost them ten minutes to set up. If you're interviewing people and reaching for something elaborate, I'd at least consider the opposite: take something almost insultingly simple, watch the first thirty seconds, then change one requirement. And if you've been on the receiving end of a task like this and read it as disrespect — I did too, briefly. I'd like to hear whether you changed your mind the way I did. --- # React Gives You the Loading State. It Does Not Give You Cancellation. Canonical: https://ma-x.im/blog/react-playbook-abort-controller Author: Maksym Kuzmitskyi Published: Aug 28, 2026 The [error handling article](/blog/react-playbook-error-handling) argued that failures are a product decision — what breaks, how loudly, and what the user does next. There's one failure mode it didn't cover, and it's the one that produces the weirdest bug reports. Not "the request failed." The opposite: the request *succeeded*, just too late, and nobody wanted the answer anymore. React 19 made the front half of this much nicer. `useActionState` gives you the pending flag without a single `useState`: ```tsx const [result, submitSearch, isPending] = useActionState(searchPoliciesAction, null); ``` Three values, one line, and the loading state is handled. That used to be four lines of ceremony and at least one bug where `setLoading(false)` didn't run on the error path. Real improvement. But look at what `isPending` actually tells you. It says React is still waiting on *this* action. It says nothing about the fetch you fired ninety milliseconds ago that's still in flight somewhere over the Atlantic. React flipped a boolean. The network doesn't know that happened. > A spinner that stops is a UI event. A request that stops is a network event. React only does the first one. ## The bug that survives `isPending` Type into a search box. Every keystroke fires a request. Responses come back whenever they feel like it — the one for "poli" leaves first, the one for "policy" leaves second and returns first, then "poli" lands and overwrites it. Now the input says *policy* and the list below shows results for *poli*. The UI is not loading. The UI is not erroring. The UI is confidently wrong, and it stays wrong until the user touches something. This is a race, and pending state cannot fix a race. `isPending` was true, then false, exactly as designed. What you needed was for the earlier request to *stop existing* the moment it stopped mattering. That's the job AbortController does, and it's the reason I think it deserves a chapter of its own rather than a footnote in a data-fetching post. Honestly, I think the main reason this stays exotic is the name. `AbortController` sounds like something you'd find in an operating systems textbook. The actual API is three things. ## The whole API, in about ten lines ```ts const controller = new AbortController(); fetch('/api/policies', { signal: controller.signal }); controller.abort(); ``` That's it. You make a controller, you hand its `signal` to whatever is doing the async work, and calling `abort()` tells that work to give up. The pending `fetch` rejects immediately. Two details worth knowing up front, because they're where people trip. First, a signal is single-use. Once a controller is aborted, it stays aborted forever — you don't reset it, you make a new one. One controller per request, not one per component. Second, aborting rejects the promise. It doesn't quietly resolve to nothing. Which brings us to the mistake I'd bet is the single most common one in this whole area. ## Cancellation is not a failure When you abort a fetch, it throws. If you have a normal `try/catch` around it, that `catch` runs, and unless you say otherwise the user gets an error state for something *you* deliberately caused. I've seen this produce red toasts on perfectly healthy apps. Navigate away from a page mid-load, and the app cheerfully informs you that something went wrong. Nothing went wrong. You left. So the rule that matters more than any other in this article: ```ts try { const response = await fetch(url, { signal }); return await response.json(); } catch (error) { if (error instanceof DOMException && error.name === 'AbortError') { return; // we cancelled this on purpose — not a user-facing failure } throw error; } ``` An abort is an instruction you gave. It should never reach your error UI, your toast system, or Sentry. Treat it as control flow, not as a fault. There's a newer, cleaner way to express the same check if you already have the signal at hand: ```ts if (signal.aborted) return; ``` Same idea, less `instanceof` archaeology. Both are fine. What's not fine is letting the abort fall through into the same branch as a 500. ## The small version that covers most cases Here's the shape I'd reach for by default. A ref holding the current controller, aborted right before the next request starts: ```tsx function PolicySearchPanel() { const inFlight = useRef(null); const [policies, searchPolicies, isPending] = useActionState( async (_previous: Policy[] | null, formData: FormData) => { inFlight.current?.abort(); const controller = new AbortController(); inFlight.current = controller; const query = String(formData.get('query') ?? ''); const response = await fetch( '/api/policies?query=' + encodeURIComponent(query), { signal: controller.signal }, ); return (await response.json()) as Policy[]; }, null, ); useEffect(() => () => inFlight.current?.abort(), []); return (
); } ``` Two lines do the real work. `inFlight.current?.abort()` kills the previous request before starting a new one, so the stale response can never land. The `useEffect` cleanup aborts on unmount, so navigating away doesn't leave a request writing into a component that no longer exists. That's the universal, boring version. It isn't clever and it doesn't need to be. Most cancellation bugs I can think of are covered by exactly those two moments: *something newer started*, and *the thing that wanted this is gone*. Notice what `useActionState` is and isn't doing here. It owns `isPending` and the result value, which is genuinely less code than before. The cancellation is still entirely yours. The new hooks didn't make this obsolete — they made the missing half more visible, because now the only thing you're hand-rolling *is* the abort. ## The signal has to reach the bottom Here's where this stops being a component concern and becomes an architecture one. Most apps don't call `fetch` in components. They call `policiesApi.search(query)`, which calls a shared `httpClient`, which eventually calls `fetch`. If any layer in that chain doesn't take a signal, cancellation dies there — and you'll be sitting in the component wondering why abort does nothing. So the API layer needs to pass it through, all the way down: ```ts export async function searchPolicies( query: string, options?: { signal?: AbortSignal }, ): Promise { const response = await httpClient.get( '/api/policies?query=' + encodeURIComponent(query), { signal: options?.signal }, ); return response.data; } ``` An optional `signal` on every async function that touches the network. It costs nothing at the call sites that don't care, and it's the difference between cancellation being available and being theoretically available. This is also why I'd rather teach the primitive than the library helper. TanStack Query already hands your query function a signal — you just have to *use* it: ```ts useQuery({ queryKey: ['policies', query], queryFn: ({ signal }) => searchPolicies(query, { signal }), }); ``` That signal is there in every TanStack Query app in the world, and a lot of them pass it nowhere. The library already solved the plumbing. If your own layers drop the signal on the floor, the plumbing has nothing to plug into. ## Two extras that are worth knowing Timeouts, without the `setTimeout` dance: ```ts fetch(url, { signal: AbortSignal.timeout(8000) }); ``` And combining reasons to stop — say, "cancel if the user navigates away *or* if eight seconds pass": ```ts const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(8000)]); ``` A timeout abort surfaces as a `TimeoutError` rather than an `AbortError`, which is exactly what you want: one of those deserves a message to the user, the other doesn't. That distinction is the whole game — *why* did this stop, and does the person staring at the screen need to know? ## What to actually remember Strip it down and there are maybe five things: - One controller per request. Never reuse an aborted one. - Abort the previous request before starting the next one. - Abort on unmount. - Never show an abort in the UI. It's control flow, not an error. - Accept an optional `signal` in every async function that reaches the network, or the chain breaks. Nothing there is advanced. It's five habits, and once they're muscle memory you stop writing an entire category of bug — the stale-write, the ghost update, the error toast on a page you already left. ## The part I keep coming back to What strikes me about React 19's async story is how much it improved the *visible* half of the problem. Pending state used to be where the boilerplate lived, and now it mostly isn't. That's real, and I'd take it every time. But it makes the asymmetry sharper. The framework got better at telling you it's waiting, and no better at stopping the thing it's waiting for — because it can't. React owns the component tree. It doesn't own the network. The moment you fire a request, you've created something that outlives React's opinion of it, and the only way to reel that back in is to have kept a handle on it. AbortController is that handle. It's fifteen lines of very unglamorous code, and I'd argue it's the difference between an app that *looks* responsive and one that's actually consistent with what the user is doing right now. If you've got a cancellation pattern that's held up better than the ref-and-cleanup version above — especially in bigger apps where requests fan out across several layers — I'd genuinely like to see it. Send it over. --- # Evaluation Is the Missing Loop in Agent Workflows Canonical: https://ma-x.im/blog/agent-playbook-evaluation-is-the-missing-loop Author: Maksym Kuzmitskyi Published: Aug 26, 2026 Agent workflows are unusually easy to improve by accident. You change an instruction. The next run looks good. You add another rule. A different task breaks. You give the model a stronger prompt. The original failure disappears, but a new one appears somewhere else. After a few weeks, you have a growing pile of instructions and no reliable answer to the only question that matters: is the agent actually better? > If you do not replay the same work, you are measuring your mood about the last run, not the quality of the system. ## The demo is not an evaluation A successful demo proves that one path worked once. Agent workflows need more than that because the system is probabilistic and stateful. Small changes in context, tool output, or task wording can produce a different path. An evaluation starts with representative work. Real tickets. Real repository structure. Real conventions. Not a toy prompt that makes the workflow look clean. The task should have a clear expected result, but not necessarily one exact sequence of actions. If the agent takes a different safe path and produces the right change, that should count as success. Evaluate the outcome and the important constraints, not theatrical obedience. ## What to measure Correctness comes first: did the implementation solve the task? Then check the engineering constraints: did it touch the right boundary, preserve existing behavior, run the required checks, and produce a reviewable change? There are operational measures too. How many tool calls did the run take? How often did it ask for help? How much did it cost? Did it retry the same action? Did it stop at the right boundary? You do not need a giant scorecard. Start with five or ten tasks that represent the work you actually care about and a short list of pass conditions for each. A task can pass while still teaching you something. The agent may have reached the result through a fragile route, used twice as many calls as necessary, or relied on a lucky document lookup. Record those details. Evaluation is not just a gate; it is a source of better design. ## Keep failures concrete "The agent was confused" is not a useful failure record. Write what happened: it selected the wrong package because two tools had overlapping names; it guessed a story-point estimate when the ticket was ambiguous; it changed a shared component without checking its consumers. Then classify the failure. Was context missing? Was a tool too broad? Was the instruction ambiguous? Was the permission wrong? Did the task itself lack an expected outcome? This classification keeps the fix proportional. Do not add a paragraph of prompt text to solve a permission problem. Do not add a new tool to solve a missing acceptance criterion. ## Test the workflow, not only the final diff The final code can look correct while the path to it is unsafe. An agent may edit production configuration, ignore a required check, or make a destructive action and then repair the result. The diff hides that story. For important workflows, record the trace: the decisions, tool calls, approvals, retries, and stop conditions. You are looking for behavior that will fail on a slightly different task. This is where the previous articles meet. The context should be sufficient. The tools should be narrow. The agent should ask at sharp edges. The guardrails should cap the run. Evaluation is the feedback loop that tells you which of those parts is weak. ## Do not overfit the benchmark A benchmark can become another form of theater. If you keep rewriting the test until the agent passes, you are measuring how well the test has adapted to the agent. Keep some tasks private or rotate them. Add a fresh real task occasionally. Compare the agent's performance against a human review standard, not only against yesterday's score. Also keep a manual path. An agent that passes a benchmark but makes work harder for the person reviewing it is not helping. The system should reduce cognitive load, not move the same uncertainty to the final reviewer. ## The reframe Prompt editing feels like progress because the feedback is immediate. Evaluation feels slower because it asks you to repeat work you already did. That repetition is the point. Without it, every improvement is anecdotal and every regression can hide in a different task. I would rather have a small honest suite of real tasks than a dashboard full of synthetic numbers. The goal is not to prove that the agent is intelligent. It is to know whether it can perform the specific work I am asking it to perform, within the boundaries I am willing to give it. Take the last five agent tasks that required correction. Turn them into a tiny evaluation set. Write down what success means, replay them after the next change, and keep the failures visible. That is how an agent workflow becomes an engineered system instead of a collection of hopeful instructions. --- # Memory Is Not a Bigger Context Window Canonical: https://ma-x.im/blog/agent-playbook-memory-vs-context Author: Maksym Kuzmitskyi Published: Aug 24, 2026 The easiest way to misunderstand agent memory is to treat it as a transcript that never ends. Keep every message. Keep every tool call. Keep every correction. Eventually the agent will know everything that happened. It will also have to search through everything that happened before making a simple decision, and it will not know which old decision is still valid. That is not memory. It is an attic. > Memory is not everything the agent has seen. It is what the next run needs to know without making the same mistake again. ## A transcript records; memory changes the baseline A transcript is valuable for audit and debugging. It tells you what the agent did, what tools returned, and where the run went wrong. But a future session does not need the whole conversation. It needs the durable result. The branch convention belongs in memory. The abandoned approach probably does not. The decision to ask before estimating an unclear ticket belongs in memory. The five speculative alternatives discussed before that decision probably do not. This distinction matters because a transcript is chronological while a working memory should be organized around use. The agent needs current facts, active constraints, decisions, and lessons. It does not need to relive every path that led there. ## Four useful kinds of memory I would keep project memory small and explicit. **Facts** describe stable reality: where the application lives, which command runs the checks, which service owns an endpoint, which branch is the production branch. **Decisions** record choices that future work must respect: why one workspace contains several repositories, why a boundary is intentionally strict, why a tool is read-only. **Lessons** capture failures and their prevention: update main before branching, do not use a broad mutation tool, stop when the same check fails repeatedly. **Tasks** describe what is active now. They should expire. A completed task is not a fact about the project and should not remain forever just because it once mattered. The categories are useful because they give old information an expiration policy. Facts change slowly. Tasks change quickly. Lessons should be revisited when the workflow changes. ## Current beats historical The hardest memory bug is stale truth. An agent reads an old instruction that sounds authoritative and follows it after the codebase has moved on. Every durable memory item needs an owner and a way to become obsolete. Keep dates where they help. Prefer one current entry over a pile of corrections. Remove a rule when the system no longer needs it. A memory store that only grows becomes another source of context pollution. This is the same principle as code. Dead code is not harmless because it is still readable. Dead instructions are not harmless because an agent can still follow them. ## Write memory at the correction point The most useful time to update memory is immediately after a mistake has been understood. Not after a month of similar failures. Not as a quarterly cleanup exercise. The entry should be short and operational: what happened, why it happened, and what rule prevents it. "The build failed" is not a lesson. "The sitemap imports every post, so an unescaped backtick in any content field breaks the build" is a lesson because it changes the next action. This is how the agent improves without pretending the model itself has permanently changed. The next session inherits the correction because the environment carries it forward. ## Memory needs boundaries too Not every project should share the same memory. A global preference can be useful. A repository-specific deployment rule can be dangerous when applied elsewhere. Scope matters: user memory, workspace memory, project memory, and task memory should not all be one undifferentiated folder. The agent should know where a rule came from and how far it applies. A local convention is not a universal law. A temporary workaround is not architecture. ## The reframe A bigger context window lets an agent carry more text. Good memory lets it carry the right lessons. Those are different capabilities. One delays forgetting. The other improves the starting point. When I add something to agent memory now, I ask whether it will change a future decision. If not, it probably belongs in a log, a document, or nowhere. Memory is a control surface for behavior, not a museum of conversations. Open your current agent instructions and find one paragraph that no longer changes what the agent does. Delete it. Then find the last correction you repeated twice and turn it into one short rule. That is a better memory system than a thousand more lines of transcript. The final question is how to know whether these rules actually improve the agent. Good intentions are not an evaluation strategy. --- # When an Agent Should Ask Instead of Acting Canonical: https://ma-x.im/blog/agent-playbook-when-to-ask Author: Maksym Kuzmitskyi Published: Aug 22, 2026 The most frustrating agent is not the one that asks too many questions. It is the one that asks about harmless details and confidently guesses at the dangerous ones. "Which branch should I use?" after you have defined the convention is noise. "Should I push this change to production?" is exactly the question you want. That difference is the whole design problem. An agent should not be maximally autonomous. It should be autonomous in the places where its decisions are clear, reversible, and within the rules you have agreed on. > Autonomy is not a volume knob. It is a map of decisions, boundaries, and consequences. ## Not every uncertainty matters equally An agent can be uncertain about a variable name and still make a safe choice. It should not be equally free to guess about an unknown business rule, a missing permission, or a destructive operation. I find it useful to separate decisions into three questions: - Is the intent clear? - Is the action reversible? - Is the consequence contained? When all three answers are comfortable, the agent can act. When one is uncertain, it may need a check. When several are uncertain, it should stop and ask before touching anything important. This gives autonomy a shape. The agent is not trusted because it sounds confident. It is trusted because the decision sits inside a boundary we understand. ## Make the safe path obvious Asking is not automatically good. An agent that responds to every small ambiguity with a question simply moves the work back to you. The goal is not to eliminate judgment. It is to reserve human judgment for the decisions where it has the highest value. That means documenting defaults. If the branch name follows a convention, the agent should know it. If a missing estimate means "ask only when the ticket is genuinely unclear," write that down. If a draft pull request is safe but merging requires approval, make the two states distinct. The agent should not ask because it lacks courage. It should ask because the workflow tells it this decision belongs to a person. ## Use staged actions A dangerous action becomes easier to govern when it is split into stages. Instead of one tool that changes production, expose inspection, preview, and apply as separate steps. The agent can read the current state. It can prepare the proposed change. It can show the effect. A person can approve the final operation. This pattern is useful far beyond deployment. A pull request can be drafted before it is merged. A database migration can be generated and checked before it runs. A bulk update can produce a count and sample before it changes records. The agent keeps momentum through the reversible work. The human appears at the sharp edge, where a mistake becomes expensive to undo. ## Ask with a decision, not a shrug There is a big difference between "I am not sure what to do" and a useful escalation. A good question contains the context, the options, the recommendation, and the consequence of each choice. For example: "The ticket has no story points. I estimate it as five because it touches the policy form and validation flow, but the description does not say whether the API changes too. Should I use five, or wait for clarification?" That is not the agent giving up. It has done the investigation and isolated the unresolved decision. The human only needs to resolve the part that genuinely depends on intent. Poor escalation pushes the whole problem back: "Please clarify the task." Good escalation makes the remaining uncertainty small. ## Change the boundary when the workflow matures The right boundary is not permanent. Early in a workflow, the agent may need approval to open a pull request. After enough successful runs, drafting the pull request can become automatic while merging remains protected. This is how I would increase autonomy: one decision at a time, based on evidence. Do not grant a broad permission because the demo looked good. Move one reversible action across the boundary, observe the results, and keep the approval where failures would be costly. A rule that nobody revisits becomes a superstition. A rule that is changed after evidence becomes an operating model. ## The reframe People often ask whether agents are ready to work autonomously. That question is too blunt to be useful. Ready to do what, with which permissions, under which stop conditions, and with what recovery path? A good agent can act independently for a long stretch and still be designed around human judgment. The human does not need to approve every keystroke. The human needs to own the decisions that carry intent, irreversible consequences, or unclear authority. Look at the last time your agent asked a question. Was it asking about the right thing? Now look at the last time it guessed. That comparison will show you where the boundary actually belongs. Once the boundary is clear, the next challenge is continuity. An agent that learns a rule in one session but forgets it in the next is not autonomous. It is repeatedly starting over. --- # Tools Are Part of the Agent's Intelligence Canonical: https://ma-x.im/blog/agent-playbook-tools-are-intelligence Author: Maksym Kuzmitskyi Published: Aug 20, 2026 People talk about giving an agent more tools as if they were adding buttons to a control panel. Add Jira. Add Confluence. Add GitHub. Add Postman. Now the agent is more capable. Sometimes it is. Sometimes you have just built a larger menu of ambiguously named actions and made it harder for the agent to choose correctly. A tool is not an API wrapper from the agent's point of view. It is a piece of reasoning infrastructure. Its name, description, parameters, return value, permissions, and failure behavior all shape the decisions the agent can make. > A tool is part of an agent's intelligence because it determines what the agent can know and how safely it can act. ## The hidden cost of a bad tool Imagine a tool called update_issue. It accepts an issue ID and a free-form payload. Technically, it can do everything: change the status, assign an owner, move the issue to a sprint, add a comment, or alter an estimate. It is also asking the agent to reconstruct your entire process from one dangerous verb. A better interface exposes the meaningful actions separately. Assign the issue. Move it to In Progress. Add it to the current sprint. Set story points. Each action has a narrower purpose and a smaller set of valid inputs. The agent has fewer ways to misunderstand the operation. This is the same reason good application code uses domain functions instead of one universal mutate function. The boundary carries meaning. ## Descriptions are executable design Humans can fill in missing details from experience. Agents cannot reliably do that, especially when several interpretations are plausible. A tool description should answer the questions an agent will have at the moment of choice: - What does this action change? - What does it leave untouched? - When should it be used? - What does success look like? - What happens when the requested state is already true? - Which actions are forbidden or require confirmation? A description that says "updates a ticket" is almost empty. A description that says "moves an assigned ticket into the current sprint without changing its estimate" gives the agent an actual contract. The return value matters just as much. Returning "done" hides the new state. Returning the issue ID, status, assignee, sprint, and a clear error gives the next step something reliable to reason from. ## Prefer tools that make wrong actions difficult The best tools do not merely explain the right behavior. They make common wrong behavior hard to express. This is the poka-yoke idea applied to agent interfaces: shape the tool so a mistake becomes impossible or obvious. A tool that opens a pull request should not silently choose the base branch. A deployment tool should expose the target environment explicitly. A production mutation should not look identical to a staging mutation with one invisible string changed. Narrow parameters help. Typed enums help. Read-only previews help. Separate approval actions help even more. The agent should be able to inspect what it is about to do before it commits to the irreversible part. That is not excessive ceremony. It is how you move risk out of the model's free-form language and into a boundary you can test. ## One excellent tool beats five overlapping ones Tool count is another place where agent design starts to resemble multi-agent design. More looks more capable. In practice, overlapping tools create routing uncertainty. The agent spends tokens deciding which nearly identical action to call, then has to recover when the chosen tool has subtly different semantics. I would rather expose one clear tool for a meaningful operation than five endpoints that reflect how the backend happens to be organized. The agent does not need to see your internal service decomposition. It needs a stable action model. This is also where MCP servers can either help or hurt. Connecting Jira, Confluence, docs, and Postman gives an agent access to the world. But access alone is not context. Each server still needs coherent names, useful descriptions, predictable errors, and permissions that match the workflow. ## Design tools from the failure backwards Start with a real mistake. The agent branched from stale main. It guessed a story-point estimate. It used the wrong API endpoint. It opened a pull request without the required context. Now ask which tool boundary allowed the mistake. Was the information missing? Was the action too broad? Could the tool have returned the state the agent needed? Did the agent have a safe way to ask for confirmation? Fix the boundary, not just the prompt. A prompt correction helps one context. A better tool helps every future context that reaches the same decision. ## The reframe We usually describe tools as the agent's hands. I think they are closer to its senses and its joints. They determine what it can perceive, which movements are available, and where the force of a bad decision lands. A strong model with weak tools is a talented engineer working through a broken dashboard. A modest model with clear, narrow, truthful tools can often do much better because the environment removes whole categories of error. Look at the most important tool your agent uses today. Can it explain its contract? Can it show the state it changed? Can it make a dangerous action explicit? If not, that tool is not finished just because the API call works. The next boundary is not a tool at all. It is the moment where the agent should stop, surface uncertainty, and let a person decide. --- # The Context Is the Product Canonical: https://ma-x.im/blog/agent-playbook-context-is-the-product Author: Maksym Kuzmitskyi Published: Aug 18, 2026 A model can be brilliant and still be useless in your project. Give it a ticket with no surrounding context, a repository with no map, and a handful of tools with vague descriptions. It will produce something plausible. That is exactly the problem. Plausible is not the same as correct. I used to think of context as the thing I supplied to an agent before the real work began. The prompt, the files, the issue. Now I think that is backwards. Context is not the preamble to the work. Context is the product I am building around the model. > An agent is only as good as the world it can see before it makes a decision. ## The model is not the whole system The model gets most of the attention because it is the visible intelligence. But an agent run is closer to a small operating system than a chat completion. It has a goal, a working memory, tools, permissions, project rules, and a history of decisions. Change any of those and the same model behaves differently. That is why comparing agents by model name alone is incomplete. Two teams can use the same model and get completely different results. One gives it the repository map, the conventions, the API documentation, and a clear stop condition. The other gives it a ticket and hopes the model guesses the rest. The second team is not using a weaker model. It is giving the model a weaker world. ## Context has layers The first layer is the task: what needs to change and why. A ticket that says "fix the payment flow" is not a task. It is a label. A useful task includes the observed behavior, the expected behavior, the boundary of the change, and the check that proves it is done. The second layer is the project: where code lives, which package owns the behavior, how data moves, and which commands validate a change. This is the map that stops an agent from editing the first file whose name looks relevant. The third layer is convention. Naming, branching, testing, commit messages, API boundaries, and the moments where the agent must ask instead of guessing. Conventions turn a technically possible action into an acceptable one. The fourth layer is history. Why is this abstraction here? Which migration is still in progress? Which shortcut is deliberate? Without that history, an agent sees an odd line and helpfully removes the reason it exists. The last layer is access. A tool is part of context because it changes what the agent can know and do. Read-only access to Jira creates one kind of workflow. The ability to update a ticket and open a pull request creates another. ## More context is not always better There is a trap here. If missing context causes mistakes, the natural reaction is to attach everything. Every document, every repository, every old discussion. That creates a larger transcript, not necessarily a clearer world. Good context is selected context. It answers the next decision the agent has to make. A small project map is better than a directory dump. A short rule about API ownership is better than a hundred pages of loosely related documentation. A current decision record is better than three contradictory conversations. The test is simple: can the agent tell which information is authoritative? If it cannot, more context increases the number of ways it can be confidently wrong. ## Build the context deliberately I would start with four durable pieces: a project map, a set of working rules, a decision log, and a list of available tools. Keep each one short enough to remain current. A stale instruction is worse than no instruction because it makes the wrong action look official. Then connect the context to the workflow. When a task arrives, the agent should be able to discover the relevant feature, read the owning documentation, inspect recent decisions, make the smallest change, and run the expected check. That sequence is more valuable than a clever initial prompt. This is also why the investment compounds. Every correction that becomes a durable rule improves the next run. Every tool that removes a guess improves the next decision. Every obsolete instruction you delete removes one false path. The agent is not becoming magically smarter. The environment around it is becoming more legible. ## The reframe The exciting part of agents is usually the model. The durable advantage is the context architecture around it. Models will change. A clear project map, coherent rules, useful tools, and visible decisions will keep paying rent. So when an agent keeps making the same kind of mistake, I do not begin by asking whether I need a stronger model. I ask what part of the world was invisible, ambiguous, or contradictory at the moment it decided. That question moves the work upstream. You stop polishing prompts and start designing the environment in which decisions happen. The next question is obvious: if tools define what the agent can see and change, tool design is part of the agent's intelligence too. Take one recurring correction from your last agent session and ask what context would have prevented it. Write that context where the next session can actually find it. That is the beginning of the product. --- # Guardrails for a Runaway Agent Canonical: https://ma-x.im/blog/agent-playbook-guardrails Author: Maksym Kuzmitskyi Published: Aug 14, 2026 Everything in this cluster has circled the same failure: an agent that runs longer, spends more, and drifts further than you intended, with nothing to stop it. The [multi-agent orchestra](/blog/agent-playbook-you-dont-need-multi-agents) fractures context, the [token bill](/blog/agent-playbook-token-bill) balloons, the [scheduled loop](/blog/agent-playbook-test-on-change) burns all night. Underneath all of them is one uncomfortable property, and Anthropic name it directly: agents are stateful, and their errors *compound*. One bad step doesn't just produce one bad result — it changes the state the next step reasons from, so the agent quietly walks off in a completely different direction and has no idea it's lost. That's the thing traditional software doesn't really do. A bug usually breaks a feature and stops. An agent's bug can send it on a confident, expensive journey to nowhere. So the design question isn't "how do I make the agent never fail?" — you can't. It's "when it fails, how do I make sure it fails *small*?" > You don't grant an agent autonomy by trusting it. You grant it autonomy by bounding what it can do when you're wrong to trust it. ## Cap the loop The first guardrail is the dumbest one and the most important: a hard ceiling on how many steps or iterations a run can take. Anthropic build exactly this into their agents — a maximum number of iterations as a stopping condition, so a task that can't converge *terminates* instead of spinning. This is the single line that turns the overnight-burn story into a non-event: the agent tries twenty times, hits the cap, stops, and tells you it's stuck. "Burned all night" becomes "gave up before breakfast." ## Budget the spend The step cap bounds *count*; a spend cap bounds *cost* directly. Give a run a token or dollar budget and a circuit breaker that trips when it's exceeded. Even if you got the iteration ceiling wrong, the budget is a second, independent wall between a stuck agent and a catastrophic invoice. Two different limits guarding the same failure is not redundancy — it's the point. The whole philosophy here is that any single guardrail might be the one you misconfigured. ## Notice when it stops making progress A cap stops an agent eventually; progress-detection stops it *sooner*. If the agent takes the same action, gets the same result, and tries again — that's not work, that's a loop, and you can detect it. Repeated identical tool calls, the same error over and over, no change in state across steps: these are all signals that the run has stopped advancing and should be cut short. It's the difference between letting it exhaust twenty iterations and killing it at the third pointless repeat. ## Put a human at the sharp edges Not every action deserves the same freedom. Reading a ticket, running a test, opening a draft PR — low consequence, let it run. Deleting data, pushing to a shared branch, spending real money, touching production — these are where autonomy should pause and check with a person. This isn't timidity; it's the [same negotiated boundary](/blog/agent-playbook-do-it-as-usual) that makes "do it as usual" safe to run unattended. The agent owns the reversible actions and stops at the irreversible ones. You decide where that line sits per action, deliberately. ## Shrink the blast radius The guardrails above assume the agent *tries* something bad; sandboxing assumes it *succeeds* and makes that survivable. Least privilege is the whole idea: an agent that physically cannot reach production can't take it down, no matter how confused it gets. Run in an environment where the worst thing it can do is still recoverable — a scratch branch, a staging database, scoped credentials. Then a runaway is an annoyance, not an incident. ## See why it ran away You can't tighten a guardrail you can't see through. Anthropic lean hard on tracing agent decisions for exactly this reason — when an agent "can't find obvious information" or spirals, the only way to fix it systematically is to look at what it actually did, step by step. Observability isn't a nice-to-have bolted on at the end; it's how you learn which guardrail was missing. Every runaway you can inspect becomes a rule you can add. ## The reframe There's a temptation to read all of this as distrust — as clipping the agent's wings. I see it the opposite way. Guardrails are what let me hand an agent *more* autonomy, not less, because I know the failure modes are bounded. The reason I can say "do it as usual" and walk away is precisely that a stuck run caps out, a runaway can't reach anything that matters, and I can see afterward what went wrong. The bounds are what make the trust affordable. An agent without guardrails isn't a bold, high-trust setup. It's an unbounded process with a credit card and access to your systems, and the only thing standing between it and a bad night is luck. Design the blast radius first, and autonomy stops being a gamble. That's the through-line of this whole cluster: the goal was never a more impressive agent. It was a *sane* one — one you can actually let run, because you decided in advance how it's allowed to fail. Take one agent you run unattended and write down what happens if it gets stuck right now: does it stop on its own, and what can it reach while it's confused? If either answer is uncomfortable, you've found your next guardrail. Tell me which one — I'd bet it's the iteration cap, because it almost always is. --- # Test on Change, Not on a Timer Canonical: https://ma-x.im/blog/agent-playbook-test-on-change Author: Maksym Kuzmitskyi Published: Aug 12, 2026 Go back to the [overnight-burn story](/blog/agent-playbook-token-bill) for a second, because the detail that matters most is the one everyone skips past. The agent was on a *schedule*. It woke up on a timer to check the environment, over and over, whether or not anything had actually changed. The loop was the accident. The schedule was the design flaw that made the accident possible. And it's such a natural design flaw. When you want an agent to keep something healthy, the first thing your brain reaches for is a cron job: "every N minutes, go check." It feels responsible — always watching, always on. But a timer is a fundamentally lazy trigger. It fires on the passage of time, which is almost never the thing you actually care about. ## A timer runs when nothing happened Think about what a scheduled agent actually does most of the time: it wakes up, looks at an environment that is *exactly* as it left it, does a bunch of work to confirm nothing changed, and goes back to sleep. You're paying full agent price — remember, [4× a chat and up](/blog/agent-playbook-token-bill) — to repeatedly discover that nothing is different. And on the rare occasion something *is* wrong, the timer is no help there either. If the environment breaks thirty seconds after a run, your schedule sits on that failure until the next tick. So you tighten the interval to catch problems faster, which means even more empty runs, which means more cost and more surface area for exactly the kind of loop that burned all night. The timer is bad at both jobs: it's wasteful when things are fine and slow when they aren't. > A clock is not an event. Waking an agent on a schedule means waking it for no reason, most of the time — and paying for the privilege. ## Wake it on a reason The alternative is almost obvious once you name it: run the agent when something *changes*. Not "every five minutes," but "when a commit lands," "when a deploy finishes," "when a check goes red," "when this file is updated." The trigger is an event that carries actual meaning, and the agent's run is a response to that meaning. This flips every problem the timer had: - **No empty runs.** No change, no event, no run. You stop paying to confirm the status quo. - **Immediate response.** The agent reacts the moment the thing it cares about happens, not on the next tick. - **Naturally bounded work.** One event produces one run with a clear scope: "here's what changed, deal with it." That's a far easier task to reason about — and to cap — than an open-ended "go check everything." - **Debuggable history.** Every run traces back to a specific event. When something misbehaves, you know exactly what set it off, instead of squinting at a timeline of identical scheduled wake-ups. Testing is the cleanest example. Running your whole suite on a timer is nonsense — nothing changed, so nothing new can break. Running it when code changes is the entire point. The event *is* the reason the test is worth running. That principle generalizes: the right moment to act is the moment the world became different, because that's the only moment new information exists. ## The honest exceptions I don't want to pretend timers never have a place. Some work genuinely is periodic: a nightly summary, a daily digest, a report that's tied to the calendar rather than to a change. If the *business meaning* is "once a day," then a schedule is correct — the time itself is the event. But even then, two rules hold. First, it should still be bounded hard, because "runs on a schedule" and "can run forever once started" are independent properties, and the second one is what bites you. Second, be honest about whether the task is *actually* periodic or whether you reached for a timer because it was the easy primitive. Most "check the environment every N minutes" jobs are change-driven work wearing a schedule's clothing. ## The reframe The shift from timer to event is small in code — a webhook instead of a cron entry — and large in consequences. It's the difference between an agent that runs because a clock ticked and an agent that runs because something happened that it should respond to. The first is a machine idling in your driveway, burning fuel to go nowhere. The second only starts when there's somewhere to go. That overnight bill wasn't really caused by a loop. The loop was the spark. The schedule was the pile of dry wood that let a single spark burn until morning. Trigger the agent on change instead, and most of that wood is never there to catch — the agent simply isn't running when there's nothing to do. What you still need is a firebreak for the runs that *do* go wrong, and that's the last piece: [the guardrails that cap the damage](/blog/agent-playbook-guardrails). Find one scheduled agent job you're running and ask what event it's really waiting for. If you can name the change it's checking for, you can trigger on that change directly — and delete the clock. Tell me what the event turned out to be; naming it is usually the moment the cron job stops making sense. --- # You Only Get to See It From the Outside Once Canonical: https://ma-x.im/blog/the-outside-view Author: Maksym Kuzmitskyi Published: Aug 11, 2026 I was in the middle of writing this article when my wife started giving me notes on it. And I did the thing I apparently do — I pushed back. I explained that engineering is different on the inside, that the processes don't work the way she was picturing, that she was missing context. I had reasons. I always have reasons. She let me finish. Then she pointed out, pretty gently, that I had just acted out the entire premise of the article I was writing. She was the outsider looking at my argument with fresh eyes. I was the one who had already climbed inside it and could no longer see it straight. On an article that is *specifically about that*. She was out of the box. I was in it. And I couldn't tell until she said so. That small, slightly embarrassing moment is the whole thing I want to talk about. ## The asset nobody writes on the offer letter When an experienced person — an architect, a staff engineer, a senior hire — joins a project, they show up with something that has nothing to do with their résumé. For a short window, they can see the project *from the outside*. They notice the thing that makes no sense. They ask "why is it like this?" about the part everyone else stopped seeing a year ago. They feel the friction a new user feels, because right now they basically *are* a new user. That vantage point is not a bonus on top of the "real" work. For a lot of senior hires, it *is* the work — or it should be. You're not paying a premium for another pair of hands to type features. You're paying for someone who can still look at the whole thing and tell you, honestly, what's wrong with it before they've been anesthetized into thinking it's normal. > The outside view is the most valuable thing an experienced engineer brings — and it's the first thing a team destroys without meaning to. ## It has a shelf life Here's the cruel part. That view is perishable. It doesn't last. Six months in, you've internalized the map. You know where everything lives, which means you've stopped noticing that nothing *should* live there. You know why the weird thing is weird — there's a Slack thread, a migration, a reason — and knowing the reason is exactly what makes you stop seeing that it's a problem. You've learned where the bodies are buried, so you no longer notice you're standing in a graveyard. Keeping the outside view alive past that honeymoon is genuinely hard. It takes deliberate effort from the person, and — much more — a culture that protects it. Most places have neither. So the clarity that walked in the door on day one quietly evaporates, and in a year that same brilliant hire is defending the exact weirdness they were hired to question. ## How teams burn it on day one The way companies destroy this asset is almost always the same, and it's well-intentioned. They hire a senior person because there's a hot new feature, or a new branch of the product, or a fire. And then, on day one, they submerge them: *"Great, let us walk you through how everything works here."* Onboarding as immersion. The clock starts, the deadlines are already there, and the expectation is feature output by roughly week two. Think about what that does. You took the one person who could still see the project from the outside, and you rushed them inside as fast as possible. You spent their most valuable, most perishable asset on getting them productive on tickets — and you never once asked them the question only they could answer for a few short weeks: *what looks wrong to you right now, before you get used to it?* What they actually needed was a little room. Time to pick the thing up, turn it over, feel how it behaves, and notice. Time to reflect. That's not slacking; that's the senior work. But reflection has no line in the sprint, so it's the first thing the deadline eats. ## I hit this wall myself Let me be specific, because I lived the other side of this. A few years back I joined a Canadian health-tech company in a good, senior role. I was there about six months, and then we parted ways — not dramatically, but because what they wanted and what I was doing had quietly stopped being the same thing. I did a lot in those months. I set up practices, fixed how a bunch of things were used. Their setup was wild in places — a designer could change a button through an AI tool more or less directly. There was review, technically. But there was essentially *zero* consistency in the code. And every time I actually picked the project up to work in it, it came apart in my hands. Long legacy, dressed in modern libraries, with no architecture underneath — you genuinely could not tell where anything lived or why. Here's the mismatch. What I was offering them was the outside view: I'm looking at this thing fresh, and I'm telling you it doesn't hold together. That was the most useful thing I had. But what they wanted, increasingly, was for me to stop looking and start shipping — hands inside the box, features out the door. They'd hired a senior and then asked him to stop doing the senior part. I couldn't unsee what I was seeing, and they didn't want to act on it. So it ended. I'm not telling that story to settle a score. Honestly, I get it — the pressure to ship is real and it's not villainy. I'm telling it because it's the clearest example I have of a company holding a valuable asset and spending it on the wrong thing. They paid for an outside view and then treated it as an obstacle to velocity. ## For the manager, and for the senior So this cuts two ways, and I want to be clear about both, because the two audiences own different halves of the fix. If you *manage* senior hires: the outside view is an asset with an expiry date, and you are almost certainly burning it. The window where a new architect or staff engineer can tell you what's actually wrong is measured in weeks, not quarters. Protect it. Before you submerge them in "how we do things here," ask them what looks broken while they can still see it — and write it down, because in three months they won't be able to tell you anymore. And then think about the harder, cultural problem: how do you keep *anyone* on the team seeing the product from the outside once the honeymoon ends? That's the real work of engineering culture, and it doesn't happen by accident. If you *are* the senior: your value was never the volume of code you produce. Plenty of people can produce code. Your rare, decaying advantage is that right now you can still see the box from the outside. Guard it. In your first weeks somewhere new, write down everything that looks wrong, everything that makes you go "wait, why?" — because that document is worth more than the features you'll ship in that same period, and you will not be able to write it later. You'll have gone native. ## The reframe The thing that still gets me about the moment with my wife is how fast it happened, and how invisible it was to me. I wasn't being stubborn on some project I'd spent years on. I'd been inside *my own article* for a couple of days, and that was already enough to make me defend it against exactly the kind of outside perspective the article is arguing you should protect. If it happens that quickly to me, on a piece of writing, imagine what six months of deadlines does to a person's ability to see the system they work in. The outside view isn't a personality trait. It's a position — you're either standing outside the thing or you're inside it — and you lose it the moment you step in and get comfortable. Which means the whole game, for teams and for individuals, is noticing that the window is open right now, and using it before it quietly closes. Think about the last time someone from outside your project — a new hire, a designer, someone who doesn't live in the code — told you something was wrong, and your first instinct was to explain why they didn't understand. That instinct is the tell. I'd genuinely like to know what they were seeing that you couldn't — reach out and tell me, because odds are they were standing exactly where you used to. --- # The Token Bill Is Part of the Architecture Canonical: https://ma-x.im/blog/agent-playbook-token-bill Author: Maksym Kuzmitskyi Published: Aug 10, 2026 There's a story that made the rounds a while back, and I keep thinking about it. Someone set up an agent to run on a schedule — every so often it would wake up and check their environment, run some tests, make sure things were healthy. Reasonable idea. Then one night something went wrong, the agent got stuck in a loop, and instead of running for the couple of hours it was supposed to, it churned all night. By morning it had burned through an eye-watering pile of tokens doing nothing useful. It's easy to read that as "lol, watch your usage." I read it differently. That bill wasn't an accident of carelessness — it was a design that never treated cost as real. The agent had no sense that its own runtime cost money, and nothing in the system did either. And that's the norm, not the exception. We design agent workflows around capability and correctness, and we bolt cost on afterward as a thing to monitor. I think that's backwards. > Cost isn't something you check after the fact. With agents, it's a first-class architectural constraint — as much a part of the design as latency or correctness. ## Agents are expensive in a way chat isn't Let me put real numbers on it, because the gap is bigger than people expect. Anthropic published figures from their own systems: an agent uses roughly **4× the tokens** of a normal chat interaction, and a multi-agent system about **15×**. Every autonomous loop, every "let me check that again," every re-read of a big context window — it all adds up per step, and agents take a *lot* of steps. This is why Anthropic's own top-line advice for building with LLMs is to find the simplest thing that works and only add complexity when it demonstrably pays. That's not aesthetic minimalism. It's economics. Agentic autonomy trades latency and money for flexibility, and if the task didn't need the flexibility, you just paid a premium for nothing. ## Where the money actually leaks Once you start looking at cost as architecture, you start seeing where it drains: **Unbounded loops.** The overnight-burn story is the pure form. An agent that can retry forever will, eventually, retry forever. Without a hard ceiling, one stuck state is an open tap. **Agents pinging agents.** The multi-agent orchestras I complained about in [the first article](/blog/agent-playbook-you-dont-need-multi-agents) don't just fracture context — they multiply token spend. One agent asking another "are you done yet?" is a paid API call every time it asks. **Re-sending the world every turn.** If every step drags the entire history back through the model, your cost grows with the square of the conversation. Long-running agents that don't compress or summarize their context pay for their whole past on every single step. **Reaching for a big model on easy work.** Routing a trivial classification through your most capable, most expensive model is money set on fire. Anthropic explicitly route easy, common cases to a small cheap model and reserve the expensive one for the hard cases. ## Designing like the meter is running None of these are exotic to fix. They just require treating the token meter as a signal you design against, the same way you'd design against a latency budget: - **Put a ceiling on every loop.** A hard cap on iterations or steps turns "burned all night" into "gave up after twenty tries and told me." This is the first guardrail, and it's the subject of [its own article](/blog/agent-playbook-guardrails). - **Give long tasks a memory, not a longer transcript.** Summarize completed phases and store the essentials, so each step reasons over a compact context instead of re-paying for the entire history. - **Match the model to the job.** Cheap model for routing and simple calls, expensive model where the reasoning actually earns it. - **Prefer a workflow to an autonomous loop when the task is well-defined.** A fixed pipeline of LLM calls is predictable in both behavior *and* cost. You reach for open-ended autonomy when you truly can't predict the steps — not by default. ## The reframe The overnight-burn story gets told as a cautionary tale about monitoring, but monitoring is the weakest possible response — it tells you about the fire after it's out. The real fix is upstream, in the design: an agent whose cost is bounded by construction can't run up that bill in the first place, because the ceiling, the compaction, and the stop conditions were part of the architecture, not a dashboard you forgot to check. So I've started treating the token bill the way I treat a slow render or a memory leak: as a property of the system I'm responsible for shaping, not an invoice that shows up later. When I sketch an agent workflow now, "what does one run cost, and what stops it from costing a hundred times that?" is one of the first questions, not the last. The story that made the rounds is only a horror story if cost was never in the design. Put it in, and the worst case is a bounded disappointment instead of a night's worth of tokens gone. The next two articles follow this thread straight down: [when to actually run the agent](/blog/agent-playbook-test-on-change) — because that scheduled loop was the root of the burn — and [the guardrails](/blog/agent-playbook-guardrails) that cap the damage when a run goes wrong anyway. Go look at one agent workflow you run and answer a single question: what's the most it could spend if it got stuck right now? If you don't know, that's the number an attacker on your patience — a loop — already knows. Tell me what you find; the not-knowing is the whole problem. --- # Do It As Usual: Teaching One Agent Your Whole Workflow Canonical: https://ma-x.im/blog/agent-playbook-do-it-as-usual Author: Maksym Kuzmitskyi Published: Aug 08, 2026 Here's a thing I can do that sounds like a party trick. I open a brand-new session with my agent and type, almost word for word: "take ticket 123 and do it." And it does — the whole thing, end to end, without me hovering. Not because I found a magic prompt. Because I spent months teaching it what "as usual" means. I bring this up because of a complaint I keep hearing, some version of: *"I can't get my agent to just do a task. I set it loose and then I have to walk behind it fixing everything."* And look — if you started last week, that's completely fair. I couldn't either at first. But when someone's been at it for months and still can't get the agent to carry a task cleanly, I get suspicious. Not of the agent. Of how they're working with it. ## "As usual" is a lot of things Let me show you what actually happens when I say "do it as usual," because the phrase is hiding an entire workflow the agent has internalized: - It takes the ticket and assigns it to me. - It moves it to In Progress. - If the ticket was sitting in the backlog, it pulls it into the current sprint. - If it has no story points, it estimates it — and if it genuinely can't tell, it asks me, the way we agreed it would. - It creates a branch by our naming convention, after first updating main so it's not branching off something stale. - It makes the changes, committing as it goes with human-readable messages that say what was actually done. - It opens the pull request, writes a real description, adds the necessary context and links, mentions the people who need to see it, and links the PR back to the ticket. - Then it waits for the pipelines, checks whether anything went red, and fixes it if it did. All of that from four words. And none of it was true on day one. ## The part nobody wants to hear That list didn't arrive as a single clever configuration. It arrived one failure at a time. The agent would branch off stale main — so I taught it to update first. It would write commit messages like "fix stuff" — so we worked out what a human-readable message looks like. It would guess a story-point estimate confidently when it had no business guessing — so we agreed that when it's unsure, it stops and asks me instead of inventing a number. > Every step in "as usual" is a scar. It's there because something once went wrong, and I turned the fix into a rule instead of re-explaining it every session. That's the whole method, honestly. It's not prompt cleverness. It's accumulation. Each time the agent got something wrong, I didn't just correct it for that one run — I wrote the correction down somewhere durable, so the next session started from the corrected baseline. Do that for a few months across a dozen steps, and "as usual" stops being a phrase and becomes a reflex the agent actually has. ## Give it real context, not guesses The second half of this is tooling. An agent working from guesses is an agent you'll always be correcting. So I connected the things it needs to *know* the state of the world instead of hallucinating it: an MCP server to read Jira, another for Confluence, one for our docs, one for Postman — the tools the work actually runs on. The difference is night and day. When the agent can read the ticket, it doesn't misunderstand the task. When it can see the docs and the API collection, it doesn't invent an endpoint. The tools aren't there to make the agent look impressive — they're there so its decisions are grounded in what's real. This is the [augmented-LLM idea](/blog/agent-playbook-you-dont-need-multi-agents) done properly: one agent, made capable by good tools, is worth more than a crowd of agents guessing at each other's intent. ## One agent, not one per repo I told this story in [the multi-agents piece](/blog/agent-playbook-you-dont-need-multi-agents), but it belongs here too, because it's the same instinct. My project spans six or seven repositories. My first move was to set up an agent in each one. Then I noticed my tasks almost never span repos — they live in one, and multi-repo changes have come up maybe twice. So instead of maintaining seven configurations, I put every repo in one workspace and taught one agent. Every hour I *didn't* spend duplicating setup across seven repos, I spent making the single one better. That's why it can do "as usual" at all — the investment was concentrated, not scattered. ## The decision points matter most The subtle part — the thing that separates an agent that helps from one you babysit — is deciding where it should act and where it should stop and ask. I didn't tell it to just do everything autonomously. We agreed on the seams. Estimation it can't confidently do? Ask. Convention it knows cold? Just do it. That negotiated boundary is what makes "as usual" safe to run unattended. The agent isn't guessing about my intent at the risky moments, because we already talked through those moments and it knows the rule. This is why "just be more autonomous" is bad advice. Autonomy isn't a slider you crank to the top. It's a map of which decisions the agent owns and which ones come back to you — and you build that map the same way you build everything else here, one correction at a time. ## The reframe So when I hear "I can't get my agent to do a task in one shot," what I mostly hear is a missing investment. People want the "do it as usual" outcome without the months of turning mistakes into durable rules and wiring in the tools that ground the agent in reality. The agent that runs my whole ticket workflow from four words isn't smarter than yours. It's just been *taught* more, and the teaching stuck because I wrote it down instead of repeating it. The uncomfortable truth is that this looks a lot less like prompting and a lot more like onboarding a junior engineer who happens to have perfect recall. You explain the convention once, correctly, and it never forgets it — but only if you actually captured it instead of hand-waving it in a single session that evaporates when the context does. Pick the one task you do most often with your agent and write down every correction you find yourself repeating this week. That list is the start of your own "as usual." Send it to me if you want a second pair of eyes — I'll tell you which corrections are rules and which are you doing the agent's thinking for it. --- # You Probably Don't Need Multi-Agents Canonical: https://ma-x.im/blog/agent-playbook-you-dont-need-multi-agents Author: Maksym Kuzmitskyi Published: Aug 06, 2026 I work across six or seven repositories on one project — a big hybrid thing, part microfrontend, part backend, several apps that all talk to each other. When I started bringing an AI agent into that work, my first instinct was the obvious one: set up an agent in each repo. Seven repos, seven configured agents. It felt right. Each repo is its own world, so each gets its own helper. I got a couple of repos in before I stopped and asked myself what I was actually doing. My tasks almost never live in seven repos at once. They live in *one*. In months of work I've had maybe two tasks that touched multiple repos. So I was about to build and maintain seven separate agent setups to serve a reality where the work is overwhelmingly single-repo. I threw it out, put every repo into one workspace, and configured one agent, once. That agent has been better than any swarm I could have wired together — and it cost me a fraction of the effort. That small decision is the whole argument of this article, scaled up. The industry's default reflex right now is *more agents*. I think the default should be *one agent, taught well* — and you should have to justify every agent you add past the first. ## The orchestra is a status symbol Here's the thing that bugs me about most "how I use AI" posts. They read like a flex. "I built an orchestrator that spawns a planner, which hands off to a coder, which pings a reviewer, which triggers a tester." Eight agents, a diagram with lots of arrows, and the unspoken message: look how sophisticated my setup is. And honestly, some of it *would* work fine — if the coordination between the pieces were as good as the diagram implies. But that's exactly the part nobody shows you. The arrows in the diagram are doing an enormous amount of invisible work. In practice, an agent that pings another agent — "are the tasks ready yet?", "go run the tests now" — is a coordination protocol you now own, built out of the least reliable component you have: one model trying to communicate intent to another model. > The number of agents in your system is not a measure of its sophistication. It's a measure of how many places your context can fracture. ## What a second agent actually costs Let's talk about the bill, because it's the part the impressive diagrams leave out. Anthropic published numbers from their own multi-agent research system, and they're worth sitting with: a single agent burns roughly **4× the tokens** of a normal chat, and a multi-agent system burns about **15×**. That's not a rounding error. That's your token budget, tripled and tripled again, in exchange for coordination overhead. Sometimes that trade is worth it. Anthropic's own finding is that multi-agent setups genuinely win at *breadth-first* research — questions where you can fan out into many independent directions at once, each subagent exploring its own slice with its own context window, then compressing what it found. If the task is "find every board member across these 400 companies," parallel agents crush a single agent that has to plod through sequentially. That's a real, honest use case. But look closely at what makes it work: the subtasks are *independent*. One agent's findings don't change what another agent should do. That's the property that makes parallelism safe. And it's exactly the property most of our work doesn't have. ## Coding is the wrong shape for a swarm Anthropic say it plainly, and it matches everything I see: most coding tasks involve *fewer* truly parallelizable subtasks than research, and today's models aren't good at coordinating and delegating to each other in real time. Code is a web of dependencies. The change you make in one file constrains the change in the next. Split that across agents and you don't get parallelism — you get two agents making conflicting assumptions about the same system. The team behind Devin wrote a whole piece called "Don't Build Multi-Agents," and their core point is sharper than the cost argument. Every action an agent takes carries an *implicit decision*. When you split work across parallel subagents, each one makes its own implicit decisions, and those decisions quietly conflict. Their example is perfect: ask two subagents to build a "Flappy Bird clone" in parallel, and one builds a Super Mario background while the other builds a bird that moves nothing like Flappy Bird. Now your final agent has to reconcile two subtly incompatible worlds. Nobody was wrong on purpose. The context just couldn't be shared thoroughly enough for them to agree. > Actions carry implicit decisions, and conflicting decisions carry bad results. That's why even Claude Code, when it spawns a subtask, usually only asks it to *answer a question* — never to go off and write code in parallel. The subagent investigates, reports back, and the main agent keeps making the actual decisions in one continuous line of context. It's a deliberately simple design, and the simplicity is the point. ## The default should be one continuous context Strip away the fashion and the reliable pattern underneath is almost boringly plain: a single agent, working in one continuous context, making decisions in sequence. It sees everything it did earlier because it never handed off. There's no telephone game, no reconciliation step, no second model guessing at the first one's intent. Yes, you eventually hit a ceiling — a task so large the context window overflows. But the answer to that is rarely "spawn a committee." It's better context management: summarizing completed phases, storing decisions in memory, spinning up a *fresh* context with a clean handoff when you truly need one. You reach for that when the single agent stops fitting, not before — and even then you're managing context, not orchestrating a crowd. ## The real lever isn't more agents Here's what actually moved the needle for me, and it wasn't a second agent. It was teaching the *one* agent my workflow properly and giving it the right tools. I wired in the MCP servers it needs — reading Jira, Confluence, docs, Postman — so it works with real context instead of guessing. And I invested the months it took to teach it how I actually work, step by step. The payoff is that I can now start a fresh session and type "take task 123 and do it as usual," and it knows what that means: assign the ticket to me, move it to In Progress, pull it into the sprint if it's sitting in the backlog, estimate it if it has no points, branch off an updated main by our convention, commit with human-readable messages, open the PR with a real description and the right people tagged, link it to the ticket, and watch the pipeline — fixing it if it goes red. One agent. One phrase. No orchestra. That's a whole article of its own — [how I taught one agent to "do it as usual"](/blog/agent-playbook-do-it-as-usual) — and it's the honest alternative to the swarm. The effort I *didn't* spend maintaining seven setups, I spent deepening one. ## The reframe The multi-agent orchestra is seductive because it looks like engineering. Boxes, arrows, roles, a system. But most of the time it's complexity cosplaying as capability — three times the token bill, a coordination protocol built on the flakiest possible substrate, and results that are *worse* because the context keeps fracturing between the players. So my rule is simple: reach for the second agent only when you can name the work it's doing — work that is genuinely independent, genuinely parallel, and genuinely worth 15× the tokens. Research that fans out? Maybe. Almost everything else? One agent, one context, taught well. The sophistication was never in the number of agents. It was always in how much of your actual work you managed to hand off cleanly to a single one. If you're running a multi-agent setup right now, do one honest audit: for each agent past the first, write down the independent, parallel task it owns and what it costs you. If you can't name that task without hand-waving, you don't have an architecture — you have a diagram. Tell me which agent you'd delete first. --- # Code-Splitting Is a Boundary Decision, Not a Bundle Trick Canonical: https://ma-x.im/blog/react-playbook-code-splitting Author: Maksym Kuzmitskyi Published: Aug 04, 2026 The [command palette article](/blog/react-playbook-command-palette) closed by promising the last piece of this look-and-feel stretch, and it's the one that looks the most like a solved problem: code-splitting. Wrap a component in `React.lazy`, drop a `Suspense` boundary around it, watch the bundle shrink. Done, right? Here's the thing that bugs me about most bundle-size advice. It's all about the *how* — `lazy`, dynamic `import()`, the router's lazy routes — and almost none of it is about the *where*. And the where is the entire problem. Splitting code is one line. Deciding what to cut, so the app loads fast without shattering into a hundred chunks you can't reason about, is an architecture decision. Get the how right and the where wrong, and you don't get a faster app. You get a slower one with more moving parts. ## A split is not free Start with what a split actually costs, because the mental model everyone skips is that lazy-loading isn't "free performance." Every split you introduce is a boundary, and every boundary buys you three things you didn't have before: a separate network request, a loading state you now have to design, and the risk of a waterfall if that request can't start until another one finishes. > A code-split isn't a size optimization. It's a boundary you're adding to the app — and boundaries have a cost on both sides. So the real question stops being "can I split this?" (you almost always can) and becomes "is there a real seam here worth paying a boundary for?" That reframe is the whole article. ## The default that quietly backfires The advice you'll read first is "split at the route level," and honestly, that advice is correct. Route boundaries are the best seams in the entire app: the user is already waiting for a navigation, they don't expect the next screen to be instant, and each route pulls in a genuinely different slice of the app. With a type-safe router like the one from the [routing article](/blog/react-playbook-tanstack-router), lazy routes are the natural unit: ```tsx // each route is its own chunk — the user is already navigating, a boundary here is invisible export const Route = createFileRoute('/reports')({ component: lazyRouteComponent(() => import('./ReportsPage')), }); ``` Where it backfires is the next step people take. Route-level splitting works, so they conclude "more splitting is more better" and start wrapping individual components — a `UserAvatar` here, a `Badge` there — in `lazy`. Now every one of those is a network round-trip and a spinner. You've turned a single fast download into a cascade of tiny requests, each with its own loading flicker, and the page assembles itself in front of the user like a slideshow. That's not a faster app. That's the same bytes, delivered worse. ## Where the seams actually are So if "everywhere" is wrong and "routes" is the safe default, what else genuinely earns a split? Three shapes, and they all have the same property: the code is *heavy* and *not needed for the first meaningful paint*. **Heavy, rarely-used features.** A rich text editor, a video player, a PDF viewer, the [chart library](/blog/react-playbook-chart-libraries) you only render on the analytics tab. These can each be hundreds of kilobytes, and most sessions never touch them. Splitting here is pure win — the cost of the boundary is paid only by the users who actually open the feature. ```tsx // the editor is 300kb of the bundle and only the 5% who click "edit" ever need it const RichTextEditor = lazy(() => import('./RichTextEditor')); function Note({ isEditing }: { isEditing: boolean }) { if (!isEditing) return ; return ( }> ); } ``` **Behind an interaction.** Anything that only appears after a click — a settings modal, a command palette, an export dialog. The boundary hides behind the click the user already made, so the tiny load feels like part of the action, not a delay. **Below the fold, and truly optional.** The stuff a user might scroll to but often won't. Notice what's *not* on this list: anything needed for the first render, anything small, and anything that's split purely because it lives in its own folder. A 4kb component doesn't deserve a network request. The download of that request costs more than the bytes you saved. ## The waterfall you'll create by accident The nastiest failure mode isn't too many chunks — it's chunks that can't load in parallel. This is the same waterfall problem the [data-fetching article](/blog/react-playbook-data-fetching) warned about, just moved from data to code. A lazy component that, once loaded, immediately lazy-loads its own child, which lazy-loads *its* child — the browser can't start request two until request one lands. You've serialized what should have been parallel. The fix is intent-based prefetching: start fetching the chunk when the user *signals* they're heading somewhere, not when they arrive. Hovering a link, focusing a button, opening the parent — all of these are the browser's chance to fetch ahead: ```tsx // kick off the chunk on hover, so by the time they click it's already in cache import('./ReportsPage')} > Reports ``` Do this and the boundary all but disappears: the request overlaps with the user's own reaction time instead of stacking behind another request. Good routers do a version of this for you. The point is that *when* a chunk starts loading matters as much as whether you split it. ## The chunk you can't reason about Here's where splitting collides with the rest of the Playbook. Remember the [barrel-file article](/blog/react-playbook-barrel-files) — the `index.ts` that re-exports everything in a folder? Lazy-load a single component *through* a barrel, and you don't get that component. You get the whole barrel: every sibling it re-exports, dragged into the chunk because the import graph can't tell them apart. Your carefully-placed `lazy` boundary quietly pulls in half the folder, and the chunk you thought was small isn't. ```ts // looks like one small component... const Chart = lazy(() => import('./widgets').then((m) => ({ default: m.Chart }))); // ...but ./widgets/index.ts re-exports Chart, Table, Map, Calendar — all now in this chunk ``` This is why I keep coming back to the idea that these topics aren't separate. A split is only as clean as the [module boundaries](/blog/react-playbook-module-dependencies) underneath it. If your imports reach sideways through barrels and shared grab-bags, your chunks will be blurry no matter how many `lazy` calls you sprinkle in. Import the file directly, and the split is exactly as big as you think it is. ## Split where it hurts, not where the folders are The [re-renders article](/blog/react-playbook-rerenders-and-architecture) made an argument I want to borrow directly: optimize where it actually hurts, and don't let the optimization wreck the structure. Code-splitting is the same discipline one layer down. The temptation is to split on the shape of your file tree — one chunk per feature folder, because it's tidy. But the file tree is your convenience, not the user's journey. The seams that matter are the ones in *their* experience: the route they navigate to, the heavy tool they occasionally open, the dialog behind a click. Before adding a `lazy`, I ask two questions. Is this code actually heavy enough that its bytes show up in the load? And is there a real moment in the user's flow where paying for a separate request is invisible? If both answers aren't yes, the split is making the app more complex for a number that doesn't move. ## The reframe Code-splitting reads like a bundle trick and behaves like an architecture decision — which makes it a fitting end to this look-and-feel cluster, because so did theming, and so did the command palette. Each one looks like polish and turns out to be a boundary in disguise. The visible artifact is trivial: a smaller bundle, a color toggle, a search modal. The value, every time, is in where you draw the line and whether the rest of the structure lets that line stay clean. So the honest heuristic isn't "split more." It's split *rarely and deliberately*, at the seams the user can feel, over module boundaries clean enough that a chunk means what its name says. Everything else is just trading one problem you can see — a big bundle — for a dozen you can't. If you've got a build with more than a handful of chunks, pull up your bundle analyzer and find the smallest lazy chunk you have. If it's a few kilobytes, that's a boundary you're paying for and getting nothing back — tell me what it is, because I'd bet it snuck in on the "more splitting is better" reflex, and it's the first thing I'd delete. --- # The Command Palette Is an Architecture, Not a Widget Canonical: https://ma-x.im/blog/react-playbook-command-palette Author: Maksym Kuzmitskyi Published: Aug 02, 2026 The [theming article](/blog/react-playbook-theming-dark-mode) ended on a move from how an app looks to how power users drive it. The command palette — the `Cmd+K` menu that fuzzy-searches everything you can do — is the poster child for a piece of UI that people build as a widget and should build as an architecture. The difference shows up fast, and it's the difference between a palette that stays useful and one that quietly lies about what the app can do. Here's the trap. You install a nice palette component, drop a modal in, and fill it with a hardcoded list of actions: "New file," "Toggle dark mode," "Go to settings." It demos beautifully. Then someone adds a feature with its own toolbar button, forgets to also add it to the palette, and now the palette is missing things. Someone renames an action in a menu but not in the palette. Six months in, the palette is a stale, hand-maintained duplicate of logic that already exists elsewhere in the app. The modal was never the hard part. The hard part is that the palette needs to know everything the app can do — and so do the menus, and the keyboard shortcuts, and the toolbar. ## A command is a first-class object The reframe is to stop thinking about a search modal and start thinking about *commands* as data. A command is a real object: an id, a title, some keywords, the thing it does, and optionally whether it's currently allowed and what shortcut triggers it. ```ts interface Command { id: string; title: string; keywords?: string[]; // for fuzzy search: "theme", "appearance"... group?: string; // "File", "View", "Navigation" shortcut?: string; // "mod+k" isEnabled?: () => boolean; // context-aware availability run: () => void; // the actual behavior } ``` Once a command is data, the interesting shift happens: the palette stops *owning* actions and starts *rendering* them. This is the same instinct as [headless components](/blog/react-playbook-headless-components) — separate the behavior (what the command does) from the presentation (how it's listed) — and the same instinct as the [typed event catalog](/blog/react-playbook-analytics-as-a-layer) — one declared source of truth instead of scattered strings. ## The registry is the single source of truth The center of the whole design is a registry: one place every command is registered, and every surface that needs to know "what can the app do?" reads from it. ```ts class CommandRegistry { private commands = new Map(); register(command: Command): () => void { this.commands.set(command.id, command); return () => this.commands.delete(command.id); // features clean up their own } all(): Command[] { return [...this.commands.values()].filter((c) => c.isEnabled?.() ?? true); } run(id: string) { this.commands.get(id)?.run(); } } export const commands = new CommandRegistry(); ``` Now features *contribute* commands instead of the palette knowing about features: ```ts // in the editor feature — it announces what it can do, and to whom it doesn't care commands.register({ id: 'file.new', title: 'New File', group: 'File', shortcut: 'mod+n', run: () => editor.createFile(), }); ``` Notice the direction of the dependency. The editor feature depends on the registry (a stable, shared thing); the palette depends on the registry; the two features never depend on each other. That's the [dependencies-point-the-right-way](/blog/react-playbook-module-dependencies) rule holding: everything points at a shared abstraction, nothing reaches sideways. Add a feature, it registers its commands, and the palette shows them with zero changes to the palette. Remove the feature, its cleanup runs, the commands vanish. Nothing drifts because nothing was duplicated. ## One dispatcher, not scattered key handlers The keyboard shortcuts fall out of the same registry, and this is where you avoid another mess. The naive approach sprinkles `onKeyDown` handlers across a dozen components, each checking for its own combo — the same scatter problem the [event bus](/blog/react-playbook-event-bus) and analytics articles warned about, just with keystrokes. Instead, one global listener resolves keys against the registry: ```ts useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { const combo = toCombo(e); // "mod+n", "mod+k", etc. const command = commands.all().find((c) => c.shortcut === combo); if (command) { e.preventDefault(); command.run(); } }; window.addEventListener('keydown', onKeyDown); return () => window.removeEventListener('keydown', onKeyDown); }, []); ``` One place owns the mapping from keys to commands. Shortcut conflicts become detectable (two commands claiming `mod+k` is now a thing you can check for, instead of a mystery). And because `isEnabled` gates `all()`, a shortcut simply does nothing when its command isn't valid in the current context — no scattered guard clauses. ## The palette is just a view over the registry And now the part everyone thought was the whole feature is the easy part. The palette is a thin view: read the registry, fuzzy-match the query against titles and keywords, render the list, run the chosen command. ```tsx function CommandPalette() { const [query, setQuery] = useState(''); const results = useMemo( () => fuzzyFilter(commands.all(), query), // search titles + keywords [query], ); return ( setQuery(e.target.value)} placeholder="Type a command…" />
    {results.map((c) => (
  • { commands.run(c.id); }}> {c.title} {c.shortcut && {c.shortcut}}
  • ))}
); } ``` Because commands are data, you get things for free that would be painful to hand-maintain: search across everything, a "keyboard shortcuts" help screen (just render the registry grouped by `group`), and an honest answer to "what can I do here?" that's always current because it's generated, never authored twice. ## The reframe The command palette is a systems problem wearing a UI costume — the same shape as theming. The visible artifact (a search modal, a color toggle) is trivial; the value is entirely in the architecture behind it (a command registry, a token system). Build either one as a widget and it rots, because you end up maintaining the same truth in several places and they drift apart. Build it as a single source of truth that many surfaces read from, and the palette, the menus, and the shortcuts can never disagree — because there's only one thing for them to agree with. That's the through-line of this whole look-and-feel stretch: the parts of an app that seem like polish are usually boundaries in disguise, and the teams that treat them as boundaries end up with UI that scales instead of UI that quietly lies. Next the series turns to the last piece of this cluster — code-splitting, and the deceptively hard question of what to actually cut so the app loads fast without fracturing into a thousand lazy chunks you can't reason about. If your app has a command palette, open it and then open your main menu side by side. If they don't list the same capabilities, you've got two sources of truth drifting apart — tell me how far they've diverged, because that gap is the whole argument for a registry. --- # Theming and Dark Mode Without the Flash: A Systems Problem in CSS Clothing Canonical: https://ma-x.im/blog/react-playbook-theming-dark-mode Author: Maksym Kuzmitskyi Published: Jul 31, 2026 The [last article](/blog/react-playbook-rerenders-and-architecture) argued that a lot of React "optimization" is really architecture damage in disguise. Theming is a great place to keep that lens on, because it's the feature that looks the most like a trivial CSS toggle and is actually a small systems-design problem — one where the naive version fails in three specific, visible ways. You start simple. A `dark` class on the body, some overrides, a bit of React state to flip it. Ship it. Then the reports come in. The page flashes white before going dark on every load. A few components didn't get the memo and stayed light. And your theme toggle mysteriously re-renders half the app. None of these is a CSS bug exactly — they're all consequences of putting theming in the wrong layer. ## Tokens are the foundation, not the paint The first mistake is letting every component decide its own colors. `color: #1a1a1a` here, `background: #fff` there, a slightly different grey in a third place. Now "dark mode" means hunting down every hardcoded color in the codebase, and "the greys drifted" is inevitable because there was never one grey to begin with. The fix is design tokens expressed as CSS custom properties: one place that owns the actual color decisions, and components that only ever refer to them *semantically*. ```css :root { /* primitive palette — raw values, referenced by nobody directly */ --gray-50: #f9fafb; --gray-900: #111827; --green-500: #22c55e; /* semantic tokens — what components actually use */ --color-surface: var(--gray-50); --color-text: var(--gray-900); --color-accent: var(--green-500); } [data-theme='dark'] { --color-surface: var(--gray-900); --color-text: var(--gray-50); --color-accent: var(--green-500); /* accent survives the theme */ } ``` The two-layer split matters more than it looks. Primitives (`--gray-900`) are the paint box; semantic tokens (`--color-surface`) are the meaning. Components consume only the semantic layer — `background: var(--color-surface)` — so they never know or care what actual color that is in a given theme. Switching themes is now just swapping what the semantic tokens point to. And critically, a component that says `var(--color-surface)` cannot drift, because there's exactly one definition of surface per theme. This is the same "one source of truth, referenced by many" idea from [data normalization](/blog/react-playbook-data-normalization), applied to color. ## The switch doesn't belong in React state Here's the part that surprises people, and it ties straight back to the last article. Flipping the theme should not be a React re-render at all. You change one attribute on the root element — `data-theme="dark"` — and the CSS cascade does the entire rest of the work, instantly, for every element on the page, with zero components re-rendering. ```ts function applyTheme(theme: 'light' | 'dark') { document.documentElement.setAttribute('data-theme', theme); localStorage.setItem('theme', theme); // persist, as a side effect } ``` Contrast that with the common mistake: putting the theme in a React context that wraps the whole app, so that toggling it re-renders every consumer to pass down new colors. That's taking a job CSS does for free — cascading a variable change to the whole tree — and turning it into a render storm, the exact anti-pattern from the [re-render article](/blog/react-playbook-rerenders-and-architecture). Let CSS variables do what they're built for. You can still keep a *small* piece of React state for the toggle's UI (which icon to show), but the actual theming mechanism is a DOM attribute and a cascade, not a re-render. ## The flash is a rendering-order problem Now the ugliest one: the flash of the wrong theme (FOUC). On a statically exported, server-rendered site — which is [exactly this stack](/blog/nextjs-ssg-github-pages) — the server has no idea what theme the user picked. It renders the default, ships the HTML, the browser paints it, and only *then* does your React code boot, read localStorage, and correct the theme. That gap between first paint and correction is the flash, and no amount of React can remove it, because React runs too late by definition. The fix has to happen *before* first paint, which means a tiny blocking script in the document ``, before any content renders: ```tsx // injected into , runs synchronously before the body paints const themeScript = ` (function () { try { var stored = localStorage.getItem('theme'); var theme = stored || (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'); document.documentElement.setAttribute('data-theme', theme); } catch (e) {} })(); `; // in the App Router root layout export default function RootLayout({ children }: { children: React.ReactNode }) { return (