AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
docs: drop stale internal notes that drifted from the code
tianma-ifb51703fb7649
diff --git a/apps/ios/README.md b/apps/ios/README.mdindex f2617245..b68cca69 100644--- a/apps/ios/README.md+++ b/apps/ios/README.md@@ -2,8 +2,6 @@Native SwiftUI client for EdgeEver. This replaces the React Native / Expo iOS target.-**Design document:** [`docs/ios-swift-rewrite.md`](../../docs/ios-swift-rewrite.md)-**App Store binaries on macOS beta:** use **Xcode Cloud (manual)** — [`docs/ios-xcode-cloud.md`](../../docs/ios-xcode-cloud.md).## Statusdiff --git a/docs/demo-sample-note.md b/docs/demo-sample-note.mddeleted file mode 100644index 4d09c3fa..00000000--- a/docs/demo-sample-note.md+++ /dev/null@@ -1,192 +0,0 @@-> **EdgeEver** is an open-source, AI-native, and portable serverless/containerized personal knowledge base that revives the beloved **Evernote-style three-pane layout**. Designed for geeks and content creators, it combines 100% free serverless hosting, absolute data ownership, native cross-platform clients, and seamless AI Agent (MCP) synergy to redefine your digital second brain.-------## ⚡ 1. Why Choose EdgeEver?--*Tip: In editor mode, click any table cell to edit text directly, or right-click to insert/delete rows and columns.*--| Dimension | Traditional Cloud Notes (e.g. Evernote) | Local Offline Notes (e.g. Obsidian) | EdgeEver Geek Knowledge Base |-| :--- | :--- | :--- | :--- |-| **Source Code** | Closed source | Closed-source core, open files | **Full-stack open source (AGPL-3.0)** |-| **Hosting Cost** | Costly commercial subscriptions ($10+/mo) | Official cloud sync subscription ($5+/mo) | **100% Free Forever (Cloudflare Free Tier / Docker Self-Hosted)** |-| **Data Ownership** | Proprietary lock-in, hard to export | Local Markdown, cumbersome mobile sync | **Full Ownership (D1 SQLite, R2 Storage, Lossless ZIP Archives)** |-| **Editing Experience** | Rich text only, fragile formatting | Plain Markdown, lacks WYSIWYG flow | **Seamless Dual-View (WYSIWYG Rich Text ⇄ Markdown Source)** |-| **Publishing Ready** | No typography styling, loses format | Requires 3rd-party plugins or scripts | **One-Click Rich Copy for WeChat, Substack, Medium & WordPress** |-| **Social Poster Cards** | Basic screenshots without styling | Requires external tools or plugins | **8 Built-in Exquisite Poster Themes with Typography Options & PNG/JPEG Export** |-| **Native AI Ecosystem** | Paywalled, limited features | Heavy plugin setup required | **Native MCP Server (`/mcp`) & Inline AI Agent Synergy** |-| **Cross-Platform Matrix** | Restricts active free devices | Complex setup across platforms | **Web / PWA / Android / iOS / macOS / Windows (Coming Soon)** |-------## 🏗️ 2. Architectural Overview & Ecosystem--The Mermaid diagram below demonstrates how EdgeEver connects cross-platform clients, zero-cost cloud infrastructure, and AI Agents into a cohesive workflow:--```mermaid-flowchart TD- subgraph MultiClients["Client Matrix"]- C1["Web / PWA (Offline Drafts & Sync Queue)"]- C2["macOS Desktop (Electron + Rust Sidecar)"]- C3["Android Native App (Expo + SQLite)"]- C4["iOS Native App (SwiftUI + GRDB)"]- C5["Web Clipper (Chrome / Edge / Firefox)"]- end-- subgraph CoreEngine["Service & Storage Core"]- API["Hono API Engine (Cloudflare Workers / Docker)"]- MCP["Native MCP Endpoint (/mcp 2026-07-28 & 2025)"]- D1[("D1 / SQLite Database (Sync Cursor & Revisions)")]- R2[("R2 / S3 Storage (Images & Media Attachments)")]- end-- subgraph AIAgents["AI Agents & Integrations"]- A1["Claude Code / Cursor / Antigravity"]- A2["Inline AI Assistant (OpenAI / Gemini / DeepSeek)"]- A3["Notion DB / Feishu Bitable Sync"]- end-- MultiClients <==>|REST API & Sync Cursor| API- API <==> D1 & R2- MCP <==> D1 & R2- A1 <==>|MCP Tools / SSE| MCP- A2 -.->|BYOK Direct Key| MultiClients- A1 -.->|Bi-directional Sync| A3-```-------## 🎨 3. Immersive Writing & Typography Aesthetics--EdgeEver is engineered to provide a distraction-free, elegant writing experience:--### 🖥️ Dual-View Editor & Focus Modes-- **Seamless Dual-View**: Click the `</>` button in the top-right corner (or use shortcuts) to instantly toggle between **WYSIWYG Rich Text** and **Markdown Source Code** with 100% fidelity.-- **Collapsible Outline Navigation**: Automatically indexes `H1-H3` heading hierarchies with smooth jump scrolling, keeping lengthy documents organized.-- **Zen Focus Mode**: Press `Cmd/Ctrl + Shift + F` to hide sidebars and distractions, immersing yourself in pure writing flow.-- **Reading Protection Mode**: When reading or reviewing notes, press `Cmd/Ctrl + E` to toggle read-only protection, locking the editor to prevent accidental edits while browsing; press it again to seamlessly resume editing.--### 🎭 Curated Typography Themes & Publishing Export-- **Preset Editor Themes**: Switch effortlessly between `WeChat Green`, `Fresh Mint`, `Minimal Jade`, `Lined Jade`, and styles such as Warm Page, Lesson Page, and Navy Draft.-- **One-Click Publishing Export**: Built for publishers and bloggers. Click the **WeChat Icon** in the top bar to format your note with inline CSS. Paste directly into WeChat Official Account editor, Substack, Medium, or WordPress while preserving layout and syntax highlighting.--### 🖼️ 8 Exquisite Social Poster Themes-Click **"Share as Card"** in the top-right menu to turn any note into an eye-catching poster card:-- **8 Themes**: `Slate`, `Aurora`, `Sunset`, `Midnight`, `Mint`, `Notepad` (skeuomorphic paper), `Xuan` (rice paper & Chinese ink), `Lavender`.-- **Customizable Typography**: Switch between Sans, Serif (Songti/Ming), and Monospace fonts, select compact, standard, or wide card widths, and export as high-resolution PNG or JPEG.-------## ⌨️ 4. Power Productivity Toolbox: Slash Commands, Backlinks & Math--### 🪄 Slash Commands-Type `/` or press `Space` on an empty line to invoke the command menu:-- Insert `H1/H2/H3` headings, quotes, horizontal rules, code blocks, and rich tables;-- Use `/date`, `/time`, or `/now` to insert current timestamps instantly;-- Attach files, insert images, or summon the inline AI assistant.--### 🔗 Bi-directional Note Links & Backlinks-Type `@` or insert `#memo=<memoId>` links to establish bi-directional references across your knowledge base, building an interconnected web of thoughts.--### 📐 KaTeX Professional LaTeX Mathematics-Native support for KaTeX renders complex mathematical equations in milliseconds:--- **Inline Math**: For instance, Einstein's mass-energy equivalence $E = mc^2$ or the Gaussian probability density function $f(x) = \frac{1}{\sigma \sqrt{2\pi}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}$.-- **Display Block Math**:-$$-\oint_{\partial \Omega} \mathbf{E} \cdot d\mathbf{S} = \frac{1}{\varepsilon_0} \iiint_{\Omega} \rho \, dV, \quad \oint_{\partial \Omega} \mathbf{B} \cdot d\mathbf{S} = 0-$$--### ✅ Interactive Task Lists-- [x] Explore EdgeEver's dual-view editing and outline navigation-- [x] Experiment with 8 editor themes and 8 social poster card styles-- [ ] Try typing `/` on an empty line to insert current timestamp and tables-- [ ] Connect your AI API Key to experience inline summarization and continuation-- [ ] Connect AI Agents via MCP to automate note categorization-------## 🤖 5. Native AI Agent Synergy & MCP Protocol--EdgeEver is architected for the agentic AI era, weaving LLMs directly into the knowledge management lifecycle:--```mermaid-sequenceDiagram- autonumber- actor User as Creator / Knowledge Worker- participant Client as EdgeEver Clients- participant MCP as EdgeEver MCP Endpoint- participant Agent as AI Agent (Claude / Cursor / Antigravity)- participant Database as Notion / Feishu Bitable-- User->>Client: Capture quick spark or meeting notes- Agent->>MCP: tools/call memo_search (Query unprocessed memos)- MCP-->>Agent: Returns structured Markdown & tags- Agent->>Agent: Analyzes content, extracts key takeaways & tags- Agent->>MCP: tools/call memo_update (Writes back summary & tags)- Agent->>Database: Syncs structured records to master database- Client-->>User: Sub-second live updates in client UI-```--### 1️⃣ Inline AI Assistant-Press the **`Space` bar** in an empty block, type **`/ai`**, use the **`/`** slash command menu, or select text and click the **AI button** on the floating toolbar to instantly summon the AI writing assistant:-- **Summarization & Action Items**: Condense documents into key takeaways, conclusions, and actionable todos;-- **Format-Preserving Translation**: Translate accurately into multiple languages while strictly preserving Markdown, math equations, links, and code blocks;-- **Rewriting & Continuation**: Polish phrasing, make writing concise, or continue writing seamlessly;-- **BYOK Direct Key (Bring Your Own Key)**: Direct client-side connection with OpenAI, Anthropic Claude, Google Gemini, DeepSeek, and OpenAI-compatible relays with zero third-party data transit.--### 2️⃣ Model Context Protocol (MCP) Integration-Generate an API token in **Settings → MCP Settings** to connect EdgeEver directly with Claude Code, Cursor, Antigravity, OpenClaw, and other agent platforms:-- **Direct Reading & Writing**: Connect via the `/mcp` endpoint (supports stateless `2026-07-28` protocol and handshake-based 2025 specs);-- **Automated Workflows**: Let AI Agents read, organize, summarize, tag, and synchronize notes with Notion databases and Feishu Bitable.-------## 📱 6. Multi-Platform Ecosystem, Offline Sync & Smart Clipping--- **Cross-Platform Native Apps**:- - **Web / PWA**: Full-featured in modern browsers with offline installation support;- - **Android Native App**: Built with Expo & SQLite, available on Google Play and GitHub Releases;- - **iOS Native App**: Native Swift / SwiftUI with GRDB local mirror, available on the App Store (requires a non-mainland China Apple ID);- - **macOS Desktop App**: Electron + Rust Sidecar for Apple Silicon & Intel Mac with silent background updates;- - **Windows Desktop App**: Development is complete, coming soon.-- **Browser Web Clipper**: Available on Chrome, Edge, and Firefox extension stores to extract clean, ad-free Markdown articles in one click.-- **Mobile WeChat Article Clipper**: Share any WeChat article to EdgeEver on your phone to automatically extract and format it as an editable note.-- **Offline Drafts & Sync Queue**: Keep writing seamlessly without network connectivity; changes are queued locally and automatically synced once reconnected.-------## 📦 7. Rich Media, Lossless Portability & Zero-Cost Hosting--### 🖼️ Smart Client-Side Image Compression-When pasting or dragging images into notes, EdgeEver compresses them to WebP locally in your browser before upload, **reducing file size by 50% - 90%** while preserving visual fidelity.----### 📎 Universal File Attachments-Embed PDFs, spreadsheets, archives, and multimedia files directly in notes for preview or download:-- [📄 Product brief PDF: edgeever-product-brief.pdf](/api/v1/resources/res_demo_product_brief_pdf/blob)-- [📊 Feature matrix CSV: feature-matrix.csv](/api/v1/resources/res_demo_feature_matrix_csv/blob)-- [📦 Sample attachment archive: edgeever-attachment-demo.zip](/api/v1/resources/res_demo_attachment_bundle_zip/blob)--### 🚀 Zero-Cost Serverless & Docker Self-Hosting-1. **Cloudflare Serverless (Recommended, 100% Free Forever)**: Runs entirely within Cloudflare's free tier (Workers + D1 SQLite + R2 Storage). No server bills, no VPS maintenance.-2. **Docker One-Command Deployment (VPS / NAS / Home Server)**:- ```sh- # Official GHCR image- curl -fsSL https://edgeever.org/install.sh | bash- ```- Configures Docker Compose and automated daily background updates with one command. Some network environments in mainland China may require an available network proxy or a trusted registry mirror to access GHCR.--### 💾 Complete Data Freedom: Lossless ZIP Portability-Export your entire library at any time from **Profile → Import and export**. The archive contains pure Markdown files with standard YAML Front Matter, relative media paths, and full revision histories—compatible with Obsidian, VS Code, and any plain text editor.-------> 💡 **Quick Exploration Tips**:-> 1. Click **`</>`** in the top right to try seamless dual-view toggling;-> 2. Press **`Cmd/Ctrl + E`** to test reading protection mode against accidental edits;-> 3. Press **`Cmd/Ctrl + O`** to summon the Quick Switcher;-> 4. Click the **WeChat Icon** to copy formatted rich text ready for publishing;-> 5. Click **"Share as Card"** to export a stunning social poster card;-> 6. Click **"Reset Demo Data"** in settings or the sidebar anytime to restore the demo workspace.diff --git a/docs/demo-sample-note.zh-CN.md b/docs/demo-sample-note.zh-CN.mddeleted file mode 100644index d435c2b6..00000000--- a/docs/demo-sample-note.zh-CN.md+++ /dev/null@@ -1,192 +0,0 @@-> **EdgeEver** 是一款兼具**经典三栏美学**与 **AI 原生动力**的开源 Serverless / 容器化个人知识库。它既找回了极客们钟爱的经典印象笔记式双视图与树状目录,又以零服务器成本、完全数据自主、全端原生覆盖与深度 MCP 智能体协同,重新定义了下一代个人第二大脑。-------## ⚡ 1. 为什么选择 EdgeEver?--*提示:在编辑器模式下,你可以直接点击任意表格单元格进行行内编辑,或右键快捷插入/删除行列。*--| 核心维度 | 传统商业云笔记 (如 Evernote) | 本地离线知识库 (如 Obsidian) | EdgeEver 极客知识库 |-| :--- | :--- | :--- | :--- |-| **源代码** | 闭源 | 核心闭源,文件开放 | **整栈开源 (AGPL-3.0)** |-| **云端托管成本** | 商业订阅高昂($10+/月) | 官方云同步收费($5+/月) | **100% 永久免费 (Cloudflare 免费额度 / Docker 自建)** |-| **数据资产所有权** | 专有格式封闭,导出困难 | 本地 Markdown,移动端同步繁琐 | **完全自主掌控 (D1 SQLite 数据库 / R2 / 无损 ZIP 导出)** |-| **写作与编辑体验** | 仅富文本,排版易错乱 | 纯 Markdown,缺乏沉浸所见即所得 | **双视图自由切换 (所见即所得富文本 ⇄ Markdown 源码)** |-| **自媒体排版分发** | 无样式优化,格式丢失 | 需借助外部排版扩展或工具 | **一键复制到微信公众号 / Substack / Medium / WordPress** |-| **社交卡片分享** | 截图粗糙或无排版设计 | 需第三方插件实现 | **内置 8 款精美海报主题,支持自定义字体与 PNG/JPEG 导出** |-| **AI 原生集成生态** | 封闭收费,仅限特定功能 | 需配置复杂的第三方插件 | **原生内置 MCP 服务端点 (`/mcp`) 与行内 AI 智能体协同** |-| **全平台多端覆盖** | 限制免费设备登录数量 | 多端同步与移动端体验门槛高 | **Web / PWA / Android / iOS / macOS / Windows (即将推出)** |-------## 🏗️ 2. 全景架构与生态联动--通过下面的 Mermaid 架构图,你可以清晰了解 EdgeEver 如何将多端客户端、零成本云基础设施与 AI Agent 紧密串联:--```mermaid-flowchart TD- subgraph MultiClients["全端客户端矩阵"]- C1["Web / PWA (离线草稿 & 增量同步)"]- C2["macOS 桌面端 (Electron + Rust Sidecar)"]- C3["Android 原生 App (Expo + SQLite)"]- C4["iOS 原生 App (SwiftUI + GRDB)"]- C5["浏览器剪藏插件 (Chrome / Edge / Firefox)"]- end-- subgraph CoreEngine["业务与数据服务层"]- API["Hono API 引擎 (Cloudflare Workers / Docker)"]- MCP["原生 MCP Endpoint (/mcp 2026-07-28 & 2025)"]- D1[("D1 / SQLite 数据库 (双向同步 & 修订版本)")]- R2[("R2 / S3 资源存储 (图片与多媒体附件)")]- end-- subgraph AIAgents["AI 智能体与外部生态"]- A1["Claude Code / Cursor / Antigravity"]- A2["行内 AI 助手 (OpenAI / Gemini / DeepSeek)"]- A3["Notion 数据库 / 飞书多维表格联动"]- end-- MultiClients <==>|REST API & 同步游标| API- API <==> D1 & R2- MCP <==> D1 & R2- A1 <==>|MCP Tools / SSE| MCP- A2 -.->|BYOK 密钥直连| MultiClients- A1 -.->|双向数据同步| A3-```-------## 🎨 3. 极致创作体验与排版美学--EdgeEver 将高效与优雅融入每一处交互细节,助你专注于思考与表达:--### 🖥️ 双视图编辑器与沉浸模式-- **自由切换视图**:点击右上角 `</>` 按钮或使用快捷键,可在**所见即所得富文本**与 **Markdown 源码**间无缝切换,实时双向保真。-- **左侧可折叠大纲**:自动解析文档 `H1-H3` 标题层级,支持点击平滑滚动跳转,助你轻松把控万字长文。-- **Zen 专注模式**:按下 `Cmd/Ctrl + Shift + F`,隐藏所有侧边栏与干扰元素,进入纯粹写作心流。-- **阅读保护模式 (Reading Protection)**:日常翻阅或查阅笔记时,按下 `Cmd/Ctrl + E` 即可一键开启只读保护,锁定当前编辑状态,避免沉浸阅读时误触键盘或意外改动笔记内容;再次按下即可随手切回编辑。--### 🎭 精选排版主题与一键自媒体发布-- **内置排版主题**:支持一键切换 `微信新绿`、`薄荷清新`、`极简青翠`、`线描翠绿`,以及日暖素笺、青页讲义、夜蓝制图等排版风格。-- **一键排版复制**:专为内容创作者设计。点击顶部工具栏的**微信公众号图标**,系统自动将当前笔记转为内联 CSS 样式的优雅富文本,直接粘贴至微信公众号后台、Substack 或 WordPress,排版与代码高亮完美保真。--### 🖼️ 8 套精美社交分享海报 (Poster Cards)-点击右上角“分享为卡片”,即可将任意笔记或片段渲染为高清分享海报,支持:-- **8 大主题风格**:`Slate (岩灰)`、`Aurora (极光青)`、`Sunset (落日暖橙)`、`Midnight (暗夜极客)`、`Mint (清爽薄荷)`、`Notepad (复古便签)`、`Xuan (宣纸水墨)`、`Lavender (薰衣草紫)`。-- **排版定制**:支持无衬线 (Sans)、宋体/明朝 (Serif)、等宽代码 (Mono) 字体切换,自由选择紧凑、标准或宽幅卡片,一键导出为高清晰度 PNG 或 JPEG 图片。-------## ⌨️ 4. 效率工具箱:斜杠指令、双链与数学公式--### 🪄 斜杠指令 (Slash Commands)-在正文空白行输入 `/` 或直接按下 `空格键`,即可呼出快捷指令菜单:-- 快速插入 `H1/H2/H3` 标题、引用、分割线、代码块与富文本表格;-- 输入 `/date`、`/time` 或 `/now` 快速插入当前标准时间戳;-- 插入附件、图片或调起行内 AI 智能助手。--### 🔗 知识双链与笔记引用-在编辑器中输入 `@` 或插入 `#memo=<笔记ID>` 链接,即可建立笔记间的双向关联,点击即可在工作区内快速打开关联笔记,构建结构化网状知识库。--### 📐 KaTeX 专业数学公式渲染-EdgeEver 原生支持 LaTeX 数学表达式,无论是行内微积分还是多行物理方程,均可毫秒级高保真渲染:--- **行内公式**:例如质能方程 $E = mc^2$,以及正态分布概率密度函数 $f(x) = \frac{1}{\sigma \sqrt{2\pi}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}$。-- **多行独立公式块**:-$$-\oint_{\partial \Omega} \mathbf{E} \cdot d\mathbf{S} = \frac{1}{\varepsilon_0} \iiint_{\Omega} \rho \, dV, \quad \oint_{\partial \Omega} \mathbf{B} \cdot d\mathbf{S} = 0-$$--### ✅ 交互式待办清单 (Task Lists)-- [x] 体验 EdgeEver 双视图与大纲导航-- [x] 探索 8 款编辑器主题与 8 套社交海报卡片-- [ ] 尝试使用斜杠指令 `/` 插入当前日期与结构化表格-- [ ] 配置个人 AI API Key,体验行内智能总结与续写-- [ ] 开启 MCP 协议,让 AI Agent 协助整理工作区-------## 🤖 5. AI 原生协同与 MCP 智能体生态--EdgeEver 走在 AI 时代前沿,将大语言模型与智能体深度融入知识管理生命周期:--```mermaid-sequenceDiagram- autonumber- actor User as 创作者 / 知识工作者- participant Client as EdgeEver 多端应用- participant MCP as EdgeEver MCP 服务端点- participant Agent as AI Agent (Claude / Cursor / Antigravity)- participant Database as Notion / 飞书多维表格-- User->>Client: 快速记录碎片想法与会议灵感- Agent->>MCP: tools/call memo_search (检索近期未整理笔记)- MCP-->>Agent: 返回结构化 Markdown 笔记内容与标签- Agent->>Agent: 理解内容、自动提炼核心摘要并归类标签- Agent->>MCP: tools/call memo_update (写回智能总结与增强标签)- Agent->>Database: 同步结构化字段至个人知识总库- Client-->>User: 客户端毫秒级感知更新,笔记井井有条-```--### 1️⃣ 行内 AI 助手 (Inline AI Assistant)-在正文空白行直接按下 **`空格键 (Space)`**、输入 **`/ai`**、通过 **`/`** 斜杠指令菜单,或选中文本点击浮动工具栏中的 **AI 按钮**,即可即时呼出 AI 写作助手面板:-- **精炼总结与要点提取**:一键压缩提炼全文核心结论、提取待办事项与关键行动项;-- **格式保真智能翻译**:在严格保留原有 Markdown、数学公式、链接与代码块的前提下,精准翻译多国语言;-- **内容重塑与续写**:支持润色与精炼表达,或按上下文顺滑续写;-- **BYOK 隐私直连 (Bring Your Own Key)**:支持直连 OpenAI、Anthropic Claude、Google Gemini、DeepSeek 及各类 OpenAI 兼容的中继 API,数据完全由端侧直发,不经过任何第三方中转。--### 2️⃣ 开放 MCP 协议 (Model Context Protocol)-在**设置 → MCP 设置**中生成专属令牌,即可将 EdgeEver 接入 Claude Code、Cursor、Antigravity、OpenClaw 等主流 AI 编码助手与智能体平台:-- **无缝读写**:支持标准 MCP 端点 `/mcp`(兼容最新的无状态 `2026-07-28` 协议与经典握手协议);-- **自动化流转**:AI Agent 可自动读取笔记、智能归档、批量打标,甚至与 Notion、飞书多维表格建立跨平台自动化同步。-------## 📱 6. 全平台原生覆盖、离线同步与智能剪藏--- **多端原生支持**:- - **Web / PWA**:支持现代浏览器全功能运行与离线安装;- - **Android 原生客户端**:基于 Expo 与 SQLite 构建,已上架 Google Play,并提供签名 APK 下载;- - **iOS 原生客户端**:基于 Swift / SwiftUI 与 GRDB 原生实现,流畅细腻,已上架 App Store(可使用非大陆区 Apple ID 下载);- - **macOS 桌面端**:Electron + Rust 高性能 Sidecar,支持 Apple Silicon 和 Intel Mac,内置静默后台更新;- - **Windows 桌面端**:已开发完毕,即将正式推出。-- **浏览器网页剪藏 (Web Clipper)**:已在 Chrome、Edge 和 Firefox 官方扩展商店发布,一键剔除网页广告,将正文纯净沉淀为 Markdown 笔记。-- **微信公众号一键剪藏**:在移动端系统分享菜单中,直接将微信文章分享到 EdgeEver,客户端将自动提取图文排版并转换为可编辑笔记。-- **离线草稿与弹性同步**:地铁、飞行模式等无网络环境下自由编辑,重新联网后自动入队完成增量同步与冲突协调。-------## 📦 7. 多媒体管理、无损备份与零成本自建--### 🖼️ 智能本地图片压缩-在笔记中粘贴或拖入高分辨率图片时,前端会在本地自动将其转码压缩为 WebP 格式,在保证视觉无损的前提下**减少 50% - 90% 的体积**,大幅降低云端存储占用并提升跨端加载速度。----### 📎 多类型附件自由挂载-支持在笔记中嵌入 PDF 文档、CSV 表格、压缩包及多媒体资源,点击即可在线预览或下载:-- [📄 产品白皮书 PDF:edgeever-product-brief.pdf](/api/v1/resources/res_demo_product_brief_pdf/blob)-- [📊 功能矩阵 CSV:feature-matrix.csv](/api/v1/resources/res_demo_feature_matrix_csv/blob)-- [📦 示例附件压缩包:edgeever-attachment-demo.zip](/api/v1/resources/res_demo_attachment_bundle_zip/blob)--### 🚀 两种自建部署方案:Serverless 与 Docker-1. **Cloudflare Serverless(推荐,永久 100% 免费)**:基于 Workers + D1 数据库 + R2 对象存储构建,完全处于 Cloudflare 免费额度内,无需采购服务器,免运维、免证书续期。-2. **Docker 一键自建(VPS / NAS / 家用服务器)**:- ```sh- # 官方 GHCR 镜像- curl -fsSL https://edgeever.org/install.sh | bash- ```- 单命令自动配置 Docker Compose 环境,并内置每日定时自动更新。部分中国大陆网络环境可能需要自行配置可用的网络代理或可信的镜像加速服务,才能正常访问 GHCR。--### 💾 绝对的数据自由:无损 ZIP 导入与导出-在**个人中心 → 导入与导出**中,可随时将完整笔记库打包导出为结构清晰的 ZIP 压缩包。解压后即为包含标准 YAML Front Matter、相对路径附件图片与完整修订版本的纯 Markdown 文件树,随时可在 Obsidian、VS Code 等任意工具中无缝打开,永不担心平台绑定!-------> 💡 **快速体验小贴士**:-> 1. 点击右上角 **`</>`** 体验丝滑的双视图切换;-> 2. 按下 **`Cmd/Ctrl + E`** 试一试阅读保护模式,锁定只读避免误改内容;-> 3. 按下 **`Cmd/Ctrl + O`** 呼出快速切换器 (Quick Switcher);-> 4. 点击顶部 **微信图标**,体验一键带格式排版复制;-> 5. 点击 **“分享为卡片”**,挑选一款你心仪的社交海报风格并导出;-> 6. 随时在侧边栏或设置中点击 **“恢复 Demo 数据”**,一键重置演示工作区。diff --git a/docs/desktop-performance-baseline.md b/docs/desktop-performance-baseline.mddeleted file mode 100644index 809b6290..00000000--- a/docs/desktop-performance-baseline.md+++ /dev/null@@ -1,65 +0,0 @@-# Desktop performance baseline--The desktop app must remain a local-first application. Remote network latency-must not be part of the critical path for opening or editing a note.--## Acceptance targets--| Operation | Target |-| --- | ---: |-| Sidecar ready after process spawn | `< 500 ms` |-| Local SQLite health request | `< 20 ms` |-| Existing local memo list query | `< 50 ms` |-| Existing local memo detail query | `< 20 ms` |-| Create/edit local memo acknowledgement | `< 50 ms` |-| Cloud sync | Background only |--The Web/PWA build keeps the install-time service-worker precache limited to the-web manifest. Mermaid,-diagram renderer, code-highlighting, and editor-only Tiptap/ProseMirror chunks-stay out of the initial HTML `modulepreload` list and fill runtime caches on-first use, so ordinary note-list startup does not pay for optional-editor/diagram support. The initial modulepreload list is also capped at 750 KiB-uncompressed; the build verifier reports the measured bytes and fails if this-critical-path budget regresses. The web app remains installable through the-manifest.--Remote resource blobs use a separate 90-day, 500-entry cache-first runtime-cache. When the browser is offline, newly attached files are written to the-same Cache Storage namespace under a local resource URL, added to the local-resource mirror, and queued for upload. The sync worker uploads the bytes,-rewrites memo JSON/Markdown references, and only then removes the local blob.--## Repeatable checks--Build and benchmark the sidecar:--```sh-cargo build --manifest-path crates/desktop-sidecar/Cargo.toml --release-EDGE_EVER_SIDECAR_PATH="$PWD/crates/desktop-sidecar/target/release/edgeever-sidecar" \- bun run benchmark:desktop:sidecar-```--Build an unsigned local desktop bundle and inspect that the bundle contains-the Web renderer, migrations, and sidecar:--```sh-bun run build:web-cargo build --manifest-path crates/desktop-sidecar/Cargo.toml --release-CSC_IDENTITY_AUTO_DISCOVERY=false \- bun --cwd apps/desktop run dist -- --dir-```--The benchmark exercises the same local domain RPCs used by the desktop-renderer: notebook discovery, memo creation, memo list, and memo detail. Its-`thresholds` object is suitable for CI gating; remote sync is deliberately not-included in the interactive critical path.--Verify that the install-time PWA precache contains only the web manifest and-that optional editor and diagram chunks stay out of the initial HTML-modulepreload list:--```sh-bun run build:web-bun run verify:web-performance-```diff --git a/docs/ios-swift-rewrite.md b/docs/ios-swift-rewrite.mddeleted file mode 100644index 9a125c93..00000000--- a/docs/ios-swift-rewrite.md+++ /dev/null@@ -1,1381 +0,0 @@-# EdgeEver iOS Swift Rewrite--| Field | Value |-| --- | --- |-| **Document** | EdgeEver iOS native rewrite (drop React Native on iOS) |-| **Author** | TBD |-| **Date** | 2026-08-06 |-| **Status** | Approved (rev 4 — design review consensus; scaffold PR 1 landed) |-| **Audience** | Senior engineers implementing `apps/ios` |-| **Related** | `docs/mobile-native-parity.md`, `apps/mobile`, `packages/client`, `packages/shared` |-------## Overview--EdgeEver’s mobile client today is a single Expo / React Native app in `apps/mobile` targeting both Android and iOS. Android is on Google Play and is healthy. iOS has been under App Store review but fails in production with hard crashes inside React Native’s JS runtime and Fabric attributed-string paths (`EXC_BREAKPOINT` / `SIGTRAP` on `com.facebook.react.runtime.JavaScript`, malloc aborts near Hermes / AttributedString). These are not ordinary app-logic bugs; further RN crash debugging on iOS is an open-ended cost with low confidence of a durable fix.--**Product decision (final):** abandon the React Native iOS path entirely and ship a pure Swift / SwiftUI native app under `apps/ios`, keeping the same App Store listing and bundle identifier `org.edgeever.mobile`. Android remains Expo / RN in `apps/mobile`. The first App Store submission of the Swift binary **must include full editing** (login, list, sync, create/edit/autosave, offline queue, TipTap body)—not a read-only MVP.--This document specifies architecture, API surface, SQLite schema, sync state machine, TipTap WKWebView integration, save lifecycle, directory layout, acceptance criteria, migration from RN iOS, risks, key decisions, and an ordered PR / work-package plan suitable to scaffold `apps/ios` immediately after approval.-------## Background & Motivation--### Current mobile architecture (RN)--| Layer | Location | Role |-| --- | --- | --- |-| Shell UI | `apps/mobile/src/screens/*` | Login, workspace, notes list, detail chrome, settings |-| Local mirror | `apps/mobile/src/lib/local-mirror.ts` | SQLite: notebooks, memos, sync meta, id mappings |-| Sync protocol helpers | `apps/mobile/src/lib/mobile-sync-protocol.ts` | Cursor rewind / identity change / bootstrap batching |-| Offline outbox | `apps/mobile/src/lib/sync-queue.ts` | `memo.create` / `memo.update` queue (AsyncStorage) |-| Session | `apps/mobile/src/lib/session.tsx` | SecureStore session + deviceId; Bearer token |-| API client | `packages/client/src/index.ts` | Full REST surface against `/api/v1/*` |-| Editor | `apps/mobile/src/components/LocalTiptapEditor.tsx` | TipTap in Expo DOM / WebView; shared toolbar copy in `@edgeever/shared/mobile-editor` |-| Share extension | `apps/mobile/ios/expo-sharing-extension/ShareIntoViewController.swift` | Already native Swift; App Group + open host app |-| Parity rules | `docs/mobile-native-parity.md` | Native shell for lists/nav/settings; TipTap WebView for note body; exclude ZIP import/export and trash browse from app core |--### Pain points--1. **iOS RN instability under review:** crash logs under `.tmp-app-review-crashes/` point at RN Fabric / Hermes, not EdgeEver business logic.-2. **Dual-platform RN cost on a broken half:** energy spent on iOS RN does not improve Android and blocks App Store continuity.-3. **Editor already hybrid:** TipTap is hosted in a WebView on mobile today. A native Swift shell with the same WebView document model is a smaller leap than rewriting the editor in native text views.-4. **Share extension is already Swift:** host-app rewrite can absorb and simplify the extension without Expo plugin constraints.--### Product constraints (confirmed)--- Minimum deployment target: **iOS 17** (SwiftUI-first).-- **Editing required** before first App Store submission of the Swift binary.-- Bundle ID continuity: **`org.edgeever.mobile`** (see `apps/mobile/app.json`).-- Android path: **unchanged** Expo/RN in `apps/mobile`.-- Repo policy (`AGENTS.md`): work on **`main` only** (no new git branches); bilingual docs when changing Chinese docs.-- Soft delete only on mobile (no trash browse UI); recovery remains desktop/PWA.-------## Goals & Non-Goals--### Goals--1. Ship a store-ready native iOS app with:- - Login to self-hosted or cloud instance (`baseUrl` + username/password + `deviceId`).- - Notebook hierarchy browse/select + memo list (filter, sort, pin, search, soft delete); memo move-to-notebook via content outbox.- - Local SQLite mirror + incremental sync (`/api/v1/sync/bootstrap`, `/api/v1/sync/changes`).- - Create / rich-edit / autosave with TipTap body (same `TiptapDoc` schema as web/RN).- - Offline create/update queue with revision conflict handling and `local:` id remap.- - Protected resource loading (images/attachments) with Bearer token.- - Image upload with optional compression and placeholder UX.- - Share Extension (text / URL → open app and create draft).- - Settings subset: locale, theme, image compression, account security (password), API tokens, device sessions, sign out.-2. Keep API contracts identical to `packages/client` (no backend fork for iOS).-3. Preserve App Store listing continuity (same bundle id, ASC app id `6792625631`).-4. Stop EAS iOS builds and RN iOS maintenance; document Android-only evolution of `apps/mobile`.-5. Structure `apps/ios` so an engineer can scaffold and implement module-by-module from this doc.--### Non-Goals (v1 submission)--- ZIP import/export, trash browse / empty trash UI.-- Multi-user **admin** UI (`listUsers` / create/disable users). RN mobile only shows the current user's role label in settings—it does **not** ship a user-management console. Do not invent one for iOS.-- Full desktop feature parity (templates library management, merge UI polish, object-storage admin).-- Replacing Android RN with Kotlin/Compose (out of scope).-- OTA JS updates on iOS (EAS Update ends for iOS; native releases only).-- Shared Swift package for Android (impossible); do **not** invent a third shared runtime.-- Offline-first for **every** mutation: content create/update always use the outbox (K6/K14); pin and soft-delete of already-synced notes remain **online-first** (match RN). Notebook **create/rename/delete** is **Deferred** (RN mobile has no CRUD UI).-- Rewriting TipTap in native Swift text views.-- Share Extension media (image/video/audio/file) in v1 (text + web URL only; intentional reduction vs current RN Share extension).--### v1 vs current RN parity matrix--Signed-off scope relative to `docs/mobile-native-parity.md` and today's `apps/mobile` implementation. **Required** = must pass store acceptance. **Deferred** = post-v1 / may land if schedule allows without blocking review. **Out of scope** = not in mobile app core.--| Capability | RN today | iOS Swift v1 |-| --- | --- | --- |-| Login + self-hosted instance | Implemented | **Required** |-| Notebook hierarchy browse + select/filter | Implemented (select/hierarchy only; **no** create/rename/delete UI—`createNotebook`/`updateNotebook`/`deleteNotebook` unused in `apps/mobile/src`) | **Required** (select/filter/tree from mirror; empty set → “请先创建一个笔记本” / create elsewhere) |-| Notebook create / rename / delete | Not in RN app UI | **Deferred** (desktop/PWA; not Gate A/B) |-| Move memo to notebook | Implemented (content path / picker) | **Required** (via memo edit notebook field + outbox `memo.update` / create payload) |-| Memo list, filter, sort, search | Implemented | **Required** |-| Pin / unpin | Implemented (online `updateMemo`) | **Required** (online-first) |-| Batch move / multi-select | Implemented | **Deferred** (single-note move OK if easy) |-| Soft delete | Implemented | **Required** |-| Local TipTap create/edit + autosave | Implemented | **Required** (gate) |-| Offline drafts + mirror + outbox | Implemented | **Required** (gate) |-| Note body viewer (TipTap) | Implemented | **Required** |-| In-note image load (Bearer) | Implemented | **Required** |-| Image upload + compression | Implemented | **Required** for App Review; **not** required for internal text-only edit gate |-| In-note attachment open / rename / delete | Implemented (`handleRenameResource` / `handleDeleteResource`) | **Required** for Gate B (body actions—not the full resource library screen) |-| Resource library screen | Implemented | **Deferred** |-| Tag management (rename/delete global tags) | Implemented | **Deferred** (tags on memo edit Required) |-| Revision history + restore | Implemented | **Deferred** (prefer include if time; not edit-gate) |-| Memo share links | Implemented | **Deferred** |-| MCP/API token management | Implemented | **Required** |-| Password change | Implemented | **Required** |-| Device sessions revoke | Implemented | **Required** |-| Multi-user admin console | Parity doc “Implemented” overstates; settings show role only | **Out of scope** |-| Share Extension text/URL | Implemented | **Required** |-| Share Extension image/video/file | Implemented in Swift extension | **Deferred** (call out in release notes) |-| ZIP import/export, trash browse | Excluded from core | **Out of scope** |-| EAS Update OTA | iOS+Android | Android only; iOS **Out of scope** |-------## Key Decisions--| # | Decision | Rationale |-| --- | --- | --- |-| K1 | **Pure Swift / SwiftUI app in `apps/ios`; abandon RN iOS entirely** | RN Fabric/Hermes crashes are not fixable with app logic. Native shell is the product requirement for store reliability. `app.json` has `newArchEnabled: true`; crash stacks align with Fabric/Hermes, reinforcing abandon over patching. |-| K2 | **iOS 17+ only** | Unlocks modern SwiftUI navigation, Observation, and simpler concurrency without UIKit-heavy polyfills. Acceptable given crash recovery priority. |-| K3 | **Same bundle id `org.edgeever.mobile` and ASC app** | Continuity of reviews, ratings, and existing App Store Connect configuration (`eas.json` `ascAppId: 6792625631`). |-| K4 | **Editing + offline queue required before first Swift submission** | Product decision: no read-only MVP. Match RN mobile core capture loop. |-| K5 | **GRDB + SQLite local mirror with same semantic tables as RN** | Proven protocol in `local-mirror.ts`; GRDB is the mature Swift SQLite layer with migrations and observation. |-| K6 | **Committed content create/update always go through optimistic mirror + SQLite outbox; never bypass the queue for body/title/tags/notebook on the content path** | Matches RN: edits of existing memos use `localUpdateMemoMutation` (queue + mirror); first commit of a new note uses `local:` + `memo.create` or, after materialize, `memo.update`. **Uncommitted new-note composer** matches RN create-sheet: draft-only (`mobile_drafts` / `new`) until Done **or** materialize-for-image—no parallel bare `createMemo` + pending `memo.create`. Online-first is **rejected** for content saves of committed memos. |-| K24 | **At most one server create per new-note session; materialize never races outbox create** | RN `materializeMemoForImage` only runs when create-sheet has no pending `memo.create` (drafts only). iOS uses the same draft-until-commit/materialize model for new notes, plus an explicit lock algorithm if a `local:` create is already queued (see Materialize algorithm). |-| K7 | **URLSession-based API client port of `packages/client` subset** | No dependency on JS packages at runtime. Hand-port Codable models from `packages/shared/src/types.ts` + OpenAPI. |-| K8 | **Keychain for session token + deviceId; App Group `group.org.edgeever.mobile` for Share Extension** | Matches SecureStore semantics; group id already in `EdgeEver.entitlements` and share extension (confirm Apple Developer portal still matches). |-| K9 | **WKWebView hosts TipTap for viewer + editor; native chrome around it** | Same document schema (`TiptapDoc` JSON), Mermaid, tables, images as web/RN. Avoid dual editors. |-| K10 | **Editor assets: versioned static `EditorBundle` built from monorepo `EditorSource` (Vite)** | Load via `loadFileURL`. Incremental milestones (viewer → editor → resources → mermaid). Smoke-test with Vitest where feasible. No remote editor at runtime. |-| K11 | **Message bridge: typed JSON over `WKScriptMessageHandler` + `evaluateJavaScript`** | Replaces Expo DOM imperative handle (`LocalTiptapEditorRef`). |-| K12 | **Resource images: native fetch with Bearer → data URL or temp file injected into WebView** | Mirrors RN `getResourceBlob` → `blobToDataUrl` / `onLoadResource`. Do not rely on cookie sessions. |-| K13 | **Offline ids: `local:` prefix; survive bootstrap rebuild; remap via `mobile_id_mappings`** | Exact RN semantics in `local-mirror.ts` / `sync-queue.ts`. |-| K14 | **Outbox kinds v1: `memo.create`, `memo.update` only for committed content; materialize is a separate single online create (K24)** | Matches RN queue for Done/offline create and all updates. Soft delete of remote notes is online; local-only pending creates cancel queue + delete row. Pin online-first. Notebook create/rename/delete **Deferred** (not RN mobile). Materialize may call `createMemo` **only** under K24 (never while a live `memo.create` remains queued). |-| K15 | **Conflict model: revision + contentHash + edit sessions** | Flush: `createMemoEditSession` then compare `baseRevision`/`baseContentHash` to expected; mismatch → `revision_conflict` **before** PATCH. On 409 / precheck conflict, mark queue `conflict` and offer discard-local / keep draft. |-| K16 | **Android stays Expo/RN in `apps/mobile`; stop iOS EAS builds only after Swift TestFlight validates edit AC** | Ordering hazard: do not remove EAS iOS job until a Swift binary is shippable. Then CI/release scripts become Android RN + native iOS pipelines. |-| K17 | **Share Extension rewritten under `apps/ios` control** | Drop Expo sharing plugin; keep App Group payload pattern. v1 = text + web URL only. |-| K18 | **No new git branches** | `AGENTS.md`: ordered **work packages / commit series on `main`**. “PR” in this doc means logical reviewable package, **not** a mandate to open long-lived GitHub branches. |-| K19 | **Minimum TipTap feature set for store = RN mobile toolbar** | Bold, bullet list, indent, blockquote, HR, image; tables/Mermaid render; not full desktop toolbar. |-| K20 | **Markdown conversion runs inside EditorBundle only; native Swift does not reimplement markdown** | Wire format for create/update remains `contentMarkdown` (RN). Editor works in `TiptapDoc` JSON; `docToMarkdown` / `markdownToDoc` use the same TipTap Markdown extension path as `@edgeever/shared` content, validated by shared golden fixtures. Autosave payloads are markdown strings produced by the bundle (or via bridge `getMarkdown()`), not a second Swift converter. |-| K21 | **Cross-client sync contract fixtures are shared and required** | Android RN and iOS Swift both consume golden fixtures under `tests/mobile-sync-fixtures/` (or `packages/shared`); Android mirror/queue changes update fixtures in the same commit series. |-| K22 | **HTTPS default; optional user-confirmed `http://` for LAN self-host** | Match Android cleartext practicality with explicit warning; limited ATS exception + App Review notes. |-| K23 | **Freeze/remove `apps/mobile/ios` generation once Android-only prebuild is configured** | Prevent accidental EAS iOS builds from the RN tree after cutover. |-------## Proposed Design--### High-level architecture--```mermaid-flowchart TB- subgraph iosApp ["apps/ios EdgeEver.app"]- UI[SwiftUI Shell<br/>Login / List / Detail / Settings]- Session[SessionStore<br/>Keychain]- API[APIClient<br/>URLSession]- Mirror[LocalMirror<br/>GRDB SQLite]- Outbox[SyncOutbox<br/>SQLite]- SyncEngine[SyncEngine<br/>bootstrap + changes + flush]- Editor[TipTapWebView<br/>WKWebView + bridge]- ShareHost[ShareHandoff<br/>App Group]- UI --> Session- UI --> Mirror- UI --> SyncEngine- UI --> Editor- SyncEngine --> API- SyncEngine --> Mirror- SyncEngine --> Outbox- Editor --> API- Session --> API- ShareHost --> UI- end-- subgraph server ["EdgeEver API"]- Auth["/api/v1/auth/*"]- Sync["/api/v1/sync/*"]- Memos["/api/v1/memos/*"]- Res["/api/v1/resources/*"]- end-- API --> Auth- API --> Sync- API --> Memos- API --> Res-- subgraph shareExt ["Share Extension"]- SE[ShareViewController]- SE --> ShareHost- end-```--### Layering--| Layer | Responsibility | Tech |-| --- | --- | --- |-| **Presentation** | Navigation, lists, forms, sheets, accessibility | SwiftUI, iOS 17+ |-| **Application** | Use cases: sign-in, open memo, save draft, run sync | Actors / `@Observable` stores |-| **Domain models** | `Notebook`, `MemoDetail`, `SyncChange`, queue items | Codable structs (parity with `packages/shared`) |-| **Data** | Mirror queries, outbox mutations, preferences | GRDB, FileManager cache |-| **Network** | REST, multipart upload, blob download | URLSession |-| **Editor host** | Load TipTap bundle, bridge messages, inject resources | WKWebView |-| **Security** | Tokens, App Group, ATS | Keychain, entitlements |--### Navigation / screens (v1)--```mermaid-flowchart LR- Launch --> SessionCheck- SessionCheck -->|no session| Login- SessionCheck -->|session| Workspace- Login --> Workspace- Workspace --> NotesList- Workspace --> Settings- NotesList --> MemoDetail- MemoDetail --> MemoEditor- NotesList --> CreateMemo- CreateMemo --> MemoEditor- Settings --> AccountSecurity- Settings --> ApiTokens- Settings --> DeviceSessions-```--| Screen | RN source of truth | Notes |-| --- | --- | --- |-| Login | `LoginScreen.tsx` | `baseUrl`, username, password; normalize URL like `session.tsx` |-| Workspace shell | `WorkspaceScreen.tsx` | Notebook sidebar/sheet + notes stack |-| Notes list | `WorkspaceNotesView.tsx` | Search debounce 250ms; sort/filter; density |-| Memo detail (viewer) | `WorkspaceMemoDetail.tsx` | Native chrome + TipTap `mode: viewer` |-| Create / edit | create sheet + rich edit session in `WorkspaceScreen.tsx` | TipTap `mode: editor` + autosave |-| Settings | `WorkspaceSettingsView.tsx` | Locale, theme, compression, sync status, sign out |-| Account security | `AccountSecurityModal.tsx` | Change password |-| Sync conflicts | inline in workspace | Discard local / copy draft (port `discardMobileMemoConflict`) |--### Data scope--Mirror and outbox are partitioned by:--```text-scope = lowercased(trimmed baseUrl) + "|" + (userId ?? "anonymous")-```--Same as `createMobileDataScope` in `local-mirror.ts`. Signing out or switching account must not leak rows across scopes. Identity change / full rebuild clears remote rows for the scope but **preserves `id LIKE 'local:%'`** memos.--### Sync engine state machine--```mermaid-stateDiagram-v2- [*] --> Idle- Idle --> CheckingMeta: appActive / pullRequested- CheckingMeta --> Bootstrap: cursor missing OR identity missing- CheckingMeta --> Incremental: meta OK- Bootstrap --> WritingSnapshot: pages from /sync/bootstrap- WritingSnapshot --> Bootstrap: has nextAfterId- WritingSnapshot --> Incremental: snapshot complete, set cursor+identity- Incremental --> ApplyingChanges: /sync/changes- ApplyingChanges --> Rebuild: cursorRewound OR identityChanged- Rebuild --> Bootstrap: clear cursor+identity meta- ApplyingChanges --> Incremental: hasMore- ApplyingChanges --> FlushOutbox: !hasMore- FlushOutbox --> Idle: done- FlushOutbox --> FlushOutbox: next pending item- FlushOutbox --> ConflictItem: 409 revision_conflict- ConflictItem --> Idle: user resolves or leaves-```--**Rules (match RN):**--1. Single-flight per scope (RN uses `syncPromises` map).-2. Bootstrap page size **200** (RN passes 200; `packages/client` default is 100—do not use the client default); write batches of 50.-3. Changes page size 200.-4. On rewind (`serverCursor < localCursor`) or identity mismatch: delete `cursor`+`identity` meta keys and re-bootstrap; delete non-`local:` memos; re-upsert notebooks from snapshot.-5. **Outbox flush triggers** (any of these; not only “after pull”):- - Queue becomes non-empty after enqueue (create/update/autosave).- - App becomes active / foreground (`scenePhase == .active`).- - After a successful mirror pull completes (opportunistic).- - Retry timer fires for `error` items (`nextAttemptAt`).- - Match RN `useMobileAutomaticSync`: if already running, coalesce a follow-up run (`requestedRef` pattern).-6. Flush order: oldest `createdAt` among `pending` / `error` / `syncing` with `nextAttemptAt == null || nextAttemptAt <= now`.-7. Retry backoff: `min(5min, 2^min(attempt,6) * 1s)` — port `getSyncRetryDelayMs` from `packages/shared/src/sync.ts`.-8. Create absorbs subsequent updates for the same memo id (RN `queueMobileMemoUpdate` folds title/markdown/notebook/tags into pending `memo.create`).-9. On successful create: `replaceLocalMemoId(temporaryId, remoteMemo)` + insert id mapping; if queue version moved during flight, promote remaining create payload to `memo.update` against new id (`promoteQueuedMemoCreate`).-10. On successful update while a newer version was enqueued: rebase `expectedRevision`/`expectedContentHash` from server memo (`rebaseQueuedMemoUpdate`).-11. On successful create flush when the queue item was **removed mid-flight** (user cancelled/deleted local note): soft-delete the remote orphan (`deleteMemo(id, permanent: false)`) — RN best-effort cleanup in `syncMobileQueuedChanges`.-12. Edit-session precheck on flush of `memo.update`: after `createMemoEditSession`, if `editSession.baseRevision != expectedRevision` **or** `editSession.baseContentHash != expectedContentHash`, treat as `revision_conflict` **before** calling `updateMemo` (RN `syncMobileQueueItem`).--#### Soft delete algorithm (port `mobile-memo-delete.ts`)--For each memo id in a delete request:--1. Classify **local-only** vs **remote**:- - Local-only if `id` starts with `local:` **or** there is a pending `memo.create` for that id.- - Exception: if `local:` maps via `mobile_id_mappings` / `resolveLocalMemo` to a non-local remote id without pending create, treat as remote.-2. **Local-only path:** `cancelMobileMemoQueueItems` (all kinds for that memoId) → hard `DELETE` mirror row → clear draft. **No API call.**-3. **Remote path:** require online client; `deleteMemo` (single) or `deleteMemos` (batch) with `permanent: false` for ordinary mobile delete → `softDeleteLocalMemo` (set `isDeleted`/`deletedAt` on mirror) → clear draft. Permanent delete only if explicitly requested (not default UI).-4. In-flight create race: if create flush already succeeded and user deleted local-only id that was remapped, resolve mapping and soft-delete remote; if create flush completes after cancel and finds item removed, soft-delete remote orphan (rule 11).--### Editing save lifecycle--**Hard decision (K6/K14/K24):**--1. **Committed content** create/update always optimistic mirror + outbox. Online-first content save for committed memos is rejected.-2. **New-note composer** matches RN create-sheet (`WorkspaceScreen` create path): **draft-until-Done-or-materialize**—no `memo.create` and no mirror list row until the user commits (Done) **or** materializes for image upload. This prevents double server creates.-3. Direct online `updateMemo` remains reserved for **non-content** paths such as pin.--RN reference:--| Situation | RN behavior | iOS |-| --- | --- | --- |-| New note typing before Done | `writeMobileNewMemoDraft` only (~350 ms); **no** outbox | Same → `mobile_drafts` key `new` |-| Done offline / no prior materialize | `local:` + `upsertLocalMemo` + `queueMobileMemoCreate` | Same |-| Done after materialize | optimistic update + `queueMobileMemoUpdate` on **server** id | Same |-| Image on create sheet | `materializeMemoForImage` → online `createMemo` once (no pending create); then upload | Same algorithm below |-| Edit existing memo | `localUpdateMemoMutation` always outbox | Same |--```mermaid-sequenceDiagram- participant User- participant Editor as TipTapWebView- participant Store as MemoEditStore- participant Drafts as mobile_drafts- participant Mirror as LocalMirror- participant Outbox as SyncOutbox- participant Sync as SyncEngine- participant API as APIClient-- alt New note before commit- User->>Editor: type- Editor->>Store: change- Store->>Drafts: write draft key new- Note over Drafts: No memo.create yet (RN create-sheet)- else Done without materialize- Store->>Mirror: upsert local: MemoDetail- Store->>Outbox: memo.create- else Edit committed / after materialize- Store->>Mirror: upsert optimistic- Store->>Outbox: memo.update or absorb into pending create- end- Sync->>Outbox: flush- Outbox->>API: createMemo OR editSession + updateMemo- API-->>Outbox: MemoDetail- Outbox->>Mirror: replaceLocalMemoId / upsert-```--**Mutation classes:**--| Class | Examples | Path |-| --- | --- | --- |-| **Uncommitted new draft** | Create-sheet typing before Done/materialize | `mobile_drafts` only—**not** outbox, **not** list row |-| **Content (outbox)** | Done on new note (`memo.create`); edits after materialize or of existing memo (`memo.update`); create-absorbs-update while `local:` pending | Optimistic mirror + outbox → flush |-| **Materialize (online create, once)** | First image on uncommitted new note | Online `createMemo` under K24 rules; then content path is `memo.update` only |-| **Online-first** | pin/unpin; soft-delete remote note | API immediately; on failure alert + keep prior UI; mirror on success |-| **Deferred online-first** | notebook create/rename/delete | Not in RN mobile UI; post-v1 if needed |-| **Local-only** | discard unsynced `local:` create or new draft | Cancel outbox if any + delete mirror/draft (no API) |--#### New-note create path (RN-aligned)--1. Require a target `notebookId` (default notebook from mirror; block if none with “请先创建一个笔记本”).-2. While composing: autosave **only** to `mobile_drafts` (`draft_key = new` for scope) at ~350 ms—**do not** allocate `local:`, **do not** enqueue `memo.create`, **do not** call `createMemo`.-3. **Done without prior materialize:**- - Allocate `temporaryId = "local:" + base36(time) + ":" + random`.- - Build `MemoDetail` (`revision: 0`, `contentHash: "local:" + temporaryId`, full content fields).- - `upsertLocalMemo` + `queue memo.create` (title, contentMarkdown, notebookId, tags, createdAt).- - Clear draft `new`. List shows the note; flush creates server row later.-4. **Done after materialize:** treat as update path on server memo id (`memo.update` outbox + mirror upsert); clear memo draft; **never** enqueue `memo.create` for that session.-5. Subsequent autosaves while `memo.create` still pending for a `local:` id **fold into** the create payload (create-absorbs-update)—never parallel `memo.update` for the same `local:` id.-6. Images: run **Materialize algorithm** (below) before upload; offline → disable image control with clear copy.--#### Materialize algorithm (at most one server create) — K24--Invariant: for a given new-note composer session / `local:` id, **exactly one** of: (a) pending or completed outbox `memo.create`, or (b) a successful online materialize `createMemo`—never both, and never two online creates.--Implement as a single actor method `materializeForImage(session)` with exclusive lock on `(scope, sessionId)`:--```text-materializeForImage(session):- // session holds: optional localId, optional serverMemo, current editor payload-- if session.serverMemo != null:- return session.serverMemo // already materialized (RN materializedMemoRef)-- if session.localId != null:- resolved = resolveLocalMemo(scope, session.localId)- if resolved != null AND not resolved.id.hasPrefix("local:"):- session.serverMemo = resolved- return resolved // outbox create already remapped-- require online client else throw needNetworkForImages-- with exclusiveTransaction(scope, memoKey: session.localId ?? session.draftKey):- createItem = outbox.find(kind: memo.create, memoId: session.localId) if localId else nil-- if createItem == null AND session.localId == null:- // RN common case: draft-only create-sheet- response = API.createMemo(currentPayload)- session.serverMemo = response.memo- upsertLocalMemo(response.memo)- clearDraft(new)- // NO memo.create enqueued- return response.memo-- if createItem == null AND session.localId != null:- // Mirror row exists without outbox create (unexpected); still only one create- response = API.createMemo(currentPayload)- replaceLocalMemoId(session.localId, response.memo) // or upsert + delete local + mapping- session.serverMemo = response.memo- session.localId = response.memo.id- return response.memo-- if createItem.status == "syncing":- // Create already in flight — MUST NOT call createMemo again- await flushWaitFor(createItem) // or wait for SyncEngine completion for this id- resolved = resolveLocalMemo(scope, session.localId)- if resolved == null OR resolved.id.hasPrefix("local:"):- throw materializeFailed- session.serverMemo = resolved- session.localId = resolved.id- return resolved-- if createItem.status == "pending" OR createItem.status == "error":- // Outbox would also create — cancel first, then single online create (or wait-for-flush)- // Preferred for image latency: cancel + online create with latest editor payload- cancelOutboxItem(createItem) // version-checked remove; no API- response = API.createMemo(currentPayloadFromEditor) // includes latest title/body/tags- replaceLocalMemoId(session.localId, response.memo)- session.serverMemo = response.memo- session.localId = response.memo.id- // Do NOT re-queue memo.create; further edits → memo.update only- return response.memo-- if createItem.status == "conflict":- // memo.create should not 409; surface error, do not create second memo- throw materializeFailed-```--**Forbidden:**--- Calling `API.createMemo` while a `memo.create` for the same local id remains in outbox (`pending`/`error`/`syncing`).-- Enqueueing `memo.create` after a successful materialize for that session.-- Leaving both a remapped server row and a live `memo.create` for the old `local:` id.--**After materialize:** image upload uses `session.serverMemo.id`; editor autosave uses `memo.update` with that id’s revision/hash; Done uses update path (RN createMutation materialized branch).--**Unit tests (required for Gate B / PR 7):** draft-only materialize → one `createMemo`; materialize after Done with pending create → cancel then one `createMemo` OR wait-flush zero extra creates; materialize while `syncing` → zero extra `createMemo`; concurrent double-tap image → single create (lock).--**Update path (content) — existing or post-materialize memo:**--1. Base revision/hash from current mirror row (`resolveLocalMemo`), not stale UI-only state.-2. Optimistic upsert of title, tags, notebookId, contentJson/markdown/text/excerpt + `queue memo.update` with `expectedRevision` / `expectedContentHash` and full content fields.-3. Title, tags, and notebook changes participate in the **same** autosave/outbox path as body (not body-only).-4. Flush: `POST /memos/:id/edit-sessions` → precheck base revision/hash → `PATCH` with `editSessionId` + expectations + contentMarkdown/title/tags/notebookId.-5. Autosave debounce: **500 ms** idle after editor body change (`CHANGE_IDLE_MS`); title/tags ~**350 ms**. Force flush on `scenePhase` background / resign active (for **committed** mirror rows / outbox items; uncommitted new drafts only force-write `mobile_drafts`).--**Drafts (process death):**--- New uncommitted: `mobile_drafts` key `new` (RN `edgeever.mobile.newMemoDraft:`).-- Committed / editing existing: `mobile_drafts` key `memo:<id>` (RN `edgeever.mobile.memoDraft:`).-- On editor open, rehydrate draft if newer than mirror; clear after successful commit enqueue or discard.--### TipTap / WKWebView integration--#### Hosting model and extraction reality--`LocalTiptapEditor.tsx` is a large DOM surface (viewer + editor modes, Mermaid via `beautiful-mermaid` + mermaid, resource press/load, image upload placeholders, search/replace, toolbar active flags, `MEMO_CONTENT_STYLE`). Treat extraction as a **multi-milestone** project, not a “small Vite page.”--Ship a static package produced at monorepo build time:--```text-apps/ios/EditorSource/ # TypeScript source (Vite)- package.json- vite.config.ts- src/main.ts- src/editor.ts- src/bridge.ts- src/markdown.ts # TipTap Markdown; sole doc↔md converter (K20)- src/mermaid.ts-apps/ios/EditorBundle/ # build output committed or CI-produced- index.html- assets/*.js- assets/*.css-```--Build: `Scripts/build-editor-bundle.sh` → Vite. Prefer smoke tests with Vitest on bridge message shapes and markdown round-trips using shared fixtures.--**Milestones (map to PR 6a–6d):**--| Milestone | Deliverable | Unlocks |-| --- | --- | --- |-| **6a Viewer** | Offline `setDocument` + render paragraphs/lists/quotes/tables; no network | Detail body without images |-| **6b Editor** | Toolbar, `change` events, `getMarkdown()` / doc JSON, focus/flush | **Text edit-ready gate** (with outbox PR) |-| **6c Resources** | `loadResource` bridge, placeholders, image upload hooks, resource press | Images + attachments |-| **6d Mermaid** | Mermaid render in viewer/editor | Full store body AC |--Load:--```swift-webView.loadFileURL(indexURL, allowingReadAccessTo: bundleDirectory)-```--#### Bridge protocol (typed JSON)--**Native → Web** (`evaluateJavaScript` calling `window.EdgeEverEditor.*`):--| Method | Purpose |-| --- | --- |-| `configure({ mode, locale, theme, placeholder })` | viewer vs editor |-| `setDocument(docJson)` | replace content |-| `getDocument()` | return current doc (promise via callback id) |-| `focusEnd()` | caret |-| `flush()` | force change emit |-| `exec(actionId)` | toolbar: bold, lists, etc. |-| `beginImageUpload(uploadId, previewDataUrl)` | placeholder image |-| `completeImageUpload(uploadId, imageUrl, alt)` | swap placeholder |-| `cancelImageUpload(uploadId)` | remove placeholder |-| `appendAttachment(url, filename)` | attachment link node |-| `removeResource(targetJson)` / `renameResource(...)` | resource ops |-| `search(query, index)` / `replaceAll(query, replacement)` | find |--**Web → Native** (`webkit.messageHandlers.edgeever.postMessage`):--| Event | Payload |-| --- | --- |-| `ready` | `{ startupMs }` |-| `change` | `{ contentJson, contentMarkdown }` (editor only; markdown from EditorBundle converter—K20) |-| `loadResource` | `{ requestId, source }` → native replies with data URL |-| `resourcePress` | `{ targetJson }` → native sheet: open / rename / delete (Required for store) |-| `imagePreview` | `{ alt, source }` (viewer) |-| `activeFlags` | bitfield matching `MOBILE_EDITOR_ACTIVE_FLAGS` |-| `searchResult` | `{ count, index }` |-| `log` / `error` | diagnostics |--Resource reply path: native completes `loadResource` by evaluating `EdgeEverEditor.resolveResource(requestId, dataUrlOrNull)`.--Native must **not** re-derive markdown from JSON; trust `contentMarkdown` from the bundle on `change` (or call `getMarkdown()` on flush).--#### Protected resources--1. Detect `/api/v1/resources/:id` and `/blob` variants (port `getResourceIdFromUrl` / `normalizeMobileResourceHref`).-2. `APIClient.getResourceData(path)` with `Authorization: Bearer <token>`.-3. Convert to data URL (images) or temp file URL (attachments open-in-place / share sheet).-4. Cache on disk under Application Support `resource-cache/<resourceId>` with size cap (e.g. 200 MB LRU) — port spirit of `cacheMobileResource` in `mobile-attachments.ts`.--#### Mermaid--Keep rendering **inside** the WebView (same as RN editor) to avoid dual implementations. Optional: separate lightweight mermaid renderer HTML for list previews is **not** required for v1 if list uses excerpt text only (RN list uses excerpt).--#### Image upload--1. `PHPicker` / `PhotosUI` → optional compression (max edge 2560, quality ~0.82 WebP) matching `mobile-image-upload.ts`.-2. Resolve target memo id via **Materialize algorithm (K24)**—never bare `createMemo` without outbox coordination.-3. `multipart/form-data` `POST /api/v1/memos/:id/resources` using the **single** server memo id returned by materialize.-4. Placeholder → complete with returned `resource.url`.-5. Offline or materialize failure: cancel placeholder; no second create attempts without user retry.--### Session & security--| Item | Storage | Notes |-| --- | --- | --- |-| Session JSON `{ baseUrl, token, user }` | Keychain (kSecClassGenericPassword) | Key: `org.edgeever.mobile.session` |-| `deviceId` | Keychain | `mobile-<time>-<random>`; sent on login |-| Preferences | UserDefaults or SQLite prefs table | locale, theme, density, imageCompression |-| Share payload | App Group UserDefaults | Suite: **`group.org.edgeever.mobile`** (repo entitlements; re-confirm portal matches at cutover) |--Login:--```http-POST /api/v1/auth/login-{ "username", "password", "deviceId" }-→ AuthSession { authenticated, sessionToken, user, ... }-```--Require `sessionToken` (same error message philosophy as RN if missing). All subsequent requests: `Authorization: Bearer <sessionToken>`. On 401: clear session, navigate to Login.--**ATS / cleartext (K22):** HTTPS is the default and recommended path. Users may enter `http://` for LAN self-host; show a persistent warning on the login screen. App Transport Security uses a limited exception (or `NSAllowsLocalNetworking` where applicable) documented in App Review notes. Do not silently upgrade HTTP to HTTPS.--**Info.plist usage strings (Required for store):**--- `NSPhotoLibraryUsageDescription` (or limited Photos picker strings) for image upload via PHPicker.-- Keep mic/camera strings only if WKWebView can still probe them; prefer disabling media capture in WKWebView configuration to avoid unnecessary TCC prompts.-- `ITSAppUsesNonExemptEncryption` / export compliance equivalent of RN `usesNonExemptEncryption: false`.--**Privacy Nutrition Labels:** re-audit App Store privacy answers when the binary drops Expo/RN SDKs (do not assume RN answers remain valid without review).--### Share Extension--Rewrite under `apps/ios/ShareExtension/`:--1. **v1 accept text + web URL only** (intentional reduction vs current RN extension which also handles image/video/audio/file). Document in release notes.-2. Encode payload JSON into App Group `group.org.edgeever.mobile`.-3. Open host via URL scheme `edgeever://share` (scheme already in `app.json`).-4. Host app on launch/active: read payload, clear it, open create-memo flow with prefilled markdown (title from page title if available; body link + selection text).--Do not re-use Expo plugin generated targets long-term.--### Directory structure of `apps/ios`--```text-apps/ios/- README.md- project.yml # optional XcodeGen- EdgeEver.xcodeproj/ # or generated- EdgeEver.xcworkspace/ # if needed- Config/- Debug.xcconfig- Release.xcconfig- Version.xcconfig # MARKETING_VERSION, CURRENT_PROJECT_VERSION- EdgeEver/- App/- EdgeEverApp.swift- AppDelegate.swift # if share / lifecycle hooks needed- RootView.swift- Features/- Auth/- LoginView.swift- SessionStore.swift- Workspace/- WorkspaceView.swift- NotebookListView.swift- NotesListView.swift- MemoDetailView.swift- MemoEditView.swift- SettingsView.swift- AccountSecurityView.swift- SyncStatusView.swift- ConflictResolutionView.swift- Share/- ShareHandoffStore.swift- Editor/- TipTapWebView.swift- TipTapBridge.swift- TipTapBridgeMessages.swift- EditorToolbarView.swift- ResourceLoader.swift- Data/- Database/- AppDatabase.swift- Migrations.swift- LocalMirrorRepository.swift- SyncOutboxRepository.swift- DraftRepository.swift- Models/- Notebook.swift- Memo.swift- SyncModels.swift- AuthModels.swift- ResourceModels.swift- OutboxModels.swift- Network/- APIClient.swift- APIEndpoints.swift- APIError.swift- MultipartFormData.swift- Sync/- SyncEngine.swift- SyncProtocol.swift # rewind/identity helpers- OutboxFlusher.swift- Session/- KeychainStore.swift- DeviceId.swift- Preferences/- PreferencesStore.swift- Cache/- ResourceCache.swift- ImageCompressor.swift- DesignSystem/- Colors.swift- Typography.swift- Components/ # list rows, empty states, banners- Resources/- Assets.xcassets- Localizable.xcstrings # en + zh-CN- Info.plist- EdgeEver.entitlements- PrivacyInfo.xcprivacy- Supporting/- URL+Normalize.swift- JSONCoding.swift- ShareExtension/- ShareViewController.swift- Info.plist- ShareExtension.entitlements- EditorBundle/ # committed build output or generated in CI- index.html- assets/- EditorSource/ # Vite/TS source for TipTap host page- package.json- vite.config.ts- src/main.ts- src/editor.ts- src/bridge.ts- Tests/- EdgeEverTests/- LocalMirrorTests.swift- SyncEngineTests.swift- OutboxTests.swift- APIClientTests.swift- BridgeMessageTests.swift- Scripts/- build-editor-bundle.sh- bump-build-number.sh- fastlane/- Fastfile- Appfile-```--**SPM dependencies (recommended):**--| Package | Use |-| --- | --- |-| [GRDB.swift](https://github.com/groue/GRDB.swift) | SQLite |-| (optional) swift-markdown or none | Prefer markdown conversion in WebView/editor bundle |-| (optional) Kingfisher | Only if native image UI needs it; WebView path may not |--Avoid large UI kits; use system SwiftUI.--### CI / release implications--| Concern | Today (RN) | After rewrite |-| --- | --- | --- |-| iOS build | EAS Build from `apps/mobile` (`store-delivery.yml` ios job: `eas build --platform ios --profile production`) | **macOS runner** + `xcodebuild` archive (or Fastlane `gym`) from `apps/ios` |-| iOS submit | `eas submit` + Fastlane `submit_review` from `apps/mobile` | Upload IPA via `xcrun altool` / Transporter / Fastlane `pilot`/`deliver`; keep ASC API key submit_review from `apps/ios/fastlane` |-| Android | Unchanged local/GA builds | Unchanged (still may use `EXPO_TOKEN` for EAS Submit of AAB) |-| GitHub Release assets | macOS arm64 DMG + x64 DMG + Android arm64 APK | **Unchanged — no IPA required** on GitHub Release (AGENTS.md). iOS binary lives in App Store Connect / TestFlight only |-| Versioning | `apps/mobile/app.json` `expo.version` + EAS iOS build autoIncrement | Android: keep `expo.version` + `android.versionCode`. iOS: `apps/ios` `MARKETING_VERSION` (= release `vX.Y.Z` without `v`) + monotonic `CURRENT_PROJECT_VERSION`. **Update `AGENTS.md` release clause** when native iOS ships |-| EAS Update | iOS + Android | **Android only** |-| Store delivery | `.github/workflows/store-delivery.yml` | Split ios job off EAS; see cutover sequence below |--#### Concrete cutover (ordering matters)--1. **While building Swift:** leave EAS iOS job intact so an emergency RN build remains possible (even if crashy). Do not delete `apps/mobile/ios` yet.-2. **Ship Swift to TestFlight** (manual or temporary workflow); validate edit acceptance criteria on device.-3. **Only then** retarget automation:- - Replace `store-delivery.yml` **ios** job:- - `runs-on`: self-hosted macOS (or `macos-latest`) with Xcode matching project.- - Checkout release tag → `bun run build:ios:editor` → `xcodebuild -scheme EdgeEver -configuration Release archive` → export IPA.- - Upload to ASC with App Store Connect API key secrets already used today (`APP_STORE_CONNECT_API_KEY_*`); **drop `eas build` / `eas submit` for iOS**.- - Move Fastlane `submit_review` working-directory from `apps/mobile` → `apps/ios`.- - Update **`docs/store-delivery.md` + `docs/store-delivery.zh-CN.md`** in the same change (bilingual required).- - Update **`docs/mobile-build.md`**: remove “EAS iOS production build” as the product path; document `apps/ios` archive steps. (No Chinese pair exists today for mobile-build.)- - Update **`docs/mobile-native-parity.md`**: shell = SwiftUI on iOS / RN on Android; TipTap body both.- - Update **`AGENTS.md`** versioning: when release includes iOS native changes, bump `apps/ios` `MARKETING_VERSION` / `CURRENT_PROJECT_VERSION` in addition to root + Android rules.- - `apps/mobile/eas.json`: remove or comment iOS production/submit profiles; keep Android submit profiles.- - `scripts/validate-store-delivery.mjs` / tests: if platform includes ios, validate `apps/ios` version files exist and match tag (extend tests in same series).-4. **Freeze RN iOS tree (K23):** configure Expo prebuild/Android-only so `apps/mobile/ios` is not required for Android CI; delete or stop generating `apps/mobile/ios` after one clean Android build without it.-5. **Credentials:** iOS distribution cert + provisioning profiles live in the Apple portal / CI keychain (export from EAS credentials once if needed). Android continues to need `EXPO_TOKEN` only for Play EAS Submit if still used.--**Do not** attach IPAs to formal GitHub Releases unless product later changes AGENTS asset rules.--### Cross-client contract (dual-platform maintenance)--After cutover, two clients implement the same protocol. Prevent drift:--| Artifact | Location | Owners |-| --- | --- | --- |-| Golden JSON fixtures | `tests/mobile-sync-fixtures/` (bootstrap pages, change streams, rewind, identity change, conflict edit-session mismatch, create-absorbs-update sequences) | Updated in the **same commit series** as any Android change to `local-mirror.ts` / `sync-queue.ts` / `mobile-sync-protocol.ts` |-| Behavioral checklist | Fixture-driven cases: scope key; bootstrap page sizes; `local:` survive rebuild; create-absorbs-update; promote; rebase; in-flight cancel orphan soft-delete; `getSyncRetryDelayMs` table; edit-session precheck conflict | RN: `bun test` existing + fixture loader. iOS: Swift unit tests decode same JSON |-| Markdown golden | Reuse / export cases from `packages/shared` content tests into EditorSource Vitest | Editor bundle only (K20) |-| Parity doc | `docs/mobile-native-parity.md` | Dual-shell rules; **owner: mobile platform engineer on any client change**; store release checklist includes “fixtures + both clients green” |-| CI | Ubuntu: fixture tests + RN mobile typecheck/tests. macOS (required before App Review, ideally on main for `apps/ios/**` paths): `xcodebuild test` | Optional nightly full if PR cost is high; **blocking** before store submit |--Process: Android queue/mirror PR without fixture update is incomplete. iOS outbox/mirror PR must run fixture suite. No silent protocol divergence.--### Monorepo integration notes--- Root `package.json`: add `build:ios:editor` to produce `EditorBundle`.-- Do **not** make `bun run typecheck` depend on Xcode.-- `typecheck:mobile` remains Android RN TypeScript.-------## API / Interface Changes--**No backend API changes required for v1.** iOS consumes the existing REST surface.--### Must-have APIs (store submission)--| Client method (`packages/client`) | HTTP | iOS need |-| --- | --- | --- |-| `login` | `POST /api/v1/auth/login` | Required |-| `logout` | `POST /api/v1/auth/logout` | Required |-| `getSession` | `GET /api/v1/auth/session` | Required (validate token) |-| `changePassword` | `POST /api/v1/auth/change-password` | Required (settings) |-| `listLoginDeviceSessions` | `GET /api/v1/auth/sessions` | Required |-| `revokeLoginDeviceSession` | `DELETE /api/v1/auth/sessions/:id` | Required |-| `revokeOtherLoginDeviceSessions` | `DELETE /api/v1/auth/sessions` | Required |-| `getMobileSyncBootstrapPage` | `GET /api/v1/sync/bootstrap` | Required |-| `getMobileSyncChanges` | `GET /api/v1/sync/changes` | Required |-| `listNotebooks` | `GET /api/v1/notebooks` | Optional if bootstrap supplies notebooks; mirror is source for UI |-| `createNotebook` | `POST /api/v1/notebooks` | **Deferred** (not RN mobile UI) |-| `updateNotebook` | `PATCH /api/v1/notebooks/:id` | **Deferred** |-| `deleteNotebook` | `DELETE /api/v1/notebooks/:id` | **Deferred** |-| `createMemo` | `POST /api/v1/memos` | Required |-| `updateMemo` | `PATCH /api/v1/memos/:id` | Required |-| `getMemo` | `GET /api/v1/memos/:id` | Required (conflict discard) |-| `deleteMemo` / `deleteMemos` | `DELETE` / batch | Required |-| `createMemoEditSession` | `POST /api/v1/memos/:id/edit-sessions` | Required |-| `uploadMemoResource` | `POST /api/v1/memos/:id/resources` | Required |-| `getResourceBlob` | `GET` resource URL | Required |-| `listTags` | `GET /api/v1/tags` | Nice for filter chips; can derive from mirror |-| `listApiTokens` / `createApiToken` / `revokeApiToken` | API tokens | Required (parity table) |-| `listMemoRevisions` / `restoreMemoRevision` | Revisions | **Deferred** (not edit-gate; include if schedule allows) |-| `createMemoShare` / `getMemoShare` / `revokeMemoShare` | Share links | **Deferred** |-| `renameResource` / `deleteResource` | In-note body actions | **Required** for gate B (not full library screen) |-| `listResources` | Resource library screen | **Deferred** |-| `moveMemos` batch | Multi-select move | **Deferred** (single-note notebook change via content outbox is Required) |-| ZIP / trash empty / JSON backup | — | **Out of scope** |--### Swift client sketch--```swift-public struct EdgeEverClient: Sendable {- public var baseURL: URL- public var token: String?- public var onUnauthorized: (@Sendable () -> Void)?-- public func login(_ input: LoginInput) async throws -> AuthSession- public func logout() async throws- public func getSession() async throws -> AuthSession-- public func getMobileSyncBootstrapPage(afterId: String?, limit: Int) async throws -> MobileSyncBootstrapPage- public func getMobileSyncChanges(cursor: Int, limit: Int) async throws -> MobileSyncChangesPage-- public func createMemo(_ payload: CreateMemoPayload) async throws -> MemoDetail- public func updateMemo(id: String, _ payload: UpdateMemoPayload) async throws -> MemoDetail- public func getMemo(id: String, includeDeleted: Bool) async throws -> MemoDetail- public func deleteMemo(id: String, permanent: Bool) async throws- public func createMemoEditSession(memoId: String) async throws -> MemoEditSession- public func uploadMemoResource(memoId: String, file: UploadFile) async throws -> Resource- public func getResourceData(path: String) async throws -> Data- // … notebooks, tags, tokens, sessions, revisions as needed-}--public struct APIError: Error, Sendable {- public let status: Int- public let code: String?- public let message: String- public var isRevisionConflict: Bool { code == "revision_conflict" || status == 409 }-}-```--Codable models must accept the same JSON field names as TS (`contentJson`, `contentMarkdown`, camelCase). Use `JSONDecoder.keyDecodingStrategy = .useDefaultKeys` with explicit `CodingKeys` matching server.--### Wire payload examples--**Create memo**--```json-{- "notebookId": "…",- "title": "无标题笔记",- "contentMarkdown": "hello",- "tags": ["a"],- "createdAt": "2026-08-06T00:00:00.000Z",- "updatedAt": "2026-08-06T00:00:00.000Z"-}-```--**Update memo (content)**--```json-{- "expectedRevision": 3,- "expectedContentHash": "…",- "editSessionId": "…",- "title": "…",- "contentMarkdown": "…",- "notebookId": "…",- "tags": []-}-```-------## Data Model Changes--### SQLite schema (GRDB migrations)--Database file: `edgeever-ios.sqlite` (Application Support). `PRAGMA journal_mode=WAL`.--```sql--- Migration 1: mirror + meta (parity with local-mirror.ts)--CREATE TABLE mobile_notebooks (- scope TEXT NOT NULL,- id TEXT NOT NULL,- name TEXT NOT NULL,- sort_order INTEGER NOT NULL,- data_json TEXT NOT NULL,- PRIMARY KEY (scope, id)-);--CREATE TABLE mobile_memos (- scope TEXT NOT NULL,- id TEXT NOT NULL,- notebook_id TEXT NOT NULL,- title TEXT NOT NULL,- content_text TEXT NOT NULL,- tags_text TEXT NOT NULL,- is_pinned INTEGER NOT NULL,- is_deleted INTEGER NOT NULL,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- deleted_at TEXT,- data_json TEXT NOT NULL,- PRIMARY KEY (scope, id)-);--CREATE INDEX idx_mobile_memos_feed- ON mobile_memos(scope, is_deleted, updated_at DESC);-CREATE INDEX idx_mobile_memos_notebook- ON mobile_memos(scope, notebook_id, is_deleted, updated_at DESC);--- Note: idx_mobile_memos_search is an iOS-only optional addition (see justified differences).--- RN uses LIKE without a dedicated search index.--CREATE TABLE mobile_sync_meta (- scope TEXT NOT NULL,- key TEXT NOT NULL,- value TEXT NOT NULL,- PRIMARY KEY (scope, key)-);--CREATE TABLE mobile_id_mappings (- scope TEXT NOT NULL,- temporary_id TEXT NOT NULL,- remote_id TEXT NOT NULL,- created_at TEXT NOT NULL,- PRIMARY KEY (scope, temporary_id)-);---- Migration 1 continued: outbox (improvement over AsyncStorage)--CREATE TABLE mobile_sync_outbox (- scope TEXT NOT NULL,- id TEXT NOT NULL, -- e.g. memo.create:<memoId>- kind TEXT NOT NULL, -- memo.create | memo.update- memo_id TEXT NOT NULL,- status TEXT NOT NULL, -- pending | syncing | conflict | error- payload_json TEXT NOT NULL,- attempt_count INTEGER NOT NULL DEFAULT 0,- last_error TEXT,- next_attempt_at TEXT,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- version INTEGER NOT NULL DEFAULT 1,- PRIMARY KEY (scope, id)-);--CREATE INDEX idx_mobile_outbox_flush- ON mobile_sync_outbox(scope, status, next_attempt_at, created_at);---- Drafts--CREATE TABLE mobile_drafts (- scope TEXT NOT NULL,- draft_key TEXT NOT NULL, -- memo:<id> | new- title TEXT NOT NULL,- content_markdown TEXT NOT NULL,- content_json TEXT, -- optional TipTap JSON cache- notebook_id TEXT NOT NULL,- tags_text TEXT NOT NULL,- expected_revision INTEGER, -- null for new- updated_at TEXT NOT NULL,- PRIMARY KEY (scope, draft_key)-);-```--### Row encoding--- `data_json` stores full `Notebook` / `MemoDetail` server shapes for forward compatibility.-- Indexed columns power list/search without parsing JSON.-- `tags_text` = tags joined by space (RN).-- Search: `LIKE %q%` on title/content_text/tags_text (RN); FTS5 optional later.--### Justified differences from RN--| Topic | RN | iOS | Why |-| --- | --- | --- | --- |-| Outbox storage | AsyncStorage JSON array | SQLite `mobile_sync_outbox` | Durability, transactional version checks |-| Drafts | AsyncStorage | SQLite `mobile_drafts` | Same |-| Search index | No dedicated index; `LIKE` on columns | Optional `idx_mobile_memos_search` (or rely on LIKE like RN) | iOS may add for large libraries; **not** claimed as RN parity—implement LIKE first |-| DB name | `edgeever-mobile.db` | `edgeever-ios.sqlite` | Platform isolation; no migration from RN local DB required |-| Preferences | AsyncStorage | UserDefaults | Simpler for flags |-| Content save path | Always outbox for content | Same (K6)—**not** a difference | Documented so implementers do not “optimize” to online-first |--**No automatic import of RN Expo SQLite files** for v1: fresh bootstrap after install/update is acceptable. Call out in release notes that offline-only unsynced RN drafts will not migrate (users should open RN build once online before upgrading if they have critical offline notes—or accept re-entry). Given RN iOS is crashing, many users may already be online-only.--### List query parity--Port `listLocalMemos` filters: notebook / multi-notebook, trash flag (always false in UI), q, filter tagged/untagged/pinned, sort updated-desc / created-desc / title-asc with pin-first, limit/offset pagination.-------## Alternatives Considered--### A1. Keep RN iOS and only fix crashes--- **Pros:** One codebase; reuse DOM editor as-is.-- **Cons:** Crashes are in RN runtime/Fabric; unbounded timeline; App Review blocked. Repo enables React Native **New Architecture** (`newArchEnabled: true` in `app.json`); observed crash stacks (Hermes / Fabric AttributedString) align with that stack, so toggling flags or chasing community patches is unlikely to yield a durable store-quality binary on a predictable schedule.-- **Verdict:** Rejected by product decision.--### A2. Capacitor / WKWebView full PWA shell--- **Pros:** Fastest reuse of web UI.-- **Cons:** Violates `mobile-native-parity.md` (no PWA as primary workspace); performance/list feel; review risk; still not “native reliability” story.-- **Verdict:** Rejected for shell; WebView allowed **only** for TipTap body.--### A3. Kotlin Multiplatform / shared business logic--- **Pros:** Share sync engine with future Android rewrite.-- **Cons:** Large toolchain cost now; Android stays RN; delays store submission.-- **Verdict:** Deferred; keep protocol documentation so a later KMP port is possible.--### A4. Native TextKit / custom rich text instead of TipTap--- **Pros:** Fully native editor performance.-- **Cons:** Schema divergence from web; tables/Mermaid/images months of work; dual formats.-- **Verdict:** Rejected for v1; revisit only if WKWebView editor fails review/performance.--### A5. Read-only MVP then add edit--- **Pros:** Faster first binary.-- **Cons:** Explicitly forbidden by product decision; incomplete capture product.-- **Verdict:** Rejected.-------## Security & Privacy Considerations--| Threat | Mitigation |-| --- | --- |-| Token theft from disk | Keychain accessibility `afterFirstUnlockThisDeviceOnly`; no token in logs |-| WebView XSS exfiltrating token | Do not inject token into JS; resources fetched natively; load only local editor bundle (`file://`) |-| MITM on self-hosted HTTP | HTTPS default (K22); HTTP only with explicit user entry + warning; limited ATS exception + App Review notes |-| Share Extension data leakage | App Group `group.org.edgeever.mobile` only; clear payload after consume; no password in extension |-| Screenshot of notes | Standard iOS; optional later hide in app switcher not required |-| Clipboard conflict draft | User-initiated only (parity with RN conflict copy) |-| Privacy Nutrition labels | Re-audit when binary composition changes (drop Expo/RN SDKs); do not blindly copy prior answers |-| Photo library | `NSPhotoLibraryUsageDescription` (or limited library picker) for PHPicker uploads |-| Microphone/Camera strings | Prefer disable media capture in WKWebView; add TCC strings only if still required by WebKit |--**WKWebView hardening:**--- `limitsNavigationsToAppBoundDomains` / deny unexpected navigations.-- Disable `isInspectable` in Release.-- `mediaTypesRequiringUserActionForPlayback = .all`.-- Do not enable file access outside editor bundle directory.-------## Observability--| Signal | Approach |-| --- | --- |-| Non-fatal errors | `os.Logger` subsystems: `auth`, `sync`, `editor`, `api` |-| Sync metrics | Local counters: last bootstrap duration, last changes page count, outbox depth, conflict count |-| Sync stuck diagnosis | **Debug-only** Settings action: “Export sync diagnostics” → JSON share sheet (`scope`, cursor, identity, outbox items with status/attempt/lastError/nextAttemptAt, last pull error). No secrets/tokens in export |-| Crash reporting | Xcode Organizer / TestFlight crash reports; **first-week post-submit watch owner** named in PR 13 release checklist (default: engineer who submitted) |-| Editor bridge failures | Log event name + error string; surface “编辑器加载失败” retry UI |-| Network | Log status code + path (never Authorization header) |-| Performance targets (adapt from parity doc) | Cold launch to shell < 1.0s; warm list < 0.5s; list scroll without sustained dropped frames; search 250ms debounce |--No requirement for server-side new analytics endpoints.-------## Rollout Plan--### Phase 0 — Scaffold (this design approved)--- Create `apps/ios` Xcode project, bundle id, App Group `group.org.edgeever.mobile`, URL scheme, empty SwiftUI shell.-- GRDB + Keychain + APIClient skeleton.-- Add shared fixture harness skeleton under `tests/mobile-sync-fixtures/`.-- CI: local `xcodebuild test` first; wire macOS CI when PR volume justifies (blocking before store).--### Phase 1 — Auth + mirror + list (internal)--- Login, bootstrap/incremental sync, notebooks + memos list + search + detail **viewer (6a)**.-- TestFlight internal (optional).--### Phase 2 — Edit path (required before App Review)--- **Internal edit-ready gate:** 6b editor + outbox create/update + drafts + soft delete + conflicts (text path; images optional).-- **App Review gate:** + 6c resources/images + 6d mermaid + settings + share text/URL.-- Soft delete + pin online-first.--### Phase 3 — Settings + share + polish--- Account security, tokens, sessions, locale/theme, debug diagnostics export.-- Share Extension (text/URL).-- Performance pass; accessibility; zh-CN/en-US strings.--### Phase 4 — Store submission + cutover--- Swift TestFlight validates **App Review gate** AC.-- Then remove EAS iOS job; retarget `store-delivery.yml`; update bilingual store-delivery docs + AGENTS versioning + parity doc.-- Freeze/remove `apps/mobile/ios` after Android-only prebuild works.-- First-week crash watch (Organizer/TestFlight).--### Feature flags--Not required for v1. Optional compile-time `#if DEBUG` editor debug HUD.--### Rollback--- App Store: halt release / phasable release if using phased.-- Cannot roll back users to RN binary automatically once Swift build supersedes; keep previous RN build in ASC only if still processing—do not re-submit known-crashing RN build.-- Server remains compatible with both clients during transition (Android RN + iOS Swift).--### Migration messaging--Release notes (bilingual structure per `AGENTS.md` when publishing):--- iOS app rewritten natively for stability.-- Same account/instance login.-- Local offline drafts from the previous iOS build may not carry over; ensure sync before upgrade if possible.-------## Acceptance Criteria--Two gates. **Never cut edit-gate bullets for share/revisions/resource-library.** Images/mermaid are App Review gate, not internal text edit-ready.--### A. Internal edit-ready gate (text path — PR 8 without requiring images)--- [ ] Login with username/password against configurable `baseUrl`; persist session across relaunch.-- [ ] Invalid credentials and unreachable host show actionable errors; 401 clears session → login.-- [ ] HTTPS default; `http://` allowed with warning (K22).-- [ ] First sync bootstraps with progress; later launches incremental; cursor rewind + identity change rebuild without losing `local:` memos.-- [ ] Notes list: notebook **hierarchy browse/select/filter**, search (250 ms debounce), sort modes, pin (online-first), soft delete.-- [ ] Create requires notebook (default notebook when available); empty notebook set blocks with clear message (RN: create notebooks elsewhere / “请先创建一个笔记本”)—**no** in-app notebook create/rename/delete in v1.-- [ ] **Move memo to notebook:** change notebook on create/edit via content outbox fields (not batch `moveMemos` API).-- [ ] **New-note draft-until-commit:** typing before Done only writes `mobile_drafts` (`new`)—no list row / no `memo.create` until Done or materialize (RN create-sheet).-- [ ] **Create offline (Done without materialize):** `local:` id in list; mirror + `memo.create` outbox; sync when online; id remap without duplicate rows.-- [ ] **Create absorbs updates:** while `memo.create` pending, further title/tags/body/notebook edits update create payload only (no parallel `memo.update` for same local id).-- [ ] **Promote:** if user keeps editing during in-flight create, remaining work becomes `memo.update` on new id after create succeeds.-- [ ] **Rebase:** if user edits during in-flight update, expectations rebase from server memo after successful flush.-- [ ] **In-flight cancel:** delete pending local create cancels queue + hard-deletes local; if create already landed, remote orphan soft-deleted.-- [ ] **Edit path always outbox for committed content:** no online-first content save for body/title/tags/notebook on existing or post-materialize memos.-- [ ] **Edit-session precheck:** baseRevision/baseContentHash mismatch → conflict before PATCH.-- [ ] **Revision conflict UI:** discard local (reload server + drop queue) or keep/copy local draft.-- [ ] Title, tags, notebook, and body all autosave through the same outbox path once committed.-- [ ] Autosave debounce (500 ms body / ~350 ms title-tags); force outbox enqueue + draft persist on background for committed memos; uncommitted new notes force-write draft only.-- [ ] Process death: reopen editor restores from `mobile_drafts` when newer than mirror.-- [ ] Soft-delete algorithm matches `mobile-memo-delete.ts` (local-only vs remote).-- [ ] Viewer (6a) + editor (6b) TipTap: paragraphs, lists, quotes, tables (render); offline open works.-- [ ] Unit tests (fixtures): scope, rewind/identity, create-absorbs-update, promote, rebase, retry delay, orphan soft-delete, edit-session precheck.--### B. App Review / store-ready gate (superset of A)--- [ ] All of gate A.-- [ ] Images (auth load) + mermaid render (6c/6d).-- [ ] Image pick → compress if enabled → upload → placeholder → final URL.-- [ ] **Materialize K24:** materialize-before-image leaves **exactly one** server memo and **no** orphan pending `memo.create` for the old `local:` id; double-tap / concurrent materialize does not double-create (unit + manual).-- [ ] Offline create-sheet + image: disabled or hard failure UX; no silent partial create; no second create on retry without canceling prior outbox state.-- [ ] In-note resource open; rename/delete from body actions (API + doc update via outbox if content changes).-- [ ] Settings: theme, locale, density, image compression, sign out, change password, API tokens, device sessions; debug “export sync diagnostics.”-- [ ] Share Extension: text/URL → create draft (not image/file in v1).-- [ ] Pin works from list; soft-deleted notes hidden; no trash browser / ZIP.-- [ ] Info.plist photo library string; encryption compliance false equivalent; privacy labels re-audited.-- [ ] Manual: cold start → 50-note list → detail → edit → background → kill → relaunch recovers content; no crash.-- [ ] EAS iOS path disabled only **after** this gate on TestFlight (cutover sequence).-- [ ] Android RN still builds; GitHub Release still DMG+APK only (no IPA).--### Performance (targets)--| Path | Target |-| --- | --- |-| Cold launch → shell | < 1.0 s |-| Warm launch → cached list | < 0.5 s |-| Cached list usable offline | yes |-| Search keystroke | no network; 250 ms debounce |-| Editor ready | log `startupMs`; investigate if > 2 s on mid-range device |-------## Risks--| Risk | Severity | Mitigation |-| --- | --- | --- |-| TipTap bridge complexity / keyboard glitches; underestimating `LocalTiptapEditor` size | **High** | Milestones 6a–6d; text edit-ready before images; IME zh-CN tests; bridge contract tests; Vitest on EditorSource |-| Dual-platform maintenance (Swift iOS + RN Android) | **High** | **Cross-client contract** fixtures + same-commit Android fixture updates; parity doc ownership; dual green before store |-| App Review scrutiny of new binary / login to self-hosted | **Medium** | Demo instance credentials in review notes; screenshots from `store-assets` |-| Editor bundle size / JS perf | **Medium** | Tree-shake TipTap; measure; lazy mermaid (6d last) |-| Markdown conversion drift vs web | **Medium** | K20: conversion only in EditorBundle; shared golden fixtures |-| Image upload / double server create on materialize | **High** if naive | K24 + draft-until-commit create-sheet; exclusive materialize algorithm; Gate B single-memo tests; not blocking Gate A text path |-| Loss of RN local DB on upgrade | **Medium** | Release notes; encourage sync; no false promises |-| Share Extension App Group misconfig | **Medium** | Use `group.org.edgeever.mobile` from current entitlements; device test |-| Cleartext HTTP ATS rejection | **Low** | K22 warning + review notes |-| Disabling EAS iOS too early | **High** | Cutover only after Swift TestFlight validates App Review gate |-| Schedule pressure to ship read-only | **High** | Product forbids; cut share/revisions/batch/media-share before cutting edit gate A |-------## Open Questions--1. ~~App Group id~~ → **Resolved:** `group.org.edgeever.mobile` (repo entitlements). Still verify Apple Developer portal matches at cutover.-2. **Whether App Review binary must include revision history UI** or Deferred is acceptable (design default: Deferred; not edit-gate).-3. ~~HTTP cleartext~~ → **Resolved (K22):** HTTPS default + optional user-confirmed HTTP with warning.-4. **CI macOS runner:** run `xcodebuild test` on every `apps/ios/**` change vs nightly only (blocking before store either way).-5. **Marketing version:** recommend `MARKETING_VERSION` always equals monorepo release `X.Y.Z` on store submissions; confirm in AGENTS update.-6. ~~`apps/mobile/ios` after cutover~~ → **Resolved (K23):** freeze/remove once Android-only prebuild is configured; do not leave a buildable RN iOS path after EAS iOS retirement.-------## References--- `docs/mobile-native-parity.md` — product/architecture rules for mobile clients-- `docs/mobile-build.md` — current Expo/EAS/Android/iOS build instructions (to be updated)-- `docs/store-delivery.md` + `docs/store-delivery.zh-CN.md` — store delivery workflow (iOS path to retarget; bilingual pair must stay in sync)-- `.github/workflows/store-delivery.yml` — current EAS iOS job to replace-- `apps/mobile/src/lib/local-mirror.ts` — mirror schema + bootstrap/changes-- `apps/mobile/src/lib/sync-queue.ts` — outbox semantics-- `apps/mobile/src/lib/session.tsx` — session + deviceId + login-- `apps/mobile/src/lib/mobile-sync-protocol.ts` — rewind/identity helpers-- `apps/mobile/src/lib/mobile-memo-delete.ts` — soft delete / local-only delete-- `apps/mobile/src/lib/mobile-image-upload.ts` — compression rules-- `apps/mobile/src/components/LocalTiptapEditor.tsx` — TipTap host behavior-- `packages/client/src/index.ts` — REST client surface-- `packages/shared/src/types.ts` — `MemoDetail`, `Notebook`, auth types-- `packages/shared/src/content.ts` — `TiptapDoc`, markdown conversion-- `packages/shared/src/sync.ts` — queue summary + retry delay-- `packages/shared/src/mobile-editor.ts` — toolbar actions + i18n strings-- `apps/mobile/app.json` — bundle id, scheme, version-- `apps/mobile/eas.json` — ASC app id `6792625631`-- `apps/mobile/ios/expo-sharing-extension/ShareIntoViewController.swift` — share handoff pattern-- `docs/openapi.json` — API schema reference-- `AGENTS.md` — main-branch-only; release bilingual notes; verification commands-------## Scaffold checklist (post-approval)--**Work on `main` only** (AGENTS.md). Each checklist item is a commit series, not a long-lived branch.--1. Create Xcode project at `apps/ios` with target `EdgeEver` (ShareExtension can wait until package 10).-2. Set deployment iOS 17, bundle `org.edgeever.mobile`, scheme `edgeever`, App Group `group.org.edgeever.mobile`.-3. Add GRDB via SPM; implement Migration 1; empty `RootView`.-4. Implement `KeychainStore` + `APIClient.login/getSession`.-5. Implement `LocalMirrorRepository` + fixture-backed unit tests + `SyncEngine` bootstrap.-6. EditorSource milestone **6a** (viewer) → then **6b** (editor).-7. Outbox + create/edit until **gate A** green (text edit-ready).-8. Resources/images/mermaid (**6c/6d**) + settings + share until **gate B** green.-9. Only then: retarget store-delivery, stop EAS iOS, freeze `apps/mobile/ios`, update AGENTS + bilingual store-delivery docs + parity doc.--**Do not mix** in one commit series: editor bundle changes + store-delivery cutover; outbox protocol + unrelated Android feature work without fixtures.-------## PR Plan--> **Repo constraint:** `AGENTS.md` forbids new long-lived git branches. Items below are **ordered work packages / commit series on `main`**. The word “PR” means a reviewable package—not a requirement to open GitHub branches. If a human opens a short-lived PR, merge immediately.->-> **Critical path:** 1 → 2 → 3 → 4 → 5 → 6a/6b → 8 **(gate A)** → 7/6c/6d → 9–11 → 12 cutover → 13 submit **(gate B)**.->-> **Effort bands (rough):** S ≤ 1 day, M 2–4 days, L 5–10 days, XL > 10 days for one experienced engineer.--### PR 1 — Scaffold `apps/ios` shell — **S**--- **Title:** `ios: scaffold SwiftUI app target and project layout`-- **Files/components:** `apps/ios/**` (App entry, empty RootView, xcconfig, entitlements with App Group, README)-- **Dependencies:** none-- **Do not mix:** store-delivery or Android changes-- **Description:** Xcode project, iOS 17, bundle id `org.edgeever.mobile`, URL scheme, PrivacyInfo. Placeholder UI only.--### PR 2 — Keychain session + APIClient auth — **M**--- **Title:** `ios: add Keychain session store and auth API client`-- **Files/components:** `Data/Session/*`, `Data/Network/APIClient.swift`, `LoginView`, auth models-- **Dependencies:** PR 1-- **Description:** login/logout/getSession/changePassword; URL normalize; 401 clears session; HTTP warning UI (K22).--### PR 3 — GRDB schema + local mirror + fixture harness — **M**--- **Title:** `ios: GRDB local mirror schema and list queries`-- **Files/components:** `Data/Database/*`, models, `tests/mobile-sync-fixtures/` skeleton, Swift tests for scope/list-- **Dependencies:** PR 1-- **Description:** Migrations (mirror + outbox + drafts). upsert/list/get/resolve/replaceLocalMemoId/softDelete. No search index required for parity.--### PR 4 — Sync engine (bootstrap + incremental) — **M**--- **Title:** `ios: sync engine for bootstrap and incremental changes`-- **Files/components:** `SyncEngine`, `SyncProtocol`, `/sync/*` client methods, progress UI-- **Dependencies:** PR 2, PR 3-- **Description:** Single-flight, page sizes 200/50/200, rewind/identity rebuild, preserve `local:`. Fixture tests for rewind/identity.--### PR 5 — Workspace UI: notebooks + notes list + detail chrome — **M**--- **Title:** `ios: workspace list and memo detail shell`-- **Files/components:** `Features/Workspace/*`, list rows, search debounce, pin + soft delete, notebook **tree browse/select/filter** (from mirror)-- **Dependencies:** PR 4-- **Description:** Navigation, notebook hierarchy selection (RN parity—**not** create/rename/delete), list from mirror, detail chrome. Empty notebook set messaging. Memo notebook field on edit comes with PR 8. Body can be placeholder until 6a.--### PR 6a — Editor viewer bundle — **M**--- **Title:** `ios: TipTap EditorBundle viewer mode`-- **Files/components:** `EditorSource/**` (viewer), `EditorBundle/**`, `TipTapWebView`, bridge `ready`/`setDocument`, `build-editor-bundle.sh`-- **Dependencies:** PR 1 (parallelizable with 2–5)-- **Description:** Offline render of doc JSON (paragraphs/lists/quotes/tables). No toolbar yet.--### PR 6b — Editor + toolbar + markdown change events — **L**--- **Title:** `ios: TipTap editor mode toolbar and markdown bridge`-- **Files/components:** editor mode, toolbar, `change` with `contentMarkdown` (K20), Vitest markdown fixtures-- **Dependencies:** PR 6a-- **Description:** Full text editing surface for gate A. Mermaid/images not required.--### PR 7 — Resource loading + image upload — **M** (App Review path)--- **Title:** `ios: authenticated resources and image upload`-- **Files/components:** ResourceLoader/Cache, ImageCompressor, multipart upload, PHPicker, photo usage string-- **Dependencies:** PR 2, PR 6b (ideally after 6c hooks)-- **Description:** Bearer → data URL; **Materialize algorithm K24** (single server create; unit tests for draft-only / pending create cancel / syncing wait / double-tap); compression toggle. **Not required for gate A.**--### PR 6c / 6d — Resources bridge + mermaid — **M**--- **Title:** `ios: TipTap resource bridge and mermaid`-- **Files/components:** `loadResource`, placeholders, mermaid module-- **Dependencies:** PR 6b; pairs with PR 7-- **Description:** Completes store body AC.--### PR 8 — Create/edit autosave + outbox flush + conflicts — **L** (**Gate A**)--- **Title:** `ios: memo create/edit autosave and sync outbox`-- **Files/components:** outbox repo/flusher, MemoEditView, drafts, conflict UI, soft-delete port, fixture tests (absorb/promote/rebase/orphan/precheck)-- **Dependencies:** PR 4, PR 5, **PR 6b** (not PR 7)-- **Description:** RN-aligned new-note draft-until-Done; Done → `local:` + `memo.create`; existing memo always-outbox (K6). Title/tags/body/notebook. Create-absorbs-update, promote, rebase, edit-session precheck. Force flush on background. **Internal edit-ready / text TestFlight gate.** Images/materialize explicitly out of this gate (PR 7).--### PR 9 — Settings, tokens, device sessions, i18n, diagnostics — **M**--- **Title:** `ios: settings account security tokens and localization`-- **Files/components:** Settings, preferences, `Localizable.xcstrings`, debug diagnostics export-- **Dependencies:** PR 2, PR 5-- **Description:** Locale/theme/density/compression, password, tokens, sessions, sign out, export sync diagnostics.--### PR 10 — Share Extension rewrite — **S–M**--- **Title:** `ios: native Share Extension handoff`-- **Files/components:** `ShareExtension/*`, App Group, ShareHandoffStore-- **Dependencies:** PR 5, PR 8-- **Description:** Text/URL only → create draft. Release notes note media share deferred.--### PR 11 — Polish + performance (+ optional revisions) — **M**--- **Title:** `ios: polish performance and optional revisions`-- **Files/components:** keyboard/safe area, empty states, optional revision UI-- **Dependencies:** PR 8; images/mermaid if targeting gate B-- **Description:** Launch timings; a11y; revisions only if schedule allows (Deferred).--### PR 12 — CI, parity docs, retire EAS iOS, store-delivery retarget — **M**--- **Title:** `build: native iOS pipeline and retire Expo iOS builds`-- **Files/components:**- - `.github/workflows/store-delivery.yml` (ios job → xcodebuild/fastlane from `apps/ios`)- - `docs/store-delivery.md` + **`docs/store-delivery.zh-CN.md`**- - `docs/mobile-build.md`- - `docs/mobile-native-parity.md` (SwiftUI iOS / RN Android shells)- - `AGENTS.md` (iOS `MARKETING_VERSION` / `CURRENT_PROJECT_VERSION` on native iOS releases)- - `apps/mobile/eas.json` (disable iOS profiles)- - `scripts/validate-store-delivery.mjs` (+ tests) for ios version checks- - `apps/ios/fastlane/*`- - optional: remove/freeze `apps/mobile/ios` (K23)-- **Dependencies:** **Gate B on TestFlight** (or at least gate A + decision to keep EAS until B). **Do not** disable EAS iOS before a shippable Swift binary exists.-- **Description:** Document Android-only Expo for RN; native iOS archive/upload; GitHub Release still APK+DMG only.--### PR 13 — App Store submission package — **S–M** (**Gate B**)--- **Title:** `release: iOS Swift binary App Store submission prep`-- **Files/components:** store metadata/screenshots, review notes (demo login, native rewrite), version bumps, first-week crash-watch owner-- **Dependencies:** PR 12 + gate B checklist green-- **Description:** Archive → TestFlight → App Review. Bilingual user-facing release notes on formal monorepo release. Name crash-watch owner for first week.-------*End of design document.*diff --git a/docs/mobile-build.md b/docs/mobile-build.mdindex 95d207e5..41c2a890 100644--- a/docs/mobile-build.md+++ b/docs/mobile-build.md@@ -1,6 +1,6 @@-# EdgeEver Mobile Builds+# EdgeEver Android Builds-EdgeEver Mobile is built with Expo and React Native. Main-branch Android packages are built directly on GitHub Actions, without using EAS Build quota.+The Android app in `apps/mobile` is built with Expo and React Native. iOS store binaries come from `apps/ios` (SwiftUI), not this tree. Main-branch Android packages are built directly on GitHub Actions, without using EAS Build quota.## App Updates@@ -139,25 +139,10 @@ repository.### iOS App Store build-The production iOS app uses the bundle identifier `org.edgeever.mobile`. The-Apple Developer team and distribution credentials are managed through EAS so-that the App Store archive can be built without storing signing certificates in-the repository or on the release machine:--```sh-cd apps/mobile-bunx eas-cli credentials:configure-build --platform ios --profile production-bunx eas-cli build --platform ios --profile production-```--The first command requires the Apple Account Holder to authenticate and may-prompt for two-factor authentication. The production profile automatically-increments the App Store build number. Routine delivery should use the separate-store-delivery workflow, which builds from an immutable formal Release tag,-uploads to App Store Connect, and submits that exact build to App Review.-Approved builds are released automatically. Apple credentials, App Store-Connect API keys, certificates, and provisioning profiles must never be-committed.+iOS is a SwiftUI app in `apps/ios`, using the same bundle identifier+`org.edgeever.mobile`. Do not build or submit iOS from `apps/mobile` or EAS.+On macOS beta hosts, archives must go through Xcode Cloud. See+[iOS Xcode Cloud](ios-xcode-cloud.md) and [Mobile Store Delivery](store-delivery.md).## EASdiff --git a/docs/mobile-native-parity.md b/docs/mobile-native-parity.mddeleted file mode 100644index f7dafd03..00000000--- a/docs/mobile-native-parity.md+++ /dev/null@@ -1,49 +0,0 @@-# Mobile native parity and performance--The Android app is a React Native client of the EdgeEver API. The PWA remains the product reference for features and visual language, but it must not be embedded as the primary App workspace.--## Performance acceptance targets--These targets are measured on a mid-range Android device using a signed release build and an already authenticated account.--| Path | Target |-| --- | --- |-| Cold launch to native shell | under 1.0 s |-| Warm launch to cached notebook and memo list | under 0.5 s |-| Cached list to usable state | no network dependency |-| Memo list scrolling | no sustained dropped-frame sequence |-| Search typing | no request per keystroke; 250 ms debounce |-| Filter or sort change | keep prior content until replacement data is ready |--Build success is not a performance result. Before a Play production rollout, record cold and warm launch timings on a physical device and compare them with the currently published internal build.--## Architecture rules--- Render startup, navigation, notebook selection, memo lists, search, and settings with native React Native views.-- Reuse the shared API client and shared data types instead of duplicating backend contracts.-- Hydrate only the default notebook and memo-list queries at startup. Refresh stale data in the background.-- Clear persisted query data when the account changes, signs out, or becomes unauthorized.-- Keep optional heavyweight features out of the startup path. Do not embed the PWA or a WebView as the App workspace shell (lists, navigation, settings).-- Note body rendering may use a TipTap WebView runtime for both **read-only preview** and **edit**, so the same document schema, images, tables, and Mermaid path are shared. Native chrome owns headers, FABs, sheets, and system actions around that body.-- Use virtualized lists and stable item components for collections.--## Mobile product scope--The App follows the mobile PWA for high-frequency layouts and interactions, but it is not a copy of every desktop management feature. Shared mobile interaction contracts belong in `@edgeever/shared`; platform-specific rendering, local persistence, protected resource loading, and save lifecycles remain separate when that preserves native performance.--| Mobile capability | Native status |-| --- | --- |-| Login and self-hosted instance connection | Implemented |-| Notebook hierarchy and management | Implemented |-| Memo list, filters, sort, pin, and batch operations | Implemented |-| Local-cache search | Implemented |-| Local TipTap create/edit and autosave flow | Implemented |-| Note detail body preview via read-only TipTap (same schema as edit) | Implemented |-| Attachments, image compression, and resource library | Implemented |-| Tag management | Implemented |-| Revision history and restore | Implemented |-| Offline drafts, local mirror, and sync queue | Implemented |-| MCP/API token management | Implemented |-| Password change and multi-user management | Implemented |--Desktop-first management features such as unified ZIP import/export and trash browsing, restore, or empty-trash actions are intentionally excluded from the App core. Ordinary mobile deletion remains a soft delete so that recovery stays available from the desktop/PWA interface. Future mobile work should prioritize capture, reading, editing, search, sync reliability, startup speed, and interaction smoothness instead of restoring these excluded screens.diff --git a/docs/personality-memory-agent.md b/docs/personality-memory-agent.mddeleted file mode 100644index ca604fb6..00000000--- a/docs/personality-memory-agent.md+++ /dev/null@@ -1,90 +0,0 @@-# EdgeEver Paw mode: design and tradeoffs--[简体中文](personality-memory-agent.zh-CN.md)--Updated: 2026-09-05. This describes implementation and validation limits, not release notes.--## 1. Product purpose--Paw connects knowledge and proposes organization during everyday note work. Long-term memory must change future suggestions, not merely accumulate chat logs. Explicit preferences and evidence-backed filing/tagging habits now form this loop; understanding every user intention is not promised.--Suggestions stay separate from notes. Without a useful result Paw stays quiet. Merge, append, filing and tagging require confirmation. Existing business services execute saved arguments; the model cannot rewrite them during confirmation or write unattended.--## 2. Controls and interface--- Settings → Paw mode. Initial activation requires an available default AI model. Disabling Paw, pausing learning and stopping memory use do not require a working provider.-- “Learn from my choices” processes future operations only. Re-enabling skips operations performed while paused; disabling Paw also stops learning processing.-- “Use saved memories” controls both chat and discovery. Chat retains per-request note access, off by default. Pausing learning keeps memories; disabling recall does not delete them.-- Existing accounts do not silently opt into learning or discovery memory. Enable these controls explicitly. The chat memory checkbox updates the same global setting.-- “Conversation and personal memory” shows explicit information, candidate/active/conflicting inferences and evidence. Memories can be corrected or forgotten.-- Organization cards offer “Stop suggesting this kind of organization,” recording an explicit preference for the source notebook. Ordinary dismissal is not a lasting preference.-- Web and desktop provide the UI. Native Android/iOS have no Paw entry yet. Only reliably attributed operations reaching the shared server business services can contribute; native end-to-end behavior is unverified.--## 3. Current capabilities--| Path | Capability and boundary |-| --- | --- |-| Connection | Explains a concrete relationship between at least two notes |-| Merge | Fragments of one concrete idea only; preserves text, attachments and tags, trashes sources and revokes shares; no complete one-click undo |-| Append | Adds a plain-text fragment to a target and preserves both originals; excludes complex documents and source attachments |-| Filing | Proposes an existing notebook; confirmation uses the existing move tool |-| Tagging | Uses tags present in candidate notes and preserves the target's existing tags |-| Optional chat | Retains the existing 28 note tools and confirmation flow; explicit and active inferred memories can enter context |--## 4. Learning and durable memory--Reuse the existing AI SDK, database and business services. No new agent framework, vector database or permanently running background process.--The first implementation uses deterministic evidence rules rather than model self-rated confidence:--1. Existing `memo.move`, `memo.update`, `tag.add/remove` audit records include before/after notebooks and tags. Note saving does not call a model or maintain memories.-2. Idle checks asynchronously consume committed audits, scoped to workspace/user and attributable user operations. Imports lack learning snapshots; tool execution is marked as agent activity and does not count as independent user behavior.-3. Learn two scoped patterns: notes with a particular tag are usually filed in a notebook; notes in a notebook are frequently given a particular tag.-4. Require three distinct notes, three independent time windows and at least two days of consistent choices. A bulk burst within ten minutes counts at most once. Event IDs deduplicate; evidence and processing cursor commit together.-5. Reevaluate when sources are deleted, filing changes, competing targets appear, or evidence exceeds 90 days. Conflicting inferences are excluded from recall. These thresholds are initial product rules, not proven accuracy guarantees.-6. Corrections become explicit user statements and cannot be overwritten by learning. Forgetting removes evidence and keeps a content-free rule exclusion key, preventing the same rule from returning from old or future observations.--Up to 50 memories, including at most 30 automatic inferences, reserving room for explicit preferences. Each pass consumes at most 50 audit events with a small number of rules per event and reviews at most 2,000 recent evidence records. Busy accounts may process later; learning every action is not guaranteed.--Automatic extraction from free-form chat, abstract project/relationship modeling, weighted learning from accepted suggestions, and precise undo attribution remain unimplemented. Explicit chat preferences can be saved with “Remember this message.” Paw's own operations do not positively reinforce its habits.--## 5. How memory changes suggestions--Discovery searches multiple keywords and recent records, selecting at most six complete note bodies within 12,000 characters. The most recently updated note remains the anchor; rotating through multiple anchors is not implemented.--Chat and discovery share memory selection: valid status, scope, keywords and recency, with explicit preferences before inferences. Up to eight records within 4,000 characters; a small fallback is used without keyword matches. No full-library prompt or model training.--The model receives selected notes, related memories and existing notebooks. Notes and memories are untrusted data, not permission changes or confirmations. Structured results cite note and memory identifiers; the server validates them and persists exact proposals. Cards can show memories used. Explicit “stop suggesting” rules are also filtered server-side.--Input fingerprints include memory and notebook context. A memory version change can trigger analysis without a note change and invalidates old context/pending actions. Execution still rechecks access, versions, sources and synchronization. Completed operations retain their receipts.--## 6. Storage, deletion and backup--New migration [0045](../migrations/0045_companion_learning.sql), without editing old migrations:--- Extend `companion_memories` with kind, scope, rule key and state; preserve legacy explicit records and versions.-- Add `companion_memory_evidence` and `companion_memory_exclusions` for evidence references and excluded rule identifiers.-- Extend discovery settings with learning/recall controls, learning cursor and last analyzed memory version.-- Expand the discovery kind constraint, preserve old discoveries and add used-memory IDs.--Records are isolated by workspace and user. Cloudflare/D1 and Docker/Bun SQLite share business services and SQL.--Separate JSON export uses version 2, preserving memory kinds and learning controls. Version 1 import remains supported. Version 2 merges memories and restores controls; imported inferences have no trusted evidence and remain candidates until explicitly confirmed. Notebook scopes, exclusions and evidence are not reconstructed across instances. Chat and execution history are not imported.--These records remain outside note ZIP backups, desktop offline mirrors and native mobile synchronization. Deleting a note retracts its learning evidence, not existing chat snapshots. Forgetting cannot delete exported files or provider-retained data.--## 7. Runtime and costs--Checks require a visible, online app without pending synchronization, after three idle minutes. Ordinary note changes are checked at most daily; memory changes can trigger earlier checks, at most hourly. Rate limits and concurrency claims are account-wide. The client does not poll continuously or retry without new events. Rule learning makes no model calls.--Each discovery makes at most one structured generation, with 1,200 output tokens, a 60-second timeout and no automatic paid retry. Selected notes and memories go to the default model provider; a check producing no notification can still cost money. Character budgets are not token counts; no fixed cost or savings claim.--## 8. Validation and rollback--Coverage includes bulk/repeated operations, pause/re-enable, isolation, conflicts, corrections, forgetting, candidate imports, memory-triggered discovery, filing/tagging confirmation and reopening/upgrading an old SQLite database. An isolated local D1 database also receives old migrations/data, then migration 0045, followed by data-preservation and foreign-key checks.--Run the full non-E2E suite, `bun run typecheck`, `bun run typecheck:mobile`, and `bun run build:web`. Browser verification uses Codex's built-in Browser.--Unverified: production D1 upgrade, long-term real-user suggestion quality, actual model cost and native mobile cross-version behavior. Do not claim no impact on existing users or automatic updates.--Pause learning to stop new evidence processing; disable memory use to return discovery to note context. Retain additive database fields instead of destructive reverse migrations. Disable Paw before downgrading code so old clients do not handle new discovery kinds. Confirmed note operations are not automatically undone by disabling or rolling back Paw.diff --git a/docs/personality-memory-agent.zh-CN.md b/docs/personality-memory-agent.zh-CN.mddeleted file mode 100644index ac51b007..00000000--- a/docs/personality-memory-agent.zh-CN.md+++ /dev/null@@ -1,90 +0,0 @@-# EdgeEver 猫爪模式:方案与取舍--[English](personality-memory-agent.md)--更新:2026-09-05。本文描述当前实现与验证边界,不是发布说明。--## 1. 产品定位--猫爪围绕日常笔记工作提供知识关联和整理建议。长期记忆必须影响后续建议,而不只是积累聊天记录。当前通过显式偏好和有证据的归档、标签规律实现这一闭环;不承诺理解用户的所有意图。--建议独立于正常笔记;没有有用结果就保持安静。合并、补入、归档和添加标签均需要用户确认后执行。确认复用现有业务服务,模型不重新生成参数,也没有无人值守写入权限。--## 2. 开关与界面--- 设置 → 猫爪模式。首次开启需要可用的默认 AI 模型;关闭模式、暂停学习和停止使用记忆不依赖模型可用性。-- “从操作中学习”只处理开启之后的操作;暂停及重新开启不会补学停用期间的历史。关闭猫爪也停止处理学习事件。-- “使用已保存的记忆”统一控制对话和主动发现。对话仍有本轮笔记访问控制,默认关闭。暂停学习保留记忆,停止使用不删除记忆。-- 旧账户升级不自动开启学习或主动发现记忆;需要在设置中明确启用。对话的记忆复选框同步这一全局设置。-- “对话与个人记忆”展示显式信息、候选推测、有效推测和冲突状态,以及操作证据。可以编辑和忘记。-- 整理卡片提供“不再建议这种整理”:针对来源笔记本记录明确偏好。普通忽略只关闭当前建议,不被解释为长期偏好。-- Web / 桌面提供界面。原生 Android / iOS 尚无猫爪入口;只有经过同一服务端业务并可靠归因的同步操作才可能参与学习,尚未完成原生端到端验证。--## 3. 当前能力--| 路径 | 能力与边界 |-| --- | --- |-| 知识关联 | 解释新旧笔记间的具体联系,至少两篇来源 |-| 合并 | 仅同一具体想法的片段;保留正文、附件、标签,来源移入回收站并撤销分享;不承诺一键整体撤销 |-| 补入 | 将纯文本片段追加到目标,保留两篇原文;不处理复杂文档或带附件的来源 |-| 归档 | 提出已有笔记本目标,确认后执行现有移动工具 |-| 添加标签 | 仅使用候选笔记中的已有标签,保留目标原有标签 |-| 可选对话 | 保留原有 28 项笔记工具与写入确认流程;显式记忆和有效推测均可进入上下文 |--## 4. 学习与长期记忆--采用现有 AI SDK、数据库和业务服务,不引入新的 Agent 框架、向量数据库或常驻后台进程。--第一版使用确定的证据规则,不调用模型给自己打置信分:--1. 在现有 `memo.move`、`memo.update`、`tag.add/remove` 审计中补充笔记本及标签前后值,不在笔记保存路径调用模型或更新记忆。-2. 空闲检查异步消费已经提交的审计。按工作区、用户过滤,仅使用可归因的用户操作;导入没有学习快照,工具执行标记为 agent,不作为主动习惯证据。-3. 学习“带某标签的笔记通常放入某笔记本”和“某笔记本中经常添加某标签”两类有范围的规律。-4. 至少三个不同笔记、三个独立时间段、跨两天的一致选择才使推测生效。同一十分钟内的批量操作至多贡献一次选择。事件 ID 去重,处理游标和证据写入同一事务。-5. 来源被删除、归类被改动、出现竞争目标或证据超过 90 天后重新评估;有冲突的推测不参与召回。这些阈值是初始产品规则,仍需真实场景验证。-6. 显式纠正转为用户确认的信息,后续学习不能覆盖。忘记学习规律会删除其证据并保存无正文的规则排除键,阻止旧证据及后续相同规律重新出现。--最多保存 50 条记忆,其中自动推测最多 30 条,给明确偏好留出空间。每次消费最多 50 个审计事件,每事件最多提取少量规律;回顾最多 2,000 条近期证据。预算可能使繁忙账户延后处理,不能保证所有行为都学到。--自动从自由对话提取偏好、抽象项目背景/关系建模、从接受建议中加权学习以及精确关联撤销操作,仍未实现。明确对话偏好可以通过“记住这句话”保存。猫爪自己的操作不用于正向强化,避免形成自我证明的循环。--## 5. 如何影响建议--主动发现通过多个关键词检索相关旧笔记,结合近期记录选取最多六篇正文,总计 12,000 字符。仍以最近更新的一篇为当前线索,尚未实现多线索轮转。--同一记忆选择模块供对话与发现复用:按有效状态、适用范围、关键词及时间召回,显式偏好优先于推测。最多八条、总计 4,000 字符;无关键词匹配时保留少量回退内容,不读取全库或训练模型。--模型收到选中笔记、相关记忆和已有笔记本。笔记、记忆都是不可信数据,不能改变权限或伪造确认。结构化结果返回笔记与记忆来源编号,服务端校验并保存准确操作方案;通知可显示采用的记忆。明确的“不再建议”规则同时在服务端过滤。--输入指纹包含记忆和笔记本上下文,避免用旧偏好缓存结果。记忆版本变化即使没有笔记变化也可触发重新分析,并使旧上下文及待确认操作失效。确认执行仍重查权限、版本、来源和同步状态;已完成操作保留回执。--## 6. 存储、删除与备份--新增迁移 [0045](../migrations/0045_companion_learning.sql),不修改旧迁移:--- 扩展 `companion_memories`:类型、范围、规则键、状态,保留原显式记忆及版本。-- 新增 `companion_memory_evidence` 和 `companion_memory_exclusions`,分别存储证据引用和排除键。-- 扩展发现设置:学习与使用开关、学习游标、最近分析记忆版本。-- 扩展发现类型约束,迁移原发现记录并增加使用的记忆 ID。--记录按工作区和用户隔离。Cloudflare/D1 与 Docker/Bun SQLite 使用相同服务代码和 SQL。--独立 JSON 导出升级至版本 2,保留记忆类型和学习控制项。兼容版本 1 导入;版本 2 导入恢复控制项,合并记忆,但推测不带入可信证据,作为候选等待用户确认。笔记本范围、规则排除键和证据不跨实例重建,导入不恢复聊天或执行记录。--这些数据仍未纳入笔记 ZIP、桌面离线镜像或原生移动同步。删除笔记会撤销其学习证据,但不删除已有聊天快照;忘记不能删除用户导出文件或模型服务商留存。--## 7. 运行与成本--应用可见、联网、无待同步改动,停止操作三分钟后尝试检查。常规笔记变化每天最多检查一次;记忆变化可提前检查,最多每小时一次。按账户共享限频和并发占用。客户端不常驻轮询,持续没有新事件就不重复请求。规则学习不调用模型。--每次发现最多一次结构化模型生成、1,200 输出 token、60 秒超时,不自动付费重试。选中笔记和相关记忆发送给默认模型服务商;无通知也可能产生费用。字符预算不是 token 计量,不承诺固定费用或节省比例。--## 8. 验证与回滚--验证覆盖批量/重复操作、关闭与重新启用、隔离、冲突、纠正、遗忘传播、候选导入、记忆触发发现、归档/标签确认及旧 SQLite 数据库重开升级。另在隔离的本地 D1 中应用旧迁移、写入旧数据、升级 0045,并检查保留数据和外键。--必须运行全量非 E2E 测试、`bun run typecheck`、`bun run typecheck:mobile`、`bun run build:web`。浏览器验证使用 Codex 内置 Browser。--尚未验证:线上 D1 升级、真实用户长期建议质量、真实模型成本和原生移动端跨版本行为。不能据此声称“不影响现有用户”或“不影响自动升级”。--关闭学习可停止新证据处理;关闭记忆使用可让发现退回笔记上下文。数据库保持向前兼容字段,不用破坏性逆向迁移回滚;降级旧代码前应关闭猫爪,避免旧客户端处理新增发现类型。已确认笔记操作不因关闭或回滚而自动撤销。diff --git a/docs/project-structure.md b/docs/project-structure.mddeleted file mode 100644index 565131c6..00000000--- a/docs/project-structure.md+++ /dev/null@@ -1,63 +0,0 @@-# EdgeEver Project Structure--```text-edgeever/-├── apps/-│ ├── web/ Vite + React product UI, PWA, offline drafts, sync queue-│ ├── extension/ Chrome/Edge/Firefox Manifest V3 web clipper-│ ├── api/ Cloudflare Worker + Hono API, OpenAPI, MCP endpoint-│ ├── mobile/ Expo + React Native Android app (production path)-│ ├── ios/ Native SwiftUI iOS app (TipTap EditorBundle, GRDB mirror/outbox; see docs/ios-swift-rewrite.md)-│ ├── desktop/ Electron shell, preload bridge, and packaging-│ └── site/ Astro official website-├── packages/-│ ├── client/ Shared API client-│ └── shared/ Shared types, schemas, and content conversion-├── crates/-│ └── desktop-sidecar/ Rust sidecar for local SQLite and native data services-├── migrations/-│ └── 0001_initial.sql-├── scripts/ Wrangler wrapper, CLI, MCP bridge, and build helpers-├── docs/ API, architecture, migration, and deployment docs-├── .github/workflows/ CI, packaging, deployment, and release workflows-├── tailwind.config.ts-├── wrangler.toml-├── bun.lock-└── package.json-```--## Deployment Shape--EdgeEver should deploy as one Cloudflare Worker:--- `/api/*` is routed to the Hono app first.-- Static files from `apps/web/dist` are served by Workers Assets.-- Unknown static routes fall back to `index.html` for SPA and PWA navigation.-- `env.DB` is the D1 binding.-- `env.RESOURCES` is the R2 bucket binding for images and attachments.--The official website in `apps/site` is an Astro static site. It is built and-deployed independently from the product Worker, typically to Cloudflare Pages.--## Frontend Boundaries--- `components/layout` owns the responsive three-pane shell.-- `components/notebook-tree` renders recursive notebooks from `parent_id`.-- `components/memo-list` owns checkbox selection and merge action surfaces.-- `components/editor` owns TipTap integration and Markdown serialization.-- `lib/api-client.ts` should be the only browser module that talks to `/api/*`.--## API Boundaries--- `routes/*` should stay thin: validate input, call services, return JSON.-- `services/merge-memos.ts` owns the D1 transaction that creates a merged memo, soft deletes source memos, and re-points resources.-- `services/resource-store.ts` owns R2 object keys and upload/download URL policy.-- `db/*` owns SQL snippets and row mapping.--## Data Model Notes--- Notebook nesting is unbounded through `notebooks.parent_id`.-- Every memo belongs to exactly one notebook through `memos.notebook_id`.-- Merge output is represented by a new memo with `source_memo_ids` and `merge_source_count`.-- Merge inputs are retained as soft-deleted rows with `merged_into_memo_id`.-- R2 objects are not moved during merge; `resources.memo_id` is updated to the new memo.diff --git a/docs/promotion/edgeever-hero-product.png b/docs/promotion/edgeever-hero-product.pngdeleted file mode 100644index 1ea6b447..00000000Binary files a/docs/promotion/edgeever-hero-product.png and /dev/null differdiff --git a/docs/promotion/juejin_cover.jpg b/docs/promotion/juejin_cover.jpgdeleted file mode 100644index 8def4f91..00000000Binary files a/docs/promotion/juejin_cover.jpg and /dev/null differdiff --git a/docs/promotion/promotion_article_juejin.md b/docs/promotion/promotion_article_juejin.mddeleted file mode 100644index 910c0e9d..00000000--- a/docs/promotion/promotion_article_juejin.md+++ /dev/null@@ -1,143 +0,0 @@-# 💡 掘金推广文章推荐标题(三选一)--1. **🔥 0 元自建!我用 Cloudflare 免费额度做了一个“印象笔记”替代品,原生支持 AI 自动整理!**-2. **别交服务器月租了!用 Cloudflare Serverless 架构,0 成本白嫖终身免费的个人知识库**-3. **这才是 AI 时代的开源笔记!经典三栏布局 + 零服务器托管,让 Claude 帮你打理知识库**--## 📝 掘金文章编辑摘要(三选一,限100字内)--* **第 1 版(最推荐,突出无服务器与AI)**:- > 0元免服务器!用Cloudflare免费级配额自部署开源三栏笔记EdgeEver,无VPS月租与运维心智负担。原生支持AI Agent (MCP),让Claude/GPT帮你管理知识库,体验终身免费的个人大脑!-* **第 2 版(侧重开发者极客风)**:- > 为AI时代打造的开源笔记EdgeEver!保留经典三栏体验,基于Cloudflare Serverless架构实现日常零费用自托管。内置MCP,AI助手可原生读取整理笔记,0成本构建个人专属的智能知识库。-* **第 3 版(侧重产品替代/告别限制)**:- > 告别收费限制与高昂自建成本!开源笔记EdgeEver完美保留经典印象笔记三栏体验,跑在Cloudflare免费额度上,终身无需服务器与运维。支持AI Agent原生连接,助你搭建免费的第二大脑。-------# 正文内容--## 引言:当你的个人知识库被“绑架”--作为一名重度笔记用户,不知道你是否也经历过这些痛点:--* **传统笔记软件越来越臃肿**:某象笔记开机卡顿、广告漫天,甚至开始限制多设备登录;-* **自建笔记成本高昂**:想用 Docker 自建个 Memos 或 Wiki,每个月还得给云服务器(VPS)交 **3~5美刀** 的服务器月租,还要配置证书、防 DDOS、维护容器,心智负担拉满;-* **数据封闭,难以迁移**:笔记被锁死在特定格式里,想导出来比登天还难;-* **对 AI 极度不友好**:不支持 MCP,AI 助手(如 Claude Code, Cursor 等)根本无法读取和整理你的本地笔记。--如果你也深受折磨,那么是时候了解一下 **EdgeEver** 了。-------## 🚀 什么是 EdgeEver?--**EdgeEver** 是一个**开源、自托管、Cloudflare-native(无服务器架构)**的现代笔记工作区。它不仅完美保留了经典印象笔记的“三栏体验”,更是一款真正**为 AI 时代设计的个人知识库**。--最重要的是:**它自部署不需要你购买任何服务器,日常使用完全免费!**--* **GitHub 仓库**:[tianma-if/edgeever](https://github.com/tianma-if/edgeever)-* **在线 Demo**:[https://demo.edgeever.org](https://demo.edgeever.org)-------## 💎 核心亮点:为什么它与众不同?--### 1. 终身免服务器,100% 免费(白嫖 Cloudflare 边缘计算红利)--传统的自部署项目离不开 VPS 虚拟主机,而 EdgeEver 另辟蹊径,采用了纯 **Serverless(无服务器)** 架构。--它完全运行在 **Cloudflare Workers + D1 (SQLite) + R2 (对象存储)** 上:-* **不需要购买任何云服务器**,省去每月的租金;-* **不需要折腾复杂的 Docker、Nginx 或 SSL 证书**,Cloudflare 帮你搞定一切;-* **白嫖 Cloudflare 的免费配额**:- * **D1 数据库**:每天读写额度极高,足够存放 **15 万条** 短笔记;- * **R2 对象存储**:提供 10GB 免费存储空间,按图片平均 200KB 算,可存放 **5 万张** 笔记配图。--> 💡 *提示*:EdgeEver 还内置了前端图片本地压缩机制,截图上传前自动转为 WebP 并限制分辨率,体积减少 50%~90%,进一步榨干免费额度!--### 2. 完美复刻“三栏式”工作流--很多轻量化笔记产品为了简洁砍掉了经典的布局。而 EdgeEver 坚持保留了最符合人类知识整理直觉的**三栏设计**:--* **左栏**:无限级嵌套的笔记本树,支持鼠标拖拽排序与层级调整;-* **中栏**:笔记列表,支持多选批量移动、批量合并;-* **右栏**:富文本编辑区,基于 TipTap 深度定制,支持 Markdown 快捷输入,并原生支持**查看历史版本**,随时可以回溯。-* **多端适配**:完美适配 PC 与移动端,支持安装为 **PWA** 应用,像原生 App 一样启动。--### 3. AI Agent 原生连接器(Remote MCP)--这不仅是一个人写的笔记,更是你和 AI 助手协同的“大脑”。--EdgeEver 内置了 **REST API**、**OpenAPI 协议** 以及 **Remote MCP (Model Context Protocol) Endpoint**:-1. 在 EdgeEver 个人中心生成一个 MCP Token;-2. 填入你的 AI 助手(如 Codex、Claude Code、Antigravity、Cursor 等);-3. **授权 AI 直接读取、整理和维护你的笔记库**。--**💡 玩法放飞脑洞:**-* 吩咐 Claude Code:“帮我把最近随手记下的散乱想法归纳成一篇技术博客大纲”;-* 让 AI 分析你过去几个月的学习笔记,精细化构建你的知识图谱;-* 批量为没有分类的笔记自动打上标签。-------## 🛠 部署指南:如何一键“白嫖”?--EdgeEver 的部署简单到了极致,甚至你都不需要打开终端。--### 方式 A:AI Agent 一句话部署(推荐)--将下面这段提示词复制给已配置 GitHub、Cloudflare MCP、插件或其他可用集成的 AI Agent:--```text-请在线完成 EdgeEver 部署:-1. Fork https://github.com/tianma-if/edgeever。-2. 将这个 Fork 导入 Cloudflare Workers & Pages。-3. 严格按照 docs/agent-deploy-cloudflare.zh-CN.md 配置 D1、R2、EDGE_EVER_AUTH_PASSWORD Worker Secret 和 Workers Builds。-4. 启动首次构建,验证健康检查和登录,然后手动运行一次 Update deployed EdgeEver。-```--### 方式 B:Fork 后在线部署--先 Fork EdgeEver 上游仓库,然后在 Cloudflare Workers & Pages 中导入自己的 Fork,在线配置 D1、R2、Worker Secret 和构建命令。部署完成后,启用仓库中的上游更新工作流,后续版本会自动同步、验证并部署。--在 GitHub Fork EdgeEver 后,参考[在线部署文档](../deploy-cloudflare-button.zh-CN.md)完成配置。--高级恢复时才需要手动运行部署命令:--```sh-# 1. 复制环境变量-cp .env.local.example .env.local--# 2. 安装依赖并自动初始化资源-bun install-EDGE_EVER_PASSWORD='你的后台登录密码' bun run deploy:setup--# 3. 环境自检并部署-bun run deploy:doctor-bun run deploy:manual-```--部署完成后,终端会直接输出你的独立访问域名,点开即可使用!-------## ⚖️ 自建方案大比拼--| 特性 | 传统自建笔记 (如 Docker 部署) | 商业云笔记 (如 Notion / 某象) | **EdgeEver 自托管** |-| :--- | :--- | :--- | :--- |-| **服务器成本** | 💰 需购买 VPS (3~5美刀/月) | 🆓 免费但受限 / 需高额订阅 | **🎉 0 元 (跑在 Cloudflare 免费额度)** |-| **运维难度** | 🛠 需维护 Docker/网络/SSL/安全漏洞 | 0 运维 | **0 运维 (Cloudflare 全托管托管)** |-| **数据隐私** | 🔒 极高 (存在自己服务器) | ⚠️ 存在第三方云端,有倒闭/扫描风险 | **🔒 极高 (存在自己的 Cloudflare 账号中)** |-| **AI 协同** | ❌ 很难对接 AI 客户端 | ⚠️ 需购买官方高昂的 AI 增值服务 | **✅ 原生 Remote MCP,免费对接各类 Agent** |-------## 💬 结语--EdgeEver 的诞生,是为了让每个开发者都能低门槛、无成本地拥有一个真正属于自己的、安全的、且面向 AI 时代的知识库。--如果你觉得这个项目对你有帮助,欢迎来 GitHub 点个 **Star** 支持一下!--* **GitHub 仓库**:👉 [tianma-if/edgeever](https://github.com/tianma-if/edgeever)-* **Demo 试用**:👉 [demo.edgeever.org](https://demo.edgeever.org)diff --git a/docs/promotion/slogan.md b/docs/promotion/slogan.mddeleted file mode 100644index 4725d7ee..00000000--- a/docs/promotion/slogan.md+++ /dev/null@@ -1,54 +0,0 @@-# 📣 EdgeEver Slogans & 推广文案记录仓--本文件用于统一记录和归档 EdgeEver 项目在各平台(GitHub、官网、README、各大社区)所使用的 Slogan、标语和短介绍,方便维护和推广时一站式查阅。-------## 🌐 官网 & README 核心 Slogan--### 🇨🇳 中文-> **无需服务器、0 费用、开源且原生支持 AI Agent 的自托管『印象笔记』替代品。**-* *位置*:官网 Hero 首屏标题下、中文 README 顶部--### 🇺🇸 英文-> **A serverless, 100% free, open-source, and AI-native self-hosted Evernote alternative on Cloudflare.**-* *位置*:官网英文版首屏、英文 README 顶部--### 🇯🇵 日文-> **EdgeEver:オープンソース、AI ネイティブ、Cloudflare 無料枠 / Docker で自前運用できる Evernote 代替ノート。**-* *位置*:官网日文版首屏、日文 README 顶部-------## 🐙 GitHub "About" 短描述 (Description)--### 🇺🇸 纯英文(当前采用)-> **Open-source, AI-native knowledge base & Evernote alternative with native MCP. Zero-cost on Cloudflare or Docker.**-* *字符数*:111 字符(精炼利落,兼顾知识库、经典笔记替代、原生 MCP 与自托管部署)--### 🇨🇳 🇺🇸 中英双语备选-> **Open-source, AI-native knowledge base & Evernote alternative with native MCP. Zero-cost on Cloudflare or Docker. | 开源、原生支持 AI、0费用自托管的个人知识库与「印象笔记」替代品**-------## 💡 README 顶栏高亮横幅 (Banner)--### 🇨🇳 中文-```markdown-> 💡 **终身免服务器,100% 免费**-> EdgeEver 可以直接运行在 Cloudflare 免费额度内,无需购买服务器,个人日常使用 **0 费用、0 运维**;也可以把同一套应用通过 Docker 部署到 VPS、NAS 或家庭服务器,数据与运行环境始终由你掌控。-```--### 🇺🇸 英文-```markdown-> 💡 **Serverless & 100% Free Forever**-> EdgeEver can run within Cloudflare's free quotas with **no server purchase and zero maintenance**, or you can deploy the same application with Docker on a VPS, NAS, or home server while keeping full control of your data and runtime.-```-------## 📢 社区推广(如掘金、V2EX)核心卖点词--* **三零特性**:零服务器开销、零运维负担、零订阅费用。-* **白嫖配额**:每天 10 万次免费 Workers 调用,15 万条 D1 笔记行数,10GB 免费 R2 附件存储。-* **AI 大脑**:原生集成 Model Context Protocol (MCP),将你的笔记瞬间转化为 Agent 的外部记忆库。