From 20c4fcfb2609c00e0b04ca2a9ac91d9a1413f955 Mon Sep 17 00:00:00 2001 From: ali Date: Wed, 9 Sep 2026 13:50:14 +0800 Subject: [PATCH] Initial commit --- AGENTS.md | 83 ++++ LICENSE | 235 +++++++++ README.md | 55 +++ rules/00-usage-and-update.md | 199 ++++++++ rules/01-arkts-grammar.md | 452 ++++++++++++++++++ rules/02-arkui-and-state-management.md | 301 ++++++++++++ .../03-architecture-and-project-structure.md | 258 ++++++++++ rules/04-navigation.md | 258 ++++++++++ rules/05-network-and-backend.md | 235 +++++++++ rules/06-data-persistence.md | 164 +++++++ rules/07-performance.md | 216 +++++++++ rules/08-logging-and-error-handling.md | 207 ++++++++ rules/09-api-verification.md | 170 +++++++ rules/10-prohibited-and-checklist.md | 213 +++++++++ spec/feature.json | 3 + spec/harmony-code-rules/plan.md | 208 ++++++++ spec/harmony-code-rules/spec.md | 158 ++++++ spec/harmony-code-rules/tasks.md | 309 ++++++++++++ 18 files changed, 3724 insertions(+) create mode 100644 AGENTS.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 rules/00-usage-and-update.md create mode 100644 rules/01-arkts-grammar.md create mode 100644 rules/02-arkui-and-state-management.md create mode 100644 rules/03-architecture-and-project-structure.md create mode 100644 rules/04-navigation.md create mode 100644 rules/05-network-and-backend.md create mode 100644 rules/06-data-persistence.md create mode 100644 rules/07-performance.md create mode 100644 rules/08-logging-and-error-handling.md create mode 100644 rules/09-api-verification.md create mode 100644 rules/10-prohibited-and-checklist.md create mode 100644 spec/feature.json create mode 100644 spec/harmony-code-rules/plan.md create mode 100644 spec/harmony-code-rules/spec.md create mode 100644 spec/harmony-code-rules/tasks.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..268dbaf --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,83 @@ +# AGENTS.md - 鸿蒙应用开发规则入口(AI 编码助手必读) + +本仓库是 HarmonyOS ArkTS 项目模板,内置一套约束 AI 编码助手与开发者的开发规则体系(`rules/` 目录 11 份专题文档)。AI 编码助手在生成任何代码前,必须先阅读本文件的红线与索引,并按任务主题加载对应专题文档。 + +--- + +## 一、核心红线(违反任意一条即为缺陷) + +1. **禁止编造 API**:禁止编造任何 `@ohos.*` / `@kit.*` 模块、方法、参数签名、枚举成员与导入路径;调用前必须完成 `devecocli docs search` → `devecocli docs read` 两步验证,无法验证即禁用。(APIV-001、APIV-003、APIV-004) +2. **禁止 any 与无类型字面量**:禁止 `any`/`unknown`;对象字面量必须显式标注类型。(ARK-001、ARK-002) +3. **禁止 ArkTS 强禁语法**:禁止解构赋值/声明、对象字面量类型、结构化类型(structural typing)、索引签名、交叉类型、`var`、`for..in`、`delete` 等动态特性。(ARK-003 ~ ARK-005、ARK-007、ARK-008、ARK-011) +4. **禁止状态管理 V1/V2 混用**:`@Component` 内禁用 `@Local`/`@Param`/`@Monitor` 等 V2 装饰器;`@ComponentV2` 内禁用 `@State`/`@Prop`/`@Link`/`@Watch` 等 V1 装饰器;新组件默认 V2 体系。(UI-001、UI-003) +5. **禁止编造组件签名**:组件属性方法、事件回调、枚举成员必须与官方 API 参考一致(如 `.backgroundColor()` 不是 `.bgColor()`,`NavigationTitleMode.Mini` 不是 `.Min`)。(UI-006) +6. **禁止 router 与 Navigation 混用**:新页面一律 Navigation + NavDestination + NavPathStack;目标页必须在系统路由表注册并配置 navDestination 映射。(NAV-001 ~ NAV-003) +7. **网络三强制**:必须声明 `ohos.permission.INTERNET`;请求生命周期 `createHttp` → `request` → `destroy`(成功失败都销毁);响应业务数据从 `result` 解析。(NET-001 ~ NET-003) +8. **禁止契约漂移**:响应模型字段名必须与后端 JSON 键名严格匹配(含大小写);分页取 `data.rows` + `data.total`;可空层级逐层判空。(NET-005、NET-006) +9. **生产代码禁止 console.log**:统一 HiLog,自定义 domain/tag;敏感信息禁止明文 `%{public}` 输出。(LOG-001、LOG-002、LOG-005) +10. **大数据量禁止 ForEach 全量渲染**:千条级以上或持续增长的数据源必须 LazyForEach + IDataSource(变更走 DataChangeListener 通知)。(PERF-002、PERF-003) + +> 踩坑经验必须按 `rules/00-usage-and-update.md` USE-005 四要素格式(问题背景/根因分析/修复模式/条目回链)版本化沉淀到对应专题文档。 + +--- + +## 二、规则文档索引(rules/) + +| 文档 | 前缀 | 主题摘要 | +|---|---|---| +| `rules/00-usage-and-update.md` | USE | 元规则:按需加载流程、五要素骨架、编号体系、踩坑沉淀流程、索引同步契约、documentId 标注规范 | +| `rules/01-arkts-grammar.md` | ARK | ArkTS 语法约束:arkts-no-* 强禁规则映射(any/解构/结构化类型/动态特性等)与 TS→ArkTS 改写模式 | +| `rules/02-arkui-and-state-management.md` | UI | ArkUI 组件与状态管理:V1/V2 装饰器对照、混用禁令、$$ 与 !!、@Monitor 迁移、组件签名规范 | +| `rules/03-architecture-and-project-structure.md` | ARCH | 分层架构与工程结构:三层架构(产品定制/基础特性/公共能力)、HAR/HSP 选型、目录组织、单 Entry 渐进式采用、模型单一来源 | +| `rules/04-navigation.md` | NAV | Navigation 路由:统一路由体系、router 混用禁令、路由表注册与白屏排查、NavDestination 生命周期、V2 传参 | +| `rules/05-network-and-backend.md` | NET | 网络与企业级后端对接:INTERNET 权限、请求封装基线、data.result 解析、统一错误处理、契约一致、token 鉴权、TaskPool 决策、RCP | +| `rules/06-data-persistence.md` | DATA | 数据持久化:四方案选型决策树(PersistentStorage/Preferences/KV-Store/RDB)、flush 落盘、batchInsert 批量写入、JSON 容错 | +| `rules/07-performance.md` | PERF | 性能优化:ForEach/LazyForEach 选型、IDataSource 规范、cachedCount、if 与 Visibility.None、@Reusable 组件复用、keyGenerator | +| `rules/08-logging-and-error-handling.md` | LOG | 日志与错误处理:HiLog 强制、console 生产禁令、五级日志标准、domain/TAG 规范、隐私保护、批量操作日志模式 | +| `rules/09-api-verification.md` | APIV | API 存在性验证:search→read 两步工作流、三类验证对象、降级策略、编造模式清单、导入路径细则 | +| `rules/10-prohibited-and-checklist.md` | GEN | 禁止事项汇总与开发总检查清单(按主题引用各文档规则编号) | + +--- + +## 三、强制工作流 + +### 工作流 1:API 验证(调用任何 @ohos/@kit API 前) + +```text +① devecocli docs search <关键词> → 定位 documentId 候选 +② devecocli docs read → 核对模块名/方法名/参数签名/枚举/导入路径/起始版本 +③ 全部确认 → 书写代码;无法确认 → 换关键词重查 → 仍无结果 → 禁用该 API 并向用户明示 +``` + +详见 `rules/09-api-verification.md`。 + +### 工作流 2:规则按需加载(会话开始时) + +```text +① 读取本文件(AGENTS.md)红线与索引 +② 按任务主题加载对应专题文档: + - 写任何 ArkTS 代码 → rules/01(必读) + - 调用任何 @ohos/@kit API → rules/09(必读) + - 组件/状态 → rules/02;路由 → rules/04;网络 → rules/05;存储 → rules/06;列表渲染 → rules/07;日志 → rules/08 +③ 提交前用 rules/10 总检查清单自查 +``` + +禁止一次性加载全部 11 份文档(上下文膨胀),禁止跳过索引凭猜测定位。 + +### 工作流 3:踩坑沉淀(发现新坑时) + +按 `rules/00-usage-and-update.md` USE-005:更新记录追加 `vX.Y (YYYY-MM-DD)` 条目(四要素:问题背景/根因分析/修复模式 ✅❌ 对照/涉及条目回链)→ 新增或修订规则条目 → 同步禁止事项与检查清单。 + +--- + +## 四、会话上下文预算(DevEco Code / GLM-5.3) + +DevEco Code 的 GLM-5.3 模型单次会话上下文上限为 **170K**,超出后早期内容会被压缩丢弃,已加载的规则与关键决策可能失真。长会话必须主动控制上下文占用: + +1. **按需加载**:规则文档严格按第二节索引按任务主题加载,禁止一次性加载全部 11 份(见工作流 2);大文件先用关键词检索定位,再分段读取。 +2. **及时收敛**:探索性检索与长文档验证完成后,主会话只保留结论与关键引用,不复述原文。 +3. **启用子代理**:会话接近上限或任务量较大时,将检索、API 验证、批量改造等可独立执行的工作委派给子代理(Task/subagent)会话,主会话仅接收结论摘要。 + +--- + +*规则体系基于 HarmonyOS API 12+;官方依据一律使用 devecocli docs documentId 标注,详见 `rules/00-usage-and-update.md`。* diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4067d2d --- /dev/null +++ b/LICENSE @@ -0,0 +1,235 @@ +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + + Preamble + +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. + +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. + +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. + +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. + +The precise terms and conditions for copying, distribution and modification follow. + + TERMS AND CONDITIONS + +0. Definitions. + +"This License" refers to version 3 of the GNU Affero General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based on the Program. + +To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. + +A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. + +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. + +A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. + +14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + HarmonyTemplate + Copyright (C) 2026 ali + + This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . diff --git a/README.md b/README.md new file mode 100644 index 0000000..36a2c3b --- /dev/null +++ b/README.md @@ -0,0 +1,55 @@ +# HarmonyTemplate + +HarmonyOS ArkTS 项目模板仓库。内置一套面向 AI 编码助手与开发者的开发规则体系,克隆本仓库即可让 AI 助手在生成鸿蒙代码时自动遵循官方规范约束。 + +--- + +## 开发规则体系 + +### 入口:AGENTS.md + +仓库根目录的 [AGENTS.md](AGENTS.md) 是规则体系入口,包含三部分: + +- **核心红线**:10 条一行式强禁令(禁编造 API、禁 any、禁 V1/V2 状态混用、禁 router 混用等),每条对齐专题文档规则编号; +- **规则文档索引**:`rules/` 全部 11 份文档的路径、编号前缀与主题摘要; +- **强制工作流**:API 验证(search→read 两步)、规则按需加载、踩坑沉淀三个流程。 + +### rules/ 目录结构 + +`rules/` 下 11 份编号专题文档,文件名 `NN-topic.md`(两位数字保证加载顺序),每份包含五要素:更新记录、规范条目(含官方依据 documentId)、正误对照(✅/❌)、禁止事项、检查清单。 + +| 文档 | 前缀 | 主题 | +|---|---|---| +| `rules/00-usage-and-update.md` | USE | 元规则:加载流程、文档骨架、编号体系、踩坑沉淀流程 | +| `rules/01-arkts-grammar.md` | ARK | ArkTS 语法约束(arkts-no-* 强禁规则映射) | +| `rules/02-arkui-and-state-management.md` | UI | ArkUI 组件与状态管理(V1/V2 对照与混用禁令) | +| `rules/03-architecture-and-project-structure.md` | ARCH | 分层架构与工程结构(三层架构/HAR/HSP 选型) | +| `rules/04-navigation.md` | NAV | Navigation 路由(统一路由体系与白屏排查) | +| `rules/05-network-and-backend.md` | NET | 网络与企业级后端对接(契约一致规范) | +| `rules/06-data-persistence.md` | DATA | 数据持久化(四方案选型决策树) | +| `rules/07-performance.md` | PERF | 性能优化(LazyForEach/IDataSource/组件复用) | +| `rules/08-logging-and-error-handling.md` | LOG | 日志与错误处理(HiLog 强制与五级标准) | +| `rules/09-api-verification.md` | APIV | API 存在性验证(search→read 两步工作流) | +| `rules/10-prohibited-and-checklist.md` | GEN | 禁止事项汇总与开发总检查清单 | + +### AI 编码助手自动加载 + +支持 AGENTS.md 约定的 AI 编码助手(DevEco Code、Claude Code 等)在会话启动时会自动读取根目录 `AGENTS.md`,获得核心红线与规则索引,并按任务主题按需加载对应专题文档,无需人工干预。 + +### 人工加载指引 + +若所用 AI 助手不支持 AGENTS.md 自动发现约定,请在会话开始时向其发送: + +```text +请先阅读仓库根目录的 AGENTS.md,遵守其中核心红线,并按任务主题加载 rules/ 目录下对应专题文档后再生成代码。 +``` + +人类开发者可直接按主题检索 `rules/` 目录:文件名编号(00~10)对应主题域,全局规则编号(如 `NET-005`)支持全文检索直达;code review 前建议通读 `rules/10-prohibited-and-checklist.md` 总检查清单。 + +### 规则更新与踩坑沉淀 + +开发中发现新坑(框架缺陷、API 误用、契约陷阱等)时,按 `rules/00-usage-and-update.md` USE-005 流程沉淀:在对应专题文档更新记录区追加四要素条目(问题背景/根因分析/修复模式/条目回链),版本号递增不跳号;新增或更名 `rules/` 文档时同步更新 `AGENTS.md` 索引。 + +--- + +*规则体系基于 HarmonyOS API 12+;全部官方依据使用 devecocli docs documentId 标注,可通过 `devecocli docs read ` 复核。* diff --git a/rules/00-usage-and-update.md b/rules/00-usage-and-update.md new file mode 100644 index 0000000..287176c --- /dev/null +++ b/rules/00-usage-and-update.md @@ -0,0 +1,199 @@ +# 00 - 规则使用与更新机制(usage-and-update) + +> **规则编号前缀**:USE +> **本文档定位**:整个规则体系的元规则(meta-rules)——定义规则如何被使用、如何组织、如何演进。其余 10 份专题文档(01~10)的结构均由本文档约束。 + +--- + +## 一、更新记录 + +| 版本 | 日期 | 摘要 | +|---|---|---| +| v1.1 | 2026-09-08 | 追加完整示例更新记录:以"AI 编造 @ohos.net.http.postJson"踩坑演示 USE-005 四要素沉淀流程(示例见 USE-005 节末) | +| v1.0 | 2026-09-08 | 初始版本:定义规则体系使用说明、五要素文档骨架、规则编号体系、版本化踩坑沉淀流程、AGENTS.md 索引同步契约与官方依据标注规范 | + +--- + +## 二、规范条目 + +### USE-001 AI 编码助手按需加载流程(MUST) + +**描述**:AI 编码助手(DevEco Code、Claude Code 等支持 AGENTS.md 约定的工具)在会话开始时必须先读取仓库根目录 `AGENTS.md`,获取核心红线与规则索引;随后**按当前任务主题**加载 `rules/` 下对应专题文档。禁止跳过索引凭猜测定位文档,禁止在单个简单任务中一次性加载全部 11 份专题文档(按需加载,控制上下文体积)。 + +**加载路径示例**: + +| 任务主题 | 应加载文档 | +|---|---| +| 编写任何 ArkTS 代码 | `rules/01-arkts-grammar.md`(必读) | +| 编写组件 / 状态管理 | `rules/02-arkui-and-state-management.md` | +| 页面路由 / 跳转传参 | `rules/04-navigation.md` | +| 网络请求 / 后端对接 | `rules/05-network-and-backend.md` | +| 本地存储 | `rules/06-data-persistence.md` | +| 列表 / 长列表渲染 | `rules/07-performance.md` | +| 调用任何 @ohos/@kit API 前 | `rules/09-api-verification.md`(必读) | +| 不确定主题 | 以 AGENTS.md 索引摘要为准逐份匹配 | + +### USE-002 人类开发者检索指引(SHOULD) + +**描述**:人类开发者 in code review 或开发遇阻时,通过文件名编号(00~10)与 `AGENTS.md` 索引定位规则,目标定位耗时 < 30 秒。任何规则条目都有全局唯一编号(如 `NET-005`),可在仓库全文检索直达;`rules/10-prohibited-and-checklist.md` 汇总了全部禁止事项与总检查清单,适合 review 前通读。 + +### USE-003 五要素文档骨架(MUST) + +**描述**:`rules/` 下每份专题文档必须**依次**包含以下五个章节,缺一不可(对应 spec FR-003): + +| 序 | 章节 | 内容要求 | +|---|---|---| +| 1 | 更新记录 | 版本条目列表,格式见 USE-005 | +| 2 | 规范条目 | 每条规则含:规则编号 + 级别词(MUST / MUST NOT / SHOULD)+ 描述 + 官方依据(documentId)+ 适用版本 + 必要的内嵌 ✅/❌ 对照 | +| 3 | 正误对照 | 本主题高频错误的 ✅ 正确 / ❌ 错误 ArkTS 代码对照汇总 | +| 4 | 禁止事项 | 本主题 ❌ 条目集中列表,须回链规则编号 | +| 5 | 检查清单 | `- [ ]` 可勾选条目,供开发自查与 code review 逐项核对,须回链规则编号 | + +### USE-004 规则编号体系(MUST) + +**描述**:每条规则拥有全局唯一编号 = 文档前缀 + 三位序号(如 `ARK-001`、`NET-003`)。前缀与文档一一对应且固定不变;禁止跨文档借用前缀,禁止复用已存在的编号。新条目在本文档内按三位序号递增追加。 + +| 文档 | 前缀 | 主题 | +|---|---|---| +| `rules/00-usage-and-update.md` | USE | 规则使用与更新机制 | +| `rules/01-arkts-grammar.md` | ARK | ArkTS 语法约束 | +| `rules/02-arkui-and-state-management.md` | UI | ArkUI 组件与状态管理 | +| `rules/03-architecture-and-project-structure.md` | ARCH | 分层架构与工程结构 | +| `rules/04-navigation.md` | NAV | Navigation 路由 | +| `rules/05-network-and-backend.md` | NET | 网络与企业级后端对接 | +| `rules/06-data-persistence.md` | DATA | 数据持久化 | +| `rules/07-performance.md` | PERF | 性能优化 | +| `rules/08-logging-and-error-handling.md` | LOG | 日志与错误处理 | +| `rules/09-api-verification.md` | APIV | API 存在性验证 | +| `rules/10-prohibited-and-checklist.md` | GEN | 禁止事项汇总与总检查清单 | + +### USE-005 版本化踩坑沉淀流程(MUST) + +**描述**:开发过程中发现新的坑(框架缺陷、API 误用、契约陷阱、编译期怪异报错)时,必须按以下流程将经验沉淀到**对应主题**的专题文档,保持规则体系持续演进(对应 spec FR-007): + +1. 在目标文档「一、更新记录」表**顶部**追加一行:`vX.Y (YYYY-MM-DD) - 摘要`。版本号在文档内单调递增:X(主版本)= 结构性变更(增删章节/骨架调整),Y(次版本)= 新增条目或既有条目修订;禁止跳号。 +2. 在「二、规范条目」新增规则条目,或修订既有条目(修订时在条目内注明生效版本)。 +3. 追加的更新记录必须**四要素齐全**:问题背景 / 根因分析 / 修复模式(✅/❌ 对照)/ 涉及规则条目回链。 +4. 同步检查「四、禁止事项」与「五、检查清单」是否需要补充。 + +**更新记录格式模板**: + +```markdown +### vX.Y (YYYY-MM-DD) - 一句话摘要 + +- **问题背景**:什么场景下出现了什么错误/异常现象 +- **根因分析**:技术层面的根本原因(为什么会出现) +- **修复模式**:❌ 错误写法 → ✅ 正确写法(代码或配置对照) +- **涉及条目**:回链本规则编号(如 NAV-003);跨文档影响时同时回链对方编号 +``` + +**完整示例**(v1.1 追加,演示踩坑沉淀流程闭环): + +### v1.1 (2026-09-08) - AI 编造 http.postJson 便捷方法导致运行时报错 + +- **问题背景**:订单列表页对接后端 POST 接口,AI 编码助手按其他平台 HTTP 库习惯生成了 `http.postJson(url, body)` 调用。代码编译通过,真机运行时点击"提交订单"抛出运行时异常(`postJson` 不是可调用方法),提交功能不可用。 +- **根因分析**:`@ohos.net.http` 模块**不存在** `postJson` 便捷方法,真实 API 为 `createHttp()` 创建实例 + `request(url, options)` 发请求 + `destroy()` 销毁。代码生成时跳过了 `rules/09-api-verification.md` 的两步验证流程(APIV-001),把其他平台习惯直接映射为鸿蒙 API 名——命中编造模式清单第 1、2 条(APIV-005)。此类错误的典型特征是**编译期不报错、运行时才崩**。 +- **修复模式**: + +❌ 错误 + +```ts +import { http } from '@kit.NetworkKit'; +let resp = await http.postJson('https://api.example.com/orders', body); // postJson 不存在 +``` + +✅ 正确 + +```ts +import { http } from '@kit.NetworkKit'; +let client = http.createHttp(); +try { + let resp = await client.request('https://api.example.com/orders', { + method: http.RequestMethod.POST, + header: { 'Content-Type': 'application/json; charset=UTF-8' }, + extraData: JSON.stringify(body) + }); + // 处理 resp(业务数据在 resp.result) +} finally { + client.destroy(); // 成功/失败都销毁 +} +``` + +- **涉及条目**:APIV-001(两步验证流程)、APIV-004(禁止编造 API)、APIV-005(编造模式清单自查);NET-002(请求生命周期 createHttp→request→destroy)、NET-003(业务数据从 result 解析) +- **复核方式**:`devecocli docs read "API参考/网络/Network_Kit_网络服务/ArkTS_API/ohos_net_http_数据请求_/js-apis-http"` 可确认 postJson 不存在、request 为真实签名 + +### USE-006 AGENTS.md 索引同步契约(MUST) + +**描述**:新增、更名或删除 `rules/` 文档时,必须在同一次变更中同步更新 `AGENTS.md` 的规则索引(相对路径 + 一句话主题摘要 + 编号前缀,三项齐备)。索引使用相对路径(`rules/NN-topic.md`),不使用绝对路径。 + +**松耦合约束**:`rules/` 各文档之间不相互依赖、可独立加载;即使 `AGENTS.md` 被实例化项目重写,`rules/` 仍须独立可用(覆盖 spec Edge Case)。 + +**文件命名契约**:`NN-topic.md`——NN 为 00~10 两位数字前缀(保证加载顺序),topic 仅用小写字母与连字符(kebab-case),不含中文、空格与其他特殊字符。 + +### USE-007 官方依据标注规范(MUST) + +**描述**:规则条目标注官方依据时,必须使用 devecocli docs 本地文档库的 **documentId 全路径**(如 `FAQ/网络/网络_Network/http网络连接中的通用知识/faqs-network-6`),任何人都可通过 `devecocli docs read ` 复核。**严禁构造任何 web URL**。`AGENTS.md` 核心红线为保持精简可省略依据标注,但其对应的专题文档中必须存在带依据的完整条目。 + +**适用版本**:规则内容以 HarmonyOS API 12+ 为基准,涉及版本敏感行为时在条目内显式标注适用版本范围;官方 API 废弃时按 USE-005 流程更新条目,避免规则过时误导(覆盖 spec Edge Case)。 + +✅ **正确** + +```markdown +- **官方依据**:`FAQ/UI框架/UI界面/状态管理V1和V2适用场景介绍/faqs-arkui-885` +``` + +❌ **错误** + +```markdown +- **官方依据**:<任意网页链接>(禁止构造 URL;正确方式为 documentId 全路径) +- **官方依据**:官方文档说了…… (无 documentId,无法复核) +``` + +--- + +## 三、正误对照 + +### 对照 1:更新记录四要素(USE-005) + +✅ **正确** + +> ### v1.2 (2026-10-12) - 修复 Navigation 跳转白屏的排查条目 +> - **问题背景**:`pushPathByName` 跳转后目标页白屏,无报错日志 +> - **根因分析**:目标页未在系统路由表注册,且 Navigation 未设置 `navDestination` 属性 +> - **修复模式**:❌ 直接调用未注册的跳转 → ✅ 先在路由表注册 NavDestination 页面并为 Navigation 配置 `navDestination` +> - **涉及条目**:NAV-003 + +❌ **错误** + +> ### v1.2 (2026-10-12) - 更新了路由文档 +> (仅有一句摘要,四要素缺失,无法追溯来龙去脉) + +### 对照 2:documentId 标注(USE-007) + +✅ **正确**:依据为 documentId 全路径,可 `devecocli docs read` 复核。 + +❌ **错误**:凭记忆构造网页链接,或只写"参考官方文档"而无可检索标识。 + +--- + +## 四、禁止事项 + +- ❌ 禁止在规则文档中构造任何 web URL 作为官方依据(USE-007) +- ❌ 禁止新增 / 更名 / 删除 `rules/` 文档后遗漏同步 `AGENTS.md` 索引(USE-006) +- ❌ 禁止更新记录只记现象不记根因——四要素缺一不可(USE-005) +- ❌ 禁止跨文档借用规则编号前缀,禁止复用已存在编号(USE-004) +- ❌ 禁止 AI 编码助手跳过 `AGENTS.md` 索引、或在简单任务中一次性加载全部专题文档(USE-001) +- ❌ 禁止任何专题文档缺失五要素章节之一(USE-003) +- ❌ 禁止版本号跳号或并行分支各自递增(USE-005) + +--- + +## 五、检查清单 + +- [ ] AI 会话已先读 `AGENTS.md` 索引,再按任务主题加载专题文档(USE-001) +- [ ] 引用的每个规则编号在对应专题文档中真实存在(USE-004) +- [ ] 新增规则条目已含编号 / 级别词 / 描述 / 官方依据 / 适用版本(USE-003) +- [ ] 官方依据均为 documentId 全路径,可经 `devecocli docs read` 复核,全文无任何 web URL(USE-007) +- [ ] 更新记录四要素齐全,版本号在文档内递增且无跳号(USE-005) +- [ ] `rules/` 目录变更已同步 `AGENTS.md` 索引(USE-006) +- [ ] 专题文档五要素章节齐备且顺序正确(USE-003) diff --git a/rules/01-arkts-grammar.md b/rules/01-arkts-grammar.md new file mode 100644 index 0000000..4486db3 --- /dev/null +++ b/rules/01-arkts-grammar.md @@ -0,0 +1,452 @@ +# 01 - ArkTS 语法约束(arkts-grammar) + +> **规则编号前缀**:ARK +> **适用版本**:API 10+(ArkTS 强化静态检查基准;规则文档内示例以 API 12+ 工程为基准) +> **核心官方依据**:`开发指南/学习ArkTS语言/从TypeScript到ArkTS的适配指导/从TypeScript到ArkTS的适配规则/typescript-to-arkts-migration-guide`(下文简称"适配规则",全部 arkts-* 规则名与强制级别均出自该文档) + +--- + +## 一、更新记录 + +| 版本 | 日期 | 摘要 | +|---|---|---| +| v1.0 | 2026-09-08 | 初始版本:arkts-no-* 强制规则映射(含 error/warning 级别)、TS→ArkTS 高频改写模式、@ohos/@kit 导入规范 | + +--- + +## 二、规范条目 + +> 强制级别说明:**错误(error)**= 编译失败,必须改写;**警告(warning)**= 编译告警,同样必须修复(本规则体系按零告警标准执行)。 + +### ARK-001 禁用 any 与 unknown 类型(MUST NOT) + +- **级别**:错误(错误码 10605008,规则 `arkts-no-any-unknown`) +- **描述**:ArkTS 不支持 `any` 与 `unknown`,含 `as unknown as T` 双重断言。用具体类型、`Object` 或联合类型替代。 +- **官方依据**:适配规则(typescript-to-arkts-migration-guide) +- **适用版本**:API 10+ + +✅ 正确 + +```ts +let valueN: number = 42; +let valueS: string | undefined = undefined; // 可空用联合类型窄化 +``` + +❌ 错误 + +```ts +let value: any = 42; +let config: unknown = JSON.parse(text); +let user = JSON.parse(text) as unknown as UserModel; // 双重断言同样禁止 +``` + +### ARK-002 对象字面量必须显式标注类型(MUST) + +- **级别**:错误(错误码 10605038,规则 `arkts-no-untyped-obj-literals`) +- **描述**:任何对象字面量都必须处于明确的类型上下文中(声明注解、函数参数类型、返回类型等);外层类型不会传播进嵌套字面量。且不可用字面量初始化含方法、含自定义带参构造函数、含 readonly 字段的类。 +- **官方依据**:适配规则(typescript-to-arkts-migration-guide) +- **适用版本**:API 10+ + +✅ 正确 + +```ts +interface RequestOptions { + url: string + timeout: number +} + +function sendRequest(options: RequestOptions): void { /* ... */ } + +let options: RequestOptions = { url: 'https://example.com', timeout: 30 }; // 有类型上下文 +sendRequest({ url: 'https://example.com', timeout: 30 }); // 形参提供类型上下文 +``` + +❌ 错误 + +```ts +let cfg = { timeout: 30 }; // 无类型注解,编译失败 +let list: Object[] = [{ id: 1 }]; // Object 类型上下文,字面量不支持 +``` + +### ARK-003 禁用对象字面量作为类型声明(MUST NOT) + +- **级别**:错误(错误码 10605040,规则 `arkts-no-obj-literals-as-types`) +- **描述**:不支持 `{ x: number, y: number }` 形式的内联对象类型;用 `class` 或具名 `interface` 声明类型。 +- **官方依据**:适配规则(typescript-to-arkts-migration-guide) +- **适用版本**:API 10+ + +✅ 正确 + +```ts +interface Point { x: number; y: number } +let p: Point = { x: 1, y: 2 }; +``` + +❌ 错误 + +```ts +let p: { x: number, y: number } = { x: 1, y: 2 }; +type S = Set<{ x: number, y: number }>; +``` + +### ARK-004 禁用一切解构语法(MUST NOT) + +- **级别**:错误(`arkts-no-destruct-decls` 10605074 / `arkts-no-destruct-assignment` 10605069 / `arkts-no-destruct-params` 10605091,均为错误) +- **描述**:不支持解构变量声明、解构赋值与函数参数解构。逐个成员访问赋值替代。 +- **官方依据**:适配规则(typescript-to-arkts-migration-guide)、`FAQ/ArkTS语言/方舟编程语言_ArkTS/ArkTS是否支持解构/faqs-arkts-80` +- **适用版本**:API 10+ + +✅ 正确 + +```ts +let zp = getZeroPoint(); +let x = zp.x; +let y = zp.y; +``` + +❌ 错误 + +```ts +let { x, y } = getZeroPoint(); // 解构声明 +[x, y] = [y, x]; // 解构赋值 +function draw({ width, height }: Size) {} // 参数解构 +``` + +### ARK-005 禁用结构化类型(MUST NOT) + +- **级别**:错误(错误码 10605030,规则 `arkts-no-structural-typing`) +- **描述**:ArkTS 编译器不比较两个类型的 public API 是否等价;类型兼容只能通过 `extends`(类继承)或 `implements`(接口实现)显式建立。 +- **官方依据**:适配规则(typescript-to-arkts-migration-guide) +- **适用版本**:API 10+ + +✅ 正确 + +```ts +interface Comparable { getId(): number } + +class OrderA implements Comparable { getId(): number { return 1 } } +class OrderB implements Comparable { getId(): number { return 2 } } + +function log(c: Comparable): void { /* ... */ } +log(new OrderA()); // 显式 implements 建立类型关系 +log(new OrderB()); +``` + +❌ 错误 + +```ts +class OrderA { getId(): number { return 1 } } +class OrderB { getId(): number { return 2 } } // API 等价也不兼容 + +let a: OrderA = new OrderB(); // 编译失败:无继承/实现关系 +``` + +### ARK-006 禁用函数表达式、嵌套函数与生成器(MUST NOT) + +- **级别**:错误(`arkts-no-func-expressions` 10605046 / `arkts-no-nested-funcs` 10605092 / `arkts-no-generators` 10605094) +- **描述**:函数不能作为 `function () {}` 表达式赋值;函数体内不能再声明函数;不支持 `function*` 生成器。统一用箭头函数替代。 +- **官方依据**:适配规则(typescript-to-arkts-migration-guide) +- **适用版本**:API 10+ + +✅ 正确 + +```ts +let onClick = (event: ClickEvent): void => { /* ... */ }; +``` + +❌ 错误 + +```ts +let onClick = function (event) { /* ... */ }; // 函数表达式 +function outer(): void { + function inner(): void {} // 嵌套函数声明 +} +function* counter(): Generator { yield 1 } // 生成器 +``` + +### ARK-007 禁用索引签名与索引访问字段(MUST NOT) + +- **级别**:错误(`arkts-no-indexed-signatures` 10605017 / `arkts-no-props-by-index` 10605029) +- **描述**:不支持 `[key: string]: T` 索引签名,改用 `Record` 或数组;字段访问用点操作符 `obj.field`,不支持 `obj['field']`(TypedArray 元素访问除外)。 +- **官方依据**:适配规则(typescript-to-arkts-migration-guide) +- **适用版本**:API 10+ + +✅ 正确 + +```ts +let scores: Record = { 'alice': 95 }; +let aliceScore = scores['alice']; // Record 支持索引访问 +let person = new Person(); +let name = person.name; // 类字段用点访问 +``` + +❌ 错误 + +```ts +interface StringArray { [index: number]: string } // 索引签名 +let n = person['name']; // 非记录类型索引访问 +``` + +### ARK-008 禁用交叉类型;utility 类型仅限四种(MUST NOT) + +- **级别**:错误(`arkts-no-intersection-types` 10605019 / `arkts-no-utility-types` 10605138;`arkts-no-mapped-types` 10605083、`arkts-no-conditional-types` 10605022 同禁) +- **描述**:不支持 `A & B` 交叉类型(用接口继承替代);utility 类型仅支持 `Partial`、`Required`、`Readonly`、`Record`;映射类型与条件类型不支持。 +- **官方依据**:适配规则(typescript-to-arkts-migration-guide) +- **适用版本**:API 10+ + +✅ 正确 + +```ts +interface Identity { id: number } +interface Contact { email: string } +interface Employee extends Identity, Contact {} // 接口多继承 +``` + +❌ 错误 + +```ts +type Employee = Identity & Contact; // 交叉类型 +type Flags = { [P in keyof T]: boolean }; // 映射类型 +type NoNull = T extends null ? never : T; // 条件类型 +type Picked = Pick; // 不支持的 utility 类型 +``` + +### ARK-009 泛型实参与返回类型显式标注(MUST) + +- **级别**:错误(`arkts-no-inferred-generic-params` 10605034 / `arkts-no-implicit-return-types` 10605090) +- **描述**:无法从实参推断的泛型必须显式书写类型实参;函数返回类型涉及递归/相互调用时必须显式标注。`async` 函数必须标注 `Promise`(无返回值写 `Promise`)。 +- **官方依据**:适配规则(typescript-to-arkts-migration-guide) +- **适用版本**:API 10+ + +✅ 正确 + +```ts +function greet(): T { return 'Hello' as T } +let z = greet(); // 显式泛型实参 + +async function loadUser(id: number): Promise { + return queryUser(id); +} +``` + +❌ 错误 + +```ts +let z = greet(); // 泛型仅依赖返回类型推断 +async function loadUser(id: number) { /* ... */ } // 缺少返回类型标注 +``` + +### ARK-010 类型转换仅 as;throw 仅 Error;catch 不标类型(MUST) + +- **级别**:错误(`arkts-as-casts` 10605053 / `arkts-limited-throw` 10605087 / `arkts-no-types-in-catch` 10605079) +- **描述**:类型转换只允许 `as T`(不支持 `value`);只能抛出 `Error` 及其子类;`catch (e)` 形参不得标注类型,系统 API 错误按 `BusinessError`(`@kit.BasicServicesKit`)处理。 +- **官方依据**:适配规则(typescript-to-arkts-migration-guide)、`FAQ/ArkTS语言/方舟编程语言_ArkTS/ArkTS里有哪些转换数据类型的方法/faqs-arkts-65` +- **适用版本**:API 10+ + +✅ 正确 + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + throw new Error('invalid state'); +} catch (e) { + let err = e as BusinessError; // catch 内再 as 转换 + console.error(`code: ${err.code}`); +} +``` + +❌ 错误 + +```ts +let c = createShape(); // <> 转换语法 +throw 4; // 抛出非 Error +try { } catch (e: unknown) { } // catch 标注类型 +``` + +### ARK-011 禁用动态特性:delete / in / for..in / with / var / #私有字段 / 构造器参数属性 / 静态 this / @ts-ignore(MUST NOT) + +- **级别**:错误(`arkts-no-delete` 10605059 / `arkts-no-in` 10605066 / `arkts-no-for-in` 10605080 / `arkts-no-with` 10605084 / `arkts-no-var` 10605005 / `arkts-no-private-identifiers` 10605003 / `arkts-no-ctor-prop-decls` 10605012 / `arkts-no-standalone-this` 10605093 / `arkts-strict-typing-required` 10605146) +- **描述**:对象布局编译期确定、运行时不可变——上述动态特性全部禁止。可空字段置 `null`/`undefined` 替代 delete;属性存在性用 `instanceof` 判断;字段私有化用 `private` 关键字;类型检查不允许被 `@ts-ignore` / `@ts-nocheck` 关闭。 +- **官方依据**:适配规则(typescript-to-arkts-migration-guide) +- **适用版本**:API 10+ + +✅ 正确 + +```ts +class Cache { + private items: Map = new Map(); + static maxSize: number = 100; + static defaultSize(): number { + return Cache.maxSize; // 静态方法用类名访问 + } +} +``` + +❌ 错误 + +```ts +var count = 0; // var +class C { #secret = 1 } // # 私有字段 +class D { constructor(private name: string) {} } // 构造器参数属性 +delete obj.field; // delete +if ('field' in obj) {} // in +for (let k in obj) {} // for..in +// @ts-ignore // 关闭类型检查 +``` + +### ARK-012 模块导入规范:置顶、禁 require、@ohos/@kit 须验证(MUST) + +- **级别**:错误(`arkts-no-misplaced-imports` 10605150 / `arkts-no-require` 10605121 / `arkts-no-export-assignment` 10605126 / `arkts-no-ts-deps` 10605147) +- **描述**:除动态 import 外,全部 import 语句必须置于文件顶部其他语句之前;禁止 `require` 与 `import x = require(...)`、`export =` 语法;`.ts`/`.js` 文件禁止 import `.ets` 文件。**所有 `@ohos.*` / `@kit.*` 导入在使用前必须按 `rules/09-api-verification.md` 验证存在性与导入路径(APIV-001)**。 +- **官方依据**:适配规则(typescript-to-arkts-migration-guide) +- **适用版本**:API 10+ + +✅ 正确 + +```ts +import { http } from '@kit.NetworkKit'; // Kit 导入(已验证) +import { UserModel } from '../model/UserModel'; // 相对路径导入 +import('module2').then(() => {}).catch(() => {}); // 动态 import 允许不在顶部 + +class Session { /* ... */ } +``` + +❌ 错误 + +```ts +class Session { /* ... */ } +import { http } from '@kit.NetworkKit'; // import 未置顶 + +import m = require('mod'); // require 赋值 +export = Point; // export = 语法 +import { player } from '@kit.MediaKit'; // 未验证的编造命名空间(player 不存在) +``` + +--- + +## 三、正误对照 + +### 对照 1:无类型对象字面量初始化(ARK-002) + +❌ 错误 + +```ts +let request = { method: 'GET', url: '/api/users' }; +``` + +✅ 正确 + +```ts +interface HttpRequest { + method: string + url: string +} + +let request: HttpRequest = { method: 'GET', url: '/api/users' }; +``` + +### 对照 2:解构改写(ARK-004) + +❌ 错误 + +```ts +const { rows, total } = pageResult; +``` + +✅ 正确 + +```ts +const rows = pageResult.rows; +const total = pageResult.total; +``` + +### 对照 3:函数表达式改箭头函数(ARK-006) + +❌ 错误 + +```ts +button.setOnClickListener(function () { submit(); }); +``` + +✅ 正确 + +```ts +button.setOnClickListener(() => { submit(); }); +``` + +### 对照 4:索引签名改 Record(ARK-007) + +❌ 错误 + +```ts +interface Dict { [key: string]: string } +``` + +✅ 正确 + +```ts +type Dict = Record; +``` + +### 对照 5:交叉类型改接口继承(ARK-008) + +❌ 错误 + +```ts +type ViewModel = BaseModel & Refreshable; +``` + +✅ 正确 + +```ts +interface ViewModel extends BaseModel, Refreshable {} +``` + +### 对照 6:可空状态初始化(含 null 安全) + +❌ 错误 + +```ts +let user: UserModel; // 无初始化直接使用报错 +let name = user!.name; // 非空断言 +``` + +✅ 正确 + +```ts +let user: UserModel | undefined = undefined; +let name = user?.name ?? ''; // ?. 窄化 + ?? 兜底 +``` + +--- + +## 四、禁止事项 + +- ❌ 禁止使用 `any` / `unknown` 及 `as unknown as T` 双重断言(ARK-001) +- ❌ 禁止使用未标注类型的对象字面量与内联对象字面量类型(ARK-002、ARK-003) +- ❌ 禁止使用任何形式的解构(声明 / 赋值 / 参数)(ARK-004) +- ❌ 禁止依赖结构化类型兼容("API 等价即可互赋")(ARK-005) +- ❌ 禁止函数表达式、函数内声明函数、生成器(ARK-006) +- ❌ 禁止索引签名与非 Record 类型的索引访问(ARK-007) +- ❌ 禁止交叉类型、映射类型、条件类型及四种之外的 utility 类型(ARK-008) +- ❌ 禁止省略无法推断的泛型实参与关键返回类型(ARK-009) +- ❌ 禁止 `` 转换语法、抛出非 Error、catch 标类型(ARK-010) +- ❌ 禁止 delete / in / for..in / with / var / #字段 / 构造器参数属性 / 静态方法 this / @ts-ignore(ARK-011) +- ❌ 禁止 import 不置顶、require / export = 语法、未经验证的 @ohos/@kit 导入路径(ARK-012) + +--- + +## 五、检查清单 + +- [ ] 全文无 `any` / `unknown` / 双重断言(ARK-001) +- [ ] 每个对象字面量都有明确类型上下文,无内联对象类型(ARK-002、ARK-003) +- [ ] 无解构语法(ARK-004) +- [ ] 类型兼容均经 extends / implements 显式建立(ARK-005) +- [ ] 函数值一律箭头函数,无嵌套函数声明与生成器(ARK-006) +- [ ] 无索引签名;类字段全部点访问(ARK-007) +- [ ] 无交叉 / 映射 / 条件类型;utility 仅 Partial/Required/Readonly/Record(ARK-008) +- [ ] 泛型实参与 async 返回类型显式标注(ARK-009) +- [ ] 转换用 as、抛错用 Error、catch 不标类型、系统错误按 BusinessError 处理(ARK-010) +- [ ] 无 ARK-011 列举的全部动态特性(ARK-011) +- [ ] import 置顶;@ohos/@kit 导入已经 09 文档两步流程验证(ARK-012) diff --git a/rules/02-arkui-and-state-management.md b/rules/02-arkui-and-state-management.md new file mode 100644 index 0000000..d813a34 --- /dev/null +++ b/rules/02-arkui-and-state-management.md @@ -0,0 +1,301 @@ +# 02 - ArkUI 组件与状态管理(arkui-and-state-management) + +> **规则编号前缀**:UI +> **适用版本**:状态管理 V2 装饰器自 API 12 起可用(@Local/@Param/@Monitor 等);高级组件与 @ReusableV2 支持 V2 自 API 18 起;animateTo 动画异常规避接口自 API 22 起 +> **核心官方依据**:`FAQ/UI框架/UI界面/状态管理V1和V2适用场景介绍/faqs-arkui-885`、`开发指南/ArkUI_方舟UI框架/UI开发_ArkTS声明式开发范式/学习UI范式状态管理/状态管理V1-V2迁移指导/V1-V2迁移概述/arkts-v1-v2-migration` + +--- + +## 一、更新记录 + +| 版本 | 日期 | 摘要 | +|---|---|---| +| v1.0 | 2026-09-08 | 初始版本:V1/V2 装饰器对照、三原则与混用禁令、$$ 与 !! 差异、@Monitor 迁移注意、组件签名规范 | + +--- + +## 二、规范条目 + +### UI-001 状态管理三原则:V2 优先 + 存量保留 + 严禁混用(MUST) + +- **描述**: + 1. **V2 优先**:新建页面/组件(0→1)默认采用状态管理 V2(@ComponentV2 体系);深度观测、计算属性、深度监听等场景 V2 为官方推荐。 + 2. **存量保留**:既有 V1 代码保持选型不强制迁移,按需参考官方 V1-V2 迁移指导增量演进。 + 3. **严禁混用**:同一组件内禁止混用 V1/V2 装饰器(详见 UI-003)。 +- **官方依据**:`FAQ/UI框架/UI界面/状态管理V1和V2适用场景介绍/faqs-arkui-885`(官方按场景给出选型建议)、`开发指南/ArkUI_方舟UI框架/UI开发_ArkTS声明式开发范式/学习UI范式状态管理/状态管理V1-V2迁移指导/V1-V2迁移概述/arkts-v1-v2-migration` +- **适用版本**:API 12+;API 18 起高级组件与 @ReusableV2 可用于 V2 组件 + +### UI-002 V1/V2 装饰器对照表(MUST) + +- **描述**:选型装饰器时按下表对应关系迁移/选型,禁止凭记忆发明装饰器组合: + +| 能力 | 状态管理 V1 | 状态管理 V2 | +|---|---|---| +| 组件装饰器 | `@Component` | `@ComponentV2` | +| 组件内部状态 | `@State` | `@Local` | +| 外部单向输入 | `@Prop` | `@Param` | +| 父子双向同步 | `@Link` | `@Param` + `@Event` | +| 跨层级同步 | `@Provide` / `@Consume` | `@Provider` / `@Consumer` | +| 嵌套类观测 | `@Observed` + `@ObjectLink` | `@ObservedV2` + `@Trace` | +| 变化监听 | `@Watch` | `@Monitor` | +| 计算属性 | 无(手工重复计算) | `@Computed` | +| 系统组件双向绑定 | `$$` | `!!` | +| 应用级状态 | `AppStorage` | `AppStorageV2` | +| UI 状态持久化 | `PersistentStorage` | `PersistenceV2` | +| 组件复用 | `@Reusable` | `@ReusableV2`(API 18+) | + +- **官方依据**:`FAQ/UI框架/UI界面/状态管理V1和V2适用场景介绍/faqs-arkui-885`、`开发指南/ArkUI_方舟UI框架/UI开发_ArkTS声明式开发范式/学习UI范式状态管理/状态管理V1-V2迁移指导/V1-V2迁移概述/arkts-v1-v2-migration` +- **适用版本**:API 12+ +- **注意**:`AppStorage` 与 `AppStorageV2` 数据**互不共享**;持久化推荐用 `PersistenceV2`(faqs-arkui-885 常见 FAQ 节)。 + +### UI-003 严禁 V1/V2 装饰器混用(MUST NOT) + +- **描述**: + 1. `@Component`(V1 类组件)内**禁止**使用任何 V2 装饰器:`@Local`、`@Param`、`@Event`、`@Monitor`、`@Computed`、`@Provider`、`@Consumer` 等。 + 2. `@ComponentV2`(V2 类组件)内**禁止**使用任何 V1 装饰器:`@State`、`@Prop`、`@Link`、`@Watch`、`@Provide`、`@Consume`、`@ObjectLink`、`@Observed`、`@Reusable` 等。 + 3. `@Local` 仅在 `@ComponentV2` 装饰的自定义组件中支持;V2 组件也无法直接向 V1 机制组件(如 `@CustomDialog`)传参,弹窗等 V1 机制须整体选型。 +- **官方依据**:`开发指南/ArkUI_方舟UI框架/UI开发_ArkTS声明式开发范式/学习UI范式状态管理/状态管理_V2/管理组件拥有的状态/Local装饰器_组件内部状态/arkts-new-local`(@Local 仅在 @ComponentV2 中支持,API 12 起)、`FAQ/UI框架/UI界面/ComponentV2自定义弹窗传参失败/faqs-arkui-771` +- **适用版本**:API 12+ + +✅ 正确 + +```ts +@ComponentV2 +struct CounterPanel { + @Local count: number = 0; // V2 组件 + V2 装饰器 + @Param title: string = ''; // 外部输入 + @Event onChange: (value: number) => void = () => {}; + + build() { + Column() { + Text(`${this.title}: ${this.count}`) + Button('add').onClick(() => { + this.count++; + this.onChange(this.count); + }) + } + } +} +``` + +❌ 错误 + +```ts +@Component +struct CounterPanel { + @Local count: number = 0; // 编译失败:@Component 内禁用 V2 装饰器 + @Param title: string = ''; +} + +@ComponentV2 +struct BadPanel { + @State items: string[] = []; // 编译失败:@ComponentV2 内禁用 V1 装饰器 + @Link value: number; // 同上 +} +``` + +### UI-004 系统组件双向绑定:V1 用 $$、V2 用 !!(MUST) + +- **描述**:系统组件内部状态与 TS 变量双向同步时,V1 组件使用 `$$` 运算符,V2 组件使用 `!!` 语法糖;两者不可交换使用。 +- **官方依据**:`FAQ/UI框架/组件使用/系统组件双向同步语法对深层对象是否兼容/faqs-arkui-920`("在状态管理V1中,使用$$实现系统组件的双向绑定。在状态管理V2中,使用!!语法糖统一处理双向绑定") +- **适用版本**:API 12+ + +✅ 正确 + +```ts +@ComponentV2 +struct LoginInput { + @Local account: string = ''; + + build() { + TextInput({ text: this.account!! }) // V2:!! 双向绑定 + .onChange((value: string) => { this.account = value; }) + } +} + +@Component +struct LegacyInput { + @State account: string = ''; + + build() { + TextInput({ text: $$this.account }) // V1 存量:$$ 保持不变 + } +} +``` + +❌ 错误 + +```ts +@ComponentV2 +struct BadInput { + @Local account: string = ''; + build() { + TextInput({ text: $$this.account }) // V2 组件误用 V1 的 $$ 语法 + } +} +``` + +### UI-005 @Watch 迁移 @Monitor 的三项注意(MUST) + +- **描述**:V2 中以 `@Monitor` 替代 `@Watch` 时必须注意(均为官方 FAQ 记录的踩坑点): + 1. **动画失效**:V1→V2 迁移时 `@Monitor` 代替 `@Watch` 可能导致动画失效(animateTo 在 V2 中可能出现动画效果异常;API 22 起可用同步刷新辅助接口规避,低版本动效场景建议保留 V1); + 2. **监听范围**:`@Monitor` 监听对象属性时,未被 `@Trace` 修饰的属性变化也可能触发回调,监听目标须与 `@Trace` 修饰范围对齐; + 3. **初始化时序**:`@Monitor` 回调先于 `onReady` 中初始化执行,`onReady` 的赋值可能"篡改"监听结果,初始化逻辑须显式区分首帧赋值与变化监听。 + - 收益:`@Monitor` 支持深层属性监听且能获取变化前后两个值(`IMonitor.value()?.before / now`),这是 V1 `@Watch` 不具备的能力。 +- **官方依据**:`FAQ/UI框架/组件使用/Monitor使用限制及常见问题介绍/faqs-arkui-1076`、`FAQ/UI框架/UI界面/Monitor如何监听深层属性的变化/faqs-arkui-1013`、`开发指南/ArkUI_方舟UI框架/UI开发_ArkTS声明式开发范式/学习UI范式状态管理/状态管理_V2/管理数据对象的状态/Monitor装饰器_状态变量修改异步监听/arkts-new-monitor` +- **适用版本**:@Monitor 自 API 12 起 + +✅ 正确 + +```ts +@ObservedV2 +class UserProfile { + @Trace name: string = ''; + @Trace age: number = 0; + + @Monitor('name') + onNameChange(monitor: IMonitor): void { + console.info(`name: ${monitor.value()?.before} -> ${monitor.value()?.now}`); + } +} +``` + +❌ 错误 + +```ts +@ObservedV2 +class UserProfile { + name: string = ''; // 未加 @Trace,深度观测不生效 + @Monitor('name') + onNameChange(): void {} // V2 类中误用无参回调,丢失 before/now 信息 +} +``` + +### UI-006 组件属性/事件签名必须与官方 API 参考一致(MUST) + +- **描述**:书写 ArkUI 组件的属性方法与事件回调时,**禁止凭记忆或类推编造**修饰符名、参数类型与枚举成员(如编造 `.bgColor()`、`NavigationTitleMode.Min`)。不确定签名时,必须先经 `rules/09-api-verification.md` 两步流程在 API 参考目录(harmonyos-references)中核对组件文档(如 Navigation 组件对应 `API参考/ArkUI_方舟UI框架/ArkTS组件/导航与切换/Navigation/ts-basic-components-navigation`)后再书写。 +- **官方依据**:API 参考目录(harmonyos-references)各组件文档;验证流程见 `rules/09-api-verification.md`(APIV-001) +- **适用版本**:全部版本 + +✅ 正确 + +```ts +Text('title') + .fontSize(16) + .fontColor(Color.White) + .backgroundColor('#F1F3F5') // 通用属性 .backgroundColor + +Navigation(this.pathStack) { } + .titleMode(NavigationTitleMode.Mini) // 枚举成员为 Mini(不是 Min) +``` + +❌ 错误 + +```ts +Text('title') + .textSize(16) // 编造:应为 .fontSize + .textColor(Color.White) // 编造:应为 .fontColor + .bgColor('#F1F3F5') // 编造:应为 .backgroundColor + +Navigation(this.pathStack) { } + .titleMode(NavigationTitleMode.Min) // 编造枚举成员:正确为 Mini +``` + +### UI-007 深度观测统一使用 @ObservedV2 + @Trace(SHOULD) + +- **描述**:嵌套类对象、二维数组等深层属性需要触发 UI 更新时,新代码使用 `@ObservedV2` + `@Trace`(属性级精准观测),不再使用 V1 的 `@Observed` + `@ObjectLink` + 子组件逐层拆解方案(嵌套层级深时代码复杂、易用性差)。 +- **官方依据**:`FAQ/UI框架/UI界面/使用状态管理V1_V2进行深度观测的区别和优缺点/faqs-arkui-1068`、`FAQ/UI框架/UI界面/状态管理V1和V2适用场景介绍/faqs-arkui-885` +- **适用版本**:API 12+ + +### UI-008 父子传参:@Param 单向输入 + @Event 事件回传(MUST) + +- **描述**:V2 组件父子数据流:`@Param` 只做父到子单向传递(子组件不得直接修改父组件状态);子组件请求更新通过 `@Event` 回调由父组件执行,状态流向明确。注意:父组件传入的若**不是状态变量**,其修改不会触发子组件 `@Param` 刷新——传参来源必须是可观测状态。 +- **官方依据**:`开发指南/ArkUI_方舟UI框架/UI开发_ArkTS声明式开发范式/学习UI范式状态管理/状态管理_V2/管理组件拥有的状态/Param装饰器_组件外部输入/arkts-new-param`、`FAQ/UI框架/组件使用/Param和_Once相较于_Prop_Link的使用场景及优势/faqs-arkui-1059` +- **适用版本**:@Param 自 API 12 起 + +--- + +## 三、正误对照 + +### 对照 1:V1 组件迁移为 V2 组件(UI-001、UI-002、UI-003) + +❌ 错误(半迁移,装饰器混用) + +```ts +@Component +struct TodoItem { + @State title: string = ''; + @Local editing: boolean = false; // @Component 内使用 V2 装饰器,编译失败 +} +``` + +✅ 正确(整体迁移到 V2 体系) + +```ts +@ComponentV2 +struct TodoItem { + @Param title: string = ''; // V1 @State 父传子语义 → @Param + @Event + @Local editing: boolean = false; // 组件内部状态 → @Local +} +``` + +### 对照 2:@Watch 迁移 @Monitor(UI-005) + +❌ 错误 + +```ts +@ComponentV2 +struct FilterBar { + @Local keyword: string = ''; + @Watch('onKeywordChange') // V2 组件内残留 V1 装饰器 + keywordProxy: string = ''; +} +``` + +✅ 正确 + +```ts +@ComponentV2 +struct FilterBar { + @Local keyword: string = ''; + + @Monitor('keyword') + onKeywordChange(monitor: IMonitor): void { + let before = monitor.value()?.before ?? ''; + let now = monitor.value()?.now ?? ''; + console.info(`keyword: ${before} -> ${now}`); + } +} +``` + +### 对照 3:双向绑定语法按体系选择(UI-004) + +❌ 错误:V2 组件内使用 `$$this.value`(见 UI-004 错误示例)。 + +✅ 正确:V2 用 `this.value!!`,V1 存量保持 `$$this.value`。 + +--- + +## 四、禁止事项 + +- ❌ 禁止同一组件内混用 V1/V2 装饰器(@Component 内禁 @Local/@Param/@Monitor 等;@ComponentV2 内禁 @State/@Prop/@Link/@Watch 等)(UI-003) +- ❌ 禁止 V2 组件使用 `$$`、V1 组件使用 `!!`(UI-004) +- ❌ 禁止在 @ObservedV2 类中遗漏 @Trace 又期望深层属性触发刷新(UI-005、UI-007) +- ❌ 禁止子组件直接修改 @Param 装饰的父组件传入数据(UI-008) +- ❌ 禁止编造组件属性方法、事件签名与枚举成员(UI-006) +- ❌ 禁止给 @Param 传非状态变量并期望其变化触发子组件刷新(UI-008) +- ❌ 禁止新项目默认选 V1 状态管理(UI-001) +- ❌ 禁止期望 AppStorage 与 AppStorageV2 数据互通(UI-002 注意项) + +--- + +## 五、检查清单 + +- [ ] 新组件均基于 @ComponentV2 + V2 装饰器(UI-001) +- [ ] 逐个核对组件内装饰器无 V1/V2 混用(UI-003) +- [ ] 双向绑定语法与组件体系匹配(V2 用 !!、V1 用 $$)(UI-004) +- [ ] @Monitor 回调签名使用 IMonitor 并利用 before/now(UI-005) +- [ ] 深层观测类已用 @ObservedV2 + @Trace 装饰目标属性(UI-007) +- [ ] 父子传参方向:@Param 单向 + @Event 回传,无子改父直接赋值(UI-008) +- [ ] 组件属性/事件签名已与 API 参考核对,无编造修饰符(UI-006) +- [ ] 迁移动画场景已评估 @Monitor 替代 @Watch 的动画失效风险(UI-005) diff --git a/rules/03-architecture-and-project-structure.md b/rules/03-architecture-and-project-structure.md new file mode 100644 index 0000000..db9b5ad --- /dev/null +++ b/rules/03-architecture-and-project-structure.md @@ -0,0 +1,258 @@ +# 03 - 分层架构与工程结构(architecture-and-project-structure) + +> **规则编号前缀**:ARCH +> **适用版本**:API 12+(HAP/HAR/HSP 工程体系全版本适用) +> **核心官方依据**:`最佳实践/分层架构设计/bpta-layered-architecture-design`、`最佳实践/架构概览/bpta-app-architecture-overview` + +--- + +## 一、更新记录 + +| 版本 | 日期 | 摘要 | +|---|---|---| +| v1.1 | 2026-09-08 | 新增 ARCH-008 单 Entry 渐进式采用:目录模拟三层 + 依赖纪律 + 四类官方拆分信号(依据 bpta-modular-design),消除多模块目标形态与 DevEco 默认单 entry 工程的衔接空档 | +| v1.0 | 2026-09-08 | 初始版本:官方三层架构模型、HAR/HSP 选型规则、HSP 页面陷阱、目录组织规范 | + +--- + +## 二、规范条目 + +### ARCH-001 采用官方三层架构模型(MUST) + +- **描述**:应用工程必须按官方三层架构组织,各层职责如下: + +| 层 | 职责 | 编译产物 | +|---|---|---| +| 产品定制层 | 不同设备/场景的个性化需求:UI 设计、资源、配置、特定交互逻辑;应用主入口 | Entry 类型 HAP | +| 基础特性层 | 相对独立的功能 UI 与业务逻辑,高内聚低耦合(如底部导航每个页签一个模块) | Feature HAP / HAR / HSP | +| 公共能力层 | 公共 UI 组件、数据管理、外部交互(网络请求/文件 I/O/设备 I/O)、工具库 | HAR 包 | + +- **官方依据**:`最佳实践/分层架构设计/bpta-layered-architecture-design`(逻辑模型与开发模型) +- **适用版本**:全部版本 + +### ARCH-002 分层依赖只能自上而下(MUST NOT) + +- **描述**:依赖方向固定为 产品定制层 → 基础特性层 → 公共能力层。公共能力层仅可被上层依赖,**不允许反向依赖**;同层模块之间避免相互依赖(防止循环依赖导致构建失败与闪退)。 +- **官方依据**:`最佳实践/分层架构设计/bpta-layered-architecture-design`("公共能力层的各子目录将编译成HAR包,仅产品定制层和基础特性层可依赖,不允许反向依赖") +- **适用版本**:全部版本 + +✅ 正确 + +```text +products/phone(Entry HAP) ──依赖──▶ features/home(HSP) ──依赖──▶ commons/network(HAR) +``` + +❌ 错误 + +```text +commons/utils(HAR) ──依赖──▶ features/home(HSP) // 反向依赖,禁止 +features/home ──依赖──▶ features/mine ──依赖──▶ features/home // 同层循环依赖,禁止 +``` + +### ARCH-003 HAR/HSP 选型规则(MUST) + +- **描述**:共享包选型按下表决策: + +| 场景 | 选型 | 理由 | +|---|---|---| +| 纯代码/组件复用,无按需加载要求 | **HAR**(静态共享包) | 编译期复制到依赖方,支持多模块共享 ArkUI 组件与代码 | +| 代码 + 资源 + C++ 库共享,或多 HAP 集成同一份实现 | **HSP**(动态共享包) | 运行期单实例共享,避免多份拷贝 | +| 需要通过 Ability 承载的独立功能 | **Feature HAP** | HAR/HSP 不能声明 UIAbility | + +- **注意**:HSP 不支持独立发布上架,跟随宿主 APP 包发布、与宿主同进程同生命周期;多 HAP 集成同一 HSP 时通过依赖配置共享。 +- **官方依据**:`FAQ/程序包结构/如何理解App_HAP_HAR_HSP的关系/faqs-package-structure-5`、`FAQ/程序包结构/HAR_HSP_HAP三者的区别和使用场景/faqs-package-structure-73`、`FAQ/程序包结构/多个HAP包集成同一个HSP的规则/faqs-package-structure-74`、`FAQ/命令行工具/动态共享包是否可以发布/faqs-command-line-tool-33` +- **适用版本**:全部版本 + +### ARCH-004 HSP/HAR 内含页面的写法陷阱(MUST) + +- **描述**: + 1. HSP 中的页面随包共享,但改为 HAR 或删除 pages 配置时**必须删除包内页面**,需要以页面形式使用时改为**命名路由或 Navigation 导航**写法; + 2. HSP 与 HAR 的 `module.json5` 中 `type` 字段(`shared`/`har`)转换时,`deliveryWithInstall`、`pages` 等字段须同步增删,hvigor 构建脚本(hspTasks/arTasks)须同步更换; + 3. 跨模块路由跳转只支持 HAR/HSP 模块(`type` 为 `har` 或 `shared`),`feature` 类型会跳转失败。 +- **官方依据**:`FAQ/工程管理/如何将HSP_动态共享包_转为HAR_静态共享包/faqs-project-management-6`、`FAQ/工程管理/如何将HAR_静态共享包_转为HSP_动态共享包/faqs-project-management-7`、`FAQ/UI框架/组件使用/Navigation跨模块跳转报错/faqs-arkui-423` +- **适用版本**:全部版本 + +### ARCH-005 HAR 不得声明 UIAbility(MUST NOT) + +- **描述**:HAR 是静态共享包,仅限代码复用,不能包含动态注册的组件;如需在 HAR 中定义 UIAbility,必须在使用方的 HAP `module.json5` 中声明对应 UIAbility,**不得在 HAR 的 module.json5 中直接声明**。 +- **官方依据**:`FAQ/程序框架/程序框架_Ability/如何在HAR_HSP包中监听系统环境变量变化/faqs-ability-153` +- **适用版本**:全部版本 + +### ARCH-006 目录组织规范(MUST) + +- **描述**:工程目录按三层架构映射组织(目录名为本仓库约定,层职责以 ARCH-001 官方定义为准): + +```text +/project-root +├── build-profile.json5 # 工程级配置(modules 数组登记全部模块) +├── oh-package.json5 # 工程级依赖 +├── products/ # 产品定制层 → Entry HAP +│ └── phone/ # 按设备形态拆分 +│ ├── src/main/ets/ +│ │ ├── entryability/ # UIAbility 入口 +│ │ └── pages/ # 入口页(Navigation 宿主) +│ └── module.json5 +├── features/ # 基础特性层 → Feature HAP / HSP +│ ├── home/ # 一个功能域一个模块 +│ └── mine/ +└── commons/ # 公共能力层 → HAR + ├── network/ # 外部交互:网络封装 + ├── datastore/ # 数据管理:持久化 + ├── ui-components/ # 公共 UI 组件 + └── utils/ # 工具库 +``` + +- **约束**:模块内目录按 `pages/`(页面)、`components/`(组件)、`model/`(数据模型)、`service/`(业务逻辑)细分;禁止在 `commons/` 出现业务专有逻辑(业务专有逻辑属于 `features/`)。 +- **官方依据**:`最佳实践/分层架构设计/bpta-layered-architecture-design`(三层职责与产物划分)、`最佳实践/架构概览/bpta-app-architecture-overview`(架构设计目标:低耦合、可扩展、易维护) +- **适用版本**:全部版本 + +### ARCH-007 数据模型单一来源(MUST) + +- **描述**:跨模块共享的数据模型(class/interface/enum)必须在**一个模块中集中定义并显式 `export`**,使用方显式 `import`;禁止在多个文件重复定义同名类型(ArkTS 禁止声明合并),禁止定义后不导出又跨文件引用。 +- **官方依据**:`开发指南/学习ArkTS语言/从TypeScript到ArkTS的适配指导/从TypeScript到ArkTS的适配规则/typescript-to-arkts-migration-guide`(arkts-no-decl-merging、arkts-no-misplaced-imports 等) +- **适用版本**:API 10+ + +✅ 正确 + +```ts +// commons/network/model/ApiResponse.ets —— 唯一定义处 +export interface PageResult { + rows: T[] + total: number +} + +// features/home/HomeViewModel.ets —— 使用方显式导入 +import { PageResult } from 'commons/network'; +``` + +❌ 错误 + +```ts +// features/home/HomeViewModel.ets —— 本地重复定义,两处漂移风险 +interface PageResult { rows: T[]; total: number } +``` + +### ARCH-008 单 Entry 起步项目的渐进式采用(MUST) + +- **描述**:三层多模块架构(ARCH-001 ~ ARCH-006)是目标形态,不要求项目首日落地。**单 UIAbility、无 ExtensionAbility、无按需加载诉求**的项目,按官方建议优先采用**单 Entry HAP** 起步;起步阶段在 Entry 模块内以目录模拟三层(目录组织方式为本仓库约定,"单 HAP 优先"与拆分信号为官方建议),依赖纪律与 ARCH-002 同构: + +```text +entry/src/main/ets/ +├── entryability/ # 产品定制层职责:UIAbility 入口 +├── pages/ # 产品定制层职责:入口页与 Navigation 宿主 +├── features/ # 基础特性层职责:功能域目录(home/、order/…,域内按 pages/components/model 细分) +└── commons/ # 公共能力层职责:network/、datastore/、components/、utils/ +``` + +- **目录内依赖纪律**:import 方向保持 产品(pages/entryability)→ 特性(features)→ 公共(commons)单向;`commons/` 不得 import `features/`。该纪律保证未来拆包时"目录 → 模块"可机械映射(相对路径 import 改包名 import),无依赖返工。 +- **模块化拆分时机**(出现任一官方信号即启动对应拆分,禁止为拆而拆): + +| 拆分信号 | 拆分动作 | +|---|---| +| 出现第二个 UIAbility(多任务/多窗口形态)或需 ExtensionAbility 承载扩展功能(卡片/分享) | 拆为 **Feature HAP** | +| 低频功能需按需加载(用户首次安装不下载) | 拆为 **HSP** | +| 多设备形态差异显著(phone/2in1/wear 各自定制) | 按设备形态拆分产品定制层(一多工程) | +| 公共能力需跨应用/跨团队共享 | 拆为 **HAR**(可发布 OHPM 私仓) | + +- **官方依据**:`最佳实践/模块化设计/bpta-modular-design`("如果只包含一个UIAbility组件…优先采用单HAP(Entry类型的HAP)来实现应用开发";不需要按需加载的单 HAP 工程"可以直接全部采用HAR进行开发设计";"应用组件的设计决定了模块化设计是采用单HAP工程还是多HAP工程。设计初期需考虑应用的任务形态";"工程模块化模型需根据业务和技术架构演进而演进")、`最佳实践/分层架构设计/bpta-layered-architecture-design`(三层职责与依赖方向,单模块阶段以目录纪律同构保持) +- **适用版本**:全部版本 + +✅ 正确 + +```text +entry/src/main/ets/ +├── entryability/EntryAbility.ets +├── pages/Index.ets // 仅 Navigation 宿主 +├── features/order/ // 订单功能域内聚 +└── commons/network/ // 网络封装 +// import 方向:pages → features/order → commons/network,单向 +``` + +❌ 错误 + +```text +entry/src/main/ets/pages/ +├── Index.ets +├── OrderApi.ets // 网络封装混进 pages +└── DateUtil.ets // 工具类与页面平铺 +// 无层间目录:依赖方向不可审查,拆包时无迁移路径 +``` + +--- + +## 三、正误对照 + +### 对照 1:功能模块放置位置(ARCH-001、ARCH-006) + +❌ 错误:把"订单列表网络接口封装"写进 `products/phone/src/main/ets/utils/`(业务逻辑进了产品定制层)。 + +✅ 正确:接口封装放 `commons/network/`(外部交互),订单页面与业务编排放 `features/order/`(基础特性层),`products/phone` 仅保留入口与设备定制。 + +### 对照 2:HAR 中声明 UIAbility(ARCH-005) + +❌ 错误 + +```json5 +// commons/utils/module.json5 —— HAR 中直接声明 +{ + "module": { + "name": "utils", + "type": "har", + "abilities": [{ "name": "EntryAbility" }] // 编译/运行失败 + } +} +``` + +✅ 正确 + +```json5 +// products/phone/module.json5 —— UIAbility 声明在 HAP +{ + "module": { + "name": "phone", + "type": "entry", + "abilities": [{ "name": "EntryAbility" }] + } +} +``` + +### 对照 3:依赖方向(ARCH-002) + +❌ 错误:`commons/utils/oh-package.json5` 的 dependencies 中出现 `features/home`(公共能力层反向依赖基础特性层)。 + +✅ 正确:依赖只出现在上层模块的 `oh-package.json5` 中,`commons/*` 的 dependencies 只允许依赖其他 commons 模块或三方库。 + +### 对照 4:起步项目目录组织(ARCH-008) + +❌ 错误:单 Entry 项目把网络封装、工具类与页面代码全部平铺在 `pages/` 下,无层间目录;后续拆模块时只能人工逐文件甄别归属,依赖方向无法审查。 + +✅ 正确:起步即在 `entry/src/main/ets/` 下建立 `features/` 与 `commons/` 目录模拟三层,import 保持 产品→特性→公共 单向;出现官方拆分信号后,目录与模块一一对应迁移。 + +--- + +## 四、禁止事项 + +- ❌ 禁止公共能力层反向依赖上层模块(ARCH-002) +- ❌ 禁止同层模块循环依赖(ARCH-002) +- ❌ 禁止纯代码复用场景选 HSP(过度设计)或多 HAP 共享场景选 HAR(多份拷贝)(ARCH-003) +- ❌ 禁止在 HAR 的 module.json5 中声明 UIAbility(ARCH-005) +- ❌ 禁止 HSP/HAR 转换时遗漏 pages 删除、type 修改与构建脚本切换(ARCH-004) +- ❌ 禁止跨模块路由跳转到 `type: "feature"` 模块(ARCH-004) +- ❌ 禁止业务专有逻辑落入 commons 层(ARCH-006) +- ❌ 禁止同一数据模型多处重复定义、定义不导出(ARCH-007) +- ❌ 禁止单 Entry 起步项目无 features/commons 层间目录,导致依赖方向不可审查、拆包无迁移路径(ARCH-008) +- ❌ 禁止未出现官方拆分信号(多 UIAbility / 按需加载 / 多设备形态 / 跨应用共享)前预先拆分 HAR/HSP(过度设计)(ARCH-008) + +--- + +## 五、检查清单 + +- [ ] 工程目录与三层架构映射清晰(多模块:products/features/commons;单 Entry 起步:entry 内 features/commons 目录模拟)(ARCH-001、ARCH-006、ARCH-008) +- [ ] 全部模块依赖方向自上而下,无反向/循环依赖(ARCH-002) +- [ ] 每个共享包的选型(HAR/HSP/Feature HAP)有明确依据(ARCH-003) +- [ ] HAR 内无 UIAbility 声明(ARCH-005) +- [ ] 包类型转换场景已核对 pages/type/构建脚本三项(ARCH-004) +- [ ] 跨模块跳转目标模块 type 为 har 或 shared(ARCH-004) +- [ ] 单 Entry 起步项目 import 方向保持 产品→特性→公共 单向(ARCH-008) +- [ ] 模块化拆分决策对照四类官方信号(多 UIAbility / 按需加载 / 多设备形态 / 跨应用共享)(ARCH-008) +- [ ] 共享数据模型单一来源且显式 export/import(ARCH-007) diff --git a/rules/04-navigation.md b/rules/04-navigation.md new file mode 100644 index 0000000..0fcb145 --- /dev/null +++ b/rules/04-navigation.md @@ -0,0 +1,258 @@ +# 04 - Navigation 路由(navigation) + +> **规则编号前缀**:NAV +> **适用版本**:API 12+(系统路由表跨包路由等能力);router 为历史 API +> **核心官方依据**:`开发指南/ArkUI_方舟UI框架/UI开发_ArkTS声明式开发范式/设置组件导航和页面路由/Router切换Navigation/arkts-router-to-navigation`、`FAQ/UI框架/UI界面/如何混用Navigation和router实现路由导航/faqs-arkui-710` + +--- + +## 一、更新记录 + +| 版本 | 日期 | 摘要 | +|---|---|---| +| v1.0 | 2026-09-08 | 初始版本:统一 Navigation 体系、router 混用禁令、路由注册白屏排查、NavPathStack 单实例、NavDestination 生命周期、V2 传参三方案 | + +--- + +## 二、规范条目 + +### NAV-001 统一使用 Navigation 路由体系(MUST) + +- **描述**:页面路由统一采用 **Navigation(根容器)+ NavDestination(子页面)+ NavPathStack(路由栈)** 体系。官方结论:**"推荐单独使用 Navigation 组件导航,不建议混用"** router。新代码一律使用 Navigation;存量 router 页面按官方迁移指导逐步切换。 +- **官方依据**:`FAQ/UI框架/UI界面/如何混用Navigation和router实现路由导航/faqs-arkui-710`(总结节)、`开发指南/ArkUI_方舟UI框架/UI开发_ArkTS声明式开发范式/设置组件导航和页面路由/Router切换Navigation/arkts-router-to-navigation`、`API参考/ArkUI_方舟UI框架/ArkTS组件/导航与切换/Navigation/ts-basic-components-navigation` +- **适用版本**:API 12+ + +✅ 正确 + +```ts +@Entry +@ComponentV2 +struct Index { + @Local pathStack: NavPathStack = new NavPathStack(); + + build() { + Navigation(this.pathStack) { + Column() { + Button('打开详情') + .onClick(() => { + this.pathStack.pushPathByName('DetailPage', 'param'); + }) + } + } + .navDestination(this.pageMap) // 子页面映射 + } + + @Builder + pageMap(name: string) { + if (name === 'DetailPage') { + DetailPage(); + } + } +} +``` + +❌ 错误 + +```ts +// 新代码使用 router API +this.getUIContext().getRouter().pushUrl({ url: 'pages/DetailPage' }); +``` + +### NAV-002 禁止 Navigation 与 router 混用(MUST NOT) + +- **描述**:同一应用禁止同时维护两套路由栈(router 页面级路由栈 + Navigation 组件级路由栈)。混用是官方明确不建议的写法,且存在硬性约束: + 1. router 仅支持跳转到 `@Entry` 页面,**无法直接从 NavDestination 跳转到另一个 NavDestination**,必须经 @Entry 页面中转; + 2. router 跳转到的页面若需承载 NavDestination,该页面必须以 Navigation 为根容器; + 3. 两套路由栈相互独立,混用跳转须显式清空 router 栈,否则出现返回链路异常(重影/回退错乱)。 + - 唯一允许场景:三方 SDK 强制使用 router 且根容器非 Navigation 时,按官方 FAQ 场景三模式(单例拉起 + 路由监听 + 显式清栈)集成。 +- **官方依据**:`FAQ/UI框架/UI界面/如何混用Navigation和router实现路由导航/faqs-arkui-710` +- **适用版本**:API 12+ + +### NAV-003 路由目标必须注册:系统路由表 + navDestination(MUST) + +- **描述**:每个 NavDestination 目标页必须满足注册三要素,否则 `pushPathByName` **不抛异常、直接白屏**: + 1. **系统路由表**:`module.json5` 声明 `"routerMap": "$profile:router_map"`,`resources/base/profile/router_map.json` 中逐页登记 `name` / `pageSourceFile` / `buildFunction`; + 2. **navDestination 映射**:Navigation 设置 `.navDestination(this.pageMap)`,builder 方法覆盖全部目标页; + 3. **name 一致**:跳转 name 与路由表注册名完全一致(含大小写)。 + - 跨模块(HAR/HSP)跳转依赖系统路由表,目标模块 `type` 必须为 `har` 或 `shared`(`feature` 跳转失败)。 + - **推荐 `pushDestinationByName`(异步)替代 `pushPathByName`(同步)**:跳转失败可 catch 错误并重定向兜底页,避免静默白屏。 +- **官方依据**:`FAQ/UI框架/UI界面/Navigation通过pushPathByName跳转页面为什么显示空白/faqs-arkui-415`(六类白屏原因与替代方案)、`FAQ/UI框架/组件使用/Navigation跳转页面白屏_可能原因是什么/faqs-arkui-390`、`FAQ/UI框架/组件使用/Navigation跨模块跳转报错/faqs-arkui-423`、`开发指南/ArkUI_方舟UI框架/UI开发_ArkTS声明式开发范式/设置组件导航和页面路由/组件导航_Navigation_推荐/Navigation跨包路由/arkts-navigation-cross-package` +- **适用版本**:API 12+ + +✅ 正确 + +```json5 +// resources/base/profile/router_map.json +{ + "routerMap": [ + { + "name": "DetailPage", + "pageSourceFile": "src/main/ets/pages/DetailPage.ets", + "buildFunction": "DetailPageBuilder" + } + ] +} +``` + +```ts +// 推荐异步跳转:失败可兜底 +this.pathStack.pushDestinationByName('DetailPage', 'param') + .catch((error: BusinessError) => { + this.pathStack.pushPathByName('ErrorPage', ''); + hilog.error(0x0000, 'Nav', `jump failed, code=${error.code}`); + }); +``` + +❌ 错误 + +```ts +// name 未在路由表注册 / 拼写错误 → 同步方法静默白屏 +this.pathStack.pushPathByName('Detailpage', 'param'); // 大小写不一致 +``` + +### NAV-004 NavPathStack 单实例原则(MUST NOT) + +- **描述**:NavPathStack 实例由 Navigation 根容器创建并持有,**子页面禁止自行 `new NavPathStack()`**(与父级路由栈冲突,页面无法渲染)。子页面获取栈实例的方式: + 1. `onReady((context: NavDestinationContext) => { this.pathStack = context.pathStack; })`(官方 V2 推荐方案一); + 2. `@Consume('pathStack')`(V1)或 `@Consumer('pathStack')`(V2)注入。 +- **官方依据**:`FAQ/UI框架/UI界面/Navigation通过pushPathByName跳转页面为什么显示空白/faqs-arkui-415`(原因六)、`FAQ/UI框架/UI界面/使用状态管理V2实现Navigation页面路由/faqs-arkui-1658`(方案一) +- **适用版本**:API 12+ + +❌ 错误 + +```ts +@ComponentV2 +struct DetailPage { + pathStack: NavPathStack = new NavPathStack(); // 子页面自建栈,路由冲突 +} +``` + +✅ 正确 + +```ts +@ComponentV2 +struct DetailPage { + pathStack: NavPathStack = new NavPathStack(); // 占位,onReady 中被真实栈覆盖 + + build() { + NavDestination() { /* ... */ } + .onReady((context: NavDestinationContext) => { + this.pathStack = context.pathStack; // 使用父级真实路由栈 + }) + } +} +``` + +### NAV-005 页面显隐监听使用 NavDestination 生命周期(MUST) + +- **描述**:`onPageShow` / `onPageHide` **仅在 router 路由页面**显示隐藏时触发,NavDestination 页面**不会触发**。显隐监听按场景选择: + 1. 子页面显示/隐藏:`NavDestination` 的 `.onShown()` / `.onHidden()`; + 2. 子页面重新激活(返回到该页):`.onActive()`; + 3. Navigation 首页显隐:`.onNavBarStateChange((isVisible: boolean) => {})`; + 4. 全局页面切换监听:`uiObserver.on('navDestinationSwitch', ...)`(from/to 判断页面,需成对 off)。 +- **官方依据**:`FAQ/UI框架/组件使用/实现Navigation首页和子页面互相跳转时的显隐监听/faqs-arkui-504` +- **适用版本**:API 12+ + +✅ 正确 + +```ts +@ComponentV2 +struct OrderListPage { + build() { + NavDestination() { /* 订单列表 */ } + .onShown(() => { this.refresh(); }) // 每次进入页面刷新 + .onHidden(() => { this.pausePolling(); }) + } +} +``` + +❌ 错误 + +```ts +@ComponentV2 +struct OrderListPage { + onPageShow(): void { // NavDestination 页面不会触发,刷新逻辑失效 + this.refresh(); + } +} +``` + +### NAV-006 V2 场景路由传参三方案(MUST) + +- **描述**:@ComponentV2 页面路由传参按场景选官方三方案: + 1. **onReady 接参(首选)**:`context.pathInfo.param` 取参 + `context.pathStack` 取栈,无跨组件耦合; + 2. **@Provider / @Consumer**:Navigation 容器内多页面共享控制同一状态; + 3. **AppStorageV2**:跨页面全局共享状态;**只支持 class 类型**,传非 class 直接运行时报错。 +- **官方依据**:`FAQ/UI框架/UI界面/使用状态管理V2实现Navigation页面路由/faqs-arkui-1658` +- **适用版本**:API 12+ + +✅ 正确 + +```ts +// 方案一:onReady 接参 +@ComponentV2 +struct DetailPage { + @Local params: string = ''; + build() { + NavDestination() { Text(this.params) } + .onReady((context: NavDestinationContext) => { + this.params = context.pathInfo.param as string; + }) + } +} +``` + +❌ 错误 + +```ts +// 方案三误用:AppStorageV2 传基本类型 +AppStorageV2.connect(String, () => 'param'); // 只支持 class 类型,运行时报错 +``` + +--- + +## 三、正误对照 + +### 对照 1:子页面获取路由栈(NAV-004) + +❌ 错误:子页面 `new NavPathStack()` 后调用 `pop()` 无效(操作的是自建空栈,见 NAV-004 错误示例)。 + +✅ 正确:`onReady` 中 `this.pathStack = context.pathStack` 后再执行栈操作。 + +### 对照 2:跳转失败处理(NAV-003) + +❌ 错误:`pushPathByName('NotExistPage')` 静默白屏,无任何日志。 + +✅ 正确:`pushDestinationByName('NotExistPage').catch(...)` 记录错误并重定向兜底页。 + +### 对照 3:首页返回刷新(NAV-005) + +❌ 错误:在 Navigation 首页依赖 `onPageShow` 监听"从子页返回"(从子页返回根页面不触发)。 + +✅ 正确:首页用 `.onNavBarStateChange((isVisible) => { if (isVisible) this.refresh(); })`,子页面用 `.onShown()`。 + +--- + +## 四、禁止事项 + +- ❌ 禁止新代码使用 router API 管理页面跳转(NAV-001) +- ❌ 禁止同一应用混用 router 与 Navigation 双路由栈(三方 SDK 场景除外,且须按官方模式集成)(NAV-002) +- ❌ 禁止从 NavDestination 直接 router 跳转到另一个 NavDestination(NAV-002) +- ❌ 禁止跳转目标未注册路由表/未配置 navDestination 映射(NAV-003) +- ❌ 禁止跨模块跳转目标模块 type 为 feature(NAV-003) +- ❌ 禁止子页面自行 new NavPathStack()(NAV-004) +- ❌ 禁止 NavDestination 页面依赖 onPageShow/onPageHide 实现业务逻辑(NAV-005) +- ❌ 禁止 AppStorageV2 路由传参使用非 class 类型(NAV-006) + +--- + +## 五、检查清单 + +- [ ] 全部页面跳转基于 NavPathStack(pushPathByName/pushDestinationByName),无 router 调用(NAV-001) +- [ ] 三方 SDK router 集成场景已按官方 FAQ 场景三模式处理并加注释说明(NAV-002) +- [ ] 每个 NavDestination 已在 router_map.json 注册且 navDestination builder 覆盖(NAV-003) +- [ ] 跳转 name 与路由表注册名逐字一致(含大小写)(NAV-003) +- [ ] 关键跳转使用 pushDestinationByName 并实现 catch 兜底(NAV-003) +- [ ] 子页面路由栈来自 onReady 或 @Consume/@Consumer 注入(NAV-004) +- [ ] 显隐逻辑使用 onShown/onHidden/onActive/onNavBarStateChange(NAV-005) +- [ ] V2 传参方案已按场景选择,AppStorageV2 仅传 class 类型(NAV-006) diff --git a/rules/05-network-and-backend.md b/rules/05-network-and-backend.md new file mode 100644 index 0000000..7f3eb35 --- /dev/null +++ b/rules/05-network-and-backend.md @@ -0,0 +1,235 @@ +# 05 - 网络与企业级后端对接(network-and-backend) + +> **规则编号前缀**:NET +> **适用版本**:API 12+ +> **核心官方依据**:`API参考/网络/Network_Kit_网络服务/ArkTS_API/ohos_net_http_数据请求_/js-apis-http`、`开发指南/网络/Network_Kit_网络服务/访问网络/使用HTTP访问网络/http-request` + +--- + +## 一、更新记录 + +| 版本 | 日期 | 摘要 | +|---|---|---| +| v1.0 | 2026-09-08 | 初始版本:INTERNET 权限、请求封装基线、data.result 解析、统一错误处理、契约一致规范、分页解析、token 鉴权、TaskPool 决策、RCP 进阶 | + +--- + +## 二、规范条目 + +### NET-001 必须声明 ohos.permission.INTERNET 权限(MUST) + +- **描述**:任何 HTTP 请求前,`module.json5` 必须声明 `ohos.permission.INTERNET` 权限,遗漏将导致请求直接失败: + +```json5 +// module.json5 +{ + "module": { + "requestPermissions": [ + { "name": "ohos.permission.INTERNET" } + ] + } +} +``` + +- **官方依据**:`FAQ/网络/网络_Network/http网络连接中的通用知识/faqs-network-6`("http请求需要申请ohos.permission.INTERNET权限") +- **适用版本**:全部版本 + +### NET-002 请求封装基线:createHttp → request → destroy(MUST) + +- **描述**:每个 http 请求对象的生命周期三段式,**成功或失败都必须调用 `destroy()` 销毁**以节省资源: + +```text +① http.createHttp() 创建请求对象 +② request(url, options) 发起请求(GET/POST 等,见 options.method) +③ destroy() 成功/失败后销毁(finally 保证) +``` + +- **补充**: + - 中文字符集:请求头添加 `'Content-Type': 'application/json; charset=UTF-8'`; + - 框架层面对并发数量**无限制**,但应用层须自行做并发治理(队列/去重/取消),避免瞬时大量请求耗尽资源。 +- **官方依据**:`FAQ/网络/网络_Network/http请求结束后是否需要进行销毁/faqs-network-29`、`FAQ/网络/网络_Network/http请求并发的最大数量限制是多少/faqs-network-28`、`开发指南/网络/Network_Kit_网络服务/访问网络/使用HTTP访问网络/http-request` +- **适用版本**:API 8+ + +### NET-003 响应解析:业务数据在 result 层级(MUST) + +- **描述**:请求成功时,HTTP 响应体业务数据在响应对象的 **`result`** 字段(`data.result`),cookie 在 `data.cookies`。解析基线: + +```text +HttpResponse.responseCode → HTTP 状态码(2xx 判断) +HttpResponse.result → 响应体(string | Object | ArrayBuffer),JSON.parse 后进入业务信封解析 +``` + +- **官方依据**:`FAQ/网络/网络_Network/http网络连接中的通用知识/faqs-network-6`("请求成功时,返回的业务数据在data.result中,cookie信息则在data.cookies中") +- **适用版本**:API 8+ + +### NET-004 统一错误处理:网络异常 / 超时 / 非 2xx 三类分支(MUST) + +- **描述**:请求封装必须覆盖三类失败分支并分别处置: + 1. **网络异常**(catch BusinessError):记录 ERROR 日志,映射为用户可读提示; + 2. **超时**:通过 `connectTimeout` / `readTimeout` 显式配置并捕获超时错误; + 3. **非 2xx 状态码**:`responseCode` 非 2xx 视为失败(禁止只看请求是否返回),按状态码映射处理(401 走 token 刷新,5xx 走重试/降级)。 + - 错误码分层与日志输出遵循 LOG-007。 +- **官方依据**:`API参考/网络/Network_Kit_网络服务/ArkTS_API/ohos_net_http_数据请求_/js-apis-http`(错误码合集、connectTimeout/readTimeout)、`最佳实践/稳定性优化/日志打印规范/HiLog打印规范/bpta-stability-log-standard-hilog` +- **适用版本**:API 8+ + +### NET-005 契约一致:响应模型字段与 JSON 键名严格匹配(MUST) + +- **描述**:企业级对接的响应模型必须与后端契约**逐字段匹配(含大小写、层级、可选性)**: + 1. 响应模型用显式 `class`/`interface` 定义,字段名与 JSON 键名完全一致; + 2. JSON 解析结果经过 `as` 转换后**逐字段空值检查**(可空字段标 `?` 或用联合类型),禁止未判空直接访问深层属性; + 3. 后端字段命名风格(snake_case / camelCase)以契约为准,**禁止**在客户端擅自改名——字段名不匹配会得到 `undefined` 且无编译期报错(LIMS 最高频线上缺陷源)。 +- **官方依据**:`开发指南/学习ArkTS语言/从TypeScript到ArkTS的适配指导/从TypeScript到ArkTS的适配规则/typescript-to-arkts-migration-guide`(arkts-no-untyped-obj-literals、arkts-as-casts:显式类型与 as 转换约束) +- **适用版本**:API 10+ + +✅ 正确 + +```ts +// 与后端契约逐字段对齐:{ "code": 0, "message": "ok", "data": { "rows": [...], "total": 100 } } +interface OrderRow { + orderId: string; // 契约键名 orderId,大小写一致 + orderStatus: number; +} + +interface PageData { + rows: T[]; // 可能为空数组,但字段必存在 + total: number; +} + +interface ApiResponse { + code: number; + message: string; + data: PageData | null; // data 可空,显式标注 +} +``` + +❌ 错误 + +```ts +interface OrderRow { + order_id: string; // 契约是 orderId:风格擅自变更 → 运行时 undefined +} +let resp: ApiResponse = JSON.parse(text) as ApiResponse; +let first: string = resp.data.rows[0].orderId; // data 可能为 null,未判空直接访问 → 崩溃 +``` + +### NET-006 分页结构解析规范(MUST) + +- **描述**:企业后端分页契约统一按 `data.rows`(当前页数据数组)+ `data.total`(总条数)解析(本仓库契约基线): + 1. `rows` 按 `T[]` 泛型数组解析,逐项字段遵循 NET-005; + 2. `total` 用于分页控件计算,禁止用 `rows.length` 冒充总条数; + 3. 分页参数请求侧统一 `page`(页码,从 1 起)+ `pageSize`(每页条数),与后端契约确认后固定。 +- **官方依据**:本仓库契约基线(源自 LIMS 分页契约经验);响应模型类型约束同 NET-005 +- **适用版本**:API 10+ + +### NET-007 token 鉴权与 401 刷新模式(MUST) + +- **描述**: + 1. 统一在请求封装层注入 `Authorization: Bearer ` 请求头,业务代码不得各自拼接; + 2. 收到 **401** 时先尝试用 refresh token 刷新后**重放原请求一次**(仅一次,防循环),刷新失败则登出并跳转登录页; + 3. token 只存安全存储,禁止明文打入日志(衔接 LOG-005 隐私规范)。 +- **官方依据**:本仓库约定;请求头注入能力见 `API参考/网络/Network_Kit_网络服务/ArkTS_API/ohos_net_http_数据请求_/js-apis-http`(header 字段) +- **适用版本**:API 8+ + +### NET-008 TaskPool 使用决策(MUST) + +- **描述**:是否用 TaskPool 处理网络请求按官方口径决策: + - **请求较少 + 后续数据处理耗时短** → **不用 TaskPool**(避免额外线程管理与数据传递开销); + - **大量请求 + 数据处理耗时长** → **用 TaskPool** 承载请求与数据处理,减轻 UI 主线程负载。 +- **官方依据**:`FAQ/ArkTS语言/方舟编程语言_ArkTS/对于_ohos_net_http网络框架是否需要使用TaskPool处理/faqs-arkts-134` +- **适用版本**:API 10+ + +### NET-009 复杂场景进阶:RCP(Remote Communication Kit)(SHOULD) + +- **描述**:业务复杂后可升级到 RCP(场景化 HTTP 通信,Network Kit 的进阶方案)。失败定位利用其扩展日志:`httpPhase` 字段为 6 位 0/1 数字,按位标记 **dns / tcp / tls / send / rcv / body** 六阶段执行进度,配合 `dnsDur`、`tcpDur`、`tlsDur`、`totDur` 等阶段耗时字段可快速定位失败环节(DNS 失败、TLS 握手失败、接收超时等)。 +- **官方依据**:`FAQ/网络/远场通信_Remote_Communication/RCP响应结果解析及常见问题定位思路/faqs-remote-communication-16` +- **适用版本**:API 12+ + +--- + +## 三、正误对照 + +### 对照 1:请求生命周期(NET-002) + +❌ 错误 + +```ts +let client = http.createHttp(); +let resp = await client.request(url, { method: http.RequestMethod.GET }); +// 无 destroy:请求对象泄漏;失败路径更未处理 +``` + +✅ 正确 + +```ts +async function getJson(url: string): Promise> { + let client = http.createHttp(); + try { + let resp = await client.request(url, { + method: http.RequestMethod.GET, + header: { 'Content-Type': 'application/json; charset=UTF-8', ...authHeader() }, + connectTimeout: 10000, + readTimeout: 10000 + }); + if (resp.responseCode < 200 || resp.responseCode >= 300) { + throw new Error(`http ${resp.responseCode}`); // 非 2xx 显式失败(NET-004) + } + return JSON.parse(resp.result as string) as ApiResponse; // 业务数据在 result(NET-003) + } finally { + client.destroy(); // 成功/失败都销毁(NET-002) + } +} +``` + +### 对照 2:分页解析(NET-006) + +❌ 错误 + +```ts +let page: PageData = resp.data; +let total: number = page.rows.length; // 用当页条数冒充总数 → 分页控件错乱 +let no: string = page.rows[0].orderId; // 未判空(rows 可能为空数组) +``` + +✅ 正确 + +```ts +let page: PageData | null = resp.data; +if (page === null || page.rows.length === 0) { + return; // 空数据分支显式处理 +} +let total: number = page.total; // 总条数取契约字段 +let first: OrderRow = page.rows[0]; +``` + +### 对照 3:TaskPool 决策(NET-008) + +❌ 错误:单个登录请求也包一层 TaskPool(增加线程管理与传递开销,无收益)。 + +✅ 正确:批量导出(数百请求 + 大响应体解析)才放 TaskPool;日常列表请求在主线程直接 await。 + +--- + +## 四、禁止事项 + +- ❌ 禁止未声明 ohos.permission.INTERNET 就发起网络请求(NET-001) +- ❌ 禁止请求结束(成功或失败)不调用 destroy()(NET-002) +- ❌ 禁止只判断请求返回不判断 responseCode(NET-004) +- ❌ 禁止响应模型字段名与契约 JSON 键名不一致(含大小写)(NET-005) +- ❌ 禁止未判空访问 data/rows 等可空层级(NET-005、NET-006) +- ❌ 禁止用 rows.length 冒充分页总数(NET-006) +- ❌ 禁止业务代码散拼 Authorization 头、401 无限刷新重放(NET-007) +- ❌ 禁止少量请求场景滥用 TaskPool(NET-008) +- ❌ 禁止 token 等敏感信息打入日志(NET-007、LOG-005) + +--- + +## 五、检查清单 + +- [ ] module.json5 已声明 ohos.permission.INTERNET(NET-001) +- [ ] 请求封装 createHttp → request → destroy(finally)三段式完整(NET-002) +- [ ] 响应解析从 result 取业务数据,JSON.parse 后走契约模型(NET-003、NET-005) +- [ ] 三类失败分支(网络异常/超时/非 2xx)均有处理与日志(NET-004) +- [ ] 响应模型与后端契约逐字段比对过(含大小写与可空性)(NET-005) +- [ ] 分页取 data.rows + data.total,空数据分支显式(NET-006) +- [ ] Authorization 统一注入,401 刷新重放仅一次(NET-007) +- [ ] TaskPool 决策符合"大量请求+长处理"标准(NET-008) diff --git a/rules/06-data-persistence.md b/rules/06-data-persistence.md new file mode 100644 index 0000000..f8720ed --- /dev/null +++ b/rules/06-data-persistence.md @@ -0,0 +1,164 @@ +# 06 - 数据持久化(data-persistence) + +> **规则编号前缀**:DATA +> **适用版本**:API 12+(relationalStore / preferences / KV-Store / PersistentStorage 全版本) +> **核心官方依据**:`FAQ/本地数据和文件/本地数据库管理/PersistentStorage_Preferences_键值型数据库_关系型数据库的区别及适用场景/faqs-local-database-management-53`、`开发指南/ArkData_方舟数据管理/应用数据持久化/应用数据持久化概述/app-data-persistence-overview` + +--- + +## 一、更新记录 + +| 版本 | 日期 | 摘要 | +|---|---|---| +| v1.0 | 2026-09-08 | 初始版本:四方案选型决策树、Preferences flush 规范、RDB 使用与批量写入、JSON 解析容错、UI 状态持久化 | + +--- + +## 二、规范条目 + +### DATA-001 四方案选型决策树(MUST) + +- **描述**:持久化方案按下表决策,禁止"一把 Preferences 走天下": + +| 方案 | 定位 | 适用场景 | 关键限制 | +|---|---|---|---| +| **PersistentStorage** | 持久化 UI 状态(配合 AppStorage) | 应用重启后恢复上次 UI 状态 | 不支持嵌套对象;适用 **<2KB** 轻量数据;同步写盘影响 UI 线程,大量数据必须改用数据库 API | +| **Preferences** | 轻量配置存储 | 应用配置/个性化设置(字体大小、夜间模式开关) | **不支持多进程**并发(易数据损坏);Key 非空 string ≤1024 字节;Value 非空 ≤16MB;建议 **≤50MB**,大数据同步持久化易引发主线程卡顿(appfreeze) | +| **KV-Store**(键值型数据库) | 非关系型数据库 | 无复杂关系模型的键值数据(商品名-价格、工号-出勤状态) | 单版本 Key ≤1KB、Value <4MB;最多同时打开 16 个;回调中禁阻塞操作(如改 UI) | +| **RelationalStore**(RDB) | 关系型数据库(SQLite) | 强关系数据(学生信息含姓名/学号/成绩等多字段多表关联) | 同一时间仅支持**一个写操作**;单条数据建议 **≤2M**(超出插入成功读取失败);卸载应用自动清除库文件 | + +- **决策路径**:UI 状态恢复 → PersistentStorage;纯配置项 → Preferences;简单键值且量大 → KV-Store;多字段/多表/需查询 → RDB。 +- **加密需求**:KV-Store 与 RDB 支持数据库加密;Preferences 不支持加密、PersistentStorage 不涉及——敏感数据禁止存 Preferences。 +- **官方依据**:`FAQ/本地数据和文件/本地数据库管理/PersistentStorage_Preferences_键值型数据库_关系型数据库的区别及适用场景/faqs-local-database-management-53`、`开发指南/ArkData_方舟数据管理/应用数据持久化/应用数据持久化概述/app-data-persistence-overview` +- **适用版本**:API 10+ + +### DATA-002 Preferences 写入后必须 flush(MUST) + +- **描述**:`preferences.put(key, value)` 后**必须调用 `preferences.flush()`** 才真正落盘;不调用 flush 数据仅保存在内存中,应用退出后丢失。 + +✅ 正确 + +```ts +import { preferences } from '@kit.ArkData'; + +let pref: preferences.Preferences = await preferences.getPreferences(context, 'app_config'); +pref.put('nightMode', true); +await pref.flush(); // 落盘,否则 App 重启后数据丢失 +``` + +❌ 错误 + +```ts +pref.put('nightMode', true); // 无 flush:数据只在内存,退出即丢 +``` + +- **官方依据**:`FAQ/本地数据和文件/本地数据库管理/ohos_data_preferences在App退出重启后_持久化数据丢失/faqs-local-database-management-28`、`开发指南/ArkData_方舟数据管理/应用数据持久化/通过用户首选项实现数据持久化_ArkTS/data-persistence-by-preferences`(引用链接) +- **适用版本**:API 10+ + +### DATA-003 RDB 使用规范(MUST) + +- **描述**:使用 RelationalStore 的基线(`import { relationalStore } from '@kit.ArkData'`): + 1. `relationalStore.getRdbStore(context, config)` 获取实例,config 显式声明 `name` 与 `securityLevel`; + 2. 建表用 `store.executeSql(CREATE_TABLE_SQL)`,SQL 中字段约束(PRIMARY KEY / NOT NULL)完整书写; + 3. 写入用 `ValuesBucket` 组织数据,配合显式 SQL 与绑定参数; + 4. RDB 同一时间仅支持一个写操作——写事务串行化,禁止并发多写; + 5. 单条数据 ≤2M(超出插入成功但读取失败)。 +- **官方依据**:`开发指南/ArkData_方舟数据管理/应用数据持久化/通过关系型数据库实现数据持久化_ArkTS/data-persistence-by-rdb-store`、`开发指南/ArkTS_方舟编程语言/ArkTS并发/应用多线程开发实践/应用多线程开发实践案例/批量数据写数据库场景/batch-database-operations-guide`(StoreConfig/executeSql 用法) +- **适用版本**:API 10+ + +### DATA-004 批量写入:batchInsert + TaskPool 子线程(MUST) + +- **描述**:RDB 大数据量写入的两条强制规范: + 1. **批量插入用 `batchInsert`,不用循环单条事务 insert**——官方结论:事务插入无法达到批量插入的效率(100 条记录,单独事务插入需 100 次数据库操作;批量插入一次完成,**内部已包含事务处理机制**); + 2. **频繁数据库操作放 TaskPool 子线程**——读写数据库存在耗时,推荐在子线程中操作避免阻塞 UI 线程(`@Concurrent` 函数承载建库/建表/插入,UI 主线程只发起请求)。 +- **官方依据**:`FAQ/本地数据和文件/本地数据库管理/数据库batchInsert和单个事务insert效率问题/faqs-local-database-management-18`、`开发指南/ArkTS_方舟编程语言/ArkTS并发/应用多线程开发实践/应用多线程开发实践案例/批量数据写数据库场景/batch-database-operations-guide` +- **适用版本**:API 10+ + +❌ 错误 + +```ts +// 主线程循环单条插入 1000 条:1000 次数据库操作 + 阻塞 UI → 卡顿/appfreeze +for (const row of rows) { + await store.insert('orders', row); // 每次独立操作 +} +``` + +✅ 正确 + +```ts +import { taskpool } from '@kit.ArkTS'; + +@Concurrent +async function batchInsertOrders(context: Context, rows: Array): Promise { + let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG); + return store.batchInsert('orders', rows); // 一次批量操作,内部含事务 +} + +// UI 线程只发起请求 +let inserted: number = await taskpool.execute(batchInsertOrders, context, rows); +``` + +### DATA-005 JSON 解析容错规范(MUST) + +- **描述**:解析网络响应/本地缓存 JSON 时(承接 NET-005 契约规范): + 1. `JSON.parse` 结果先判空再 `as` 转换到显式类型; + 2. **逐层空值检查**:可空层级(`data`、`data.rows`)访问前判 null/undefined; + 3. **数组防御**:数组字段按"可能为空数组"处理,取元素前判 `length`; + 4. **类型映射显式化**:number/string 联合语义字段(后端返回字符串数字)在模型层统一转换,禁止在 UI 层到处 `parseInt`。 +- **官方依据**:`开发指南/学习ArkTS语言/从TypeScript到ArkTS的适配指导/从TypeScript到ArkTS的适配规则/typescript-to-arkts-migration-guide`(arkts-as-casts 显式转换、arkts-no-untyped-obj-literals 类型化约束) +- **适用版本**:API 10+ + +### DATA-006 UI 状态持久化:PersistentStorage / PersistenceV2(SHOULD) + +- **描述**:跨启动恢复 UI 状态(主题、引导标记、上次浏览位置)用 PersistentStorage(V1)或 PersistenceV2(V2 体系,`@ObservedV2` class 类型且需在 UI 初始化前 connect)。红线: + - 仅存 **<2KB 轻量数据**,**不支持嵌套对象**(对象数组、属性为对象); + - 需要持久化大量数据或复杂结构时**必须改用数据库 API**(PersistentStorage 同步写盘机制会影响 UI 线程性能)。 +- **官方依据**:`FAQ/本地数据和文件/本地数据库管理/PersistentStorage_Preferences_键值型数据库_关系型数据库的区别及适用场景/faqs-local-database-management-53`、`开发指南/ArkUI_方舟UI框架/UI开发_ArkTS声明式开发范式/学习UI范式状态管理/状态管理_V2/管理应用拥有的状态/PersistenceV2_持久化存储UI状态/arkts-new-persistencev2` +- **适用版本**:PersistentStorage API 7+;PersistenceV2 API 12+ + +--- + +## 三、正误对照 + +### 对照 1:方案选型(DATA-001) + +❌ 错误:把上万条订单记录(含金额、状态、关联商品)存进 Preferences 键值对(超 50MB 建议、无关系查询能力、同步写盘卡主线程)。 + +✅ 正确:订单数据入 RDB(关系模型 + SQL 查询);仅"是否首次启动""夜间模式开关"存 Preferences。 + +### 对照 2:批量导入(DATA-004) + +❌ 错误:主线程 for 循环 1000 次 `store.insert()`(见 DATA-004 错误示例)。 + +✅ 正确:`batchInsert` + TaskPool 子线程(见 DATA-004 正确示例)。 + +### 对照 3:嵌套对象入 PersistentStorage(DATA-006) + +❌ 错误:把整个购物车对象数组(嵌套商品对象)挂 PersistentStorage 持久化。 + +✅ 正确:购物车落 RDB 表;PersistentStorage 只存轻量标记(如购物车数量上限开关)。 + +--- + +## 四、禁止事项 + +- ❌ 禁止 preferences.put 后不调用 flush()(DATA-002) +- ❌ 禁止 Preferences 存敏感数据(不支持加密)、跨多进程使用(DATA-001) +- ❌ 禁止用 PersistentStorage 持久化嵌套对象或 >2KB 数据(DATA-001、DATA-006) +- ❌ 禁止 RDB 循环单条 insert 替代 batchInsert 批量写入(DATA-004) +- ❌ 禁止频繁数据库操作直接在 UI 主线程执行(DATA-004) +- ❌ 禁止 RDB 并发多写(同一时间仅支持一个写操作)(DATA-003) +- ❌ 禁止 RDB 单条数据超过 2M(DATA-003) +- ❌ 禁止 JSON 解析未判空直接访问深层字段(DATA-005) + +--- + +## 五、检查清单 + +- [ ] 每个持久化需求已对照四方案决策树选型(DATA-001) +- [ ] Preferences 全部写路径带 flush()(DATA-002) +- [ ] RDB 实例获取显式声明 name 与 securityLevel(DATA-003) +- [ ] 批量写入走 batchInsert 且在 TaskPool 子线程执行(DATA-004) +- [ ] JSON 解析逐层判空、数组判 length、类型转换在模型层(DATA-005) +- [ ] UI 状态持久化仅存 <2KB 非嵌套轻量数据(DATA-006) +- [ ] 敏感数据未落入 Preferences(DATA-001) diff --git a/rules/07-performance.md b/rules/07-performance.md new file mode 100644 index 0000000..9f8fe82 --- /dev/null +++ b/rules/07-performance.md @@ -0,0 +1,216 @@ +# 07 - 性能优化(performance) + +> **规则编号前缀**:PERF +> **适用版本**:API 12+(LazyForEach/组件复用全版本适用) +> **核心官方依据**:`最佳实践/性能优化/渲染范围控制/bpta-control-rendering-range`、`最佳实践/性能场景优化案例/界面渲染性能优化/长列表加载丢帧优化/bpta-best-practices-long-list` + +--- + +## 一、更新记录 + +| 版本 | 日期 | 摘要 | +|---|---|---| +| v1.0 | 2026-09-08 | 初始版本:ForEach/LazyForEach 选型、IDataSource 规范、cachedCount、if 与 Visibility.None、@Reusable 组件复用、长列表五段优化、keyGenerator 键值规范 | + +--- + +## 二、规范条目 + +### PERF-001 循环渲染选型:ForEach vs LazyForEach 按官方场景表决策(MUST) + +- **描述**:循环渲染组件选型必须对照官方场景表: + +| 场景 | ForEach | LazyForEach | +|---|---|---| +| 小数据量列表(百条级) | ✅ 推荐 | ❌ 不推荐(无性能优势) | +| 大数据量列表(千条级以上) | ❌ 不推荐(滚动卡顿) | ✅ 推荐 | +| 静态数据(很少更新) | ✅ 推荐 | ❌ 不推荐 | +| 动态数据(频繁更新) | ❌ 不推荐(每次更新全量渲染) | ✅ 推荐 | +| 频繁交互、跳转定位的列表 | ✅ 推荐 | ❌ 不推荐(频繁重建,生命周期不稳定) | + +- **官方依据**:`FAQ/UI框架/组件使用/ForEach和LazyForEach的区别/faqs-arkui-1291`(总结场景表) +- **适用版本**:全部版本 + +### PERF-002 大数据量列表强制 LazyForEach(MUST) + +- **描述**:列表/Grid/瀑布流等数据量达到**千条级或持续增长(分页加载、实时流)**时,必须使用 LazyForEach 按需加载。官方实验:ForEach 遍历约 25000 条数据耗时 2 秒以上导致页面卡死;10000 条量级下 ForEach 各项性能指标显著劣化、滑动明显卡顿甚至应用崩溃,LazyForEach 则明显缩短首屏完全显示时间(TTFD)、降低独占内存(USS)、提高滑动帧率。 +- **AI 高频错误**:对无上限数据源默认生成 `ForEach` 全量渲染——生成前必须评估数据量级与增长性。 +- **官方依据**:`FAQ/UI框架/组件使用/ForEach和LazyForEach的区别/faqs-arkui-1291`(常见FAQ:25000条卡顿案例)、`最佳实践/性能场景优化案例/界面渲染性能优化/长列表加载丢帧优化/bpta-best-practices-long-list` +- **适用版本**:全部版本 + +### PERF-003 LazyForEach 必须配套 IDataSource 数据源(MUST) + +- **描述**:LazyForEach 的数据源必须实现 `IDataSource` 接口(按需迭代),且**数据变更必须通过 `DataChangeListener` 通知框架**,禁止直接改动内部数组后期望 UI 刷新: + +```text +IDataSource: + totalCount(): number + getData(index: number): ESObject + registerDataChangeListener(listener: DataChangeListener): void + unregisterDataChangeListener(listener: DataChangeListener): void + +DataChangeListener(按变更类型精确通知): + onDataReloaded() // 全量刷新 + onDataAdd(index) / onDataDelete(index) / onDataChange(index) + onDataMove(from, to) +``` + +- **官方依据**:`API参考/ArkUI_方舟UI框架/ArkTS组件/状态管理与渲染控制/LazyForEach/ts-rendering-control-lazyforeach`、`最佳实践/性能场景优化案例/界面渲染性能优化/长列表加载丢帧优化/bpta-best-practices-long-list`(IDataSource 完整定义) +- **适用版本**:全部版本 + +✅ 正确 + +```ts +class ListDataSource implements IDataSource { + private items: string[] = []; + private listeners: DataChangeListener[] = []; + + totalCount(): number { return this.items.length; } + getData(index: number): string { return this.items[index]; } + + registerDataChangeListener(listener: DataChangeListener): void { + this.listeners.push(listener); + } + unregisterDataChangeListener(listener: DataChangeListener): void { + const pos = this.listeners.indexOf(listener); + if (pos >= 0) { this.listeners.splice(pos, 1); } + } + + push(item: string): void { + this.items.push(item); + this.listeners.forEach((l) => l.onDataAdd(this.items.length - 1)); // 精确通知 + } +} +``` + +❌ 错误 + +```ts +LazyForEach(this.dataSource, (item: string) => { ListItem() { Text(item) } }); +// 直接修改实现类内部数组,未调用 onDataAdd → 滑动到新增数据处白屏/不刷新 +``` + +### PERF-004 懒加载必须评估 cachedCount 缓存数量(SHOULD) + +- **描述**:LazyForEach 通过 `cachedCount` 指定屏幕可视区外的预加载数量(含 List/Swiper 等容器级 cachedCount 与 LazyForEach 组件级),预加载可提升滑动体验但占用更多内存。默认值未必匹配业务——列表项重/滑动快(瀑布流、长图信息流)应上调,内存敏感场景应审慎。 +- **官方依据**:`最佳实践/性能优化/渲染范围控制/bpta-control-rendering-range`(懒加载与缓存列表项)、`最佳实践/性能场景优化案例/界面渲染性能优化/懒加载优化性能/bpta-lazyforeach-optimization` +- **适用版本**:全部版本 + +### PERF-005 显示/隐藏控制:if 与 Visibility.None 的阶段差异(MUST) + +- **描述**:两种隐藏机制作用阶段不同,误用将引起性能问题: + 1. **`if` 条件渲染**:控制组件**创建与布局阶段**——条件为 false 时组件不创建、不占内存;条件翻转时发生完整创建/销毁; + 2. **`Visibility.None`**:组件**已创建**,仅控制布局阶段**不参与布局渲染**——切换开销低,但节点常驻内存。 + - 选择原则(由官方阶段语义推导):**频繁切换显隐的常驻区域用 Visibility.None**(避免反复创建销毁);**一次性/条件性出现且不再复现的内容用 if**(不创建节点,节省内存);禁止用 Visibility.None 隐藏大段从未展示的内容。 +- **官方依据**:`最佳实践/性能优化/渲染范围控制/bpta-control-rendering-range`("if条件判断控制的是组件的创建、布局阶段,visibility属性控制的是元素在布局阶段是否参与布局渲染") +- **适用版本**:全部版本 + +### PERF-006 自定义组件销毁重建场景使用 @Reusable 组件复用(SHOULD) + +- **描述**:出现**相同自定义组件销毁再创建**的场景(长列表滑动的列表项、瀑布流、Swiper 切页等)应使用组件复用(V1 `@Reusable`,V2 组件 API 18 起支持复用体系):复用缓存池中的已有组件节点,降低频繁创建/销毁的开销,提升 UI 线程响应速度。 +- **官方依据**:`开发指南/ArkUI_方舟UI框架/UI开发_ArkTS声明式开发范式/学习UI范式基本语法/自定义组件/自定义组件复用/Reusable装饰器_V1组件复用/arkts-reusable`、`最佳实践/性能优化/渲染范围控制/bpta-control-rendering-range`(组件复用) +- **适用版本**:@Reusable V1 组件复用全版本;V2 组件复用 API 18+ + +### PERF-007 长列表优化五段清单(MUST) + +- **描述**:长列表/Grid/Swiper/瀑布流场景交付前逐项核对官方五段优化手段: + 1. **懒加载**:LazyForEach 按需加载(PERF-002); + 2. **缓存列表项**:cachedCount 预加载(PERF-004); + 3. **动态预加载**:按历史加载耗时动态调整屏幕外数据预取数量; + 4. **组件复用**:列表项自定义组件接入复用池(PERF-006); + 5. **布局优化**:扁平化布局,减少嵌套层级与组件数,避免过度绘制。 + - Swiper 场景另见官方 Swiper 组件加载丢帧优化指导(懒加载 + 组件复用组合)。 +- **官方依据**:`最佳实践/性能场景优化案例/界面渲染性能优化/长列表加载丢帧优化/bpta-best-practices-long-list`(五种优化手段)、`最佳实践/性能场景优化案例/界面渲染性能优化/Swiper组件加载丢帧优化/bpta-swiper_high_performance_development_guide` +- **适用版本**:全部版本 + +### PERF-008 keyGenerator 提供稳定键值(SHOULD) + +- **描述**:ForEach/LazyForEach 未提供 keyGenerator 时,框架默认键值为 `index + '__' + JSON.stringify(item)`。对以下场景必须显式提供稳定 keyGenerator: + - 数据项含函数、循环引用或超大对象(JSON.stringify 失效/昂贵); + - 列表存在增删、移动、排序(index 参与键值导致大量无差别重建)。 + - 键值变化是框架捕获数据源变更、重建组件节点刷新 UI 的依据;数据源更新后界面不刷新时,优先排查键值是否未变化。 +- **官方依据**:`FAQ/UI框架/组件使用/使用ForEach_LazyForEach循环渲染时_会出现更改数据源时_界面不刷新的情况_如何解决/faqs-arkui-41` +- **适用版本**:全部版本 + +✅ 正确 + +```ts +LazyForEach(this.dataSource, + (item: Article) => { ListItem() { ArticleCard({ article: item }) } }, + (item: Article) => item.id.toString() // 稳定业务主键 +) +``` + +❌ 错误 + +```ts +LazyForEach(this.dataSource, + (item: Article) => { ListItem() { ArticleCard({ article: item }) } }, + (item: Article, index: number) => `${index}` // 索引作键:插入项导致全列表错位重建 +) +``` + +--- + +## 三、正误对照 + +### 对照 1:长列表数据源选择(PERF-001、PERF-002) + +❌ 错误 + +```ts +// 分页加载的订单列表,数据持续增长却用 ForEach 全量渲染 +@Local orders: Order[] = []; +List() { + ForEach(this.orders, (o: Order) => { ListItem() { OrderCard({ order: o }) } }) +} +``` + +✅ 正确 + +```ts +List() { + LazyForEach(this.orderSource, + (o: Order) => { ListItem() { OrderCard({ order: o }) } }, + (o: Order) => o.id.toString()) +} +.cachedCount(5) +``` + +### 对照 2:隐藏已创建组件的显隐切换(PERF-005) + +❌ 错误:底部筛选面板每秒可能切换多次,用 `if (this.panelVisible)` 反复创建销毁整棵面板子树。 + +✅ 正确:面板节点常驻,用 `Column().visibility(this.panelVisible ? Visibility.Visible : Visibility.None)`;一次性引导浮层才用 if。 + +### 对照 3:数据源更新通知(PERF-003) + +❌ 错误:`dataSource.items.push(newItem)` 后不通知,滑动到新数据处空白。 + +✅ 正确:封装 `push()` 方法内部调用 `listener.onDataAdd(index)`(见 PERF-003 正确示例)。 + +--- + +## 四、禁止事项 + +- ❌ 禁止千条级以上/持续增长数据源使用 ForEach 全量渲染(PERF-002) +- ❌ 禁止 LazyForEach 数据源不实现 IDataSource 四方法(PERF-003) +- ❌ 禁止数据变更绕过 DataChangeListener 直接改数组(PERF-003) +- ❌ 禁止用索引作为列表键值、或对含函数/循环引用对象依赖默认 JSON.stringify 键(PERF-008) +- ❌ 禁止用 Visibility.None 常驻隐藏大段从未展示的内容(PERF-005) +- ❌ 禁止高频显隐切换场景使用 if 反复创建销毁组件(PERF-005) +- ❌ 禁止小数据量(百条级静态)列表强行使用 LazyForEach(无性能优势,增加复杂度)(PERF-001) +- ❌ 禁止长列表交付前跳过五段优化自查(PERF-007) + +--- + +## 五、检查清单 + +- [ ] 循环渲染选型已对照官方五场景表(PERF-001) +- [ ] 千条级/增长型数据源已使用 LazyForEach(PERF-002) +- [ ] IDataSource 四方法实现完整,变更走 DataChangeListener 精确通知(PERF-003) +- [ ] cachedCount 已按列表项复杂度评估设置(PERF-004) +- [ ] 显隐控制已按 if(创建阶段)/Visibility.None(布局阶段)语义选择(PERF-005) +- [ ] 列表项/Swiper 页等销毁重建组件已接入 @Reusable 复用(PERF-006) +- [ ] 长列表交付前完成五段优化自查(懒加载/缓存/动态预加载/复用/扁平化布局)(PERF-007) +- [ ] keyGenerator 使用稳定业务键,无索引键(PERF-008) diff --git a/rules/08-logging-and-error-handling.md b/rules/08-logging-and-error-handling.md new file mode 100644 index 0000000..98eea71 --- /dev/null +++ b/rules/08-logging-and-error-handling.md @@ -0,0 +1,207 @@ +# 08 - 日志与错误处理(logging-and-error-handling) + +> **规则编号前缀**:LOG +> **适用版本**:API 12+(hilog 全版本;setMinLogLevel 自 API 15 起) +> **核心官方依据**:`API参考/调测调优/Performance_Analysis_Kit_性能分析服务/ArkTS_API/ohos_hilog_HiLog日志打印_/js-apis-hilog`、`最佳实践/稳定性优化/日志打印规范/HiLog打印规范/bpta-stability-log-standard-hilog` + +--- + +## 一、更新记录 + +| 版本 | 日期 | 摘要 | +|---|---|---| +| v1.0 | 2026-09-08 | 初始版本:HiLog 强制、console.log 生产禁令、五级日志标准、domain/TAG 规范、隐私与打印时机、统一错误处理与批量操作日志模式 | + +--- + +## 二、规范条目 + +### LOG-001 生产代码强制使用 HiLog(MUST) + +- **描述**:生产代码的日志输出统一使用 HiLog(`import { hilog } from '@kit.PerformanceAnalysisKit'`),并自定义 domain 与 tag;打印前可用 `hilog.isLoggable(domain, tag, level)` 判断是否可打印。 +- **官方依据**:`API参考/调测调优/Performance_Analysis_Kit_性能分析服务/ArkTS_API/ohos_hilog_HiLog日志打印_/js-apis-hilog`、`开发指南/调测调优/Performance_Analysis_Kit_性能分析服务/日志打印/使用HiLog打印日志_ArkTS/hilog-guidelines-arkts` +- **适用版本**:全部版本 + +✅ 正确 + +```ts +import { hilog } from '@kit.PerformanceAnalysisKit'; + +const DOMAIN = 0x0001; +const TAG = 'OrderService'; + +hilog.info(DOMAIN, TAG, 'submit order %{public}s', orderNo); +``` + +### LOG-002 console.log 仅限临时调试,禁入生产(MUST NOT) + +- **描述**:`console.log` 本质是 hilog 的封装:**domain 固定为 0xA0c0d0、tag 固定为 JSApp、级别固定为 info**——无法按业务模块过滤与检索。仅允许本地临时调试使用,提交前必须替换为 HiLog 或删除。 +- **官方依据**:`FAQ/技术质量/运维/console_log和hilog的区别_如何选择使用/faqs-performance-analysis-kit-24` +- **适用版本**:全部版本 + +❌ 错误 + +```ts +// 生产代码 +console.info('order submitted: ' + orderNo); // domain 0xA0c0d0 / tag JSApp,无法按模块过滤 +``` + +✅ 正确 + +```ts +hilog.info(DOMAIN, TAG, 'order submitted: %{public}s', orderNo); +``` + +### LOG-003 五级日志使用标准(MUST) + +- **描述**:日志级别必须符合内容实际级别(对齐官方 LogLevel 语义): + +| 级别 | 语义(官方定义) | 典型使用 | +|---|---|---| +| FATAL | 重大致命异常,程序/功能即将崩溃,故障无法恢复 | 不可恢复错误、即将 Crash | +| ERROR | 发生错误,影响功能正常运行或用户正常使用;可恢复但恢复代价较高 | 接口失败、数据写入失败 | +| WARN | 较严重的非预期情况,对用户影响不大,可自动恢复或简单操作恢复 | 重试成功、降级触发 | +| INFO | 业务关键流程节点,可还原业务主要运行过程;可预期的非正常情况(如无网络信号、登录失败) | 关键路径打点、状态迁移 | +| DEBUG | 比 INFO 更详细的流程记录,用于分析业务流程与定位问题;**正式发布版本默认不打印** | 详细中间变量、分支追踪 | + +- **INFO 记录权**:由业务内处于支配地位的模块记录,避免在多个被调用模块或低级函数中重复记录。 +- **官方依据**:`最佳实践/稳定性优化/日志打印规范/HiLog打印规范/bpta-stability-log-standard-hilog`(日志级别规则)、`开发指南/调测调优/Performance_Analysis_Kit_性能分析服务/日志打印/使用HiLog打印日志_ArkTS/hilog-guidelines-arkts` +- **适用版本**:全部版本 + +### LOG-004 domain 与 TAG 规范(MUST) + +- **描述**: + 1. **domain**:取值范围 `0x0000~0xFFFF`,按业务域分配(本仓库约定:网络=0x0001、数据=0x0002、UI=0x0003……集中定义于 `commons/utils/LogDomain.ets`,禁止魔法数字散落各处); + 2. **tag**:标识调用所在的类或业务行为;**最多 31 字节,超出截断**;**不建议中文字符**(乱码/对齐问题);统一大驼峰英文。 +- **官方依据**:`开发指南/调测调优/Performance_Analysis_Kit_性能分析服务/日志打印/使用HiLog打印日志_ArkTS/hilog-guidelines-arkts`(参数解析节) +- **适用版本**:全部版本 + +### LOG-005 日志内容规范:隐私保护与格式化(MUST) + +- **描述**: + 1. **隐私格式符**:hilog 格式串按 `%{private flag}specifier` 打印——`%{private}s` 输出 ``(缺省即 private)、`%{public}s` 明文输出。**默认 private,仅在确认非敏感后才显式使用 public**; + 2. **禁止打印隐私信息**:硬件序列号、个人账号、密码、身份信息等一律禁止; + 3. **禁止业务无关信息**:issue/需求单号、公司部门、开发人员姓名工号等; + 4. **禁止重复信息**:不同位置打印内容完全一样的日志(无法定位代码位置); + 5. **禁止在日志语句中调用业务接口函数**:日志不得影响业务流程; + 6. 内容用英文描述,拼写无误、语法规范,单行尽量 100 字符内(避免超过 160 字符)。 +- **官方依据**:`最佳实践/稳定性优化/日志打印规范/HiLog打印规范/bpta-stability-log-standard-hilog`(日志内容规则)、`开发指南/调测调优/Performance_Analysis_Kit_性能分析服务/日志打印/使用HiLog打印日志_ArkTS/hilog-guidelines-arkts`(隐私标识符) +- **适用版本**:全部版本 + +❌ 错误 + +```ts +hilog.info(DOMAIN, TAG, 'login with phone=%{public}s password=%{public}s', phone, pwd); // 隐私明文,违规 +hilog.info(DOMAIN, TAG, '1234'); // 无语义内容 +``` + +✅ 正确 + +```ts +hilog.info(DOMAIN, TAG, 'login result: %{public}s, phone: %{private}s', result, phone); // 手机号脱敏 +``` + +### LOG-006 打印时机与长度限制(MUST) + +- **描述**: + 1. **高频代码正常流程禁止打印日志**(高频接口、大数据量循环、音视频流、屏幕刷新等),错误分支可以打印; + 2. **可能重复发生的日志实施频率限制**,防止刷屏; + 3. **调试日志禁止提交代码仓**:逐步排查用的临时日志提交前必须删除或用开关关闭(DEBUG 级别发布版默认不打印,可作为开关策略); + 4. **单条日志长度上限 4096 字节**,超出截断——超长内容(如完整响应体)禁止整段打印,截取关键片段。 +- **官方依据**:`最佳实践/稳定性优化/日志打印规范/HiLog打印规范/bpta-stability-log-standard-hilog`(打印时机规则)、`FAQ/技术质量/运维/使用HiLog打印日志是否有长度限制/faqs-performance-analysis-kit-58`(4096 字节截断) +- **适用版本**:全部版本 + +### LOG-007 统一错误处理与批量操作日志模式(MUST) + +- **描述**: + 1. **错误码分层**:系统错误(BusinessError.code)→ 业务错误码(项目自定义分段)→ 用户提示文案三层映射,禁止把系统错误码直接抛给用户; + 2. **用户友好提示**:对外提示为可理解的中文文案("网络异常,请稍后重试"),对内日志记录完整错误码与堆栈(ERROR 级别); + 3. **批量操作日志模式**(LIMS 方法论移植,仓库约定): + - 批量操作**开始前**:INFO 记录操作类型与总数; + - **失败逐条**:ERROR/WARN 记录每条失败项的业务主键与失败原因; + - **完成后**:INFO 汇总统计(成功数/失败数/耗时)。 +- **官方依据**:`最佳实践/稳定性优化/日志打印规范/bpta-stability-log-standard-hilog`(ERROR 级别语义与内容规范);错误码分层与批量模式为本仓库约定 +- **适用版本**:全部版本 + +✅ 正确(批量模式示例) + +```ts +async function batchSyncOrders(orders: Order[]): Promise { + hilog.info(DOMAIN, TAG, 'batch sync start, total=%{public}d', orders.length); + let ok = 0, fail = 0; + const start = Date.now(); + for (const order of orders) { + try { + await syncOne(order); + ok++; + } catch (e) { + fail++; + hilog.error(DOMAIN, TAG, 'sync failed, orderNo=%{public}s, reason=%{public}s', + order.orderNo, JSON.stringify((e as BusinessError).code)); + } + } + hilog.info(DOMAIN, TAG, 'batch sync done, ok=%{public}d, fail=%{public}d, cost=%{public}dms', + ok, fail, Date.now() - start); +} +``` + +--- + +## 三、正误对照 + +### 对照 1:日志接口选择(LOG-001、LOG-002) + +❌ 错误:生产代码用 `console.info/error` 输出(tag 固定 JSApp,模块过滤失效)。 + +✅ 正确:HiLog + 自定义 domain/tag(见 LOG-001 正确示例)。 + +### 对照 2:级别选择(LOG-003) + +❌ 错误 + +```ts +hilog.error(DOMAIN, TAG, 'enter detail page'); // 正常流程打点用 ERROR,告警噪音 +hilog.info(DOMAIN, TAG, 'db corrupted, unrecoverable'); // 致命错误用 INFO,漏报 +``` + +✅ 正确 + +```ts +hilog.info(DOMAIN, TAG, 'enter detail page, id=%{public}s', id); // 关键流程节点 → INFO +hilog.fatal(DOMAIN, TAG, 'db corrupted, unrecoverable'); // 不可恢复 → FATAL +``` + +### 对照 3:失败处理的信息完整性(LOG-007) + +❌ 错误 + +```ts +try { await syncOne(order); } catch (e) { console.error('failed'); } // 无主键、无原因、错误接口 +``` + +✅ 正确:按 LOG-007 批量模式记录 orderNo + code + 汇总统计。 + +--- + +## 四、禁止事项 + +- ❌ 禁止生产代码使用 console.log/info/warn/error(LOG-002) +- ❌ 禁止打印隐私信息(密码、账号、硬件序列号、身份信息)及无语义 `%{public}` 明文输出敏感字段(LOG-005) +- ❌ 禁止高频正常流程打印日志、重复日志不限频(LOG-006) +- ❌ 禁止调试日志提交代码仓(LOG-006) +- ❌ 禁止超长内容整段打印(>4096 字节截断丢信息)(LOG-006) +- ❌ 禁止日志语句中调用业务接口函数(LOG-005) +- ❌ 禁止向用户直接展示系统错误码/原始异常信息(LOG-007) +- ❌ 禁止使用中文/超 31 字节 tag、domain 魔法数字散落代码(LOG-004) + +--- + +## 五、检查清单 + +- [ ] 全部生产日志走 hilog,domain/tag 集中定义(LOG-001、LOG-004) +- [ ] 代码中 grep 无 console.* 残留(LOG-002) +- [ ] 每条日志级别与语义匹配(FATAL/ERROR/WARN/INFO/DEBUG)(LOG-003) +- [ ] 敏感字段使用 %{private}s,public 输出逐条确认非敏感(LOG-005) +- [ ] 批量操作有开始/逐条失败/汇总三类日志(LOG-007) +- [ ] 错误处理三层齐备:系统错误码捕获 → 业务错误映射 → 用户文案(LOG-007) +- [ ] 高频路径无正常流程日志,重复日志已限频(LOG-006) diff --git a/rules/09-api-verification.md b/rules/09-api-verification.md new file mode 100644 index 0000000..c48c28f --- /dev/null +++ b/rules/09-api-verification.md @@ -0,0 +1,170 @@ +# 09 - API 存在性验证(api-verification) + +> **规则编号前缀**:APIV +> **适用版本**:全部版本(验证流程本身不依赖 API 版本) +> **核心官方依据**:devecocli docs 本地官方文档库(harmonyos-guides / harmonyos-references / best-practices / harmonyos-faqs 四目录,T001 已验证可用) + +--- + +## 一、更新记录 + +| 版本 | 日期 | 摘要 | +|---|---|---| +| v1.0 | 2026-09-08 | 初始版本:两步验证工作流、三类验证对象、降级策略、编造模式清单、导入路径细则 | + +--- + +## 二、规范条目 + +### APIV-001 强制两步验证工作流:search → read(MUST) + +- **描述**:AI 生成任何涉及系统 API 的代码前,**必须**完成两步验证,未完成不得写入代码: + 1. **检索定位**:`devecocli docs search <关键词>`,从返回的 documentId 候选中定位目标 API 所属文档(接口类查 harmonyos-references 目录,使用指导查 harmonyos-guides,问题排查查 harmonyos-faqs,性能/架构查 best-practices); + 2. **原文核对**:`devecocli docs read `,逐项核对**模块名、接口名、参数签名(类型与顺序)、返回值、枚举成员、导入路径、起始 API 版本**,全部确认后方可使用。 +- **官方依据**:devecocli docs 工具链(`devecocli docs catalog` 确认四目录可检索;search/read 链路可用性已抽查验证) +- **适用版本**:全部版本 + +✅ 正确流程示例 + +```text +任务:发起 HTTP POST 请求 +① devecocli docs search "http 数据请求" + → 命中 API参考/网络/Network_Kit_网络服务/ArkTS_API/ohos_net_http_数据请求_/js-apis-http +② devecocli docs read "API参考/网络/Network_Kit_网络服务/ArkTS_API/ohos_net_http_数据请求_/js-apis-http" + → 核对:import { http } from '@kit.NetworkKit'; + http.createHttp() 创建实例;request(url, options) 发请求; + options.method 取 http.RequestMethod.POST;response.responseCode 为状态码 +③ 全部确认 → 按核对结果书写代码 +``` + +### APIV-002 三类验证对象(MUST) + +- **描述**:以下三类对象**逐个**执行 APIV-001 流程,缺一不可: + +| 验证对象 | 验证内容 | 反例(编造后果) | +|---|---|---| +| ① 接口存在性 | `@ohos.*` / `@kit.*` 模块、类、方法是否真实存在 | 调用不存在的方法 → 运行时 undefined 报错 | +| ② 参数签名准确性 | 参数个数、类型、顺序、可选性、返回值、枚举成员 | 签名不匹配 → 编译失败或运行时行为异常 | +| ③ 导入路径正确性 | import 语句的 Kit 名与导出成员名 | 路径错误 → 模块加载失败 | + +- **官方依据**:同 APIV-001;API 签名以 harmonyos-references 目录 API 参考为准 +- **适用版本**:全部版本 + +### APIV-003 无法验证即禁用(MUST) + +- **描述**:**经两步验证仍无法确认存在性的 API 一律禁用**。降级策略按序执行: + 1. 检索同能力的**已验证替代方案**(换关键词重查、查 FAQ 目录同类场景实现); + 2. 无替代方案时,向用户**明示不确定**("该 API 未能核实,请以官方文档为准"),并给出保守实现; + 3. 禁止以"记忆中应该存在""同类平台有此 API"为由跳过验证直接使用。 +- **官方依据**:本仓库强制约定(源于编造 API 导致线上缺陷的历史教训) +- **适用版本**:全部版本 + +### APIV-004 禁止编造 API(MUST NOT) + +- **描述**:严禁编造以下内容: + - 不存在的模块/Kit(如 `@ohos.network`); + - 不存在的便捷方法(如给 `@ohos.net.http` 编造 `postJson()`——实际 POST 用 `request()` + `http.RequestMethod.POST`); + - 不存在的参数与枚举成员; + - 错误的导入路径与导出成员名。 +- **历史教训**:LIMS v3.11——AI 按其他平台习惯编造 `postJson` 便捷方法,运行时才暴露,产生线上缺陷。鸿蒙开发中此风险模式完全一致:**编译期不报错、运行时才崩**是编造 API 的典型特征。 +- **官方依据**:`API参考/网络/Network_Kit_网络服务/ArkTS_API/ohos_net_http_数据请求_/js-apis-http`(http 真实签名:createHttp/request/destroy,无 postJson) +- **适用版本**:全部版本 + +### APIV-005 典型编造模式清单(自查用)(MUST) + +- **描述**:生成代码后对照本清单自查,命中任意一条即回退 APIV-001 流程: + 1. **习惯迁移**:把其他平台习惯(axios.post / fetch / uni.request)映射成鸿蒙 API 名; + 2. **链式脑补**:给真实类编造链式方法(如 `httpInstance.postJson().then()`); + 3. **省参调用**:省略必要参数(如 `hilog.info(msg)`——真实签名要求 domain, tag, format 三参起); + 4. **枚举臆造**:猜枚举成员名(大小写/单复数错误,如 `NavigationTitleMode.Min` 应为 `Mini`); + 5. **Kit 错配**:Kit 名与成员张冠李戴(如 `import { http } from '@kit.RemoteCommunicationKit'`——http 属 `@kit.NetworkKit`)。 +- **官方依据**:本仓库约定;各反例的正确签名见对应 API 参考(js-apis-hilog、ts-basic-components-navigation、js-apis-http) +- **适用版本**:全部版本 + +### APIV-006 导入路径验证细则(MUST) + +- **描述**:import 语句按以下规则书写并验证: + 1. **Kit 方式优先**:统一使用 `import { xxx } from '@kit.XxxKit'` 聚合导入;Kit 名与成员名均须在 API 参考文档开头核实; + 2. **已验证示例**(均经 `devecocli docs read` 核对): + +| 能力 | 正确导入 | 依据文档 | +|---|---|---| +| HTTP 请求 | `import { http } from '@kit.NetworkKit'` | js-apis-http | +| HiLog 日志 | `import { hilog } from '@kit.PerformanceAnalysisKit'` | js-apis-hilog | +| 页面切换无感监听 | `import { uiObserver } from '@kit.ArkUI'` | faqs-arkui-504 | +| AppStorageV2 | `import { AppStorageV2 } from '@kit.ArkUI'` | faqs-arkui-1658 | +| router(存量) | `import { router } from '@kit.ArkUI'` | faqs-arkui-710 | + + 3. 未在表中且未经 read 核对的导入路径,视为未验证,回退 APIV-001。 +- **官方依据**:各模块 API 参考文档(documentId 见表内依据列) +- **适用版本**:全部版本 + +--- + +## 三、正误对照 + +### 对照 1:POST 请求写法(APIV-001、APIV-004) + +❌ 错误(编造便捷方法) + +```ts +import { http } from '@kit.NetworkKit'; + +let resp = await http.postJson('https://api.example.com/orders', body); // postJson 不存在 +``` + +✅ 正确(按 js-apis-http 真实签名) + +```ts +import { http } from '@kit.NetworkKit'; + +let client = http.createHttp(); +let resp = await client.request('https://api.example.com/orders', { + method: http.RequestMethod.POST, + header: { 'Content-Type': 'application/json' }, + extraData: JSON.stringify(body) +}); +client.destroy(); // 请求结束销毁,避免资源泄漏 +``` + +### 对照 2:日志调用签名(APIV-005 模式三) + +❌ 错误 + +```ts +hilog.info('order submitted'); // 省略 domain/tag/format,签名不匹配 +``` + +✅ 正确 + +```ts +hilog.info(0x0001, 'OrderService', 'order submitted: %{public}s', orderNo); +``` + +### 对照 3:无法验证时的降级(APIV-003) + +❌ 错误:"我记得 @ohos.deviceInfo 有 getSerial(),直接用。"(未验证,且序列号属敏感信息) + +✅ 正确:`devecocli docs search "设备信息"` → read 核对 deviceInfo 真实接口与隐私限制 → 确认存在并合规后再使用;查不到就明示不确定并给保守方案。 + +--- + +## 四、禁止事项 + +- ❌ 禁止跳过 search → read 两步直接书写 @ohos/@kit 调用(APIV-001) +- ❌ 禁止使用任何未经文档核对的模块、方法、参数、枚举、导入路径(APIV-002) +- ❌ 禁止在无法验证时凭记忆/习惯/类推使用 API(APIV-003) +- ❌ 禁止编造便捷方法、链式方法、Kit 名、导出成员(APIV-004) +- ❌ 禁止省略已核实签名的必要参数(APIV-005) +- ❌ 禁止把其他平台 API 习惯直接映射为鸿蒙 API 名(APIV-005) + +--- + +## 五、检查清单 + +- [ ] 代码中每个 @ohos/@kit 导入语句都经过 read 核对(APIV-006) +- [ ] 每个系统 API 调用的参数签名与 API 参考一致(APIV-002) +- [ ] 用到的枚举成员逐个与文档比对(含大小写)(APIV-002) +- [ ] 无 postJson 式编造便捷方法(APIV-004、APIV-005 自查清单过一遍) +- [ ] 无法验证的 API 已替换为已验证方案或向用户明示不确定(APIV-003) +- [ ] HTTP 请求代码含 createHttp → request → destroy 完整链路(APIV-004 对照 1) diff --git a/rules/10-prohibited-and-checklist.md b/rules/10-prohibited-and-checklist.md new file mode 100644 index 0000000..adc42c4 --- /dev/null +++ b/rules/10-prohibited-and-checklist.md @@ -0,0 +1,213 @@ +# 10 - 禁止事项汇总与开发总检查清单(prohibited-and-checklist) + +> **规则编号前缀**:GEN +> **本文档定位**:全部专题文档禁止事项的**汇总索引**与开发/评审两用的**总检查清单**。条目一律引用规则编号并给出极简提示,权威原文在各专题文档(C5 契约:单一事实来源,避免两处维护漂移)。 + +--- + +## 一、更新记录 + +| 版本 | 日期 | 摘要 | +|---|---|---| +| v1.1 | 2026-09-08 | 同步 ARCH-008(单 Entry 渐进式采用)禁止事项与检查项 | +| v1.0 | 2026-09-08 | 初始版本:按主题汇总全部禁止事项索引、开发自查清单与 Code Review 清单 | + +--- + +## 二、规范条目 + +### GEN-001 汇总引用契约(MUST) + +- **描述**:本文档所有禁止事项与检查清单条目**只引用规则编号与极简提示**,禁止复制专题文档正文全文;条目语义与各专题文档第四节/第五节保持一致,冲突时**以专题文档为准**。 +- **官方依据**:`rules/00-usage-and-update.md`(USE-004 编号体系、USE-006 松耦合约束) +- **适用版本**:全部版本 + +### GEN-002 开发自查流程(MUST) + +- **描述**:开发者提交代码前,按「五、开发总检查清单」的**开发自查**部分逐项勾选;命中任一禁止事项即回对应专题文档查看修复模式(第三节正误对照)。 +- **官方依据**:本仓库约定(流程入口 `AGENTS.md` 工作流 2) +- **适用版本**:全部版本 + +### GEN-003 Code Review 流程(MUST) + +- **描述**:评审人按「五、开发总检查清单」的 **Code Review** 部分逐项核对;重点核对红线级条目(MUST/MUST NOT),SHOULD 级条目记录为建议。 +- **官方依据**:本仓库约定 +- **适用版本**:全部版本 + +--- + +## 三、正误对照 + +### 对照 1:主题定位流程(USE-002,30 秒目标) + +❌ 错误:遇到"长列表卡顿"问题,在 `rules/` 全目录逐份打开全文通读。 + +✅ 正确:`AGENTS.md` 索引 → 主题摘要"性能优化(LazyForEach/…)" → 打开 `rules/07-performance.md` → 命中 PERF-002(大数据量强制 LazyForEach)→ 需要修复模式时看该文档第三节对照 1。全程 < 30 秒。 + +### 对照 2:汇总条目与权威原文的关系(GEN-001) + +❌ 错误:只看本清单一句话提示就直接改代码(提示不完整,如 PERF-008 提示"keyGenerator 稳定键值",未含 JSON.stringify 失效细节)。 + +✅ 正确:由编号跳转专题文档,按完整条目与 ✅/❌ 对照修复。 + +--- + +## 四、禁止事项汇总(按主题分组,详情见各专题文档) + +### 元规则(USE)— `rules/00-usage-and-update.md` + +- ❌ 规则文档中构造任何 web URL 作为官方依据(USE-007) +- ❌ 新增/更名/删除 `rules/` 文档后遗漏同步 `AGENTS.md` 索引(USE-006) +- ❌ 更新记录缺四要素(问题背景/根因/修复模式/条目回链)(USE-005) +- ❌ 版本号跳号(USE-005) +- ❌ 跨文档借用前缀、复用已存在编号(USE-004) +- ❌ AI 跳过 `AGENTS.md` 索引、简单任务一次性加载全部 11 份文档(USE-001) +- ❌ 专题文档缺失五要素章节之一(USE-003) + +### ArkTS 语法(ARK)— `rules/01-arkts-grammar.md` + +- ❌ `any` / `unknown` 与 `as unknown as T` 双重断言(ARK-001) +- ❌ 未标注类型的对象字面量、内联对象字面量类型(ARK-002、ARK-003) +- ❌ 任何形式的解构:声明/赋值/参数(ARK-004) +- ❌ 结构化类型兼容("API 等价即可互赋")(ARK-005) +- ❌ 函数表达式、函数内声明函数、生成器(ARK-006) +- ❌ 索引签名与非 Record 索引访问(ARK-007) +- ❌ 交叉/映射/条件类型、四种之外的 utility 类型(ARK-008) +- ❌ 省略无法推断的泛型实参与关键返回类型(ARK-009) +- ❌ `` 转换语法、抛出非 Error、catch 标类型(ARK-010) +- ❌ delete / in / for..in / with / var / #私有字段 / 构造器参数属性 / 静态方法 this / @ts-ignore(ARK-011) +- ❌ import 不置顶、require / export = 语法、未经验证的 @ohos/@kit 导入路径(ARK-012) + +### 组件与状态管理(UI)— `rules/02-arkui-and-state-management.md` + +- ❌ 同一组件混用 V1/V2 装饰器(UI-003) +- ❌ V2 组件用 `$$`、V1 组件用 `!!`(UI-004) +- ❌ @ObservedV2 类漏 @Trace 期望深层刷新(UI-005、UI-007) +- ❌ 子组件直接修改 @Param 传入数据(UI-008) +- ❌ 编造组件属性方法/事件签名/枚举成员(UI-006) +- ❌ 给 @Param 传非状态变量并期望其变化触发刷新(UI-008) +- ❌ 新项目默认选 V1 状态管理(UI-001) +- ❌ 期望 AppStorage 与 AppStorageV2 数据互通(UI-002) + +### 分层架构(ARCH)— `rules/03-architecture-and-project-structure.md` + +- ❌ 公共能力层反向依赖上层、同层循环依赖(ARCH-002) +- ❌ 纯代码复用选 HSP / 多 HAP 共享选 HAR(选型错配)(ARCH-003) +- ❌ HAR 声明 UIAbility(ARCH-005) +- ❌ HSP/HAR 转换漏删 pages、漏改 type、漏换构建脚本(ARCH-004) +- ❌ 跨模块路由跳转 `type: "feature"` 模块(ARCH-004) +- ❌ 业务专有逻辑落入 commons 层(ARCH-006) +- ❌ 数据模型多处重复定义、定义不导出(ARCH-007) +- ❌ 单 Entry 起步项目无 features/commons 层间目录、依赖方向不可审查(ARCH-008) +- ❌ 未出现官方拆分信号(多 UIAbility/按需加载/多设备形态/跨应用共享)前预先拆 HAR/HSP(ARCH-008) + +### Navigation 路由(NAV)— `rules/04-navigation.md` + +- ❌ 新代码使用 router API 管理跳转(NAV-001) +- ❌ router 与 Navigation 双路由栈混用(三方 SDK 场景除外且按官方模式)(NAV-002) +- ❌ 从 NavDestination 直接 router 跳转另一 NavDestination(NAV-002) +- ❌ 跳转目标未注册路由表/未配 navDestination 映射(NAV-003) +- ❌ 跨模块跳转目标模块 type 为 feature(NAV-003) +- ❌ 子页面自行 new NavPathStack()(NAV-004) +- ❌ NavDestination 依赖 onPageShow/onPageHide(NAV-005) +- ❌ AppStorageV2 路由传参用非 class 类型(NAV-006) + +### 网络与后端对接(NET)— `rules/05-network-and-backend.md` + +- ❌ 未声明 ohos.permission.INTERNET 发请求(NET-001) +- ❌ 请求结束(成功/失败)不 destroy()(NET-002) +- ❌ 只判请求返回不判 responseCode(NET-004) +- ❌ 响应模型字段名与契约 JSON 键名不一致(含大小写)(NET-005) +- ❌ 未判空访问 data/rows 可空层级(NET-005、NET-006) +- ❌ rows.length 冒充分页总数(NET-006) +- ❌ 业务代码散拼 Authorization、401 无限刷新重放(NET-007) +- ❌ 少量请求滥用 TaskPool(NET-008) +- ❌ token 等敏感信息入日志(NET-007、LOG-005) + +### 数据持久化(DATA)— `rules/06-data-persistence.md` + +- ❌ preferences.put 后不 flush()(DATA-002) +- ❌ Preferences 存敏感数据、跨多进程使用(DATA-001) +- ❌ PersistentStorage 存嵌套对象或 >2KB 数据(DATA-001、DATA-006) +- ❌ RDB 循环单条 insert 替代 batchInsert(DATA-004) +- ❌ 频繁数据库操作在 UI 主线程执行(DATA-004) +- ❌ RDB 并发多写、单条数据 >2M(DATA-003) +- ❌ JSON 解析未判空直访深层字段(DATA-005) + +### 性能优化(PERF)— `rules/07-performance.md` + +- ❌ 千条级以上/持续增长数据源 ForEach 全量渲染(PERF-002) +- ❌ LazyForEach 数据源不实现 IDataSource 四方法(PERF-003) +- ❌ 数据变更绕过 DataChangeListener 直接改数组(PERF-003) +- ❌ 索引作列表键、依赖默认 JSON.stringify 键(PERF-008) +- ❌ Visibility.None 常驻隐藏大段永不展示内容(PERF-005) +- ❌ 高频显隐切换用 if 反复创建销毁(PERF-005) +- ❌ 小数据量静态列表强用 LazyForEach(PERF-001) +- ❌ 长列表交付跳过五段优化自查(PERF-007) + +### 日志与错误处理(LOG)— `rules/08-logging-and-error-handling.md` + +- ❌ 生产代码 console.log/info/warn/error(LOG-002) +- ❌ 打印隐私信息、敏感字段明文 %{public}(LOG-005) +- ❌ 高频正常流程打印、重复日志不限频(LOG-006) +- ❌ 调试日志提交代码仓(LOG-006) +- ❌ 超长内容整段打印(>4096 字节截断)(LOG-006) +- ❌ 日志语句中调用业务接口函数(LOG-005) +- ❌ 向用户直接展示系统错误码/原始异常(LOG-007) +- ❌ 中文/超 31 字节 tag、domain 魔法数字散落(LOG-004) + +### API 验证(APIV)— `rules/09-api-verification.md` + +- ❌ 跳过 search→read 两步直接书写 @ohos/@kit 调用(APIV-001) +- ❌ 使用未经核对的模块/方法/参数/枚举/导入路径(APIV-002) +- ❌ 无法验证时凭记忆/习惯/类推使用(APIV-003) +- ❌ 编造便捷方法/链式方法/Kit 名/导出成员(APIV-004、APIV-005) +- ❌ 其他平台 API 习惯直接映射鸿蒙 API 名(APIV-005) + +--- + +## 五、开发总检查清单 + +### A. 开发自查(提交前逐项勾选) + +**语法与类型** +- [ ] 全文无 any/unknown/双重断言;对象字面量均有类型上下文(ARK-001~003) +- [ ] 无解构、无结构化类型、无索引签名、无 ARK-011 动态特性(ARK-004、ARK-005、ARK-007、ARK-011) +- [ ] 泛型实参与 async 返回类型显式;转换用 as、抛错用 Error(ARK-009、ARK-010) +- [ ] @ohos/@kit 导入全部经 09 文档两步验证(ARK-012、APIV-001) + +**组件与状态** +- [ ] 新组件为 @ComponentV2 体系,无 V1/V2 混用(UI-001、UI-003) +- [ ] 双向绑定语法与体系匹配(V2 !! / V1 $$)(UI-004) +- [ ] 组件属性/事件/枚举签名与 API 参考一致(UI-006) +- [ ] 父子传参 @Param 单向 + @Event 回传(UI-008) + +**架构与路由** +- [ ] 模块依赖自上而下,无反向/循环依赖(ARCH-002) +- [ ] 单 Entry 起步项目以 features/commons 目录模拟分层且 import 单向;拆包决策对照四类官方信号(ARCH-008) +- [ ] 新页面全部 Navigation 体系且目标页已注册路由表(NAV-001、NAV-003) +- [ ] 子页面路由栈来自 onReady/@Consume 注入(NAV-004) +- [ ] 显隐逻辑用 onShown/onHidden/onNavBarStateChange(NAV-005) + +**网络与数据** +- [ ] module.json5 已声明 INTERNET 权限(NET-001) +- [ ] 请求 createHttp→request→destroy(finally)完整(NET-002) +- [ ] 响应模型与契约逐字段一致;可空层级逐层判空;分页取 rows+total(NET-005、NET-006) +- [ ] Preferences 写入带 flush;批量写库用 batchInsert + TaskPool(DATA-002、DATA-004) + +**性能与日志** +- [ ] 千条级以上数据源用 LazyForEach + IDataSource,变更走通知(PERF-002、PERF-003) +- [ ] 列表键值用稳定业务键(PERF-008) +- [ ] 生产日志全走 hilog,domain/tag 集中定义,无 console.*(LOG-001、LOG-002、LOG-004) +- [ ] 敏感字段 %{private}s;批量操作三类日志齐备(LOG-005、LOG-007) + +### B. Code Review(评审逐项核对) + +- [ ] 红线 10 条(`AGENTS.md`)零违反:编造 API / any / V1V2 混用 / 组件签名 / router 混用 / INTERNET / 契约漂移 / console.log / ForEach 滥用(APIV-004、ARK-001、UI-003、UI-006、NAV-002、NET-001、NET-005、LOG-002、PERF-002) +- [ ] 抽查 2~3 个 @ohos/@kit 调用可经 `devecocli docs read` 复核(APIV-002) +- [ ] 状态装饰器、双向绑定语法、枚举成员逐个比对官方文档(UI-004、UI-006) +- [ ] 跳转 name 与路由表注册名逐字一致(NAV-003) +- [ ] 错误处理三分支齐备(网络异常/超时/非 2xx),用户提示友好(NET-004、LOG-007) +- [ ] 空数据/边界分支显式处理(空数组、null data、首帧时序)(NET-005、DATA-005、UI-005) +- [ ] 高频路径与主线程无重活(日志、数据库、批量请求)(LOG-006、DATA-004、NET-008) +- [ ] 踩坑改动已按 USE-005 四要素沉淀到对应专题文档(USE-005) diff --git a/spec/feature.json b/spec/feature.json new file mode 100644 index 0000000..41b5e09 --- /dev/null +++ b/spec/feature.json @@ -0,0 +1,3 @@ +{ + "feature_directory": "spec/harmony-code-rules" +} diff --git a/spec/harmony-code-rules/plan.md b/spec/harmony-code-rules/plan.md new file mode 100644 index 0000000..fbe5588 --- /dev/null +++ b/spec/harmony-code-rules/plan.md @@ -0,0 +1,208 @@ +# Implementation Plan: 鸿蒙应用开发规则约束体系(harmony-code-rules) + +**Input**: Feature specification from `spec/harmony-code-rules/spec.md` + +## Summary + +为 Gitea 模板仓库 HarmonyTemplate 构建"约束 AI 编码助手"的鸿蒙开发规则体系:根目录 `AGENTS.md` 入口(核心红线 + 规则索引 + 强制工作流)+ `rules/` 目录 11 份编号专题规则文档。方法论移植自 LIMS 规则五大模式(分层规范、禁止事项、✅/❌ 正误对照、API 存在性验证、版本化踩坑沉淀);全部技术内容基于 HarmonyOS 官方文档(devecocli docs 本地库)验证并标注 documentId 依据。本 feature 为**纯文档工程**,不涉及 ArkTS 源码生成。 + +## Technical Context + +**Language/Version**: Markdown(GitHub Flavored);规则内容面向 HarmonyOS ArkTS(API 12+ 基准,标注适用版本) +**Primary Dependencies**: HarmonyOS 官方文档本地库(devecocli docs:harmonyos-guides / harmonyos-references / best-practices / harmonyos-faqs 四目录) +**State Management**: N/A(文档工程;规则内容本身覆盖状态管理 V1/V2 双体系选型与混用禁令) +**Storage**: 仓库内 markdown 文件(无运行时存储) +**Testing**: 文档审查——结构完整性检查(五要素齐全率)+ 官方依据真实性抽查(documentId 可检索) +**Target Platform**: AI 编码助手(DevEco Code / Claude Code 等 AGENTS.md 约定兼容工具)+ 人类开发者 +**Project Type**: 文档工程(Gitea 模板仓库的规则体系组成部分) +**Performance Goals**: SC-005 规则定位 < 30 秒;AGENTS.md 体积受控(红线+索引+工作流,避免上下文膨胀) +**Constraints**: 中文撰写;每份专题文档五要素齐全率 100%;引用 API 编造率 0%;不生成任何 web URL(官方依据用 documentId 标注) +**Scale/Scope**: 12 个 markdown 文件(1 入口 + 11 专题)+ README.md 小幅更新 + +## Project Structure + +### Documentation (this feature) + +```text +spec/harmony-code-rules/ +├── spec.md # 需求规格(已完成) +├── plan.md # 本文件(/spec-plan 命令输出) +└── tasks.md # 任务拆解(/spec-tasks 命令输出) +``` + +### Source Code (repository root) + +> 本 feature 为纯文档工程,无 ArkTS 源码交付。交付物为文档树: + +```text +{PROJECT_ROOT}/ +├── AGENTS.md # AI 编码助手入口:核心红线 + rules/ 索引 + 强制工作流 +├── README.md # 更新:追加"规则体系"章节,指引 AI/人加载规则 +└── rules/ + ├── 00-usage-and-update.md # 规则使用说明 + 版本化踩坑沉淀流程(对应 LIMS 更新记录机制) + ├── 01-arkts-grammar.md # ArkTS 语法约束(arkts-no-* 映射 + TS→ArkTS 改写模式) + ├── 02-arkui-and-state-management.md # ArkUI 组件与状态管理(V1/V2 选型、混用禁令) + ├── 03-architecture-and-project-structure.md # 分层架构与工程结构(三层架构、HAR/HSP、目录组织) + ├── 04-navigation.md # Navigation 路由规范(NavPathStack、路由表、router 禁令) + ├── 05-network-and-backend.md # 网络与企业级后端对接(HTTP/RCP、契约一致、分页、token) + ├── 06-data-persistence.md # 数据持久化(Preferences/KV/RDB 选型决策树、JSON 解析容错) + ├── 07-performance.md # 性能优化(LazyForEach、渲染范围控制、组件复用) + ├── 08-logging-and-error-handling.md # 日志与错误处理(HiLog 分级、TAG 规范、统一错误处理) + ├── 09-api-verification.md # API 存在性验证(devecocli docs 强制工作流、禁止编造条款) + └── 10-prohibited-and-checklist.md # 禁止事项汇总(按主题分类)+ 开发检查清单 +``` + +**Structure Decision**: 本 feature 为文档工程,不适用 Trivial/Light/MVVM 代码结构分层(无 ArkTS 源码目录、无 entry/src/main/ets 结构)。交付物为 12 个 markdown 文件 + README 更新,文件数与 spec FR-002 的 11 个专题领域一一对应(00~10)+ 1 个 AGENTS.md 入口。文档树采用"入口与详细规则松耦合"设计:AGENTS.md 仅含红线/索引/工作流,rules/ 各专题文档相互独立可单独加载(满足 Edge Case:入口被重写后 rules/ 仍可用;单文档过大时可按需加载)。 + +## Complexity Tracking + +> 无 Constitution 违规,无需填写。 + +## Research & Decisions + +### D1: 入口文件选 AGENTS.md(而非 CLAUDE.md / .cursorrules) + +- **Decision**: 根目录单入口 `AGENTS.md`,README.md 追加指引章节。 +- **Rationale**: AGENTS.md 是跨工具通用约定(DevEco Code、Claude Code、主流 AI 编码工具均支持自动读取项目根目录);模板仓库实例化的新项目自动携带;单入口避免多文件内容漂移。 +- **Alternatives considered**: CLAUDE.md(仅 Claude Code 系工具识别,通用性弱);.cursor/rules/(Cursor 专有);多入口并存(维护成本高、内容易失同步)。 + +### D2: 状态管理规范采用"V2 优先 + 存量保留 + 严禁混用"三原则 + +- **Decision**: 新建项目(0→1)推荐状态管理 V2(@ComponentV2/@Local/@Param/@ObservedV2/@Trace/@Monitor/@Provider/@Consumer/AppStorageV2);存量代码保持既有 V1 选型不做强制迁移;同一组件树内严禁 V1/V2 混用。 +- **Rationale**: 官方 FAQ(faqs-arkui-885)确认 V1/V2 并存且 V2 提供深度观测/属性级更新增强;FAQ 记录大量混用陷阱(faqs-arkui-1059 @Param vs @Prop/@Link 语义差异、faqs-arkui-1076 @Monitor 限制)。规则需覆盖:V2 类组件内禁止使用 V1 装饰器(@Component 内不可用 @Local)、@Monitor 替代 @Watch 的迁移注意点、$$(V1)与 !!(V2)双向绑定语法差异。 +- **Alternatives considered**: 只写 V1(官方已主推 V2,新项目会踩坑);强制全量迁移 V2(违反官方"增量保留"建议,破坏存量项目)。 + +### D3: 分层架构规范以官方"分层架构设计"最佳实践为基准 + +- **Decision**: 采纳官方三层模型——产品定制层 / 基础特性层 / 公共能力层(依据:bpta-layered-architecture-design、bpta-app-architecture-overview),结合 HAR/HSP 选型规则(HAR 静态共享包用于纯代码复用;HSP 动态共享包用于代码+资源+C++库共享、多 HAP 共享场景;依据:faqs-package-structure-5)。 +- **Rationale**: 官方最佳实践与"一次开发多端部署"理念一致;HAR/HSP 误用是高频工程化错误(HSP 含页面需改命名路由、HAR 不能声明 UIAbility 等,依据:faqs-project-management-6/7、faqs-ability-153)。 +- **Alternatives considered**: 自创分层模型(脱离官方体系,失去依据可验证性);仅写目录结构不写分层职责(无法约束 AI 乱放文件)。 + +### D4: 网络规范以 @ohos.net.http 为基线、RCP 为进阶,强制契约一致条款 + +- **Decision**: 网络规范包含:ohos.permission.INTERNET 权限声明强制(依据:faqs-network-6);HTTP 响应解析基线(业务数据在 data.result,依据 faqs-network-6);TaskPool 决策标准(大量请求+耗时数据处理才用 TaskPool,否则不用,依据 faqs-arkts-134);RCP(Remote Communication Kit)作为复杂场景进阶方案(依据 faqs-remote-communication-16)。企业级后端对接章节移植 LIMS 契约一致规范:响应模型字段名与 JSON 键名严格匹配(含大小写)、分页结构(rows/total 层级)处理、统一错误处理、token 鉴权管理。 +- **Rationale**: LIMS 最高频线上 Bug 均源于契约不一致(字段名大小写、分页层级、参数名),此为方法论移植的直接映射;权限遗漏与响应层级误用是 HarmonyOS 网络开发高频错误(官方 FAQ 多条印证)。 +- **Alternatives considered**: 仅写三方库 axios 封装(脱离官方基线,且第三方库版本演进快易过时);不写 TaskPool 决策(AI 会过度或欠缺使用并发)。 + +### D5: 日志规范强制 HiLog 优先、禁用 console.log 用于生产代码 + +- **Decision**: 生产代码使用 hilog(自定义业务领域域/TAG/级别);console.log 仅限临时调试。日志五级使用标准(DEBUG/INFO/WARN/ERROR/FATAL)对齐官方定义;批量操作日志模式(移植 LIMS:批量前记总数、失败逐条记原因、完成后汇总统计)。 +- **Rationale**: 官方明确 console.log 是 hilog 的固定默认参数封装(TAG 固定 JSApp,依据 faqs-performance-analysis-kit-24),生产环境无法按模块过滤;LIMS 的批量日志模式是被验证的排查利器。 +- **Alternatives considered**: 允许 console.log(与官方建议冲突)。 + +### D6: 持久化选型采用官方四方案决策树 + +- **Decision**: 规则以决策树呈现——轻量键值配置用 Preferences;分布式数据同步用 KV-Store;复杂关系数据用 RDB(RelationalStore,SQLite);PersistentStorage 特定于与 AppStorage 联动的持久化场景(依据:faqs-local-database-management-53、data-persistence-by-rdb-store)。附加:RDB 大数据量写库须参考官方批量写入建议,避免卡顿。 +- **Rationale**: 官方 FAQ 明确四方案适用场景差异,选型错误是典型返工源;JSON 解析容错(空值检查、类型映射)并入本主题(对应 LIMS 数组 null 检查经验)。 +- **Alternatives considered**: 只写 RDB 单方案(轻量场景过度设计)。 + +### D7: Navigation 规范强制"新项目统一 Navigation、禁止 router 混用" + +- **Decision**: 新项目路由统一使用 Navigation + NavDestination + NavPathStack 体系;禁止与 router API 混用(混用导致 onPageShow 生命周期不触发、来源判断复杂等问题,依据:faqs-arkui-710、faqs-arkui-504);路由表/目标页注册缺失导致白屏的排查条款(依据:faqs-arkui-415);V2 场景下 @Provider/@Consumer 与 AppStorageV2 的路由传参模式(依据:faqs-arkui-1658)。 +- **Rationale**: 官方将 Navigation 定位为推荐路由容器,router 为兼容存量;AI 生成代码混用两套 API 是高频错误,从严禁令可直接防住。 +- **Alternatives considered**: 允许混用(官方 FAQ 有混用方案,但复杂度高、陷阱多,不适合作为默认规则)。 + +### D8: 性能规范聚焦"数据源 + 渲染范围 + 复用"三大官方优化主线 + +- **Decision**: 性能规则覆盖:LazyForEach 懒加载(IDataSource 规范、与 ForEach 选型标准,依据 bpta-lazyforeach-optimization);渲染范围控制(if 与 Visibility.None 的阶段差异及误用性能问题,依据 bpta-control-rendering-range);长列表/Grid/Swiper/瀑布流场景优化要点(依据 bpta-best-practices-long-list 等系列最佳实践)。 +- **Rationale**: 渲染性能是移动端第一性能瓶颈,官方最佳实践已形成完整体系;AI 默认生成 ForEach 全量渲染,需要明确规则强制大数据场景用 LazyForEach。 +- **Alternatives considered**: 罗列所有性能条目(文档膨胀,按需加载原则下应聚焦高频场景)。 + +### D9: API 存在性验证工作流(两步验证 + 降级策略) + +- **Decision**: 强制工作流——(1) `devecocli docs search <关键词>` 定位候选文档;(2) `devecocli docs read ` 核对 API 签名/参数/导入路径后方可使用。(3) 无法验证存在性的 API 一律不得使用(改用已验证替代方案或向用户明示不确定)。三类验证对象:@ohos.*/@kit.* 接口存在性、参数签名准确性、Kit 导入路径正确性。此规则同时写入 AGENTS.md 核心红线。 +- **Rationale**: 直接移植 LIMS"使用任何框架方法前必须先在项目中搜索确认其存在性"教训(其 v3.11 记录:编造 Gikam.postJson 导致运行时报错);AI 编造 API 是最高频严重错误;devecocli docs 是环境内置的可执行验证手段,规则具备可操作性。 +- **Alternatives considered**: 仅要求"参考官方文档"(无强制可执行步骤,AI 会跳过);要求联网查询(环境不保证网络,本地 docs 库已覆盖)。 + +### D10: 版本化踩坑沉淀机制(文档级 semver + 统一更新记录格式) + +- **Decision**: 每份专题文档顶部维护"更新记录"区块;新踩坑经验以 `vX.Y (日期) - 摘要` 条目追加,必含四要素:问题背景 / 根因分析 / 修复模式(✅/❌ 对照)/ 涉及规则条目回链。规则体系整体版本与单文档版本并存。 +- **Rationale**: LIMS 规则文档的生命力验证了该机制(v3.8~v3.17 全部由实际踩坑驱动,含框架 Bug 记录如 MatchPattern.IN);四要素格式保证沉淀质量,避免只记现象不记根因。 +- **Alternatives considered**: 独立 CHANGELOG 文件(与规则条目分离,查阅需跨文件跳转);无版本机制(规则僵化,无法演进)。 + +### D11: 官方依据标注格式统一使用 documentId(禁 web URL) + +- **Decision**: 规则条目标注官方依据时使用 devecocli docs 的 documentId 全路径(如 `开发指南/学习ArkTS语言/从TypeScript到ArkTS的适配指导/从TypeScript到ArkTS的适配规则/typescript-to-arkts-migration-guide`),并说明可通过 `devecocli docs read` 复核;禁止构造任何 web URL。 +- **Rationale**: documentId 是本地文档库的可检索稳定标识,与环境验证手段一致;符合输出红线(不生成/猜测 URL)。 +- **Alternatives considered**: 标注网页链接(违反红线且易失效)。 + +## Data Model + +> 文档工程的"数据模型"= 文档结构与内容单元的标准化定义。 + +### 实体 1: AGENTS.md 入口(三段式) + +| 组成部分 | 内容约束 | +|---|---| +| 核心红线 | 8~10 条,每条一行式强禁令(含 API 禁编造、V1/V2 禁混用、router 禁混用、权限必声明、契约必匹配等),可直接约束代码生成 | +| 规则索引 | rules/00~10 逐份列出:文件名 + 一句话主题摘要 + 对应规则编号前缀 | +| 强制工作流 | API 验证两步流程(search→read)、按需加载规则流程(先索引后专题)、踩坑沉淀流程(指向 00 文档) | + +### 实体 2: 专题规则文档(五要素统一结构,FR-003) + +| 要素 | 定义 | +|---|---| +| 1. 更新记录 | 版本条目列表,每条含版本号/日期/摘要(详见实体 4) | +| 2. 规范条目 | 规则编号 + 描述 + 官方依据(documentId)+ 适用版本 + ✅/❌ 对照示例 | +| 3. 正误对照 | 每条重要规则附 `✅ 正确` / `❌ 错误` 代码对照(ArkTS 代码块) | +| 4. 禁止事项 | 本主题 ❌ 条目集中列表 | +| 5. 检查清单 | `- [ ]` 可勾选条目,供开发/CR 逐项核对 | + +### 实体 3: 规则条目(最小规则单元) + +| 字段 | 规则 | +|---|---| +| 规则编号 | 文档前缀 + 三位序号(见编号体系) | +| 规则描述 | 一句话可判定表述(MUST/MUST NOT/SHOULD 级别词) | +| 官方依据 | documentId 全路径,可 `devecocli docs read` 复核 | +| 对照示例 | ✅/❌ ArkTS 代码块(允许在规则文档中出现示例代码——文档即交付物) | +| 适用版本 | API/SDK 版本范围标注 | + +**规则编号体系**:00=USE(使用与更新)、01=ARK(ArkTS 语法)、02=UI(ArkUI 与状态管理)、03=ARCH(架构与工程结构)、04=NAV(路由)、05=NET(网络与后端)、06=DATA(持久化)、07=PERF(性能)、08=LOG(日志与错误)、09=APIV(API 验证)、10=GEN(通用禁止与清单)。示例:`ARK-001`、`NET-003`。 + +### 实体 4: 更新记录条目(踩坑沉淀单元) + +| 字段 | 规则 | +|---|---| +| 版本号 | 文档内递增 `vX.Y` | +| 日期 | YYYY-MM-DD | +| 问题背景 | 现象描述(何种错误/何种场景) | +| 根因分析 | 技术根因(对应 LIMS"根本原因"模式) | +| 修复模式 | ✅/❌ 对照 + 涉及规则条目编号回链 | + +## Contracts & Interfaces + +> 文档间契约:保证 AGENTS.md 与 rules/ 松耦合但引用一致。 + +### C1: AGENTS.md ↔ rules/ 索引契约 + +- AGENTS.md 索引必须覆盖 rules/ 下全部 11 份文档,逐份含:相对路径、主题摘要、规则编号前缀。 +- 索引使用相对路径(`rules/01-arkts-grammar.md`),不使用绝对路径或 URL。 +- 新增/更名 rules/ 文档时必须同步更新 AGENTS.md 索引(写入 00 文档的更新流程)。 + +### C2: 文档命名契约 + +- 格式:`NN-topic.md`,NN 为 00~10 两位数字前缀,保证阅读/加载顺序。 +- 文件名仅用小写字母与连字符(kebab-case),不含中文与空格。 + +### C3: 官方依据引用契约 + +- 全部专题文档引用官方文档时统一使用 documentId 全路径标注。 +- AGENTS.md 红线条目可省略依据标注(保持精简),但对应专题文档中必须存在带依据的完整条目。 + +### C4: README.md 更新契约 + +- README.md 追加"开发规则体系"章节:说明 AGENTS.md 入口作用、rules/ 目录结构、对 AI 编码助手与人类开发者的使用指引(覆盖 Edge Case:AI 不支持 AGENTS.md 约定时人工加载)。 + +### C5: 禁止事项汇总契约(10 号文档) + +- `10-prohibited-and-checklist.md` 必须汇总各专题文档的禁止条目(按主题分组,引用规则编号而非复制全文,避免两处维护漂移)。 +- 总检查清单必须与各专题文档的检查清单保持编号引用关系。 + +## 与 spec 的对齐说明(非独立章节,并入 Changelog 逻辑) + +FR-001→D1(AGENTS.md 入口)、FR-002→Project Structure 文档树(11 份一一对应)、FR-003→Data Model 实体 2(五要素)、FR-004→D11(documentId 标注)、FR-005→D9(API 验证工作流)、FR-006→D4(网络契约一致)、FR-007→D10(版本化沉淀)、FR-008→C5(禁止汇总契约)、FR-009→lims/ 已移除(前置动作完成)、FR-010→D2(含 arkts-no-* 映射所在 01 文档规划)、FR-011→D3(分层与模块化)。成功标准映射:SC-003→实体 2、SC-004→C3/D11、SC-005→实体 3 编号体系与 C1/C2 契约。 + +## Changelog + +- **2026-09-08**: 初版生成。基于 spec/harmony-code-rules/spec.md(含 lims/ 移除调整)与 9 轮 devecocli docs 官方文档验证(语法/状态管理/架构/路由/网络/持久化/性能/日志/模块化)产出 11 项研究决策、4 类文档实体、5 项文档间契约。 diff --git a/spec/harmony-code-rules/spec.md b/spec/harmony-code-rules/spec.md new file mode 100644 index 0000000..fcb6f9f --- /dev/null +++ b/spec/harmony-code-rules/spec.md @@ -0,0 +1,158 @@ +# Feature Specification: 鸿蒙应用开发规则约束体系(harmony-code-rules) + +**Created**: 2026-09-08 +**Status**: Draft +**Input**: User description: "lims 文件夹中, 是一个企业级的 java web 应用的一些规则, 请你基于这些规则, 再结合HarmonyOS的官方文档, 制定一下开发鸿蒙应用的规则约束."(后续澄清:用途=约束 AI 编码助手;结构=多文档拆分;范围=全部核心领域+工程化+API验证+企业级后端对接;位置=根目录 AGENTS.md + rules/;lims/ 目录移除、不保留作方法论参考源) + +## Overview + +为 Gitea 模板仓库 HarmonyTemplate 制定一套**约束 AI 编码助手**的鸿蒙(HarmonyOS ArkTS)应用开发规则体系。规则方法论移植自某企业级 Java Web 应用(LIMS)的规则文档(分层规范、禁止事项、✅/❌ 正误对照、API 存在性验证、版本化踩坑沉淀五大模式,已完成提炼内化,原 lims/ 参考目录已从仓库移除),技术内容基于 HarmonyOS 官方文档验证。交付物为根目录 `AGENTS.md` 入口文件 + `rules/` 目录多文档专题规则,使每个从模板实例化的新项目自动获得 AI 编码约束。 + +## User Scenarios & Testing *(mandatory)* + +### User Story 1 - AI 编码助手自动发现并加载规则入口 (Priority: P1) + +当一个 AI 编码助手(DevEco Code / Claude Code 等)在从 HarmonyTemplate 模板实例化的新项目中启动会话时,自动发现项目根目录的 `AGENTS.md` 入口文件,读取核心红线与规则索引,并在后续代码生成中遵循这些约束。 + +**Why this priority**: 入口文件是整个规则体系生效的前提;没有自动发现机制,所有详细规则都形同虚设。 + +**Independent Test**: 在模板仓库根目录放置 AGENTS.md 后,任何支持该约定的 AI 编码助手启动会话时能正确引用其中至少一条核心红线(如"禁止编造 @ohos API")。 + +**Acceptance Scenarios**: + +1. **Given** 一个从 HarmonyTemplate 实例化的新项目, **When** AI 编码助手启动会话, **Then** 它自动读取根目录 AGENTS.md 并获知核心红线与 rules/ 索引 +2. **Given** AGENTS.md 中的规则索引, **When** AI 需要处理特定主题(如网络请求), **Then** 它能按索引定位到 rules/ 下对应专题文档并加载详细规则 + +--- + +### User Story 2 - AI 生成 ArkTS 代码时遵循语法与状态管理约束 (Priority: P1) + +AI 编码助手生成 ArkTS/ArkUI 代码时,遵循语法约束(arkts-no-* 规则映射)、状态管理规范(V1/V2 选型与混用禁令)、组件使用规范,产出可编译、符合官方规范的代码。 + +**Why this priority**: ArkTS 语法约束直接决定生成代码能否通过编译,是最基础的代码质量保障。 + +**Independent Test**: 给 AI 一个典型页面开发任务,其产出代码通过 ArkTS 严格模式检查(无 arkts-no-* 违规)。 + +**Acceptance Scenarios**: + +1. **Given** ArkTS 语法约束规则文档, **When** AI 生成 ArkTS 代码, **Then** 代码不违反任何列明的 arkts-no-* 规则(如不使用 any 类型、不使用对象字面量类型) +2. **Given** 状态管理规范, **When** AI 编写组件, **Then** 不混用 V1/V2 装饰器(如 @Component 中不使用 @Local),状态装饰器选型符合规范 +3. **Given** ArkUI 组件规范, **When** AI 使用组件, **Then** 组件属性、事件写法符合官方 API 签名 + +--- + +### User Story 3 - AI 调用系统 API 前验证存在性 (Priority: P1) + +AI 编码助手使用任何 @ohos.* / @kit.* API 前,必须通过 devecocli docs 或官方文档验证其存在性与正确签名,严禁编造不存在的 API、参数或 Kit 导入路径。 + +**Why this priority**: 移植 LIMS"禁止编造框架方法"的核心教训——编造 API 是 AI 生成代码最高频的严重错误。 + +**Independent Test**: 检查 AI 生成的代码中所有 @ohos/@kit 导入与调用均真实存在于官方 API 参考中。 + +**Acceptance Scenarios**: + +1. **Given** API 存在性验证规则, **When** AI 需要调用系统能力(如网络、存储), **Then** 它先通过 devecocli docs search/read 验证 API 存在与签名 +2. **Given** 某个无法验证存在性的 API, **When** AI 考虑使用它, **Then** AI 不得使用该 API,须改用已验证的替代方案或明示不确定 +3. **Given** Kit 导入路径规范, **When** AI 编写 import 语句, **Then** 导入路径与官方文档一致,不出现编造路径 + +--- + +### User Story 4 - AI 与企业后端对接时遵循契约一致规范 (Priority: P1) + +AI 编码助手开发网络层(HTTP 请求、响应解析、分页处理、鉴权)时,遵循契约一致规范:响应字段与数据模型严格匹配、分页结构正确处理、统一错误处理与 token 管理。 + +**Why this priority**: LIMS 的最高频线上 Bug 均源于前后端契约不一致(字段名大小写、分页结构、参数名),此规范直接防住此类缺陷。 + +**Independent Test**: 给 AI 一份后端 API 响应样例,其产出的数据模型字段名、类型与响应 JSON 完全匹配,空值容错处理完整。 + +**Acceptance Scenarios**: + +1. **Given** 后端返回的 JSON 响应样例, **When** AI 定义数据模型, **Then** 模型字段名与 JSON 键名完全一致(含大小写),类型映射正确 +2. **Given** 分页响应结构(如 rows/total), **When** AI 处理分页数据, **Then** 正确解析数据数组与总数字段,不误用错误层级 +3. **Given** 网络异常/超时/非 2xx 响应, **When** AI 封装网络层, **Then** 有统一错误处理与用户友好提示,不出现未捕获异常 + +--- + +### User Story 5 - 开发者按主题快速检索规则 (Priority: P2) + +人类开发者(或 AI)在 code review、开发遇到疑问时,能通过 rules/ 的编号文档结构快速定位到对应主题的规则条目,包括 ✅/❌ 正误对照示例。 + +**Why this priority**: 规则的可检索性决定其实际使用率,但晚于前四条基础约束。 + +**Independent Test**: 给定一个"懒加载列表"场景,能在 30 秒内通过目录定位到性能优化文档中的对应规则。 + +**Acceptance Scenarios**: + +1. **Given** rules/ 目录的编号专题结构, **When** 开发者需要查某主题规则, **Then** 通过文件名编号即可定位对应文档 +2. **Given** 任一规则条目, **When** 开发者阅读, **Then** 每条重要规则附 ✅ 正确 / ❌ 错误 对照示例 + +--- + +### User Story 6 - 踩坑经验版本化沉淀 (Priority: P2) + +当开发过程中发现新的坑(框架缺陷、API 误用、契约陷阱),能按规则使用与更新文档定义的流程,将经验沉淀为带版本号的新规则条目,保持规则体系持续演进。 + +**Why this priority**: 移植 LIMS 的核心生命力机制(其 v3.8~v3.17 规则全部来自踩坑沉淀),但属于长期维护机制。 + +**Independent Test**: 按更新流程文档演练一次规则更新,产出符合格式的更新记录条目。 + +**Acceptance Scenarios**: + +1. **Given** 一次新的踩坑修复, **When** 开发者按更新流程操作, **Then** 在对应专题文档顶部追加带版本号的更新记录(问题背景/根因/修复模式/正误对照) +2. **Given** 更新后的规则文档, **When** 其他项目成员阅读, **Then** 能通过更新记录理解规则来龙去脉 + +--- + +### Edge Cases + +- AGENTS.md 被实例化项目重写后,rules/ 仍独立可用(入口与详细规则松耦合,rules/ 文档间不相互依赖) +- 单个规则文档过大影响 AI 上下文时,AGENTS.md 索引须支持按需加载(只加载当前任务相关主题) +- 官方 API 随版本演进废弃时,规则文档须标注适用 SDK 版本范围,避免规则本身过时误导 +- AI 助手不支持 AGENTS.md 约定时,README.md 须提供指引入工加载规则 +- 模板仓库本身不含 ArkTS 工程源码,规则为纯文档交付物,不依赖工程构建验证 + +## Requirements *(mandatory)* + +### Functional Requirements + +- **FR-001**: 交付物 MUST 在项目根目录提供 `AGENTS.md` 入口文件,包含:核心红线(精简、可直接约束代码生成)、rules/ 完整索引(含各文档主题摘要)、强制工作流(API 验证流程、规则加载流程) +- **FR-002**: 交付物 MUST 在 `rules/` 目录提供按主题拆分、带编号前缀的专题规则文档,覆盖 11 个领域:00-规则使用与更新机制、01-ArkTS 语法约束、02-ArkUI 组件与状态管理、03-分层架构与工程结构、04-Navigation 路由、05-网络与企业级后端对接、06-数据持久化、07-性能优化、08-日志与错误处理、09-API 存在性验证、10-禁止事项汇总与检查清单 +- **FR-003**: 每份规则文档 MUST 遵循统一结构:更新记录 → 规范条目 → ✅/❌ 正误对照 → 禁止事项 → 检查清单 +- **FR-004**: 所有技术性规则内容 MUST 基于 HarmonyOS 官方文档验证(开发指南/API 参考/最佳实践/FAQ),关键条目标注官方依据 +- **FR-005**: API 存在性验证规则 MUST 定义强制验证流程(devecocli docs search → read)与禁止编造条款,覆盖 @ohos.*/@kit.* 接口、参数签名、Kit 导入路径三类验证对象 +- **FR-006**: 网络对接规范 MUST 覆盖:HTTP 请求封装模式、响应数据模型与 JSON 字段严格匹配(含大小写)、分页结构处理、统一错误处理、token 鉴权管理 +- **FR-007**: 规则体系 MUST 提供版本化更新机制:新踩坑经验以带版本号的更新记录形式追加到对应专题文档,更新记录含问题背景/根因分析/修复模式/正误对照 +- **FR-008**: 禁止事项汇总文档 MUST 按主题分类汇总所有 ❌ 禁止条目,并提供开发检查清单(checklist 形式,可逐项勾选) +- **FR-009**: 仓库 MUST NOT 保留 lims/ 目录;规则方法论已提炼内化,spec 及规则文档中可引用方法论来源但不得依赖该目录存在 +- **FR-010**: ArkTS 语法约束文档 MUST 映射官方 arkts-no-* 规则体系(含强制级别说明),并给出 TS→ArkTS 常见改写模式 +- **FR-011**: 分层架构文档 MUST 定义 ArkTS 工程的标准分层(如 UI 层/业务逻辑层/数据层)、模块划分(HAR/HSP 选型规则)与目录组织规范 + +### Key Entities + +- **AGENTS.md 入口**: AI 自动发现的核心红线 + 规则索引 + 强制工作流,与 rules/ 松耦合 +- **专题规则文档(rules/NN-topic.md)**: 独立可读的单一主题规则集合,含更新记录/规范条目/正误对照/禁止事项/检查清单五要素 +- **规则条目(Rule Item)**: 最小规则单元,含规则描述、官方依据、✅/❌ 对照示例、适用版本 +- **更新记录(Changelog Entry)**: 带版本号的踩坑沉淀记录,含问题背景/根因/修复模式 + +## Success Criteria *(mandatory)* + +### Measurable Outcomes + +- **SC-001**: 从模板实例化新项目后,支持 AGENTS.md 约定的 AI 编码助手无需人工指引即可引用至少 1 条核心红线 +- **SC-002**: 按规则文档生成的典型页面代码通过 ArkTS 严格模式检查,arkts-no-* 违规数为 0 +- **SC-003**: 11 份专题文档全部遵循统一结构(更新记录/规范/正误对照/禁止事项/检查清单,五要素齐全率 100%) +- **SC-004**: 规则文档中引用的每一个 @ohos/@kit API 均可在官方文档中检索到(编造率 0%) +- **SC-005**: 开发者按主题定位规则平均耗时 < 30 秒(通过文件名编号与 AGENTS.md 索引) + +## Assumptions + +- AI 编码助手(DevEco Code 等)遵循 AGENTS.md 约定自动读取项目根目录入口文件 +- 规则文档语言为中文 +- HarmonyOS 官方文档可通过 devecocli docs 本地检索(harmonyos-guides/references/best-practices/faqs 等目录可用) +- LIMS 方法论已在前置分析中完成提炼,移除原文件不影响规则制定 +- 模板仓库当前不含 ArkTS 工程源码(rules 为纯文档交付物),Phase 5 验证以文档审查为主,不涉及构建验证 +- 规则内容以当前稳定版 HarmonyOS API 为基准,标注适用版本范围 + +## Open Questions + +(无——关键歧义已全部通过前置澄清解决:用途=约束 AI 编码助手、结构=多文档拆分、范围=全部核心领域+工程化与模块化+API 验证+企业级后端对接、位置=根目录 AGENTS.md + rules/、lims/=移除不保留) diff --git a/spec/harmony-code-rules/tasks.md b/spec/harmony-code-rules/tasks.md new file mode 100644 index 0000000..14879ea --- /dev/null +++ b/spec/harmony-code-rules/tasks.md @@ -0,0 +1,309 @@ +# Tasks: 鸿蒙应用开发规则约束体系(harmony-code-rules) + +**Input**: Design documents from `spec/harmony-code-rules/` +**Prerequisites**: plan.md(11 项决策 D1~D11、4 类文档实体、5 项契约 C1~C5)、spec.md(6 个 User Story、FR-001~FR-011、SC-001~SC-005) + +**Tests**: 无独立测试任务(纯文档工程,spec 未要求测试框架;验证以文档审查任务 T017~T019 承载)。 + +**Organization**: 任务按 User Story 组织。P1 四个故事中,US2/US3/US4 的交付物是相互独立的专题文档,US1(入口聚合)依赖其完成,故执行顺序为 US2→US3→US4→US1;P2 为 US5→US6。US2 组包含 6 份文档:01/02 直接对应 US2 验收场景(语法/状态管理),03/04/07/08 为 US2"产出符合官方规范的代码"目标的扩展约束域(FR-002 十一域覆盖要求)。 + +**工程类型说明**: 本 feature 为纯文档工程(13 个 Markdown 交付物,无 ArkTS 源码、无可构建工程),spec Assumptions 已确认"Phase 5 验证以文档审查为主,不涉及构建验证"。Verification 阶段无 `build_project`/`start_app` 适用对象,build/deploy 任务以等价的文档验证任务(T017~T019)替代。 + +## Format: `[ID] [P?] [Story] Description` + +- **[P]**: 可并行(不同文件、无未完成依赖) +- **[Story]**: 所属 User Story +- 每条任务描述含确切文件路径与内容要点(提炼自 plan.md 对应决策),LLM 可无需额外上下文直接执行 + +## Path Conventions + +- **本 feature 为纯文档工程**:交付物位于仓库根目录(`AGENTS.md`、`README.md`)与 `rules/` 目录(11 份编号专题文档),不适用 `src/`、`tests/` 约定 +- **rules/ 文件名契约(C2)**:`NN-topic.md`,NN 为 00~10 两位数字前缀(保证加载顺序),topic 仅用小写字母与连字符(kebab-case),不含中文与空格 +- **官方依据标注(D11)**:统一使用 devecocli docs 的 documentId 全路径,禁构造任何 web URL +- **spec/ 目录**:SDD 工作流工件(spec.md/plan.md/tasks.md),非交付物 + +--- + +## Phase 1: Setup(共享基础设施) + +**Purpose**: 确认官方文档检索工具链可用,为全部规则文档的 documentId 依据标注提供验证基础 + +- [X] T001 验证 devecocli docs 本地官方文档库可用性:执行 `devecocli docs catalog` 确认 harmonyos-guides / harmonyos-references / best-practices / harmonyos-faqs 四目录可检索,并抽查 `devecocli docs search` / `devecocli docs read` 链路可用(无文件产出,工具链确认) + +--- + +## Phase 2: Foundational(阻塞性前提) + +**Purpose**: 元规则文档定义统一骨架与编号体系,是全部 11 份专题文档的结构前提 + +**⚠️ CRITICAL**: 未完成 T002 前,任何专题文档不得开工(五要素结构、规则编号、更新记录格式均由 00 文档定义) + +- [X] T002 编写元规则文档,产出 `rules/00-usage-and-update.md`:① 规则体系使用说明(AI 按需加载流程:先读 AGENTS.md 索引→按任务主题加载对应专题文档,人类开发者 review 检索指引);② 统一五要素文档骨架定义(更新记录→规范条目→✅/❌ 正误对照→禁止事项→检查清单,FR-003);③ 规则编号体系定义(USE/ARK/UI/ARCH/NAV/NET/DATA/PERF/LOG/APIV/GEN 前缀+三位序号,plan 实体 3);④ 版本化踩坑沉淀流程定义(vX.Y 条目四要素:问题背景/根因分析/修复模式✅❌对照/涉及条目回链,D10、FR-007);⑤ AGENTS.md 索引同步契约(新增/更名 rules/ 文档必须同步更新索引,C1/C2);⑥ 官方依据标注规范(documentId 全路径、禁 web URL,D11);USE-001 起编号,五要素结构完整,更新记录首条为 v1.0 初始版本 + +**Checkpoint**: 元规则就绪,专题文档可并行开工 + +--- + +## Phase 3: User Story 2 - AI 生成 ArkTS 代码时遵循语法与状态管理约束 (Priority: P1) 🎯 + +**Goal**: 交付 6 份代码约束类专题文档(语法/状态管理/架构/路由/性能/日志),使 AI 生成的 ArkTS 代码可编译、符合官方规范 + +**Independent Test**: 给 AI 一个典型页面开发任务,其产出代码通过 ArkTS 严格模式检查(无 arkts-no-* 违规);状态装饰器不混用 V1/V2;组件属性/事件写法符合官方 API 签名 + +### Implementation for User Story 2 + +- [X] T003 [P] [US2] 编写 ArkTS 语法约束文档,产出 `rules/01-arkts-grammar.md`:arkts-no-* 强制规则映射(禁 any 类型、禁对象字面量类型、禁解构部分场景、禁 structural typing 等,逐条标注强制级别 error/warning,FR-010)、TS→ArkTS 常见改写模式(✅/❌ 对照:类型显式化、class 替代 interface 类型、无类型注解对象字面量初始化等)、@ohos/@kit 导入语句规范(衔接 09 文档验证流程);官方依据用 documentId 标注(typescript-to-arkts 适配指导系列);ARK-001 起编号,五要素齐全 +- [X] T004 [P] [US2] 编写 ArkUI 组件与状态管理文档,产出 `rules/02-arkui-and-state-management.md`:状态管理 V1/V2 双体系装饰器对照表、V2 优先+存量保留+严禁混用三原则(D2)、混用禁令逐条列明(@Component 内禁用 @Local、V2 类组件内禁用 V1 装饰器等)、$$(V1)与 !!(V2)双向绑定语法差异、@Monitor 替代 @Watch 迁移注意点、ArkUI 组件属性/事件签名规范(依据 faqs-arkui-885、faqs-arkui-1059、faqs-arkui-1076);UI-001 起编号,五要素齐全 +- [X] T005 [P] [US2] 编写分层架构与工程结构文档,产出 `rules/03-architecture-and-project-structure.md`:官方三层架构模型(产品定制层/基础特性层/公共能力层,D3,依据 bpta-layered-architecture-design、bpta-app-architecture-overview)、HAR/HSP 选型规则(HAR 静态共享纯代码复用;HSP 动态共享代码+资源+C++库、多 HAP 共享;HSP 含页面命名路由等陷阱,依据 faqs-package-structure-5、faqs-project-management-6/7)、标准目录组织规范(FR-011);ARCH-001 起编号,五要素齐全 +- [X] T006 [P] [US2] 编写 Navigation 路由文档,产出 `rules/04-navigation.md`:Navigation+NavDestination+NavPathStack 统一路由体系、禁止与 router API 混用严令(混用致 onPageShow 不触发等问题,依据 faqs-arkui-710、faqs-arkui-504)、路由表/目标页注册缺失白屏排查条款(依据 faqs-arkui-415)、V2 场景 @Provider/@Consumer 与 AppStorageV2 路由传参模式(依据 faqs-arkui-1658,D7);NAV-001 起编号,五要素齐全 +- [X] T007 [P] [US2] 编写性能优化文档,产出 `rules/07-performance.md`:LazyForEach 懒加载与 IDataSource 数据源规范、ForEach/LazyForEach 选型标准(大数据量必须 LazyForEach,AI 默认生成 ForEach 全量渲染为高频错误,D8,依据 bpta-lazyforeach-optimization)、渲染范围控制(if 与 Visibility.None 阶段差异及误用性能问题,依据 bpta-control-rendering-range)、长列表/Grid/Swiper/瀑布流场景优化要点(依据 bpta-best-practices-long-list 系列);PERF-001 起编号,五要素齐全 +- [X] T008 [P] [US2] 编写日志与错误处理文档,产出 `rules/08-logging-and-error-handling.md`:生产代码强制 HiLog(自定义 domain/TAG/级别)、console.log 仅限临时调试禁入生产(TAG 固定 JSApp 无法按模块过滤,依据 faqs-performance-analysis-kit-24,D5)、日志五级使用标准(DEBUG/INFO/WARN/ERROR/FATAL 对齐官方定义)、批量操作日志模式(批量前记总数/失败逐条记原因/完成后汇总统计,LIMS 方法论移植)、统一错误处理模式(错误码分层/用户友好提示);LOG-001 起编号,五要素齐全 + +**Checkpoint**: 6 份代码约束文档就绪,US2 可独立验收(严格模式检查/状态装饰器选型/组件签名) + +--- + +## Phase 4: User Story 3 - AI 调用系统 API 前验证存在性 (Priority: P1) + +**Goal**: 交付 API 存在性验证规则,杜绝编造 @ohos.*/@kit.* 接口、参数签名、导入路径 + +**Independent Test**: 检查 AI 生成的代码中所有 @ohos/@kit 导入与调用均真实存在于官方 API 参考(devecocli docs 可检索) + +### Implementation for User Story 3 + +- [X] T009 [P] [US3] 编写 API 存在性验证文档,产出 `rules/09-api-verification.md`:强制两步验证工作流(① `devecocli docs search <关键词>` 定位候选文档 → ② `devecocli docs read ` 核对 API 签名/参数/导入路径后方可使用,D9、FR-005)、三类验证对象(@ohos.*/@kit.* 接口存在性、参数签名准确性、Kit 导入路径正确性)、降级策略(无法验证存在性的 API 一律禁用,改用已验证替代方案或向用户明示不确定)、禁止编造条款与典型编造模式示例(LIMS v3.11 编造 postJson 教训的鸿蒙化映射:编造不存在的 @ohos 方法导致运行时报错);APIV-001 起编号,五要素齐全 + +**Checkpoint**: API 验证工作流规则就绪,US3 可独立验收 + +--- + +## Phase 5: User Story 4 - AI 与企业后端对接时遵循契约一致规范 (Priority: P1) + +**Goal**: 交付网络层与数据层规范,防住 LIMS 最高频线上缺陷源(前后端契约不一致) + +**Independent Test**: 给 AI 一份后端 API 响应样例,其产出数据模型字段名、类型与响应 JSON 完全匹配(含大小写),空值容错完整,分页结构解析正确 + +### Implementation for User Story 4 + +- [X] T010 [P] [US4] 编写网络与企业级后端对接文档,产出 `rules/05-network-and-backend.md`:ohos.permission.INTERNET 权限声明强制(遗漏致请求失败,依据 faqs-network-6)、@ohos.net.http 请求封装基线(响应业务数据在 data.result 层级的解析规范,依据 faqs-network-6)、RCP(Remote Communication Kit)复杂场景进阶(依据 faqs-remote-communication-16)、TaskPool 并发决策标准(大量请求+耗时数据处理才用,否则不用,依据 faqs-arkts-134)、企业级契约一致规范(响应模型字段名与 JSON 键名严格匹配含大小写、分页结构 rows/total 层级正确解析、统一错误处理含网络异常/超时/非 2xx、token 鉴权管理与刷新模式,FR-006、D4);NET-001 起编号,五要素齐全 +- [X] T011 [P] [US4] 编写数据持久化文档,产出 `rules/06-data-persistence.md`:四方案选型决策树(轻量键值配置→Preferences;分布式数据同步→KV-Store;复杂关系数据→RDB/RelationalStore;与 AppStorage 联动持久化→PersistentStorage,依据 faqs-local-database-management-53,D6)、RDB 大数据量批量写入规范(参考官方批量写入建议避免卡顿)、JSON 解析容错(空值检查/类型映射/数组 null 防御,LIMS 契约经验映射);DATA-001 起编号,五要素齐全 + +**Checkpoint**: US4 可独立验收(契约匹配/分页解析/空值容错) + +--- + +## Phase 6: User Story 1 - AI 编码助手自动发现并加载规则入口 (Priority: P1) 🎯 MVP 收口 + +**Goal**: 交付 AGENTS.md 入口(核心红线+完整索引+强制工作流)与 README 指引章节,使规则体系可被 AI 助手自动发现加载 + +**Independent Test**: 支持该约定的 AI 编码助手在新项目会话启动时能正确引用至少 1 条核心红线(如"禁止编造 @ohos API"),并按索引定位专题文档 + +**⚠️ 依赖**: T012 需 T003~T011 全部完成(红线须与专题文档规则对齐,索引须覆盖 11 份文档实际主题) + +### Implementation for User Story 1 + +- [X] T012 [US1] 编写 AI 编码助手入口文件,产出 `AGENTS.md`(仓库根目录):① 核心红线 8~10 条一行式强禁令(禁编造 @ohos/@kit API 及导入路径、禁 V1/V2 状态装饰器混用、禁 router 与 Navigation 混用、网络权限必须声明、响应模型字段必须与 JSON 契约严格匹配、生产代码禁 console.log、禁 any 类型等,每条与对应专题文档规则编号对齐,FR-001);② rules/ 完整索引(11 份文档逐份:相对路径+一句话主题摘要+规则编号前缀,C1 契约,相对路径格式 `rules/NN-topic.md`);③ 强制工作流(API 验证两步流程 search→read、按需加载规则流程先索引后专题、踩坑沉淀流程指向 00 文档);红线省略依据标注保持精简(C3 契约,完整带依据条目在各专题文档);体积受控(红线+索引+工作流三段式,避免上下文膨胀) +- [X] T013 [US1] 更新 `README.md`(仓库根目录):追加"开发规则体系"章节——AGENTS.md 入口作用说明、rules/ 目录结构一览(11 份编号文档)、AI 编码助手自动加载说明、AI 助手不支持 AGENTS.md 约定时的人工加载指引(C4 契约,覆盖 spec Edge Case) + +**Checkpoint**: MVP 完整收口——入口+11 份专题文档全部就绪,US1 可独立验收 + +--- + +## Phase 7: User Story 5 - 开发者按主题快速检索规则 (Priority: P2) + +**Goal**: 交付禁止事项汇总与总检查清单,配合编号体系实现 <30 秒主题定位 + +**Independent Test**: 给定"懒加载列表"场景,能在 30 秒内通过 AGENTS.md 索引与文件名编号定位到性能优化文档对应规则 + +### Implementation for User Story 5 + +- [X] T014 [P] [US5] 编写禁止事项汇总与检查清单文档,产出 `rules/10-prohibited-and-checklist.md`:按主题分组汇总全部专题文档的 ❌ 禁止条目(引用规则编号而非复制全文,避免两处维护漂移,C5 契约、FR-008)、开发总检查清单(`- [ ]` 可勾选条目,与各专题文档检查清单保持编号引用关系,覆盖开发自查与 code review 两用途);GEN-001 起编号,五要素齐全 + +**Checkpoint**: US5 可独立验收(编号检索/清单勾选) + +--- + +## Phase 8: User Story 6 - 踩坑经验版本化沉淀 (Priority: P2) + +**Goal**: 通过完整示例更新记录演示沉淀流程闭环,使规则体系具备持续演进能力 + +**Independent Test**: 按更新流程演练一次规则更新,产出符合四要素格式的更新记录条目 + +### Implementation for User Story 6 + +- [X] T015 [P] [US6] 在 `rules/00-usage-and-update.md` 更新流程章节追加完整示例更新记录:按四要素格式(问题背景/根因分析/修复模式含 ✅/❌ 代码对照/涉及规则条目回链)演示一次踩坑沉淀,示例素材可取 LIMS v3.11 编造 API 教训的鸿蒙化场景(AI 编造不存在的 @ohos 方法→运行时报错→根因:未走 09 文档验证流程→修复模式回链 APIV-001);同步将该示例版本号追加至 00 文档更新记录区(FR-007、D10) + +**Checkpoint**: US6 可独立验收(四要素示例完整、流程闭环可演练) + +--- + +## Phase 9: Polish(横切关注点) + +**Purpose**: 全体系交叉一致性校验,消除文档间漂移 + +- [X] T016 交叉一致性校验与修订,涉及 `AGENTS.md`、`README.md` 与 `rules/` 全部 11 份文档:① AGENTS.md 索引与 rules/ 实际文件一一对应(数量 11、相对路径、主题摘要、编号前缀,C1/C2 契约);② 10 号文档引用的每个规则编号在对应专题文档中真实存在(C5 契约);③ AGENTS.md 红线与专题文档规则语义一致(C3 契约);④ README 章节描述与实际目录结构一致(C4 契约);⑤ 全部文档规则编号无冲突、更新记录区版本号递增无跳号;发现漂移即修订对应文件 + +--- + +## Phase 10: Verification + + + +**Purpose**: 文档完整性与准确性验证(纯文档工程,无 build_project/start_app 适用对象,以文档审查替代构建部署,依据 spec Assumptions 与用户 Verification Choice Gate 选择 "Run verification") + +- [X] T017 结构完整性审查:12 份规则交付物(`rules/00-usage-and-update.md` ~ `rules/10-prohibited-and-checklist.md` 共 11 份 + 根目录 `AGENTS.md`)五要素齐全率 100%(更新记录/规范条目/正误对照/禁止事项/检查清单,SC-003)、规则编号体系一致(11 个前缀无混用、三位序号无冲突)、检查清单条目均为 `- [ ]` 可勾选格式 +- [X] T018 官方依据真实性抽查:全部规则文档中标注的 documentId 依据逐一经 `devecocli docs read` 检索确认存在(SC-004);文档中引用的每一个 @ohos/@kit API 名称、参数签名、Kit 导入路径经 `devecocli docs search` 确认真实(编造率 0%,SC-004);全文无任何 web URL(D11) +- [X] T019 场景演练验证:① 按 US5 场景演练主题定位(给定"懒加载列表"场景,经 AGENTS.md 索引+文件名编号定位 `rules/07-performance.md` 对应规则条目,耗时 <30 秒,SC-005);② 按 US1 场景核对核心红线可引用性(至少 1 条红线完整可被 AI 助手引用,SC-001);③ 按 US6 场景演练版本化更新记录追加流程,产出条目符合四要素格式 + +--- + +## Dependencies & Execution Order + +### Phase Dependencies + +- **Setup(Phase 1)**: 无依赖,立即开始(T001) +- **Foundational(Phase 2)**: 依赖 Setup(T001)——**阻塞全部 User Story**(T002) +- **User Stories(Phase 3~8)**: 全部依赖 Foundational 完成;US2/US3/US4 的 9 份专题文档(T003~T011)相互独立可全并行;US1(T012~T013)依赖 T003~T011;US5(T014)依赖 T003~T011;US6(T015)仅依赖 T002 +- **Polish(Phase 9)**: 依赖 T012~T015 全部完成 +- **Verification(Phase 10)**: 依赖 Polish 完成,T017→T018→T019 串行 + +### 📊 Dependency Graph + +```mermaid +graph TD + T001[T001 docs 工具链验证] --> T002[T002 元规则 00 文档] + T002 --> T003[T003 01-语法] + T002 --> T004[T004 02-状态管理] + T002 --> T005[T005 03-架构] + T002 --> T006[T006 04-路由] + T002 --> T007[T007 07-性能] + T002 --> T008[T008 08-日志] + T002 --> T009[T009 09-API验证] + T002 --> T010[T010 05-网络] + T002 --> T011[T011 06-持久化] + T003 --> T012[T012 AGENTS.md 入口] + T004 --> T012 + T005 --> T012 + T006 --> T012 + T007 --> T012 + T008 --> T012 + T009 --> T012 + T010 --> T012 + T011 --> T012 + T012 --> T013[T013 README 更新] + T003 --> T014[T014 10-汇总清单] + T004 --> T014 + T005 --> T014 + T006 --> T014 + T007 --> T014 + T008 --> T014 + T009 --> T014 + T010 --> T014 + T011 --> T014 + T002 --> T015[T015 更新记录示例] + T012 --> T016[T016 交叉一致性校验] + T013 --> T016 + T014 --> T016 + T015 --> T016 + T016 --> T017[T017 结构完整性审查] + T017 --> T018[T018 官方依据抽查] + T018 --> T019[T019 场景演练验证] +``` + +### User Story Dependencies + +- **US2/US3/US4(P1)**: Foundational 完成后即可并行开工,9 份专题文档互不依赖 +- **US1(P1)**: 依赖 US2/US3/US4 的专题文档完成(红线对齐+索引覆盖);README(T013)依赖 AGENTS.md(T012) +- **US5(P2)**: 依赖 US2/US3/US4 的专题文档完成(汇总引用其规则编号);与 US1 的 T012 可并行 +- **US6(P2)**: 仅依赖 T002(00 文档存在);可与 T003~T014 全并行 + +### Within Each User Story + +- 每份专题文档为独立文件,文档内按五要素顺序撰写(更新记录→规范条目→正误对照→禁止事项→检查清单) +- 规范条目先于正误对照(对照依附条目);禁止事项先于检查清单(清单引用禁止条目) + +--- + +## ⚡ Parallel Execution Guide + +| Phase | Tasks | Required Files | Execution Notes | +|---|---|---|---| +| Setup | T001 | (无文件产出) | 单任务先行,确认四目录与 search/read 链路 | +| Foundational | T002 | `rules/00-usage-and-update.md` | 阻塞全部专题文档,必须最先完成 | +| US2 | T003~T008 | `rules/01`~`04`、`07`、`08` 共 6 文件 | 六份文档相互独立,可全部并行 | +| US3 | T009 | `rules/09-api-verification.md` | 与 US2 组并行 | +| US4 | T010~T011 | `rules/05`、`rules/06` | 与 US2/US3 组并行 | +| US1 | T012→T013 | `AGENTS.md`、`README.md` | 需 T003~T011 全部完成;T012→T013 串行 | +| US5 | T014 | `rules/10-prohibited-and-checklist.md` | 需 T003~T011 完成;与 T012 可并行 | +| US6 | T015 | `rules/00-usage-and-update.md` | 仅需 T002;可与 T003~T014 全并行 | +| Polish | T016 | 全部 13 个交付文件 | 需 T012~T015 全部完成 | +| Verification | T017→T018→T019 | 全部 13 个交付文件 | 串行执行,前序产出作为后序输入 | + +--- + +## Parallel Example: 专题文档并行组(T002 完成后) + +```bash +# Foundational(T002)完成后,9 份专题文档可全部同时启动: +Task: "T003 [P] [US2] 编写 ArkTS 语法约束文档,产出 rules/01-arkts-grammar.md" +Task: "T004 [P] [US2] 编写 ArkUI 组件与状态管理文档,产出 rules/02-arkui-and-state-management.md" +Task: "T005 [P] [US2] 编写分层架构与工程结构文档,产出 rules/03-architecture-and-project-structure.md" +Task: "T006 [P] [US2] 编写 Navigation 路由文档,产出 rules/04-navigation.md" +Task: "T007 [P] [US2] 编写性能优化文档,产出 rules/07-performance.md" +Task: "T008 [P] [US2] 编写日志与错误处理文档,产出 rules/08-logging-and-error-handling.md" +Task: "T009 [P] [US3] 编写 API 存在性验证文档,产出 rules/09-api-verification.md" +Task: "T010 [P] [US4] 编写网络与企业级后端对接文档,产出 rules/05-network-and-backend.md" +Task: "T011 [P] [US4] 编写数据持久化文档,产出 rules/06-data-persistence.md" +# US6 的 T015(更新记录示例)亦可同时启动(仅依赖 T002) +# T003~T011 全部完成后,T012(AGENTS.md)与 T014(10-汇总清单)可并行启动 +``` + +--- + +## Implementation Strategy + +### MVP First(T001→T002→T003~T011→T012,共 12 任务) + +1. T001 确认 docs 工具链 → T002 元规则(阻塞项) +2. T003~T011 九份专题文档并行交付 +3. T012 AGENTS.md 入口收口 +4. **STOP and VALIDATE**: 此时规则体系已可被 AI 助手发现加载(US1/US2/US3/US4 四个 P1 故事全部可独立验收) + +### Incremental Delivery + +1. Setup+Foundational → 元规则就绪 +2. +US2/US3/US4 专题文档 → 代码约束、API 验证、契约一致可独立验收 +3. +US1 入口 → MVP 交付(AI 自动发现加载) +4. +US5 汇总清单 → 检索体验完整 +5. +US6 沉淀示例 → 演进机制闭环 +6. Polish 一致性校验 → Verification 文档审查收口 + +--- + +## Summary Report + +| 维度 | 统计 | +|---|---| +| 总任务数 | **19**(T001~T019) | +| Setup | 1(T001) | +| Foundational | 1(T002) | +| User Story 任务 | 13(US1: 2 / US2: 6 / US3: 1 / US4: 2 / US5: 1 / US6: 1) | +| Polish | 1(T016) | +| Verification | 3(T017~T019,build-only 文档审查) | +| 交付文件数 | 13(AGENTS.md + README.md + rules/ 11 份) | +| 最大并行度 | T003~T011 共 9 任务(Foundational 完成后) | +| 每故事独立测试 | US1 红线可引用 / US2 严格模式 0 违规 / US3 API 可检索 / US4 契约匹配 / US5 30 秒定位 / US6 四要素演练 | +| MVP 范围 | T001~T012(12 任务,覆盖 4 个 P1 故事) | + +--- + +## Notes + +- [P] 任务 = 不同文件、无未完成依赖 +- [Story] 标签映射 User Story,便于追溯 +- 每个 User Story 可独立完成与验收(Independent Test 见各故事章节) +- 每完成一个任务或逻辑组提交一次(git commit) +- 可在任意 Checkpoint 停下,独立验收对应故事 +- 避免:模糊任务、同文件冲突、破坏独立性的跨故事依赖 +- Verification 阶段已按用户选择标记 ``,不含 UI 验证任务 +- 格式自检已通过:全部任务以 `- [ ]` 开头、ID 唯一递增(T001~T019)、Story 标签仅出现在 Story 阶段、总数与 Summary Report 一致(19)