This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-background-workmanager-budgeting-guardrail

Capacitor 7 Background Fetch and WorkManager Adaptive Budgeting Guardrail

Enforces strict synchronization between Capacitor 7 JavaScript runtime tasks and native mobile background executors (Android WorkManager and iOS BackgroundTasks). Prevents OS watchdog terminations (such as iOS 0x8badf00d) and Android App Standby Bucket demotions by enforcing explicit task completion signals, cancellation propagation via AbortController, and battery-aware chunked execution budgets.

Prohibited Anti-Pattern: Unbounded Webview Execution and Orphaned Background Tasks Leading to OS SIGKILL

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Fetch and WorkManager Adaptive Budgeting Guardrail - Enforces strict synchronization between Capacitor 7 JavaScript runtime tasks and native mobile background executors (Android WorkManager and iOS BackgroundTasks). Prevents OS watchdog terminations (such as iOS 0x8badf00d) and Android App Standby Bucket demotions by enforcing explicit task completion signals, cancellation propagation via AbortController, and battery-aware chunked execution budgets.
globs: src/**/*.{ts,tsx}, android/app/src/main/java/**/*.kt, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-workmanager-budgeting-guardrail"
---

# Capacitor 7 Background Fetch and WorkManager Adaptive Budgeting Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Webview Execution and Orphaned Background Tasks Leading to OS SIGKILL

## System Constraints
You are a Principal Mobile Architect enforcing strict background execution constraints for Capacitor 7 hybrid applications. You must ensure that any JavaScript work initiated by native Android WorkManager or iOS BGTaskScheduler executes within a strictly bounded window, respects OS-level cancellation events (iOS expirationHandler and Android isStopped), and always calls the native bridge completion handler. Failure to observe watchdog deadlines leads to process death (0x8badf00d on iOS) and severe battery-budget deprioritization by Android JobScheduler.

## Strict Guidelines
- Engineers MUST ALWAYS link Capacitor background tasks to a cooperative AbortController that listens to native timeout/expiration events.
- Engineers MUST NEVER run unbounded loops or indefinite async/await chains inside background sync handlers; operations must be chunked with atomic checkpoint persistence.
- Services MUST ALWAYS resolve or reject the native task promise before the OS deadline expires (typically within 25 seconds for iOS BGAppRefreshTask and before WorkManager worker timeout).
- Code SHOULD inspect device battery status and network metering prior to initiating heavyweight sync operations, deferring processing if constraints are violated.
- Components NEVER execute UI mutations or assume the Webview DOM rendering tree is active during background fetch cycles.

## Bad vs Good Implementations
### Background Sync Execution: Unbounded Loop vs. Budgeted Abortable Worker

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The loop does not respect execution time budgets or OS task cancellation events. On iOS, once the ~30s watchdog expires, the operating system kills the app with exception 0x8badf00d and marks the app as battery-inefficient, drastically reducing future background task opportunities.
```typescript
import { BackgroundTask } from '@capacitor/background-task';
import { syncPendingRecords, getUnsyncedItems } from './syncService';

// ANTI-PATTERN: Indefinite execution, no expiration handling, no timeout bounds.
BackgroundTask.beforeExit(async () => {
  const items = await getUnsyncedItems();
  // If items contains 1000 items, the OS watchdog terminates the app (SIGKILL) 
  // after ~30s on iOS or WorkManager marks Worker as failed and kills the process.
  for (const item of items) {
    await syncPendingRecords(item);
  }
  BackgroundTask.finish({ taskId: 'sync-all' });
});
```

#### Production Standard (Correct)
> **Standard**: Implements an explicit 20-second watchdog timeout via AbortController, checks battery health before dispatching work, runs bounded batches with atomic checkpoint persistence, and guarantees that BackgroundTask.finish is called inside a finally block to prevent OS-level process termination.
```typescript
import { BackgroundTask } from '@capacitor/background-task';
import { Device } from '@capacitor/device';
import { syncBatch, getUnsyncedItems, saveSyncCheckpoint } from './syncService';

const BACKGROUND_TIME_BUDGET_MS = 20_000; // Safe threshold below iOS 30s limit

BackgroundTask.beforeExit(async () => {
  const taskId = BackgroundTask.beginTask({ name: 'adaptive-sync' });
  const abortController = new AbortController();
  
  // Enforce rigid deadline before native OS termination
  const budgetTimeout = setTimeout(() => {
    abortController.abort(new Error('Background budget exhausted'));
  }, BACKGROUND_TIME_BUDGET_MS);

  try {
    const batteryInfo = await Device.getBatteryInfo();
    if (batteryInfo.batteryLevel !== undefined && batteryInfo.batteryLevel < 0.15 && !batteryInfo.isCharging) {
      console.warn('[Sync] Battery too low, deferring work');
      return;
    }

    let cursor: string | undefined = undefined;
    while (!abortController.signal.aborted) {
      const batch = await getUnsyncedItems({ limit: 20, cursor });
      if (!batch.items.length) break;

      await syncBatch(batch.items, { signal: abortController.signal });
      await saveSyncCheckpoint(batch.nextCursor);
      cursor = batch.nextCursor;
    }
  } catch (error) {
    if (abortController.signal.aborted) {
      console.warn('[Sync] Worker halted cooperatively via budget watchdog');
    } else {
      console.error('[Sync] Background sync encountered unhandled error', error);
    }
  } finally {
    clearTimeout(budgetTimeout);
    // CRITICAL: Must notify native layer immediately to release wake locks
    BackgroundTask.finish({ taskId });
  }
});
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Capacitor 7 Background Fetch and WorkManager Adaptive Budgeting Guardrail

Capacitor 7 Background Fetch and WorkManager Adaptive Budgeting Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict synchronization between Capacitor 7 JavaScript runtime tasks and native mobile background executors (Android WorkManager and iOS BackgroundTasks). Prevents OS watchdog terminations (such as iOS 0x8badf00d) and Android App Standby Bucket demotions by enforcing explicit task completion signals, cancellation propagation via AbortController, and battery-aware chunked execution budgets. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unbounded Webview Execution and Orphaned Background Tasks Leading to OS SIGKILL Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnbounded Webview Execution and Orphaned Background Tasks Leading to OS SIGKILLCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS link Capacitor background tasks to a cooperative AbortController that listens to native timeout/expiration events.

Engineers MUST ALWAYS link Capacitor background tasks to a cooperative AbortController that listens to native timeout/expiration events.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NEVER run unbounded loops or indefinite async/await chains inside background sync handlers

Engineers MUST NEVER run unbounded loops or indefinite async/await chains inside background sync handlers; operations must be chunked with atomic checkpoint persistence.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Services MUST ALWAYS resolve or reject the native task promise before the OS deadline expires (typically within 25 seconds for iOS BGAppRefreshTask and before WorkManager worker timeout).

Services MUST ALWAYS resolve or reject the native task promise before the OS deadline expires (typically within 25 seconds for iOS BGAppRefreshTask and before WorkManager worker timeout).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code SHOULD inspect device battery status and network metering prior to initiating heavyweight sync operations, deferring processing if constraints are violated.

Code SHOULD inspect device battery status and network metering prior to initiating heavyweight sync operations, deferring processing if constraints are violated.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER execute UI mutations or assume the Webview DOM rendering tree is active during background fetch cycles.

Components NEVER execute UI mutations or assume the Webview DOM rendering tree is active during background fetch cycles.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Capacitor 7 Background Fetch and WorkManager Adaptive Budgeting Guardrail critical for AI coding assistants?

Enforces strict synchronization between Capacitor 7 JavaScript runtime tasks and native mobile background executors (Android WorkManager and iOS BackgroundTasks). Prevents OS watchdog terminations (such as iOS 0x8badf00d) and Android App Standby Bucket demotions by enforcing explicit task completion signals, cancellation propagation via AbortController, and battery-aware chunked execution budgets. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unbounded Webview Execution and Orphaned Background Tasks Leading to OS SIGKILL) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Capacitor