Skip to content

CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息

docs: 增加英文文档

Bob124681dea7c5
diff --git a/Docs/DeveloperGuide/README.md b/Docs/DeveloperGuide/README.md
index 91ae64e..e62a9e0 100644
--- a/Docs/DeveloperGuide/README.md
+++ b/Docs/DeveloperGuide/README.md
@@ -1,5 +1,7 @@
# CodexBar 开发者指南
+简体中文 | [English](../en/DeveloperGuide/README.md)
+
本指南面向希望理解 CodexBar 架构、调试数据链路或参与开发的开发者。
内容不仅描述模块做什么,还解释为什么这样划分职责,哪些失败路径是刻意保守处理,以及修改实现时必须继续维持哪些不变量。
diff --git a/Docs/DeveloperGuide/activity-monitor.md b/Docs/DeveloperGuide/activity-monitor.md
index 1c437ff..9d6dabb 100644
--- a/Docs/DeveloperGuide/activity-monitor.md
+++ b/Docs/DeveloperGuide/activity-monitor.md
@@ -1,5 +1,7 @@
# 实时任务监控
+简体中文 | [English](../en/DeveloperGuide/activity-monitor.md)
+
## 设计出发点
实时任务不是 Hook 事件的直接映射。
diff --git a/Docs/DeveloperGuide/app-server.md b/Docs/DeveloperGuide/app-server.md
index 827e49a..8c28e73 100644
--- a/Docs/DeveloperGuide/app-server.md
+++ b/Docs/DeveloperGuide/app-server.md
@@ -1,5 +1,7 @@
# app-server 数据链路
+简体中文 | [English](../en/DeveloperGuide/app-server.md)
+
## 设计出发点
CodexBar 不重新实现 Codex 登录、token 刷新和账户协议,而是把本机 `codex app-server` 作为账户能力边界。
diff --git a/Docs/DeveloperGuide/architecture.md b/Docs/DeveloperGuide/architecture.md
index d67aa3b..b20a417 100644
--- a/Docs/DeveloperGuide/architecture.md
+++ b/Docs/DeveloperGuide/architecture.md
@@ -1,5 +1,7 @@
# 整体架构
+简体中文 | [English](../en/DeveloperGuide/architecture.md)
+
## 这套架构要解决什么
CodexBar 的核心挑战不是绘制菜单栏界面,而是在一个长期运行的 `LSUIElement` App 中同时协调短命 Hook 子进程、本机 app-server、持续追加的文件、CloudKit、系统通知和 root helper。
diff --git a/Docs/DeveloperGuide/data-and-privacy.md b/Docs/DeveloperGuide/data-and-privacy.md
index d70b091..519ed2a 100644
--- a/Docs/DeveloperGuide/data-and-privacy.md
+++ b/Docs/DeveloperGuide/data-and-privacy.md
@@ -1,5 +1,7 @@
# 数据与隐私边界
+简体中文 | [English](../en/DeveloperGuide/data-and-privacy.md)
+
## 原则
CodexBar 只读取实现账户展示、自动重置、Hook 统计、实时任务和防睡眠所需的数据:
diff --git a/Docs/DeveloperGuide/design-decisions.md b/Docs/DeveloperGuide/design-decisions.md
index 2432760..e9fcc0e 100644
--- a/Docs/DeveloperGuide/design-decisions.md
+++ b/Docs/DeveloperGuide/design-decisions.md
@@ -1,5 +1,7 @@
# 设计原则与关键决策
+简体中文 | [English](../en/DeveloperGuide/design-decisions.md)
+
这篇文档解释 CodexBar 为什么采用现在的结构,以及这些结构在解决什么问题。
它不是源码目录索引,也不是功能列表。阅读目标是建立一套判断标准:当实现需要变化时,哪些只是可以替换的手段,哪些是必须继续成立的系统不变量。
diff --git a/Docs/DeveloperGuide/development.md b/Docs/DeveloperGuide/development.md
index af5d052..713e854 100644
--- a/Docs/DeveloperGuide/development.md
+++ b/Docs/DeveloperGuide/development.md
@@ -1,5 +1,7 @@
# 开发与验证
+简体中文 | [English](../en/DeveloperGuide/development.md)
+
## 环境要求
- macOS 15 或更高版本
diff --git a/Docs/DeveloperGuide/hook-and-aggregation.md b/Docs/DeveloperGuide/hook-and-aggregation.md
index af871c2..d0317fa 100644
--- a/Docs/DeveloperGuide/hook-and-aggregation.md
+++ b/Docs/DeveloperGuide/hook-and-aggregation.md
@@ -1,5 +1,7 @@
# Hook 采集与历史聚合
+简体中文 | [English](../en/DeveloperGuide/hook-and-aggregation.md)
+
## 设计出发点
Hook 链路同时服务两个看似接近但要求相反的目标:
diff --git a/Docs/DeveloperGuide/notifications.md b/Docs/DeveloperGuide/notifications.md
index 38f2f65..20d4e07 100644
--- a/Docs/DeveloperGuide/notifications.md
+++ b/Docs/DeveloperGuide/notifications.md
@@ -1,5 +1,7 @@
# 通知系统
+简体中文 | [English](../en/DeveloperGuide/notifications.md)
+
## 职责
[`CodexNotificationService.swift`](../../CodexBar/Services/Notifications/CodexNotificationService.swift) 是通知副作用的统一入口。
diff --git a/Docs/DeveloperGuide/sleep-prevention.md b/Docs/DeveloperGuide/sleep-prevention.md
index c37f46f..73f4a2d 100644
--- a/Docs/DeveloperGuide/sleep-prevention.md
+++ b/Docs/DeveloperGuide/sleep-prevention.md
@@ -1,5 +1,7 @@
# 防睡眠系统
+简体中文 | [English](../en/DeveloperGuide/sleep-prevention.md)
+
## 设计目标
防睡眠功能需要同时满足 3 个目标:
diff --git a/Docs/DeveloperGuide/sync.md b/Docs/DeveloperGuide/sync.md
index 9abe985..fbbec6f 100644
--- a/Docs/DeveloperGuide/sync.md
+++ b/Docs/DeveloperGuide/sync.md
@@ -1,5 +1,7 @@
# CloudKit 同步
+简体中文 | [English](../en/DeveloperGuide/sync.md)
+
## 同步范围
CloudKit 同步用于在同一 iCloud 账户的 Mac 之间合并 Hook 日级统计。
diff --git a/Docs/DeveloperGuide/ui-and-lifecycle.md b/Docs/DeveloperGuide/ui-and-lifecycle.md
index cade667..2f07b8b 100644
--- a/Docs/DeveloperGuide/ui-and-lifecycle.md
+++ b/Docs/DeveloperGuide/ui-and-lifecycle.md
@@ -1,5 +1,7 @@
# UI 与应用生命周期
+简体中文 | [English](../en/DeveloperGuide/ui-and-lifecycle.md)
+
## LSUIElement 约束
CodexBar 在 [`Info.plist`](../../CodexBar/Resources/Info.plist) 中配置为 `LSUIElement`
diff --git a/Docs/README.md b/Docs/README.md
index 446d6f0..acd04eb 100644
--- a/Docs/README.md
+++ b/Docs/README.md
@@ -1,5 +1,7 @@
# CodexBar 文档
+简体中文 | [English](en/README.md)
+
CodexBar 文档按读者和职责分成两套,使用说明与实现细节保持独立:
| 文档 | 目标读者 | 解决的问题 |
diff --git a/Docs/UserGuide/README.md b/Docs/UserGuide/README.md
index a9adcf5..38edc0a 100644
--- a/Docs/UserGuide/README.md
+++ b/Docs/UserGuide/README.md
@@ -1,5 +1,7 @@
# CodexBar 用户手册
+简体中文 | [English](../en/UserGuide/README.md)
+
## 文档目录
| 文档 | 内容 |
diff --git a/Docs/UserGuide/activity-and-hook.md b/Docs/UserGuide/activity-and-hook.md
index db2ae9b..e226c4f 100644
--- a/Docs/UserGuide/activity-and-hook.md
+++ b/Docs/UserGuide/activity-and-hook.md
@@ -1,5 +1,7 @@
# 实时任务与 CodexBar Hook
+简体中文 | [English](../en/UserGuide/activity-and-hook.md)
+
## Hook 解决什么问题
账户、额度和 Token 用量是周期性快照,无法说明一轮 Codex 任务正在运行、等待批准还是已经结束。
diff --git a/Docs/UserGuide/getting-started.md b/Docs/UserGuide/getting-started.md
index f97be7c..1b8453b 100644
--- a/Docs/UserGuide/getting-started.md
+++ b/Docs/UserGuide/getting-started.md
@@ -1,5 +1,7 @@
# 安装与快速开始
+简体中文 | [English](../en/UserGuide/getting-started.md)
+
## 运行要求
- macOS 15.0 或更高版本
diff --git a/Docs/UserGuide/main-panel.md b/Docs/UserGuide/main-panel.md
index 9269a89..d0aac68 100644
--- a/Docs/UserGuide/main-panel.md
+++ b/Docs/UserGuide/main-panel.md
@@ -1,5 +1,7 @@
# 主面板与菜单栏
+简体中文 | [English](../en/UserGuide/main-panel.md)
+
## 菜单栏图标
CodexBar 用图标、状态点和可选额度条同时表达账户、任务和额度状态:
diff --git a/Docs/UserGuide/notifications.md b/Docs/UserGuide/notifications.md
index 88faa93..a5752f0 100644
--- a/Docs/UserGuide/notifications.md
+++ b/Docs/UserGuide/notifications.md
@@ -1,5 +1,7 @@
# 通知与提醒
+简体中文 | [English](../en/UserGuide/notifications.md)
+
## 开启通知
1. 打开 `设置 > 高级`
diff --git a/Docs/UserGuide/settings.md b/Docs/UserGuide/settings.md
index 102638d..1247515 100644
--- a/Docs/UserGuide/settings.md
+++ b/Docs/UserGuide/settings.md
@@ -1,5 +1,7 @@
# 设置参考
+简体中文 | [English](../en/UserGuide/settings.md)
+
右键或 Control 点击菜单栏图标并选择 `设置`,或按 `⌘,` 打开设置窗口。
设置窗口包含 `通用`、`高级` 和 `关于` 三个页面。
diff --git a/Docs/UserGuide/sleep-prevention.md b/Docs/UserGuide/sleep-prevention.md
index 9c6c88f..aa8a7dc 100644
--- a/Docs/UserGuide/sleep-prevention.md
+++ b/Docs/UserGuide/sleep-prevention.md
@@ -1,5 +1,7 @@
# 防止系统睡眠
+简体中文 | [English](../en/UserGuide/sleep-prevention.md)
+
## 功能目标
macOS 进入系统睡眠后,正在本机运行的 Codex 任务可能被挂起。
diff --git a/Docs/UserGuide/sync-data-privacy.md b/Docs/UserGuide/sync-data-privacy.md
index 458f201..f14b313 100644
--- a/Docs/UserGuide/sync-data-privacy.md
+++ b/Docs/UserGuide/sync-data-privacy.md
@@ -1,5 +1,7 @@
# 数据、同步与隐私
+简体中文 | [English](../en/UserGuide/sync-data-privacy.md)
+
## 跨设备同步的内容
跨设备同步用于合并多台 Mac 的每日 Hook 聚合,不同步账户、额度、Token 用量、重置次数或自动重置设置。
diff --git a/Docs/UserGuide/troubleshooting.md b/Docs/UserGuide/troubleshooting.md
index 4c500e1..b8e0121 100644
--- a/Docs/UserGuide/troubleshooting.md
+++ b/Docs/UserGuide/troubleshooting.md
@@ -1,5 +1,7 @@
# 常见问题与排查
+简体中文 | [English](../en/UserGuide/troubleshooting.md)
+
## 菜单栏找不到 CodexBar
- CodexBar 是菜单栏 App,不显示 Dock 图标
diff --git a/Docs/en/DeveloperGuide/README.md b/Docs/en/DeveloperGuide/README.md
new file mode 100644
index 0000000..de95a17
--- /dev/null
+++ b/Docs/en/DeveloperGuide/README.md
@@ -0,0 +1,131 @@
+# CodexBar Developer Guide
+
+[简体中文](../../DeveloperGuide/README.md) | English
+
+This guide is for developers who want to understand CodexBar's architecture, debug its data flows, or contribute to the project.
+
+It describes not only what each module does, but also why responsibilities are divided this way, which failure paths are intentionally conservative, and which invariants must survive implementation changes.
+
+For product features and instructions, see the [User Guide](../UserGuide/README.md).
+
+## Goals
+
+The Developer Guide should help readers with four kinds of work:
+
+- Build a system model: understand where data originates, where it becomes state, and which component ultimately consumes it
+- Find the right place to make a change: identify the sole owner of a behavior and the boundary of its side effects
+- Understand design tradeoffs: avoid simplifying away seemingly redundant generations, stale markers, or recovery steps
+- Validate changes: derive acceptance coverage from invariants and failure scenarios
+
+Each topic follows roughly the same structure:
+
+```text
+Goals and constraints
+ -> Data or control flow
+ -> State ownership
+ -> Key design rationale
+ -> Failure and recovery
+ -> Change guide
+ -> Validation scenarios
+```
+
+## Reading Order
+
+If you are new to the project, read these topics in order:
+
+1. [Architecture](architecture.md)
+2. [Design Principles and Key Decisions](design-decisions.md)
+3. [app-server Data Flow](app-server.md)
+4. [Hook Capture and Historical Aggregation](hook-and-aggregation.md)
+5. [Live Task Monitoring](activity-monitor.md)
+6. [Sleep Prevention System](sleep-prevention.md)
+7. [CloudKit Sync](sync.md)
+8. [Notification System](notifications.md)
+9. [UI and App Lifecycle](ui-and-lifecycle.md)
+10. [Data and Privacy Boundaries](data-and-privacy.md)
+11. [Development and Validation](development.md)
+
+## Find by Responsibility
+
+| Document | Contents |
+| --- | --- |
+| [Architecture](architecture.md) | Processes, modules, lifecycle, actor boundaries, and the three data flows |
+| [Design Principles and Key Decisions](design-decisions.md) | Cross-module rationale, system invariants, failure priorities, and subtle implementation details |
+| [app-server Data Flow](app-server.md) | CLI discovery, JSON-RPC sessions, account data, rate limits, usage refresh, and the Automatic Reset state machine |
+| [Hook Capture and Historical Aggregation](hook-and-aggregation.md) | Hook installation, event persistence, aggregation, retention, and schema evolution |
+| [Live Task Monitoring](activity-monitor.md) | Incremental reading, rollout reconciliation, task state machine, and Stalled Task Protection |
+| [Sleep Prevention System](sleep-prevention.md) | IOKit assertions, CodexBarHelper, XPC leases, Automatic Reset wake schedules, and recovery |
+| [CloudKit Sync](sync.md) | Private database, device pseudonymization, upload, merge, and rebuild |
+| [Notification System](notifications.md) | Notification triggers, deduplication, sounds, haptics, and click behavior |
+| [UI and App Lifecycle](ui-and-lifecycle.md) | Menu bar, panels, focus, global shortcuts, and service assembly |
+| [Data and Privacy Boundaries](data-and-privacy.md) | Local files, network access, cloud fields, and logging boundaries |
+| [Development and Validation](development.md) | Project structure, build checks, debugging, and change acceptance |
+
+## Find by Change
+
+| Change | Read first | Also review |
+| --- | --- | --- |
+| Add an account or usage field | [app-server Data Flow](app-server.md) | [Data and Privacy Boundaries](data-and-privacy.md) |
+| Add a Hook event or historical metric | [Hook Capture and Historical Aggregation](hook-and-aggregation.md) | [CloudKit Sync](sync.md) |
+| Change task states or terminal-state detection | [Live Task Monitoring](activity-monitor.md) | [Notification System](notifications.md), [Sleep Prevention System](sleep-prevention.md) |
+| Change a menu, window, or shortcut | [UI and App Lifecycle](ui-and-lifecycle.md) | [Development and Validation](development.md) |
+| Change notification triggers or deduplication | [Notification System](notifications.md) | The guide for the corresponding data source |
+| Change sleep-prevention policy or the helper | [Sleep Prevention System](sleep-prevention.md) | [Data and Privacy Boundaries](data-and-privacy.md) |
+| Change Automatic Reset scheduling or wake plans | [app-server Data Flow](app-server.md) | [Sleep Prevention System](sleep-prevention.md), [Data and Privacy Boundaries](data-and-privacy.md) |
+| Change sync fields or merge rules | [CloudKit Sync](sync.md) | [Hook Capture and Historical Aggregation](hook-and-aggregation.md) |
+| Change persistence formats or defaults | [Development and Validation](development.md) | [Design Principles and Key Decisions](design-decisions.md) |
+
+## Core Design Constraints
+
+- Startup must handle `--hook-event` mode first; that mode must not initialize the UI
+- app-server rate limits and usage, historical Hook aggregation, and live task monitoring are three independent data flows
+- `CodexActivityMonitor` is the sole source of task state
+- UI, controllers, view models, and settings run on `MainActor` by default
+- Blocking I/O and shared mutable state must stay off the main actor
+- CodexBarHelper is limited to fixed sleep controls and Automatic Reset wake schedules; it must not gain network access, arbitrary command execution, or additional file access
+- Hook configuration changes must preserve handlers installed by the user and other applications
+- Changes to aggregation semantics must increment the aggregation schema and fully rebuild from raw events
+- A missing Hook count means the historical source is unavailable; it must not be interpreted as an explicit `0`
+
+## Core Terminology
+
+| Term | Precise meaning in this project |
+| --- | --- |
+| snapshot | Repeatable current state; it does not imply that an event just occurred |
+| transition | A one-time state change from trusted live input that may drive side effects such as notifications |
+| bootstrap | Restoring an in-memory baseline from existing local data without replaying historical side effects |
+| stale | An old value is available for display, but the source could not confirm it in the current cycle |
+| unavailable | No trusted source is currently available; this is not equivalent to empty or `0` |
+| generation | The generation of a data source or asynchronous operation, used to reject late results |
+| source generation | The source identity of a day's raw Hook file; distinct from a code schema |
+| owned | CodexBar changed the system state and is entitled to restore it |
+| external | A source outside CodexBar had already set the system state |
+
+## How to Read the Source
+
+Identify the state owner first, then read backward from its consumers.
+
+For example, when changing approval-waiting behavior, use this order:
+
+```text
+CodexActivityTask
+ -> CodexActivityMonitor
+ -> CodexActivitySnapshot / transition
+ -> CodexNotificationService
+ -> KeepAliveController
+ -> SwiftUI View
+```
+
+Starting from a view usually reveals only the final display condition and makes it easy to miss bootstrap, deduplication, and recovery semantics.
+
+## Main Entry Points
+
+- App startup: [`CodexBarApp.swift`](../../../CodexBar/App/CodexBarApp.swift)
+- Service assembly: [`CodexBarAppDelegate.swift`](../../../CodexBar/Controllers/CodexBarAppDelegate.swift)
+- app-server service: [`CodexStatusService.swift`](../../../CodexBar/Services/CodexStatus/CodexStatusService.swift)
+- Hook subprocess entry: [`WorkflowHookEventRecorder.swift`](../../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift)
+- Live task state machine: [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)
+- Automatic Reset state machine: [`AutoResetController.swift`](../../../CodexBar/Services/CodexStatus/AutoResetController.swift)
+- Automatic Reset wake synchronization: [`AutoResetWakeScheduler.swift`](../../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)
+- Sleep-prevention orchestration: [`KeepAliveController.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveController.swift)
+- CodexBarHelper: [`main.swift`](../../../CodexBarHelper/main.swift)
diff --git a/Docs/en/DeveloperGuide/activity-monitor.md b/Docs/en/DeveloperGuide/activity-monitor.md
new file mode 100644
index 0000000..9f5bff0
--- /dev/null
+++ b/Docs/en/DeveloperGuide/activity-monitor.md
@@ -0,0 +1,538 @@
+# Live Task Monitoring
+
+[简体中文](../../DeveloperGuide/activity-monitor.md) | English
+
+## Design Motivation
+
+A live task is not a direct mapping of Hook events.
+
+One turn may have missing, late, or duplicate events; only a session ID; a new prompt replacing an old turn; `Stop` and rollout terminal arriving in either order; or an app launch after the task has already run for some time.
+
+`CodexActivityMonitor` combines these incomplete observations into a conservative task state machine and produces two different outputs:
+
+- A snapshot describes what can be displayed now
+- A transition describes what just happened and may drive a one-time side effect
+
+If every consumer inferred tasks from Hook lists independently, the menu bar, notifications, and sleep prevention would disagree at edge cases.
+
+## Goals
+
+The live-task flow answers four questions:
+
+- Is a task currently running?
+- Is a task waiting for user approval?
+- Did a recent task complete or terminate?
+- Which running tasks have made no progress for too long?
+
+Hook events provide low-latency signals, and rollout files provide authoritative lifecycle context. [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) merges both into the sole task snapshot:
+
+```text
+Hook JSONL -> HookEventTailReader -----+
+ +-> CodexActivityMonitor -> ActivitySnapshot
+rollout JSONL -> SessionLifecycleReader+
+```
+
+### Division Between Sources
+
+| Information | Primary source | Supplemental source |
+| --- | --- | --- |
+| Live prompt, tool, compact, and subagent progress | Hook | Rollout progress |
+| User-approval candidate | `PermissionRequest` | Rollout reviewer confirmation |
+| Turn start | `UserPromptSubmit` | Rollout `startedAt` or historical lookup |
+| Completion candidate | `Stop` | Rollout terminal |
+| Completion versus termination | Rollout terminal | Grace-expiration fallback |
+| Effort | Hook-recorder lookup | Rollout lifecycle backfill |
+
+Hook prioritizes low latency; rollout prioritizes semantic accuracy. They do not simply overwrite by timestamp. Every field has its own trusted source.
+
+### Why Snapshot and Transition Are Separate
+
+A snapshot may be read repeatedly after view reconstruction, a new subscription, or a settings change. A transition may be emitted once from live data only.
+
+For example, bootstrap may recover a task already waiting for approval when the app starts:
+
+- The snapshot should show it waiting
+- No waiting transition should be emitted
+- The notification service therefore does not replay a historical alert
+
+Completion works the same way. Notifications consume `.completed` transitions rather than scanning `recentCompletions`, preventing reminders on app restart or UI refresh.
+
+## HookEventTailReader
+
+[`HookEventTailReader.swift`](../../../CodexBar/Services/Workflow/HookEventTailReader.swift) is an actor that checks Hook event files every 2 seconds by default.
+
+### Bootstrap
+
+Initial startup reads the latest 24 hours to establish a task baseline:
+
+- Read chunks of at most 512 KB
+- Try at most 3 times to obtain stable file boundaries
+- Use inode and size to detect replacement or append during reading
+- Never trigger historical completion or waiting notifications from bootstrap results
+
+If it cannot obtain a stable boundary, the reader moves to the current file tail and publishes explicit unhealthy state. Incomplete history is not misrepresented as a real task change.
+
+### Bootstrap Is One Logical Transaction
+
+The 24-hour window may span two calendar-day files, and one file may arrive in several 512 KB batches.
+
+At `.bootstrapStart`, the monitor clears previous recovered state and pauses side effects. It consumes every `.bootstrapEvents` batch, then waits until `.bootstrapEnd` to:
+
+- Fill in lifecycle from rollout
+- Apply persisted Activity Protection records
+- Reconcile silence under the current threshold
+- Look up missing prompt starts selectively
+- Publish one complete snapshot
+
+Neither UI nor notifications should observe a partially recovered intermediate batch.
+
+### Why Stable Boundaries Retry Three Times
+
+At the start of an attempt, the reader fixes inode and size for all relevant date files and validates them again after reading to those bounds:
+
+- A historical date must retain both inode and size
+- The current date may append only beyond the fixed upper bound
+- The calendar day must not cross midnight during the read
+
+If any condition fails, the reader retries from a new baseline. After three consecutive failures it moves to the current tail so bootstrap cannot block forever. Degraded health communicates the cost to Activity Protection instead of pretending success.
+
+### Why Offset Advances Only Across Complete Lines
+
+The Hook recorder may be writing the final line. The reader includes only bytes before the last newline in `completeOffset`.
+
+A partial line is neither discarded nor classified as corrupt. The next cycle rereads from the old offset and commits after the line is complete.
+
+### Date Rollover and File Replacement
+
+Normal rollover drains the old date file before switching to the new date. An inode change or file shrink restarts bootstrap instead of reusing the old cursor.
+
+When `UserPromptSubmit` predates the current incremental window, the reader can look backward up to 8 MB to recover the prompt start of an existing task.
+
+### `drainNow()` Read Barrier
+
+`drainNow()` is not an ordinary immediate-refresh hint. Every caller must wait for a read that begins after its request:
+
+```text
+Call drainNow
+ -> Record request generation
+ -> Wait for the next new read to begin
+ -> Wait for that read to finish
+ -> Return that read's result
+```
+
+A read already in progress before the call cannot satisfy the barrier. If the reader is replaced, the data source is unavailable, or the task is canceled, the caller must not continue evaluating from an old snapshot.
+
+### Exact Generational Semantics of the Barrier
+
+Each `drainNow()` increments `requestedDrainGeneration` and registers its own waiter.
+
+If a read is in flight, the request sets only `hasPendingDrain`. After the current cycle completes, the reader must begin another cycle that captures this request generation.
+
+One read can satisfy several waiters queued before it begins, but not a waiter added afterward. This is the happens-after guarantee required for wake recovery.
+
+Actors can reenter during `await`; `isProcessingReads` and `hasPendingDrain` converge all external requests into one serial drain loop so two reads never advance offset concurrently.
+
+## Rollout Lifecycle Reading
+
+[`CodexSessionLifecycleReader.swift`](../../../CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift) reads `$CODEX_HOME/sessions` and `$CODEX_HOME/archived_sessions`.
+
+Rules are:
+
+- Poll every 1 second by default
+- Begin with a 512 KB tail window
+- Look back at most 8 MB for turn-context fields such as effort
+- Parse only lifecycle, turn, progress, effort, and reviewer
+- Never read or store conversation content for product presentation
+
+Hook `Stop` is only a completion candidate. Rollout terminal state distinguishes actual completion, user cancellation, and abnormal termination.
+
+### Locating Session Files
+
+The reader checks a few likely directories first:
+
+1. `sessions/YYYY/MM/DD` for the task start date
+2. The current date directory
+3. `archived_sessions`
+
+A resume can continue a session created long ago. If the fast path misses, each active session lifecycle performs one recursive fallback scan at most, avoiding a full sessions-tree traversal every second.
+
+If a file moves to the archive, a missing cached URL clears its cursor and allows full discovery again.
+
+### Why the Rollout Cursor Starts at the Last 512 KB
+
+Live tasks need lifecycle near an active turn, not a full read of a long-running session. Starting from the last 512 KB reduces resident I/O and discards the first potentially partial line.
+
+If effort remains missing, a targeted lookup for that turn can read up to 8 MB.
+
+Effort backfill applies only to nonterminal tasks that have run for at least 2 seconds and still lack effort, with a 10-second retry interval per turn. This avoids a large search immediately after every task creation.
+
+### Why Only Structural Events Are Parsed
+
+The shared `CodexRolloutLineEnvelope` extracts only fields needed for turn context, lifecycle, and progress. Prompt, response, and tool content never enters the activity model.
+
+This tightens privacy boundaries and reduces decode cost for large rollouts. A new live field should extend the minimal envelope rather than decode the full transcript into a general JSON tree.
+
+## Task Identity
+
+The task key chooses the most precise available identity:
+
+1. `session ID + turn ID`
+2. `session ID`
+3. Anonymous project key
+
+A new prompt replaces the old turn in the same session. The old turn enters terminal grace for up to 5 seconds so late ending events can reconcile it.
+
+Subagent events update activity under their parent task and do not create separate top-level cards.
+
+### Why Identity Degrades by Precision
+
+`session ID + turn ID` precisely distinguishes sequential turns in one session and is preferred.
+
+Some events contain only session ID. A session key still participates in state, but terminal matching must be more conservative. If one session has several candidates, the monitor returns ambiguous rather than guessing which task ended.
+
+Without a session ID, only a project key remains. It may merge concurrent anonymous tasks in one project, so anonymous tasks provide reversible UI visibility but cannot drive notifications, sleep prevention, or persisted protection.
+
+### Why a New Prompt Does Not Immediately Terminate the Old Turn
+
+Turns in one session run sequentially. When a new prompt arrives, the old turn must leave the active list immediately or the UI briefly shows two top-level tasks.
+
+The new prompt may precede the old turn's rollout terminal, however. Recording termination immediately would misclassify a normally completed task.
+
+The old turn therefore moves to `pendingTerminalTasks`:
+
+- Remove it from the active snapshot immediately
+- Retain task metadata and start time
+- Wait up to 5 seconds for rollout terminal
+- Classify accurately as completed or aborted when terminal arrives
+- Converge with a conservative fallback when grace expires without terminal
+
+`SessionEnd` uses the same confirmation window but moves all tasks in the session no later than that event.
+
+### Rejecting Late Events
+
+Tasks store `lastActivityAt`, and terminal memory stores completion or termination time:
+
+- An event older than current last activity cannot overwrite newer state
+- A new prompt no later than a remembered terminal cannot revive the old task
+- A `Stop` matching several candidates is not guessed
+- A key already in terminal deduplication memory clears recovery tasks left by abnormal ordering
+
+These comparisons use event time rather than batch-arrival order because cross-process file writes and rollout polling can deliver old events late.
+
+### Anonymous Tasks
+
+When `WorkflowHookEvent.sessionId` is missing, the key is an anonymous project key. `isAnonymous` propagates through `CodexActivityTaskSnapshot`, `CodexActivityCompletion`, and `CodexActivityTermination`.
+
+Anonymous tasks remain in activity snapshots and recent terminal records. The activity card and Task Center use the orange `person.crop.circle.dashed` icon with help text `Anonymous tasks do not prevent sleep`. The card's `+N` counts all other active tasks only.
+
+Anonymous running tasks do not show precise elapsed time, and anonymous completion and termination records omit precise duration.
+
+They publish no waiting or completion transitions to notification consumers, trigger no task haptics, enter neither the running nor waiting sets for KeepAlive, and do not participate in Stalled Task Protection. `activityProtectionIdentifier` returns `nil` for an anonymous key, so protection state never persists an anonymous task.
+
+### Why Anonymous Tasks Still Appear in the UI
+
+A missing session ID does not mean the task does not exist. Dropping it entirely would show Codex working while CodexBar appears idle.
+
+Keeping visibility while forbidding high-impact side effects is a layered response to uncertain identity:
+
+- Later events can correct a visibility error
+- A false notification interrupts the user
+- Incorrect sleep prevention may last for hours
+- Persisting an anonymous project key might suppress a different real task later
+
+The orange dashed-person icon therefore communicates limited capability instead of presenting an anonymous task as precise.
+
+## State Machine
+
+Active tasks mainly use these internal states:
+
+| State | Meaning |
+| --- | --- |
+| `running` | Codex is processing the current turn |
+| `waitingApproval` | The current turn is explicitly waiting for user approval |
+| `suppressed` | Stalled Task Protection hid the task pending new progress |
+
+`PermissionRequest` enters `waitingApproval` only when the reviewer is the user. Automatic or policy approval does not count as user waiting.
+
+Terminal signals reconcile by reliability:
+
+- `SessionEnd` ends the session
+- Rollout terminal distinguishes completion from termination
+- `Stop` creates a completion candidate without stronger evidence
+- A new prompt may end the display lifecycle of the old turn
+
+### Main Event-to-State Transitions
+
+| Current state | Input | New state | Additional action |
+| --- | --- | --- | --- |
+| Absent | `UserPromptSubmit` | running | Save trusted `startedAt` |
+| Absent | Top-level tool or compact | running | Recover task with unknown `startedAt` |
+| running | Tool, compact, or subagent progress | running | Update last progress and generation |
+| running | `PermissionRequest` + reviewer user | waitingApproval | Publish live waiting transition |
+| waitingApproval | New progress | running | Clear pending approval and protection record |
+| running or waiting | `Stop` | terminal candidate | Retain completion or wait for rollout reconciliation |
+| active | New prompt or `SessionEnd` | pending terminal | Remove from snapshot and begin 5-second grace |
+| running | Silence exceeds threshold | suppressed | Hide and remove sleep-prevention contribution |
+| suppressed | New progress | running | Clear persisted protection and old notification |
+
+### Why Waiting for Approval Uses Two-Phase Confirmation
+
+`PermissionRequest` indicates an approval flow, but reviewer may be user, policy, or automatic review.
+
+If the Hook event includes reviewer, the task can confirm immediately. If reviewer is missing, it saves `pendingApprovalRequestedAt` and waits for rollout polling to fill it in.
+
+Only an explicit user reviewer emits a waiting transition. Remaining running while uncertain is more truthful than falsely telling the user Codex is waiting for them.
+
+### Why Effort Can Become `mixed`
+
+Several context events in one turn may report different reasoning efforts. The task does not silently let the last overwrite the first. It marks `mixed` after observing conflict.
+
+This tells the UI that several values genuinely appeared over the task lifecycle rather than displaying a precise-looking value from only the final observation.
+
+### Why Subagent Count Can Be Unknown
+
+A subagent turn ID belongs to the subagent, so its parent can be associated only by shared session.
+
+Active subagent count is reliable only when exactly one active parent exists in that session, no pending-terminal ambiguity exists, and start/stop events carry stable agent IDs.
+
+With missing IDs, stop-before-start, or several candidates in one session, the monitor lowers reliability and the UI omits a falsely precise number.
+
+## Snapshot Priority
+
+When several tasks and temporary states coexist, the outward snapshot uses this priority:
+
+```text
+Waiting for approval > Running > Recently completed > Recently terminated > Idle
+```
+
+Completion remains green in the menu bar for 30 seconds. Task Center retains recent tasks for 10 minutes, while terminal deduplication memory lasts 24 hours.
+
+The snapshot feeds:
+
+- Menu bar status dot
+- Main-panel task card
+- Task Center
+- Notification system
+- Sleep-prevention controller
+
+### Why Recent Completion and Termination Have Different Weight
+
+Completion produces a 30-second green menu bar highlight as short positive feedback. Termination appears only in recent records, emits no completion transition, and has no green state.
+
+Task Center retains terminal items for 10 minutes, while keys preventing duplicate completion from late events remain for 24 hours. Display retention and deduplication retention solve different problems and must not be combined into one cache.
+
+### Why Publish Only When the Snapshot Changes
+
+The monitor polls rollout each second and also updates itself at several deadlines. Assigning the same value to `@Published` on every cycle would make SwiftUI and all Combine consumers recalculate unnecessarily.
+
+A candidate snapshot is compared with the current value and published only after structural change. Views format elapsed time from the current clock and do not require per-second mutation of task objects.
+
+### Stable Sorting Tie-Breaker
+
+Several tasks in one batch can share timestamps, and Swift sorting is unstable.
+
+All lists sort by most recent time first and then display UUID string. Stable order keeps SwiftUI diffing from jumping when equivalent tasks randomly exchange positions.
+
+### Cleanup Uses the Nearest Deadline
+
+The monitor manages completion highlight, terminal grace, activity retention, history retention, terminal deduplication, and protection-record expiration.
+
+It does not scan everything on a fixed high-frequency timer. It gathers future deadlines and schedules one `Task` for the nearest. After it fires, it recalculates the next.
+
+This reduces meaningless wakeups for a resident menu bar app and lets every retention period take effect on time even without a new Hook event.
+
+## System Sleep and Wake
+
+Stalled Task Protection pauses when the system is about to sleep. Wake follows a strict recovery order:
+
+1. Enter recovery and keep protection paused
+2. Wait for `HookEventTailReader.drainNow()` to succeed
+3. Reset rollout-lifecycle parsing fallback
+4. Reconcile from the new Hook and rollout results together
+5. Resume Stalled Task Protection
+
+If the new read fails, the reader is replaced, or the source is unavailable, evaluation must not continue from the pre-sleep snapshot.
+
+### Why Silence Timing Pauses During System Sleep
+
+Neither Hook nor rollout produces normal progress during system sleep. Comparing wall time alone would classify every running task as stalled immediately after a two-hour sleep.
+
+Protection schedules its next check with `SuspendingClock`, but system-time changes and data-source recovery still require explicit recalculation. `will-sleep` enters recovery first; `did-wake` restores evaluation only through a new data read barrier.
+
+### Why Wake Order Cannot Be Reversed
+
+Rollout reconciliation must occur after a successful Hook drain.
+
+Reading rollout first may find lifecycle data whose task key has not yet been added to the monitor from Hook events written during sleep. Resuming protection first could hide tasks from a pre-sleep last-progress time.
+
+`readerGeneration` prevents a returning wake task from using a reader replaced by a Hook settings change. `recoveryGeneration` prevents an older recovery from unpausing evaluation after two overlapping sleep or settings changes.
+
+## Stalled Task Protection
+
+Stalled Task Protection works only while Prevent System Sleep is enabled and evaluates only non-anonymous `running` tasks.
+
+Tasks waiting for approval are excluded because waiting is a legitimate no-progress state.
+
+Threshold options are:
+
+- 30 minutes
+- 1 hour, the default
+- 2 hours
+- 4 hours
+
+At the threshold:
+
+1. Persist a protection record first
+2. Start notification submission and a 3-second grace period together
+3. Revalidate the candidate after notification completes or grace expires
+4. If still valid, hide it from the activity snapshot
+5. If new progress appears during or after this process, clear protection and restore display
+
+Hiding does not depend on notification success. The 3 seconds is only the maximum wait for an explanatory notification; sleep-prevention contribution is still released afterward.
+
+Evaluation pauses during:
+
+- Hook bootstrap
+- System sleep
+- Wake recovery
+- Hook data-source unavailability
+- Reader replacement
+
+### Failure Model Addressed by Protection
+
+After Hook or Codex exits abnormally, `Stop`, `SessionEnd`, and rollout terminal may all be missing. A task can remain running indefinitely and keep sleep prevention active forever.
+
+Protection does not decide whether Codex is “truly stuck.” It handles one observable fact: a non-anonymous running task made no Hook or rollout progress beyond the threshold while sources were trusted.
+
+Waiting tasks are excluded because waiting for the user is legitimate silence. Anonymous tasks are excluded because a project key cannot prove which specific task a persisted record belongs to.
+
+### Purpose of Progress Generation
+
+Timestamps alone cannot protect an asynchronous attempt. Two progress events may share the same second, and the threshold setting may change while notification submission is in flight.
+
+Every valid progress event increments `progressGeneration`. A protection candidate stores:
+
+- Task display ID
+- Last-progress timestamp
+- Progress generation
+- Threshold at the time
+
+All four must still match when notification returns or grace expires. Any new progress or threshold change invalidates the old attempt.
+
+### Why Persist Before Hiding
+
+After a task disappears from the snapshot, the app may immediately exit or the system may sleep. Without a queued persistence write, restart bootstrap could show it again and let it support sleep prevention.
+
+The attempt therefore writes the record first, waits for notification submission, then hides. Failed notification permission or service does not block suppression because releasing erroneous sleep prevention is the protection's core purpose.
+
+### Meaning of the 3-Second Notification Grace
+
+The protection notification is useful explanation but cannot block sleep restoration indefinitely:
+
+- Suppress immediately when notification submission succeeds
+- Suppress after 3 seconds if it has not finished
+- If notification succeeds later but the attempt is invalid, withdraw it immediately
+- New progress within grace cancels the attempt and persisted record
+
+This window constrains the notification side effect only; it does not alter the silence threshold.
+
+### Reconciling Threshold Changes
+
+Shortening the threshold immediately reevaluates running tasks already past it.
+
+Lengthening it silently restores suppressed tasks that no longer exceed the new threshold and clears their records and notifications. Tasks still beyond the new threshold remain suppressed without duplicate alerts.
+
+Turning off Prevent System Sleep disables Activity Protection and restores all suppressed tasks because protection exists to prevent incorrect sleep blocking, not to hide tasks permanently.
+
+## Protection-State Persistence
+
+[`ActivityProtectionStateStore.swift`](../../../CodexBar/Services/Workflow/ActivityProtectionStateStore.swift) writes:
+
+```text
+~/Library/Application Support/CodexBar/ActivityProtection/state.json
+```
+
+- Current schema is `1`
+- Contains only hashed task identities and timestamps
+- File permissions are `0600`
+- Debug and Release share it through `flock`
+- Records remain at most 24 hours after last progress
+
+Task identity uses a SHA-256 digest; raw session and turn IDs never enter this state file. Anonymous tasks have no protection identity and never enter it.
+
+### Constructing the Hashed Identity
+
+Turn and session keys first become canonical strings with type prefixes and NUL separators, then SHA-256 is applied with the fixed domain separator `CodexBar.ActivityProtection.v1`.
+
+Types and separators prevent boundary ambiguity between concatenated fields. The domain separator prevents directly correlating the same raw ID hashed for another use.
+
+This does not resist brute force when the session ID is already known. It prevents readable identity from appearing directly in the state file and limits cross-purpose correlation.
+
+### Why Debug and Release Share a Locked File
+
+Both app bundle IDs can run together and observe the same Codex Hook data. With separate protection state, a stalled task hidden by one build might still drive sleep prevention in the other.
+
+The state store uses an actor to serialize within one process and `flock` for cross-process read-modify-write. A removal can include `matchingMarkedAt`, preventing a late delete from an old process from removing a new record just written by another.
+
+Writes sort by task identifier, atomically replace the file, and correct final permissions to `0600`.
+
+## Generation and Old-Result Isolation
+
+The monitor maintains generations for readers and asynchronous recovery:
+
+- Discard late results from a replaced reader
+- Publish no transition side effects before bootstrap completes
+- A canceled drain does not satisfy a recovery barrier
+- Explicitly unhealthy source state cannot reuse the last healthy snapshot for silence evaluation
+
+These constraints prevent false completion alerts and incorrect release during system wake, Hook reinstall, or `CODEX_HOME` change.
+
+### Main Generations in the Monitor
+
+| Generation | Protected asynchronous path |
+| --- | --- |
+| `tailReaderGeneration` | Reader batch, rollout polling, and prompt backfill |
+| `bootstrapCompletionGeneration` | Asynchronous lifecycle completion after repeated bootstrap attempts |
+| `activityProtectionRecoveryGeneration` | Sleep, wake, and data-source recovery |
+| Task `progressGeneration` | Protection candidate during notification grace |
+
+Each answers a different “is this current?” question and cannot become one global counter. A task making progress without a reader change should invalidate only its protection attempt, not the entire reader.
+
+## Steps to Extend the Task State Machine
+
+1. Classify new input as fact, metadata, progress, or terminal
+2. Define whether bootstrap and live input produce the same snapshot and whether either may emit a transition
+3. Define degradation when turn or session ID is missing
+4. Define how timestamp, terminal memory, or generation rejects late and duplicate input
+5. If reading a new rollout field, extend the minimal envelope rather than reading content
+6. Keep per-task domain state in `CodexActivityTask` and cross-task association in the monitor
+7. Before changing the snapshot, decide whether notifications and sleep prevention should consume the new state
+8. Define recovery for system sleep, reader replacement, and unhealthy sources
+9. By default, anonymous tasks gain no new high-impact side effect unless identity reliability changes fundamentally
+
+## Suggested Failure-Scenario Tests
+
+- Starting the app while a task is running shows it through bootstrap without replaying notifications
+- Bootstrap retries while files continuously append and eventually obtains a stable boundary
+- Three unstable attempts enter degraded state without starting silence evaluation
+- A new prompt immediately replaces the old turn, and rollout terminal within 5 seconds classifies it correctly
+- A `Stop` is not guessed when one session has several terminal candidates
+- A missing reviewer enters waiting only after rollout confirms user
+- Automatic review never emits a waiting transition
+- The UI omits a falsely precise subagent count when association is unreliable
+- Calling `drainNow()` during a read forces another new read
+- Protection remains paused after a failed wake drain
+- A silence candidate that progresses within the 3-second window is not hidden, and a late notification is withdrawn
+- Lengthening the threshold restores suppressed tasks below the new threshold
+- Concurrent Debug and Release updates do not let an old removal delete a new protection record
+- Anonymous tasks never enter transitions, KeepAlive, or the protection state file
+
+## Key Source Files
+
+- [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)
+- [`CodexActivityTask.swift`](../../../CodexBar/Services/Workflow/CodexActivityTask.swift)
+- [`CodexActivityTerminalResolution.swift`](../../../CodexBar/Services/Workflow/CodexActivityTerminalResolution.swift)
+- [`HookEventTailReader.swift`](../../../CodexBar/Services/Workflow/HookEventTailReader.swift)
+- [`CodexSessionLifecycleReader.swift`](../../../CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift)
+- [`CodexActivityProtection.swift`](../../../CodexBar/Services/Workflow/CodexActivityProtection.swift)
+- [`ActivityProtectionStateStore.swift`](../../../CodexBar/Services/Workflow/ActivityProtectionStateStore.swift)
diff --git a/Docs/en/DeveloperGuide/app-server.md b/Docs/en/DeveloperGuide/app-server.md
new file mode 100644
index 0000000..50d4a71
--- /dev/null
+++ b/Docs/en/DeveloperGuide/app-server.md
@@ -0,0 +1,490 @@
+# app-server Data Flow
+
+[简体中文](../../DeveloperGuide/app-server.md) | English
+
+## Design Motivation
+
+CodexBar does not reimplement Codex sign-in, token refresh, or account protocols. It treats local `codex app-server` as the account-capability boundary.
+
+This design means:
+
+- Codex owns authentication and server protocols, so CodexBar does not duplicate a client that can drift
+- The app communicates with a local subprocess over stdio, avoiding another direct network implementation in the primary account flow
+- The version of Codex actually running comes from the handshake and can gate global and Hook capabilities
+- A global CLI and an app-bundled CLI share one upper-level data model
+
+The cost is that a menu bar app must handle missing shell environments, subprocess lifecycle, pipe backpressure, mixed stdout, timeouts, and connection rotation after upgrades.
+
+## Responsibilities
+
+The app-server flow reads Codex account and server state:
+
+- Current account and plan
+- 5-hour and weekly rate limits
+- Token usage and usage history
+- Reset Credits state
+- Hook feature flags, handler lists, and configuration-write capabilities
+
+It does not own historical Hook metrics or live task state.
+
+### Input and Output Boundaries
+
+```text
+CodexCLIResolver
+ -> AppServerCommand
+ -> CodexStatusService actor
+ -> AppServerSession
+ -> Process + stdin/stdout/stderr
+ -> CodexQuotaSnapshot
+ -> CodexStatusViewModel
+ -> Menu bar and main panel
+```
+
+`CodexStatusService` owns the connection and same-account cache. `CodexStatusViewModel` owns only UI loading state, automatic-refresh timing, and the latest connection information.
+
+This division lets Settings reuse the same app-server session to read and write Hook and TUI configuration without giving a view direct ownership of `Process` or pipes.
+
+## Locating Codex CLI
+
+[`CodexCLIResolver.swift`](../../../CodexBar/Services/CodexCLI/CodexCLIResolver.swift) first searches the process `PATH` for global `codex`, then checks bundled paths:
+
+```text
+/Applications/ChatGPT.app/Contents/Resources/codex
+/Applications/Codex.app/Contents/Resources/codex
+```
+
+A menu bar app launched from Finder may lack the complete `PATH` of an interactive shell, so the resolver also adds common installation directories:
+
+```text
+/opt/homebrew/bin
+/usr/local/bin
+~/.npm-global/bin
+~/.local/bin
+~/.volta/bin
+/usr/bin
+/bin
+/usr/sbin
+/sbin
+```
+
+The data directory uses `CODEX_HOME` when set and otherwise uses `~/.codex` under the real user's home directory.
+
+### Why the Process Environment Is Not Trusted Directly
+
+An `LSUIElement` app launched from Finder or Login Items usually lacks the complete `PATH` injected by an interactive shell. Calling only `/usr/bin/env codex` would make Homebrew, Volta, or global npm installations work in Terminal but disappear from CodexBar.
+
+The resolver normalizes in three layers:
+
+1. Resolve the real login user's home with `getpwuid(getuid())`, avoiding an incorrect `HOME` inherited from Xcode or a container
+2. Preserve the existing `PATH`, then append common directories in order and deduplicate
+3. Resolve symlinks and standardized URLs for candidates so one bundled binary is not identified as both global and bundled
+
+Preferring the global CLI is an explicit product choice. A CLI deliberately installed by a developer generally represents the intended version; a bundled CLI is a fallback when no global version exists.
+
+### Why On-Disk and Running Versions Are Separate
+
+Settings may read versions from both CLI candidates on disk, but minimum-version checks for the primary flow and Hook use only the app-server `userAgent` returned by `initialize`.
+
+A connection may be reused for up to 1 hour. If the user upgrades the on-disk binary while it remains alive, the current process is still the old version. Checking the disk value would let the UI claim a capability is available while the running app-server does not support its method.
+
+## Process and Protocol
+
+CodexBar launches this command and communicates over stdio:
+
+```bash
+codex app-server --listen stdio://
+```
+
+The protocol is line-delimited JSON-RPC. A connection sends `initialize`, then `initialized`, then reads the account:
+
+```text
+Start subprocess
+ -> initialize(clientInfo)
+ -> Validate actual version >= 0.143.0
+ -> initialized
+ -> account/read
+ -> account/rateLimits/read
+ -> account/usage/read
+```
+
+stdout may contain non-JSON output. The pipe reader continuously reads complete lines and forwards only messages that decode and match the response ID of a pending request. stderr is drained separately so the subprocess cannot block on a full pipe.
+
+### Complete Connection Transaction
+
+```text
+Resolve executable
+ -> Create stdin/stdout/stderr pipes
+ -> Start Process
+ -> initialize(clientInfo)
+ -> Save actual version from userAgent
+ -> Validate actual version >= 0.143.0
+ -> initialized notification
+ -> account/read(refreshToken: false)
+ -> Account exists: commit connection
+ -> Account missing: close process and return notLoggedIn
+```
+
+A connection enters service state only after the actual version passes the global threshold and both handshake and first account read succeed. A version below `0.143.0` or an unparseable version is treated as unsupported; the half-initialized session closes without further account requests.
+
+### Why the stdout Reader Exposes Complete Lines Only
+
+app-server frames one JSON message per line. A `Data` block delivered to the pipe callback may:
+
+- Contain half a line
+- Contain several lines
+- Mix ordinary logs between JSON lines
+- End with an unterminated final line when the process exits
+
+`PipeReadBuffer` therefore maintains its own byte buffer and publishes only complete, nonempty lines terminated by a newline. The session first decodes only the response ID and fully decodes a result or error only when the ID matches.
+
+This avoids treating logs as protocol errors and fully decodes a large response only once.
+
+### Why stderr Must Also Be Drained
+
+Even though CodexBar does not display stderr content, it must drain the pipe. A subprocess pipe buffer is finite; if the parent never reads stderr, app-server eventually blocks while writing and no later stdout response can arrive.
+
+`PipeDrain` does not parse content. It only removes backpressure. This is required for process correctness, not a logging feature.
+
+### Shutdown Strategy
+
+A session shuts down in this order:
+
+1. Stop stdout and stderr readers
+2. Close the stdin writer so app-server can observe EOF normally
+3. Wait up to 1 second for a graceful exit
+4. If still running, force termination and wait another 0.5 seconds
+5. If it remains alive, record a diagnostic error
+
+Writing after an early process exit may raise `SIGPIPE`. The service ignores that signal during initialization so the write returns a Swift error and follows the transport-rebuild path instead of terminating the entire menu bar app.
+
+## API Surface
+
+| Method | Purpose |
+| --- | --- |
+| `account/read` | Read account, plan, and authentication state |
+| `account/rateLimits/read` | Read rate-limit windows |
+| `account/rateLimitResetCredit/consume` | Use a specified Reset Credit |
+| `account/usage/read` | Read tokens and usage history |
+| `config/read` | Read Codex configuration |
+| `hooks/list` | Validate Hook source and event capabilities |
+| `config/batchWrite` | Change Hook or TUI notification configuration |
+
+Each session caches unsupported methods. After app-server explicitly returns method unsupported, that connection does not request the method again.
+
+### Why Unsupported State Is Cached Per Session
+
+Method unsupported usually means the running app-server lacks a capability. Calling it again every minute only adds logs and latency.
+
+The conclusion must not persist to UserDefaults, however, because a new connection may come from an upgraded binary. The unsupported set belongs only to `AppServerSession` and is probed again after reconstruction.
+
+### Why Configuration Reuses the Same Connection
+
+`config/read`, `hooks/list`, and `config/batchWrite` must use the same actual app-server source as account refresh.
+
+A separate resolver or process for Settings could connect the main panel to the global CLI while Hook validation connects to a bundled CLI. One service keeps capability checks, configuration source, and running version tied to the same process choice.
+
+## Session Lifecycle
+
+[`CodexStatusService.swift`](../../../CodexBar/Services/CodexStatus/CodexStatusService.swift) is an actor that owns the connection and refresh state:
+
+- One request times out after 20 seconds
+- A connection is reused for at most 1 hour
+- A business error retries at most once in the same session
+- A transport failure rebuilds the connection at most once
+- When authentication requires refresh, `account/read` retries with `refreshToken = true` at most once
+- Closing the service or exiting the process terminates the subprocess and completes all pending requests
+
+Business and transport errors are separate. The former may be a temporary failure of one method; the latter makes the current stdio session untrustworthy.
+
+### Connection State Machine
+
+```text
+no connection
+ -> resolve CLI
+ -> open and initialize
+ -> ready
+
+ready
+ -> age < 1h and process alive: reuse
+ -> process exited: close and rebuild
+ -> age >= 1h: close and rebuild
+ -> transport failure: close and rebuild once
+ -> account missing after refresh: close and notLoggedIn
+```
+
+One hour is the maximum connection lifetime, not the data-refresh interval. Periodic reconstruction ensures an upgraded Codex binary takes effect within one connection cycle.
+
+### Error Classification Matrix
+
+| Error | Current request | Current connection | Full refresh |
+| --- | --- | --- | --- |
+| Retriable server error | Retry the same method once | Preserve | Continue from second result |
+| Method unsupported | Mark unsupported for this session | Preserve | Corresponding field is missing |
+| Ordinary business failure | Do not retry | Preserve | Same-account cache may degrade |
+| Authentication required | Refresh the token once for the cycle, then retry | Preserve or become signed out | At most one refresh overall |
+| Timeout, pipe close, invalid transport | Fail | Discard immediately | Rebuild once only when reusing a connection |
+
+Limiting reconstructions prevents a fault from repeatedly launching subprocesses. The next normal timed refresh still gets a new attempt after the current cycle ends.
+
+### Why Authentication Refresh Happens Only Once per Cycle
+
+One refresh reads account, rate limits, and usage; Reset Credits details are included in the rate-limit response. Several interfaces may detect an expired token in the same cycle.
+
+`fetchData` uses one `didRefresh` latch for the entire cycle. The first authentication failure triggers `account/read(refreshToken: true)`, and later methods reuse that result. A second authentication requirement is classified as signed out.
+
+This avoids repeatedly refreshing the same credential during one UI refresh.
+
+## Refresh Model
+
+The status view model refreshes every 60 seconds by default. The user can also double-click in the main panel for an immediate refresh.
+
+Each refresh resolves the account first, then reads rate limits and usage. Supplemental caches are strictly bound to account identity:
+
+- If the account is unchanged and a supplemental request fails, cached values may remain visible
+- If the account changes, the old-account cache is cleared immediately
+- An explicitly unsupported method appears as a missing source
+- A missing source must not become the business value `0`
+
+A coordinator coalesces refresh tasks so the timer, panel opening, and manual refresh do not issue duplicate concurrent requests.
+
+### Building One Snapshot
+
+```text
+Confirm or create connection
+ -> On reuse, account/read
+ -> Confirm account identity
+ -> account/rateLimits/read (including Reset Credits details)
+ -> account/usage/read
+ -> Build CodexQuotaSnapshot
+ -> Commit loadState and connection info on MainActor
+```
+
+Rate limits and usage are supplemental. As long as the account is valid, CodexBar still creates a snapshot when both interfaces return no data so the UI can show the account and an explicit “No Data.”
+
+Treating missing supplemental interfaces as signed out would make identity flicker between real sign-in and error and would hide the difference between authentication problems and one unsupported new method.
+
+### Cache Decision Table
+
+| Current result | Same-account cache | Output | stale |
+| --- | --- | --- | --- |
+| Success | Any | New value and cache update | `false` |
+| Ordinary request failure | Yes | Cached value | `true` |
+| Ordinary request failure | No | `nil` | Not applicable |
+| Method unsupported | Any | `nil` | Not applicable |
+| Account changed | Old-account cache | Clear all first | Not applicable |
+
+Method unsupported does not use old cache because it is an explicit capability result. Ordinary failure does because the source may be transiently unavailable for one cycle.
+
+### How Stale State Affects Consumers
+
+- The UI may display old values but reduces menu bar and progress-bar opacity
+- `hasTrustedData` counts only non-stale rate-limit or usage data as trusted
+- Rate-limit notifications skip stale rate limits entirely
+- System logs record only a `cached` step, never actual rate-limit values
+
+Stale is part of data confidence. A new presentation must not copy the value while dropping the marker.
+
+### Why the Refresh Coordinator Still Needs a Generation
+
+An `isRefreshing` guard prevents ordinary duplicate triggers, but cancellation and object lifecycle may still let an old `Task` return.
+
+`RefreshTaskCoordinator` advances its generation at each start, cancels the old task, and allows only a result satisfying `canCommit(generation)` to update UI. “Last requested refresh wins” becomes an explicit rule.
+
+Automatic refresh waits for the remaining interval since the last completion. After a manual refresh, the countdown realigns naturally rather than letting the old timer refresh again a few seconds later.
+
+### Small Model-Layer Optimizations
+
+`CodexUsageSnapshot` aggregates potentially repeated daily buckets into `tokensByDate` during initialization.
+
+A heatmap queries dates repeatedly during one render. Building the index up front avoids a linear scan for every cell while preserving the raw array for snapshot equality.
+
+Rate-limit ordering is also centralized in the model:
+
+- The primary limit referenced by the top-level app-server `rateLimits` comes first
+- Remaining limits use a stable sort by localized name and limit ID
+- Stable enums distinguish primary and secondary; views do not infer window type from label strings
+
+## Reset Credits
+
+`rateLimitResetCredits` from `account/rateLimits/read` provides both an available count and optional details:
+
+- `availableCount` is the authoritative total
+- `credits == nil` means only the count is known
+- An empty array means the server obtained details but returned no available credit
+- The server may truncate details, so their length can be less than `availableCount`
+- Each detail includes an opaque `id`, `status`, and optional Unix-seconds `expiresAt`
+- Each detail also includes `resetType`; Automatic Reset accepts only `codexRateLimits`
+
+The model retains expiration dates only for entries with `status == available` and a time later than snapshot creation, then sorts them by time. The count still comes independently from `availableCount` and cannot be inferred from filtered dates.
+
+Expiration details are supplemental. With `credits == nil`, the main panel still shows the available count and details show an unknown expiration time without affecting rate limits or usage. When rate-limit data comes from same-account cache, the UI may display old details, but notifications never use stale data for new expiration alerts.
+
+### Automatic Reset
+
+After the user explicitly enables Automatic Reset, [`AutoResetController.swift`](../../../CodexBar/Services/CodexStatus/AutoResetController.swift) processes only credit details explicitly returned by the latest `account/rateLimits/read`:
+
+- It never calls consume for a stale snapshot, `credits == nil`, missing `expiresAt`, non-`available` state, or a `resetType` other than `codexRateLimits`
+- Details may be truncated; it processes only returned credits and never guesses unlisted `creditId` values from `availableCount`
+- It selects only the earliest-expiring returned credit at a time, then selects the next after completion or disappearance
+- After entering the user-selected lead-time window, it forces another account and credit read before redemption
+- The request always passes an explicit `creditId`; the backend never chooses implicitly
+- It reads rate limits again immediately after a redemption result
+- `reset`, `alreadyRedeemed`, and `noCredit` request a full rate-limit refresh; `nothingToReset` schedules another attempt if the target remains, otherwise it requests a full refresh
+
+The call has this shape:
+
+```text
+account/rateLimitResetCredit/consume
+ creditId: <exact opaque id>
+ idempotencyKey: <deterministic UUIDv5>
+```
+
+Results have these semantics:
+
+| `outcome` | Conclusion | Next action |
+| --- | --- | --- |
+| `reset` | This call redeemed the credit | Success notification, rate-limit refresh, stop retrying this credit |
+| `alreadyRedeemed` | The same idempotency key redeemed it previously | Treat like `reset` and as success |
+| `nothingToReset` | No rate-limit window can currently be reset | Credit remains unredeemed; retry with the same idempotency key |
+| `noCredit` | The account currently has no available credit | Force refresh; stop silently if the target disappears, otherwise retry as temporary inconsistency |
+
+`alreadyRedeemed` is neither failure nor a second redemption. It confirms that the same logical request already succeeded, so a device receiving it stops retries and sends its local “Automatic Reset” notification.
+
+### Cross-Device Idempotency Contract
+
+The same Codex account may run CodexBar on several Macs. Devices do not coordinate through CloudKit. They calculate the exact same UUIDv5 for the same `creditId`:
+
+```text
+namespace = c2904ab3-0a87-5648-997d-bd8515edd401
+name = raw UTF-8 bytes of creditId
+output = lowercase UUID string
+```
+
+The namespace is UUIDv5 of the URL namespace and `https://codexbar.zabrian.app/idempotency/auto-reset/v1`. This URL determines the namespace only and does not represent a runtime network request.
+
+The fixed test vector is:
+
+```text
+creditId = RateLimitResetCredit_123
+idempotencyKey = 4035685d-9ca4-524f-8193-6e0ae2a7b3b9
+```
+
+The namespace, UUID version, raw UTF-8 input, and lowercase output form a cross-version compatibility protocol and must not change in an ordinary refactor. The first successful device redeems the credit; other devices calling with the same key receive `alreadyRedeemed` or discover during preread that the credit disappeared.
+
+Disappearance cannot distinguish manual use, use by another device, or server expiration. The local task therefore stops without an Automatic Reset success notification. Only a device that explicitly receives `reset` or `alreadyRedeemed` sends one.
+
+### Scheduling and Retry
+
+The Automatic Reset state machine and network requests remain in the regular app process. CodexBarHelper owns only a constrained system wake schedule:
+
+- Enabling the feature reuses existing CodexBarHelper registration and approval without depending on Prevent System Sleep
+- The app submits only the nearest threshold or retry time; the helper replaces only CodexBar's own event with a fixed owner and `wake` type and accepts no arbitrary event type
+- After setting or canceling, the helper reads back system events and reports success only if exactly one target-time event exists or the event is confirmed absent
+- After a timer or wake, the app holds `PreventUserIdleSystemSleep` only during fresh reads and redemption; it does not keep the display awake or change `SleepDisabled`
+- A task change, feature disable, app exit, or corresponding XPC disconnect cancels CodexBar's wake event
+- On startup, the helper removes stale events for its fixed owner before accepting connections; if cancellation fails, it abandons the invalid connection owner and retries internally
+- Normal app exit waits for cancellation read-back; a forced exit or XPC disconnect makes the helper cancel immediately, while a sudden-power-loss event converges at next helper startup, after which the app reschedules from fresh details
+- On app launch, feature enable, or system wake, the app performs a fresh read first; it attempts immediately if the credit is inside its lead-time window and unexpired, otherwise it schedules for that window
+- The app does not persist raw `creditId` after exit; next launch rebuilds tasks and the same deterministic idempotency key from fresh details
+- When `expiresAt` changes for the same `creditId`, it preserves idempotent identity but cancels the current threshold or retry and reschedules; if the new lead-time point has passed, it rechecks immediately
+- A retry wake event requires a known `creditId + expiresAt`; a count-only or failed read never wakes the Mac merely to query again
+- Network, timeout, disconnect, or temporary service errors use `15s, 30s, 1m, 2m, 5m` backoff but never schedule a retry at or after the current 5-minute deadline
+- At round timeout, local work and the system wake event are canceled without marking the target failed; a later normal rate-limit refresh may start a new round for it
+- `nothingToReset` waits a fixed 60 seconds when expiration is less than 10 minutes away and the round remains active; otherwise it uses general backoff
+- Authentication failure first uses the service's single token refresh; if still unsuccessful, it pauses the current credit and notifies according to settings, then resumes after a trusted snapshot proves recovery
+- Parameter, protocol, or method errors stop the current credit without meaningless retries
+
+When Automatic Reset requests a full rate-limit refresh while an ordinary refresh is in progress, the new refresh queues behind it and must not be dropped by the `isRefreshing` guard.
+
+## Hook Version and Configuration Validation
+
+Hook settings reuse the app-server flow but maintain independent availability state:
+
+- `isEnabled` means the target handler is installed
+- `isVerified` means the latest explicit app-server validation passed
+- `isOperable` is true only when both are `true`
+- A transient RPC failure preserves the last explicit validation result
+
+Enabling or validating Hook requires the actual app-server version to be at least `0.145.0`.
+
+See [Hook Capture and Historical Aggregation](hook-and-aggregation.md) for the full configuration flow.
+
+### Timing of the Actual-Version Check
+
+Enabling or validating Hook calls `readyConnectionInfo()`:
+
+- If no connection exists, it establishes one first
+- If a connection exists, it reuses the actual current process
+- It parses the running version from the handshake user agent
+- An unparseable version is treated as unsupported rather than allowed optimistically
+
+This is a capability-safety boundary. A future feature depending on an app-server method must place its minimum-version check at the actual connection-capability entry point, not merely show an on-disk version on About.
+
+## Request Logs
+
+[`RequestLog.swift`](../../../CodexBar/Services/CodexStatus/RequestLog.swift) keeps the latest 500 request records in memory for the in-app Logs window.
+
+It helps inspect process startup, JSON-RPC methods, retries, and error classifications. It must not contain access tokens or Hook prompt content.
+
+### Why There Are Two Logging Channels
+
+Unified system logs retain only control-flow classifications and support long-term diagnosis of whether refresh ran and which stage failed.
+
+The in-app `RequestLog` keeps previews of at most 500 request interactions in current-process memory for user-initiated protocol inspection.
+
+Reset Credits details include opaque credit IDs. Unified logs must not record IDs or raw responses; the in-app request log remains current-process-only under its existing rules. Before logging a new RPC, check whether its payload can contain credentials or content fields.
+
+## Steps to Extend app-server Data
+
+1. Model protocol optionality in the external DTO without filling display defaults first
+2. Decide in `CodexStatusService` whether the method is account-critical or supplemental
+3. Define degradation separately for ordinary failure, unsupported, and authentication failure
+4. If cached, bind the value to account identity and carry stale semantics
+5. Convert timestamps, percentages, ordering, and other stable rules in the domain snapshot
+6. Let UI consume only the snapshot, never the raw response
+7. Let notifications and other side effects use only trusted snapshots
+8. Check whether requests or logging broaden privacy boundaries
+
+## Suggested Failure-Scenario Tests
+
+- A Finder launch still finds Codex installed by Homebrew, npm, or Volta
+- When the global CLI is absent, fallback correctly uses the binary bundled with ChatGPT App or Codex App
+- Ordinary text mixed into stdout does not prevent matching the correct response ID
+- Continuous stderr output does not stall requests through pipe backpressure
+- A transport failure on a reused connection rebuilds only once
+- After an on-disk CLI upgrade, the current connection version remains distinct from the disk version
+- app-server below `0.143.0` blocks the primary account flow and asks for an upgrade
+- app-server `0.143.x` or `0.144.x` supports the primary account flow while Hook still requires `0.145.0`
+- app-server `0.145.0` or later supports both the account flow and Hook validation
+- A failed rate-limit read with same-account cache displays stale data without triggering notifications
+- An account switch clears old rate-limit and usage data immediately
+- An unsupported method is not retried every minute
+- Reset Credits with `credits == nil` preserve the authoritative count and show unknown expiration
+- Empty or truncated Reset Credits details do not redefine the available count from array length
+- Expired or non-available Reset Credits do not enter details or notifications
+- Stale rate limits may show old details but do not trigger expiration notifications
+- Automatic Reset does not call consume while off; a missing setting defaults off and lead time defaults to 30 minutes
+- Automatic Reset does not consume stale, detail-less, expiration-less, or unlisted credits
+- Two devices derive the same idempotency key for a fixed `creditId`, matching the fixed test vector
+- Changing expiration earlier or later for the same `creditId` reschedules while preserving the idempotency key
+- Both `reset` and `alreadyRedeemed` stop retries and send success notifications
+- `nothingToReset` retains the credit and retries under backoff
+- With sleep prevention off, the helper can still register and receive approval, and a future threshold writes a fixed-owner `wake` event
+- A scheduled time during system sleep wakes the Mac and triggers a reread; natural wake and app launch run the same catch-up check
+- Disabling the feature, changing the target, or quitting cancels the wake event without affecting other apps' scheduled events
+- Count-only or failed reads with no specific target do not schedule a query-retry wake event
+- A known target stops continuous retries 5 minutes after the near-expiration trigger; a later normal refresh may start a new round
+- A full rate-limit refresh after redemption is not dropped behind a concurrent ordinary refresh
+- The 60-second countdown realigns after manual refresh
+
+## Key Source Files
+
+- [`CodexCLIResolver.swift`](../../../CodexBar/Services/CodexCLI/CodexCLIResolver.swift)
+- [`AppServerSession.swift`](../../../CodexBar/Services/CodexStatus/AppServerSession.swift)
+- [`AppServerPipeReaders.swift`](../../../CodexBar/Services/CodexStatus/AppServerPipeReaders.swift)
+- [`CodexStatusService.swift`](../../../CodexBar/Services/CodexStatus/CodexStatusService.swift)
+- [`CodexStatusViewModel.swift`](../../../CodexBar/Services/CodexStatus/CodexStatusViewModel.swift)
+- [`AutoResetController.swift`](../../../CodexBar/Services/CodexStatus/AutoResetController.swift)
+- [`AutoResetIdentity.swift`](../../../CodexBar/Services/CodexStatus/AutoResetIdentity.swift)
+- [`AutoResetWakeScheduler.swift`](../../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)
+- [`CodexBarHelperXPC.swift`](../../../Shared/CodexBarHelperXPC.swift)
diff --git a/Docs/en/DeveloperGuide/architecture.md b/Docs/en/DeveloperGuide/architecture.md
new file mode 100644
index 0000000..c0889b3
--- /dev/null
+++ b/Docs/en/DeveloperGuide/architecture.md
@@ -0,0 +1,405 @@
+# Architecture
+
+[简体中文](../../DeveloperGuide/architecture.md) | English
+
+## What This Architecture Solves
+
+CodexBar's central challenge is not drawing a menu bar interface. It is coordinating short-lived Hook subprocesses, a local app-server, append-only files, CloudKit, system notifications, and a root helper inside a long-running `LSUIElement` app.
+
+See the [interactive runtime architecture diagram](https://codexbar.zabrian.app/architecture) for the full component relationships, data flows, and source references.
+
+The architecture must continuously satisfy these goals:
+
+- A failure in one data flow must not disable unrelated features
+- Short-lived Hook mode and normal app mode share an executable but have completely isolated lifecycles
+- The UI observes explainable snapshots and does not own I/O, deduplication, or recovery logic
+- Privileged operations expose the smallest possible interface while business policy remains in the unprivileged app process
+- Every asynchronous result can prove that it still belongs to the current configuration and data-source generation
+- Rebuildable data remains separate from side effects that cannot be replayed
+
+For the broader rationale, see [Design Principles and Key Decisions](design-decisions.md).
+
+## Technical Baseline
+
+CodexBar is a menu bar app for macOS 15 and later, built with Swift 6, SwiftUI, AppKit, and MVVM.
+
+The project has one `CodexBar` scheme with two targets:
+
+| Target | Responsibility |
+| --- | --- |
+| `CodexBar` | Menu bar UI, Codex data collection, Automatic Reset, notifications, sync, and system-power orchestration |
+| `CodexBarHelper` | A root LaunchDaemon that handles fixed system-sleep controls and Automatic Reset wake schedules |
+
+The targets share their XPC protocol through [`CodexBarHelperXPC.swift`](../../../Shared/CodexBarHelperXPC.swift).
+
+The app uses Sparkle for update checks. The project enables `MainActor` isolation by default, and Debug and Release use different app and CodexBarHelper bundle IDs.
+
+## Process and Trust Boundaries
+
+```text
+Codex
+ | launches a --hook-event subprocess and passes the event through stdin
+ v
+CodexBar executable
+ |-- Hook mode: minimal parsing + flock + JSONL append + exit
+ |
+ `-- Normal mode
+ |-- stdio JSON-RPC <-> codex app-server (account, rate limits, Reset Credits)
+ |-- local read-only <-> Hook JSONL / rollout JSONL
+ |-- HTTPS <-> Sparkle
+ |-- CloudKit private database <-> daily aggregations
+ `-- signed XPC lease / wake date <-> root CodexBarHelper
+ |-- fixed pmset commands
+ `-- fixed IOPM wake event
+```
+
+Two points define these boundaries:
+
+- Using the same executable for Hook mode keeps the handler pointed at the current app version without deploying a separate capture tool
+- The root helper knows nothing about Codex tasks, accounts, or reset credits; it receives only signature-validated sleep leases and Automatic Reset wake times
+
+### Process Lifecycle Differences
+
+| Process | Lifetime | May do | Must not do |
+| --- | --- | --- | --- |
+| Hook subprocess | One event, at most a few seconds | Read stdin, extract minimal fields, append local JSONL | Initialize UI, open network connections, or wait for long-running services |
+| Main app | Long-running within the user login session | Orchestrate UI, data flows, and side effects | Change system settings directly as root |
+| app-server | Reused for up to 1 hour | Expose account and configuration capabilities through JSON-RPC | Substitute for Hook history or live task state |
+| CodexBarHelper | LaunchDaemon | Run fixed `pmset` operations, manage a `wake` event for a fixed owner, and restore system state | Access accounts, Hook data, rollout files, the network, or arbitrary commands |
+
+## Directory Responsibilities
+
+```text
+CodexBar/
+ App/ App entry points
+ Controllers/ AppKit window, menu bar, and panel controllers
+ Models/ DTOs, state snapshots, and presentation models
+ Services/ Data access, state machines, settings, notifications, and system services
+ Views/ SwiftUI views
+ Resources/ Info.plist, entitlements, localization, and sounds
+CodexBarHelper/ root LaunchDaemon
+Shared/ Cross-target XPC interface
+Config/ Version configuration
+Scripts/ Build, DMG, appcast, and CodexBarHelper cleanup scripts
+```
+
+## Startup Order
+
+The initialization order in [`CodexBarApp.swift`](../../../CodexBar/App/CodexBarApp.swift) is an architectural constraint, not an implementation detail:
+
+```text
+Process starts
+ -> WorkflowHookEventRecorder.handleIfRequested()
+ -> in --hook-event mode, read stdin, write JSONL, and exit immediately
+ -> in normal mode, continue
+ -> Create CodexBarAppDelegate
+ -> AppDelegate assembles long-lived services
+ -> Create the menu bar and auxiliary windows
+ -> Start refresh, activity monitoring, Automatic Reset, notifications, and power coordination
+```
+
+`--hook-event` is the short-lived subprocess mode invoked by Codex. It must finish before any UI, CloudKit, notification, or long-lived service is initialized. Capture failure must not block the main Codex workflow.
+
+In normal mode, `CodexBarAppDelegate` creates and owns long-lived objects, including:
+
+- `CodexStatusService` and `CodexStatusViewModel`
+- `WorkflowService` and its view model
+- `CodexHookSettings`
+- `CodexActivityMonitor`
+- `KeepAliveController`
+- `AutoResetController`
+- `WorkflowSyncSettings` and the sync scheduler
+- `CodexNotificationService`
+- Menu bar, shortcut, Settings-window, and update services
+
+Before quitting, the app must cancel the Automatic Reset wake schedule and release sleep prevention. If CodexBarHelper has not confirmed that both categories of system state were restored, termination waits or is canceled. Before accepting a new connection at startup, the helper also removes stale wake events for its fixed owner, converging state left by sudden power loss or forced termination.
+
+### Why Hook Detection Must Run in `App.init`
+
+`@NSApplicationDelegateAdaptor` connects the AppKit lifecycle to the SwiftUI app. Once the normal lifecycle begins, it may create menu bar objects, register a notification delegate, or access CloudKit.
+
+The Hook handler runs on Codex's critical path and must behave like a command-line tool. `WorkflowHookEventRecorder.handleIfRequested()` therefore runs at the very beginning of `CodexBarApp.init()` and calls `exit(EXIT_SUCCESS)` immediately when Hook mode matches.
+
+This order also prevents Hook capture failures from contaminating normal-exit diagnostics. `AppProcessDiagnostics.install()` runs only in `applicationDidFinishLaunching`, so a Hook subprocess is not misclassified as a complete app that exited abnormally.
+
+### Why AppDelegate Owns Long-Lived Objects
+
+SwiftUI may recreate views because of layout, conditional branches, or window reconstruction. If a view owned a service, an ordinary UI change could terminate a reader, app-server, or XPC connection.
+
+`CodexBarAppDelegate` therefore acts as the composition root:
+
+- It is the only place that creates long-lived services, settings, and view models
+- It wires callbacks among monitoring, notifications, and keep-alive coordination
+- Views receive references that already exist
+- Shutdown stops services in reverse order from the same owner
+
+This does not place all logic in AppDelegate. It owns assembly and lifecycle only; business rules remain in their services or controllers.
+
+### Why Termination Can Be Canceled
+
+`applicationShouldTerminate` first calls `KeepAliveController.prepareForTermination()` and returns `.terminateLater`.
+
+The app allows termination only after the helper explicitly confirms that the Automatic Reset wake event was canceled and the sleep-prevention release completed. If either cleanup fails, that termination attempt is canceled and the controller returns to normal coordination under the current settings.
+
+Releasing asynchronously in `applicationWillTerminate` is too late because that callback cannot reliably extend process lifetime.
+
+## Three Independent Data Flows
+
+CodexBar does not use a single aggregation service for all state. The three flows have different inputs, freshness needs, and failure semantics:
+
+| Flow | Input | Output | Main consumers |
+| --- | --- | --- | --- |
+| app-server | `codex app-server` JSON-RPC | Account, rate limits, token usage, Reset Credit use, Hook configuration capabilities | Main panel, menu bar rate limit, Settings, Automatic Reset state machine |
+| Hook history | Hook JSONL | Daily event, session, turn, tool, and model aggregations | Activity heatmap, historical metrics, CloudKit |
+| Live tasks | Incremental Hook events plus rollout lifecycle | Running, waiting for approval, completed, terminated | Menu bar status, Task Center, notifications, sleep prevention |
+
+The flows may share infrastructure and models, but they cannot replace one another:
+
+- app-server does not provide complete live task state
+- Historical aggregation may be delayed or rebuilt; live tasks cannot wait for aggregation
+- Live task snapshots cannot be a persistent source for historical metrics
+- If one flow becomes unavailable, the others must remain available
+
+### Dependency Direction
+
+```text
+CodexStatusService ----------------> CodexStatusViewModel ----------------> UI
+CodexStatusViewModel --------------> CodexNotificationService
+CodexStatusService ----------------> AutoResetController
+CodexStatusViewModel --------------> AutoResetController
+AutoResetController ---------------> CodexNotificationService
+AutoResetController ---------------> KeepAliveController ---> AutoResetWakeScheduler ---> helper
+
+WorkflowService -------> WorkflowViewModel -----------> UI
+
+Hook + rollout --------> CodexActivityMonitor --------> UI
+ | |
+ | +------------> CodexNotificationService
+ `-----------------------> KeepAliveController --> helper
+```
+
+Arrows show the direction in which data or read-only state is consumed. A downstream component must not become an upstream source of truth.
+
+For example, the menu bar may draw rate-limit progress and task state in one icon, but whether that icon exists must not decide whether the task monitor runs. The sync scheduler may reuse a historical-maintenance trigger, but CloudKit availability must not decide whether local aggregation runs.
+
+### A Shared Trigger Is Not a Data Dependency
+
+Historical maintenance normally runs after the 60-second rate-limit refresh to reduce resident timers and log noise. The flows share scheduling, not facts.
+
+When changing refresh timing, distinguish among these constraints:
+
+- The trigger source may change
+- Maintenance must still be able to run independently when app-server fails
+- A lightweight statistics refresh when the UI opens must not implicitly start CloudKit network activity
+
+## Concurrency Boundaries
+
+The project uses Swift 6 strict concurrency with default `MainActor` isolation.
+
+### MainActor Objects
+
+- SwiftUI view models and settings
+- AppKit controllers
+- `CodexActivityMonitor`
+- `KeepAliveController`
+- `CodexNotificationService`
+- `AutoResetController`
+- `AutoResetWakeScheduler`
+
+These objects own observable state and UI coordination. They must not perform blocking I/O directly.
+
+### Actor Services
+
+- `CodexStatusService` manages app-server connections and refreshes
+- `WorkflowService` manages historical aggregation
+- `HookEventTailReader` manages Hook-file cursors
+- `CodexSessionLifecycleReader` manages rollout-file cursors
+- `WorkflowSyncService` manages CloudKit state
+- `ActivityProtectionStateStore` manages cross-process protection records
+
+DTOs crossing actor boundaries must be immutable value types and declare `Sendable` or `nonisolated` where appropriate.
+
+### Why the Monitor Still Runs on MainActor
+
+Actors read inputs for `CodexActivityMonitor`, but the state machine itself is closely connected to several Combine consumers.
+
+Keeping the monitor on `MainActor` provides:
+
+- Naturally serialized publication order for `@Published snapshot` and transitions
+- Identical state-commit order for notification and sleep-prevention consumers
+- Unified ordering of system sleep, wake, Hook-setting changes, and UI lifecycle
+
+The monitor must not perform blocking file reads directly. `HookEventTailReader`, `CodexSessionLifecycleReader`, and `ActivityProtectionStateStore` own those I/O boundaries.
+
+### Why the Nonisolated Pipe Reader Uses a Lock
+
+app-server communicates over stdio, requiring a combination of `FileHandle`, `DispatchSourceRead`, and semaphores. These types are not naturally `Sendable`, and crossing a Swift actor hop for every line is unsuitable.
+
+`PipeReadBuffer` confines the unsafe boundary to one `@unchecked Sendable` type. An `NSLock` protects all mutable state, read events stay on a dedicated queue, and the caller sees only complete lines and closed state.
+
+Here, `@unchecked` is a localized promise backed by encapsulation, not a way to disable concurrency checks for the whole module.
+
+### Why Cross-Process Files Need More Than an Actor
+
+The Hook recorder runs in another process, so the `WorkflowService` actor cannot protect it. `stats.lock` uses `flock` to provide a process-wide exclusive transaction over joint changes to event files and maintenance state.
+
+The same flow therefore uses both an actor and `flock`:
+
+- The actor prevents maintenance operations inside the main app from changing state concurrently
+- `flock` prevents the main app and short-lived Hook subprocesses from committing conflicting file changes at the same time
+
+## Model Layers
+
+The project does not reuse one large object directly across app-server DTOs, persistence, and views:
+
+| Model type | Role | Design requirement |
+| --- | --- | --- |
+| External DTO | Decode app-server, Hook, rollout, or CloudKit data | Tolerate version differences and carry no UI side effects |
+| Persistence model | Store recoverable state and schema | Remain compatible with old values and express missing semantics |
+| Domain snapshot | Express current trusted state to consumers | Immutable, comparable, and safe across actors |
+| Transition | Represent one live state change | Never inferred from historical snapshots; deduplicated upstream |
+| Presentation format | Dates, percentages, copy, and colors | Follow the locale and never feed back into business decisions |
+
+For example, `CodexQuotaSnapshot` can carry both a current value and a stale marker. `CodexActivitySnapshot` contains only task fields needed for presentation; raw session IDs do not enter views.
+
+## Lifecycles and Retention
+
+Different states have different lifetimes and cannot share one cache duration:
+
+| State | Lifetime | Reason |
+| --- | --- | --- |
+| app-server connection | Up to 1 hour | Reuse reduces startup cost; periodic reconstruction picks up on-disk upgrades |
+| app-server supplemental cache | Current account only | Prevents values from leaking across accounts |
+| Hook live bootstrap window | 24 hours | Covers long-running tasks that may still be active |
+| Completion highlight | 30 seconds | Short menu bar feedback |
+| Task Center terminal history | 10 minutes | Provides recent context without occupying the UI indefinitely |
+| Terminal deduplication memory | 24 hours | Prevents late Hook or rollout data from reviving old tasks |
+| Raw Hook data and daily aggregations | 210 days | Supports long-term metrics and rebuilding |
+| Daily-aggregation identity details | 3 days | Balances recent exact deduplication with privacy and file size |
+| Activity Protection records | 24 hours after the last progress | Preserves suppression across restarts while limiting identity retention |
+
+Before changing one time window, check for paired invariants. For example, the tail-reader bootstrap window must match the active-task retention window.
+
+## State Ownership
+
+Live task state has one authoritative source: [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift).
+
+Its snapshot is consumed by:
+
+- The menu bar icon and main-panel task card
+- Task Center
+- Completion and approval-request notifications
+- Sleep-prevention eligibility
+- Stalled Task Protection
+
+Consumers may present the snapshot or perform side effects from it, but must not rebuild separate task state machines.
+
+### State Ownership Table
+
+| State | Sole owner | Permissions of other modules |
+| --- | --- | --- |
+| app-server connection and same-account cache | `CodexStatusService` | Request read-only results |
+| Main-panel account loading state | `CodexStatusViewModel` | Observe published values |
+| Automatic Reset target, deadline, and retries | `AutoResetController` | Settings changes only the switch and lead time |
+| Automatic Reset wake-time synchronization | `AutoResetWakeScheduler` | `AutoResetController` submits only the next time; `KeepAliveController` submits only helper readiness |
+| Hook installation and validation | `CodexHookSettings` | Read `isOperable` |
+| Historical aggregation and maintenance cursor | `WorkflowService` | Request snapshots or rebuilds |
+| Live tasks | `CodexActivityMonitor` | Read snapshots or transitions |
+| Sync cursors and remote cache | `WorkflowSyncService` | Request merged snapshots |
+| Sleep-prevention policy and app assertion | `KeepAliveController` | Read derived state or invoke settings entry points |
+| Root sleep ownership | `CodexBarHelper` | Request and query through XPC |
+| Root Automatic Reset wake event | `CodexBarHelper` | Replace or cancel one `wake` event for the fixed owner through XPC |
+| Notification deduplication | `CodexNotificationService` | Upstream publishes candidate events only |
+
+When adding a consumer, subscribe to an existing snapshot first. If it lacks a field, extend the stable value type at the state owner instead of making the consumer reread raw files.
+
+## Error and Degradation Principles
+
+- On transient network or RPC failure, prefer the last explainable state
+- Explicitly represent an unavailable data source; do not disguise it as empty data
+- Bootstrap establishes a baseline without sending notifications for historical transitions
+- When a reader or data-source generation changes, discard results from the old generation
+- Recovery must complete a new read barrier before evaluation continues
+- Persistent writes require atomic replacement or file locking to avoid corruption from concurrent Debug and Release processes
+
+### Error Classification Matters More Than Uniform Retries
+
+| Error class | Typical handling | Incorrect handling |
+| --- | --- | --- |
+| Explicitly unsupported capability | Cache method unsupported and show the source as unavailable | Retry every minute or display `0` |
+| Transient business failure | Use stale cache scoped to the same account | Clear the entire account snapshot |
+| Transport failure | Discard the connection and rebuild it at most once | Continue sending requests over an untrusted pipe |
+| Data-source identity change | Start a new generation and rebuild from the raw source | Continue appending from the old offset |
+| Late asynchronous result | Discard when generations differ | Overwrite new settings or new reader state |
+| Uncertain privileged state | Retain the possible lease or wake event and actively confirm cleanup | Assume the helper did nothing |
+| Hook recorder failure | Drop this capture and exit successfully | Block Codex or present UI |
+
+### Why Logs Record Stages Instead of User Data
+
+System logs explain control flow with `trigger`, `stage`, `reason`, `counts`, and `elapsed`, without recording rate-limit values, project paths, or task identities.
+
+This structure can distinguish whether:
+
+- Sync failed during zone, device, fetch, upload, or prune
+- app-server created or reused a connection
+- Aggregation was a no-op, incremental write, or dirty rebuild
+- A particular condition blocked sleep prevention
+
+Diagnostics need control-flow evidence, not copies of user data.
+
+## Where to Make a Core-Flow Change
+
+### Adding a Data Source
+
+1. Decide whether it belongs to one of the existing three flows
+2. Define source-missing, stale, and failure semantics
+3. Perform I/O and caching inside an actor service
+4. Cross into MainActor through an immutable snapshot
+5. Review network and privacy boundaries separately
+
+### Adding a One-Time Side Effect
+
+1. Find a live transition that proves the event just occurred
+2. Do not infer it from a current snapshot or historical list
+3. Define in-process and cross-restart deduplication scopes
+4. Check immediately before submission that the event is still relevant
+5. Define whether side-effect failure may affect primary state
+
+### Adding Persistent State
+
+1. Explain why in-memory state is insufficient
+2. Define the schema, atomicity, and concurrent-access boundary
+3. Define how old versions read new files and new versions read old files
+4. Limit stored fields and retention
+5. Confirm the compatibility strategy before changing the format
+
+## System Integration
+
+| Capability | System interface |
+| --- | --- |
+| Menu bar | `NSStatusItem` |
+| Main panel | `NSPopover` and a floating fallback panel |
+| Global shortcut | Carbon Hot Key API |
+| App idle-sleep prevention | IOKit power assertion |
+| System-sleep control | CodexBarHelper invokes `/usr/bin/pmset` with fixed arguments |
+| Automatic Reset system wake | CodexBarHelper calls `IOPMSchedulePowerEvent` and `IOPMCancelScheduledPowerEvent` |
+| CodexBarHelper installation and launch | `SMAppService` |
+| App-to-CodexBarHelper communication | XPC |
+| Notifications | `UNUserNotificationCenter` |
+| Cloud sync | CloudKit private database |
+| Automatic updates | Sparkle |
+
+## Key Source Files
+
+- [`CodexBarApp.swift`](../../../CodexBar/App/CodexBarApp.swift) defines the startup entry point
+- [`CodexBarAppDelegate.swift`](../../../CodexBar/Controllers/CodexBarAppDelegate.swift) assembles services in normal mode
+- [`StatusItemController.swift`](../../../CodexBar/Controllers/StatusItemController.swift) orchestrates the menu bar
+- [`CodexStatusService.swift`](../../../CodexBar/Services/CodexStatus/CodexStatusService.swift) manages app-server
+- [`WorkflowService.swift`](../../../CodexBar/Services/Workflow/WorkflowService.swift) manages historical Hook aggregation
+- [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift) manages live tasks
+- [`AutoResetController.swift`](../../../CodexBar/Services/CodexStatus/AutoResetController.swift) manages Automatic Reset targets and retries
+- [`AutoResetWakeScheduler.swift`](../../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift) synchronizes the next system wake time
+- [`KeepAliveController.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveController.swift) manages helper registration, sleep-prevention policy, and wake-scheduler readiness
+- [`WorkflowSyncService.swift`](../../../CodexBar/Services/Workflow/WorkflowSyncService.swift) manages CloudKit sync
+- [`CodexBarHelperXPC.swift`](../../../Shared/CodexBarHelperXPC.swift) defines the constrained privileged interface
+- [`CodexBarHelper/main.swift`](../../../CodexBarHelper/main.swift) executes and validates system sleep and wake operations
diff --git a/Docs/en/DeveloperGuide/data-and-privacy.md b/Docs/en/DeveloperGuide/data-and-privacy.md
new file mode 100644
index 0000000..2ead95d
--- /dev/null
+++ b/Docs/en/DeveloperGuide/data-and-privacy.md
@@ -0,0 +1,332 @@
+# Data and Privacy Boundaries
+
+[简体中文](../../DeveloperGuide/data-and-privacy.md) | English
+
+## Principles
+
+CodexBar reads only the data required for account display, Automatic Reset, Hook metrics, live tasks, and sleep prevention:
+
+- Do not upload raw data when it can remain local
+- Store aggregates instead of content when possible
+- Store hashed identities instead of raw identities when possible
+- Mark missing data explicitly when a source is unavailable
+
+Privacy boundaries are architectural constraints on every data flow, not a static blacklist of fields. Even if a new field is technically easy to read, first ask whether it is necessary to achieve a product goal.
+
+## Data Classification Model
+
+Classifying data during development helps determine its storage and propagation scope:
+
+| Class | Examples | Default handling |
+| --- | --- | --- |
+| Content | Prompts, responses, tool arguments, and output | Do not collect |
+| Identity and context | Session IDs, full paths, project names | Minimize use to necessary flows; redact or remove before upload |
+| Aggregated metrics | Daily event counts, model counts | May persist locally; upload only specified fields after explicit opt-in |
+
+“Stored only on this Mac” does not mean zero privacy cost. Local logs, crash reports, backups, and other processes on the same machine can expand exposure, so unnecessary data should be discarded at the parsing boundary.
+
+## Trust Boundaries
+
+```text
+Codex hook stdin / rollout / app-server
+ |
+ v
+ User-privileged CodexBar
+ | |
+ v v
+ CloudKit private DB Constrained XPC interface
+ |
+ v
+ root CodexBarHelper
+```
+
+These boundaries mean:
+
+- Codex input files and protocol data are external input; decode failure must not expand into arbitrary file access or command execution
+- CloudKit is a user-enabled remote boundary; even a private database may receive only the specified aggregate fields
+- The root helper is a privilege-escalation boundary whose capabilities must be narrower than the app's business capabilities
+- Debug and Release are separate app identities but intentionally share some local files, requiring process locks and compatible schemas
+
+## Minimize at the Capture Boundary
+
+Removing sensitive fields only during upload is insufficient because raw values may already have entered local JSONL, in-memory logs, or error messages.
+
+CodexBar narrows data in this order:
+
+1. The Hook recorder extracts only allowlisted structural fields from stdin
+2. The rollout reader uses minimal Codable structures that omit content
+3. The aggregator reduces older identity details to counts
+4. The sync model projects again into CloudKit-allowed fields
+5. Logging records only stages, classifications, and nonsensitive counts
+
+Every layer narrows the data shape, so adding a downstream field does not automatically expose all upstream source text.
+
+## Data-Flow Overview
+
+| Source | Use in CodexBar | Persisted? | Uploaded to CloudKit? |
+| --- | --- | --- | --- |
+| app-server account, rate limits, and Reset Credits | Main panel, notification decisions, and user-enabled Automatic Reset | Short-lived state only | No |
+| Structured Hook events | Historical aggregation and live tasks | Yes, up to 210 days | Daily aggregations only |
+| Rollout lifecycle | Terminal and progress reconciliation | Not persisted separately | No |
+| App settings | Feature switches and thresholds | UserDefaults | No |
+| Activity Protection | Stalled-task recovery | Hashed identity, up to 24 hours | No |
+| CodexBarHelper ownership | System-sleep recovery | Root-owned state file | No |
+| Automatic Reset wake schedule | Fixed owner, `wake` type, and next time | System power management | No |
+
+### Why the Three Business Flows Remain Independent
+
+app-server, Hook history, and live activity read different facts with different freshness and failure modes:
+
+- app-server failure must not erase local history
+- Hook aggregation maintenance failure must not freeze live tasks
+- Temporary rollout unavailability must not mark rate limits as erroneous
+- CloudKit failure must not block current-device aggregation
+
+Collapsing them into one “globally loaded” state would let a lower-sensitivity or lower-priority flow expand the data access and availability impact of another.
+
+## Local Reads
+
+### Codex app-server
+
+The app launches local `codex app-server --listen stdio://` to obtain account data, rate limits, token usage, Reset Credits details, and Codex configuration. After the user explicitly enables Automatic Reset, it also calls the Reset Credit redemption method through the same stdio session.
+
+CodexBar does not implement account sign-in. Whether app-server accesses OpenAI services follows normal Codex CLI authentication and protocol behavior.
+
+CodexBar communicates with the local process only over stdio and does not copy authentication material from app-server responses. The request log stores normalized complete request and response JSON only in current-process memory. It may contain account responses, opaque credit IDs, and idempotency keys and must not be treated as a redacted summary.
+
+### Hook Events
+
+The Hook subprocess extracts from stdin:
+
+- Time and event type
+- Working directory
+- Tool, model, and effort
+- Permission and reviewer
+- Session, turn, and agent identities
+
+It does not write prompt text, responses, tool arguments, or tool output to CodexBar Hook files.
+
+The working directory is used only to derive a project display name and live-task ownership. Raw Hook JSONL may still include `cwd`, making it sensitive local context subject to retention and file-permission limits. CloudKit uploads only derived project-name counts and only after explicit opt-in.
+
+### Rollout Files
+
+The live-activity reader accesses `$CODEX_HOME/sessions` and `$CODEX_HOME/archived_sessions`.
+
+It parses only structural fields such as lifecycle, time, turn context, progress, effort, and reviewer. It neither copies conversation text into CodexBar storage nor presents it in the UI.
+
+The rollout reader scans backward from file tails under a budget. This reduces I/O and limits how much unrelated historical content enters process memory. Parsing DTOs declare only required fields, and `JSONDecoder` ignores everything else.
+
+This is not complete privacy isolation from rollout files because the reader must still open them. A future full-text search or prompt display would be a new privacy capability, not a natural extension of the current reader.
+
+### Reset Credits Details
+
+`account/rateLimits/read` returns the Reset Credits count and optional details in the app-server response.
+
+- `availableCount` is authoritative for the available total
+- `credits == nil` means the server provides a count only
+- An empty details array means the server read details but returned no available credit
+- The details list may be truncated and its length must not overwrite the total count
+- The menu and expiration notifications use only `available` credits with a future `expiresAt`
+- Automatic Reset processes only `available + codexRateLimits + expiresAt` details explicitly listed in a fresh response
+- Opaque credit IDs and deterministic idempotency keys exist only in current-process memory, including app-server responses and cache, quota snapshots, the Automatic Reset state machine, and the in-memory request log; they are neither persisted nor uploaded
+- Automatic Reset notification deduplication keys in UserDefaults contain only a SHA-256 combination of the account and credit ID, never raw values
+
+A rate-limit response from stale cache may remain visible but cannot trigger a new expiration notification or redemption. Automatic Reset settings and scheduling state do not enter CloudKit; Macs converge only through deterministic idempotency keys at the server redemption interface.
+
+## Local Persistence
+
+### App User Directory
+
+```text
+~/Library/Application Support/CodexBar/
+ HookEvents/
+ events/YYYY-MM-DD.jsonl
+ daily.jsonl
+ maintenance.json
+ stats.lock
+ Sync/
+ ActivityProtection/
+ state.json
+```
+
+| Path | Contents | Lifetime |
+| --- | --- | --- |
+| `HookEvents/events` | Raw structured Hook events | 210 days |
+| `HookEvents/daily.jsonl` | Daily aggregations | 210 days |
+| `HookEvents/maintenance.json` | File cursors, generation, and maintenance state | Continuously updated |
+| `HookEvents/Sync` | CloudKit cache and cursor | While sync state remains valid |
+| `ActivityProtection/state.json` | Hashed task identities and timestamps | Up to 24 hours after the last progress |
+
+Daily aggregations for the latest 3 days may retain session and turn ID details for exact deduplication. Older data retains counts only.
+
+Three days of identity detail balances exact deduplication against long-term minimization:
+
+- Recent Hook files may still receive late or duplicate writes and require identity sets for correct merging
+- Distant history rarely changes, and retaining only totals substantially reduces long-term identity exposure
+- Counts cannot restore identities after compaction, so algorithm changes rebuild from raw JSONL still inside the 210-day retention period
+
+Raw events and daily aggregations share the same 210-day limit, preventing more sensitive raw data from remaining indefinitely after derived data is gone.
+
+Anonymous tasks do not create Stalled Task Protection identifiers and therefore never write to `ActivityProtection/state.json`.
+
+### UserDefaults
+
+UserDefaults stores:
+
+- Feature switches and options
+- Notification thresholds and sound names
+- Global shortcut
+- Menu bar display selection
+- Automatic Reset switch and lead time
+- Bounded notification deduplication keys
+- Runtime configuration such as the CodexBarHelper fingerprint
+
+Renaming a persistence key, changing its structure, or changing a default requires consideration of upgrades from older versions.
+
+UserDefaults is not schemaless. Renaming an existing key, changing an enum raw value, or changing the default for a missing value changes behavior for upgrading users. These are compatibility issues and require an agreed migration and degradation strategy first.
+
+### CodexBarHelper Directory
+
+```text
+/Library/Application Support/CodexBar/helper-state.json
+```
+
+The file stores only the recovery transaction describing whether CodexBarHelper owns `SleepDisabled`. It contains no Codex task, account, or Hook data.
+
+System power management stores the Automatic Reset wake schedule, which contains only a fixed CodexBar owner, `wake` type, and next time. The helper neither receives nor stores account data, `creditId`, idempotency keys, or network data.
+
+The directory and file are root-managed. See [Sleep Prevention System](sleep-prevention.md) for permissions and recovery.
+
+## In-Memory and System Logs
+
+The in-app [`RequestLog.swift`](../../../CodexBar/Services/CodexStatus/RequestLog.swift) is an in-memory ring buffer of at most 500 entries and disappears when the process exits.
+
+It diagnoses the app-server protocol. Even in memory, it must not contain OAuth tokens or Hook content.
+
+The 500-entry cap limits memory and rendering cost when the Logs window opens. It is not an audit log and cannot track problems across launches. Cross-launch diagnosis uses unified system logging under the same field boundaries.
+
+The unified logging subsystem is `app.zabrian.codexbar`, with a `.debug` suffix in Debug builds.
+
+System logs may contain only:
+
+- Operation stage and result
+- State classification
+- Nonsensitive counts
+- Errors that identify a module
+
+System logs must not contain:
+
+- OAuth tokens
+- Prompts, responses, or tool content
+- Session, turn, or agent IDs
+- Full project paths or sensitive project names
+- Account rate-limit or token-usage details
+
+## Network Access
+
+| Destination | Purpose | Trigger |
+| --- | --- | --- |
+| CloudKit private database | Sync daily Hook aggregations | User explicitly enables sync |
+| Sparkle appcast and update resources | Check for or install updates | Automatic check or manual user request |
+
+Account data, rate limits, token usage, Reset Credits details, and explicitly enabled Reset Credit redemption use local app-server stdio. CodexBar does not add a separate HTTP client for Automatic Reset.
+
+CodexBarHelper performs no network access.
+
+## CloudKit Boundary
+
+CloudKit uploads only daily aggregate fields:
+
+- Device pseudonym
+- Date and source generation
+- Hook event counts
+- Session and turn counts
+- Project display-name counts
+- Model counts
+- Update time
+
+CloudKit does not upload:
+
+- Raw Hook JSONL
+- Session, turn, or agent IDs
+- Full working directories
+- Prompts, responses, tool arguments, or output
+- Codex account, rate-limit, or token usage data
+- Reset Credits details, Automatic Reset settings, or redemption state
+- Access tokens
+- App request logs
+- Activity Protection state
+
+A project display name may derive from a directory name and still contain sensitive information. Sync must remain an explicit user choice.
+
+An HMAC device pseudonym reduces linkability of hardware identity but does not anonymize project names. A private database also does not mean that data remains on the device. Settings copy and developer documentation must therefore continue to explain synced content rather than enabling it by default simply because CloudKit belongs to the user's account.
+
+## Root Helper Data Isolation
+
+CodexBarHelper needs only four kinds of state:
+
+- Which verified client holds which lease generation
+- The currently measured `SleepDisabled` value
+- Whether CodexBar owns restoration responsibility
+- A bounded Unix timestamp for the Automatic Reset wake schedule and the current connection owner
+
+It does not need task IDs, project names, Hook paths, account state, `creditId`, or complete user settings. XPC carries only Boolean requests, client session ID, generation, update identifier, and a bounded Unix timestamp.
+
+This capability minimization means future network or data features in the regular app do not automatically reach the root process. Business services must not be linked into the helper merely to reuse file or network code.
+
+The helper ownership file is a crash-recovery transaction record, not a user preference. It must be root-owned, reject group- or world-writable directories, and use full sync plus atomic rename so a restart can decide whether restoration is required.
+
+## File Security
+
+- Hook subprocesses and the app aggregator coordinate writes with `flock`
+- JSONL appends complete lines only
+- Aggregation and state files use recoverable write workflows
+- Activity Protection files have `0600` permissions
+- CodexBarHelper state commits with root ownership, permission checks, full sync, and atomic rename
+- Data shared by Debug and Release uses locking and compatible schemas
+
+## Privacy Meaning of Missing, Stale, and Unavailable
+
+Do not hide unavailable data behind friendly-looking defaults:
+
+| State | Correct representation | Incorrect behavior |
+| --- | --- | --- |
+| Field missing from an older source | `nil` or unavailable | Decode as an explicit zero |
+| app-server cache expired | Stale snapshot | Continue triggering notifications |
+| Rollout reader unavailable | Pause live evaluation | Use old tasks to continue sleep prevention |
+| CloudKit offline | Preserve old cache with source attribution | Treat it as new data for the current account |
+| Battery read failed | Preserve prior decision and mark unreadable | Treat as no battery |
+
+Explicit degradation improves correctness and avoids reading extra fallback sources or storing additional data simply to fill the UI.
+
+## Checklist Before Adding a Data Field
+
+1. State the product goal and the behavior that is impossible without the field
+2. Classify it as credential, content, identity context, or aggregate metric
+3. Define its capture boundary and the earliest layer that can discard the raw value
+4. Define whether and where it exists in memory, UserDefaults, Application Support, system logs, and CloudKit
+5. Define retention, deletion triggers, and cleanup after failure
+6. Check whether Debug and Release share its file or identity
+7. Distinguish missing from explicitly empty values
+8. Check whether logs or error objects copy the raw value indirectly
+9. If it affects CloudKit, network access, or logs, update the privacy explanation and obtain an explicit product decision first
+10. If it affects a schema or old-version coexistence, agree on compatibility before changing code
+
+## Suggested Privacy-Failure Tests
+
+- Run a task with a conspicuous marker in the prompt and tool arguments; confirm the marker is absent from Hook JSONL, app logs, and CloudKit cache
+- Put a sensitive test term in a project directory name; confirm it appears only in allowed local presentation and opt-in aggregate fields
+- Simulate a failed Reset Credits request and confirm that access tokens do not enter the in-memory or unified logs
+- Confirm CloudKit records contain no session, turn, or agent IDs or full paths
+- As a non-root user, verify that the helper-state directory is not writable
+- Corrupt each cache type and confirm the system degrades or rebuilds rather than broadening fallback data collection
+
+## Key Source Files
+
+- [`WorkflowHookEventRecorder.swift`](../../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift)
+- [`WorkflowService.swift`](../../../CodexBar/Services/Workflow/WorkflowService.swift)
+- [`CodexSessionLifecycleReader.swift`](../../../CodexBar/Services/Workflow/CodexSessionLifecycleReader.swift)
+- [`WorkflowSyncService.swift`](../../../CodexBar/Services/Workflow/WorkflowSyncService.swift)
+- [`ActivityProtectionStateStore.swift`](../../../CodexBar/Services/Workflow/ActivityProtectionStateStore.swift)
+- [`RequestLog.swift`](../../../CodexBar/Services/CodexStatus/RequestLog.swift)
+- [`CodexBarHelper/main.swift`](../../../CodexBarHelper/main.swift)
diff --git a/Docs/en/DeveloperGuide/design-decisions.md b/Docs/en/DeveloperGuide/design-decisions.md
new file mode 100644
index 0000000..74fae4e
--- /dev/null
+++ b/Docs/en/DeveloperGuide/design-decisions.md
@@ -0,0 +1,317 @@
+# Design Principles and Key Decisions
+
+[简体中文](../../DeveloperGuide/design-decisions.md) | English
+
+This document explains why CodexBar has its current structure and which problems that structure solves.
+
+It is neither a source-tree index nor a feature list. Its purpose is to establish decision criteria: when implementation must change, which mechanisms are replaceable and which system invariants must remain true.
+
+## Deriving the Architecture from Product Goals
+
+CodexBar may look like a simple menu bar app, but it crosses four fundamentally different boundaries:
+
+- Codex's local protocol and configuration
+- Continuously changing Hook and rollout files
+- macOS windows, notifications, and power management
+- Root-privileged control of system sleep and scheduled wake
+
+These boundaries cannot share one failure strategy.
+
+For example, preserving the previous value is usually more useful than clearing it when a rate-limit refresh fails. A failed Hook capture must be abandoned immediately because statistics must never block Codex. A failed sleep-state release, however, must not be ignored during exit because CodexBar may still own system state.
+
+The project therefore avoids one global service that does everything. It separates components first by input source and failure semantics, then combines read-only snapshots at the UI and side-effect layers.
+
+## Decision Priorities
+
+Resolve implementation tradeoffs in this order:
+
+1. Do not block the Codex task the user is running
+2. Do not leave behind or incorrectly change system-level state
+3. Do not present old, missing, or uncertain data as a current fact
+4. Do not let a late asynchronous result overwrite newer user intent
+5. Do not broaden the boundaries of privileged processes, network access, or persisted data
+6. Only then optimize latency, file size, and UI animation
+
+This order explains several intentionally asymmetric behaviors:
+
+- A Hook recorder drops the current statistic after a lock timeout instead of waiting longer
+- App termination may be delayed until the helper confirms release of CodexBar-owned sleep state and cancellation of the Automatic Reset wake schedule
+- A failed supplemental app-server request may show stale cached data, but an unsupported method must show that the source is unavailable
+- Stalled Task Protection remains paused if wake recovery has not passed a new Hook read barrier
+
+## Facts, Snapshots, and Side Effects
+
+Project state has three layers:
+
+| Layer | Meaning | Examples |
+| --- | --- | --- |
+| Fact | An input that has occurred in an external system or local log | Hook event, rollout terminal, app-server response |
+| Snapshot | Displayable state derived from facts under current rules | `CodexQuotaSnapshot`, `WorkflowSnapshot`, `CodexActivitySnapshot` |
+| Side effect | A one-time action caused by a trusted state change | Notification, haptic feedback, XPC lease, CloudKit upload |
+
+Views intentionally do not execute side effects from raw facts.
+
+For example, the notification service does not scan Task Center and guess which task just completed; it consumes transitions published by the monitor. The sleep-prevention controller does not parse Hook data; it consumes running and waiting tasks in the activity snapshot.
+
+This has two benefits:
+
+- A snapshot may be read repeatedly, while a transition must be consumed at most once
+- One state machine handles bootstrap, deduplication, late events, and rollout reconciliation consistently, so consumers do not implement similar but divergent rules
+
+## Why the Three Data Flows Must Remain Independent
+
+### app-server Flow
+
+app-server provides periodic snapshots of account, rate-limit, and token usage data. Minute-level refreshes are appropriate, and transient failures may fall back to a same-account cache.
+
+### Historical Hook Flow
+
+The historical flow converts append-only raw events into daily aggregations. It may be delayed and rebuilt from raw JSONL; long-term consistency is its primary goal.
+
+### Live Task Flow
+
+The live flow tracks task states and one-time transitions on a seconds-level timescale. It combines Hook and rollout data, cannot wait for daily aggregation, and must not treat a terminal state from ten minutes ago as a new notification.
+
+Combining the three produces incorrect coupling:
+
+- A transient app-server failure would erase local task state that remains readable
+- An aggregation rebuild would block live task updates
+- Terminal deduplication designed for notifications would contaminate historical counts
+- CloudKit or network failures would affect local Hook presentation
+
+The UI may combine the flows, but they must never become sources of fact for one another. This is one of CodexBar's most important architectural boundaries.
+
+## User Intent, Dependency Availability, and Actual Effect
+
+Settings-driven features usually have three distinct states:
+
+```text
+User intent -> Dependency availability -> Actual effect
+```
+
+Sleep prevention is the clearest example:
+
+- `isEnabled` means the user allows CodexBar to manage sleep
+- Hook, helper, battery, and duration state determine whether execution is currently possible
+- `isPreventingSleep` means the app and helper have confirmed the actual effect
+
+A temporarily unavailable dependency must not write `false` back to `isEnabled`. Otherwise, one RPC failure would permanently change a user preference and prevent automatic recovery.
+
+Hook settings make a similar distinction:
+
+- `isEnabled` means the handler is installed in the configuration file
+- `isVerified` means app-server most recently returned an explicit usable result
+- `isOperable` is the state downstream dependencies should consume
+
+This three-layer model has more states than one Boolean but avoids merging configuration, diagnostics, and effect into an unexplained switch.
+
+## Uncertainty Must Appear in Types and UI
+
+Several parts of the project preserve `nil`, stale, or degraded state instead of converting everything to zero or an empty array.
+
+### Missing Is Not Zero
+
+When old Hook data lacks a count field, `nil` means the capture capability did not exist at that time. Only `0` means the source explicitly confirms that nothing occurred.
+
+Merging them would draw unknown history as real zeroes and make the interpretation impossible to repair later.
+
+### Stale Is Not Failure
+
+If a supplemental app-server method fails temporarily for the same account, old rate-limit or usage values remain useful. The snapshot marks them with `isRateLimitsStale` and `isUsageStale`; the UI uses opacity to show reduced confidence, while notifications skip stale rate limits entirely.
+
+### Degraded Bootstrap Is Not Idle
+
+If the live reader cannot obtain a stable file boundary, it moves to the end of the file while also publishing degraded state and an unhealthy data source. This means “existing tasks cannot be recovered reliably,” not “there are definitely no tasks.”
+
+## Why Generations Are Used Extensively
+
+Most CodexBar I/O shares this race:
+
+1. Request A begins
+2. The user changes a setting or the reader is replaced
+3. Request B begins and finishes first
+4. Request A returns last
+
+Canceling a `Task` is not enough. Some system APIs and synchronous bridges cannot truly cancel, so old callbacks may still arrive.
+
+Critical asynchronous paths therefore maintain monotonically increasing generations:
+
+- The refresh coordinator allows only the current generation to commit
+- Hook settings allow only the latest operation to update UI
+- Replacing a tail reader invalidates batches from the old reader
+- Wake recovery validates both reader and recovery generations
+- XPC lease requests use generations so a late acquire cannot overwrite a release
+- Helper-state requests and CloudKit availability checks also discard old results by generation
+
+The value of a generation is not easier cancellation. It turns permission to commit into an explicit, verifiable condition.
+
+## Why the Project Uses Actors, MainActor, and Locks
+
+Each mechanism covers a different boundary:
+
+| Mechanism | Scope | Typical objects |
+| --- | --- | --- |
+| `MainActor` | UI-observable state and AppKit lifecycle | Controllers, view models, settings, monitor |
+| Swift actor | Asynchronous mutable state within one process | app-server, aggregation, readers, CloudKit service |
+| `flock` | Transactions over files shared across processes | Hook recorder and main-app statistics files |
+
+An actor cannot protect another CodexBar Hook subprocess. `flock` is unsuitable for UI state. Choose the concurrency tool based on where contention occurs rather than forcing every synchronization problem into actors because the project already uses them.
+
+Default `MainActor` isolation makes UI types safer, but every blocking file or pipe wait must explicitly move off the main actor. `AppServerSession` and its pipe reader use locked nonisolated boundaries, while the higher-level `CodexStatusService` actor serializes connection management.
+
+## Why Raw Logs and Derived Caches Are Separate
+
+Raw Hook JSONL is an auditable fact source; `daily.jsonl` is a cache generated by the current algorithm.
+
+This structure provides three long-term benefits:
+
+- Historical data can be rebuilt after an aggregation fix without designing a migration for every old field
+- The write-critical path appends one line instead of reading and rewriting all statistics during the few seconds Codex is waiting
+- CloudKit sync can upload only aggregations, leaving raw identities and paths on the Mac
+
+The cost is explicit management of schemas, offsets, and source replacement. Maintenance state therefore stores `sourceGeneration`, inode, size, boundary hash, and dirty/pending state.
+
+## `sourceGeneration` Is Not a Version Number
+
+An event file for a given day may be replaced, truncated, or rebuilt by the user. The same date does not prove that it is the same fact source.
+
+`sourceGeneration` gives “which generation of raw file produced this day's data” a stable identity:
+
+- Normal appends preserve the generation
+- An inode change, file shrink, or rewrite before the consumed boundary creates a new generation
+- CloudKit record names can distinguish generations
+- The presentation layer adds clearly independent contributions and treats same-source results as replacements
+
+If date alone were the identity, a rebuilt value would be added to the old cloud value and create permanent double counting.
+
+## Why Live Tasks Read Both Hook and Rollout Data
+
+Each source solves only half of the problem:
+
+| Source | Strength | Gap |
+| --- | --- | --- |
+| Hook | Low latency, clear event types, suitable for live UI | `Stop` cannot always distinguish completion from interruption; some context fields may be missing |
+| rollout | More authoritative terminal, effort, and reviewer fields | Slower file discovery and parsing; unsuitable as the only low-latency signal |
+
+The monitor first establishes active state from Hook data, then fills in lifecycle details from rollout files. `Stop` creates a completion candidate. `SessionEnd` or a new prompt moves the task into a short terminal-confirmation window, and rollout provides accurate classification during the grace period.
+
+This is not a simple two-source merge. Conflicts require semantic authority rules, and late events must not revive a task that already completed.
+
+## Why the Privileged Helper Accepts Only Constrained Power Operations
+
+The app needs root privileges to change `pmset disablesleep` and schedule system `wake` events. Task identification, Automatic Reset policy, network access, and file parsing do not require root.
+
+Putting policy in the helper would greatly expand its attack surface and recovery scope. The current boundary keeps it a small executor:
+
+- Inputs are limited to sleep leases, generations, state queries, update-recovery markers, and bounded Unix wake timestamps
+- Sleep commands are fixed argument combinations for `/usr/bin/pmset`; wake schedules use a fixed CodexBar owner and `wake` type
+- Clients are validated through code-signing requirements
+- The helper does not read Codex files, access the network, or accept arbitrary paths or commands
+
+The app decides what should happen; the helper executes and verifies it with constrained privileges.
+
+## Why Leases Still Need Ownership Records
+
+A lease answers whether an active app still requests the effect. Ownership answers whether CodexBar changed the current system value.
+
+Neither can replace the other:
+
+- When no lease remains, the helper should revoke its own effect
+- If `SleepDisabled=1` was originally set by the user or another app, CodexBar has no right to restore it to `0`
+- If CodexBar completed `0 -> 1`, the helper must persist owned state first so it can recover after a crash
+
+The release condition is therefore “the last lease ended and ownership is owned,” not simply “there are no clients, so write `0`.”
+
+## Why CloudKit Syncs Aggregations Instead of Raw Events
+
+Cross-device presentation needs only daily metrics. Uploading raw events would expose more identity data, increase volume, and complicate deduplication without enabling a current product capability.
+
+Benefits of syncing aggregations include:
+
+- Session, turn, and agent IDs remain local
+- Network and CloudKit operations scale with days rather than events
+- Each Mac can still rebuild independently, while the cloud stores only per-device contributions
+- Cross-device merge rules can be defined around `deviceId + date + sourceGeneration`
+
+Project display names may still be sensitive, so sync must be explicitly enabled. Signing in to iCloud must never upload them by default.
+
+## Subtle but Important Details
+
+### `@Published` Callback Arguments Are More Reliable Than Immediate Reads
+
+Combine publishes during `willSet`. When a subscriber closure runs, the property itself may still contain the old value.
+
+Subscriptions for Hook availability, sync activation, and sleep-prevention dependencies therefore calculate from closure arguments instead of immediately reading the object property again. This explains several seemingly redundant state mirrors.
+
+### The Boundary Hash Covers Only the Consumed Tail
+
+Historical aggregation does not hash every file in full on every cycle. It stores a boundary hash for the 4 KB before the offset and uses mtime to decide whether to recompute it.
+
+Normal appends occur after the offset and do not change this boundary. This detects in-place rewrites of consumed content without holding `stats.lock` for long, letting Hook subprocesses persist events quickly.
+
+### State Sorting Uses UUID as a Tie-Breaker
+
+Several tasks may share a timestamp, and Swift sorting is unstable. Snapshots break timestamp ties with the UUID string so SwiftUI diffing does not repeatedly refresh because of meaningless order changes.
+
+### Notifications Recheck Relevance Before Submission
+
+An asynchronous window exists between deciding to notify about an approval request or stalled task and the system actually accepting it. The task may already have resumed.
+
+Before every submission or retry, the notification service calls `isStillRelevant`. If it is false, pending and delivered notifications are withdrawn. This is more reliable than attempting removal only when state changes.
+
+### An XPC Timeout Cannot Clear a “Possible Lease”
+
+A timeout proves only that the reply did not arrive; it does not prove that the helper failed to acquire the lease. `mayHaveHelperLease` therefore remains true until an explicitly successful release.
+
+Clearing it on timeout could make app termination skip release and leave the helper waiting for its watchdog before restoring system state.
+
+### External Sleep Sources Need Continuous Observation
+
+If the system already has `SleepDisabled=1` when a task starts, the helper marks the source external. That source may remove its setting while the task is still running.
+
+The helper periodically reads the actual value. If the external effect disappears while a lease remains valid, CodexBar can safely perform its own `0 -> 1` transition, take ownership, and keep sleep prevention from silently ending.
+
+### Menu Bar Anchors Must Be Validated
+
+When a global shortcut fires, the `NSStatusBarButton` may temporarily lack a valid window or be on another display. Showing a popover directly may position it incorrectly or not display it at all.
+
+The controller first validates the anchor size and screen intersection. If it is untrusted, it uses a fallback panel on the screen under the pointer. Both containers share the same SwiftUI content, so the business layer does not need to know which one is active.
+
+### Schedule Only the Nearest Real Deadline
+
+Task expiration, completion highlighting, terminal grace, and stalled-task silence are not scanned by a high-frequency UI timer. The monitor gathers all deadlines, creates one `Task` for the nearest, then recalculates and schedules the next deadline when it fires.
+
+This reduces meaningless wakeups while the menu bar app is resident and gives every retention period an explicit source in code.
+
+## How to Review a Design Change
+
+Before adding a feature or changing core semantics, answer these questions in order:
+
+1. Which flow supplies the new data, and what is its authoritative source?
+2. Are missing data, old values, explicit zeroes, and failures distinct?
+3. Is this repeatable state or a transition that may execute at most once?
+4. When an asynchronous result returns, how does it prove that it still belongs to the current generation?
+5. Does the change broaden network, persistence, CloudKit, or root-helper boundaries?
+6. Does it affect old UserDefaults, local schemas, CloudKit records, or Debug and Release coexistence?
+7. How does it recover from crashes, forced exits, system sleep, and file replacement?
+8. Which logs distinguish expected degradation from real failure without exposing user data?
+9. Which manual scenarios validate design invariants, not only the ideal path?
+
+If any answer remains unclear, the implementation does not yet have a complete lifecycle design.
+
+## Invariants That Should Not Change Lightly
+
+- Hook subprocess failure must not block Codex
+- The three data flows remain independent
+- `CodexActivityMonitor` is the sole source of live task state
+- Bootstrap does not publish historical transitions
+- `drainNow()` guarantees a new read barrier after the request
+- Missing count fields are not interpreted as `0`
+- Raw events are the rebuild source for aggregation caches
+- Changes to aggregation semantics increment the schema and trigger a full rebuild
+- The root helper gains no network access, arbitrary command execution, or additional file-read capability
+- CodexBar may restore only sleep state it acquired itself
+- Automatic Reset replaces or cancels only the `wake` event for CodexBar's fixed owner; it does not change other scheduled events
+- Notifications that describe a system effect are sent only after the effect is confirmed
+- Anonymous tasks do not participate in notifications, sleep prevention, or Stalled Task Protection
+- Compatibility changes require a migration and degradation strategy before implementation
diff --git a/Docs/en/DeveloperGuide/development.md b/Docs/en/DeveloperGuide/development.md
new file mode 100644
index 0000000..b0c772e
--- /dev/null
+++ b/Docs/en/DeveloperGuide/development.md
@@ -0,0 +1,495 @@
+# Development and Validation
+
+[简体中文](../../DeveloperGuide/development.md) | English
+
+## Requirements
+
+- macOS 15 or later
+- Xcode and the macOS SDK
+- Swift 6 toolchain
+- `swiftformat`
+- `swiftlint`
+- A working local Codex CLI or an app with bundled Codex
+
+The project uses the `CodexBar` scheme. Routine builds do not require a Developer ID or notarization credentials.
+
+## Project Structure
+
+| Directory | Responsibility |
+| --- | --- |
+| `CodexBar/App` | App startup entry points |
+| `CodexBar/Controllers` | AppKit lifecycle, menu bar, and window control |
+| `CodexBar/Models` | Business DTOs, snapshots, and presentation models |
+| `CodexBar/Services` | app-server, Hook, task, sync, notification, and system services |
+| `CodexBar/Views` | SwiftUI interface |
+| `CodexBar/Resources` | Plists, entitlements, localization, and resources |
+| `CodexBarHelper` | Root LaunchDaemon |
+| `Shared` | Shared XPC interface |
+| `Config` | Version configuration |
+| `Scripts` | Release and maintenance scripts |
+
+## Recommended Order for Reading the Code
+
+Do not infer business state backward from a view. Follow the facts:
+
+1. Start in [`CodexBarApp.swift`](../../../CodexBar/App/CodexBarApp.swift) to see Hook subprocess branching
+2. Read [`CodexBarAppDelegate.swift`](../../../CodexBar/Controllers/CodexBarAppDelegate.swift) for the normal-mode composition root
+3. Read [`StatusItemController.swift`](../../../CodexBar/Controllers/StatusItemController.swift) for menu bar and window orchestration
+4. Choose one flow and follow its source, service, snapshot, and view model
+5. Then see how notifications or sleep prevention subscribe to upstream results
+6. Finally, inspect how SwiftUI presents state and reports user intent
+
+For live tasks:
+
+```text
+WorkflowHookEventRecorder
+ -> HookEventTailReader
+ -> CodexActivityMonitor
+ -> CodexActivitySnapshot / CodexActivityTransition
+ -> StatusItemController assembly
+ -> UI
+ -> CodexNotificationService
+ -> KeepAliveController
+```
+
+Finding authoritative state first prevents mistaking a UI cache, notification deduplication set, or controller intermediate state for a business fact.
+
+## Define Five Things Before a Change
+
+Before implementing anything beyond a purely visual change, answer at least these questions in design or development notes:
+
+| Question | Example |
+| --- | --- |
+| Target fact | “The task is waiting for user approval,” not “show an orange dot” |
+| Authoritative source | Hook event after reviewer confirmation |
+| Derived consumers | Activity card, notifications, sleep prevention |
+| Failure semantics | Pause evaluation while the reader is unavailable |
+| Acceptance evidence | One transition, no bootstrap replay, reconciliation after recovery |
+
+This step is not process for its own sake. It reveals when three side-effect consumers have assigned different meanings to one field.
+
+## Where Common Changes Belong
+
+| Change | Preferred location | Avoid |
+| --- | --- | --- |
+| app-server protocol method | `CodexStatus/` service and DTO | SwiftUI view |
+| Raw Hook field | Recorder model and aggregation projection | Reading stdin directly into a CloudKit record |
+| Live task transition | `CodexActivityMonitor` | Notification service inferring from history |
+| Daily metrics presentation | `WorkflowViewModel` projection | View remerging raw events |
+| System notification | `CodexNotificationService` | Button action or view lifecycle |
+| Sleep-prevention condition | `KeepAliveController.sleepBlockReason` | Several UI computed properties |
+| Window behavior | AppKit controller | Service or model |
+| User default | Corresponding settings type | Scattered `UserDefaults.standard` calls |
+
+Prefer extending an existing responsibility for a small change. Create a service only when a capability has its own lifecycle, state ownership, or failure boundary.
+
+## Routine Checks
+
+### Build
+
+```bash
+xcodebuild \
+ -project CodexBar.xcodeproj \
+ -scheme CodexBar \
+ -destination 'generic/platform=macOS' \
+ build
+```
+
+### Format
+
+```bash
+swiftformat .
+```
+
+The project uses Swift 6 and four-space indentation configured in `.swiftformat`.
+
+### Static Analysis
+
+```bash
+swiftlint
+```
+
+Rules are in `.swiftlint.yml`.
+
+The repository currently has no XCTest target or coverage gate. Build, formatting, and lint do not replace manual validation of affected workflows.
+
+### Recommended Check Order
+
+```text
+Inspect worktree scope
+ -> Complete the smallest implementation
+ -> swiftformat
+ -> Review formatting diff
+ -> swiftlint
+ -> xcodebuild
+ -> Targeted manual validation
+ -> git diff --check
+```
+
+Formatting before build ensures final validation covers the actual code intended for submission. If the repository already contains uncommitted user changes, do not format everything indiscriminately. Check scope first with `git status --short` and `git diff --name-only`, and format only touched Swift files when necessary.
+
+`xcodebuild` checks Swift 6 concurrency, target membership, entitlements, and resource references. `swiftlint` checks style and some static rules. Neither validates AppKit focus, XPC crash recovery, or notification relevance.
+
+Even documentation-only changes follow the repository convention of formatting, linting, and building. Those checks do not validate documentation, so also check Markdown relative links, `git diff --check`, and the repository's Chinese-punctuation rules.
+
+### Reading Build Failures
+
+Find the first real `error:` rather than the final `BUILD FAILED`.
+
+- An actor-isolation error usually indicates unclear state ownership; do not first suppress it with `nonisolated(unsafe)`
+- For a missing file or resource, check target membership and Xcode project references
+- A helper protocol error requires checking the app target, helper target, and `Shared` interface together
+- For entitlement or signing errors, confirm whether the current identity is Debug or Release
+
+Fix the first root cause and rebuild. Many later generic or module errors are cascading failures.
+
+## Logging
+
+View Release system logs with:
+
+```bash
+/usr/bin/log stream \
+ --predicate 'subsystem == "app.zabrian.codexbar"' \
+ --style compact
+```
+
+The Debug subsystem has a `.debug` suffix.
+
+The in-app Logs window shows the latest 500 app-server interactions in the current process and helps diagnose CLI discovery, handshake, method unsupported, and retries.
+
+### What a Log Should Answer
+
+A useful state-machine log should identify:
+
+- What triggered the operation
+- Which state it intended to reach
+- Which stage failed
+- Which degradation or retry action followed
+- Duration and processing scale
+
+The repository uses `LogTrigger`, `LogDuration`, and `LogFields.joined` for consistent fields. High-frequency polling logs only state transitions or result changes so no-op messages do not obscure real faults.
+
+Prefer stable English keys with controlled values, for example:
+
+```text
+trigger=wake want=0 reason=lowBattery elapsed=0.183s
+```
+
+Do not log notification bodies, full paths, identities, or tokens. If an error's `localizedDescription` may contain sensitive request data, classify the error before logging it.
+
+### Troubleshooting by Subsystem and Stage
+
+| Symptom | First logs and state to inspect |
+| --- | --- |
+| Rate limits do not refresh | app-server handshake, method, retry, stale |
+| Hook has no metrics | Hook configuration, recorder timeout, maintenance counts |
+| Live task is stuck | Tail-reader generation, rollout reconciliation, data-source availability |
+| Sync data is missing | Sync stage, local and confirmed counts, replacement dates |
+| Notification does not appear | Authorization, kind, duplicate, or obsolete |
+| Sleep prevention does not engage | Block reason, helper registration, XPC generation, source |
+| Automatic Reset did not run | Target, threshold, retry window, helper registration, wake schedule |
+
+## Debug and Release
+
+The configurations use separate identities:
+
+| Configuration | App bundle ID | CodexBarHelper bundle ID |
+| --- | --- | --- |
+| Release | `app.zabrian.codexbar` | `app.zabrian.codexbar.helper` |
+| Debug | `app.zabrian.codexbar.debug` | `app.zabrian.codexbar.debug.helper` |
+
+Do not mix configurations while diagnosing CodexBarHelper installation, LaunchDaemon state, or system approval.
+
+The Hook handler binds to the current app executable path. When switching between Debug and Release, confirm that the installed handler points to the intended build.
+
+### Why the Builds Still Share Some State
+
+Separating bundle IDs prevents app, helper registration, and system approval from overwriting one another. Raw Hook data and Activity Protection must observe the same Codex work facts, however, and deliberately share files.
+
+Shared state means:
+
+- Writes require `flock`; actors protect only one process
+- Schemas must remain interpretable while two versions coexist
+- A changed identity-hash algorithm affects both builds
+- Diagnosis must record which app writes and which helper controls the system
+
+Do not temporarily isolate Debug by renaming its directory. That changes the product definition of its data source and hides real coexistence problems.
+
+## Architecture Rules
+
+### Startup Entry
+
+`WorkflowHookEventRecorder.handleIfRequested()` must be the first work in app initialization.
+
+`--hook-event` mode reads stdin, writes JSONL under a lock, and exits immediately. It initializes no UI, notifications, CloudKit, or long-lived services.
+
+### MainActor
+
+UI, controllers, view models, and settings use default isolation. Blocking file, subprocess, and network I/O belongs in actors or asynchronous services.
+
+Shared mutable state belongs in an actor. Add concurrency declarations to DTOs and cross-actor value types where needed rather than disabling Swift 6 checks.
+
+#### MainActor Is Not an I/O Queue
+
+Default isolation clarifies UI state mutation; it does not permit synchronous file and subprocess work on the main thread.
+
+Use this pattern:
+
+```text
+MainActor captures immutable input
+ -> Actor or async API performs I/O
+ -> Return a Sendable result
+ -> MainActor validates generation
+ -> Commit snapshot
+```
+
+Do not pass a mutable controller or non-Sendable AppKit object into a background closure. A cross-actor DTO should generally be a small value type. Use `nonisolated` to express that the type itself does not depend on an actor, not to bypass one access error.
+
+#### Actors and `flock` Solve Different Problems
+
+- An actor serializes tasks within one process
+- `flock` coordinates the app, Hook subprocesses, Debug, Release, and other processes
+
+An actor-safe read-modify-write can still be interrupted by another process. Conversely, `flock` alone does not protect in-memory state across actor reentrancy before and after `await`.
+
+#### `@Published` Uses `willSet`
+
+When a Combine sink receives a new value, the property on its publisher may still be old. For decisions based on the combined post-change state:
+
+- Use the sink argument for the changing value
+- Read other unchanged dependencies from the object
+- Or publish one snapshot containing the complete new state
+
+Sync activation and low-rate-limit threshold reevaluation depend on this rule. Replacing callback arguments with immediate property reads creates a one-frame inverted decision.
+
+### Data Flows
+
+Keep these flows independent:
+
+- app-server account, rate limits, and usage
+- Historical Hook aggregation
+- Live tasks from `CodexActivityMonitor`
+
+New UI may combine snapshots from all three, but one flow must not become an implicit prerequisite of another.
+
+Combination belongs only in presentation or explicit business policy. A menu bar icon may show both a rate-limit bar and activity dot, but app-server failure must not stop activity monitoring, and Hook maintenance must not wait for CloudKit before publishing local metrics.
+
+Write a truth table for any new cross-flow behavior. Sleep prevention is a legitimate example: it explicitly requires an operational Hook and a non-anonymous live task rather than acquiring the dependency simply because both objects happen to share a controller.
+
+### Hook
+
+- Preserve existing user and third-party configuration when changing handlers
+- Enabling and validation require actual app-server version `0.145.0` or later
+- Hook subprocess failure must not block Codex
+- `SessionEnd` times out after 3 seconds; other events after 5 seconds
+- `drainNow()` must preserve read-barrier semantics
+- An unavailable source must not reuse an old snapshot for evaluation
+
+When adding a Hook event, review:
+
+1. Handler group and timeout in Codex configuration
+2. Recorder allowlist fields and fail-open path
+3. Forward and backward compatibility of raw JSONL decoding
+4. Aggregation counts and missing semantics
+5. Whether the live monitor consumes it
+6. Whether CloudKit projection needs a field
+7. Privacy documentation and logging fields
+
+Not every event belongs in every layer. An explicit “not consumed” is easier to maintain than reliance on default decoder behavior.
+
+### Aggregation
+
+When the raw-event-to-aggregate algorithm, output fields, meanings, or deduplication rules change:
+
+1. Increment `WorkflowMaintenanceState.currentAggregationSchema`
+2. Fully rebuild from raw JSONL inside retention
+3. Do not add field-level historical migration
+4. Preserve the difference between missing and `0`
+5. Mark current-device replacement dates in CloudKit
+
+Increment schema when the same raw event produces semantically different output, not only when Codable can no longer decode. Even a deduplication fix requires rebuilding because old daily files already contain the incorrect result.
+
+Full rebuild is preferable because raw JSONL is the fact source. Field-level migration must guess information lost by old algorithms and accumulates historical branches that cannot compose.
+
+### System Power Control
+
+- CodexBarHelper controls only fixed sleep state and Automatic Reset `wake` events
+- CodexBarHelper gains no network or arbitrary-command capability
+- CodexBar must neither claim nor restore external `SleepDisabled=1`
+- Leases, watchdog, and owned persistence must all remain in place
+- The Automatic Reset wake interface accepts only bounded timestamps; owner and event type are fixed by the helper
+- Before exit, the app confirms sleep restoration and Automatic Reset wake-schedule cancellation
+
+Before changing sleep prevention, write five sequences: acquire, release, timeout, crash, and external owner. Testing only normal toggling does not prove global system state is recoverable.
+
+Before changing Automatic Reset wake scheduling, write six sequences: schedule, replace, cancel, connection loss, helper startup, and unregister. System read-back must prove that the fixed owner has exactly one matching event or none.
+
+Every new helper method requires proof that root execution is necessary. Reads, network operations, and file work possible in the regular app must not enter the helper merely for reuse.
+
+### Compatibility
+
+Compatibility concerns include:
+
+- Renamed or restructured persistence keys
+- Local schema changes
+- CloudKit record or field changes
+- CodexBarHelper ownership format changes
+- Automatic Reset wake-event owner or type changes
+- Debug/Release shared identity-calculation changes
+- Minimum system-version or API-availability changes
+
+These affect old data, old apps, or Debug/Release coexistence and require migration and degradation design.
+
+By repository policy, an implementer must not choose a compatibility outcome silently. Before changing anything, explain to the user:
+
+- Affected versions and data scope
+- Options to preserve old format, migrate once, rebuild fully, or discard explicitly
+- Failure modes and future maintenance costs of each choice
+- Whether old and new apps may run together
+- How upgrade and, if necessary, downgrade will be validated
+
+Implement only after the user chooses. Documentation should record the resulting invariant, not merely the migration steps.
+
+## Common Change Recipes
+
+### Adding a Setting
+
+1. Define one key and its missing-value default in the corresponding settings type or controller
+2. Define the value for upgrading users instead of relying on a coincidentally matching Swift property default
+3. Connect changes to one reconciliation entry point
+4. Do not let views write `UserDefaults` directly
+5. Test first install, existing install, and immediate effect after toggling
+
+### Adding a State Field
+
+1. Classify it as fact, derived state, or presentation format
+2. Put it in the model nearest the authoritative source
+3. Define `nil`, empty, zero, and stale
+4. Decide whether it changes Equatable snapshots
+5. Check whether notifications, sleep prevention, and UI consume it
+6. If persistence or sync is required, perform compatibility and privacy review first
+
+### Adding an Asynchronous Refresh
+
+1. Define trigger and freshness rules
+2. Coalesce identical requests with single-flight or a coordinator
+3. Add a generation for connection or source replacement
+4. Revalidate current eligibility after every `await`
+5. Define cancellation, timeout, and last-usable-snapshot behavior
+6. Log only state change or final result
+
+### Adding a Window or Side Panel
+
+1. Decide whether it belongs to the menu interaction surface or is an independent auxiliary window
+2. Reuse `HostingWindowController` or `MenuSideDetailPanel`
+3. Add it to mutual-exclusion registration and extra hit regions
+4. Handle multi-display visible frames and Spaces
+5. Validate key focus, activation, and closing-animation intermediate states
+
+## Validation by Change Type
+
+### Menus and Windows
+
+- Left-click, right-click, and Control-click behavior
+- Dismissal after clicking outside the popover
+- Side-panel hit regions and mutual exclusion
+- Settings and Logs window focus
+- Global shortcut and fallback panel
+- Multiple displays and menu bar locations
+
+### Hook and Aggregation
+
+- Preserve existing handlers
+- Reject enable when the version is insufficient
+- Persist every event within its timeout
+- File replacement, truncation, and cross-day reads
+- Full rebuild after schema upgrade
+- Missing fields do not display as `0`
+
+### Live Tasks
+
+- Running, waiting, completion, and termination transitions
+- Automatic review does not enter waiting state
+- Subagents belong to parent tasks
+- Bootstrap sends no notifications
+- Wake reconciles only after a new successful read
+- Reader replacement discards old results
+
+### Sync
+
+- Initial backfill
+- Multi-device merge without duplicating current-device contribution
+- Rebuild replaces only dates for the current device
+- iCloud offline, account switching, and recovery
+- Retention pruning
+
+### Notifications
+
+- System permission allowed and denied
+- Threshold crossing and persistent deduplication
+- Foreground presentation and click activation
+- Missing custom sound fallback
+- TUI and app notifications remain independent
+
+### System Power and Helper
+
+- CodexBarHelper and plist locations inside the app bundle
+- App and CodexBarHelper signatures
+- First-time system approval
+- Running and waiting-for-approval transitions
+- Low-battery and maximum-duration stops
+- Coexistence with external `SleepDisabled`
+- Recovery after normal and abnormal exit
+- Confirmation every time Automatic Reset or sleep prevention is enabled, and remaining off after cancellation
+- Confirmation copy for unregistered, awaiting-approval, and approved Helper states
+- Automatic Reset options appear only while enabled and the Helper is approved
+- Helper registration and system approval with Automatic Reset enabled
+- Automatic Reset threshold and retry retain only the nearest `wake` event for the fixed owner
+- Wake-event cleanup after Automatic Reset disable, target change, normal exit, disconnect, and helper restart
+- The fixed-owner wake event is confirmed empty before helper unregister
+- Debug and Release remain separated
+
+## Recording Reviewable Manual Evidence
+
+For every affected workflow, record at least:
+
+- Whether the build is Debug or Release
+- Initial settings and data state
+- Action sequence
+- Expected and actual UI
+- Relevant log fields
+- Whether restart, failure, and recovery paths were checked
+
+For example, Hook wake recovery can record:
+
+```text
+Precondition: 1 non-anonymous running task, sleep prevention enabled
+Action: Put the Mac to sleep and wake it after rollout writes terminal during sleep
+Expected: Task ends after a new drainNow cycle succeeds, no bootstrap notification, helper lease released
+Logs: trigger=wake, reader generation advanced, rollout reconciliation completed
+```
+
+This is easier to reproduce during a future regression than “manual test passed.”
+
+## Definition of Done
+
+A change is complete only when:
+
+- Code lives in the correct state owner without duplicating a second rule
+- Normal, missing, stale, failure, and recovery semantics are explicit
+- Concurrent requests have cancellation or generation boundaries
+- Compatibility and privacy impact are confirmed
+- Formatting, lint, and build pass for the change scope
+- Affected workflows receive manual validation
+- DeveloperGuide matches actual constants, schemas, and behavior
+- `git diff` contains no unrelated user changes or accidental formatting
+
+## Release Scripts
+
+These scripts require Developer ID, signing, notarization, or appcast credentials and are not for routine validation:
+
+- `Scripts/build.sh`
+- `Scripts/dmg.sh`
+- `Scripts/appcast.sh`
+
+The version comes from [`Version.xcconfig`](../../../Config/Version.xcconfig).
diff --git a/Docs/en/DeveloperGuide/hook-and-aggregation.md b/Docs/en/DeveloperGuide/hook-and-aggregation.md
new file mode 100644
index 0000000..ccb3f74
--- /dev/null
+++ b/Docs/en/DeveloperGuide/hook-and-aggregation.md
@@ -0,0 +1,543 @@
+# Hook Capture and Historical Aggregation
+
+[简体中文](../../DeveloperGuide/hook-and-aggregation.md) | English
+
+## Design Motivation
+
+The Hook flow serves two similar-looking goals with opposite requirements:
+
+- Record facts as quickly as possible on Codex's critical path
+- Maintain reliable long-term statistics in the main app
+
+Capture must be small, bounded, and allowed to fail. Aggregation can run asynchronously and must detect file changes, repair damaged caches, and support full rebuilds.
+
+The implementation therefore uses append-only raw JSONL plus rebuildable daily aggregations instead of making Hook subprocesses update a complex statistics object directly.
+
+## Flow Responsibilities
+
+The Hook flow turns Codex lifecycle events into rebuildable local history:
+
+```text
+Codex Hook
+ -> CodexBar --hook-event
+ -> Raw JSONL
+ -> Incremental WorkflowService aggregation
+ -> daily.jsonl
+ -> Activity UI and CloudKit sync
+```
+
+Raw events are the fact source; daily aggregation is a rebuildable cache. A change to the aggregation algorithm or field semantics requires a full rebuild from raw events within retention.
+
+### Why Hook Subprocesses Do Not Aggregate Directly
+
+Reading and rewriting `daily.jsonl` appears to remove a file layer but creates four problems:
+
+- Every Hook invocation decodes and rewrites history, so latency grows with event volume
+- The subprocess runs within Codex's timeout budget, turning aggregation failure into task delay
+- Algorithm upgrades lack raw facts for recalculation
+- Concurrent Codex sessions can lose updates between read and rewrite
+
+The current design reduces the critical path to one append. The main app aggregates in batches on its own schedule, and a failure leaves raw events for a later repair.
+
+### Raw Facts and Cache Responsibilities
+
+| File | Authoritative? | Recovery |
+| --- | --- | --- |
+| `events/YYYY-MM-DD.jsonl` | Yes | Append only; prune after retention |
+| `daily.jsonl` | No | Fully rebuild from raw events |
+| `maintenance.json` | No | Reconcile when missing or after schema change |
+| `stats.lock` | Stores no business data | Coordinates cross-process transactions only |
+
+## Installation and Validation
+
+[`CodexHookSettings.swift`](../../../CodexBar/Services/Settings/CodexHookSettings.swift) reads and changes Hook configuration through app-server.
+
+Enabling requires:
+
+- A resolvable current executable path
+- Actual app-server version `0.145.0` or later
+- Available `features.hooks`
+- A trusted source returned by `hooks/list`
+- A complete required event set
+
+The target file is `$CODEX_HOME/hooks.json`, or `~/.codex/hooks.json` when `CODEX_HOME` is unset.
+
+Installation adds the CodexBar handler as a separate command within the existing configuration. It never overwrites the entire file from a template:
+
+- Preserve existing user fields
+- Preserve handlers from other applications
+- Update only handlers matching the current executable and `--hook-event`
+- On disable, remove only an exact CodexBar handler match
+- Preserve unrecognized configuration unchanged
+
+`isEnabled` means only that a handler exists; `isVerified` means the most recent app-server validation passed. The UI treats Hook as a working source only when `isOperable` is true.
+
+### Why Installation and Validation Are Separate
+
+A command in `hooks.json` proves only that configuration exists on disk, not that Codex will run it.
+
+Execution may still be blocked when:
+
+- The current app-server version is too old
+- `features.hooks` is globally disabled
+- The handler event set is incomplete
+- app-server resolves another source file
+- The handler is untrusted or modified
+
+`isEnabled` is therefore a local configuration fact, while `isVerified` is Codex's most recent explicit conclusion for the current source. Sleep prevention and task notifications depend only on their combined `isOperable` state.
+
+A transient RPC failure means validation could not run this cycle, not that the handler became invalid. CodexBar preserves the last explicit conclusion while exposing the operation error for diagnosis.
+
+### Enable Transaction Order
+
+```text
+Confirm running app-server >= 0.145.0
+ -> Confirm features.hooks is not globally disabled
+ -> Read existing hooks.json
+ -> Remove only old CodexBar handlers for this executable
+ -> Append a separate group for every event
+ -> Atomically write hooks.json
+ -> Use hooks/list to read app-server's parsed result
+ -> Trust only entries matching command + sourcePath + event
+ -> Run hooks/list again for full validation
+```
+
+Preflight checks happen before file changes. A failed version or global-feature check leaves the user's file byte-for-byte unchanged.
+
+Trust matching requires both command and `sourcePath`. Command-only matching might trust the same command from another configuration; source-only matching might select the user's own handler.
+
+### Why Disable Queries Trust Keys First
+
+An app-server Hook key comes from the handler it currently parsed. Removing the command from `hooks.json` first would make a later `hooks/list` unable to recover the corresponding key.
+
+Disable therefore saves keys for exact matches, removes handlers, then removes those keys from `hooks.state`. Cleanup reads and replaces the complete state so trust entries belonging to users and other tools survive.
+
+A failed trust cleanup does not reinstall the handler. The UI reports that Hook is off but cleanup is incomplete because the user's intent to stop capture succeeded.
+
+### Why Every Event Uses a Separate Group
+
+CodexBar does not insert commands into an existing user group. Separate groups make uninstall remove only its own handler without interpreting the composition of user matchers and other handlers.
+
+Removal skips structurally malformed sibling entries instead of failing the entire switch. CodexBar recognizes its own command; it is not a global validator for the user's Hook configuration.
+
+### Generations for Asynchronous Settings Operations
+
+The user may toggle Hook quickly, and app activation also triggers validation. `CodexHookSettings` increments `updateGeneration` and cancels the old task for every operation.
+
+After every file write or RPC `await`, it checks the generation again. Even if an old operation cannot truly be canceled, it cannot overwrite the latest switch state or error.
+
+## Supported Events
+
+CodexBar subscribes to:
+
+| Event | Aggregation or live use |
+| --- | --- |
+| `SessionStart` | Establish session lifecycle |
+| `SessionEnd` | End session |
+| `UserPromptSubmit` | Establish turn and task start |
+| `PreToolUse` | Record tool-call start |
+| `PostToolUse` | Record tool-call end |
+| `PermissionRequest` | Detect user approval waiting |
+| `PreCompact` | Record context-compaction start |
+| `PostCompact` | Record context-compaction end |
+| `Stop` | Create a task-completion candidate |
+| `SubagentStart` | Record subagent start |
+| `SubagentStop` | Record subagent end |
+
+### Event Fields Serve Different Uses
+
+Historical counts need event name, date, project, model, and identity sets. Live state additionally needs turn, reviewer, effort, tool, and agent relationships.
+
+One minimal raw record lets the recorder write once while both consumers select their fields. A new field still requires a demonstrated consumer; its presence in the Hook payload does not justify persisting everything.
+
+Reviewer or effort for `PermissionRequest` and `UserPromptSubmit` may be absent from the Hook payload. Only for these two events, the recorder reads the rollout tail for that turn, avoiding extra file I/O on every event.
+
+## Hook Subprocess
+
+[`WorkflowHookEventRecorder.swift`](../../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift) checks for `--hook-event` at the earliest startup point.
+
+When matched, it only:
+
+1. Reads event JSON from stdin
+2. Extracts the minimal fields needed for metrics and state machines
+3. Acquires the file lock
+4. Appends one complete JSONL line
+5. Marks maintenance state in the same lock transaction
+6. Exits immediately
+
+Timeout depends on event:
+
+| Event | Timeout |
+| --- | --- |
+| `SessionEnd` | 3 seconds |
+| Other events | 5 seconds |
+
+The lock-wait budget is the handler timeout minus 2 seconds. Lock acquisition starts with 1 ms exponential backoff capped at 20 ms per wait.
+
+Invalid stdin, lock timeout, or write failure is swallowed. A statistics failure in the Hook subprocess must never block Codex.
+
+### Why It Still Returns Success
+
+Hook metrics are supplemental to CodexBar and not required for Codex to finish a task. Returning a nonzero exit code after a parsing or disk error could turn one statistics failure into a user's Codex failure.
+
+After explicitly entering `--hook-event` mode, the process therefore reports handled and exits successfully regardless of input validity. Failure loses one statistic but never escalates into an upstream task failure.
+
+### Why Event and Maintenance State Commit in One Lock Transaction
+
+One capture performs under the same `stats.lock`:
+
+```text
+Check current file identity
+ -> Start a new source generation if required
+ -> Append one complete JSONL line
+ -> Mark the date pending
+ -> Atomically save maintenance.json
+```
+
+If append and pending were separate lock transactions, the app could finish maintenance between them and consider the date caught up. The recorder might then append the event but fail before marking pending, leaving the new line invisible until a later full-directory reconciliation.
+
+The joint commit keeps “the file grew” consistent with “maintenance knows it must read.”
+
+### Why Lock Waiting Uses Only Part of the Timeout
+
+Codex waits at most 3 seconds for `SessionEnd` and 5 seconds for other events. The recorder caps lock waiting at total budget minus 2 seconds.
+
+The reserve covers encoding, append, saving maintenance state, and process exit. Spending the whole budget on the lock could let Codex terminate the process mid-write, leaving a partial line or unmatched maintenance state.
+
+Waiting backs off exponentially from 1 ms to 20 ms. Normal app critical sections are short, so a small start resumes quickly after release, while the cap avoids busy looping under contention.
+
+### Why the Lock File Uses One `open(O_CREAT)`
+
+Code must not check for absence, create, then reopen. Two processes could create different inodes; after one replaces the directory entry, both would lock separate files and each believe it has exclusivity.
+
+One `open` makes creation and opening an atomic entry point so all participants use `flock` on the same inode at that path.
+
+## Captured Fields
+
+Raw records retain only information required for statistics and live state:
+
+- Timestamp and event name
+- Working directory
+- Tool name
+- Model and reasoning effort
+- Permission and approval reviewer
+- Session and turn IDs
+- Agent and parent relationships
+
+For `UserPromptSubmit` and `PermissionRequest`, input may omit reviewer or effort. When needed, the recorder looks for a matching `turn_context` near the end of the rollout transcript.
+
+The lookup:
+
+- Reads at most 512 KB once
+- Extracts only structural fields such as reviewer and effort
+- Never writes prompt or response content to Hook statistics
+
+### Input Normalization
+
+Hook payload versions may represent identifiers and time as different JSON types. `WorkflowHookPayload` centralizes permissive normalization:
+
+- Trim strings and turn empty strings into missing values
+- Convert numeric identifiers to strings
+- Accept ISO-8601, local timestamps, Unix seconds, and Unix milliseconds
+- Fall back to recorder current time when time is missing
+- Fall back to the subprocess current directory when cwd is missing
+
+Permissiveness exists only at the external-input boundary. After conversion to `WorkflowHookEvent`, downstream aggregation and monitoring use uniform types instead of guessing protocol differences again.
+
+### Rollout Tail-Lookup Boundary
+
+The lookup reads only the last 512 KB of the transcript, discards a potentially truncated first line, then searches backward for the matching turn's `turn_context`.
+
+Backward search finds the latest context for a turn nearest the file tail. The read limit protects Hook timeout; a miss leaves the field absent instead of expanding into an unbounded scan.
+
+## Local Files
+
+The default data root is:
+
+```text
+~/Library/Application Support/CodexBar/HookEvents/
+```
+
+Directory structure:
+
+```text
+HookEvents/
+ events/
+ YYYY-MM-DD.jsonl
+ daily.jsonl
+ maintenance.json
+ stats.lock
+ Sync/
+ state.json
+ cache.jsonl
+ cursor.data
+```
+
+| File | Purpose |
+| --- | --- |
+| `events/YYYY-MM-DD.jsonl` | Store raw Hook events by day |
+| `daily.jsonl` | Store aggregations by date and source generation |
+| `maintenance.json` | Store pending maintenance and schema state |
+| `stats.lock` | Coordinate Hook subprocesses and app maintenance |
+| `Sync/*` | CloudKit sync cursor and cache |
+
+Raw events and daily aggregations are retained for up to 210 days. Detailed session and turn ID lists remain only for 3 days; older dates compact them to counts to reduce file size and identity retention.
+
+### Why JSONL
+
+JSONL matches this write pattern:
+
+- The recorder appends one complete record to the tail
+- One damaged line can be isolated instead of failing the whole file
+- Files can rotate by day and be pruned by retention
+- Individual structures remain inspectable during manual diagnosis
+- Aggregation and remote caches can use the same line-level recovery strategy
+
+A regular JSON array would rewrite tail structure on every append. A database would add schema, locking, and deployment complexity, while current queries only scan chronologically by date and gain too little from it.
+
+### A Complete Line Is the Commit Unit
+
+The reader advances only to the offset of the final newline. If a partial line is being written at the tail, the current cycle keeps its old offset and processes the line after a future cycle sees it complete.
+
+`JSONLines.decodeWithFailures` decodes per line. One malformed line increments the corrupt count without discarding valid events from the same read block.
+
+### Why Identity Details Remain for Only 3 Days
+
+Session and turn IDs support recent exact deduplication, while long-term presentation needs counts only.
+
+Compacting identifiers to counts after 3 days reduces file size and identity retention. The aggregation model must record whether a field is retained or compacted; otherwise it cannot know whether later events can still use IDs for exact deduplication.
+
+Raw events remain for 210 days and support a full algorithm rebuild. CloudKit never uploads these raw identities.
+
+## Incremental Reading and Source Generations
+
+For each raw file, the aggregator records inode, size, offset, and source generation:
+
+- Normal appends resume at the previous offset
+- An inode change means file replacement
+- Size below offset means truncation
+- Replacement or truncation creates a new source generation
+
+Source generation distinguishes raw sources for the same day. Same-source results replace one another; clearly independent generations may add together. A user-requested full rebuild tells sync that all old generations are invalid through a replacement marker.
+
+### `pending` Versus `dirty`
+
+`maintenance.json` tracks two work states for a date:
+
+| State | Used when | Next step |
+| --- | --- | --- |
+| `pending` | Confirmed normal append to the same source | Aggregate incrementally from the old offset |
+| `dirty` | Source change, schema change, missing cache, or previous failure | Fully rebuild from the file start |
+
+`dirty` takes priority. If a date appears in both sets, only a rebuild task is created, avoiding an append to the old aggregate followed by complete replacement.
+
+Explicit states are safer than guessing from `offset == 0`. A new empty file, truncated file, and requested rebuild can all have offset 0 but differ in source generation and sync semantics.
+
+### Determining Whether a File Is the Same Source
+
+Maintenance combines four kinds of evidence:
+
+- Whether inode identity changed
+- Whether current size is below consumed offset
+- Whether current size equals the previous recorded size
+- Whether the boundary hash over the 4 KB before offset still matches
+
+Inode and size detect replacement and truncation; the boundary hash detects an in-place rewrite at the same length.
+
+### Why Boundary Hash Also Uses mtime
+
+Rehashing every file across 210 days each cycle would hold `stats.lock` for too long and directly increase Hook recorder wait probability.
+
+Maintenance records nanosecond mtime from the last boundary validation. If inode, size, and mtime are unchanged, it skips hashing. It recomputes the 4 KB before offset only after file change.
+
+A normal append changes bytes only after offset, so the boundary continues to match and maintenance can aggregate incrementally. A changed boundary creates a new generation and marks it dirty.
+
+### Why Build and Commit Are Separate
+
+The aggregator cannot hold `stats.lock` while reading a full day because Hook subprocesses could time out repeatedly.
+
+The actual flow is:
+
+```text
+Prepare under lock
+ -> Fix sourceGeneration, inode, startOffset, and read upper bound
+Build without lock
+ -> Read in chunks and produce a candidate aggregate
+Validate under lock
+ -> Generation still matches
+ -> Inode still matches
+ -> Candidate upper bound still exists
+ -> Boundary hash still matches
+Commit daily.jsonl
+Validate again under lock and advance maintenance offset
+```
+
+The recorder may continue appending during the read. As long as bytes before the candidate upper bound remain unchanged, the result is valid and the new tail remains pending for the next cycle.
+
+If the source is replaced during build, the candidate does not commit; maintenance starts a new generation and waits for rebuild.
+
+## Aggregation Rules
+
+Daily results include:
+
+- Total Hook events and per-event counts
+- Session and turn counts
+- Tool-call count
+- Compaction count
+- Subagent count
+- Project distribution
+- Model distribution
+
+Only one side of a paired event may persist. Counts therefore use rules that avoid duplicates while tolerating missing data:
+
+- Tool calls use `max(PreToolUse, PostToolUse)`
+- Compactions use `max(PreCompact, PostCompact)`
+- Subagents use `max(SubagentStart, SubagentStop)`
+
+A missing field differs from numeric `0`:
+
+- Missing means the historical source cannot provide this metric for the date
+- `0` means the source is available and explicitly observed none
+
+Decoding and UI must preserve the distinction.
+
+### Why Paired Events Use `max`
+
+`PreToolUse` and `PostToolUse` describe the two sides of one tool call. Since the recorder may fail, either side may be absent:
+
+- Adding counts one complete call twice
+- Pre-only misses a failed pre write followed by a successful post
+- Post-only misses a tool that started before process interruption
+- `max(pre, post)` is the least duplicate-prone estimate without stable call IDs
+
+Compaction and subagent pairs follow the same rule.
+
+If a future Hook protocol provides stable operation IDs, the algorithm can move to set deduplication, but that changes aggregation semantics and requires a schema increment and full rebuild.
+
+### Carrying Availability Through Old Data
+
+Older aggregations may not have a newer Hook count. Rebuild cannot assume that an old source captured an event merely because current code understands it.
+
+`WorkflowHookCountAvailability` records source availability for each count. Rebuild inherits an existing date's availability for old fields, while a fresh source can declare all current fields available.
+
+The UI can therefore distinguish:
+
+- Explicitly zero occurrences
+- Historical capture for the date did not provide the metric
+
+## Schema Evolution and Rebuild
+
+The current aggregation schema is `5`, managed by `WorkflowMaintenanceState.currentAggregationSchema`.
+
+Increment the schema for:
+
+- Changes to the raw-event-to-aggregate algorithm
+- Added or removed output fields
+- Changed field meanings
+- Changed deduplication rules
+- Changed source-generation merge semantics
+
+After upgrade, CodexBar fully rebuilds from raw JSONL within the 210-day retention period instead of performing field-level historical migration. Every aggregation under one schema is then generated by the same current algorithm.
+
+User-requested rebuilding uses the same full-recalculation path and marks dates for replacement in sync.
+
+### Aggregation Schema Versus Source Generation
+
+| Identity | Describes | Changes when |
+| --- | --- | --- |
+| Aggregation schema | How current code calculates an aggregate from raw events | Algorithm, fields, or semantics change |
+| Source generation | Which generation of raw file a particular day belongs to | Replacement, truncation, requested rebuild, or boundary rewrite |
+
+A schema change usually marks all event dates in retention dirty. A source-generation change affects only a specific date.
+
+Neither can be replaced with the app version. One app version may not change aggregation, while development builds may iterate schemas without changing a version number.
+
+### Why There Is No Field-Level Migration
+
+`daily.jsonl` is a derived cache and raw JSONL remains available during retention. Migrating every historical field would retain both old and new algorithms and make mixed semantics more likely.
+
+A full rebuild has a bounded one-time cost and guarantees:
+
+- Every date under one schema uses the same code
+- Removed or redefined fields leave no residual values
+- Damaged aggregate lines are repaired at the same time
+- CloudKit replacement follows source generation consistently
+
+Only when the raw source itself lacks a field does missing preserve the historical capability difference.
+
+### Commit Semantics for a User Rebuild
+
+A batch rebuild handles dates independently. Failure on one day does not block days that succeeded; failed dates become dirty for normal maintenance to retry.
+
+Both successful and failed dates register CloudKit replacement first. A failed date already entered a new generation, and its later successful automatic rebuild will use a new record identity. Without an early marker, the old generation might remain in the cloud and be added to the new value.
+
+The operation fails as a whole only if every date fails. Partial success returns a detailed summary of successful dates, damaged lines, and pending replacement state.
+
+## Maintenance Scheduling
+
+[`WorkflowService.swift`](../../../CodexBar/Services/Workflow/WorkflowService.swift) is an actor that serializes reading, aggregation, pruning, and rebuild.
+
+Maintenance coordinates with the rate-limit refresh cycle but has no data dependency on it. The Workflow view model refreshes UI no more often than every 5 seconds to avoid rerendering for frequent file changes.
+
+### Why No-Op Maintenance Does Not Emit Normal Logs
+
+Maintenance normally follows the 60-second refresh. An idle machine would otherwise emit more than a thousand no-change checks per day.
+
+`WorkflowService` accumulates consecutive idle cycles and logs one summary only after a write, skip, failure, or cleanup, including the preceding idle count. Logs can prove that maintenance runs without burying real failures.
+
+### How the Scheduler Coalesces Requests
+
+`WorkflowSyncScheduler` serializes three request classes:
+
+1. User rebuild, highest priority
+2. Maintenance with sync
+3. Local-only maintenance
+
+After sync completes, an 8-second cooldown combines incoming requests and retains the earliest trigger as the real cause.
+
+Opening the UI reads the current local snapshot and does not bypass the scheduler to start an unconditional CloudKit request.
+
+## Steps to Add a Hook Event or Metric
+
+1. Register the protocol name, configuration name, and handler timeout in `CodexHookEvent`
+2. Ensure the recorder persists only minimal fields required for calculation
+3. Update Hook-installation completeness validation
+4. Define count and deduplication semantics in the accumulator
+5. Update aggregate Codable and JSONL encoding while preserving missing semantics for old fields
+6. Increment `WorkflowMaintenanceState.currentAggregationSchema`
+7. Update CloudKit record schema and upload/download mapping
+8. Decide coexistence with old apps and new records before changing compatibility formats
+9. Update UI and privacy boundaries
+10. Manually test normal append, a missing side of a pair, file replacement, and full rebuild
+
+## Suggested Failure-Scenario Tests
+
+- Concurrent Codex sessions write complete lines without overwriting one another
+- While the main app holds the lock, the Hook recorder succeeds within budget or abandons safely
+- Non-JSON stdin or missing event name still exits successfully and immediately
+- A partial tail line does not advance offset and is read after completion
+- One malformed JSONL line increments only the corrupt count
+- Inode change, file shrink, and boundary rewrite each create a new generation
+- Appends during build commit only to the fixed upper bound and leave the tail pending
+- A schema change rebuilds every in-retention date with the current algorithm
+- Missing fields on old dates remain unavailable instead of becoming `0`
+- Disabling CodexBar Hook preserves user handlers and trust entries
+- During rapid Hook toggling, old RPC results cannot overwrite the final operation
+
+## Failure Boundaries
+
+- One malformed JSONL line must not make the entire retention period unreadable
+- A changed file source must not continue from the old offset
+- A failed rebuild preserves the last usable aggregate
+- Interrupted maintenance must not commit a partial result as a complete date
+- When Hook is unavailable, the UI shows source unavailability rather than clearing to `0`
+- A failed configuration write must not damage existing handlers
+
+## Key Source Files
+
+- [`CodexHookSettings.swift`](../../../CodexBar/Services/Settings/CodexHookSettings.swift)
+- [`WorkflowHookEventRecorder.swift`](../../../CodexBar/Services/Workflow/WorkflowHookEventRecorder.swift)
+- [`CodexHookEvent.swift`](../../../CodexBar/Models/CodexHookEvent.swift)
+- [`JSONLines.swift`](../../../CodexBar/Services/Workflow/JSONLines.swift)
+- [`WorkflowService.swift`](../../../CodexBar/Services/Workflow/WorkflowService.swift)
+- [`CodexWorkflowModels.swift`](../../../CodexBar/Models/CodexWorkflowModels.swift)
diff --git a/Docs/en/DeveloperGuide/notifications.md b/Docs/en/DeveloperGuide/notifications.md
new file mode 100644
index 0000000..0f6aa79
--- /dev/null
+++ b/Docs/en/DeveloperGuide/notifications.md
@@ -0,0 +1,364 @@
+# Notification System
+
+[简体中文](../../DeveloperGuide/notifications.md) | English
+
+## Responsibility
+
+[`CodexNotificationService.swift`](../../../CodexBar/Services/Notifications/CodexNotificationService.swift) is the single entry point for notification side effects.
+
+It consumes three kinds of state:
+
+- app-server account, rate-limit, and Reset Credits snapshots
+- Task transitions and sleep-restoration events from `CodexActivityMonitor`
+- Confirmed redemption results or user-facing failures from `AutoResetController`
+
+Views and other services do not create system notifications directly. They publish state changes; the notification service handles eligibility, deduplication, sound, and click behavior.
+
+## Design Principles
+
+A notification is not state. It is an external side effect triggered by a state change. A reliable notification requires all four conditions:
+
+```text
+The event occurred
+ + The user allows this category
+ + The event is still relevant
+ + It has not been sent in this lifecycle or persistence cycle
+```
+
+Centralizing these checks serves two purposes:
+
+- Upstream components publish facts and transitions without knowing about system permission, sounds, or deduplication storage
+- Every submission follows the same relevance checks, retry rules, and privacy-preserving logging
+
+Direct notification delivery from a view could repeat after SwiftUI reconstruction, repeated panel openings, or snapshot republication. Views may change settings or display state, but cannot own notification side effects.
+
+## Snapshots and Transitions Are Not Interchangeable
+
+Different notifications require different evidence:
+
+| Notification | Input | Reason |
+| --- | --- | --- |
+| Low rate limit | Consecutive trusted snapshots | Must compare values on both sides of a threshold |
+| Rate-limit reset | Consecutive trusted snapshots | Must observe consumption before observing a return to zero |
+| Reset Credits expiration | Current snapshot plus time scheduling | A future deadline triggers the reminder |
+| Automatic Reset | app-server mutation result | Only an explicit result proves that this Mac performed the automatic action |
+| Task completion | Monitor transition | Historical terminal snapshots must not replay |
+| Waiting for approval | Monitor transition plus current snapshot | Notify on new waiting state, then withdraw stale notifications |
+| Stalled Task Protection | Committed protection result | Must describe a task that has already been hidden |
+| Sleep prevention stopped | Confirmed system-restoration result | Must not announce success before restoration |
+
+Inferring task completion from a current snapshot looks simpler, but every app launch would treat historical completed tasks as new events. Conversely, one transition alone cannot identify a low-rate-limit case when the app starts after the threshold was crossed.
+
+## App Settings and System Authorization Are Separate Gates
+
+`NotificationSettings` stores in-app intent separately from macOS authorization:
+
+| State | Meaning |
+| --- | --- |
+| `isEnabled` | The user enabled the master switch in CodexBar |
+| `authorizationStatus` | Whether macOS permits notifications |
+| `canDeliver` | Effective eligibility when both allow delivery |
+
+The master switch is off by default, so first launch does not present an unexplained permission request. CodexBar invokes the authorization API only after the user enables it.
+
+The app rereads system state on activation because permission may have changed in System Settings. If the app switch is on but system state remains `notDetermined`, it requests again, covering a quit before the first dialog finished.
+
+Haptic feedback does not depend on `UNUserNotificationCenter` authorization but still follows the in-app master switch. This is a capability boundary, not a way around user intent.
+
+## Notification Switches
+
+The master switch is off by default. The eight configurable category switches default to on, and haptic feedback defaults to off.
+
+While the master switch is off, CodexBar neither requests system notification permission nor sends category notifications. Once it is on, category settings select specific types:
+
+| Category | Data source | Control |
+| --- | --- | --- |
+| Rate-limit reset | app-server rate-limit window | Independent category switch |
+| Low rate limit | app-server remaining allowance | Independent category switch and threshold |
+| Reset Credits expiration | app-server reset-credit details | Independent category switch |
+| Automatic Reset | Confirmed redemption result or user-facing failure | Automatic Reset, category, and master switches |
+| Task completion | Live-task terminal transition | Independent category switch and minimum duration |
+| Waiting for approval | Live-task waiting transition | Independent category switch |
+| Stalled Task Protection | Activity Protection | Prevent System Sleep and notification master switches |
+| Low-battery stop | KeepAlive restoration result | Independent category switch, enabled only when protection is available |
+| Keep-awake limit | KeepAlive restoration result | Independent category switch, enabled only for a finite duration |
+
+Stalled Task Protection has no independent notification switch. It follows Prevent System Sleep, then the notification master switch after protection occurs. Preferences for low-battery and duration-limit notifications are retained, but the UI displays them off and disabled when their protection conditions are unavailable, without changing persisted preferences.
+
+## Rate-Limit Reset
+
+A rate-limit reset notification requires observing a consumed window first and then a new window restored to an unconsumed state.
+
+This prevents a notification merely because the first value seen after launch is 100%.
+
+Observation state is isolated by account and rate-limit window. An account change does not carry the previous account's consumption state into the new account.
+
+Each window also has an in-session lifecycle token. A window that disappears from trusted snapshots and later returns receives a new token. If a failed submission callback for the old window arrives late, it restores `hasObservedConsumption` only if the token still matches.
+
+This prevents a race in which app-server switches account or window while an old notification is submitting, then the late failure callback incorrectly marks the new window as previously consumed.
+
+Reset observation is not persisted. After launch, the app must observe consumption again before notifying. It deliberately accepts missing an offline reset in exchange for never misreporting 0% usage as a reset at startup.
+
+## Automatic Reset
+
+An automatic reset operation and a rate-limit-window reset are separate events, so they retain separate notifications:
+
+- “Automatic Reset” means CodexBar's automatic action returned `reset` or `alreadyRedeemed`
+- “Rate Limit Reset” means a normal rate-limit snapshot first showed consumption and later returned to zero
+
+One automatic reset may satisfy both, so the same Mac can receive both notifications. Similar wording is not a reason to merge them: one proves an automation action, the other represents the rate-limit lifecycle, and their sources and settings differ.
+
+The success body prefers a fresh post-redemption read of remaining reset credits, including an explicit `0`. If that read fails, the explicit success still stands and CodexBar sends a title-only notification.
+
+`alreadyRedeemed` means the same idempotency key succeeded previously and must not be retried. When several devices call concurrently, every device that explicitly receives `reset` or `alreadyRedeemed` may send its local success notification. A device that only sees the credit disappear during refresh cannot distinguish manual use, use by another device, or expiration, so it stops silently.
+
+Failure notifications use “Automatic Reset Failed” and currently cover:
+
+- Still signed out after one authentication refresh: pause the current credit until a trusted snapshot proves recovery
+- Parameter, protocol, or method error: stop retrying the current credit
+- This Mac explicitly observes that the target expired: stop retrying the current credit
+
+Transient network and service failures enter backoff without bothering the user on every attempt. The same failure reason notifies at most once per credit. Authentication, permanent error, and locally observed expiration use different deduplication keys, so one credit may produce different failure notifications over time. When the target disappears from server details, its cause is unknown and the state machine stops silently without adding an expiration notification.
+
+Success and failure share the Automatic Reset Notifications switch and sound, enabled by default with the system default sound. When Automatic Reset is off, the setting row is disabled without overwriting saved notification or sound choices; re-enabling restores them.
+
+## Low Rate Limit
+
+Available thresholds are 5%, 10%, and 25%; the default is 10%.
+
+A notification is sent only when remaining allowance moves from above the threshold to the threshold or below. Remaining in the low region does not repeat on each refresh.
+
+The first trusted snapshot being below the threshold also counts as a downward crossing, covering app startup after the actual crossing.
+
+The persisted deduplication key contains the second-level reset time returned by app-server. For the same account and rate-limit window, a reset time within 60 seconds of the recorded value belongs to the same cycle; only a difference greater than 60 seconds creates a new cycle.
+
+Returning above the threshold rearms crossing detection, but one reset cycle still notifies only once. After a new reset cycle begins, the next downward crossing may notify again.
+
+### Why Detection Uses a Downward Crossing
+
+“Currently below 10%” is a persistent state. “Just dropped below 10%” is the notification event. For each `account + limit + window`, the service stores the previous remaining percentage:
+
+- Notify when the previous value was above the threshold and the current value is not
+- Notify once when the first in-session value is already at or below the threshold
+- Do not notify while remaining continuously in the low region
+- When the threshold setting changes, clear the observation and reevaluate immediately against the new threshold
+
+The settings subscription uses the new value passed to its callback. Combine publishes `@Published` during `willSet`, when rereading the settings property would still return the old value. This detail ensures that changing the threshold from 5% to 25% evaluates immediately at 25%.
+
+A stale app-server snapshot neither advances the previous value nor triggers low-rate-limit or reset notifications. Old cache data supports display continuity but cannot prove a new side effect.
+
+### Why Reset Time Allows 60 Seconds of Drift
+
+After rebuilding an app-server connection, the same window's `resetsAt` may receive a seconds-level correction. Absolute equality would treat it as a new cycle and notify twice.
+
+Within the same account, limit, and window, the service finds sent or in-flight keys within a 60-second tolerance and reuses the original key. This tolerance normalizes identity only; the UI still displays the actual time returned by the service.
+
+## Reset Credits Expiration
+
+When the number of Reset Credits is greater than `0` and an expiration date is available, the notification service sends daily reminders from 7 days to 1 day before expiration.
+
+The deduplication key includes account, expiration date, and days remaining. Multiple refreshes on one day do not repeat the notification.
+
+The service does not create seven long-lived system pending requests. It schedules only the nearest future checkpoint, then recalculates from the current snapshot and schedules the next one when that point arrives.
+
+This handles:
+
+- app-server changes to the number or expiration time of Reset Credits
+- Notification settings being disabled midway
+- A Mac sleeping past the deadline and rechecking through the wake observer
+- Combining multiple credits with the same expiration second into one notification
+
+Date classification uses seconds remaining until expiration, with separate deduplication keys for 7 through 1 day. The scheduler only wakes the check; the current snapshot makes the final eligibility decision.
+
+## Task Completion
+
+Task notifications respond only to new terminal transitions published by the monitor and never infer them by scanning historical lists:
+
+- Tasks established during bootstrap do not notify
+- The activity monitor retains terminal IDs for 24-hour deduplication
+- The notification service also tracks its own sent keys
+- `Stop` and rollout terminal data for the same turn reconcile into one notification
+
+Anonymous tasks are not published to task-notification consumers. The notification service filters `isAnonymous` again at the transition boundary, so anonymous tasks cannot send completion or approval notifications or trigger task haptics.
+
+Minimum completion duration is 30, 60, 120, or 300 seconds; the default is 60 seconds. A shorter completed task does not notify but may still appear briefly in the UI.
+
+Filtering anonymous tasks again is defense in depth at the side-effect boundary, even though the monitor already omits their transitions. If a future upstream refactor or new transition type changes that guarantee, a task without a session ID still cannot produce a system notification or haptic effect accidentally.
+
+Haptics start for every task transition. A new transition cancels the previous sequence of 10 pulses and begins again. Settings are rechecked before each pulse, so disabling haptics stops an old sequence immediately.
+
+## Waiting for Approval
+
+A waiting notification is sent only when the `PermissionRequest` reviewer is confirmed to be the user:
+
+- Automatic review does not notify
+- One waiting item notifies only once
+- Leaving waiting state removes the item from the relevant set
+- Waiting state found during bootstrap does not replay historical notifications
+
+Whether waiting maintains sleep prevention is an independent setting and does not affect notification eligibility.
+
+The notification uses stable task ID as its system identifier. The service also observes activity snapshots:
+
+- Skip submission if the task has already left waiting state
+- If state changes after `UNUserNotificationCenter.add` succeeds, withdraw immediately
+- When a later snapshot no longer contains the task, remove both delivered and pending notifications
+- On submission failure, remove it from the in-memory relevance set so a genuinely new wait may try again later
+
+Relevance checks both before and after submission cover the asynchronous window. Checking only before submission could leave a stale reminder in Notification Center after approval.
+
+## Stalled Task Protection
+
+When a non-anonymous task reaches its silence threshold, Activity Protection first saves a protection record and hides the task, then requests a notification. Anonymous tasks never become protection candidates and cannot create protection notifications.
+
+The notification service checks again before submission that the task remains protected. New progress during the 3-second grace period cancels the stale notification.
+
+Protection notifications always use the default sound rather than the task-completion category sound. A failed notification does not undo protection that already completed.
+
+The notification identifier uses `taskID + attemptID`; relevance also compares progress generation and silence duration. When the task progresses during the 3-second grace period, the monitor invalidates the protection attempt and requests withdrawal.
+
+These notifications have an explicit `retryCount` of 0. Protection results are time-sensitive, and a retry after immediate failure may no longer be relevant. General notifications may retry once; a protection notification prefers omission over a late false alert.
+
+## Sleep Prevention Stopped
+
+When low battery or the duration limit stops sleep prevention, `KeepAliveController` first revokes the CodexBarHelper lease and waits for a read-back confirmation of `SleepDisabled=0`.
+
+It submits the notification only after confirmation. The app idle assertion remains until notification submission completes, preventing a closed-lid Mac from sleeping before the notification reaches the system. The controller then releases the assertion and, if needed, issues a compensating lid-close sleep.
+
+This ensures the copy describes a completed system-level restoration while giving asynchronous submission time to converge.
+
+## Sounds
+
+[`NotificationSoundOption.swift`](../../../CodexBar/Services/Notifications/NotificationSoundOption.swift) combines three option groups:
+
+- No sound
+- System sounds available on macOS
+- Sounds bundled with the app
+
+Bundled sounds are under [`NotificationSounds`](../../../CodexBar/Resources/NotificationSounds).
+
+If a saved sound name does not exist on a new system or app version, CodexBar falls back to the default sound without blocking the notification.
+
+Each notification category stores its own sound setting.
+
+Sound options persist stable IDs rather than absolute file paths:
+
+- Bundled sounds resolve through bundle resources
+- On first access, system sounds are scanned from User, Local, and System sound directories
+- `/Network/Library/Sounds` is intentionally excluded because probing automounted paths may block the UI
+- Duplicate names choose the earlier directory in system search order
+- Bundled IDs are reserved in advance so a same-named local file cannot change the meaning of a saved choice after restart
+- An unresolvable saved ID falls back to system default
+
+System default and silent choices cannot be previewed. Playing a system alert as a substitute for Notification Center's default sound creates a false expectation, so previews support only system and bundled sounds backed by explicit files.
+
+## Haptic Feedback
+
+Haptic feedback is off by default. When enabled, it uses 10 pulses roughly 100 ms apart.
+
+Haptics are a separate local feedback channel from system notifications. They respond to completion or waiting transitions for non-anonymous tasks and follow the notification master switch and haptics switch, but do not depend on system authorization, a category switch, or the completion-duration threshold.
+
+This separation lets a user disable banners while keeping consistent task haptics. The upstream transition must still be valid; bootstrap history and anonymous tasks never trigger it.
+
+## Submission and Deduplication
+
+Notifications are submitted through `UNUserNotificationCenter`:
+
+- One failed submission retries at most once
+- Sent deduplication keys persist in UserDefaults
+- No more than 300 keys are retained
+- Keys include enough account or task scope to avoid suppressing different objects
+- Expired or irrelevant waiting keys are removed
+
+Persistent deduplication prevents immediate repeats after restart but does not replace upstream terminal deduplication.
+
+### Two Deduplication Layers Solve Different Problems
+
+`submittingDedupKeys` and `sentDedupKeys` cannot be merged:
+
+| Set | Lifetime | Prevents |
+| --- | --- | --- |
+| `submittingDedupKeys` | Current asynchronous submission | Two synchronous calls passing the check before the first `await` |
+| `sentDedupKeys` | UserDefaults, up to 300 entries | Repeating the same business cycle after an app restart |
+
+The deduplication check and `submitting` insertion happen synchronously before creating a `Task`, so correctness does not depend on Swift task scheduling order.
+
+A key enters the sent set only after `UNUserNotificationCenter.add` succeeds and the event is still relevant afterward. Recording it earlier would permanently consume an alert after one system submission failure.
+
+The 300-entry cap prevents UserDefaults from becoming an unbounded event log. An old event could theoretically recur after eviction; that is accepted because upstream cycle identity and live-transition deduplication remain the first boundary.
+
+### Shared Delivery Semantics
+
+All notification content eventually passes through the same `send` and `deliver` flow:
+
+```text
+Synchronously check deduplication
+ -> Build an immediate notification request
+ -> Check relevance before submission
+ -> Call the system notification center
+ -> Check relevance again after submission
+ -> Persist deduplication after success
+ -> On failure, retry at most once and run category cleanup
+```
+
+Logs record only `kind` and the failure reason, never title or body. Notification bodies may contain project names or task information and must not be copied into logs even when those logs remain local.
+
+## Foreground Presentation and Clicks
+
+CodexBar is an `LSUIElement`, so its notification-center delegate explicitly allows banners and sounds while the app is in the foreground.
+
+Clicking a notification opens the main panel. The status-bar controller performs the action and reuses existing popover or fallback-panel logic.
+
+The delegate explicitly returns banner, list, and sound for foreground presentation. An `LSUIElement` app often remains foregrounded or in unusual activation states; relying on default foreground policy would make notifications appear to disappear unpredictably.
+
+Click handling calls `openMenuSurface` instead of constructing a new window. This reuses the popover when its anchor is valid, uses the fallback panel otherwise, and preserves the same focus and dismissal rules.
+
+## Checklist for a New Notification Type
+
+1. Identify whether its input is a snapshot, transition, or confirmed side-effect result
+2. Define identity scoped to account, window, task, or attempt
+3. Decide whether it needs session deduplication, persistent deduplication, and relevance checks
+4. Define whether bootstrap, stale data, and anonymous tasks may trigger it
+5. Choose sound and failure-retry semantics
+6. Ensure sensitive fields from the body cannot enter logs
+7. Define defaults and behavior for missing old UserDefaults values
+8. Validate foreground display, click activation, and withdrawal after invalidation
+
+## Codex TUI Notifications
+
+The Codex TUI Notifications setting belongs to Codex itself and is read and written through app-server `config/batchWrite`.
+
+It is completely independent of CodexBar system notifications:
+
+- Turning off CodexBar notifications does not turn off TUI notifications
+- A failed TUI setting does not affect app notification state
+- The UI must distinguish the scope of both switches clearly
+
+## Manual Validation Matrix
+
+- Enabling the master switch for the first time requests system permission correctly
+- Settings presents an understandable state when permission is denied
+- Low-rate-limit alerts occur only on downward threshold crossings
+- An initial 100% rate limit does not produce a false reset alert
+- Explicit Automatic Reset `reset` sends “Automatic Reset”; a later return to zero can independently send “Rate Limit Reset”
+- Explicit `alreadyRedeemed` is treated as success and stops retries
+- Merely observing the target credit disappear does not send an Automatic Reset notification
+- Network retries do not send failure alerts, and one credit reports the same failure reason at most once
+- Turning off Automatic Reset disables its notification option; re-enabling restores the prior switch and sound
+- Success and failure notifications use the sound selected for Automatic Reset Notifications; both are silent when no sound is selected
+- Behavior is correct for completed tasks below and above the duration threshold
+- `Stop` and rollout terminal arriving together produce one notification
+- Automatic approval does not send a waiting notification
+- Allowed notifications still appear while the app is foregrounded
+- Clicking a notification activates the `LSUIElement` app and opens the main panel
+- A missing saved sound resource falls back correctly
+- Restarting the app does not repeat persisted events
+
+## Key Source Files
+
+- [`CodexNotificationService.swift`](../../../CodexBar/Services/Notifications/CodexNotificationService.swift)
+- [`NotificationSettings.swift`](../../../CodexBar/Services/Settings/NotificationSettings.swift)
+- [`NotificationSoundOption.swift`](../../../CodexBar/Services/Notifications/NotificationSoundOption.swift)
+- [`CodexCLINotificationSettings.swift`](../../../CodexBar/Services/Settings/CodexCLINotificationSettings.swift)
+- [`CodexActivityMonitor.swift`](../../../CodexBar/Services/Workflow/CodexActivityMonitor.swift)
+- [`KeepAliveController.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveController.swift)
diff --git a/Docs/en/DeveloperGuide/sleep-prevention.md b/Docs/en/DeveloperGuide/sleep-prevention.md
new file mode 100644
index 0000000..b9df5a7
--- /dev/null
+++ b/Docs/en/DeveloperGuide/sleep-prevention.md
@@ -0,0 +1,467 @@
+# Sleep Prevention System
+
+[简体中文](../../DeveloperGuide/sleep-prevention.md) | English
+
+## Design Goals
+
+Sleep prevention must satisfy three goals at once:
+
+- Prevent idle sleep while an eligible Codex task exists
+- Restore system settings reliably after app exit, crash, or disconnection
+- Never overwrite a system sleep setting already owned by the user or another app
+
+The regular app process owns policy and UI. CodexBarHelper executes only constrained system sleep and wake operations:
+
+```text
+CodexActivityMonitor
+ -> KeepAliveController
+ -> App IOKit assertion
+ -> XPC lease
+ -> CodexBarHelper
+ -> /usr/bin/pmset
+
+AutoResetController
+ -> AutoResetWakeScheduler
+ -> XPC wake date
+ -> CodexBarHelper
+ -> IOPMSchedulePowerEvent
+```
+
+## Why This Is Not an Assertion Switch
+
+Sleep prevention looks like one Boolean setting but spans user intent, live tasks, power state, app lifecycle, and root system state. Any layer can change before another, so `isEnabled` cannot mean that system sleep is already disabled.
+
+State is split into four layers:
+
+| Layer | Representative field | Question answered |
+| --- | --- | --- |
+| User intent | `isEnabled` | Does the user want the feature? |
+| Decision condition | `sleepBlockReason` | Are activation conditions currently met? |
+| Request state | `appliedSleepPreventionRequested` and `requestInFlight` | What did the app most recently request from the helper? |
+| Confirmed effect | `isPreventingSleep` and `sleepPreventionSource` | Has the app received evidence that system state matches? |
+
+This distinction resolves two issues often hidden by UI:
+
+- Temporary helper unavailability preserves the user's switch, allowing automatic recovery without requiring them to enable it again
+- UI does not claim success after an XPC request but before confirmation, avoiding disagreement with actual system state
+
+`sleepBlockReason` is the sole decision output for all conditions. Derived UI state, condition logging, and actual switching read the same result. Every new condition must use a finite `switch` to state whether the settings entry remains available. This intentionally prevents omissions.
+
+## Why App Assertions and System Settings Coexist
+
+The mechanisms have different scopes:
+
+| Mechanism | Lifetime | Effect | How it ends |
+| --- | --- | --- | --- |
+| IOKit assertion | App process | Prevents idle system sleep and optionally display sleep | Reclaimed automatically after app exit |
+| `pmset disablesleep` | System-wide | Covers system-sleep paths not guaranteed by assertions | Requires explicit restoration, ownership, and a watchdog |
+
+Assertions are cheap to recover but incomplete. `pmset` is stronger but can leave global state after a crash. CodexBar uses both and delegates high-risk global state to a least-privileged helper.
+
+The app assertion is established before XPC acquisition begins so there is no idle-sleep gap while the helper switches state. A shared cleanup path releases it after helper failure, preventing a half-success known only to the app.
+
+## Acquisition and Release Are Confirmed Transactions
+
+Acquisition does not optimistically change UI and patch system state later. It is verified:
+
+```text
+Conditions allow activation
+ -> Establish app idle assertion
+ -> Mark that helper may have received a lease
+ -> Send generation-tagged XPC request
+ -> Helper reads current SleepDisabled
+ -> Write and read back when needed
+ -> App validates source and measured value
+ -> Publish active state and begin duration accumulation
+```
+
+Release converges in the opposite direction:
+
+```text
+Conditions block activation
+ -> Ask helper to revoke lease
+ -> Helper restores system value only when owned and no leases remain
+ -> App receives measured result
+ -> Publish inactive state and release display assertion
+ -> Stop duration accumulation
+ -> Submit low-battery or duration-limit notification
+ -> Release app idle assertion
+ -> Compensate for lid-close sleep if needed
+```
+
+Notifications come after the helper confirms `SleepDisabled=0`, ensuring that “sleep prevention stopped” describes fact rather than pending intent.
+
+The app idle assertion remains until notification submission ends. A closed-lid Mac may sleep immediately after global restoration; releasing the last assertion first could prevent the request from reaching the notification system. CodexBar then releases it immediately and compensates for the lid edge without reclaiming system ownership.
+
+## Why `mayHaveHelperLease` Survives a Timeout
+
+An XPC timeout proves only that the app received no reply, not that the helper did not execute the request. The helper may hold the lease while its reply was lost during disconnect.
+
+`mayHaveHelperLease` therefore uses conservative semantics:
+
+- Set `true` immediately when requesting acquisition
+- Remain `true` after timeout or connection invalidation
+- Change to `false` only after an explicitly confirmed release
+
+This may add one idempotent release during exit, but that is far cheaper than leaving global `SleepDisabled=1`.
+
+## The Race Solved by Generation
+
+The user may turn off the switch, a task may finish, and retry may start before an earlier XPC reply returns. Applying replies by arrival order could let old acquisition success overwrite newer release success.
+
+Both app and helper use monotonically increasing generations:
+
+- The app accepts callbacks only for current `requestGeneration`
+- The helper ignores requests older than a lease's current generation
+- Invalidating a connection advances app generation so in-flight callbacks become stale
+
+Generation is not a logging sequence number. It proves eligibility to commit asynchronous state.
+
+## Activation Conditions
+
+[`KeepAliveController.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveController.swift) establishes sleep prevention only when all conditions hold:
+
+- Prevent System Sleep is enabled
+- Hook is enabled and validated
+- At least one live task qualifies under settings
+- CodexBarHelper is installed and connectable
+- The low-battery threshold is not active
+- The per-period maximum duration has not been reached
+- The app is not terminating
+
+Waiting-for-approval tasks do not count by default but can be enabled separately. Tasks suppressed by Activity Protection no longer maintain sleep prevention.
+
+`KeepAliveController` first removes `isAnonymous` tasks from running and waiting snapshots. Only non-anonymous tasks can enter active sets, begin a new duration period, or keep sleep prevention alive.
+
+The controller publishes an explicit blocking reason:
+
+| Reason | Meaning |
+| --- | --- |
+| `notStarted` | Service has not started |
+| `userOff` | User turned off the master switch |
+| `hookDisabled` | Hook is not operational |
+| `noTasks` | No task qualifies |
+| `helperUnavailable` | CodexBarHelper is not installed or connectable |
+| `helperRefreshing` | CodexBarHelper state is recovering or being confirmed |
+| `terminating` | App is quitting |
+| `lowBattery` | Battery is below the threshold |
+| `limitReached` | Per-period duration limit was reached |
+
+## App-Side Assertions
+
+[`SystemSleepService.swift`](../../../CodexBar/Services/KeepAlive/SystemSleepService.swift) creates an IOKit `PreventUserIdleSystemSleep` assertion.
+
+If Keep Display Awake is enabled, it also creates `NoDisplaySleep` and declares user activity every 30 seconds so display idle timing does not activate early.
+
+App assertions cover only the current process. CodexBarHelper manages system-level `SleepDisabled` to cover sleep paths assertions cannot guarantee.
+
+## CodexBarHelper Installation and Communication
+
+CodexBarHelper registers as a LaunchDaemon through `SMAppService`. The app and helper use the XPC interface in [`CodexBarHelperXPC.swift`](../../../Shared/CodexBarHelperXPC.swift).
+
+The interface exposes only four capability classes:
+
+- Set or revoke an app lease
+- Query helper runtime and ownership state
+- Reset helper state after an app update
+- Set or cancel the next Automatic Reset `wake` event for CodexBar's fixed owner
+
+Automatic Reset and sleep prevention share helper registration and macOS approval but use separate XPC connections. Enabling Automatic Reset attempts helper registration even when Prevent System Sleep is off; while approval is pending, its setting row shows the same state and `Open System Settings` entry.
+
+Settings separates user confirmation, helper registration, and navigation to Helper authorization:
+
+- `HelperFeatureConfirmation` presents one shared dialog whenever Automatic Reset or Prevent System Sleep changes from off to on
+- `.notRegistered` and `.notFound` explain that background installation and authorization are required; `.requiresApproval` explains that installation succeeded but authorization is pending; `.enabled` shows only the feature description
+- Only user confirmation calls `AutoResetSettings.setEnabled(true)` or `KeepAliveController.setEnabled(true)`; cancellation does not write enabled state
+- `ensureHelperRegistration()` handles registration, refresh, and coordination only; it does not open authorization settings
+- `AppSettingsView` shows `Open System Settings` only for an enabled row in `.requiresApproval`; the button calls `KeepAliveController.openSystemSettings()`
+- Automatic Reset options require its switch on and `helperStatus == .enabled`; losing that condition closes an open panel
+- Sleep-prevention options read `KeepAliveController.canShowOptions`; settings remain adjustable with no task, low-battery block, limit reached, or helper refresh
+- Automatic Reset and sleep-prevention rows show no status explanation while their switches are off
+
+Wake schedules converge from actual system state rather than depending only on normal-exit cleanup:
+
+- Before opening the XPC listener on every startup, the helper removes stale events for its fixed owner; after reconnect, the app reschedules from the latest target
+- Set succeeds only after read-back finds exactly one time-matching event; cancel succeeds only after read-back finds none
+- A corresponding XPC disconnect abandons the in-memory owner immediately; failed cancellation enters pending cleanup and retries on a short helper cycle
+- App exit waits separately for wake-schedule and sleep-lease release; helper update freezes wake synchronization first and explicitly cancels when the current process has a wake connection or applied time
+- Before unregistering the helper, `Scripts/cleanup.swift` checks the fixed owner and stops if it cannot cancel and confirm an empty schedule, avoiding removal of the last process able to clean it; after successful unregister it turns off both sleep prevention and Automatic Reset so the next app launch does not reregister
+
+Each app process creates a stable `clientSessionID` that survives XPC reconnection. Every lease change carries a monotonically increasing generation, and CodexBarHelper accepts only newer requests:
+
+- One XPC request times out after 10 seconds
+- Lost connections have a 15-second watchdog grace period
+- CodexBarHelper checks leases and system state every 5 seconds
+- Abnormal state retries recovery every 60 seconds
+
+## CodexBarHelper Privilege Boundary
+
+[`CodexBarHelper/main.swift`](../../../CodexBarHelper/main.swift) runs as root but is intentionally constrained:
+
+- System sleep switching invokes only fixed `/usr/bin/pmset`
+- It uses only fixed arguments to read or toggle `disablesleep`
+- It sets or cancels one system wake event with a fixed owner and fixed `wake` type
+- The wake interface accepts only bounded timestamps, never arbitrary owners, event types, or commands
+- It accepts no arbitrary command or arguments
+- It does not access Hook, rollout, account, or log data
+- It performs no network access
+- It does not determine Codex task state
+
+CodexBarHelper derives the client code-signing requirement from its own signature and applies it to the XPC listener. A client that fails the signing requirement cannot establish a control connection.
+
+## System-State Ownership
+
+CodexBarHelper first reads the current value with:
+
+```bash
+/usr/bin/pmset -g
+```
+
+When system-level prevention is needed, it runs only:
+
+```bash
+/usr/bin/pmset -a disablesleep 1
+```
+
+On release it runs:
+
+```bash
+/usr/bin/pmset -a disablesleep 0
+```
+
+Ownership rules prevent damage to external state:
+
+- If the initial observed value is already `1`, the helper marks it external
+- CodexBar does not claim external state
+- CodexBar records owned only after personally completing `0 -> 1`
+- Only owned state may restore to `0` when leases end
+
+Thus, `SleepDisabled=1` set earlier by a user or another tool remains on after CodexBar exits.
+
+### How the Ownership File Forms a Recovery Transaction
+
+Persistence deliberately favors recoverability:
+
+```text
+Acquire: persist owned -> pmset 1 -> read back 1
+Release: persist restoring -> pmset 0 -> read back 0 -> persist idle
+```
+
+Acquisition persists owned first. A crash after file write but before `pmset 1` causes one extra idempotent `pmset 0` at next start rather than leaving global sleep disabled. Writing the system value first could crash before recording restoration responsibility.
+
+Release persists restoring first. A crash before `pmset 0` or final idle commit still leaves a known incomplete restoration. Idle may persist only after read-back confirms system value `0`.
+
+### Taking Over After an External Source Disappears
+
+`external` is not a permanent decision. While eligible tasks remain, CodexBar periodically reads system state cached by the helper:
+
+- Continue borrowing `SleepDisabled=1` without writing while the external source remains
+- If it disappears while a task remains, reacquire a lease and let the helper perform a new `0 -> 1`
+- If another valid client already made helper state owned, update source presentation without restarting the duration period
+
+This avoids a subtle gap: another tool disables sleep first, so CodexBar reports external; that tool later restores sleep while the task still runs. Without observation, the UI would continue claiming prevention while the system could sleep.
+
+## CodexBarHelper State Persistence
+
+CodexBarHelper stores ownership at:
+
+```text
+/Library/Application Support/CodexBar/helper-state.json
+```
+
+Security and reliability requirements are:
+
+- Current schema is `1`
+- Directory is root-owned with `0755` permissions
+- Directory is not group- or world-writable
+- File is root-owned with `0600` permissions
+- Commits use a temporary file, full sync, and atomic rename
+- If a trusted owned record cannot be read at startup, recover to `disablesleep 0`
+
+The file records CodexBar's ownership of system sleep settings.
+
+Automatic Reset wake events are not stored there. macOS power management persists them under an identity formed from the current Debug or Release helper mach service plus `.auto-reset`, with fixed type `wake`.
+
+## Leases and Failure Recovery
+
+While the app has eligible tasks, it holds an identified XPC lease. CodexBarHelper does not interpret one request as permanent authorization detached from its connection:
+
+```text
+Lease valid -> Keep owned state
+Connection briefly lost -> Wait 15-second watchdog
+Reconnect within grace -> Continue with the same clientSessionID
+Grace expires -> Revoke lease and restore owned state
+```
+
+After abnormal exit, connection invalidation, the watchdog, and persisted ownership together restore system settings.
+
+Normal app exit first cancels the Automatic Reset wake schedule, then revokes the lease and IOKit assertion. If the helper has not confirmed both root-state categories clean, app termination waits instead of leaving under uncertainty.
+
+### Why Normal Exit Can Be Canceled
+
+`applicationShouldTerminate` cannot approve exit before confirmed release. `prepareForTermination()` stops new retries, cancels a possible Automatic Reset wake schedule, requests release of a possible lease, and waits for helper read-back:
+
+- Continue termination after successful release
+- Cancel this termination and resume normal condition evaluation and retries after failure
+
+Canceling exit is stricter than simply closing, but it is part of recoverability. Normal exit is the app's only opportunity to confirm root global state actively and should not discard it. Forced exit still falls back to the helper's 15-second watchdog.
+
+### Helper Self-Check Is More Than Process Liveness
+
+The helper checks leases, ownership records, and measured `SleepDisabled` independently:
+
+- While owned with leases, reestablish `1` if another source changes the system value to `0`
+- While owned without leases, restore `0`
+- While external, observe only and never persist external state as owned
+- On an untrusted persistence record, fail safe by restoring rather than treating corruption as permission to remain active
+- If Automatic Reset cancellation failed and no connection owner remains, reread and clean the fixed owner every 5 seconds
+
+Periodic checks supplement event-driven XPC by repairing drift after another process changes settings, a callback is lost, or a process restarts.
+
+## Duration and Battery Policy
+
+The per-period duration counts only time when sleep prevention is actually active:
+
+- Pause or reset when no task exists
+- A new task period can receive a fresh budget
+- Default limit is 12 hours
+- Choices are 1, 2, 4, 8, 12, or 24 hours, or unlimited
+
+Low-battery stopping applies only on battery power:
+
+- Threshold options are 5%, 10%, 15%, 20%, and 25%
+- Off by default
+- Recovery uses 5 percentage points of hysteresis to prevent toggling near the threshold
+
+When low battery or duration limit stops prevention, notification must follow confirmed sleep restoration.
+
+### Defining a Duration Period
+
+“Maximum per-period duration” is accumulated time that CodexBar actually blocks system sleep, not wall time from task appearance to disappearance.
+
+`KeepAliveDurationLimiter` uses `SuspendingClock`:
+
+- The clock pauses in system sleep, so sleeping time does not count as prevention
+- Accumulation pauses while helper is unavailable, low battery blocks, or another condition prevents activation
+- A new running task begins a new period
+- A waiting task resuming running begins a new period
+- Refreshing snapshots for the same task set across running and observation does not reset repeatedly
+
+`hasReached` is sticky for the current period. An ordinary snapshot refresh cannot immediately reactivate after the limit; only a clearly new task period or a settings change reevaluates it.
+
+The task set uses stable task IDs to detect “new task” and “resumed from waiting,” not count alone. If one task ends as another starts, count remains one, but the new task deserves a full budget.
+
+### Why Battery Reading Has Three States
+
+Battery reads use `unavailable`, `unreadable`, and `present` rather than one optional value:
+
+| State | Meaning | Policy |
+| --- | --- | --- |
+| `unavailable` | Confirmed no built-in battery | Hide low-battery settings and clear the block |
+| `unreadable` | IOKit read failed this cycle | Preserve the previous decision |
+| `present` | Trusted level and power source | Evaluate the threshold normally |
+
+Preserving state through one read failure prevents the row from flickering and avoids transiently disabling active low-battery protection. Once a machine has reported a battery, a later empty list is `unreadable` because hardware cannot disappear at runtime.
+
+Battery use comes from power-source state, not `isCharging`. A connected Mac that has stopped charging also reports `isCharging == false`, but tasks are not draining its battery.
+
+### Low-Battery Latch and Hysteresis
+
+For threshold `T`, protection enters while on battery at or below `T` and exits only at or above `T + 5`.
+
+The five points are state-machine hysteresis, not a display adjustment. Without it, measurement noise near the threshold would repeatedly cause root writes, assertion switches, and notification checks.
+
+Low-battery notification has a per-period latch:
+
+- Queue it only if CodexBar previously prevented sleep
+- Record it as notified only after successful restoration
+- Connecting power clears the current block, but only crossing the recovery threshold ends the latch period
+- Changing the threshold starts a new period so notification state under the old threshold cannot contaminate the new setting
+
+## Display Awake Is a Supplemental Effect
+
+Keeping the display awake depends on confirmed sleep prevention plus the user option; it does not independently maintain system sleep.
+
+`NoDisplaySleep` prevents display sleep but not the screen saver or idle lock, so the app also declares user activity every 30 seconds. It reuses one assertion ID; otherwise `pmset -g assertions` would accumulate same-named entries.
+
+A failed display assertion records its own error without overriding primary sleep-prevention success. This intentionally separates core and supplemental effects so Settings does not report “sleep prevention completely failed” when only the display did not stay awake.
+
+Assertion names use ASCII. On some system versions, Chinese names appear empty in `pmset -g assertions` and lose diagnostic identity.
+
+## Lid-Close Edge Compensation
+
+Lid-close sleep is an edge event. If `SleepDisabled=1` at lid close, later restoring it to `0` does not necessarily make the system reevaluate the missed edge.
+
+After confirming restoration of CodexBar-owned state, CodexBar reads clamshell state. If the lid remains closed and that hardware mode should sleep on close, it explicitly requests system sleep once.
+
+Compensation applies only to `.codexBar` source:
+
+- External state was not changed by CodexBar, so it cannot decide sleep timing for its owner
+- It must not request sleep while `SleepDisabled` remains `1`
+- It does not guess when clamshell state is unreadable
+
+This repairs an edge event and cannot be replaced by merely reaching the correct final value.
+
+## Failure and Retry
+
+Sleep prevention uses bounded retries because each attempt reconstructs a privileged connection and may launch a root process:
+
+- A 10-second request timeout precedes the 15-second helper watchdog; the app abandons the untrusted connection first, then the helper can clean its lease
+- Recompare desired state before each retry so acquisition stops after the user disables the feature
+- Preserve an explicit error after exhaustion instead of looping forever and consuming resources
+- Release the app assertion immediately on connection invalidation so a degraded UI does not coexist with indefinite process-level idle prevention
+- Invalidate old requests by generation rather than relying on every cancellation path to retract the underlying message
+
+Diagnostics distinguish registration from operation errors. Registration means the helper is missing, awaiting approval, or failed to update. Operation error means an installed helper did not produce a trusted result for one transition.
+
+Automatic Reset wake scheduling uses a separate bounded synchronization policy:
+
+- After set or replace failure, retry at `2s, 4s, 8s, 16s, 32s, 64s`; preserve the error on the Automatic Reset row after exhaustion
+- Before normal exit or helper update, cancel and read back immediately, then after `250ms`, then after `1s`
+- Do not register a system event within 5 seconds of now; the in-app task proceeds directly to deadline execution
+- After XPC loss, clear app-side applied state and recoordinate; the helper simultaneously cancels the fixed event owned by that connection
+
+## CodexBarHelper Updates
+
+An app update may change the bundled helper's signature or content. The app records a CodexBarHelper fingerprint and refreshes installation through `SMAppService` and the reset interface after detecting change.
+
+Validation must cover:
+
+- CodexBarHelper is in the correct app-bundle location
+- LaunchDaemon plist matches the Debug or Release bundle ID
+- App and helper signatures match expectations
+- First-time system authorization completes
+- Old owned state restores safely after update
+- Automatic Reset wake schedules are canceled before update and recreated from the current target after the new helper is ready
+
+## Manual Validation Matrix
+
+- App assertion and CodexBarHelper lease switch together when a running task starts and ends
+- Eligible-task decisions are correct with Keep Awake While Waiting off and on
+- If an external source sets `disablesleep 1` first, CodexBar neither claims ownership nor restores `0`
+- Normal app exit restores owned state
+- Forced exit or XPC disconnect lets the watchdog restore owned state
+- Automatic Reset and sleep prevention show confirmation every time they are enabled and remain off after cancellation
+- Confirmation text and feature descriptions are correct for unregistered, awaiting-approval, and approved helper states
+- Enabling only triggers helper registration; authorization settings opens solely from `Open System Settings` on the row
+- Automatic Reset options appear only when enabled and approved and close when that condition fails
+- Automatic Reset can register and gain approval while sleep prevention remains off
+- Future thresholds and retries retain one `wake` event for the fixed owner and do not affect other owners when replaced
+- Disabling Automatic Reset, changing its target, and normal exit each confirm the schedule is empty by read-back
+- An Automatic Reset XPC disconnect or helper restart cleans stale schedules
+- `Scripts/cleanup.swift` unregisters the helper only after the fixed-owner schedule is confirmed empty
+- Reaching the duration limit restores sleep before notifying
+- Low-battery triggering and 5% hysteresis recovery work correctly
+- Hiding a task through Activity Protection releases sleep prevention
+- Debug and Release CodexBarHelper instances are never mixed
+
+## Key Source Files
+
+- [`KeepAliveController.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveController.swift)
+- [`SystemSleepService.swift`](../../../CodexBar/Services/KeepAlive/SystemSleepService.swift)
+- [`HelperRuntimeStatusMonitor.swift`](../../../CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift)
+- [`AutoResetWakeScheduler.swift`](../../../CodexBar/Services/KeepAlive/AutoResetWakeScheduler.swift)
+- [`KeepAliveDurationLimiter.swift`](../../../CodexBar/Services/KeepAlive/KeepAliveDurationLimiter.swift)
+- [`PowerSourceMonitor.swift`](../../../CodexBar/Services/KeepAlive/PowerSourceMonitor.swift)
+- [`CodexBarHelperXPC.swift`](../../../Shared/CodexBarHelperXPC.swift)
+- [`CodexBarHelper/main.swift`](../../../CodexBarHelper/main.swift)
diff --git a/Docs/en/DeveloperGuide/sync.md b/Docs/en/DeveloperGuide/sync.md
new file mode 100644
index 0000000..5ff0773
--- /dev/null
+++ b/Docs/en/DeveloperGuide/sync.md
@@ -0,0 +1,347 @@
+# CloudKit Sync
+
+[简体中文](../../DeveloperGuide/sync.md) | English
+
+## Sync Scope
+
+CloudKit sync merges daily Hook metrics across Macs signed in to the same iCloud account.
+
+It syncs aggregated results, not raw Hook events:
+
+```text
+Local raw Hook JSONL
+ -> Local daily aggregation
+ -> Current-device CloudKit record
+ -> Download records from other devices
+ -> Merge by date for display
+```
+
+Account data, rate limits, total tokens, Reset Credits, Automatic Reset settings and state, live tasks, and sleep-prevention state do not sync.
+
+## Goals and Non-Goals
+
+Sync does not replicate one Mac's database. It safely adds independent contributions from multiple devices for the same day.
+
+Its priorities are:
+
+1. Do not upload raw work content or identities directly tied to hardware
+2. Local metrics must remain displayable without CloudKit
+3. Rescans and file replacement must not create duplicate counts
+4. Preserve the last explainable remote snapshot during network failure
+5. Retries must be idempotent rather than depending on exactly-once requests
+
+The sync protocol explicitly excludes:
+
+- Live task state, which changes quickly and requires low-latency local evaluation
+- Account rate limits, which belong to the Codex account rather than device work history
+- Automatic Reset, whose multi-device convergence uses a deterministic idempotency key for the same `creditId`, not CloudKit locks or task records
+- Sleep-prevention state, which is a system side effect on the current Mac
+- Raw events, because cross-device statistics need only mergeable daily facts
+
+Placing sync after aggregation also improves maintenance: the raw Hook format can evolve independently while CloudKit sees a stable daily projection.
+
+## Sources of Authority
+
+Synced presentation combines three kinds of values:
+
+| Data | Authoritative source | Offline behavior |
+| --- | --- | --- |
+| Current-device contributions for today and history | Local `daily.jsonl` | Continues updating live |
+| Contributions from other devices | Last successfully fetched records in `cache.jsonl` | Preserves the last snapshot |
+| Upload confirmation and incremental position | `state.json` and `cursor.data` | Continues or rebuilds next time |
+
+The current device is always local-first. Its CloudKit copy exists for other devices, not as truth for its own UI. This rule avoids a value appearing once locally and then doubling after a round trip to the cloud.
+
+The remote cache is a rebuildable projection, and the cursor is only an optimization. Any cursor failure can fall back to a full custom-zone read without requiring the user to delete local files.
+
+## CloudKit Structure
+
+[`WorkflowSyncService.swift`](../../../CodexBar/Services/Workflow/WorkflowSyncService.swift) uses the app's CloudKit private database:
+
+| Item | Value |
+| --- | --- |
+| Container | `iCloud.app.zabrian.codexbar` |
+| Custom zone | `CodexBarZone` |
+| Metadata record type | `CodexBarSyncMetadata` |
+| Daily aggregate record type | `CodexBarDailyAggregate` |
+
+Private-database content belongs only to the current iCloud account and is never written to the public database.
+
+The custom zone is more than a namespace. It provides zone change tokens and deletion events so devices can sync additions, modifications, and deletions incrementally instead of scanning the entire private database each cycle.
+
+Confirmed zone state and the account salt are cached in the actor across sync cycles, avoiding two fixed network round trips each time. Any sync failure invalidates both because an iCloud account switch may first appear as a request failure. Reconfirming next cycle is safer than continuing with the wrong account context.
+
+## Activation Conditions
+
+Sync runs only when all conditions hold:
+
+- The user enabled CloudKit sync
+- Hook is enabled and validated
+- The current iCloud account is available
+- The local aggregation service is available
+
+First enable marks a backfill and uploads dates within local retention that need synchronization. Scheduling has a minimum 8-second cooldown to coalesce several local changes.
+
+## Device Pseudonymization
+
+Sync must distinguish device contributions without uploading a raw hardware identifier:
+
+1. Create a random 32-byte account salt in the private database
+2. Read the local `IOPlatformUUID`
+3. Compute HMAC-SHA256 of the UUID with the account salt
+4. Use the result as the cloud `deviceId`
+
+The raw `IOPlatformUUID` is never uploaded. One device receives a stable pseudonym within one iCloud account and a different value in another account.
+
+HMAC is used instead of plain SHA-256. Hardware UUIDs have a fixed input format, so a simple hash would remain stable across accounts. A private per-account salt makes the same hardware unlinkable across accounts.
+
+The salt lives in the same private custom zone. If several devices attempt initial creation, they converge on the existing record by reading it after a CloudKit conflict instead of keeping incompatible salts.
+
+Local state records the most recently resolved `deviceId`. If it changes, sync clears the old cursor and remote cache while retaining pending replacement dates. A device-identity change means the cached account scope is untrusted and cannot continue incrementally.
+
+## Daily Aggregate Fields
+
+Each daily record contains:
+
+- Schema
+- Device ID pseudonym
+- Date
+- Source generation
+- Hook event counts
+- Session and turn counts
+- Project counts
+- Model counts
+- Update time
+
+It does not upload:
+
+- Raw Hook JSONL
+- Raw session or turn IDs
+- Full working directories
+- Prompt or response content
+- Codex account or rate-limit data
+- Tokens or files such as `auth.json`
+- App request logs
+- Stalled Task Protection state
+
+For complete boundaries, see [Data and Privacy Boundaries](data-and-privacy.md).
+
+## One Sync Cycle
+
+```text
+Confirm iCloud account
+ -> Create or confirm custom zone
+ -> Read account salt and resolve device pseudonym
+ -> Read local sync state and cache
+ -> Upload changed dates for this device
+ -> Fetch remote changes
+ -> Update the local CloudKit cache
+ -> Prune records outside retention
+ -> Publish merged results
+```
+
+The implementation intentionally performs a fetch before upload:
+
+- Before uploading, it must know whether a same-device, same-day remote record exists so it can update, create a generation record, or skip
+- Before replacement, it must perform a full fetch to discover old generations that an incremental cache may have missed
+- It fetches again after upload to merge this cycle's writes and concurrent writes from other devices into the local cache
+- It prunes expired records last so a pruning failure cannot block valid uploads in the same cycle
+
+Every stage writes a `stage` field to logs, so an error identifies zone, device, fetch, upload, or prune instead of reporting only a generic CloudKit error:
+
+- Upload batches contain at most 25 records
+- One batch waits at most 20 seconds
+- A fetch page contains at most 200 changes
+- SHA-256 hashes of local content skip unchanged records
+
+The 20 seconds is a budget for the complete upload cycle, not a per-record timeout. After the budget is reached, remaining dates stay unconfirmed for a later schedule. A historical backfill therefore does not occupy the actor and user-visible refresh path indefinitely.
+
+Stable JSON for each date is encoded and hashed once, and the same result drives filtering and success confirmation. Re-encoding in different phases could let dictionary order or optional fields make change detection drift.
+
+Uploads use `atomically: false`. On partial batch success, each CloudKit result is confirmed separately, while failed dates lose their local hash so they retry. The protocol relies on idempotent single-record identity rather than requiring all 25 records to succeed together.
+
+## Merge Semantics
+
+One day may have records from several devices plus a newer local result that the current device has not uploaded yet.
+
+Merge rules are:
+
+- Add contributions from other devices by field
+- Replace the current device's same-source cloud contribution with its latest local aggregation
+- Count a source generation at most once
+- Add generations confirmed to represent independent sources
+- Use a current-device cloud contribution only when local data is missing
+
+Replacing the current device's cloud value with its local value prevents double counting when sync just uploaded but the local UI was already updated.
+
+### Why One Device Can Have Multiple Records for One Day
+
+Legacy record names contain only `deviceId + date`. New source records may use `deviceId + date + sourceGeneration`.
+
+A generation record identifies one raw source. Same-source local and cloud results replace one another, while clearly distinct sources may represent independent contributions created on the same day.
+
+The read layer first finds the record matching local `sourceGeneration`. It uses whichever local or remote copy is more complete and continues adding other generations. A legacy record has no generation, but identical content can still be treated as the same source for compatibility.
+
+The system does not infer “all old generations are invalid” from generation values. An explicit `replacementDates` transaction expresses that intent. This distinction preserves independent contributions during normal source rotation while allowing a user-requested full rebuild to remove historical copies.
+
+Upload targets follow these rules:
+
+| Remote state | Local source | Action |
+| --- | --- | --- |
+| No record for the date | Any | Create a legacy or generation record |
+| Same-source record exists | Local is at least as complete as remote | Update that record |
+| Same-source remote has more events | Local has a generation | Keep remote so a shorter stale scan cannot overwrite a more complete result |
+| Other-source record exists | Local source is fresh | Create a record for the current generation |
+| Other-source record exists | Local source is not fresh | Skip and wait for an authoritative rebuild |
+
+`sourceIsFresh` describes the completeness of the raw source for one read, not its timestamp. A newer timestamp is not more authoritative while a file is replaced, truncated, or awaiting stable-boundary confirmation.
+
+### Why Missing Cannot Become Zero
+
+As the CloudKit record schema evolves, an old record may lack a new count field. `nil` means that device cannot provide the metric for that day; `0` means it explicitly observed zero occurrences.
+
+Preserving availability during merge lets the UI distinguish “all devices total zero” from “some historical sources do not support this metric.” Decoding missing as zero creates a false fact that cannot be repaired later.
+
+## Source Replacement and Rebuild
+
+When a raw Hook file is replaced or fully rebuilt, the aggregation layer changes its source generation. Sync must interpret this as replacement rather than adding old and new generations.
+
+When the user requests a rescan:
+
+1. Local aggregation rebuilds from raw JSONL
+2. Affected dates are marked for replacement
+3. Cloud records for those dates on the current device are overwritten or deleted and recreated
+4. Other-device records remain unchanged
+
+This design limits a rebuild to correcting the current device's contribution.
+
+### Why Replacement Is a Persistent Transaction
+
+Rebuild and CloudKit synchronization may not finish in one process lifetime, so `replacementDates` persists in `state.json` instead of memory only.
+
+For each replacement date, sync:
+
+1. Rebuilds the remote cache in full
+2. Enumerates all known legacy and generation record IDs for that date on the current device
+3. Deletes those contributions, treating `unknownItem` as idempotent success
+4. Removes the date from the local hash table to force reupload
+5. Clears the replacement marker only after confirming the new content
+
+While replacement is in progress, the snapshot filters the current device's cloud cache for that date and shows the latest local aggregation. Even if the app quits between deletion and reupload, the UI does not add the old cloud contribution to the new local contribution.
+
+The full fetch before deletion is the crucial detail. An incremental cursor guarantees completeness only after its position; it cannot prove that an older app or manual deletion never caused the local cache to miss records. Full enumeration prevents ghost generations from remaining.
+
+## Incremental Cursor and Local Cache
+
+Sync state lives at:
+
+```text
+~/Library/Application Support/CodexBar/HookEvents/Sync/
+```
+
+| File | Purpose |
+| --- | --- |
+| `state.json` | Sync schema, local hashes, backfill, and replacement state |
+| `cache.jsonl` | Cached daily aggregates from remote devices |
+| `cursor.data` | CloudKit zone change token |
+
+The current CloudKit record schema is `5`. The local sync-state schema is `4` and can read the previous schema `3`.
+
+The three files have different recovery costs:
+
+| File | Cost if lost | Recovery |
+| --- | --- | --- |
+| `state.json` | Loses upload hashes and replacement progress | Recompare and upload; replacement depends on markers that still exist |
+| `cache.jsonl` | Temporarily loses other-device contributions | Full custom-zone fetch |
+| `cursor.data` | Loses incremental position | Full fetch and new baseline |
+
+`cursor.data` stores the opaque CloudKit token with secure coding; code does not inspect its structure. After a full fetch, sync must also create a new cursor baseline, or the next cycle may consume all recently fetched changes again from an empty cursor.
+
+The local `3 -> 4` read path rebuilds the remote cache before committing new state. An unknown schema falls back to empty sync state because misinterpreting upload confirmations is more dangerous than resynchronizing.
+
+Any change to record fields, identity, or schema is a compatibility decision. It must account for old apps still writing, new apps reading old fields, and whether downgrade can overwrite new records—not merely increment a constant.
+
+## Why the Scheduler Is Separate
+
+Local maintenance and CloudKit sync share aggregation input but require different trigger rates. `WorkflowSyncScheduler` coalesces triggers into a single-threaded state machine.
+
+Priority is:
+
+```text
+User-requested rebuild > Sync maintenance ready now > Local-only maintenance > Sync in cooldown
+```
+
+Important details include:
+
+- Requests during the 8 seconds after a sync finishes merge into the next cycle so one Hook burst does not trigger many network operations
+- Merged requests retain the earliest trigger because it is the real cause of the cycle
+- A rebuild cancels completion for an earlier rebuild that has not started, preventing a caller from waiting forever
+- Disabling sync during a wait clears pending sync but still allows required local maintenance
+- `@Published` subscriptions run during `willSet`, when rereading the property returns the old value, so activation is calculated explicitly from the new callback argument
+
+The last detail is easy to break while “cleaning up” Combine lifecycle code. Rereading settings appears simpler but would decide synchronization using the old value.
+
+## Failure and Recovery Semantics
+
+A sync failure neither rolls back independently confirmed records nor clears the last usable cache. The next cycle converges through hashes, record IDs, and idempotent CloudKit APIs:
+
+| Failure point | Preserved state | Next cycle |
+| --- | --- | --- |
+| Zone or account confirmation | Local aggregation and old cache | Reconfirm zone and salt |
+| Incremental fetch | Old cache | Fall back to a full rebuild |
+| Partial upload | Hashes for successful dates | Retry only unconfirmed dates |
+| Replacement deletion | Replacement marker | Re-enumerate and delete idempotently |
+| Prune | In-retention data and upload results | Prune later |
+
+Account-level caches are invalidated after failure, but the disk cache is not immediately published as fact for a new account. The sync snapshot returns only after availability and device identity are confirmed again.
+
+## Checklist for Sync Protocol Changes
+
+1. Define field semantics first, especially whether missing, zero, and empty collections differ
+2. Decide whether record identity remains idempotent
+3. Evaluate concurrent writes by old and new app versions
+4. Define upgrade or rebuild paths for local state, cache, and cursor
+5. Confirm replacement can delete every old generation
+6. Recheck privacy boundaries and explicit opt-in
+7. Validate eventual convergence with two devices and an interrupted cycle
+
+## Retention and Pruning
+
+CloudKit records share the local Hook-history retention period of up to 210 days:
+
+- Expired local raw data and daily aggregations are deleted
+- Expired cloud records for the current device enter pruning
+- Expired dates are removed from the local remote cache
+- Prune failure does not affect in-retention display
+
+## Error Classification
+
+The sync layer distinguishes these states for Settings and notifications:
+
+- Network unavailable
+- iCloud account unavailable
+- CloudKit service unavailable
+- Server requested a later retry
+- Local data or schema incompatible
+- Sync succeeded or had no changes
+
+Transient errors preserve the last usable remote cache. After account switching or identity invalidation, old-account cache must not be presented as current-account data.
+
+## Manual Validation Matrix
+
+- First enable uploads local aggregations within retention
+- A second device merges contributions without duplicating the current device
+- Disabling sync shows local metrics only
+- When iCloud is signed out, the app shows a clear state and local metrics keep working
+- After network loss, the app uses the last cache and completes incremental sync on recovery
+- A local rebuild replaces only current-device records
+- Local and remote cache older than 210 days is pruned
+- Switching iCloud accounts does not show cache from the previous account
+
+## Key Source Files
+
+- [`WorkflowSyncService.swift`](../../../CodexBar/Services/Workflow/WorkflowSyncService.swift)
+- [`WorkflowSyncScheduler.swift`](../../../CodexBar/Services/Workflow/WorkflowSyncScheduler.swift)
+- [`WorkflowSyncSettings.swift`](../../../CodexBar/Services/Settings/WorkflowSyncSettings.swift)
+- [`CodexWorkflowModels.swift`](../../../CodexBar/Models/CodexWorkflowModels.swift)
+- [`CodexBar.entitlements`](../../../CodexBar/Resources/CodexBar.entitlements)
diff --git a/Docs/en/DeveloperGuide/ui-and-lifecycle.md b/Docs/en/DeveloperGuide/ui-and-lifecycle.md
new file mode 100644
index 0000000..7d1a705
--- /dev/null
+++ b/Docs/en/DeveloperGuide/ui-and-lifecycle.md
@@ -0,0 +1,327 @@
+# UI and App Lifecycle
+
+[简体中文](../../DeveloperGuide/ui-and-lifecycle.md) | English
+
+## `LSUIElement` Constraints
+
+CodexBar is configured as an `LSUIElement` in [`Info.plist`](../../../CodexBar/Resources/Info.plist).
+
+It has no Dock icon or conventional main-window lifecycle. The menu bar, popover, floating panel, Settings window, and notification clicks must all manage app activation and focus explicitly.
+
+Default SwiftUI `Window` behavior does not cover these cases, so the UI combines SwiftUI content with AppKit controllers.
+
+## UI Responsibilities
+
+SwiftUI declares content; AppKit owns window and event lifecycles:
+
+| Layer | Responsible for | Not responsible for |
+| --- | --- | --- |
+| SwiftUI view | Layout, data presentation, callbacks for user intent | Creating long-lived services, choosing the key window, installing global event monitors |
+| View model and settings | Publishing stable snapshots, saving user settings | Owning windows or evaluating screen coordinates |
+| AppKit controller | Popovers, panels, windows, focus, event monitoring | Reimplementing business state machines |
+| AppDelegate | Assembling and retaining long-lived objects | Specific view layout |
+
+This boundary allows the same menu content to run in an `NSPopover` or fallback `NSPanel`, while preventing SwiftUI identity changes from destroying monitors, XPC connections, or notification services.
+
+## Three Kinds of Focus Under `LSUIElement`
+
+Development must distinguish among:
+
+- Whether the app is active
+- Whether a window is key
+- Whether the menu surface is logically presented
+
+These states do not synchronize automatically. Command-Space, for example, makes the app resign active while the user briefly opens Spotlight; that should not necessarily close the menu. A Settings window may already be visible, but it must not retake key status during the menu's closing animation and cause a flash.
+
+The code therefore does not treat `NSApp.isActive` as the sole truth for the menu. It maintains explicit menu-surface state and the current container, then lets event monitors coordinate activation.
+
+## Service Assembly
+
+[`CodexBarAppDelegate.swift`](../../../CodexBar/Controllers/CodexBarAppDelegate.swift) is the composition root for normal mode. [`StatusItemController.swift`](../../../CodexBar/Controllers/StatusItemController.swift) is responsible only for the menu bar and related window orchestration.
+
+AppDelegate:
+
+- Creates long-lived services, view models, and settings
+- Connects the monitor to notifications and sleep prevention, and assembles the Automatic Reset state machine
+- Starts status refresh and Hook activity reading
+- Creates the status-item controller
+- Installs the global shortcut
+- Configures Sparkle updates
+- Coordinates Automatic Reset wake-schedule cancellation and sleep-prevention release during termination
+
+The composition root retains these objects explicitly so SwiftUI view lifecycle cannot destroy long-running services accidentally.
+
+### Why Startup Order Matters
+
+Normal-mode assembly reflects dependency direction:
+
+```text
+Create settings and data services
+ -> Build view models
+ -> Create status item and window controllers
+ -> Start notification and Automatic Reset side effects
+ -> Start activity monitoring and keep-alive coordination
+ -> Start periodic refresh and update services
+```
+
+Notifications and sleep prevention consume only snapshots or transitions already published by the monitor; they do not control readers upstream. Controllers connect these services through closures, keeping AppKit containers out of the service layer.
+
+Shutdown reverses the order, except for helper-owned system state. AppDelegate first confirms asynchronously that the Automatic Reset wake schedule is canceled and the sleep-prevention lease is released, then allows process termination. See [Sleep Prevention System](sleep-prevention.md) for the transaction.
+
+## Status Bar Icon
+
+The status icon combines app-server loading state, the menu bar rate-limit setting, and the task-activity snapshot.
+
+Task-status priority is:
+
+```text
+Waiting for approval > Running > Recently completed > Recently terminated > Idle
+```
+
+Rendered icons are cached by input state to avoid redrawing on every timed refresh. Inactive or unavailable state is expressed through alpha.
+
+### Separating Image State from Tooltip State
+
+`StatusIconState` contains both image and tooltip inputs, but `renderState` retains only fields that change pixels:
+
+- Active-task duration changes every minute and updates only the tooltip
+- When expired rate-limit data remains visible from cache, the icon and progress indicator use reduced alpha
+- A roughly 0.18-second, 10-frame animation starts only when the indicator dot or rate-limit bar appears or disappears
+- A new render state cancels the previous animation; every frame confirms that its target is still current
+
+Redrawing `NSImage` from the complete state would interrupt animations and add menu bar work whenever timer text changes. Explicit render identity is a small but important performance boundary.
+
+With no status dot or rate-limit bar, the icon remains a template image so the system colors it for light mode, dark mode, and menu bar state. Adding custom colors or a progress bar switches to explicit color rendering.
+
+The tooltip starts a 60-second timer only when a live task duration exists; it does not retain a permanent timer while idle. The app also sets `NSInitialToolTipDelay` to 500 ms so the status explanation for this small click target is easier to discover.
+
+Left-click opens the main panel. Right-click or Control-click opens the context menu.
+
+## Main Panel
+
+The main panel prefers an `NSPopover` with `behavior` set to `applicationDefined`.
+
+CodexBar manages dismissal because:
+
+- The main panel can open Settings, Logs, and side detail panels
+- `LSUIElement` activation changes cause ordinary transient popovers to close incorrectly
+- Side panels must behave as part of one interaction surface
+- Closing needs a consistent fade-out
+
+[`MenuSurfaceDismissMonitor.swift`](../../../CodexBar/Controllers/MenuSurfaceDismissMonitor.swift) observes global and local events. [`MenuSurfaceFadeCoordinator.swift`](../../../CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift) coordinates closing animation.
+
+### Why Opening and Closing Need an Explicit State Machine
+
+`menuSurfaceState` has four states:
+
+```text
+hidden -> opening -> shown -> closing -> hidden
+```
+
+They resolve intermediate states from rapid repeated clicks:
+
+- Toggling in `opening` or `shown` starts closing
+- Toggling in `closing` finishes the old close, then opens a new surface
+- Starting a close cancels delayed refresh and old animations
+- A nonanimated close converges state immediately rather than waiting for an animation completion that will never occur
+
+Checking only `popover.isShown` cannot represent logical opening or fade-out state and cannot cover the fallback panel.
+
+### Why One Monitor Owns Dismissal Rules
+
+The allowed click region for the main panel is a set:
+
+```text
+Current menu window + status item button + all visible side panels
+```
+
+A local monitor handles mouse and keyboard events inside the app, a global monitor handles clicks over other apps, and workspace and window observers handle activation changes. Every path ends in the same `onDismiss` callback.
+
+Special rules include:
+
+- Escape consumes the event and closes the surface
+- Command-Tab allows the system switch and closes the surface
+- Command-Space temporarily suppresses activation dismissal so opening Spotlight does not close the surface accidentally
+- After a click, the code pins `NSVisualEffectView` back to inactive so AppKit background emphasis does not cause a brightness jump
+- After first installing observers, `Task.yield()` performs a second window acquisition and focus pass in case the popover window was not attached yet
+
+Change these rules as a single interaction surface. Adding a separate event monitor to one side panel creates monitor-order and duplicate-dismissal problems.
+
+### Fade Content, Not the Window
+
+AppKit owns the popover's system window, so animating its alpha directly can conflict with system presentation state. `MenuSurfaceFadeCoordinator` animates the active container's content view, then calls the shared close operation.
+
+Auxiliary windows temporarily reject `makeKey()` while closing. Otherwise, an already-open Settings or Logs window can jump to the front for a few frames during menu fade-out.
+
+## Fallback Panel
+
+The status-bar button's screen position may be unavailable or untrusted when a global shortcut fires. [`FallbackPanelController.swift`](../../../CodexBar/Controllers/FallbackPanelController.swift) then presents a floating panel on the screen under the pointer.
+
+The popover and fallback panel host identical SwiftUI content and state. Business logic must not depend on the container type.
+
+### Why the Anchor Needs a Trust Check
+
+A global shortcut may fire before status-item layout completes, while the menu bar is on another display, or when the system temporarily provides no button window. The code validates more than a non-`nil` button:
+
+- The window and screen exist
+- The button is visible and has nonempty bounds
+- The converted screen rect is valid and at least 1 point
+- The rect intersects the target screen frame within a 1-point tolerance
+
+Only then does it use a popover arrow. Otherwise, the fallback panel appears on the screen under the pointer. This prevents AppKit from placing the popover on the wrong display or completely offscreen.
+
+Before showing, the fallback panel constrains its size from the SwiftUI fitting size and the target screen's visible area. Coordinate calculations live in `ScreenGeometry` because AppKit's bottom-left origin, SwiftUI local layout, and multi-display frames are easy to mix up.
+
+## Side Detail Panels
+
+The main panel can open:
+
+- Activity heatmap details
+- Reset Credits details
+- Task Center
+
+These panels are mutually exclusive. Opening one closes the others. Each adds its screen region to the main surface's extra hit regions, so moving or clicking between the main and side panels does not dismiss them accidentally.
+
+All detail panels implement `MenuSideDetailPanel` and register in the `sideDetailPanels` array. Mutual exclusion, main-surface closing, and hit testing all iterate over this one registry.
+
+This scales better than encoding every pairwise close relationship. Adding a fourth panel requires one registry entry rather than six new mutual-exclusion pairs.
+
+The hover-driven heatmap panel may fade before another panel opens; click-driven panels normally close the old panel immediately. This avoids two opposing slide animations at the same screen location.
+
+Related controllers include:
+
+- [`HeatmapDetailPanelController.swift`](../../../CodexBar/Controllers/HeatmapDetailPanelController.swift)
+- [`ResetCreditsPanelController.swift`](../../../CodexBar/Controllers/ResetCreditsPanelController.swift)
+- [`ActivityCenterPanelController.swift`](../../../CodexBar/Controllers/ActivityCenterPanelController.swift)
+- [`SidePanelSupport.swift`](../../../CodexBar/Controllers/SidePanelSupport.swift)
+
+## Settings and Logs Windows
+
+Separate `HostingWindowController` instances manage `NSWindow` for Settings and Logs.
+
+When an `LSUIElement` app opens a normal window, it must temporarily allow that window to become key, activate the app, and transfer focus to the target control. Closing restores menu-bar-app foreground behavior.
+
+Focus recovery waits about 120 ms for AppKit to finish window and activation transitions. This delay coordinates system lifecycle and cannot simply become a synchronous call.
+
+Context-menu actions wait until menu tracking finishes before running, avoiding window creation or activation inside AppKit's menu event loop.
+
+### Auxiliary Window Retention and Placement
+
+`HostingWindowController` lazily creates and reuses one window:
+
+- `isReleasedWhenClosed = false`: closing hides it and preserves the window object and SwiftUI state
+- `.moveToActiveSpace`: reopening follows the current Space instead of switching the user back to an old desktop
+- Placement prefers centering on the status item's screen, then falls back to the window screen or main screen
+- A minimized window is deminiaturized before activation
+
+Settings-window height follows the current tab while pinning the top edge and constraining the window to the visible screen frame. The pinned top prevents the entire window from drifting vertically between tabs and keeps the title bar as a stable visual anchor.
+
+Secondary panels for notifications, Automatic Reset, and sleep prevention are created on demand. Once created, a controller subscribes to content-height updates for its lifetime. Prebuilding every panel at app launch would keep unused UI participating in updates.
+
+When Automatic Reset or Prevent System Sleep changes from off to on, `AppSettingsView` presents a shared confirmation through `HelperFeatureConfirmation`. It combines guidance from `KeepAliveController.HelperStatus` with the feature description and writes enabled state only after user confirmation. An enabled settings row in `.requiresApproval` shows `Open System Settings`.
+
+Each secondary-settings entry uses its own availability decision:
+
+- Notifications reads `NotificationSettings.canShowOptions`
+- Automatic Reset requires `AutoResetSettings.isEnabled` and `KeepAliveController.helperStatus == .enabled`
+- Sleep prevention reads `KeepAliveController.canShowOptions`
+
+When a condition becomes false, Settings sends the corresponding `close` action so an unavailable child panel does not remain visible. Automatic Reset and sleep-prevention rows show no status explanation while their main switches are off.
+
+### The 120 ms Focus Recovery Is Not Business Delay
+
+While the menu closes, `AuxiliaryHostingWindow` temporarily sets `allowsKeyFocus` to false. It waits about 120 ms after closing before restoring it.
+
+This gives AppKit time to complete popover order-out, activation, and key-window recalculation. Removing it may produce an intermittent Settings-window flash only on some machines; treat it as a system event-ordering constraint, not arbitrary wait time.
+
+Right-click menu actions also dispatch on the main queue after `menuDidClose`. Menu tracking is a nested event loop, and creating a window synchronously inside it produces unstable activation order.
+
+## Global Shortcut
+
+[`GlobalHotKeyController.swift`](../../../CodexBar/Controllers/GlobalHotKeyController.swift) uses the Carbon Hot Key API.
+
+Shortcut constraints:
+
+- At least two modifier keys
+- Reject `Command-Space`
+- Reject `Command-Tab`
+- Roll back to the previous working setting if system registration conflicts
+- Reregister immediately after a setting change
+
+The Carbon API fits a menu bar app without a Dock icon and avoids a global keyboard event tap or Input Monitoring permission.
+
+Registration uses try-before-swap:
+
+1. Install a temporary handler and hot key for the candidate shortcut
+2. Release the current registration only after the candidate succeeds
+3. On failure, clean up candidate resources and restore the previous setting
+
+Unregistering first would leave the user without either shortcut after one conflict. `GlobalHotKeyRegistration` releases Carbon references in both explicit invalidation and `deinit` to avoid leaking handlers during reregistration.
+
+At least two modifiers reduce accidental activation. Command-Space and Command-Tab are rejected because they are core system navigation shortcuts and should not be captured even if the registration API occasionally permits it.
+
+## Automatic Refresh and Panel Opening
+
+app-server state refreshes every 60 seconds by default. Opening the panel schedules a refresh after about 160 ms so animation and focus transitions finish before data updates.
+
+The main panel displays a countdown. A double-click triggers manual refresh, avoiding ambiguity between clicking the status item and invoking a button action.
+
+The refresh coordinator merges concurrent triggers so the timer, panel opening, and user action do not issue duplicate requests.
+
+When the panel opens, Hook metrics refresh immediately from local cache, while the app-server request waits about 160 ms. The former is cheap and fills content quickly; the latter may launch a process or make protocol requests, so deferring it reduces first-frame stalls.
+
+`refreshIfNeeded` still performs freshness coalescing; the 160 ms delay is not a second refresh path that bypasses coordination. If the panel closes while waiting, the task is canceled and no request runs for hidden UI.
+
+## Checklist for UI Lifecycle Changes
+
+1. Decide whether the change belongs to SwiftUI content or AppKit container lifecycle
+2. Confirm that the popover and fallback panel behave identically
+3. Test intermediate `opening` and `closing` states, not only stable states
+4. Determine whether a click region belongs to the extra surface
+5. Check whether app-active, key-window, and logical-presentation states can diverge
+6. Ensure tasks and timers are canceled on close and uninstall
+7. Test multiple displays, multiple Spaces, and an untrusted status-item anchor
+8. Open the UI separately from a notification click, global shortcut, and right-click menu
+
+## Localization and Formatting
+
+Simplified Chinese and English interface strings are in [`Localizable.xcstrings`](../../../CodexBar/Resources/Localizable.xcstrings).
+
+Dates, numbers, and percentages follow the system's automatically updating locale. Business models must not hard-code Chinese formatting or consume localized strings as state-machine inputs.
+
+## Automatic Updates
+
+[`AppUpdater.swift`](../../../CodexBar/Services/Updates/AppUpdater.swift) wraps Sparkle:
+
+- The appcast URL comes from app configuration
+- Automatic checks run every 3,600 seconds
+- Settings and the context menu trigger update UI
+- After an update, CodexBar checks CodexBarHelper fingerprint and registration state separately if the helper changed
+
+Release scripts require Developer ID, signing, and notarization credentials and are not part of routine local builds.
+
+## Manual Validation Matrix
+
+- Left-click opens the main panel; right-click and Control-click open the context menu
+- Clicking outside the main panel dismisses it; clicking a side panel does not
+- Heatmap, Reset Credits, and Task Center panels remain mutually exclusive
+- The global shortcut opens the panel with both valid and invalid status-bar anchors
+- Clicking a notification activates the app and opens the panel
+- Focus is correct when opening Settings for the first time, closing it, and reopening it
+- Notification, Automatic Reset, and sleep-prevention child panels remain mutually exclusive, align their top edges with their setting rows, and resize correctly when content changes
+- Opening Settings or Logs from the context menu does not lose focus
+- On multiple displays and with different menu bar locations, the fallback panel appears on the pointer's screen
+- The old shortcut still works after a new shortcut conflicts
+- Panel-open refresh does not stall animation or issue duplicate requests
+
+## Key Source Files
+
+- [`CodexBarAppDelegate.swift`](../../../CodexBar/Controllers/CodexBarAppDelegate.swift)
+- [`StatusItemController.swift`](../../../CodexBar/Controllers/StatusItemController.swift)
+- [`FallbackPanelController.swift`](../../../CodexBar/Controllers/FallbackPanelController.swift)
+- [`MenuSurfaceDismissMonitor.swift`](../../../CodexBar/Controllers/MenuSurfaceDismissMonitor.swift)
+- [`MenuSurfaceFadeCoordinator.swift`](../../../CodexBar/Controllers/MenuSurfaceFadeCoordinator.swift)
+- [`GlobalHotKeyController.swift`](../../../CodexBar/Controllers/GlobalHotKeyController.swift)
+- [`SettingsWindowController.swift`](../../../CodexBar/Controllers/SettingsWindowController.swift)
+- [`LogWindowController.swift`](../../../CodexBar/Controllers/LogWindowController.swift)
+- [`CodexStatusMenuView.swift`](../../../CodexBar/Views/Menu/CodexStatusMenuView.swift)
diff --git a/Docs/en/README.md b/Docs/en/README.md
new file mode 100644
index 0000000..9ce7ccc
--- /dev/null
+++ b/Docs/en/README.md
@@ -0,0 +1,61 @@
+# CodexBar Documentation
+
+[简体中文](../README.md) | English
+
+CodexBar documentation is split into two sets by audience and responsibility, keeping product instructions separate from implementation details:
+
+| Document | Audience | What it covers |
+| --- | --- | --- |
+| [User Guide](UserGuide/README.md) | CodexBar users | Installing and using features, understanding settings, and resolving common issues |
+| [Developer Guide](DeveloperGuide/README.md) | Contributors and code readers | How the app works, how data flows, and how to validate core constraints |
+
+## Recommended Reading Paths
+
+### Using CodexBar for the first time
+
+1. Read [Installation and Quick Start](UserGuide/getting-started.md)
+2. Learn about the [Main Panel and Menu Bar](UserGuide/main-panel.md)
+3. Enable [Live Tasks and CodexBar Hook](UserGuide/activity-and-hook.md) if needed
+4. Review automatic reset, sleep prevention, and other options in the [Settings Reference](UserGuide/settings.md)
+
+### Troubleshooting
+
+1. Start with [Troubleshooting](UserGuide/troubleshooting.md)
+2. Check app-server request status in the app's Logs window
+3. For local files or network boundaries, see [Data, Sync, and Privacy](UserGuide/sync-data-privacy.md)
+
+### Reading or modifying the code
+
+1. Start with [Architecture](DeveloperGuide/architecture.md) for a system-wide view
+2. Continue to the data-flow or service guide relevant to your change
+3. See [Development and Validation](DeveloperGuide/development.md) for build, debugging, and verification workflows
+4. See [Data and Privacy Boundaries](DeveloperGuide/data-and-privacy.md) for local and cloud data scopes
+
+## Directory Structure
+
+```text
+Docs/en
+├── UserGuide
+│ ├── README.md
+│ ├── getting-started.md
+│ ├── main-panel.md
+│ ├── activity-and-hook.md
+│ ├── notifications.md
+│ ├── sleep-prevention.md
+│ ├── sync-data-privacy.md
+│ ├── settings.md
+│ └── troubleshooting.md
+└── DeveloperGuide
+ ├── README.md
+ ├── architecture.md
+ ├── design-decisions.md
+ ├── app-server.md
+ ├── hook-and-aggregation.md
+ ├── activity-monitor.md
+ ├── sleep-prevention.md
+ ├── sync.md
+ ├── notifications.md
+ ├── ui-and-lifecycle.md
+ ├── data-and-privacy.md
+ └── development.md
+```
diff --git a/Docs/en/UserGuide/README.md b/Docs/en/UserGuide/README.md
new file mode 100644
index 0000000..80d7b2a
--- /dev/null
+++ b/Docs/en/UserGuide/README.md
@@ -0,0 +1,38 @@
+# CodexBar User Guide
+
+[简体中文](../../UserGuide/README.md) | English
+
+## Contents
+
+| Document | Contents |
+| --- | --- |
+| [Installation and Quick Start](getting-started.md) | Requirements, installation, basic controls, and feature dependencies |
+| [Main Panel and Menu Bar](main-panel.md) | Menu bar states, account, rate limits, token heatmap, and Task Center |
+| [Live Tasks and CodexBar Hook](activity-and-hook.md) | What the Hook does, how to enable it, task states, and historical metrics |
+| [Notifications and Alerts](notifications.md) | Triggers, defaults, sounds, and haptic feedback for each notification type |
+| [Preventing System Sleep](sleep-prevention.md) | Activation conditions, protection options, CodexBarHelper authorization, and coexistence with external sleep settings |
+| [Data, Sync, and Privacy](sync-data-privacy.md) | Local data, iCloud sync, rebuilding data, and network boundaries |
+| [Settings Reference](settings.md) | Every setting on the General, Advanced, and About pages, including Automatic Reset |
+| [Troubleshooting](troubleshooting.md) | Sign-in, Hook, notifications, Automatic Reset, sleep prevention, sync, and logging issues |
+
+## Find What You Need
+
+- To view only your account and rate limits, start with [Installation and Quick Start](getting-started.md)
+- To follow running tasks or tasks waiting for approval, read [Live Tasks and CodexBar Hook](activity-and-hook.md)
+- To reset your rate limit automatically before reset credits expire, see [Automatic Reset](settings.md#automatic-reset)
+- To keep your Mac awake during long tasks, read [Preventing System Sleep](sleep-prevention.md)
+- To find out whether a setting uploads data, read [Data, Sync, and Privacy](sync-data-privacy.md)
+- If you already see an error, go directly to [Troubleshooting](troubleshooting.md)
+
+## Terminology
+
+| Term | Meaning |
+| --- | --- |
+| Codex | Codex capabilities running through Codex CLI, ChatGPT App, or Codex App |
+| app-server | The local Codex data-interface process that CodexBar launches and connects to |
+| CodexBar Hook | The event handler that CodexBar installs in your Codex configuration |
+| Live task | A running task or task waiting for approval, inferred from Hook events and local session state |
+| Hook aggregation | Daily session, turn, tool, and other metrics calculated from local raw Hook events |
+| CodexBarHelper | CodexBar's background service for system-level sleep-state changes and a fixed Automatic Reset wake schedule |
+
+Back to the [CodexBar README](../../../README.en.md)
diff --git a/Docs/en/UserGuide/activity-and-hook.md b/Docs/en/UserGuide/activity-and-hook.md
new file mode 100644
index 0000000..78a3ef5
--- /dev/null
+++ b/Docs/en/UserGuide/activity-and-hook.md
@@ -0,0 +1,124 @@
+# Live Tasks and CodexBar Hook
+
+[简体中文](../../UserGuide/activity-and-hook.md) | English
+
+## What the Hook Provides
+
+Account, rate-limit, and token usage data are periodic snapshots. They cannot tell you whether a Codex task is running, waiting for approval, or finished.
+
+CodexBar Hook records a small set of structured fields when key Codex events occur, enabling:
+
+- Menu bar task-status dots and task details
+- The main-panel activity card and Task Center for concurrent tasks
+- Alerts for task completion, approval requests, and stalled tasks
+- Haptic feedback for task events
+- Daily metrics for sessions, turns, tool calls, permission requests, context compactions, and subagents
+- Automatic sleep prevention based on live tasks
+- Cross-device sync of daily Hook aggregations
+- Rebuilding historical aggregations from raw events
+
+## Requirements
+
+Before enabling CodexBar Hook, make sure that:
+
+- CodexBar can connect to the currently running Codex app-server
+- The running app-server version is `0.145.0` or later
+- `features.hooks` is not disabled globally in the Codex configuration
+- The current `hooks.json` is valid JSON
+
+The version check uses the handshake version from the connected app-server, not a newly installed version on disk.
+
+If CodexBar still reports an older version after you update Codex, quit and reopen CodexBar to establish a new connection.
+
+## Enabling the Hook
+
+1. Right-click or Control-click the menu bar icon
+2. Select `Settings`
+3. Open the `Advanced` page
+4. Enable `CodexBar Hook`
+5. Wait for configuration and validation to finish
+
+CodexBar checks the installed Hook again whenever you open Settings or reactivate the app.
+
+## Configuration Changes
+
+CodexBar uses `$CODEX_HOME/hooks.json`, or `~/.codex/hooks.json` when `CODEX_HOME` is unset.
+
+When enabled, CodexBar:
+
+1. Reads and preserves the existing configuration
+2. Appends a separate command handler for CodexBar
+3. Asks Codex to validate the event list, source, and trust status
+4. Updates only trust entries that match the current CodexBar handler
+
+When disabled, it removes only handlers that match both the current CodexBar executable path and the `--hook-event` argument.
+
+Your own handlers, handlers from other apps, unrecognized fields, and unrelated trust entries are preserved.
+
+## Understanding Task States
+
+| State | Meaning | Active task? |
+| --- | --- | --- |
+| Running | The task is still making progress | Yes |
+| Waiting for Approval | The task is waiting for you to approve its next action | Yes |
+| Recently Completed | A task turn has been confirmed as finished | No |
+| Recently Terminated | A task turn has been confirmed as terminated | No |
+| Hidden | A running task exceeded the stalled-task silence threshold | No |
+
+Completion means that a task turn ended; it does not necessarily mean that the result was successful.
+
+Waiting for Approval applies only to approval requests that require user action. Automatically reviewed requests are not shown as waiting for you.
+
+Subagent events update their parent top-level task instead of appearing as separate concurrent tasks.
+
+When a Hook event has no session ID, CodexBar shows an anonymous task for its project. Anonymous tasks can still appear in Running, Waiting for Approval, Recently Completed, and Recently Terminated lists, but they do not trigger task notifications or haptic feedback and do not participate in sleep prevention or stalled task protection.
+
+The activity card and Task Center mark these tasks with an orange anonymous icon. Hovering over it shows `Anonymous tasks do not prevent sleep`.
+
+## Hook Events and Their Uses
+
+| Event | Primary use |
+| --- | --- |
+| `SessionStart` and `SessionEnd` | Session lifecycle, session metrics, and task finalization |
+| `UserPromptSubmit` and `Stop` | Turn metrics, task start, and completion candidates |
+| `PreToolUse` and `PostToolUse` | Tool-call metrics and task progress |
+| `PermissionRequest` | User-waiting state and permission-request metrics |
+| `PreCompact` and `PostCompact` | Context-compaction metrics and task progress |
+| `SubagentStart` and `SubagentStop` | Subagent count, state, and task progress |
+
+## How Daily Metrics Are Calculated
+
+| Metric | Meaning |
+| --- | --- |
+| Sessions | Number of distinct Codex sessions on that day |
+| Turns | Number of distinct turns on that day |
+| Tool calls | The larger of the `PreToolUse` and `PostToolUse` counts |
+| Permission requests | Number of `PermissionRequest` events |
+| Context compactions | The larger of the `PreCompact` and `PostCompact` counts |
+| Subagents | The larger of the `SubagentStart` and `SubagentStop` counts |
+| Most-used model | The model that appears most often in Hook events for that day |
+
+Using the larger count preserves observed operations when one side of an event pair is missing.
+
+## Effects of Disabling the Hook
+
+Disabling CodexBar Hook stops updates to:
+
+- Live tasks and Task Center
+- Menu bar task-status dots
+- Task notifications and haptic feedback
+- Daily Hook metrics
+- Sleep prevention
+- Cross-device sync of Hook aggregations
+
+Account data, rate limits, the token heatmap, update checks, and the Logs window remain available.
+
+## Data Boundaries
+
+Raw Hook events contain only structured fields such as time, event name, model, reasoning effort, approval mode, `reviewer`, `session`, `turn`, `agent`, tool name, and working directory.
+
+CodexBar does not store prompt text, Codex responses, tool arguments, or tool output.
+
+See [Data, Sync, and Privacy](sync-data-privacy.md) for complete storage and sync boundaries.
+
+Back to the [User Guide](README.md)
diff --git a/Docs/en/UserGuide/getting-started.md b/Docs/en/UserGuide/getting-started.md
new file mode 100644
index 0000000..0459aa3
--- /dev/null
+++ b/Docs/en/UserGuide/getting-started.md
@@ -0,0 +1,83 @@
+# Installation and Quick Start
+
+[简体中文](../../UserGuide/getting-started.md) | English
+
+## Requirements
+
+- macOS 15.0 or later
+- [Codex CLI](https://github.com/openai/codex) installed and signed in, or ChatGPT App or Codex App with bundled Codex installed
+- The running Codex app-server must be `0.143.0` or later
+- Hook features require the running Codex app-server to be `0.145.0` or later
+- Cross-device sync requires an available iCloud account on the Mac
+
+CodexBar prefers a globally installed Codex CLI. If it cannot find one, it tries the Codex bundled with ChatGPT App and Codex App.
+
+## Installation
+
+### Homebrew
+
+```bash
+brew install --cask bob-zebedy/tap/codexbar
+```
+
+### DMG
+
+1. Download the latest DMG from [GitHub Releases](https://github.com/bob-zebedy/CodexBar/releases)
+2. Open the DMG and drag CodexBar into Applications
+3. Launch CodexBar from Applications
+
+## First Launch
+
+CodexBar is a menu bar app, so it does not show an icon in the Dock after launch:
+
+1. Find the CodexBar icon in the menu bar at the top of the screen
+2. Left-click the icon to open the main panel
+3. Wait for the initial account and usage refresh to finish
+4. If the panel says you are not signed in, sign in through the active Codex installation first
+5. For live tasks, task notifications, sleep prevention, or Hook metrics, enable CodexBar Hook under `Settings > Advanced`
+
+CodexBar refreshes account, rate-limit, and token usage data every 60 seconds. Double-click the account icon in the main panel to refresh immediately.
+
+## Basic Controls
+
+| Action | Result |
+| --- | --- |
+| Left-click the menu bar icon | Open or close the main panel |
+| Right-click or Control-click the menu bar icon | Open the Settings, Logs, and Quit menu |
+| `⌘⇧W` | Open or close the main panel with the default global shortcut |
+| `⌘,` | Open the Settings window |
+| `⌘L` | Close the main panel and open the Logs window while the panel is open |
+| Double-click the account icon | Refresh account, rate-limit, and usage data immediately |
+| Double-click the account email | Toggle email blurring |
+| Hover over a heatmap cell | View token and Hook metrics for that day |
+| Click the activity card | Open Task Center for concurrent tasks |
+| Click the reset-credit count | View the expiration time of each credit batch |
+| `Settings > Advanced > Automatic Reset` | Configure automatic use and lead time |
+
+The global shortcut opens the main panel on the screen under the pointer when possible. If the menu bar anchor is unavailable, CodexBar uses a standalone floating panel.
+
+## Feature Dependencies
+
+| Feature | CodexBar Hook | Other requirements |
+| --- | --- | --- |
+| Account, plan, and rate limits | Not required | Signed in to Codex; app-server `0.143.0` or later |
+| Token totals and heatmap | Not required | app-server `0.143.0` or later |
+| Live tasks and Task Center | Required | Hook validation has passed |
+| Daily Hook metrics | Required | Local raw Hook events are available |
+| Rate-limit notifications | Not required | System Notifications and macOS permission are enabled |
+| Automatic Reset | Not required | Confirmation is required each time it is enabled; waking from system sleep and showing the lead-time options require approved CodexBarHelper access; lead time ranges from 15 minutes to 6 hours and defaults to 30 minutes |
+| Task notifications | Required | Hook validation has passed and notifications are enabled |
+| Prevent System Sleep | Required | Confirmation is required each time it is enabled; CodexBarHelper is registered and approved by macOS |
+| Cross-device sync | Required | iCloud is available and sync is explicitly enabled |
+
+Disabling CodexBar Hook does not affect account data, rate limits, the token heatmap, update checks, or the Logs window.
+
+## Language and Region
+
+CodexBar provides Simplified Chinese and English interfaces. By default, it follows the macOS per-app language preference.
+
+To choose a language specifically for CodexBar, use Language & Region in macOS System Settings.
+
+Dates, times, durations, percentages, calendar layout, and the first day of the week always follow the current regional format.
+
+Next, read [Main Panel and Menu Bar](main-panel.md) or the [Settings Reference](settings.md).
diff --git a/Docs/en/UserGuide/main-panel.md b/Docs/en/UserGuide/main-panel.md
new file mode 100644
index 0000000..b70467a
--- /dev/null
+++ b/Docs/en/UserGuide/main-panel.md
@@ -0,0 +1,128 @@
+# Main Panel and Menu Bar
+
+[简体中文](../../UserGuide/main-panel.md) | English
+
+## Menu Bar Icon
+
+CodexBar combines its icon, a status dot, and an optional rate-limit bar to show account, task, and rate-limit status:
+
+| Appearance | Meaning |
+| --- | --- |
+| Normal account icon | Account data is available |
+| Error account icon | You are signed out, initialization failed, or trusted rate-limit and usage data is unavailable |
+| Blue status dot | At least one task is running |
+| Orange status dot | At least one task is waiting for your approval |
+| Green status dot | A task has just finished; the highlight remains for 30 seconds |
+| Rate-limit bar beside the icon | Remaining percentage in the selected rate-limit window |
+
+When several states exist at once, waiting for approval takes priority over running, and running takes priority over recently completed.
+
+Hover over the menu bar icon to see the current task state, project name, elapsed time, number of concurrent tasks, and remaining percentage in the selected rate-limit window.
+
+When rate-limit data comes from cache, the icon and progress bar become translucent to indicate that the visible data is not the latest snapshot.
+
+## Account
+
+- Shows the signed-in account or account type
+- Identifies Enterprise, Team, Business, Pro, Plus, Edu, and Free plans
+- Double-clicking the account icon refreshes account, rate-limit, and usage data immediately
+- Double-clicking the email toggles blurring
+- Shows `Not signed in` when no account is signed in
+- Shows `Initialization failed` when app-server cannot initialize
+
+The main panel presents only states that help you decide what to do. Detailed request errors remain available in the Logs window.
+
+## Rate Limits
+
+CodexBar shows every rate-limit group and window returned by Codex.
+
+Each rate-limit window includes:
+
+- A window name, such as `5h` or `7d`
+- Remaining percentage
+- A segmented progress bar
+- The next reset time
+
+The primary rate-limit group may also show:
+
+- Available credits or unlimited-credit status
+- Available reset credits
+- The expiration time for each batch of reset credits
+
+Click the reset-credit count to open its details. This entry appears only when Codex reports available reset credits.
+
+## Token Usage and Heatmap
+
+The summary area shows:
+
+- All-time token usage
+- Highest daily token usage
+- Current usage streak
+- Longest usage streak
+- Longest task duration
+
+The heatmap uses a 30-column by 7-row grid to show daily token usage over the last 30 weeks. Color intensity is relative to the highest value currently visible in the heatmap.
+
+Hover over a day to see its date, token count, and usage intensity.
+
+When CodexBar Hook is enabled and data exists for that day, the details also include:
+
+- Most-used model
+- Sessions
+- Turns
+- Subagents
+- Tool calls
+- Permission requests
+- Context compactions
+
+## Activity Card
+
+Activity-card states are prioritized as waiting for approval, running, recently completed, then recently terminated.
+
+The card shows the following fields when available:
+
+- Project name
+- Model and reasoning effort
+- Current tool or execution stage
+- Running or waiting duration
+- Active subagent count
+- Number of other concurrent tasks
+- Anonymous-task icon
+
+When sleep prevention is actively engaged, a coffee-cup indicator appears on the right side of the activity card.
+
+If a Hook event has no session ID, the task still appears in the activity card and Task Center with an orange anonymous icon. Hovering over the icon shows `Anonymous tasks do not prevent sleep`.
+
+The activity card's `+N` shows only the total number of other active tasks; it does not break out anonymous tasks separately.
+
+Click a populated activity card to open Task Center.
+
+## Task Center
+
+Task Center groups tasks into:
+
+- Waiting for Approval
+- Running
+- Recently Completed
+- Recently Terminated
+
+Recently completed and recently terminated tasks remain in Task Center for 10 minutes. Completion and termination are distinct states.
+
+Completion means that a task turn ended; it does not necessarily mean that the result was successful.
+
+Terminated tasks do not trigger task-completion notifications.
+
+Anonymous tasks use the same anonymous icon while running, waiting for approval, recently completed, or recently terminated.
+
+## Footer Status
+
+The bottom of the main panel shows:
+
+- Data update time
+- Countdown to the next automatic refresh
+- iCloud sync status: off, syncing, synced, or failed
+- Available-update indicator
+
+When a new version is available, double-click the update indicator to start the update.
+
+Back to the [User Guide](README.md)
diff --git a/Docs/en/UserGuide/notifications.md b/Docs/en/UserGuide/notifications.md
new file mode 100644
index 0000000..6b5a75f
--- /dev/null
+++ b/Docs/en/UserGuide/notifications.md
@@ -0,0 +1,97 @@
+# Notifications and Alerts
+
+[简体中文](../../UserGuide/notifications.md) | English
+
+## Enabling Notifications
+
+1. Open `Settings > Advanced`
+2. Enable `System Notifications`
+3. Allow notifications in the macOS permission dialog
+4. Click the slider button on the right to configure individual notification types
+
+If system permission is denied, Settings shows an `Open System Settings` button.
+
+System Notifications is off by default. Turning it off disables all CodexBar system notifications and task haptic feedback.
+
+## Notification Types
+
+| Notification | Trigger | Default option | Additional requirement |
+| --- | --- | --- | --- |
+| Task completed | A task finishes after running for at least the selected duration | On, 1 minute | CodexBar Hook |
+| Waiting for approval | A task starts waiting for user approval | On | CodexBar Hook |
+| Low rate limit | A trusted rate limit reaches or crosses the threshold for the first time | On, 10% | None |
+| Rate limit reset | A rate-limit window previously observed as consumed returns to an unconsumed state | On | None |
+| Reset credits expiring | Reset credits enter the 7-day expiration window | On | Available reset credits |
+| Automatic Reset | An automatic reset explicitly returns success or reports that it already succeeded | On | Automatic Reset, its notification option, and System Notifications |
+| Automatic Reset failed | Authentication failure pauses the task, a protocol error stops it, or this Mac explicitly observes expiration | Shares the success-notification setting | Automatic Reset, its notification option, and System Notifications |
+| Low Battery Protection | Low Battery Protection successfully restores system sleep | On | Sleep prevention and Low Battery Protection |
+| Keep-awake limit | The time limit is reached and system sleep is successfully restored | On | Sleep prevention and a finite time limit |
+| Stalled Task Protection | A running task exceeds the silence threshold and the candidate is still valid | Fixed behavior | CodexBar Hook and Prevent System Sleep |
+
+Stalled Task Protection has no separate notification option and uses the default system sound.
+
+Even if its notification cannot be delivered, a confirmed stalled task is still hidden and stops participating in sleep prevention.
+
+Anonymous tasks do not trigger completion, approval, or Stalled Task Protection notifications or task haptic feedback, but remain visible in the activity card and Task Center.
+
+## Thresholds
+
+| Setting | Options |
+| --- | --- |
+| Minimum duration for completed tasks | 30 seconds, 1 minute, 2 minutes, 5 minutes |
+| Low rate-limit threshold | 5%, 10%, 25% |
+
+A low-rate-limit alert fires only when the remaining percentage moves from above the threshold to the threshold or below. It does not repeat on every 60-second refresh.
+
+Restarting CodexBar does not repeat the alert within the same rate-limit reset cycle.
+
+Reset credits are checked for reminders at 7, 6, 5, 4, 3, 2, and 1 day before expiration.
+
+## Automatic Reset Notifications
+
+“Automatic Reset” and “Rate Limit Reset” represent two independent facts:
+
+- “Automatic Reset” means this Mac's automatic call returned `reset` or `alreadyRedeemed`
+- “Rate Limit Reset” means a rate-limit window changed from consumed to unconsumed
+
+One automatic reset can therefore produce both notifications. Neither replaces the other, and each follows its own trigger rules.
+
+When several devices try at the same time, each device that receives an explicit success result sends its own success notification. A device that only sees the credit disappear during refresh does not notify because it cannot tell whether the credit was used manually, used by another device, or expired.
+
+Network errors, timeouts, and temporary service errors retry silently in the background. If authentication still fails, the current task pauses and resumes after a later trusted snapshot confirms recovery. A definitive protocol error stops the current task. If this Mac explicitly observes expiration, the task stops and notifies. If the credit simply disappears from server details, the task stops silently because the cause is unknown.
+
+The same failure reason is reported at most once for a given credit; different reasons may be reported separately. Success and failure notifications share the `Automatic Reset Notification` option and sound. When Automatic Reset is off, this option is unavailable. Re-enabling the feature restores the previous notification and sound choices.
+
+## Notification Sounds
+
+Each configurable notification can use:
+
+- Default notification sound
+- No sound
+- Any system alert sound available on the current Mac
+- CodexBar's built-in Modern and Material sounds
+
+You can preview any sound other than the default or silent options in Settings.
+
+If a saved sound is unavailable on the current Mac, CodexBar falls back to the default notification sound.
+
+## Haptic Feedback
+
+When `Task Haptic Feedback` is enabled, the trackpad provides haptic feedback when a task finishes or starts waiting for approval.
+
+Haptic feedback does not require macOS notification permission, but it still follows CodexBar's System Notifications switch and CodexBar Hook status.
+
+## Codex TUI Notifications
+
+`Codex TUI Notifications` changes `tui.notifications` in the Codex user configuration.
+
+It is independent of CodexBar's local notifications. Enabling one does not enable the other.
+
+## Notification Interaction
+
+- Banners, Notification Center entries, and sounds still appear while CodexBar is in the foreground
+- Clicking any CodexBar notification opens the main panel
+- When a task is no longer waiting for approval, its waiting notification is removed from Notification Center
+- When a stalled task resumes progress or its candidate becomes invalid, its protection notification is removed from Notification Center
+
+Back to the [User Guide](README.md)
diff --git a/Docs/en/UserGuide/settings.md b/Docs/en/UserGuide/settings.md
new file mode 100644
index 0000000..2a84b90
--- /dev/null
+++ b/Docs/en/UserGuide/settings.md
@@ -0,0 +1,174 @@
+# Settings Reference
+
+[简体中文](../../UserGuide/settings.md) | English
+
+Right-click or Control-click the menu bar icon and select `Settings`, or press `⌘,` to open the Settings window.
+
+Settings contains three pages: `General`, `Advanced`, and `About`.
+
+## General Settings
+
+| Setting | Effect | Default or initial state |
+| --- | --- | --- |
+| Launch at Login | Starts CodexBar automatically through macOS Login Items | Follows the current system Login Item state |
+| Automatically Check for Updates | Lets Sparkle check periodically for updates | Follows the current Sparkle setting |
+| Menu Bar Quota Indicator | Shows the remaining percentage for a selected rate-limit window beside the menu bar icon | Primary rate limit |
+| Global Shortcut | Opens or closes the CodexBar main panel from any app | `⌘⇧W` |
+
+### Menu Bar Quota Indicator
+
+- Choose from the rate-limit windows returned by the current Codex installation
+- CodexBar remembers the last selected window when you turn the indicator off
+- Turning it on again restores the previous selection
+- Cached rate-limit data is shown with reduced opacity
+
+### Global Shortcut
+
+- A recorded shortcut must contain at least two modifier keys
+- System-reserved combinations such as `Command-Space` and `Command-Tab` cannot be used
+- CodexBar reports combinations already used by another app as conflicts
+- You can clear the shortcut
+- You can restore the default `⌘⇧W`
+
+## Advanced Settings
+
+| Setting | Effect | Default |
+| --- | --- | --- |
+| CodexBar Hook | Installs and validates the Codex event handler | Off when not installed |
+| Show Task Center in Menu | Controls whether the activity card and Task Center appear | On; unavailable while Hook is off |
+| System Notifications | Controls CodexBar local notifications and task haptic feedback | Off |
+| Automatic Reset | Uses unredeemed reset credits at the selected lead time before expiration | Off; 30 minutes early |
+| Prevent System Sleep | Manages system sleep automatically based on live Codex tasks | Off |
+| Sync Across Devices | Syncs daily Hook aggregations through iCloud | Off |
+| Rebuild Data | Regenerates aggregations from local raw events for selected dates | Manual action |
+
+### CodexBar Hook
+
+Enabling the Hook unlocks live tasks, task notifications, Hook metrics, sleep prevention, and cross-device sync.
+
+Enabling and validating it requires the current app-server to be `0.145.0` or later.
+
+See [Live Tasks and CodexBar Hook](activity-and-hook.md) for details.
+
+### Show Task Center in Menu
+
+When this setting is off, the main panel no longer shows the activity card or the Task Center entry.
+
+It does not disable the Hook or stop Hook metrics, notifications, or sleep prevention.
+
+When the Hook is off, this option appears off and disabled without overwriting your saved choice.
+
+### System Notification Options
+
+| Option | Default | Other choices or notes |
+| --- | --- | --- |
+| Task Completion | On, 1 minute | Minimum duration: 30 seconds or 1, 2, or 5 minutes |
+| Approval Requests | On | Requires CodexBar Hook |
+| Low Quota | On, 10% | Threshold: 5%, 10%, or 25% |
+| Quota Reset | On | Recognized only after consumption has been observed |
+| Reset Expiration | On | Alerts for reset credits expiring within 7 days |
+| Automatic Reset Notifications | On | Available only while Automatic Reset is enabled; success and failure share one sound |
+| Low Battery Alert | On | Applies only when Low Battery Protection is available |
+| Keep-Awake Limit | On | Applies only when the maximum duration is not unlimited |
+| Task Haptics | Off | Provides trackpad feedback when a task finishes or waits for approval |
+| Codex TUI Notifications | Follows the Codex configuration | Independent of CodexBar notifications |
+
+Each system notification can use the default sound, no sound, a system sound, or a built-in app sound.
+
+See [Notifications and Alerts](notifications.md) for details.
+
+### Confirmation for Automatic Reset and Sleep Prevention
+
+Every transition of `Automatic Reset` or `Prevent System Sleep` from off to on shows a confirmation dialog. The dialog first shows guidance based on the current CodexBarHelper state, then explains the selected feature:
+
+| CodexBarHelper state | Confirmation message |
+| --- | --- |
+| Not registered or file missing | `CodexBar Helper must be installed and authorized to run in the background` |
+| Installed but awaiting macOS approval | `CodexBar Helper is installed but still needs authorization to run in the background` |
+| Installed and approved | Shows only the feature description |
+
+Feature descriptions are:
+
+| Feature | Confirmation title | Description |
+| --- | --- | --- |
+| Automatic Reset | `Enable Automatic Reset?` | `When enabled, CodexBar automatically uses a manual reset credit at the configured time before it expires and may briefly wake your Mac.` |
+| Prevent System Sleep | `Enable System Sleep Prevention?` | `When enabled, CodexBar prevents system sleep while Codex tasks are running and restores normal sleep afterward.` |
+
+Selecting `Enable` saves your intent and attempts to register CodexBarHelper. Selecting `Cancel` leaves the switch off. System Settings for Helper approval opens only through the `Open System Settings` button below an enabled settings row; the button appears while CodexBarHelper is awaiting approval. No status explanation appears below either row while its switch is off.
+
+### Automatic Reset
+
+When Automatic Reset is enabled and CodexBarHelper is installed and approved, an options button appears on the right side of the main row. Open it to choose a `Time Before Expiration` of `15 Minutes`, `30 Minutes`, `1 Hour`, `2 Hours`, `4 Hours`, or `6 Hours`; the default is `30 Minutes`. The entry is hidden if the Helper state no longer qualifies, and any open Automatic Reset side panel closes.
+
+- Processes only available reset credits explicitly listed in the latest app-server response
+- Revalidates the account, credit state, and expiration time before every use
+- Processes only the earliest-expiring credit at a time
+- Attempts to register CodexBarHelper after confirmation; even if Prevent System Sleep is off, CodexBar may need approval to run in the background under Login Items & Extensions
+- Shows CodexBarHelper approval, registration, registration-failure, or wake-schedule synchronization status on the Automatic Reset row
+- If a future task exists, CodexBarHelper registers one system wake event for the nearest threshold or retry; the schedule is canceled when the task changes, the feature is disabled, or the app exits, and a schedule left by an abnormal exit is removed the next time the helper starts
+- At the scheduled time, prevents idle system sleep only while it rereads and uses the credit; it does not wake the display or enable Prevent System Sleep
+- Rechecks immediately after a natural system wake or the next app launch; it retries if the credit is still inside its lead-time window and has not expired, otherwise it reschedules for that window
+- Schedules a retry wake only after reading a specific credit and expiration time; continuous retries last no more than 5 minutes per round, while later normal rate-limit refreshes can try again
+- Does not consume anything when no reset is currently available, and reuses the same idempotency key throughout that 5-minute round
+- Preserves the credit's idempotent identity and reschedules when the server changes its expiration time
+- Pauses or stops the current task on authentication failure or a definitive protocol error, with a system notification when notification settings permit
+
+When several Macs enable Automatic Reset, each schedules independently but derives the same idempotency key for the same `creditId`. The first device to succeed consumes the credit. Other devices stop after receiving an already-successful result, or stop silently after a refresh shows that the credit disappeared.
+
+After success, CodexBar sends an “Automatic Reset” notification. A regular “Quota Reset” notification comes from a change in the rate-limit window, so both may appear. Automatic Reset itself does not depend on System Notifications; it still runs when notifications are off but does not show a result notification.
+
+The `Automatic Reset Notifications` side-panel option controls both success and failure notifications and configures one sound for both. When Automatic Reset is off, the option appears off and disabled without overwriting your saved notification and sound choices.
+
+This setting is stored only on the current Mac and is not synced through CloudKit.
+
+### Prevent System Sleep Options
+
+When Prevent System Sleep is enabled and CodexBar Hook is available, an options button can appear on the right side of the main row. The entry remains visible when there is no eligible task, CodexBarHelper is refreshing, Low Battery Protection is active, or the maximum duration has been reached. It is hidden when an eligible task exists but CodexBarHelper is unavailable.
+
+| Option | Default | Choices |
+| --- | --- | --- |
+| Keep Awake While Waiting | Off | On or off |
+| Keep Display Awake | Off | On or off |
+| Keep-Awake Limit | 12 hours | 1, 2, 4, 8, 12, or 24 hours; unlimited |
+| Stalled Task Protection | 1 hour | 30 minutes; 1, 2, or 4 hours |
+| Low Battery Protection | Off | Off; 5%, 10%, 15%, 20%, or 25% |
+
+Low Battery Protection does not appear on Macs without a built-in battery.
+
+See [Preventing System Sleep](sleep-prevention.md) for details.
+
+### Sync Across Devices
+
+- Can be enabled only when CodexBar Hook is on and iCloud is available
+- On first enable, uploads daily local Hook aggregations within the retention period
+- Settings shows sync status and the most recent successful upload time
+- Turning it off stops network sync but keeps local Hook data
+
+See [Data, Sync, and Privacy](sync-data-privacy.md) for details.
+
+### Rebuild Data
+
+- The date picker allows only dates within the raw Hook-data retention period
+- Dates with raw events are marked
+- Rebuild becomes available only after a complete range is selected
+- A confirmation appears before rebuilding
+- The result shows the number of rebuilt days, parsed events, and skipped invalid lines
+- Incomplete dates retry automatically when the Hook is available
+
+## About
+
+| Item | Purpose |
+| --- | --- |
+| Codex CLI | Shows the on-disk version and path of the global Codex CLI |
+| Codex APP | Shows the on-disk version and path of the CLI bundled with ChatGPT App or Codex App |
+| In Use | Identifies the Codex source and running app-server version currently in use |
+| CodexBar Version | Shows the current version, update status, and any available update |
+| GitHub Project | Opens the CodexBar project page |
+| Check for Updates | Runs a manual Sparkle update check |
+| Quit CodexBar | Completes required cleanup before quitting the app |
+
+If Codex has been updated on disk but the current app-server has not reconnected, About shows the newly installed version as well.
+
+Click an executable path to copy the full path.
+
+Back to the [User Guide](README.md)
diff --git a/Docs/en/UserGuide/sleep-prevention.md b/Docs/en/UserGuide/sleep-prevention.md
new file mode 100644
index 0000000..9aed702
--- /dev/null
+++ b/Docs/en/UserGuide/sleep-prevention.md
@@ -0,0 +1,128 @@
+# Preventing System Sleep
+
+[简体中文](../../UserGuide/sleep-prevention.md) | English
+
+## Purpose
+
+When macOS enters system sleep, Codex tasks running on that Mac may be suspended.
+
+CodexBar manages system sleep automatically based on live task state, allowing long tasks to continue unattended and restoring normal system behavior when tasks finish or a protection rule is triggered.
+
+This feature is not a general-purpose switch that keeps your Mac awake indefinitely.
+
+Enabling it only allows CodexBar to manage sleep automatically. CodexBar does not change system sleep when no eligible task exists.
+
+## Activation Conditions
+
+CodexBar prevents system sleep only when all of the following are true:
+
+1. CodexBar is running and is not quitting
+2. `Prevent System Sleep` is enabled
+3. CodexBar Hook is installed and passed the latest explicit validation
+4. At least one non-anonymous task is running, or `Keep Awake While Waiting` is enabled and a non-anonymous task is waiting
+5. CodexBarHelper is registered and approved by macOS
+6. CodexBarHelper is not being updated
+7. Low Battery Protection is not active
+8. The current keep-awake period has not reached its limit
+
+If any condition becomes false, CodexBar stops its own sleep prevention.
+
+If the conditions recover while an eligible task still exists, sleep prevention resumes automatically.
+
+Anonymous tasks do not count as eligible, even when shown as running or waiting for approval.
+
+## Options
+
+| Option | Effect | Default | Choices |
+| --- | --- | --- | --- |
+| Keep Awake While Waiting | Tasks waiting for your approval continue to prevent sleep | Off | On or off |
+| Keep Display Awake | Also prevents display sleep, the screen saver, and idle screen locking | Off | On or off |
+| Keep-Awake Limit | Limits accumulated time that sleep is actively prevented in one period | 12 hours | 1, 2, 4, 8, 12, or 24 hours; unlimited |
+| Stalled Task Protection | Hides tasks with no progress for an extended period and removes their contribution to sleep prevention | 1 hour | 30 minutes; 1, 2, or 4 hours |
+| Low Battery Protection | Restores system sleep when running on low battery | Off | Off; 5%, 10%, 15%, 20%, or 25% |
+
+Low Battery Protection does not appear on Macs without a built-in battery.
+
+## Keep Awake While Waiting
+
+When this option is off, a task stops supporting sleep prevention after it moves from Running to Waiting for Approval.
+
+When it is on, sleep prevention continues while the task waits for approval.
+
+Approval requests have no natural timeout, so an unattended Mac may stay awake for a long time. The Keep-Awake Limit still applies.
+
+Stalled Task Protection evaluates only running tasks, not tasks waiting for approval.
+
+## Keep Display Awake
+
+This option takes effect only while CodexBar is already preventing system sleep.
+
+CodexBar also prevents display sleep and periodically declares user activity to suppress the screen saver and idle screen locking.
+
+It releases these effects when tasks finish, Low Battery Protection activates, the time limit is reached, or sleep prevention fails.
+
+Because this may leave the screen unlocked while you are away, the option is off by default.
+
+## Keep-Awake Limit
+
+- Counts only time during which system sleep is actively prevented
+- Excludes time paused because of low battery, unavailable CodexBarHelper, or another condition
+- Does not count time spent in system sleep or changes to the system clock
+- Resets when there are no active tasks
+- Starts a new period when a new running task appears or a waiting task resumes running
+- Restores system sleep when the limit is reached, until the next task period begins
+
+## Stalled Task Protection
+
+Stalled Task Protection handles tasks that have stopped making real progress but still appear as running because no reliable terminal state is available:
+
+- Follows the Prevent System Sleep switch and has no separate on/off switch
+- Evaluates only non-anonymous running tasks
+- Uses Hook events, subagent events, and local session lifecycle as progress signals
+- Saves a protection record, attempts a notification, and hides the task when the threshold is reached
+- Removes hidden tasks from the activity card and Task Center and excludes them from sleep prevention
+- Restores a task automatically and withdraws any active notification when new progress appears
+- Restores hidden tasks that no longer exceed the threshold after you select a longer threshold
+- Pauses evaluation during Hook history replay, system sleep, wake reconciliation, or Hook data-source outages
+- Keeps protection records for no more than 24 hours after the last progress
+
+Protection records contain only hashed task identifiers and timestamps. They do not contain raw `session` or `turn` IDs, project names, or task content.
+
+## Low Battery Protection
+
+- Applies only while the Mac is running on battery power
+- Restores system sleep when the battery first reaches or falls below the selected threshold
+- Remains active until the battery rises 5 percentage points above the threshold
+- Clears immediately when the Mac is connected to power
+- Resumes sleep prevention automatically if an eligible task remains
+- Sends a low-battery notification only after CodexBar successfully stops its own sleep prevention
+
+The 5-point recovery margin prevents repeated toggling near the selected threshold.
+
+## Authorizing CodexBarHelper
+
+Sleep prevention requires the bundled CodexBarHelper to change system-level sleep settings. Automatic Reset shares the same background-service registration and approval state to install a fixed system wake schedule:
+
+- Every transition from off to on shows an `Enable System Sleep Prevention?` confirmation dialog
+- If CodexBarHelper is unregistered or missing, the dialog says `CodexBar Helper must be installed and authorized to run in the background`
+- If CodexBarHelper is installed but awaiting approval, the dialog says `CodexBar Helper is installed but still needs authorization to run in the background`
+- If CodexBarHelper is approved, the dialog shows only `When enabled, CodexBar prevents system sleep while Codex tasks are running and restores normal sleep afterward.`
+- Selecting `Enable` saves the switch state and attempts to register the background service; selecting `Cancel` leaves it off
+- When macOS requires approval for the background item, the enabled settings row shows `Open System Settings`; use it to open Login Items & Extensions
+- No status explanation appears while the main switch is off; when the switch and Hook are available, the current blocking reason determines whether the sleep-prevention options are shown
+- Sleep prevention does not run if CodexBarHelper is missing or registration fails
+- If an app update changes CodexBarHelper, CodexBar refreshes its registration and validates the sleep state
+- Before a normal app exit, CodexBar cancels the Automatic Reset wake schedule, releases the CodexBarHelper lease, and restores any state it changed
+- If a CodexBarHelper connection ends unexpectedly, the helper releases that client's lease after a grace period
+- Automatic Reset uses a separate connection; if it disconnects, the helper immediately cancels the wake schedule owned by that connection
+
+## Coexisting with Other Sleep-Prevention Sources
+
+If system sleep was already disabled by another app or by the user before a task started, CodexBar marks the source as external:
+
+- CodexBar does not claim ownership of the external setting
+- It does not restore or overwrite that setting when the task finishes
+- If the external setting is restored while the task is still running, CodexBar checks again and takes over when needed
+- The main panel still shows the coffee cup, while Settings explains that system sleep is disabled by another source
+
+Back to the [User Guide](README.md)
diff --git a/Docs/en/UserGuide/sync-data-privacy.md b/Docs/en/UserGuide/sync-data-privacy.md
new file mode 100644
index 0000000..024dc36
--- /dev/null
+++ b/Docs/en/UserGuide/sync-data-privacy.md
@@ -0,0 +1,137 @@
+# Data, Sync, and Privacy
+
+[简体中文](../../UserGuide/sync-data-privacy.md) | English
+
+## What Cross-Device Sync Includes
+
+Cross-device sync merges daily Hook aggregations from multiple Macs. It does not sync account data, rate limits, token usage, reset credits, or Automatic Reset settings.
+
+It requires:
+
+- CodexBar Hook to be enabled
+- An available iCloud account
+- `Sync Across Devices` to be explicitly enabled
+
+After you enable it, CodexBar uploads daily Hook aggregations within the local retention period, then uploads changed dates during later statistics maintenance.
+
+Each device stores its contribution for a date separately. CodexBar merges contributions from different devices for display while avoiding double-counting the current device's local and cloud copies.
+
+Sync uses the CloudKit private database in the `iCloud.app.zabrian.codexbar` container.
+
+## Sync Status
+
+The bottom of the main panel and the Settings page show these states:
+
+| Status | Meaning |
+| --- | --- |
+| Sync is off | You have not enabled sync, or CodexBar Hook is off |
+| Syncing | CodexBar is reading from or writing to CloudKit |
+| Synced | The most recent sync completed successfully |
+| Sync failed | The network, iCloud account, or service is temporarily unavailable |
+
+Settings also shows the time of the most recent successful upload.
+
+## Rebuilding Data
+
+Use `Settings > Advanced > Rebuild Data` to regenerate daily aggregations for selected dates from local raw Hook events.
+
+This is useful when:
+
+- Older aggregations lack metrics added by a newer version
+- Metrics for certain dates look incorrect
+- Local raw events were replaced or truncated
+- You need to replace the current device's cloud contribution for those dates with a local result
+
+The rebuild process works as follows:
+
+1. The date picker allows only dates within the raw Hook-event retention period
+2. Dates with raw data are marked
+3. After confirmation, CodexBar reparses the selected local JSONL files
+4. Unparseable lines are skipped and included in the result count
+5. If sync is enabled, the rebuilt dates replace this device's cloud contribution during a later sync
+
+Rebuilding does not change your Codex account, rate limits, or token usage.
+
+## Data Stored Locally
+
+| Data | Contents | Location or lifetime |
+| --- | --- | --- |
+| Raw Hook events | Selected structured event fields | `~/Library/Application Support/CodexBar/HookEvents/events`, retained for 210 days |
+| Daily Hook aggregations | Event counts, sessions and turns, project-name counts, and model counts | `~/Library/Application Support/CodexBar/HookEvents/daily.jsonl`, retained for 210 days |
+| Hook maintenance state | File `offset`, `generation`, and pending dates | `~/Library/Application Support/CodexBar/HookEvents/maintenance.json` |
+| Sync cache | CloudKit cache, cursors, and upload state | `~/Library/Application Support/CodexBar/HookEvents/Sync` |
+| Stalled Task Protection | Hashed task identifiers and timestamps | `~/Library/Application Support/CodexBar/ActivityProtection/state.json`, up to 24 hours |
+| CodexBarHelper ownership | Sleep-state ownership and recovery transactions | `/Library/Application Support/CodexBar/helper-state.json` |
+| Automatic Reset wake schedule | CodexBar's fixed owner, `wake` type, and next time | macOS power management; removed after firing or cancellation |
+| App preferences | Switches, thresholds, shortcut, Automatic Reset lead time, and notification deduplication state | macOS UserDefaults |
+| app-server interaction log | The latest 500 requests and responses | Current app process memory only |
+
+Daily aggregations retain lists of session and turn IDs only for the latest 3 days. Older dates are reduced to counts and the lists are removed.
+
+The CodexBarHelper ownership file is owned by root and is used to recover sleep state after an unexpected CodexBar or CodexBarHelper exit.
+
+The Automatic Reset wake schedule contains no account data, reset credits, `creditId`, or idempotency key. CodexBarHelper removes schedules left by the same build identity when it starts. The app also cancels schedules when tasks change, the feature is disabled, or the app exits normally.
+
+Anonymous tasks do not participate in Stalled Task Protection, so they do not create hashed task identifiers or write to the protection-state file.
+
+## Fields Uploaded to CloudKit
+
+Each daily aggregation record may contain:
+
+- A pseudonymous device identifier scoped to the iCloud account
+- Date
+- The local Hook data source `generation`
+- Counts for each Hook event type
+- Session and turn counts
+- Project display-name counts
+- Model-name counts
+- Update time
+
+The pseudonymous device identifier is derived from the device UUID and a random salt in the iCloud private database. The raw device UUID is not uploaded.
+
+## Data Not Uploaded to CloudKit
+
+- Raw Hook event files
+- Session IDs, turn IDs, and agent IDs
+- Full working-directory paths
+- Prompts, Codex responses, tool arguments, or tool output
+- Codex account, rate-limit, or token usage data
+- Reset-credit details, Automatic Reset settings, or redemption state
+- app-server interaction logs
+- Stalled Task Protection records
+- Codex authentication tokens
+
+Project display names and model names are synced. Do not enable cross-device sync if a project name itself contains sensitive information.
+
+## Local Data Access
+
+CodexBar reads the following local data:
+
+- Account, rate-limit, token usage, reset-credit details, and Codex configuration through the local app-server
+- Raw Hook events to generate metrics and live tasks
+- Lifecycle fields from local Codex rollout files to distinguish completion from termination and supplement progress timestamps
+
+Rollout reading extracts only lifecycle, time, reasoning-effort, and similar fields. It does not display or store conversation text or tool content.
+
+After you explicitly enable Automatic Reset, CodexBar uses reset credits that the same local app-server explicitly reports as near expiration. Raw `creditId` and idempotency keys are not written to disk or CloudKit. `UserDefaults` stores only the feature switch, lead time, notification switch, sound choice, and hashed notification-deduplication keys.
+
+CodexBar does not copy or persist Codex authentication tokens.
+
+## Network Activity
+
+| Network access | Purpose | Trigger |
+| --- | --- | --- |
+| Sparkle update feed | Check for and install CodexBar updates | Automatic checking is enabled or you check manually |
+| CloudKit private database | Sync daily Hook aggregations across devices | You enable cross-device sync |
+
+Account data, rate limits, token usage, reset-credit details, and user-enabled Automatic Reset actions all use stdio communication with the local app-server. Automatic Reset does not add CloudKit requests. It sends CodexBarHelper only the time for a fixed system wake schedule, never account or reset-credit data.
+
+## Log Privacy
+
+System logs contain only operation results, state classifications, counts, and error stages.
+
+They must not record account rate-limit values, token usage, project names, task content, session IDs, turn IDs, or OAuth tokens.
+
+The in-app app-server interaction log may contain request and response data, but it exists only in current-process memory and is shown only when you explicitly open the Logs window.
+
+Back to the [User Guide](README.md)
diff --git a/Docs/en/UserGuide/troubleshooting.md b/Docs/en/UserGuide/troubleshooting.md
new file mode 100644
index 0000000..52c2b9b
--- /dev/null
+++ b/Docs/en/UserGuide/troubleshooting.md
@@ -0,0 +1,161 @@
+# Troubleshooting
+
+[简体中文](../../UserGuide/troubleshooting.md) | English
+
+## CodexBar Is Missing from the Menu Bar
+
+- CodexBar is a menu bar app and does not show a Dock icon
+- Check Control Center settings in macOS to make sure the menu bar item is not hidden
+- Launching CodexBar again from Applications does not create a second instance
+- If it is still missing, check Activity Monitor to confirm that CodexBar is running
+
+## The Main Panel Says “Not Signed In”
+
+1. Open the Codex CLI, ChatGPT App, or Codex App currently in use
+2. Sign in to Codex
+3. Double-click the account icon in the CodexBar main panel to refresh
+4. If it still says you are not signed in, quit and reopen CodexBar
+
+CodexBar prefers the global Codex CLI. The `In Use` indicator on the About page identifies the actual source.
+
+## The Main Panel Says “Initialization Failed”
+
+Common causes include:
+
+- No executable Codex installation was found
+- Codex app-server failed to start
+- app-server did not respond before the timeout
+- app-server returned a response that could not be parsed
+
+Open the Logs window for the latest failed request and error details, then check the Codex path and version on the About page.
+
+## Rate Limits or Tokens Appear Dimmed
+
+A dimmed value means that the current read failed and CodexBar fell back to cached data for the same account.
+
+The cache preserves the last available information; it does not mean that the data refreshed successfully.
+
+Double-click the account icon to retry. If the values remain dimmed, check `account/rateLimits/read` and `account/usage/read` in the Logs window.
+
+## CodexBar Hook Cannot Be Enabled or Validated
+
+| Message | Meaning | Recommended action |
+| --- | --- | --- |
+| A newer Codex version is required | The current app-server version is too old | Update Codex, then restart CodexBar |
+| Codex Hook is disabled globally | `features.hooks` is disabled | Re-enable Hooks in the Codex configuration |
+| CodexBar Hook is incomplete | At least one required event is missing the current handler | Turn CodexBar Hook off, then on again |
+| CodexBar Hook is not trusted | Codex still considers the handler untrusted or modified | Re-enable the Hook and inspect the Codex configuration |
+| Unexpected CodexBar Hook source | app-server reported a source other than the active configuration file | Check `CODEX_HOME` and the active Codex source |
+| Invalid `hooks.json` format | The top-level value or `hooks` structure is not valid JSON | Repair the JSON, then try again |
+| Unable to validate Codex Hook | app-server is temporarily unavailable or validation failed | Check the logs and reopen Settings after Codex becomes available |
+
+The Hook configuration is at `$CODEX_HOME/hooks.json`, or `~/.codex/hooks.json` when `CODEX_HOME` is unset.
+
+If CodexBar reports an incomplete Hook after an upgrade, turn the Hook off and on again to add events required by the current version.
+
+## Live Tasks Do Not Appear
+
+1. Confirm that CodexBar Hook is enabled with no error
+2. Confirm that `Show Task Center in Menu` is enabled
+3. Start a new Codex task to generate live events
+4. Open Settings to trigger Hook validation again
+
+CodexBar does not send notifications for old tasks during history replay. When data-source boundaries are unstable, it falls back safely and skips untrusted history.
+
+## System Notifications Do Not Arrive
+
+Check in this order:
+
+1. `System Notifications` is enabled
+2. macOS allows notifications from CodexBar
+3. The relevant notification option is enabled
+4. CodexBar Hook is valid for task notifications
+5. The completed task reached the selected duration threshold
+6. The notification sound is not set to silent
+
+Haptic feedback does not require macOS notification permission, but it does require CodexBar's System Notifications switch.
+
+## Sleep Prevention Does Not Engage
+
+Check in this order:
+
+1. CodexBar Hook is valid
+2. `Prevent System Sleep` is enabled
+3. A task is currently running
+4. If only waiting tasks exist, `Keep Awake While Waiting` is enabled
+5. Settings does not report that CodexBar needs approval to run in the background
+6. Low Battery Protection is not active
+7. The Keep-Awake Limit has not been reached
+
+The coffee cup indicates that system sleep is actually being prevented. An enabled switch without a coffee cup is not necessarily an error.
+
+If Settings says `System sleep is disabled by another source`, CodexBar does not overwrite that source.
+
+## CodexBarHelper Cannot Be Registered
+
+- Confirm that `Automatic Reset` or `Prevent System Sleep` is enabled; Helper status is hidden while both are off
+- If the Helper is awaiting approval, click `Open System Settings` below the settings row and allow CodexBar to run in the background
+- Confirm that CodexBar is in Applications and that the app bundle is complete
+- If the service is reported as unhealthy or the CodexBarHelper file is missing, reinstall the complete CodexBar app
+- If failures continue after an update, quit CodexBar, reopen it, and check authorization again
+
+## Automatic Reset Did Not Run on Time
+
+Check in this order:
+
+1. `Automatic Reset` is enabled and its lead time is what you expect
+2. The Automatic Reset row does not report pending CodexBarHelper approval, missing registration, or wake-schedule failure; the lead-time options appear only after the Helper is approved
+3. The current app-server response includes a specific available reset credit and expiration time
+4. Network access and Codex sign-in were available at the scheduled time
+5. `Automatic Reset Notifications` is enabled if you expected a notification; disabling notifications does not stop Automatic Reset itself
+
+Automatic Reset processes only credits explicitly listed in the latest app-server response. A single round retries network or temporary service failures continuously for no more than 5 minutes. Later normal rate-limit refreshes can schedule another attempt for a credit that remains valid.
+
+Disabling Automatic Reset or quitting CodexBar cancels the current wake schedule. To inspect system schedules, run this command in Terminal:
+
+```bash
+pmset -g sched
+```
+
+## Cross-Device Sync Is Unavailable
+
+- Confirm that the Mac is signed in to iCloud
+- Confirm that iCloud Drive and CloudKit are available
+- Confirm that CodexBar Hook is enabled
+- Confirm that `Sync Across Devices` is enabled
+- Hover over the iCloud icon at the bottom of the main panel for the detailed status
+
+A sync failure does not delete local Hook data. A later maintenance run retries it.
+
+## CodexBar Still Shows the Old Version After Updating Codex
+
+The current version comes from the running app-server handshake. The on-disk version comes from running Codex `--version` again.
+
+If About shows the new installed version but `In Use` still shows the old one, quit and reopen CodexBar.
+
+## Using the Logs Window
+
+Open it by either:
+
+- Right-clicking the menu bar icon and selecting `Log`
+- Pressing `⌘L` while the main panel is open
+
+The Logs window keeps the latest 500 app-server requests from the current process.
+
+Each entry includes request time, method, status, and response time. Expand it to inspect a request, response, or error preview.
+
+You can view or copy the full content in a separate window. It cannot be recovered after you clear the log or quit the app.
+
+## Viewing System Logs
+
+Run this command in Terminal:
+
+```bash
+/usr/bin/log stream --predicate 'subsystem == "app.zabrian.codexbar"' --style compact
+```
+
+Debug builds use a `subsystem` with a `.debug` suffix.
+
+When reporting an issue, describe the reproduction steps and visible error. Before sharing logs, check whether the in-app interaction log contains request data that you do not want to disclose.
+
+Back to the [User Guide](README.md)
diff --git a/README.en.md b/README.en.md
new file mode 100644
index 0000000..b19a181
--- /dev/null
+++ b/README.en.md
@@ -0,0 +1,115 @@
+<div align="center">
+
+<img src="Images/icon.png" width="128" alt="CodexBar">
+
+# CodexBar
+
+**Codex at a glance, right from your macOS menu bar**
+
+[简体中文](README.md) | English
+
+[![macOS](https://img.shields.io/badge/macOS-15.0+-000000?logo=apple&logoColor=white)](https://www.apple.com/macos/)
+[![Release](https://img.shields.io/github/v/release/bob-zebedy/CodexBar?color=1F6FEB)](https://github.com/bob-zebedy/CodexBar/releases)
+[![Downloads](https://img.shields.io/github/downloads/bob-zebedy/CodexBar/total?color=2EA043)](https://github.com/bob-zebedy/CodexBar/releases)
+[![License](https://img.shields.io/github/license/bob-zebedy/CodexBar?color=8957E5)](LICENSE)
+
+[Features](#features) | [Installation](#installation) | [Quick Start](#quick-start) | [Documentation](#documentation) | [Privacy](#privacy)
+
+<img src="Images/preview.gif" width="640" alt="CodexBar preview">
+
+</div>
+
+---
+
+CodexBar is a menu bar app for macOS 15 and later that brings your Codex account, rate limits, token usage, and live task status into one place.
+
+It can notify you when a task finishes, needs approval, or when your rate limits change. It can also keep your Mac awake only while Codex tasks are running.
+
+## Features
+
+### Account and rate limits at a glance
+
+- View your current Codex account and plan
+- See every rate-limit window, its remaining allowance, and reset time
+- Check available credits and reset credits
+- Automatically use reset credits from 15 minutes to 6 hours before they expire, with a default lead time of 30 minutes; CodexBar can wake your Mac at the scheduled time and revalidate availability before use
+- Show a selected rate-limit window directly beside the menu bar icon
+
+### Understand your Codex usage
+
+- Track total tokens, your highest daily usage, and usage streaks
+- See your longest task duration
+- Review 30 weeks of daily token usage in a heatmap
+- Enable CodexBar Hook for daily session, turn, tool call, subagent, and other activity metrics
+
+### Keep track of active tasks
+
+- Menu bar status dots distinguish running tasks, tasks waiting for approval, and recently completed tasks
+- The main panel shows the current task, project, model, reasoning effort, and elapsed time
+- Task Center brings concurrent, recently completed, and recently terminated tasks together
+- Receive alerts for completed tasks, approval requests, and stalled tasks
+
+### Let long-running tasks finish
+
+- Prevent system sleep only while eligible Codex tasks are active
+- Optionally stay awake while waiting for approval or keep the display awake as well
+- Set a keep-awake time limit, low-battery protection, and stalled task protection
+- Restore normal system sleep automatically when tasks finish or a protection rule is triggered
+
+### Fit naturally into macOS
+
+- Runs as a menu bar app without taking up space in the Dock
+- Supports a global keyboard shortcut, launch at login, and automatic updates
+- Provides Simplified Chinese and English interfaces
+- Optionally merges daily Hook metrics across Macs through iCloud
+
+## Installation
+
+### Homebrew
+
+```bash
+brew install --cask bob-zebedy/tap/codexbar
+```
+
+### DMG
+
+Download the latest version from [GitHub Releases](https://github.com/bob-zebedy/CodexBar/releases), then drag CodexBar into Applications.
+
+## Requirements
+
+- macOS 15.0 or later
+- [Codex CLI](https://github.com/openai/codex) installed and signed in, or ChatGPT App or Codex App with bundled Codex installed
+- The running Codex version must be `0.143.0` or later
+- Live tasks and other Hook features require the running Codex version to be `0.145.0` or later
+- Cross-device sync requires an available iCloud account on the Mac
+
+## Quick Start
+
+1. Launch CodexBar and find its icon in the menu bar
+2. Left-click the icon to view your account, rate limits, and token usage
+3. Right-click or Control-click the icon to open Settings, Logs, or the Quit menu
+4. Enable CodexBar Hook under `Settings > Advanced` to unlock live tasks, task notifications, sleep prevention, and Hook metrics
+
+The default global shortcut is `⌘⇧W`. You can record a different shortcut or disable it in Settings.
+
+## Documentation
+
+| Document | Contents |
+| --- | --- |
+| [User Guide](Docs/en/UserGuide/README.md) | Installation, main panel, Hook, notifications, sleep prevention, sync, settings, and troubleshooting |
+| [Developer Guide](Docs/en/DeveloperGuide/README.md) | Architecture, data flows, core state machines, storage, privacy boundaries, and development validation |
+| [Documentation Index](Docs/en/README.md) | Complete documentation index |
+
+## Privacy
+
+CodexBar processes all data locally. It uploads aggregated data to your private iCloud database only when you enable cross-device sync.
+
+See [Data, Sync, and Privacy](Docs/en/UserGuide/sync-data-privacy.md) for complete details about data access, local storage, and network boundaries.
+
+## Feedback
+
+Report bugs, request features, or ask questions through [GitHub Issues](https://github.com/bob-zebedy/CodexBar/issues).
+
+## License
+
+[GNU General Public License v3.0](LICENSE)
diff --git a/README.md b/README.md
index b2cedc7..e268881 100644
--- a/README.md
+++ b/README.md
@@ -6,6 +6,8 @@
**在 macOS 菜单栏一眼看清 Codex**
+简体中文 | [English](README.en.md)
+
[![macOS](https://img.shields.io/badge/macOS-15.0+-000000?logo=apple&logoColor=white)](https://www.apple.com/macos/)
[![Release](https://img.shields.io/github/v/release/bob-zebedy/CodexBar?color=1F6FEB)](https://github.com/bob-zebedy/CodexBar/releases)
[![Downloads](https://img.shields.io/github/downloads/bob-zebedy/CodexBar/total?color=2EA043)](https://github.com/bob-zebedy/CodexBar/releases)