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

Capacitor 7 Background Task Execution Watchdog Fence

Enforces deterministic watchdog fencing, cooperative task abortion, and atomic state checkpointing for Capacitor 7 hybrid background operations. Prevents data corruption, dangling database locks, and OS watchdog terminations (iOS 0x8badf00d) caused by abrupt mobile thread freezing.

Prohibited Anti-Pattern: Unbounded Background Workloads Relying on Indefinite Web Runtime Execution Without Proactive Fencing

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Background Task Execution Watchdog Fence - Enforces deterministic watchdog fencing, cooperative task abortion, and atomic state checkpointing for Capacitor 7 hybrid background operations. Prevents data corruption, dangling database locks, and OS watchdog terminations (iOS 0x8badf00d) caused by abrupt mobile thread freezing.
globs: src/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/background/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-background-task-watchdog-fence"
---

# Capacitor 7 Background Task Execution Watchdog Fence

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unbounded Background Workloads Relying on Indefinite Web Runtime Execution Without Proactive Fencing

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 background task execution standards. Hybrid WebViews and background JavaScript threads are abruptly frozen or terminated by iOS (Task Watchdog) and Android (Cached/Doze states) without graceful teardown. You must mandate strict execution budget fences, proactive timeout races via AbortController, transactional write-ahead checkpoints, and deterministic background task release via native bridge plugins.

## Strict Guidelines
- Engineers MUST ALWAYS bound background workloads with an internal watchdog timer configured to fire at least 5000ms BEFORE the mobile operating system ceiling (e.g., maximum 20-25s on iOS).
- Engineers MUST instantiate an AbortController for every background task cycle and propagate its AbortSignal to all downstream network requests, IndexedDB operations, and native plugins.
- Engineers MUST ALWAYS invoke the native task completion callback (e.g., `BackgroundTask.finish({ taskId })` or custom native bridge release) inside an unskippable `finally` block.
- Code MUST flush all dirty memory state, persist sync cursors, and commit or rollback open SQLite/IndexedDB transactions immediately upon receiving the watchdog abort signal.
- Services NEVER execute open-ended polling loops, unbounded recursion, or unresolved Promise chains while running in background runtime contexts.
- Components MUST NOT hold active WebSocket connections, wake locks, or camera/sensor feeds across background lifecycle boundaries without explicit re-acquisition fencing.

## Bad vs Good Implementations
### Watchdog-Fenced Background Sync with Cooperative Cancellation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to register a background task with the native runtime, lacks an execution budget watchdog, passes no AbortController signal, and allows SQLite/network operations to be abruptly frozen in flight by the mobile OS, corrupting persistent storage.
```typescript
import { App } from '@capacitor/app';
import { syncPendingData, flushMetrics } from './syncService';

// ANTI-PATTERN: Indefinite background execution vulnerable to OS freeze
App.addListener('appStateChange', async (state) => {
  if (!state.isActive) {
    // No watchdog, no AbortSignal propagation, no bridge task boundary.
    // iOS will abruptly freeze this thread mid-write when the background budget expires,
    // leaving corrupted SQLite/IndexedDB state and orphan pending locks.
    await syncPendingData();
    await flushMetrics();
  }
});
```

#### Production Standard (Correct)
> **Standard**: Wraps execution in a proactive 22-second watchdog fence, races tasks against an AbortController, guarantees native task release in a `finally` block, and commits checkpoints or rolls back transactions prior to OS thread suspension.
```typescript
import { App } from '@capacitor/app';
import { BackgroundTask } from '@capawesome/capacitor-background-task';
import { syncPendingData, commitCheckpoint, rollbackTransaction } from './syncService';

const BACKGROUND_BUDGET_MS = 22000; // Safe margin well below iOS 30s limit

App.addListener('appStateChange', async (state) => {
  if (state.isActive) return;

  let taskId: string | null = null;
  const abortController = new AbortController();
  const { signal } = abortController;

  try {
    taskId = await BackgroundTask.beforeExit(async () => {
      // Watchdog timeout race
      const watchdog = new Promise<never>((_, reject) => {
        const timer = setTimeout(() => {
          abortController.abort(new Error('WATCHDOG_BUDGET_EXHAUSTED'));
          reject(new Error('WATCHDOG_BUDGET_EXHAUSTED'));
        }, BACKGROUND_BUDGET_MS);
        signal.addEventListener('abort', () => clearTimeout(timer), { once: true });
      });

      const worker = (async () => {
        await syncPendingData(signal);
        await commitCheckpoint();
      })();

      await Promise.race([worker, watchdog]);
    });
  } catch (error) {
    if (signal.aborted) {
      console.warn('[WatchdogFence] Background cycle aborted early, rolling back locks');
      await rollbackTransaction().catch(console.error);
    } else {
      console.error('[WatchdogFence] Background task failed:', error);
    }
  } finally {
    if (taskId) {
      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 Task Execution Watchdog Fence

Capacitor 7 Background Task Execution Watchdog Fence defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic watchdog fencing, cooperative task abortion, and atomic state checkpointing for Capacitor 7 hybrid background operations. Prevents data corruption, dangling database locks, and OS watchdog terminations (iOS 0x8badf00d) caused by abrupt mobile thread freezing. 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 Background Workloads Relying on Indefinite Web Runtime Execution Without Proactive Fencing 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 Background Workloads Relying on Indefinite Web Runtime Execution Without Proactive FencingCritical
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 bound background workloads with an internal watchdog timer configured to fire at least 5000ms BEFORE the mobile operating system ceiling (e.g., maximum 20-25s on iOS).

Engineers MUST ALWAYS bound background workloads with an internal watchdog timer configured to fire at least 5000ms BEFORE the mobile operating system ceiling (e.g., maximum 20-25s on iOS).

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 instantiate an AbortController for every background task cycle and propagate its AbortSignal to all downstream network requests, IndexedDB operations, and native plugins.

Engineers MUST instantiate an AbortController for every background task cycle and propagate its AbortSignal to all downstream network requests, IndexedDB operations, and native plugins.

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

Engineers MUST ALWAYS invoke the native task completion callback (e.g., `BackgroundTask.finish({ taskId })` or custom native bridge release) inside an unskippable `finally` block.

Engineers MUST ALWAYS invoke the native task completion callback (e.g., `BackgroundTask.finish({ taskId })` or custom native bridge release) inside an unskippable `finally` block.

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 MUST flush all dirty memory state, persist sync cursors, and commit or rollback open SQLite/IndexedDB transactions immediately upon receiving the watchdog abort signal.

Code MUST flush all dirty memory state, persist sync cursors, and commit or rollback open SQLite/IndexedDB transactions immediately upon receiving the watchdog abort signal.

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

Services NEVER execute open-ended polling loops, unbounded recursion, or unresolved Promise chains while running in background runtime contexts.

Services NEVER execute open-ended polling loops, unbounded recursion, or unresolved Promise chains while running in background runtime contexts.

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.
6

Components MUST NOT hold active WebSocket connections, wake locks, or camera/sensor feeds across background lifecycle boundaries without explicit re-acquisition fencing.

Components MUST NOT hold active WebSocket connections, wake locks, or camera/sensor feeds across background lifecycle boundaries without explicit re-acquisition fencing.

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 Task Execution Watchdog Fence critical for AI coding assistants?

Enforces deterministic watchdog fencing, cooperative task abortion, and atomic state checkpointing for Capacitor 7 hybrid background operations. Prevents data corruption, dangling database locks, and OS watchdog terminations (iOS 0x8badf00d) caused by abrupt mobile thread freezing. 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 Background Workloads Relying on Indefinite Web Runtime Execution Without Proactive Fencing) 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