Maintaining SaaS Codebases When AI Writes More Code

November 16, 2026 | Artificial Intelligence

A SaaS codebase becomes difficult to maintain when the same business decision is implemented in several places, dependencies cross ownership boundaries, and every small change touches more of the system than expected. AI coding agents can accelerate that pattern. They can also help reverse it by writing characterization tests, removing old code and carrying out well-scoped migrations. The difference is how much of the architecture the team makes visible and enforceable.

If you read nothing else

Keep AI-generated code maintainable by giving each business rule a clear owner, explaining module boundaries to coding agents, and checking those boundaries in CI. Start with a small area of the codebase. Record existing architectural violations, block new violations, and review whether the changes actually reduce rework. Use tests that express business behavior independently of the generated implementation. For long-lived SaaS products, maintainability includes stable API contracts, safe database migrations, controlled feature flags and the ability to reproduce historical transactions. The aim is not fewer lines of code. It is a product that remains safe to change six months after the original feature ships.

When does AI-assisted development create or reduce technical debt?

AI lowers the effort required to propose a change. It does not automatically lower the effort required to understand, integrate and maintain it. If an agent sees only an API route, it may add a correct-looking calculation there without noticing the pricing module that already owns it. If reviewers face more changes than they can assess, those decisions accumulate.

There is a more promising use of the same tools. An agent can add tests around undocumented legacy behavior, migrate callers from a deprecated API, remove dead code or apply a well-established convention across many files. Those are valuable activities when the expected behavior and ownership are defined first.

Our position is straightforward: if the team cannot identify who owns a business rule, settle that decision before asking an agent to change it. Agent instructions cannot compensate for an architecture that nobody agrees on. Our AI-assisted SDLC guide addresses how teams make those decisions earlier in the development process.

Birgitta Böckeler’s guides-and-sensors model distinguishes instructions that steer an agent before a change from checks that detect problems afterward. Her maintainability-sensors experiment illustrates the approach on a small application; it is practitioner evidence, not a production SaaS benchmark.

A pricing change that passes its tests and still breaks consistency

Consider an illustrative SaaS platform with a storefront, merchant administration, and order-processing service. The business rule is explicit: apply 10% off eligible items when the cart subtotal is at least $100. Three developers—or agents—implement it independently. One discounts the whole cart, ignoring eligibility. Another requires a subtotal strictly greater than $100, so the discount is missed at the threshold. The third checks the inclusive threshold and discounts eligible items only.

On a $100 cart with $50 of eligible items, those implementations return $90, $100 and $95. Only the $95 result follows the specified rule. All three implementations may compile, but two encode the wrong business decision. A clone detector may not catch them because the code is structurally different.

The proposed fix is a single pricing-domain contract, with user-facing surfaces consuming the same result. A cart preview can ask the pricing service for a quote. At checkout, the server confirms applicable conditions and creates a versioned price snapshot. Refunds and invoices refer to the accepted snapshot; they should not silently recalculate a historical order using today's promotion rules.

Illustrative TypeScript pricing contract

type PriceRequest = {
  cart: Cart;
  customer: CustomerContext;
  asOf: string; // effective-time input
  rules: PinnedRule[]; // resolved by the caller for asOf
};

type PriceBreakdown = {
  currency: string;
  subtotalMinor: number;
  discountMinor: number;
  totalMinor: number;
  appliedRules: Array<{ id: string; version: string }>;
};

function priceCart(input: PriceRequest): PriceBreakdown {
  // Pure computation: no I/O and no clock reads.
  // Caller supplies effective-dated, pinned rule versions.
  // Apply eligibility and integer-minor-unit rounding consistently.
  throw new Error('implementation omitted');
}

Money is represented in integer minor units with an explicitly documented currency and rounding policy. Effective-dated rules are resolved to pinned versions before calculation. A promotion capped at a fixed number of redemptions requires a separate atomic reservation or database constraint and an idempotency key: a pure pricing function cannot guarantee that two concurrent checkouts do not claim the last redemption.

Before code generation, a product owner or engineer should approve acceptance cases with inputs and expected totals. Do not let the implementation-writing agent define the only test oracle. One high-value test is to submit the same cart fixture through storefront preview, admin order creation and the order API, then compare the price breakdowns and rule versions. Add a two-parallel-checkouts test for a capped promotion. During migration, run the old and new calculators in shadow mode, log differences without changing the charged total, and investigate mismatches before switching traffic. Use contract tests to protect response compatibility. For targeted changes, mutation testing (for example, Stryker for TypeScript) can check whether a deliberate logic fault is detected; run it selectively because it adds CI cost. Böckeler’s experiment described surviving mutants even in code with high statement coverage, showing why coverage alone is insufficient. Our article on AI-generated code verification covers the broader testing and human-accountability questions.

One rule, three results

Illustrative: $100 cart; $50 eligible; 10% off eligible items for carts of $100 or more.

Storefront: $90 (wrong eligibility)  ·  Admin: $100 (wrong threshold)  ·  Order service: $95 (matches rule)

One promotion implemented three ways produces inconsistent totals. A shared, versioned pricing contract should return the same accepted calculation to each surface. Values are illustrative.

Make boundaries visible to people, agents and CI

A good repository guide answers a few questions: which module owns a rule, which API may be called, what an agent must not change, and which tests prove the contract. Keep these decisions in version control rather than in a chat transcript. Support for instruction files differs across coding tools and features, so confirm how the selected agent discovers them. GitHub documents several instruction scopes and feature-specific limitations. For the broader implementation sequence, see Centizen’s reliable AI-assisted development workflow.

Example module-scoped instruction file (illustrative)

# src/pricing/AGENTS.md
Owns: price, discount eligibility and rounding decisions.
Public entry point: src/pricing/index.ts.
Never calculate final discounts in storefront or admin.
Use integer minor units and pinned promotion rule versions.
Every new promotion requires acceptance fixtures.
Before submitting: run pricing tests and architecture checks.

Instructions are guidance, not enforcement. For a Node.js/TypeScript codebase, dependency-cruiser can block forbidden imports; ESLint or Semgrep can detect project-specific prohibited patterns. A rule that bans direct repository imports from storefront code is mechanically enforceable. A rule that says “do not duplicate the meaning of discount eligibility” is harder: supplement import checks with domain ownership, representative cross-surface tests and periodic architectural review.

Example dependency-cruiser rule (adapt paths to your repository)

module.exports = {
  forbidden: [{
    name: 'storefront-no-pricing-repository',
    severity: 'error',
    from: { path: '^src/storefront/' },
    to: { path: '^src/pricing/repositories/' }
  }]
};

That check catches an import violation. It does not detect all architectural problems. A copied pricing formula inside a permitted module may still pass. Mutation testing can help establish whether a test suite would detect a deliberate behavioral defect, but it is not a substitute for business-rule review.

Protect the checks themselves. If an agent can casually modify its instruction files, weaken lint rules or raise complexity thresholds, the guardrail becomes part of the code it is supposed to inspect. In GitLab, repository CODEOWNERS entries and required approvals on protected branches can govern changes to these files, when GitLab Premium or Ultimate, protected-branch rules and required Code Owner approval are configured. Direct pushes by permitted users can bypass merge-request approval, so restrict those permissions on protected branches. GitLab documents these controls.

Illustrative CODEOWNERS entries

/src/pricing/             @your-group/pricing-owners
/.dependency-cruiser.cjs @your-group/architecture
/**/AGENTS.md            @your-group/architecture

Within a CODEOWNERS section, later matching entries take precedence. In this example, the architecture team owns any AGENTS.md file, including one inside the pricing module. Confirm ownership patterns against your GitLab version and repository layout.

Guides before generation; checks before merge

Define ownership → provide module instructions → generate bounded change → run blocking checks and advisory warnings → review protected configuration → release and monitor

Enforce clear module boundaries with executable checks. Start with high-confidence blocking rules and monitor the noise and cost of advisory checks.

Introduce controls in a legacy SaaS codebase without freezing delivery

A mature product may already contain hundreds of dependency violations. Enabling every new rule as a blocking check on day one can stop unrelated work. Baseline existing violations, prevent new ones and reduce the baseline as touched modules are cleaned up. The dependency-cruiser CLI documentation recommends --baseline from version 18.3.0 onward; older releases may use the separate depcruise-baseline utility. Verify which version your CI uses and commit the known-violations file.

Example commands for dependency-cruiser 18.3.0 or newer

npx depcruise src --config .dependency-cruiser.cjs --baseline
# Review and commit .dependency-cruiser-known-violations.json
npx depcruise src --config .dependency-cruiser.cjs --ignore-known .dependency-cruiser-known-violations.json
# Reconcile baselines only through reviewed changes; do not automatically absorb new violations.

Start by blocking a high-confidence boundary such as “storefront cannot import pricing repositories.” SonarQube’s new-code quality model is a related pattern: assess changes without requiring the whole legacy codebase to be fixed immediately. Run noisier duplication and complexity checks as warnings. Require an owner, reason and expiry for exceptions; a production hotfix needs a controlled path, not an undocumented permanent bypass. Keep rule files under code-owner approval.

For a small pilot, assume one senior engineer, one frequently changed module, access to CI and a person who knows the business rules. The work may take several engineering days to define and test the first constraints, plus ongoing review time. That is a planning assumption, not a measured Centizen delivery estimate.

First 30 daysWork and ownerEvidence to retain
Week 1Architect + module owner: select a hotspot using changes, defects and dependency analysis; document rule ownershipModule map, baseline and 3–5 business invariants
Week 2Senior developer: add scoped agent guidance, one dependency rule, and approved exceptionsVersioned guide, known-violations baseline
Week 3QA + developer: add cross-surface fixtures and targeted mutation or fault-injection checksFailing-case demonstration and regression checks
Week 4Engineering lead: compare comparable changes, CI time, new violations and rework; decide what to retainDecision log with keep/change/remove choices

Measure change amplification, then prioritize the debt that matters

Choose measurements that help a team decide what to fix. Track how many files a small feature touches, how many architectural violations are newly introduced, and whether a recently merged change needs corrective work. For a small set of high-value business rules, count how many implementations exist. A simple duplicate-rule census may be more useful than a large text-clone percentage.

  • Change amplification: median number of modules touched per comparable change in the pilot area.
  • New architecture violations: zero should be the target for the first blocking rule; record existing violations separately.
  • Rework: changes reopened or corrected within 14 days, using a defined team convention.
  • Test strength: percentage of deliberately injected faults (mutants) caught by tests on changed code; separately track mutation-test runtime and flaky checks.
  • Constraint cost: CI minutes and engineer time lost to false alarms and legitimate exceptions.

Compare four to six weeks of prior history with similar changes during the pilot. Task mix, team experience and concurrent platform changes can confound the result. Before the pilot starts, agree on review triggers, such as a repeated false-positive pattern, a material increase in CI duration, or excessive exemption requests. Define thresholds from your own baseline rather than publishing invented universal cutoffs. If checks repeatedly block legitimate work, review the rule. If the agent keeps changing configuration to pass checks, tighten ownership. If rework stays high, inspect the actual architectural problem instead of adding more rules.

Rank debt by change frequency, incident history and business consequence. Highly complex code that nobody touches may be less urgent than a modest pricing module changed every sprint. This article focuses on maintainability; our engineering productivity article covers broader delivery metrics.

Long-lived SaaS needs decisions that survive the next change

Architecture drift is only one long-term concern. SaaS teams also inherit versioned APIs, database schema changes, dormant feature flags and tenant-specific behavior. When introducing an agent-driven change, check whether consumers need a deprecation window, whether a schema change requires an expand/contract migration, and whether temporary flags have an owner and removal date. A “clean” code diff can still impose years of compatibility work.

Centralize business knowledge that must produce one answer: pricing, tax, authorization and accounting rules are strong candidates. Do not centralize every duplicated helper. Two simple UI formatters can be cheaper to maintain independently than a shared package that couples unrelated teams. The right boundary is determined by consistency requirements and change ownership, not by a universal ban on duplication.

Maintainability now has another audience: coding agents. Clear ownership, enforced boundaries and one authoritative implementation per business rule help human developers and agents make changes with less guesswork. The codebase itself becomes part of the context that determines whether AI assistance is useful.

Frequently asked questions

How do you find duplicated business logic if clone detectors miss it?

Start with rule ownership. Inspect where the same price, eligibility or permission decision is made. Add cross-surface acceptance tests and domain-specific static checks, then review recurring changes for semantic duplication.

What should be in an agent instruction file?

Keep module ownership, permitted APIs, forbidden dependencies, important invariants and required tests. Put enforceable rules into CI. Confirm which instruction formats each coding tool actually supports.

What are architecture fitness functions?

They are automated checks of architectural characteristics that must stay true as software changes, such as import restrictions, service contracts, data isolation and key performance constraints.

Discuss long-term SaaS maintainability with Centizen

When a SaaS feature becomes expensive to change, start by examining the rule it owns, the components it touches, and the evidence that protects its behavior. Centizen provides custom software and SaaS engineering services. A useful first conversation is a focused review of one high-change module and its release constraints.

Continue the Centizen AI Engineering series

For upstream workflow decisions, read Rethinking the Software Development Lifecycle in the Age of AI, How to Build a Reliable AI-Assisted Development Workflow, and AI-Generated Code: Testing, Security, and Human Accountability. The engineering productivity guide addresses delivery measurement. The companion article on enterprise agent governance should be linked here once its public URL is verified.

Sources and further reading

Illustrative example and proposed pilot: the pricing scenario, code snippets, timelines and measurement design are technical recommendations, not reported Centizen results. Code must be adapted and tested in the actual repository.

Our services:

  • Staffing: Contract, contract-to-hire, direct hire, remote global hiring, SOW projects, and managed services.
  • Remote hiring: Hire full-time IT professionals from our India-based talent network.
  • Custom software development: Web/Mobile Development, UI/UX Design, QA & Automation, API Integration, DevOps, and Product Development.

Our products:

  • ZenBasket: A customizable ecommerce platform.
  • Zenyo payroll: Automated payroll processing for India.
  • Zenyo workforce: Streamlined HR and productivity tools.