diff --git a/.harness/skills/domain-init/SKILL.md b/.harness/skills/domain-init/SKILL.md index 4eb24ad..3e0aea2 100644 --- a/.harness/skills/domain-init/SKILL.md +++ b/.harness/skills/domain-init/SKILL.md @@ -7,7 +7,7 @@ description: >- 触发词:domain-init、领域初始化、生成领域规范、领域扫描 metadata: author: "devkeel" - version: "2.0.2" + version: "2.1.0" --- # Domain Init — 项目领域能力生成器 @@ -31,6 +31,7 @@ metadata: - `references/project-index.md` — 参考项目索引(GitHub 地址 + 参考内容) - `references/output-formats.md` — 产出格式规范 + 质量标准 - `references/domain-matrix.md` — 领域适用性矩阵(8 大领域 × 23 维度) +- `references/architecture-knowledge.md` — 选中 K1,或增强项涉及架构知识时,读取扫描与验收要求 ## 何时使用 @@ -101,6 +102,7 @@ Phase 4: 收尾 → 配置更新 + 链接检查 + 生成报告 | ID | 维度 | 候选产出 | subAgent 职责 | |----|------|------|--------------| +| K1 | 架构知识 | docs | 按 `references/architecture-knowledge.md` 扫描结构、组件归属、通信与关键流程 | | R1 | 编码规范 | rule / docs | 扫描代码风格、格式化配置、lint 规则、导入习惯 | | R4 | 测试策略 | rule / docs | 扫描测试框架、覆盖模式、测试文件组织、mock 策略 | | R5 | 错误处理 | rule / docs | 扫描异常模式、日志使用、错误边界、重试策略 | @@ -111,6 +113,8 @@ Phase 4: 收尾 → 配置更新 + 链接检查 + 生成报告 | R20 | 编辑纪律 | rule / docs | 基于 surgical changes 原则:只改相关代码 | | A1 | 领域 Code Reviewer | agent | 基于以上扫描结果生成专属审查维度和输出规则 | +K1 面向所有领域,按实际代码触点裁剪;是否生成和调查深度仍由下述范围确认决定。 + ### 2.2 用户选择与优先级确认 **在扫描前,必须先让用户确认 baseline 范围和优先级。** @@ -246,7 +250,7 @@ node .harness/skills/domain-init/scripts/sync-submodule-skills.mjs --prune # ### 4.4 生成报告 -输出本次生成的完整清单(类型、文件、状态、参考项目),标记新增 vs 增强,建议后续完善方向,提醒用户 review 后 commit。 +输出本次生成的完整清单(类型、文件、简述、状态、参考项目),标记新增 vs 增强,列出待确认事项、未覆盖范围与未验证行为,建议后续完善方向,并提醒用户 review 后 commit。 ### 4.5 更新文档与 AGENTS 入口 @@ -258,7 +262,7 @@ node .harness/skills/domain-init/scripts/sync-submodule-skills.mjs --prune # 3. 更新 AGENTS 的文档链接与读取条件,规则和能力通过最小触发矩阵发现;不要求全量读取 docs。 4. 填充完成后删除该槽位成对的 `` / `` 边界注释与已用完的占位提示,保留正文及相邻框架内容。未填槽位保留占位;已有正文不重加标记。 -5. 核对相对链接、规则触发范围和事实来源。后续实施改变已验证的项目事实时,同步相关文档。 +5. 按 `references/output-formats.md` 的质量标准核对产物及规则触发范围。后续实施改变已验证的项目事实时,同步相关文档。 | 用户槽位 | 内容 | |----------|------| diff --git a/.harness/skills/domain-init/references/architecture-knowledge.md b/.harness/skills/domain-init/references/architecture-knowledge.md new file mode 100644 index 0000000..94c4b91 --- /dev/null +++ b/.harness/skills/domain-init/references/architecture-knowledge.md @@ -0,0 +1,52 @@ +# 架构知识扫描与验收 + +选中 K1,或增强项涉及当前架构说明时使用。记录当前实现;待实施方案留在任务文档中。 +只调查已确认的作用域和主题,按 `output-formats.md` 归属、引用与合并产物。 + +## 扫描顺序 + +1. **定位仓库与入口**:识别单仓、monorepo 或多仓;读取各目标仓库的 manifest、构建配置、 + 启动入口与已有文档。分别确认职责、技术栈、共享配置和依赖集成方式;根项目记录跨项目关系, + 子项目记录自身实现,跨项目通过链接关联。 +2. **追踪结构与依赖**:沿入口和代表性调用链核对模块、分层、组装位置与依赖方向。 + 区分源码调用、包/构建依赖与进程间通信;命名和目录只能提供线索,结论须核对代码与配置。 +3. **追踪通信与流程**:从已确认范围内的关键入口追到结果及失败分支,核对跨边界调用、 + 消息或事件定义、状态变化及恢复处理。高优先项深入边界与例外,其余按已确认深度采样。 +4. **映射已有文档**:将发现对应到已有主题和缺口,形成目标文件、依据及待确认事项,交回 + Phase 2/3 review;跨仓调用链的发现不扩大对子项目的写入授权。 + +## 按需覆盖的内容 + +以下是内容检查项,不是固定章节或文件清单。已有文档能承接时直接更新;简单项目可合并, +没有触点的主题省略。DDD 仅在代码或已确认约定支持时展开。 + +| 主题 | 应回答的问题 | 可复用的文档位置示例 | +|------|--------------|----------------------| +| 项目与结构 | 项目做什么;各仓库/模块、入口、技术栈、分层、依赖方向与集成方式是什么 | project.md、architecture.md | +| 组件与归属 | 组件负责和不负责什么;边界依据是什么;新功能按什么判据归属 | architecture.md;内容较多时 components.md / modules.md | +| 通信与契约 | 谁调用谁;同步/异步、协议或机制、接口/消息定义、用途、所属模块和代码入口是什么 | architecture.md;按需拆分 communication-patterns.md / interfaces.md | +| 关键流程 | 从触发到结果经过哪些组件和状态;关键失败、超时、重试、取消或恢复在何处处理 | 现有业务专题;按需创建流程文档 | +| 开发与交付 | 在哪里运行构建、测试和发布;哪些配置或脚本定义环境、版本与依赖更新方式 | development.md、testing.md、已有发布文档 | + +组件归属在存在多种落点时使用简短决策表,列出任务类型、所属组件与边界依据。 +现有代码只能证明边界和依赖;历史划分理由遵循 Docs 的证据标记要求,不反推为已确认决定。 + +通信检查由实际触点触发,覆盖 HTTP/RPC、队列、IPC、CLI/SDK 调用、回调或事件。 +接口清单优先链接已有协议、schema、路由或公开头文件;缺少导航时仅补充定位表,字段按机制裁剪 +为方法/命令/路径/topic、用途、调用方与接收方、所属模块和定义位置,避免复制完整定义。 +未发现的超时或恢复机制记为扫描范围内的缺口,不补写理想行为。 + +## 图表与导航 + +- 模块或跨仓关系难以用短文解释时,用 Mermaid flowchart/graph 表达职责与依赖方向; + 跨组件交互复杂时用 sequenceDiagram,必要时补充状态图。简单关系用文字或表格。 +- 图中参与者、调用方向和状态须与实现及正文一致。显示文本加引号;classDiagram 使用合法类 + 标识符,不将带 `::` 的命名空间直接用作类标识符。 +- 专题之间用相对链接关联;文档索引注明用途和读取场景,AGENTS 只链接实际存在的文档。 + +## 完成检查 + +- 读者能找到入口、职责边界、依赖方向与相关代码,能判断新增功能的归属。 +- 已选且有触点的通信与流程说明包含调用双方、关键状态和失败路径;无法追踪的边界已列明。 +- 图表、正文和接口导航使用一致名称与方向,关键结论可定位到证据。 +- 已覆盖主题能指向目标文档;未覆盖范围、推断、待确认事项和未验证行为进入报告。 diff --git a/.harness/skills/domain-init/references/dimension-pool.md b/.harness/skills/domain-init/references/dimension-pool.md index 57a5d3a..8165dc9 100644 --- a/.harness/skills/domain-init/references/dimension-pool.md +++ b/.harness/skills/domain-init/references/dimension-pool.md @@ -2,6 +2,9 @@ 基于 Phase 1 识别的领域,**过滤掉不适用的维度**后,向用户展示可选增强项。 R-* 是扫描主题:执行约束进入 rules,背景、结构和示例进入 docs;不强制每个主题生成 rule。 +选中 R2、R3、R9、S12 或 S13 且涉及当前架构知识时,读取 +[架构知识扫描与验收](architecture-knowledge.md)。已选择 K1 时复用本轮扫描和已有产物,仅补选中范围的缺口。 +通信与流程按实际触点调查,包含系统/C++ 的 IPC、回调和事件,不受 R9 的展示过滤限制。 ## 规则与项目知识增强池 diff --git a/.harness/skills/domain-init/references/output-formats.md b/.harness/skills/domain-init/references/output-formats.md index b9420cf..7e79b86 100644 --- a/.harness/skills/domain-init/references/output-formats.md +++ b/.harness/skills/domain-init/references/output-formats.md @@ -24,6 +24,10 @@ OpenSpec 内容保留在主仓库 `openspec/`;项目文档引用相关规范 标题说明主题;按实际需要记录适用范围、当前事实、来源和相关入口,不强制章节数量。 命令注明运行目录并链接对应 scripts;详细示例注明用途,不把示意代码当作当前实现。 +关键结论引用代码或配置的相对路径与符号,必要时给出起始行;已确认约定链接其记录。 +缺少证据的历史设计理由标为「推测」或「待确认」,改进建议与当前事实分开。 +只做静态扫描时明确证据边界,不将配置声明或调用关系写成已运行验证的行为。 + - `docs/README.md` 可作为按任务组织的索引,已有索引则复用。 - 文件名沿用项目惯例;项目概览、架构、开发与测试说明按需创建,不生成空目录和占位文档。 - AGENTS 的 `project` 槽位统一维护项目知识入口;rules 按需引用相关说明。只添加已存在文件 @@ -94,6 +98,8 @@ model: sonnet | 内容归属 | 约束与知识分开,低频硬约束不丢失 | | 文档引用 | 链接存在、读取条件明确、同主题复用 | | 代码依据 | 约定必须能在项目代码中找到出处 | +| 术语一致 | 模块、组件、接口和消息名称在正文、图表与引用中一致 | +| 架构知识 | 涉及架构的产物按 [架构知识扫描与验收](architecture-knowledge.md) 检查 | | Skill 完整性 | 必须有「何时使用」和「Hard Rules」 | | Agent 完整性 | 必须有「审查维度」和「输出规则」 | | 禁止理想化 | 不输出与项目实际不符的规范 | diff --git a/.harness/versions.yml b/.harness/versions.yml index afd3610..0842637 100644 --- a/.harness/versions.yml +++ b/.harness/versions.yml @@ -19,7 +19,7 @@ skills: openspec-onboard: "2.4" openspec-sync-specs: "2.2" openspec-verify-change: "3.4" - domain-init: "2.0.2" + domain-init: "2.1.0" verify-init: "2.0.1" ui-fidelity-playbook: "1.0.3" rules: {} diff --git a/README.md b/README.md index 988106e..d318a3c 100644 --- a/README.md +++ b/README.md @@ -94,10 +94,10 @@ Lite / Full 使用 OpenSpec 保存共同设计和任务过程。常用入口是 | 命令 | 用途 | 常用选项 | |------|------|----------| -| `devkeel init` | 初始化协作资产和平台入口 | `--name`、`--targets`、`-y`、`--force` | +| `devkeel init` | 初始化协作资产和平台入口 | `--name`、`--targets`、`-y`、`--force`、`--template-package`、`--template-registry` | | `devkeel doctor` | 检查协作资产 | `--fix` | | `devkeel sync` | 同步平台入口 | `--targets`、`--force` | -| `devkeel update` | 更新当前项目的模板资产 | `--dry-run`、`--force`、`--beta`、`--template-version` | +| `devkeel update` | 更新当前项目的模板资产 | `--dry-run`、`--force`、`--beta`、`--template-version`、`--template-package`、`--template-registry` | | `devkeel evidence` | 收集 OpenSpec change 的实现证据 | `--change `、`--json`、`--write-base` | | `devkeel openspec <命令>` | 调用内置 OpenSpec CLI | 如 `list`、`status`、`validate` | | `devkeel -V` | 查询 CLI 与模板的发布渠道版本 | 可加 `--beta` | @@ -118,6 +118,43 @@ devkeel update `devkeel update` 不升级全局 CLI。选择“全部更新”或使用 `--force` 会覆盖受管组件中的本地修改; 退役的受管 Skill 目录及其中的自定义内容也可能被删除。更新前先查看 `--dry-run` 结果。 +### 使用自定义模板源 + +`init` 和 `update` 支持指定兼容 DevKeel 目录布局的 npm 模板包: + +```bash +devkeel init --template-package @example/devkeel-templates --template-registry https://npm.example.com/ +# 已初始化项目可通过 update 切换来源,建议先预览 +devkeel update --template-package @example/devkeel-templates --template-registry https://npm.example.com/ --dry-run +``` + +来源配置分两级,使用相同的 JSON 格式: + +- 用户级:`~/.harness/template-source.json`,手动配置一次,供所有项目继承。 +- 项目级:`.harness/template-source.json`,覆盖用户级配置,可随项目提交。 + +例如在用户级文件中配置: + +```json +{ + "packageName": "@example/devkeel-templates", + "registry": "https://npm.example.com/" +} +``` + +各字段优先级为:命令行参数 → 项目级配置 → 用户级配置 → 默认值。两个字段均可单独配置。 +未配置项目级来源的项目直接继承用户级来源,不会自动生成项目级文件。 +显式传入来源参数并成功执行后,参数会保存为项目级覆盖;继承的字段不会被固定下来。 +删除项目级文件即可恢复继承用户级来源,后续直接运行 `devkeel update`。 +默认包为 `devkeel-templates`;未指定 registry 时,遵循 npm 的 scope registry 或普通 registry +配置,且不会把这个解析结果固定到来源文件。认证由项目或用户 `.npmrc` 提供,来源文件不保存凭据。 +`-V` 与 `doctor` 更新提示也使用相同的来源优先级;CLI 自身的发布查询保持独立。 + +缓存按 registry、包名、版本隔离。切换来源时,即使组件版本号相同也会重新检查,仍沿用原有 +覆盖确认流程;`--force` 会覆盖本地修改。中断或跳过组件时不保存新来源,需带相同参数重试。 +`--dry-run` 可下载缓存,但不修改配置或项目资产。拉取失败不会回退到公共模板。 +版本与渠道参数只影响本次更新,不会持久化。当前仅支持 npm 包,不支持本地目录或 Git URL。 + ## 开发与文档 从[项目文档索引](docs/README.md)进入开发、测试与构建说明;源码与问题反馈见 diff --git a/docs/architecture.md b/docs/architecture.md index 10b9b0b..34570c5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -26,6 +26,13 @@ 平台由现有目录和入口文件识别,CLI 不读取或生成 `.harness/config.yml`。 [update.ts](../src/lib/update.ts)维护资产更新和兼容迁移。 +[template-source.ts](../src/lib/template-source.ts)统一解析模板包及 npm registry:命令行参数覆盖 +项目 `.harness/template-source.json`,项目配置覆盖用户 `~/.harness/template-source.json`,缺省时使用 `devkeel-templates` 和 npm 配置。来源文件仅保存包名与 +显式 registry,不保存认证信息。普通项目继承用户配置;仅显式参数或已有项目配置落盘为项目覆盖。`.harness/versions.yml` 的 `templateSource` 保存已完成同步的 +来源指纹;换源过程中为 `pending`,确保失败或部分更新后重试仍检查同版本组件。 +[templates-cache.ts](../src/lib/templates-cache.ts)按来源指纹及版本隔离下载缓存,npm 在项目目录 +运行以沿用 `.npmrc`;下载、版本输出和更新提示使用同一来源解析。 + 约束见 [架构规则](../.harness/rules/architecture-constraints.md)。例如 templates 调用版本读取、 detect 复用模板目录检查能力;模块依赖应保持无环。模板渲染使用 `{{VAR}}` 替换,具体实现以 [renderTemplate](../src/lib/templates.ts)为准。 diff --git a/openspec/specs/domain-templates/spec.md b/openspec/specs/domain-templates/spec.md index 98acb4f..a48f39c 100644 --- a/openspec/specs/domain-templates/spec.md +++ b/openspec/specs/domain-templates/spec.md @@ -18,7 +18,7 @@ - **WHEN** 对比领域模板与主仓库模板 - **THEN** 领域模板 SHALL 不复制 Direct/Lite/Full、Brainstorming 或 OpenSpec 的主仓库编排算法 -- **AND** 模板 SHALL 明确代码与验证留在子仓库、OpenSpec 和知识产出归属主仓库 +- **AND** 模板 SHALL 明确代码、验证与项目知识留在所属子仓库,项目知识写入其 `docs/`,OpenSpec 由主仓库协调 #### Scenario: Domain AGENTS.md is safe as a standalone entry diff --git a/openspec/specs/templates-cache/spec.md b/openspec/specs/templates-cache/spec.md index 1e696d7..4d49e4d 100644 --- a/openspec/specs/templates-cache/spec.md +++ b/openspec/specs/templates-cache/spec.md @@ -6,35 +6,34 @@ ### Requirement: 实时拉取最新模板版本 -当用户执行 `devkeel update` 或 `devkeel init` 时,系统 SHALL 通过 `npm view devkeel-templates@latest version --json` 查询公共 npm registry 的最新版本号。 +当用户执行 `devkeel update` 或 `devkeel init` 时,系统 SHALL 根据命令行、项目级、用户级和 npm 配置解析来源,通过 `npm view @latest version --json` 查询所选 registry 的最新版本号。 #### Scenario: 成功查询到最新版本 - **WHEN** 用户执行 `devkeel update` 且 npm 环境正常 -- **THEN** 系统解析 `npm view` 的 JSON 输出,提取版本号,随后通过 `npm pack devkeel-templates@` 下载模板 +- **THEN** 系统解析 `npm view` 的 JSON 输出,提取版本号,随后通过 `npm pack @` 下载模板 #### Scenario: npm 未安装或不在 PATH - **WHEN** `npm view` 执行失败,exit code ≠ 0 - **THEN** 系统抛出 `TemplatesFetchError`,错误信息包含: - 1. 原始 npm stderr + 1. 所选包名、registry 和失败阶段,不回显可能包含凭据的 npm 输出 2. 修复指引:确认 `npm --version` 可用 - 3. 修复指引:`npm config get registry` 检查公共包访问配置 - 4. 修复指引:`curl -I ` 验证网络可达 - 5. 修复指引:确认 `devkeel-templates` 已发布 + 3. 修复指引:检查 npm registry、认证与网络配置 + 4. 修复指引:确认模板包已在该 registry 发布 #### Scenario: npm 输出非预期 JSON - **WHEN** `npm view` 成功但输出无法解析为版本号字符串 -- **THEN** 系统抛出 `TemplatesFetchError`,错误信息包含原始 stdout +- **THEN** 系统抛出 `TemplatesFetchError`,不回显未经验证的 stdout ### Requirement: 缓存目录布局与版本隔离 -系统 SHALL 将模板缓存到 `~/.harness/cache/devkeel-templates//`,每个版本独立目录,支持并发安全与回滚。 +系统 SHALL 将模板缓存到 `~/.harness/cache/devkeel-templates///`,source-key 为规范化 registry 与包名的指纹;不同来源或版本不得共用缓存。旧布局缺少来源信息,不复用。 #### Scenario: 首次拉取 - **WHEN** 缓存根目录不存在或无对应版本目录 -- **THEN** 系统创建 `~/.harness/cache/devkeel-templates/.tmp/`,下载并解压 tarball,完成后 `rename` 为 `/` +- **THEN** 系统创建 `~/.harness/cache/devkeel-templates//.tmp/`,下载并解压 tarball,完成后 `rename` 为 `/` #### Scenario: 缓存命中 -- **WHEN** `/package.json` 的包名为 `devkeel-templates`、版本号与请求版本一致,且 `versions-yml.yml` 存在 +- **WHEN** `/package.json` 的包名与所选包一致、版本号与请求版本一致,且 `versions-yml.yml` 存在 - **THEN** 系统跳过下载,直接返回缓存路径 #### Scenario: 缓存版本过期 @@ -66,30 +65,30 @@ CLI 所有读取模板的函数(`getTemplatesDir()`、`getBuiltinVersions()` - **THEN** 系统输出诊断文案(含 registry 检查命令)后以 `exit(1)` 退出 #### Scenario: 包未发布 -- **WHEN** npm 返回 404(`devkeel-templates` 不存在) -- **THEN** 系统输出诊断文案(提示维护者首次发版)后以 `exit(1)` 退出 +- **WHEN** npm 返回 404(所选模板包不存在) +- **THEN** 系统输出诊断文案(提示确认包已发布)后以 `exit(1)` 退出 ### Requirement: update 支持指定模板版本 -`devkeel update` SHALL 支持用户通过显式模板版本选择 `devkeel-templates` 的下载版本,且默认不改变最新稳定版本更新行为。 +`devkeel update` SHALL 支持用户为所选模板包指定下载版本,且默认不改变最新稳定版本更新行为。 #### Scenario: 默认更新最新稳定模板 - **WHEN** 用户执行 `devkeel update` -- **THEN** 系统查询 `devkeel-templates` 的 npm `version` 字段并下载该版本模板 +- **THEN** 系统查询所选模板包的 npm `latest` dist-tag 并下载该版本模板 #### Scenario: 使用 option 指定模板版本 - **WHEN** 用户执行 `devkeel update --template-version 1.2.3-beta.1` -- **THEN** 系统下载 `devkeel-templates@1.2.3-beta.1` 并用该模板目录执行后续 update 检测和同步 +- **THEN** 系统下载 `@1.2.3-beta.1` 并用该模板目录执行后续 update 检测和同步 #### Scenario: 使用位置参数指定模板版本 - **WHEN** 用户执行 `devkeel update 1.2.3` -- **THEN** 系统下载 `devkeel-templates@1.2.3` 并用该模板目录执行后续 update 检测和同步 +- **THEN** 系统下载 `@1.2.3` 并用该模板目录执行后续 update 检测和同步 #### Scenario: 显式版本格式非法 - **WHEN** 用户指定的模板版本不符合 semver 字符串格式 - **THEN** 系统 MUST 在执行 `npm pack` 前失败,并输出 `TemplatesFetchError` ### Requirement: update 支持 npm beta 渠道模板版本 -`devkeel update --beta` SHALL 解析 `devkeel-templates` 的 npm `beta` dist-tag,并使用该 tag 指向的具体版本作为模板下载目标。具体版本可以是普通 semver,也可以是带 beta prerelease 的 semver。 +`devkeel update --beta` SHALL 解析所选模板包的 npm `beta` dist-tag,并使用该 tag 指向的具体版本作为模板下载目标。具体版本可以是普通 semver,也可以是带 beta prerelease 的 semver。 #### Scenario: beta tag 指向普通 semver - **WHEN** npm dist-tags 为 `latest=1.3.0`、`beta=2.0.0` @@ -116,12 +115,38 @@ CLI 所有读取模板的函数(`getTemplatesDir()`、`getBuiltinVersions()` #### Scenario: 默认显示 latest - **WHEN** 用户执行 `devkeel -V` -- **THEN** 系统查询 `devkeel@latest` 与 `devkeel-templates@latest` 的版本并显示,且不添加 beta 标识 +- **THEN** 系统查询 `devkeel@latest` 与 `@latest` 的版本并显示,且不添加 beta 标识 #### Scenario: 显式显示 beta - **WHEN** 用户执行 `devkeel -V --beta` -- **THEN** 系统查询 `devkeel@beta` 与 `devkeel-templates@beta` 的版本,并分别输出 `harness (beta)` 与 `templates (beta)` +- **THEN** 系统查询 `devkeel@beta` 与 `@beta` 的版本,并分别输出 `devkeel (beta)` 与 `templates (beta)` #### Scenario: registry 不可达 - **WHEN** 查询 CLI dist-tags 或模板版本失败 -- **THEN** 系统沿用当前 CLI 版本与现有本地模板版本回退,不因版本查询失败退出 +- **THEN** CLI 版本可回退为本地版本;配置了自定义来源时,模板查询失败显示 unknown,不显示其他来源模板版本,不因查询失败退出 + + +### Requirement: 两级模板来源配置 +系统 SHALL 按字段采用命令行 `--template-package` / `--template-registry`、项目 `.harness/template-source.json`、用户 `~/.harness/template-source.json`、默认包名与 npm 配置的优先级。JSON 使用可选 `packageName` 和 `registry`,至少有一项。仅支持 npm 包名和无凭据的 HTTP(S) registry,认证由 npm 配置管理。 + +#### Scenario: 全局继承与项目覆盖 +- **WHEN** 用户配置了用户级来源,项目没有来源覆盖 +- **THEN** init、update、版本查询和更新提示使用用户级来源,不自动生成项目覆盖 +- **WHEN** 用户显式提供来源参数并成功完成 init 或 update +- **THEN** 将显式字段保存为项目级覆盖,保留已有项目字段,不固定继承的字段,不修改用户级配置 + +#### Scenario: 来源切换与部分更新 +- **WHEN** 已安装来源指纹与当前解析来源不同 +- **THEN** 即使组件版本相同也重新纳入更新检查,保持原有覆盖确认语义 +- **WHEN** 换源失败、取消或跳过组件 +- **THEN** 不保存新项目来源;已开始写入的换源记录 pending,重试仍须重新检查组件 +- **WHEN** 使用 --dry-run +- **THEN** 可以填充下载缓存,但不得保存来源或修改项目资产 + +#### Scenario: npm 配置上下文 +- **WHEN** 解析版本或下载模板包 +- **THEN** npm 在项目目录运行,沿用项目与用户认证;明确所选 registry 同时覆盖 scope registry,npm pack 通过 --pack-destination 写入临时目录并禁用脚本 + +#### Scenario: 缓存与提示隔离 +- **WHEN** 不同来源发布了相同版本 +- **THEN** 下载缓存与更新提示缓存按来源独立,下载后验证实际包名、版本和版本清单;失败不得回退到公共源 diff --git a/src/commands/init.ts b/src/commands/init.ts index 1cef19b..9d366ef 100644 --- a/src/commands/init.ts +++ b/src/commands/init.ts @@ -11,6 +11,7 @@ import { detectEnvironment, detectRepositoryType, detectSubmodules } from '../li import { removeLegacyPlatformIgnores } from '../lib/gitignore.js' import { copyTemplateSkills, copyTemplateAgents, copyTemplateRules, copyTemplateCommands, createPlatformLinks, copyOpenspecTemplate, readTemplateFile, renderTemplate, ensureGitignore, detectDeprecatedAssets, removeDeprecatedAssets, updateOpenspecIncremental, writeSmartFile, getTemplatesDir, setTemplatesDir, copyDirRecursive, detectExistingPlatformTargets } from '../lib/templates.js' import { ensureTemplatesCache, TemplatesFetchError } from '../lib/templates-cache.js' +import { hasTemplateSourceChanged, resolveTemplateSource, templateSourceKey, writeTemplateSource, type TemplateSourceOptions } from '../lib/template-source.js' import { applyDiscussionSkillMigration, applyLegacyMigrations, assertSchemaTargetsAvailable, planLegacyMigrations, writeVersionsAtomically } from '../lib/update.js' import { createLog } from '../lib/log.js' import { syncSkillLinks } from '../lib/skill-distribution.js' @@ -21,7 +22,7 @@ import { mergeAgentsMdContent, } from '../lib/agents-md.js' -export interface InitOptions { +export interface InitOptions extends TemplateSourceOptions { name?: string targets?: string yes?: boolean @@ -79,6 +80,8 @@ export async function runInit(opts?: InitOptions): Promise { const projectRoot = process.cwd() const env = detectEnvironment(projectRoot) const repoType = detectRepositoryType(projectRoot) + const source = resolveTemplateSource(projectRoot, opts) + const sourceKey = templateSourceKey(source) const log = createLog() log.intro('DevKeel v2 项目初始化') @@ -86,7 +89,7 @@ export async function runInit(opts?: InitOptions): Promise { const s = p.spinner() s.start('正在拉取最新模板...') try { - const { cacheDir } = await ensureTemplatesCache() + const { cacheDir } = await ensureTemplatesCache({ source, projectRoot }) setTemplatesDir(cacheDir) s.stop('模板缓存就绪') } catch (e) { @@ -142,6 +145,10 @@ export async function runInit(opts?: InitOptions): Promise { } const initialVersions = readVersions(projectRoot) + const sourceChanged = hasTemplateSourceChanged(initialVersions?.templateSource, source) + if (initialVersions && sourceChanged) { + writeVersionsAtomically(projectRoot, { ...initialVersions, templateSource: 'pending' }) + } if (repoType === 'main' && initialVersions) { const discussionResult = applyDiscussionSkillMigration(projectRoot, getTemplatesDir()) if (discussionResult.changedPaths.length > 0 || discussionResult.recovered) { @@ -151,7 +158,7 @@ export async function runInit(opts?: InitOptions): Promise { const existingVersions = readVersions(projectRoot) const builtinVersions = getBuiltinVersions() const versions = filterManagedVersions(builtinVersions, repoType) - const outdated = computeOutdatedCategories(existingVersions, versions) + const outdated = computeOutdatedCategories(sourceChanged ? null : existingVersions, versions) let debuggingSkillInstalled = false const templateVars = { @@ -170,7 +177,7 @@ export async function runInit(opts?: InitOptions): Promise { const skillsTarget = path.join(projectRoot, '.harness', 'skills') fs.mkdirSync(skillsTarget, { recursive: true }) for (const skillName of outdated.skills) { - if (skillName === 'brainstorming') continue + if (skillName === 'brainstorming' && !sourceChanged) continue const src = path.join(templatesDir, 'skills', skillName) if (fs.existsSync(src)) { copyDirRecursive(src, path.join(skillsTarget, skillName)) @@ -214,7 +221,7 @@ export async function runInit(opts?: InitOptions): Promise { if (repoType === 'main') { copyTemplateCommands( path.join(projectRoot, '.harness', 'commands'), - existingVersions ? ['opsx/explore.md'] : [], + existingVersions && !sourceChanged ? ['opsx/explore.md'] : [], ) log.success('.harness/commands/') } @@ -320,6 +327,10 @@ export async function runInit(opts?: InitOptions): Promise { ) if (agentsResult === 'preserved') { log.info(`${subPath}/AGENTS.md 已按用户选择保留`) + writeVersionsAtomically(subFull, { + ...filterManagedVersions(builtinVersions, 'domain'), + templateSource: 'pending', + }) } if (targetList.includes('claude-code') || targetList.includes('cursor')) { @@ -332,6 +343,13 @@ export async function runInit(opts?: InitOptions): Promise { removeLegacyPlatformIgnores(subFull) createPlatformLinks(subFull, targetList) + if (agentsResult !== 'preserved') { + writeTemplateSource(subFull, source) + writeVersionsAtomically(subFull, { + ...filterManagedVersions(builtinVersions, 'domain'), + templateSource: sourceKey, + }) + } log.success(`${subPath}/ 配置 + 平台链接`) } } @@ -400,7 +418,14 @@ export async function runInit(opts?: InitOptions): Promise { log.success('package.json') } - writeVersionsAtomically(projectRoot, versions) + if (sourceChanged && agentsResult === 'preserved') { + writeVersionsAtomically(projectRoot, { ...versions, templateSource: 'pending' }) + log.warning('AGENTS.md 已保留,模板来源尚未完整切换;未保存新来源,请带相同来源参数重试并确认合并') + } else { + writeVersionsAtomically(projectRoot, { ...versions, templateSource: sourceChanged ? 'pending' : sourceKey }) + writeTemplateSource(projectRoot, source) + if (sourceChanged) writeVersionsAtomically(projectRoot, { ...versions, templateSource: sourceKey }) + } log.success('.harness/versions.yml') const existingDocs = ['wiki', 'docs'].filter(d => fs.existsSync(path.join(projectRoot, d))) diff --git a/src/commands/update.ts b/src/commands/update.ts index 18a2491..8ab4b31 100644 --- a/src/commands/update.ts +++ b/src/commands/update.ts @@ -11,6 +11,7 @@ import { } from '../lib/versions.js' import { getTemplatesDir, setTemplatesDir, copyDirRecursive, copyTemplateCommands, detectDeprecatedAssets, detectExistingPlatformTargets, removeDeprecatedAssets, readTemplateFile, renderTemplate, updateOpenspecIncremental } from '../lib/templates.js' import { ensureTemplatesCache, TemplatesFetchError } from '../lib/templates-cache.js' +import { hasTemplateSourceChanged, resolveTemplateSource, templateSourceKey, writeTemplateSource, type TemplateSourceOptions } from '../lib/template-source.js' import { applyDiscussionSkillMigration, applyLegacyMigrations, assertSchemaTargetsAvailable, assertLegacyMigrationPreflight, detectUpdates, isLegacySchema, isDiscussionSkillMigrationRequired, planLegacyMigrations, recoverDiscussionSkillMigration, resolveUpdatePaths, collectCommitStagePaths, RETIRED_MANAGED_SKILLS, writeVersionsAtomically, type LegacyMigrationPlan, type UpdateItem } from '../lib/update.js' import { createLog } from '../lib/log.js' import { applyLegacyPlatformIgnorePlan, planLegacyPlatformIgnores } from '../lib/gitignore.js' @@ -24,7 +25,7 @@ import { restoreAgentsMdSlots, } from '../lib/agents-md.js' -export interface UpdateOptions { +export interface UpdateOptions extends TemplateSourceOptions { force?: boolean dryRun?: boolean templateVersion?: string @@ -214,11 +215,16 @@ export async function runUpdate(options?: UpdateOptions): Promise { } const s = p.spinner() + const source = resolveTemplateSource(projectRoot, options) + const sourceKey = templateSourceKey(source) + const sourceChanged = hasTemplateSourceChanged(versionsBeforeUpdate.templateSource, source) try { s.start(formatTemplatesFetchMessage(resolvedOptions)) const { cacheDir, version } = await ensureTemplatesCache({ version: resolvedOptions.templateVersion, beta: resolvedOptions.beta, + source, + projectRoot, }) setTemplatesDir(cacheDir) s.stop(`模板缓存就绪 (${version})`) @@ -246,7 +252,7 @@ export async function runUpdate(options?: UpdateOptions): Promise { if (repoType === 'main') assertLegacyMigrationPreflight(migrationPlan, templatesDir) const discussionMigrationRequired = repoType === 'main' && isDiscussionSkillMigrationRequired(projectRoot, templatesDir) - const updates = detectUpdates(projectRoot, force, templatesDir, builtinVersions) + const updates = detectUpdates(projectRoot, force, templatesDir, builtinVersions, sourceChanged) const debuggingUpdateRequired = updates.some(update => ( updateKey(update) === DEBUGGING_UPDATE_KEY )) @@ -273,6 +279,10 @@ export async function runUpdate(options?: UpdateOptions): Promise { agentsFrameworkHasChanges, profileVersionsHaveChanges, )) { + if (!dryRun) { + writeTemplateSource(projectRoot, source) + writeVersionsAtomically(projectRoot, { ...versionsBeforeUpdate, templateSource: sourceKey }) + } log.success('所有组件已是最新版本') log.outro('') return @@ -306,6 +316,9 @@ export async function runUpdate(options?: UpdateOptions): Promise { } let updated = 0 + if (sourceChanged) { + writeVersionsAtomically(projectRoot, { ...versionsBeforeUpdate, templateSource: 'pending' }) + } if (updates.some(update => update.category === 'skills')) { const skills = syncSkillLinks(projectRoot, skillTargets) if (!skills.ok) { @@ -508,6 +521,13 @@ export async function runUpdate(options?: UpdateOptions): Promise { } const gitignorePath = path.join(projectRoot, '.gitignore') + const allComponentsUpdated = updates.every(update => successfulUpdateKeys.has(updateKey(update))) + if (allComponentsUpdated && skipped === 0) { + writeTemplateSource(projectRoot, source) + writeVersionsAtomically(projectRoot, { ...newVersions, templateSource: sourceKey }) + } else if (sourceChanged) { + log.warning('模板来源尚未完整切换,未保存新来源;重试时请继续指定相同来源参数') + } const gitignoreMatchesPlan = removedIgnores.length > 0 && fs.existsSync(gitignorePath) && fs.readFileSync(gitignorePath, 'utf-8') === gitignorePlan.updatedContent diff --git a/src/index.ts b/src/index.ts index 4a281f6..29e90e4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,6 +6,7 @@ import { Command } from 'commander' import { getTemplatesDir, setTemplatesDir } from './lib/templates-dir.js' import { ensureTemplatesCache } from './lib/templates-cache.js' import { getPublishedHarnessVersion } from './lib/release-channel.js' +import { readTemplateSource, readUserTemplateSource } from './lib/template-source.js' import { runInit } from './commands/init.js' import { runDoctor } from './commands/doctor.js' import { runUpdate } from './commands/update.js' @@ -16,13 +17,17 @@ import { interceptOpenspec } from './commands/openspec.js' async function showVersion(isBeta = false): Promise { const releaseChannel = isBeta ? 'beta' : 'latest' const harnessVersion = getPublishedHarnessVersion(releaseChannel, packageJson.version) + let fetched = false try { const { cacheDir } = await ensureTemplatesCache(isBeta ? { beta: true } : undefined) setTemplatesDir(cacheDir) - } catch { /* 网络不可达时读本地缓存 */ } + fetched = true + } catch { /* 自定义来源不可达时保持 unknown,默认来源允许源码态回退 */ } const pkgPath = path.join(getTemplatesDir(), 'package.json') let templatesVersion = 'unknown' - if (fs.existsSync(pkgPath)) { + let hasCustomSource = false + try { hasCustomSource = readTemplateSource() !== null || readUserTemplateSource() !== null } catch { hasCustomSource = true } + if ((fetched || !hasCustomSource) && fs.existsSync(pkgPath)) { try { const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')) as Record if (typeof pkg['version'] === 'string') templatesVersion = pkg['version'] @@ -60,6 +65,8 @@ program .option('--targets ', '目标平台(逗号分隔:claude-code,codex,cursor,copilot,gemini,opencode)') .option('-y, --yes', '跳过确认提示,使用默认行为') .option('--force', '备份并覆盖冲突的技能入口') + .option('--template-package ', '模板 npm 包名(可带 @scope)') + .option('--template-registry ', '模板 npm registry URL(认证沿用 npm 配置)') .action((opts) => runInit(opts)) program @@ -76,6 +83,8 @@ program .option('--dry-run', '仅预览') .option('--template-version ', '指定模板版本') .option('--beta', '使用 beta 渠道模板版本') + .option('--template-package ', '模板 npm 包名(可带 @scope)') + .option('--template-registry ', '模板 npm registry URL(认证沿用 npm 配置)') .action((templateVersion, opts) => runUpdate({ ...opts, positionalTemplateVersion: templateVersion, diff --git a/src/lib/npm-command.ts b/src/lib/npm-command.ts index dcacbe4..0ef83c5 100644 --- a/src/lib/npm-command.ts +++ b/src/lib/npm-command.ts @@ -1,4 +1,5 @@ -import { execFileSync, type ExecFileSyncOptionsWithStringEncoding } from 'node:child_process' +import { execFile, execFileSync, type ExecFileOptions, type ExecFileSyncOptionsWithStringEncoding } from 'node:child_process' +import { promisify } from 'node:util' interface NpmInvocation { file: string @@ -33,4 +34,15 @@ export function execNpmSync( return execFileSync(invocation.file, invocation.args, options) } +const execFileAsync = promisify(execFile) + +export async function execNpm( + args: readonly string[], + options: ExecFileOptions = {}, +): Promise { + const invocation = resolveNpmInvocation(args) + const { stdout } = await execFileAsync(invocation.file, invocation.args, options) + return typeof stdout === 'string' ? stdout : stdout.toString() +} + export const __test__ = process.env['VITEST'] ? { resolveNpmInvocation } : undefined diff --git a/src/lib/template-source.ts b/src/lib/template-source.ts new file mode 100644 index 0000000..8641fdd --- /dev/null +++ b/src/lib/template-source.ts @@ -0,0 +1,133 @@ +import fs from 'node:fs' +import path from 'node:path' +import os from 'node:os' +import { createHash } from 'node:crypto' +import { execNpmSync } from './npm-command.js' + +export const DEFAULT_TEMPLATE_PACKAGE = 'devkeel-templates' +const SOURCE_FILE = '.harness/template-source.json' + +export interface TemplateSourceOptions { + templatePackage?: string + templateRegistry?: string +} + +export interface TemplateSource { + packageName: string + registry: string + configuredRegistry?: string + projectConfig?: SavedTemplateSource +} + +interface SavedTemplateSource { + packageName?: string + registry?: string +} + +function validatePackage(value: unknown): string { + if (typeof value !== 'string' || value.length > 214 + || !/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(value)) { + throw new Error('模板包名必须是 npm 包名(可带 @scope),不能包含版本或路径') + } + return value +} + +function validateRegistry(value: unknown): string { + if (typeof value !== 'string') throw new Error('模板 registry 必须是 HTTP(S) URL') + let url: URL + try { url = new URL(value) } catch { throw new Error('模板 registry 必须是 HTTP(S) URL') } + if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password + || url.search || url.hash || /[\s\\%"!()^&|<>]/.test(value)) { + throw new Error('模板 registry 必须是无凭据、查询参数和片段的 HTTP(S) URL;认证请配置在 .npmrc') + } + return url.href.replace(/\/+$/, '') + '/' +} + +function readSourceFile(file: string): SavedTemplateSource | null { + if (!fs.existsSync(file)) return null + try { + const parsed = JSON.parse(fs.readFileSync(file, 'utf-8')) as Record + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) + || (parsed['packageName'] === undefined && parsed['registry'] === undefined)) throw new Error('empty source') + return { + ...(parsed['packageName'] === undefined ? {} : { packageName: validatePackage(parsed['packageName']) }), + ...(parsed['registry'] === undefined ? {} : { registry: validateRegistry(parsed['registry']) }), + } + } catch { + throw new Error(`${file} 无效,请检查 packageName 和 registry(不要在文件中保存凭据)`) + } +} + +export function readTemplateSource(projectRoot = process.cwd()): SavedTemplateSource | null { + return readSourceFile(path.join(projectRoot, SOURCE_FILE)) +} + +export function readUserTemplateSource(homeDir = os.homedir()): SavedTemplateSource | null { + return readSourceFile(path.join(homeDir, '.harness', 'template-source.json')) +} + +export function resolveTemplateSource( + projectRoot = process.cwd(), + options: TemplateSourceOptions = {}, + homeDir = os.homedir(), +): TemplateSource { + const user = readUserTemplateSource(homeDir) + const project = readTemplateSource(projectRoot) + const packageName = validatePackage(options.templatePackage ?? project?.packageName ?? user?.packageName ?? DEFAULT_TEMPLATE_PACKAGE) + const configured = options.templateRegistry ?? project?.registry ?? user?.registry + const projectConfig = project || options.templatePackage !== undefined || options.templateRegistry !== undefined + ? { + ...project, + ...(options.templatePackage === undefined ? {} : { packageName }), + ...(options.templateRegistry === undefined ? {} : { registry: validateRegistry(options.templateRegistry) }), + } + : undefined + const persistence = projectConfig ? { projectConfig } : {} + if (configured !== undefined) { + const registry = validateRegistry(configured) + return { packageName, registry, configuredRegistry: registry, ...persistence } + } + const configGet = (key: string): string => execNpmSync(['config', 'get', key], { + cwd: projectRoot, encoding: 'utf-8', timeout: 3000, stdio: ['ignore', 'pipe', 'pipe'], + }).trim() + try { + const scope = packageName.startsWith('@') ? packageName.split('/')[0] : undefined + const scopedRegistry = scope ? configGet(`${scope}:registry`) : undefined + const registry = scopedRegistry && scopedRegistry !== 'undefined' && scopedRegistry !== 'null' + ? scopedRegistry : configGet('registry') + return { packageName, registry: validateRegistry(registry), ...persistence } + } catch { + throw new Error('无法解析模板 npm registry,请检查 npm 配置或指定 --template-registry') + } +} + +export function templateSourceKey(source: TemplateSource): string { + return createHash('sha256').update(JSON.stringify([source.packageName, source.registry])).digest('hex') +} + +export function hasTemplateSourceChanged(installedKey: string | undefined, source: TemplateSource): boolean { + // Legacy projects used the default package through npm configuration, without provenance. + if (installedKey === undefined) { + return source.packageName !== DEFAULT_TEMPLATE_PACKAGE || source.configuredRegistry !== undefined + } + return installedKey !== templateSourceKey(source) +} + +export function templateRegistryArgs(source: TemplateSource): string[] { + const args = [`--registry=${source.registry}`] + if (source.packageName.startsWith('@')) args.push(`--${source.packageName.split('/')[0]}:registry=${source.registry}`) + return args +} + +export function writeTemplateSource(projectRoot: string, source: TemplateSource): void { + if (!source.projectConfig) return + const file = path.join(projectRoot, SOURCE_FILE) + fs.mkdirSync(path.dirname(file), { recursive: true }) + const temp = `${file}.${process.pid}.tmp` + try { + fs.writeFileSync(temp, JSON.stringify(source.projectConfig, null, 2) + '\n', 'utf-8') + fs.renameSync(temp, file) + } finally { + fs.rmSync(temp, { force: true }) + } +} diff --git a/src/lib/templates-cache.ts b/src/lib/templates-cache.ts index ad44184..99cca4f 100644 --- a/src/lib/templates-cache.ts +++ b/src/lib/templates-cache.ts @@ -2,9 +2,10 @@ import fs from 'node:fs' import path from 'node:path' import os from 'node:os' import { extract } from 'tar' -import { execNpmSync } from './npm-command.js' +import { execNpm, execNpmSync } from './npm-command.js' +import { resolveTemplateSource, templateRegistryArgs, templateSourceKey, type TemplateSource } from './template-source.js' -const PACKAGE_NAME = 'devkeel-templates' +const DEFAULT_PACKAGE_NAME = 'devkeel-templates' const CACHE_ROOT = path.join(os.homedir(), '.harness', 'cache', 'devkeel-templates') const META_FILE = 'meta.json' const SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/ @@ -17,23 +18,25 @@ export interface TemplatesCacheInfo { export interface EnsureTemplatesCacheOptions { version?: string beta?: boolean + source?: TemplateSource + projectRoot?: string } export class TemplatesFetchError extends Error { readonly diagnostic: string - constructor(originalError: string) { - super(`无法拉取 ${PACKAGE_NAME}:\n ${originalError}`) + constructor(originalError: string, source: TemplateSource = { packageName: DEFAULT_PACKAGE_NAME, registry: 'https://registry.npmjs.org/' }) { + super(`无法拉取 ${source.packageName}(${source.registry}):\n ${originalError}`) this.name = 'TemplatesFetchError' this.diagnostic = [ '请确认:', ' 1. npm 已安装且在 PATH 中:', ' npm --version', - ' 2. npm registry 配置可访问公共 npm 包:', + ' 2. npm registry 配置可访问:', ' npm config get registry', - ' 3. 当前网络可访问 registry:', - ` curl -I https://registry.npmjs.org/${encodeURIComponent(PACKAGE_NAME)}`, - ' 4. 模板包已发布到上述 registry(维护者首次发版后才可用)', + ` 包:${source.packageName}`, + ` Registry:${source.registry}`, + ' 3. 当前网络可访问所选 registry,且模板包已发布。', ].join('\n') } } @@ -43,166 +46,125 @@ interface CacheMeta { fetchedAt: string } -function npmViewVersion(tag = 'latest'): string { +function npmViewVersion(source: TemplateSource, projectRoot: string, tag = 'latest'): string { let stdout: string try { stdout = execNpmSync( - ['view', `${PACKAGE_NAME}@${tag}`, 'version', '--json'], - { encoding: 'utf-8', timeout: 30_000, stdio: ['pipe', 'pipe', 'pipe'] }, + ['view', `${source.packageName}@${tag}`, 'version', '--json', ...templateRegistryArgs(source)], + { cwd: projectRoot, encoding: 'utf-8', timeout: 30_000, stdio: ['pipe', 'pipe', 'pipe'] }, ) - } catch (e) { - const msg = e instanceof Error ? e.message : String(e) - throw new TemplatesFetchError(msg) + } catch { + throw new TemplatesFetchError('npm view 查询失败。', source) } - try { const version = JSON.parse(stdout) - if (typeof version !== 'string') { - throw new TemplatesFetchError(`npm view 输出格式异常:${stdout.slice(0, 200)}`) - } + if (typeof version !== 'string') throw new Error('invalid version type') return version - } catch (e) { - if (e instanceof TemplatesFetchError) throw e - throw new TemplatesFetchError(`npm view JSON 解析失败:${stdout.slice(0, 200)}`) + } catch { + throw new TemplatesFetchError('npm view 返回了无效版本信息。', source) } } -function assertValidTemplateVersion(version: string): string { - if (!SEMVER_RE.test(version)) { - throw new TemplatesFetchError(`版本号格式异常:${version}`) - } +function assertValidTemplateVersion(version: string, source?: TemplateSource): string { + if (!SEMVER_RE.test(version)) throw new TemplatesFetchError(`版本号格式异常:${version}`, source) return version } function resolveRequestedTemplatesVersion( options: EnsureTemplatesCacheOptions = {}, - stableVersionResolver: () => string = npmViewVersion, - betaVersionResolver: () => string = () => npmViewVersion('beta'), + stableVersionResolver?: () => string, + betaVersionResolver?: () => string, ): string { + const projectRoot = options.projectRoot ?? process.cwd() + const source = options.source ?? ((stableVersionResolver && betaVersionResolver) + ? undefined + : resolveTemplateSource(projectRoot)) + const stable = stableVersionResolver ?? (() => npmViewVersion(source!, projectRoot)) + const beta = betaVersionResolver ?? (() => npmViewVersion(source!, projectRoot, 'beta')) const requestedVersion = options.version?.trim() - if (requestedVersion && options.beta) { - throw new TemplatesFetchError('不能同时指定模板版本和 --beta') - } - - if (requestedVersion) { - return assertValidTemplateVersion(requestedVersion) - } - - if (options.beta) { - return assertValidTemplateVersion(betaVersionResolver()) - } - - return assertValidTemplateVersion(stableVersionResolver()) + if (requestedVersion && options.beta) throw new TemplatesFetchError('不能同时指定模板版本和 --beta', source) + if (requestedVersion) return assertValidTemplateVersion(requestedVersion, source) + if (options.beta) return assertValidTemplateVersion(beta(), source) + return assertValidTemplateVersion(stable(), source) } function readMeta(cacheRoot: string = CACHE_ROOT): CacheMeta | null { - const metaPath = path.join(cacheRoot, META_FILE) - if (!fs.existsSync(metaPath)) return null try { - const content = fs.readFileSync(metaPath, 'utf-8') - return JSON.parse(content) as CacheMeta - } catch { - return null - } + return JSON.parse(fs.readFileSync(path.join(cacheRoot, META_FILE), 'utf-8')) as CacheMeta + } catch { return null } } function writeMeta(meta: CacheMeta, cacheRoot: string = CACHE_ROOT): void { fs.mkdirSync(cacheRoot, { recursive: true }) - const metaPath = path.join(cacheRoot, META_FILE) - fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2), 'utf-8') + fs.writeFileSync(path.join(cacheRoot, META_FILE), JSON.stringify(meta, null, 2), 'utf-8') } -function isUsableCacheDir(cacheDir: string, version: string): boolean { - if (!fs.existsSync(cacheDir)) return false - const packagePath = path.join(cacheDir, 'package.json') - const versionsPath = path.join(cacheDir, 'versions-yml.yml') - if (!fs.existsSync(packagePath) || !fs.existsSync(versionsPath)) return false +function isUsableCacheDir(cacheDir: string, version: string, packageName = DEFAULT_PACKAGE_NAME): boolean { try { - const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf-8')) as Record - return pkg['name'] === PACKAGE_NAME && pkg['version'] === version - } catch { - return false - } + const pkg = JSON.parse(fs.readFileSync(path.join(cacheDir, 'package.json'), 'utf-8')) as Record + return pkg['name'] === packageName && pkg['version'] === version && fs.statSync(path.join(cacheDir, 'versions-yml.yml')).isFile() + } catch { return false } } -function npmPack(version: string, targetDir: string): string { - if (!SEMVER_RE.test(version)) { - throw new TemplatesFetchError(`版本号格式异常:${version}`) - } +async function npmPack(source: TemplateSource, version: string, targetDir: string, projectRoot: string): Promise { + assertValidTemplateVersion(version, source) fs.mkdirSync(targetDir, { recursive: true }) - let stdout: string try { - stdout = execNpmSync( - ['pack', `${PACKAGE_NAME}@${version}`], - { - cwd: targetDir, - encoding: 'utf-8', - timeout: 60_000, - stdio: ['pipe', 'pipe', 'pipe'], - }, + const stdout = await execNpm( + ['pack', `${source.packageName}@${version}`, '--pack-destination', targetDir, '--ignore-scripts', ...templateRegistryArgs(source)], + { cwd: projectRoot, encoding: 'utf-8', timeout: 60_000, maxBuffer: 1024 * 1024 }, ) - } catch (e) { - const msg = e instanceof Error ? e.message : String(e) - throw new TemplatesFetchError(`npm pack 下载失败:${msg}`) - } - - const filename = stdout.trim().split('\n').pop() - if (!filename) { - throw new TemplatesFetchError('npm pack 未返回文件名') + const filename = stdout.trim().split(/\r?\n/).pop() + if (!filename) throw new Error('no pack filename') + const tarball = path.resolve(targetDir, filename) + if (!tarball.startsWith(path.resolve(targetDir) + path.sep) || !fs.existsSync(tarball)) throw new Error('invalid pack path') + return tarball + } catch { + throw new TemplatesFetchError('npm pack 下载失败。', source) } - return path.join(targetDir, filename) } async function extractTarball(tarballPath: string, targetDir: string): Promise { const tmpDir = targetDir + '.tmp' - if (fs.existsSync(tmpDir)) { - fs.rmSync(tmpDir, { recursive: true, force: true }) - } + if (fs.existsSync(tmpDir)) fs.rmSync(tmpDir, { recursive: true, force: true }) fs.mkdirSync(tmpDir, { recursive: true }) - - await extract({ - file: tarballPath, - cwd: tmpDir, - strip: 1, - }) - - if (fs.existsSync(targetDir)) { - fs.rmSync(targetDir, { recursive: true, force: true }) + try { + await extract({ file: tarballPath, cwd: tmpDir, strip: 1 }) + if (fs.existsSync(targetDir)) fs.rmSync(targetDir, { recursive: true, force: true }) + fs.renameSync(tmpDir, targetDir) + } catch (error) { + fs.rmSync(tmpDir, { recursive: true, force: true }) + throw error } - fs.renameSync(tmpDir, targetDir) } -export async function ensureTemplatesCache(options?: EnsureTemplatesCacheOptions): Promise { - const version = resolveRequestedTemplatesVersion(options) - - const versionDir = path.join(CACHE_ROOT, version) - - if (isUsableCacheDir(versionDir, version)) { - writeMeta({ version, fetchedAt: new Date().toISOString() }) +export async function ensureTemplatesCache(options: EnsureTemplatesCacheOptions = {}): Promise { + const projectRoot = path.resolve(options.projectRoot ?? process.cwd()) + const source = options.source ?? resolveTemplateSource(projectRoot) + const version = resolveRequestedTemplatesVersion({ ...options, source, projectRoot }) + const sourceRoot = path.join(CACHE_ROOT, templateSourceKey(source)) + const versionDir = path.join(sourceRoot, version) + if (isUsableCacheDir(versionDir, version, source.packageName)) { + writeMeta({ version, fetchedAt: new Date().toISOString() }, sourceRoot) return { cacheDir: versionDir, version } } - if (fs.existsSync(versionDir)) { - fs.rmSync(versionDir, { recursive: true, force: true }) - } - + if (fs.existsSync(versionDir)) fs.rmSync(versionDir, { recursive: true, force: true }) const downloadDir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-tpl-')) try { - const tarballPath = npmPack(version, downloadDir) + const tarballPath = await npmPack(source, version, downloadDir, projectRoot) await extractTarball(tarballPath, versionDir) + if (!isUsableCacheDir(versionDir, version, source.packageName)) { + fs.rmSync(versionDir, { recursive: true, force: true }) + throw new TemplatesFetchError('下载的模板包名称、版本或 versions-yml.yml 不匹配。', source) + } } finally { fs.rmSync(downloadDir, { recursive: true, force: true }) } - - writeMeta({ version, fetchedAt: new Date().toISOString() }) - + writeMeta({ version, fetchedAt: new Date().toISOString() }, sourceRoot) return { cacheDir: versionDir, version } } export const __test__ = process.env['VITEST'] ? { - readMeta, - writeMeta, - extractTarball, - SEMVER_RE, - isUsableCacheDir, + readMeta, writeMeta, extractTarball, SEMVER_RE, isUsableCacheDir, resolveRequestedTemplatesVersion, } : undefined diff --git a/src/lib/update-notifier.ts b/src/lib/update-notifier.ts index fc789fe..0e7fec8 100644 --- a/src/lib/update-notifier.ts +++ b/src/lib/update-notifier.ts @@ -1,12 +1,11 @@ import fs from 'node:fs' import path from 'node:path' import os from 'node:os' -import { execFile } from 'node:child_process' import { gt, valid } from 'semver' import { readVersions } from './versions.js' +import { execNpm } from './npm-command.js' +import { resolveTemplateSource, templateRegistryArgs, templateSourceKey, type TemplateSource } from './template-source.js' -const PACKAGE_NAME = 'devkeel-templates' -const REGISTRY = 'https://registry.npmjs.org/' const CACHE_TTL = 3 * 24 * 60 * 60 * 1000 const FETCH_TIMEOUT = 3000 @@ -17,6 +16,7 @@ function getCachePath(): string { export interface UpdateCache { lastCheck: number latestVersion: string + sourceKey?: string } export function readUpdateCache(cachePath = getCachePath()): UpdateCache | null { @@ -30,6 +30,7 @@ export function readUpdateCache(cachePath = getCachePath()): UpdateCache | null return { lastCheck: parsed['lastCheck'], latestVersion: parsed['latestVersion'], + ...(typeof parsed['sourceKey'] === 'string' ? { sourceKey: parsed['sourceKey'] } : {}), } } catch { return null @@ -51,20 +52,18 @@ export function compareVersions(current: string, latest: string): boolean { return currentVersion !== null && latestVersion !== null && gt(latestVersion, currentVersion) } -export function fetchLatestVersion(): Promise { - return new Promise((resolve) => { - execFile('npm', ['view', `${PACKAGE_NAME}@latest`, 'version', `--registry=${REGISTRY}`, '--json'], - { timeout: FETCH_TIMEOUT }, - (error, stdout) => { - if (error) { resolve(null); return } - try { - const version = JSON.parse(stdout) - if (typeof version === 'string' && version.length > 0) { resolve(version); return } - } catch { /* fall through */ } - resolve(null) - }, +export async function fetchLatestVersion( + source: TemplateSource, + projectRoot = process.cwd(), +): Promise { + try { + const stdout = await execNpm( + ['view', `${source.packageName}@latest`, 'version', ...templateRegistryArgs(source), '--json'], + { cwd: projectRoot, timeout: FETCH_TIMEOUT }, ) - }) + const version: unknown = JSON.parse(stdout) + return typeof version === 'string' && valid(version) ? version : null + } catch { return null } } export function formatUpdatePrompt(from: string, to: string): string { @@ -78,29 +77,34 @@ export function formatUpdatePrompt(from: string, to: string): string { export async function checkAndNotify( projectRoot = process.cwd(), - cachePath = getCachePath(), + cachePath?: string, ): Promise { try { const versions = readVersions(projectRoot) if (!versions) return null + const source = resolveTemplateSource(projectRoot) + const sourceKey = templateSourceKey(source) + const sourceCachePath = cachePath ?? path.join(path.dirname(getCachePath()), `devkeel-update-check-${sourceKey}.json`) + const currentVersion = versions.harness - const cache = readUpdateCache(cachePath) + const cache = readUpdateCache(sourceCachePath) let latestVersion: string | null = null - if (cache && !isCacheExpired(cache)) { + if (cache?.sourceKey === sourceKey && !isCacheExpired(cache)) { latestVersion = cache.latestVersion } if (!latestVersion) { - latestVersion = await fetchLatestVersion() + latestVersion = await fetchLatestVersion(source, projectRoot) if (!latestVersion) return null writeUpdateCache({ lastCheck: Date.now(), latestVersion, - }, cachePath) + sourceKey, + }, sourceCachePath) } if (!compareVersions(currentVersion, latestVersion)) return null diff --git a/src/lib/update.ts b/src/lib/update.ts index cdb670b..58b582b 100644 --- a/src/lib/update.ts +++ b/src/lib/update.ts @@ -1213,6 +1213,7 @@ export function detectUpdates( force = false, templatesDir = getTemplatesDir(), builtinVersions = getBuiltinVersions(templatesDir), + sourceChanged = false, ): UpdateItem[] { const current = readVersions(projectRoot) if (!current) return [] @@ -1227,8 +1228,10 @@ export function detectUpdates( const builtinMap = (builtin[category] ?? {}) as Record for (const [name, version] of Object.entries(builtinMap)) { const currentVersion = currentMap[name] - if (force || !currentVersion || currentVersion !== version) { - const from = force && currentVersion === version + if (sourceChanged || force || !currentVersion || currentVersion !== version) { + const from = sourceChanged && currentVersion === version + ? `${currentVersion} (source changed)` + : force && currentVersion === version ? `${currentVersion} (force)` : currentVersion ?? '(missing)' updates.push({ category, name, from, to: version }) @@ -1257,8 +1260,10 @@ export function detectUpdates( }) } - if (force || current.harness !== builtin.harness) { - const from = force && current.harness === builtin.harness + if (sourceChanged || force || current.harness !== builtin.harness) { + const from = sourceChanged && current.harness === builtin.harness + ? `${current.harness} (source changed)` + : force && current.harness === builtin.harness ? `${current.harness} (force)` : current.harness updates.push({ category: 'core', name: 'harness', from, to: builtin.harness }) diff --git a/src/lib/versions.ts b/src/lib/versions.ts index 2dcc64d..d6a853d 100644 --- a/src/lib/versions.ts +++ b/src/lib/versions.ts @@ -16,6 +16,7 @@ function readSchemaVersion(schemaName: string, base: string): string | null { export interface VersionsRecord { harness: string + templateSource?: string skills: Record agents: Record rules: Record @@ -43,6 +44,7 @@ export function filterManagedVersions( } return { harness: versions.harness, + ...(versions.templateSource ? { templateSource: versions.templateSource } : {}), skills: {}, agents: {}, rules: {}, diff --git a/templates/skills/domain-init/SKILL.md b/templates/skills/domain-init/SKILL.md index 4eb24ad..3e0aea2 100644 --- a/templates/skills/domain-init/SKILL.md +++ b/templates/skills/domain-init/SKILL.md @@ -7,7 +7,7 @@ description: >- 触发词:domain-init、领域初始化、生成领域规范、领域扫描 metadata: author: "devkeel" - version: "2.0.2" + version: "2.1.0" --- # Domain Init — 项目领域能力生成器 @@ -31,6 +31,7 @@ metadata: - `references/project-index.md` — 参考项目索引(GitHub 地址 + 参考内容) - `references/output-formats.md` — 产出格式规范 + 质量标准 - `references/domain-matrix.md` — 领域适用性矩阵(8 大领域 × 23 维度) +- `references/architecture-knowledge.md` — 选中 K1,或增强项涉及架构知识时,读取扫描与验收要求 ## 何时使用 @@ -101,6 +102,7 @@ Phase 4: 收尾 → 配置更新 + 链接检查 + 生成报告 | ID | 维度 | 候选产出 | subAgent 职责 | |----|------|------|--------------| +| K1 | 架构知识 | docs | 按 `references/architecture-knowledge.md` 扫描结构、组件归属、通信与关键流程 | | R1 | 编码规范 | rule / docs | 扫描代码风格、格式化配置、lint 规则、导入习惯 | | R4 | 测试策略 | rule / docs | 扫描测试框架、覆盖模式、测试文件组织、mock 策略 | | R5 | 错误处理 | rule / docs | 扫描异常模式、日志使用、错误边界、重试策略 | @@ -111,6 +113,8 @@ Phase 4: 收尾 → 配置更新 + 链接检查 + 生成报告 | R20 | 编辑纪律 | rule / docs | 基于 surgical changes 原则:只改相关代码 | | A1 | 领域 Code Reviewer | agent | 基于以上扫描结果生成专属审查维度和输出规则 | +K1 面向所有领域,按实际代码触点裁剪;是否生成和调查深度仍由下述范围确认决定。 + ### 2.2 用户选择与优先级确认 **在扫描前,必须先让用户确认 baseline 范围和优先级。** @@ -246,7 +250,7 @@ node .harness/skills/domain-init/scripts/sync-submodule-skills.mjs --prune # ### 4.4 生成报告 -输出本次生成的完整清单(类型、文件、状态、参考项目),标记新增 vs 增强,建议后续完善方向,提醒用户 review 后 commit。 +输出本次生成的完整清单(类型、文件、简述、状态、参考项目),标记新增 vs 增强,列出待确认事项、未覆盖范围与未验证行为,建议后续完善方向,并提醒用户 review 后 commit。 ### 4.5 更新文档与 AGENTS 入口 @@ -258,7 +262,7 @@ node .harness/skills/domain-init/scripts/sync-submodule-skills.mjs --prune # 3. 更新 AGENTS 的文档链接与读取条件,规则和能力通过最小触发矩阵发现;不要求全量读取 docs。 4. 填充完成后删除该槽位成对的 `` / `` 边界注释与已用完的占位提示,保留正文及相邻框架内容。未填槽位保留占位;已有正文不重加标记。 -5. 核对相对链接、规则触发范围和事实来源。后续实施改变已验证的项目事实时,同步相关文档。 +5. 按 `references/output-formats.md` 的质量标准核对产物及规则触发范围。后续实施改变已验证的项目事实时,同步相关文档。 | 用户槽位 | 内容 | |----------|------| diff --git a/templates/skills/domain-init/references/architecture-knowledge.md b/templates/skills/domain-init/references/architecture-knowledge.md new file mode 100644 index 0000000..94c4b91 --- /dev/null +++ b/templates/skills/domain-init/references/architecture-knowledge.md @@ -0,0 +1,52 @@ +# 架构知识扫描与验收 + +选中 K1,或增强项涉及当前架构说明时使用。记录当前实现;待实施方案留在任务文档中。 +只调查已确认的作用域和主题,按 `output-formats.md` 归属、引用与合并产物。 + +## 扫描顺序 + +1. **定位仓库与入口**:识别单仓、monorepo 或多仓;读取各目标仓库的 manifest、构建配置、 + 启动入口与已有文档。分别确认职责、技术栈、共享配置和依赖集成方式;根项目记录跨项目关系, + 子项目记录自身实现,跨项目通过链接关联。 +2. **追踪结构与依赖**:沿入口和代表性调用链核对模块、分层、组装位置与依赖方向。 + 区分源码调用、包/构建依赖与进程间通信;命名和目录只能提供线索,结论须核对代码与配置。 +3. **追踪通信与流程**:从已确认范围内的关键入口追到结果及失败分支,核对跨边界调用、 + 消息或事件定义、状态变化及恢复处理。高优先项深入边界与例外,其余按已确认深度采样。 +4. **映射已有文档**:将发现对应到已有主题和缺口,形成目标文件、依据及待确认事项,交回 + Phase 2/3 review;跨仓调用链的发现不扩大对子项目的写入授权。 + +## 按需覆盖的内容 + +以下是内容检查项,不是固定章节或文件清单。已有文档能承接时直接更新;简单项目可合并, +没有触点的主题省略。DDD 仅在代码或已确认约定支持时展开。 + +| 主题 | 应回答的问题 | 可复用的文档位置示例 | +|------|--------------|----------------------| +| 项目与结构 | 项目做什么;各仓库/模块、入口、技术栈、分层、依赖方向与集成方式是什么 | project.md、architecture.md | +| 组件与归属 | 组件负责和不负责什么;边界依据是什么;新功能按什么判据归属 | architecture.md;内容较多时 components.md / modules.md | +| 通信与契约 | 谁调用谁;同步/异步、协议或机制、接口/消息定义、用途、所属模块和代码入口是什么 | architecture.md;按需拆分 communication-patterns.md / interfaces.md | +| 关键流程 | 从触发到结果经过哪些组件和状态;关键失败、超时、重试、取消或恢复在何处处理 | 现有业务专题;按需创建流程文档 | +| 开发与交付 | 在哪里运行构建、测试和发布;哪些配置或脚本定义环境、版本与依赖更新方式 | development.md、testing.md、已有发布文档 | + +组件归属在存在多种落点时使用简短决策表,列出任务类型、所属组件与边界依据。 +现有代码只能证明边界和依赖;历史划分理由遵循 Docs 的证据标记要求,不反推为已确认决定。 + +通信检查由实际触点触发,覆盖 HTTP/RPC、队列、IPC、CLI/SDK 调用、回调或事件。 +接口清单优先链接已有协议、schema、路由或公开头文件;缺少导航时仅补充定位表,字段按机制裁剪 +为方法/命令/路径/topic、用途、调用方与接收方、所属模块和定义位置,避免复制完整定义。 +未发现的超时或恢复机制记为扫描范围内的缺口,不补写理想行为。 + +## 图表与导航 + +- 模块或跨仓关系难以用短文解释时,用 Mermaid flowchart/graph 表达职责与依赖方向; + 跨组件交互复杂时用 sequenceDiagram,必要时补充状态图。简单关系用文字或表格。 +- 图中参与者、调用方向和状态须与实现及正文一致。显示文本加引号;classDiagram 使用合法类 + 标识符,不将带 `::` 的命名空间直接用作类标识符。 +- 专题之间用相对链接关联;文档索引注明用途和读取场景,AGENTS 只链接实际存在的文档。 + +## 完成检查 + +- 读者能找到入口、职责边界、依赖方向与相关代码,能判断新增功能的归属。 +- 已选且有触点的通信与流程说明包含调用双方、关键状态和失败路径;无法追踪的边界已列明。 +- 图表、正文和接口导航使用一致名称与方向,关键结论可定位到证据。 +- 已覆盖主题能指向目标文档;未覆盖范围、推断、待确认事项和未验证行为进入报告。 diff --git a/templates/skills/domain-init/references/dimension-pool.md b/templates/skills/domain-init/references/dimension-pool.md index 57a5d3a..8165dc9 100644 --- a/templates/skills/domain-init/references/dimension-pool.md +++ b/templates/skills/domain-init/references/dimension-pool.md @@ -2,6 +2,9 @@ 基于 Phase 1 识别的领域,**过滤掉不适用的维度**后,向用户展示可选增强项。 R-* 是扫描主题:执行约束进入 rules,背景、结构和示例进入 docs;不强制每个主题生成 rule。 +选中 R2、R3、R9、S12 或 S13 且涉及当前架构知识时,读取 +[架构知识扫描与验收](architecture-knowledge.md)。已选择 K1 时复用本轮扫描和已有产物,仅补选中范围的缺口。 +通信与流程按实际触点调查,包含系统/C++ 的 IPC、回调和事件,不受 R9 的展示过滤限制。 ## 规则与项目知识增强池 diff --git a/templates/skills/domain-init/references/output-formats.md b/templates/skills/domain-init/references/output-formats.md index b9420cf..7e79b86 100644 --- a/templates/skills/domain-init/references/output-formats.md +++ b/templates/skills/domain-init/references/output-formats.md @@ -24,6 +24,10 @@ OpenSpec 内容保留在主仓库 `openspec/`;项目文档引用相关规范 标题说明主题;按实际需要记录适用范围、当前事实、来源和相关入口,不强制章节数量。 命令注明运行目录并链接对应 scripts;详细示例注明用途,不把示意代码当作当前实现。 +关键结论引用代码或配置的相对路径与符号,必要时给出起始行;已确认约定链接其记录。 +缺少证据的历史设计理由标为「推测」或「待确认」,改进建议与当前事实分开。 +只做静态扫描时明确证据边界,不将配置声明或调用关系写成已运行验证的行为。 + - `docs/README.md` 可作为按任务组织的索引,已有索引则复用。 - 文件名沿用项目惯例;项目概览、架构、开发与测试说明按需创建,不生成空目录和占位文档。 - AGENTS 的 `project` 槽位统一维护项目知识入口;rules 按需引用相关说明。只添加已存在文件 @@ -94,6 +98,8 @@ model: sonnet | 内容归属 | 约束与知识分开,低频硬约束不丢失 | | 文档引用 | 链接存在、读取条件明确、同主题复用 | | 代码依据 | 约定必须能在项目代码中找到出处 | +| 术语一致 | 模块、组件、接口和消息名称在正文、图表与引用中一致 | +| 架构知识 | 涉及架构的产物按 [架构知识扫描与验收](architecture-knowledge.md) 检查 | | Skill 完整性 | 必须有「何时使用」和「Hard Rules」 | | Agent 完整性 | 必须有「审查维度」和「输出规则」 | | 禁止理想化 | 不输出与项目实际不符的规范 | diff --git a/templates/versions-yml.yml b/templates/versions-yml.yml index c4198e2..406ecde 100644 --- a/templates/versions-yml.yml +++ b/templates/versions-yml.yml @@ -19,7 +19,7 @@ skills: openspec-onboard: "2.4" openspec-sync-specs: "2.2" openspec-verify-change: "3.4" - domain-init: "2.0.2" + domain-init: "2.1.0" verify-init: "2.0.1" ui-fidelity-playbook: "1.0.3" rules: {} diff --git a/tests/init-agents.test.ts b/tests/init-agents.test.ts index 83cafdf..f662755 100644 --- a/tests/init-agents.test.ts +++ b/tests/init-agents.test.ts @@ -51,6 +51,8 @@ vi.mock('@clack/prompts', () => ({ describe.sequential('init AGENTS templates', () => { const originalCwd = process.cwd() + const originalHome = process.env['USERPROFILE'] + const originalUnixHome = process.env['HOME'] let projectDir: string beforeEach(() => { @@ -61,10 +63,16 @@ describe.sequential('init AGENTS templates', () => { vi.mocked(prompts.confirm).mockResolvedValue(false) vi.mocked(prompts.multiselect).mockReset() vi.mocked(prompts.multiselect).mockResolvedValue([]) + process.env['USERPROFILE'] = projectDir + process.env['HOME'] = projectDir process.chdir(projectDir) }) afterEach(() => { + if (originalHome === undefined) delete process.env['USERPROFILE'] + else process.env['USERPROFILE'] = originalHome + if (originalUnixHome === undefined) delete process.env['HOME'] + else process.env['HOME'] = originalUnixHome process.chdir(originalCwd) fs.rmSync(projectDir, { recursive: true, force: true }) }) diff --git a/tests/npm-command.test.ts b/tests/npm-command.test.ts index 717f706..0171008 100644 --- a/tests/npm-command.test.ts +++ b/tests/npm-command.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { __test__ } from '../src/lib/npm-command.js' +import { __test__, execNpm } from '../src/lib/npm-command.js' const { resolveNpmInvocation } = __test__! @@ -57,4 +57,8 @@ describe('npm-command', () => { } }) }) + + it('exposes an asynchronous npm runner using the same platform invocation', async () => { + await expect(execNpm(['--version'])).resolves.toMatch(/^\d+\.\d+/) + }) }) diff --git a/tests/template-source-cli.test.ts b/tests/template-source-cli.test.ts new file mode 100644 index 0000000..b8e2b22 --- /dev/null +++ b/tests/template-source-cli.test.ts @@ -0,0 +1,356 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { spawnSync } from 'node:child_process' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import YAML from 'yaml' +import { create } from 'tar' + +const HARNESS_BIN = path.resolve('bin/devkeel.js') +const TEMPLATE_ROOT = path.resolve('templates') + +describe('template source CLI', () => { + let tmpDir: string + let fakeBinDir: string + let fakeNpmScript: string + let npmLog: string + let tarballs: Record + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-template-source-cli-')) + fakeBinDir = path.join(tmpDir, 'bin') + fs.mkdirSync(fakeBinDir, { recursive: true }) + npmLog = path.join(tmpDir, 'npm-log.jsonl') + tarballs = {} + + fakeNpmScript = path.join(fakeBinDir, 'fake-npm.cjs') + fs.writeFileSync(fakeNpmScript, [ + "'use strict'", + "const fs = require('node:fs')", + "const path = require('node:path')", + 'const args = process.argv.slice(2)', + "fs.appendFileSync(process.env['FAKE_NPM_LOG'], JSON.stringify({ args, cwd: process.cwd() }) + '\\n')", + "if (args[0] === 'config' && args[1] === 'get') { process.stdout.write(process.env['FAKE_NPM_REGISTRY'] + '\\n'); process.exit(0) }", + "if (args[0] === 'view') { process.stdout.write(JSON.stringify(process.env['FAKE_NPM_VERSION']) + '\\n'); process.exit(0) }", + "if (args[0] === 'pack') {", + " const nameAndVersion = args[1]", + " const tarballs = JSON.parse(process.env['FAKE_NPM_TARBALLS'])", + " if (nameAndVersion.startsWith(process.env['FAKE_NPM_FAIL_PACKAGE'] + '@')) process.exit(1)", + ' const registryArg = args.find(arg => arg.startsWith("--registry="))', + ' const registry = registryArg ? registryArg.slice("--registry=".length) : ""', + ' const tarball = tarballs[`${nameAndVersion}|${registry}`] || tarballs[nameAndVersion]', + " const destination = args[args.indexOf('--pack-destination') + 1]", + ' if (!tarball || !destination || args.includes("--ignore-scripts") === false) process.exit(1)', + ' const filename = path.basename(tarball)', + ' fs.copyFileSync(tarball, path.join(destination, filename))', + ' process.stdout.write(filename + "\\n")', + ' process.exit(0)', + '}', + 'process.exit(1)', + '', + ].join('\n'), 'utf-8') + + const npmExecutable = path.join(fakeBinDir, process.platform === 'win32' ? 'npm.cmd' : 'npm') + const wrapper = process.platform === 'win32' + ? `@"${process.execPath}" "${fakeNpmScript}" %*\r\n` + : `#!/bin/sh\nexec "${process.execPath}" "${fakeNpmScript}" "$@"\n` + fs.writeFileSync(npmExecutable, wrapper, 'utf-8') + if (process.platform !== 'win32') fs.chmodSync(npmExecutable, 0o755) + }) + + afterEach(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }) + }) + + async function createTemplateTarball(packageName: string, version: string, marker: string, registry?: string, agentsMarker?: string): Promise { + const identity = `${packageName.replaceAll('/', '-')}-${version}-${Object.keys(tarballs).length}` + const fixtureRoot = path.join(tmpDir, 'fixtures', identity) + const packageRoot = path.join(fixtureRoot, 'package') + fs.mkdirSync(packageRoot, { recursive: true }) + fs.cpSync(TEMPLATE_ROOT, packageRoot, { recursive: true }) + fs.writeFileSync(path.join(packageRoot, 'package.json'), JSON.stringify({ name: packageName, version }), 'utf-8') + + const versionsPath = path.join(packageRoot, 'versions-yml.yml') + const versions = YAML.parse(fs.readFileSync(versionsPath, 'utf-8')) as { + rules: Record + } + versions.rules['source-fixture'] = '1.0.0' + fs.writeFileSync(versionsPath, YAML.stringify(versions), 'utf-8') + const markerPath = path.join(packageRoot, 'rules', 'source-fixture.md') + fs.mkdirSync(path.dirname(markerPath), { recursive: true }) + fs.writeFileSync(markerPath, `${marker}\n`, 'utf-8') + + if (agentsMarker) fs.appendFileSync(path.join(packageRoot, 'agents-md.md'), `\n${agentsMarker}\n`) + const tarball = path.join(tmpDir, `${identity}.tgz`) + await create({ gzip: true, file: tarball, cwd: fixtureRoot }, ['package']) + tarballs[registry ? `${packageName}@${version}|${registry}` : `${packageName}@${version}`] = tarball + return tarball + } + + function runCli(projectRoot: string, args: string[], env: NodeJS.ProcessEnv = {}): ReturnType { + return spawnSync(process.execPath, [HARNESS_BIN, ...args], { + cwd: projectRoot, + encoding: 'utf-8', + timeout: 30_000, + env: { + ...env, + HOME: path.join(tmpDir, 'home'), + USERPROFILE: path.join(tmpDir, 'home'), + PATH: `${fakeBinDir}${path.delimiter}${process.env['PATH'] ?? ''}`, + FAKE_NPM_LOG: npmLog, + FAKE_NPM_REGISTRY: 'https://npm-config.example.test/', + FAKE_NPM_VERSION: env['FAKE_NPM_VERSION'] ?? '1.0.0', + FAKE_NPM_TARBALLS: JSON.stringify(tarballs), + }, + }) + } + + function readNpmCalls(): Array<{ args: string[]; cwd: string }> { + if (!fs.existsSync(npmLog)) return [] + return fs.readFileSync(npmLog, 'utf-8').trim().split(/\r?\n/).filter(Boolean) + .map(line => JSON.parse(line) as { args: string[]; cwd: string }) + } + + function projectSourcePath(projectRoot: string): string { + return path.join(projectRoot, '.harness', 'template-source.json') + } + + function userSourcePath(): string { + return path.join(tmpDir, 'home', '.harness', 'template-source.json') + } + + function writeUserSource(source: Record): void { + fs.mkdirSync(path.dirname(userSourcePath()), { recursive: true }) + fs.writeFileSync(userSourcePath(), JSON.stringify(source, null, 2) + '\n', 'utf-8') + } + + function readProjectSource(projectRoot: string): unknown { + return JSON.parse(fs.readFileSync(projectSourcePath(projectRoot), 'utf-8')) + } + + function readVersionsText(projectRoot: string): string { + return fs.readFileSync(path.join(projectRoot, '.harness', 'versions.yml'), 'utf-8') + } + + it('should init from an explicit source, save it, and run npm in the project root', async () => { + await createTemplateTarball('@acme/templates', '1.0.0', 'custom source') + const projectRoot = path.join(tmpDir, 'project') + fs.mkdirSync(projectRoot) + fs.writeFileSync(path.join(projectRoot, '.npmrc'), '//registry.example.test/:_authToken=fixture-token\n', 'utf-8') + + const result = runCli(projectRoot, [ + 'init', '--yes', '--name', 'source-fixture', '--targets', 'copilot', + '--template-package', '@acme/templates', '--template-registry', 'https://registry.example.test', + ]) + + expect(result.status).toBe(0) + expect(readProjectSource(projectRoot)).toEqual({ + packageName: '@acme/templates', + registry: 'https://registry.example.test/', + }) + expect(fs.existsSync(userSourcePath())).toBe(false) + expect(fs.readFileSync(path.join(projectRoot, '.harness', 'rules', 'source-fixture.md'), 'utf-8')).toBe('custom source\n') + const calls = readNpmCalls() + expect(calls.length).toBeGreaterThan(0) + expect(calls.every(call => call.cwd === projectRoot)).toBe(true) + expect(calls.some(call => call.args[0] === 'pack' + && call.args.includes('--pack-destination') + && call.args.includes('--ignore-scripts') + && call.args.includes('--@acme:registry=https://registry.example.test/'))).toBe(true) + }) + + it('should let separate projects inherit one user source without creating project source files', async () => { + await createTemplateTarball('global-templates', '1.0.0', 'inherited source') + const userSource = { packageName: 'global-templates', registry: 'https://global.example.test/' } + writeUserSource(userSource) + const firstProject = path.join(tmpDir, 'first-project') + const secondProject = path.join(tmpDir, 'second-project') + fs.mkdirSync(firstProject) + fs.mkdirSync(secondProject) + + for (const projectRoot of [firstProject, secondProject]) { + const result = runCli(projectRoot, ['init', '--yes', '--name', 'source-fixture', '--targets', 'copilot']) + expect(result.status).toBe(0) + expect(fs.existsSync(projectSourcePath(projectRoot))).toBe(false) + expect(fs.readFileSync(path.join(projectRoot, '.harness', 'rules', 'source-fixture.md'), 'utf-8')).toBe('inherited source\n') + } + + expect(fs.readFileSync(userSourcePath(), 'utf-8')).toBe(JSON.stringify(userSource, null, 2) + '\n') + const packageCalls = readNpmCalls().filter(call => call.args[0] === 'pack') + expect(packageCalls).toHaveLength(1) + expect(packageCalls.every(call => call.args[1] === 'global-templates@1.0.0' + && call.args.includes('--registry=https://global.example.test/'))).toBe(true) + }) + + it('should isolate cache entries for the same package and version on different registries', async () => { + await createTemplateTarball('shared-templates', '1.0.0', 'registry one', 'https://one.example.test/') + await createTemplateTarball('shared-templates', '1.0.0', 'registry two', 'https://two.example.test/') + const firstProject = path.join(tmpDir, 'registry-one-project') + const secondProject = path.join(tmpDir, 'registry-two-project') + fs.mkdirSync(firstProject) + fs.mkdirSync(secondProject) + + const first = runCli(firstProject, [ + 'init', '--yes', '--name', 'source-fixture', '--targets', 'copilot', + '--template-package', 'shared-templates', '--template-registry', 'https://one.example.test/', + ]) + const second = runCli(secondProject, [ + 'init', '--yes', '--name', 'source-fixture', '--targets', 'copilot', + '--template-package', 'shared-templates', '--template-registry', 'https://two.example.test/', + ]) + + expect(first.status).toBe(0) + expect(second.status).toBe(0) + expect(fs.readFileSync(path.join(firstProject, '.harness', 'rules', 'source-fixture.md'), 'utf-8')).toBe('registry one\n') + expect(fs.readFileSync(path.join(secondProject, '.harness', 'rules', 'source-fixture.md'), 'utf-8')).toBe('registry two\n') + }) + + it('should reject a tarball whose package name does not match the requested source', async () => { + const wrongPackageTarball = await createTemplateTarball('wrong-templates', '1.0.0', 'wrong package') + tarballs['expected-templates@1.0.0'] = wrongPackageTarball + const projectRoot = path.join(tmpDir, 'project') + fs.mkdirSync(projectRoot) + + const result = runCli(projectRoot, [ + 'init', '--yes', '--name', 'source-fixture', '--targets', 'copilot', + '--template-package', 'expected-templates', '--template-registry', 'https://registry.example.test/', + ]) + + expect(result.status).not.toBe(0) + expect(fs.existsSync(path.join(projectRoot, '.harness', 'versions.yml'))).toBe(false) + expect(fs.existsSync(projectSourcePath(projectRoot))).toBe(false) + }) + + it('should reuse the saved package and registry on force update and fetch its new version', async () => { + await createTemplateTarball('acme-templates', '1.0.0', 'version one') + const projectRoot = path.join(tmpDir, 'project') + fs.mkdirSync(projectRoot) + const init = runCli(projectRoot, [ + 'init', '--yes', '--name', 'source-fixture', '--targets', 'copilot', + '--template-package', 'acme-templates', '--template-registry', 'https://source.example.test/', + ]) + expect(init.status).toBe(0) + + await createTemplateTarball('acme-templates', '1.1.0', 'version two') + const update = runCli(projectRoot, ['update', '--force'], { FAKE_NPM_VERSION: '1.1.0' }) + + expect(update.status).toBe(0) + expect(readProjectSource(projectRoot)).toEqual({ + packageName: 'acme-templates', + registry: 'https://source.example.test/', + }) + expect(fs.readFileSync(path.join(projectRoot, '.harness', 'rules', 'source-fixture.md'), 'utf-8')).toBe('version two\n') + const calls = readNpmCalls().filter(call => call.args[0] === 'view' || call.args[0] === 'pack') + expect(calls.some(call => call.args[1] === 'acme-templates@latest')).toBe(true) + expect(calls.some(call => call.args[0] === 'pack' + && call.args[1] === 'acme-templates@1.1.0' + && call.args.includes('--registry=https://source.example.test/'))).toBe(true) + }) + + it('should leave project source and assets untouched for a dry-run source switch', async () => { + await createTemplateTarball('first-templates', '1.0.0', 'first source') + await createTemplateTarball('second-templates', '1.0.0', 'second source') + const projectRoot = path.join(tmpDir, 'project') + fs.mkdirSync(projectRoot) + const init = runCli(projectRoot, [ + 'init', '--yes', '--name', 'source-fixture', '--targets', 'copilot', + '--template-package', 'first-templates', '--template-registry', 'https://first.example.test/', + ]) + expect(init.status).toBe(0) + const sourceBefore = fs.readFileSync(projectSourcePath(projectRoot), 'utf-8') + const versionsBefore = readVersionsText(projectRoot) + const assetPath = path.join(projectRoot, '.harness', 'rules', 'source-fixture.md') + const assetBefore = fs.readFileSync(assetPath, 'utf-8') + const previousCalls = readNpmCalls().length + + const update = runCli(projectRoot, [ + 'update', '--dry-run', '--template-package', 'second-templates', + '--template-registry', 'https://second.example.test/', + ]) + + expect(update.status).toBe(0) + expect(update.stdout).toMatch(/source-fixture.*1\.0\.0 \(source changed\)\s*→\s*1\.0\.0/) + expect(fs.readFileSync(projectSourcePath(projectRoot), 'utf-8')).toBe(sourceBefore) + expect(readVersionsText(projectRoot)).toBe(versionsBefore) + expect(fs.readFileSync(assetPath, 'utf-8')).toBe(assetBefore) + expect(readNpmCalls().slice(previousCalls).some(call => call.args[0] === 'view' + && call.args[1] === 'second-templates@latest')).toBe(true) + }) + + it('should refresh assets when switching source even if component versions match', async () => { + await createTemplateTarball('first-templates', '1.0.0', 'first source') + await createTemplateTarball('second-templates', '1.0.0', 'second source') + const projectRoot = path.join(tmpDir, 'project') + fs.mkdirSync(projectRoot) + const init = runCli(projectRoot, [ + 'init', '--yes', '--name', 'source-fixture', '--targets', 'copilot', + '--template-package', 'first-templates', '--template-registry', 'https://first.example.test/', + ]) + expect(init.status).toBe(0) + + const update = runCli(projectRoot, [ + 'update', '--force', '--template-package', 'second-templates', + '--template-registry', 'https://second.example.test/', + ]) + + expect(update.status).toBe(0) + expect(fs.readFileSync(path.join(projectRoot, '.harness', 'rules', 'source-fixture.md'), 'utf-8')).toBe('second source\n') + expect(readProjectSource(projectRoot)).toEqual({ + packageName: 'second-templates', + registry: 'https://second.example.test/', + }) + }) + + it('should keep the old source and retry a partially applied init source switch', async () => { + await createTemplateTarball('first-templates', '1.0.0', 'first source') + await createTemplateTarball('second-templates', '1.0.0', 'second source', undefined, 'New source execution contract') + const projectRoot = path.join(tmpDir, 'project') + fs.mkdirSync(projectRoot) + const common = ['--template-registry', 'https://source.example.test/'] + expect(runCli(projectRoot, [ + 'init', '--yes', '--name', 'source-fixture', '--targets', 'copilot', + '--template-package', 'first-templates', ...common, + ]).status).toBe(0) + const originalSource = fs.readFileSync(projectSourcePath(projectRoot), 'utf-8') + const originalAgents = fs.readFileSync(path.join(projectRoot, 'AGENTS.md'), 'utf-8') + const switched = runCli(projectRoot, [ + 'init', '--yes', '--name', 'source-fixture', '--targets', 'copilot', + '--template-package', 'second-templates', ...common, + ]) + expect(switched.status).toBe(0) + expect(fs.readFileSync(projectSourcePath(projectRoot), 'utf-8')).toBe(originalSource) + expect(fs.readFileSync(path.join(projectRoot, 'AGENTS.md'), 'utf-8')).toBe(originalAgents) + expect(YAML.parse(readVersionsText(projectRoot)).templateSource).toBe('pending') + const retried = runCli(projectRoot, ['update', '--force', '--template-package', 'second-templates', ...common]) + expect(retried.status).toBe(0) + expect(readProjectSource(projectRoot)).toEqual({ packageName: 'second-templates', registry: 'https://source.example.test/' }) + expect(YAML.parse(readVersionsText(projectRoot)).templateSource).toMatch(/^[a-f0-9]{64}$/) + expect(fs.readFileSync(path.join(projectRoot, 'AGENTS.md'), 'utf-8')).toContain('New source execution contract') + }) + + it('should preserve the old source and assets when fetching a switched source fails', async () => { + await createTemplateTarball('first-templates', '1.0.0', 'first source') + await createTemplateTarball('second-templates', '1.0.0', 'second source') + const projectRoot = path.join(tmpDir, 'project') + fs.mkdirSync(projectRoot) + const init = runCli(projectRoot, [ + 'init', '--yes', '--name', 'source-fixture', '--targets', 'copilot', + '--template-package', 'first-templates', '--template-registry', 'https://first.example.test/', + ]) + expect(init.status).toBe(0) + const sourceBefore = fs.readFileSync(projectSourcePath(projectRoot), 'utf-8') + const versionsBefore = readVersionsText(projectRoot) + const assetPath = path.join(projectRoot, '.harness', 'rules', 'source-fixture.md') + const assetBefore = fs.readFileSync(assetPath, 'utf-8') + + const update = runCli(projectRoot, [ + 'update', '--force', '--template-package', 'second-templates', + '--template-registry', 'https://second.example.test/', + ], { FAKE_NPM_FAIL_PACKAGE: 'second-templates' }) + + expect(update.status).not.toBe(0) + expect(fs.readFileSync(projectSourcePath(projectRoot), 'utf-8')).toBe(sourceBefore) + expect(readVersionsText(projectRoot)).toBe(versionsBefore) + expect(fs.readFileSync(assetPath, 'utf-8')).toBe(assetBefore) + }) +}) diff --git a/tests/template-source.test.ts b/tests/template-source.test.ts new file mode 100644 index 0000000..46b4ff2 --- /dev/null +++ b/tests/template-source.test.ts @@ -0,0 +1,185 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { + DEFAULT_TEMPLATE_PACKAGE, + hasTemplateSourceChanged, + readTemplateSource, + readUserTemplateSource, + resolveTemplateSource, + templateRegistryArgs, + templateSourceKey, + writeTemplateSource, +} from '../src/lib/template-source.js' + +describe('template-source', () => { + let tmpDir: string + let projectRoot: string + let homeDir: string + + beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-template-source-')) + projectRoot = path.join(tmpDir, 'project') + homeDir = path.join(tmpDir, 'home') + fs.mkdirSync(projectRoot, { recursive: true }) + fs.mkdirSync(homeDir, { recursive: true }) + }) + + afterEach(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }) + }) + + function writeProjectSource(source: Record): void { + const file = path.join(projectRoot, '.harness', 'template-source.json') + fs.mkdirSync(path.dirname(file), { recursive: true }) + fs.writeFileSync(file, JSON.stringify(source), 'utf-8') + } + + function writeUserSource(source: Record): void { + const file = path.join(homeDir, '.harness', 'template-source.json') + fs.mkdirSync(path.dirname(file), { recursive: true }) + fs.writeFileSync(file, JSON.stringify(source), 'utf-8') + } + + describe('readTemplateSource', () => { + it('should return null when the project source file does not exist', () => { + expect(readTemplateSource(projectRoot)).toBe(null) + }) + + it('should read partial source and normalize its registry', () => { + writeProjectSource({ registry: 'https://registry.example.test///' }) + expect(readTemplateSource(projectRoot)).toEqual({ registry: 'https://registry.example.test/' }) + }) + + it('should reject malformed saved source data', () => { + writeProjectSource({ packageName: '../templates' }) + expect(() => readTemplateSource(projectRoot)).toThrow('template-source.json 无效') + }) + + it('should reject empty source and registry credentials', () => { + writeProjectSource({}) + expect(() => readTemplateSource(projectRoot)).toThrow('template-source.json 无效') + writeProjectSource({ registry: 'https://user:secret@registry.example.test/' }) + expect(() => readTemplateSource(projectRoot)).toThrow('template-source.json 无效') + }) + }) + + describe('readUserTemplateSource', () => { + it('should return null when the user source file does not exist', () => { + expect(readUserTemplateSource(homeDir)).toBe(null) + }) + + it('should read package-only or registry-only user configuration', () => { + writeUserSource({ packageName: '@acme/templates' }) + expect(readUserTemplateSource(homeDir)).toEqual({ packageName: '@acme/templates' }) + writeUserSource({ registry: 'https://registry.example.test' }) + expect(readUserTemplateSource(homeDir)).toEqual({ registry: 'https://registry.example.test/' }) + }) + }) + + describe('resolveTemplateSource', () => { + it('should resolve each field in flag, project, user, and npm default order', () => { + writeProjectSource({ packageName: '@project/templates' }) + writeUserSource({ packageName: '@user/templates', registry: 'https://user.example.test/' }) + + expect(resolveTemplateSource(projectRoot, {}, homeDir)).toEqual({ + packageName: '@project/templates', registry: 'https://user.example.test/', + configuredRegistry: 'https://user.example.test/', + projectConfig: { packageName: '@project/templates' }, + }) + expect(resolveTemplateSource(projectRoot, { templatePackage: '@flag/templates' }, homeDir)).toEqual({ + packageName: '@flag/templates', registry: 'https://user.example.test/', + configuredRegistry: 'https://user.example.test/', + projectConfig: { packageName: '@flag/templates' }, + }) + expect(resolveTemplateSource(projectRoot, { templateRegistry: 'https://flag.example.test' }, homeDir)).toEqual({ + packageName: '@project/templates', registry: 'https://flag.example.test/', + configuredRegistry: 'https://flag.example.test/', + projectConfig: { packageName: '@project/templates', registry: 'https://flag.example.test/' }, + }) + }) + + it('should keep inherited user values out of projectConfig and use npm defaults when absent', () => { + writeUserSource({ packageName: 'user-templates' }) + const npm = path.join(tmpDir, process.platform === 'win32' ? 'npm.cmd' : 'npm') + const script = process.platform === 'win32' + ? `@echo https://registry.example.test/\r\n` + : '#!/bin/sh\nprintf "%s\\n" "https://registry.example.test/"\n' + fs.writeFileSync(npm, script, 'utf-8') + if (process.platform !== 'win32') fs.chmodSync(npm, 0o755) + const previousPath = process.env['PATH'] + process.env['PATH'] = `${tmpDir}${path.delimiter}${previousPath ?? ''}` + try { + expect(resolveTemplateSource(projectRoot, {}, homeDir)).toEqual({ + packageName: 'user-templates', registry: 'https://registry.example.test/', + }) + } finally { + process.env['PATH'] = previousPath + } + }) + + it('should use npm scoped registry configuration for a scoped package', () => { + const npm = path.join(tmpDir, process.platform === 'win32' ? 'npm.cmd' : 'npm') + const script = process.platform === 'win32' + ? '@if "%~3"=="@acme:registry" (echo https://scoped.example.test/) else (echo https://general.example.test/)\r\n' + : '#!/bin/sh\nif [ "$3" = "@acme:registry" ]; then printf "%s\\n" "https://scoped.example.test/"; else printf "%s\\n" "https://general.example.test/"; fi\n' + fs.writeFileSync(npm, script, 'utf-8') + if (process.platform !== 'win32') fs.chmodSync(npm, 0o755) + const previousPath = process.env['PATH'] + process.env['PATH'] = `${tmpDir}${path.delimiter}${previousPath ?? ''}` + try { + expect(resolveTemplateSource(projectRoot, { templatePackage: '@acme/templates' }, homeDir)).toEqual({ + packageName: '@acme/templates', registry: 'https://scoped.example.test/', + projectConfig: { packageName: '@acme/templates' }, + }) + } finally { + process.env['PATH'] = previousPath + } + }) + + it('should reject invalid explicit package names and registries', () => { + expect(() => resolveTemplateSource(projectRoot, { templatePackage: '../templates' }, homeDir)).toThrow('模板包名') + expect(() => resolveTemplateSource(projectRoot, { templateRegistry: 'https://u:p@registry.example.test' }, homeDir)).toThrow('模板 registry') + expect(() => resolveTemplateSource(projectRoot, { templateRegistry: 'file:///tmp/registry' }, homeDir)).toThrow('模板 registry') + }) + }) + + describe('writeTemplateSource', () => { + it('should persist only explicit project configuration and no-op without it', () => { + const inherited = { packageName: 'user-templates', registry: 'https://npm.example.test/' } + writeTemplateSource(projectRoot, inherited) + expect(readTemplateSource(projectRoot)).toBe(null) + + writeTemplateSource(projectRoot, { ...inherited, projectConfig: { packageName: '@acme/templates' } }) + expect(readTemplateSource(projectRoot)).toEqual({ packageName: '@acme/templates' }) + }) + }) + + describe('templateSourceKey and change detection', () => { + it('should fingerprint package and normalized registry identity', () => { + const source = { packageName: DEFAULT_TEMPLATE_PACKAGE, registry: 'https://registry.example.test/' } + expect(templateSourceKey(source)).toMatch(/^[a-f0-9]{64}$/) + expect(templateSourceKey(source)).toBe(templateSourceKey({ ...source })) + expect(templateSourceKey(source)).not.toBe(templateSourceKey({ ...source, registry: 'https://other.example.test/' })) + expect(templateSourceKey(source)).not.toBe(templateSourceKey({ ...source, packageName: '@acme/templates' })) + }) + + it('should recheck legacy defaults only for a configured registry or changed source fingerprint', () => { + const source = { packageName: DEFAULT_TEMPLATE_PACKAGE, registry: 'https://registry.example.test/' } + expect(hasTemplateSourceChanged(undefined, source)).toBe(false) + expect(hasTemplateSourceChanged(undefined, { ...source, configuredRegistry: source.registry })).toBe(true) + expect(hasTemplateSourceChanged(templateSourceKey(source), source)).toBe(false) + expect(hasTemplateSourceChanged('old-key', source)).toBe(true) + }) + }) + + describe('templateRegistryArgs', () => { + it('should include general and scoped registry arguments for scoped packages', () => { + expect(templateRegistryArgs({ packageName: '@acme/templates', registry: 'https://registry.example.test/' })).toEqual([ + '--registry=https://registry.example.test/', + '--@acme:registry=https://registry.example.test/', + ]) + }) + }) +}) diff --git a/tests/templates-cache.test.ts b/tests/templates-cache.test.ts index 4ba6806..3a4875c 100644 --- a/tests/templates-cache.test.ts +++ b/tests/templates-cache.test.ts @@ -4,6 +4,7 @@ import path from 'node:path' import os from 'node:os' import { create } from 'tar' import { TemplatesFetchError, __test__ } from '../src/lib/templates-cache.js' +import { templateRegistryArgs } from '../src/lib/template-source.js' const { readMeta, writeMeta, extractTarball, SEMVER_RE, resolveRequestedTemplatesVersion, isUsableCacheDir } = __test__! @@ -30,7 +31,6 @@ describe('templates-cache', () => { expect(err.diagnostic).toContain('npm --version') expect(err.diagnostic).toContain('npm config get registry') expect(err.diagnostic).toContain('registry.npmjs.org') - expect(err.diagnostic).toContain('curl -I') expect(err.diagnostic).toContain('模板包已发布') }) @@ -124,6 +124,16 @@ describe('templates-cache', () => { expect(isUsableCacheDir(cacheDir, '1.2.3')).toBe(true) }) + it('should validate the configured custom package name', () => { + const cacheDir = path.join(tmpDir, 'custom-cache') + fs.mkdirSync(cacheDir, { recursive: true }) + fs.writeFileSync(path.join(cacheDir, 'package.json'), JSON.stringify({ name: '@acme/templates', version: '1.2.3' })) + fs.writeFileSync(path.join(cacheDir, 'versions-yml.yml'), 'harness: "1.2.3"\n') + + expect(isUsableCacheDir(cacheDir, '1.2.3', '@acme/templates')).toBe(true) + expect(isUsableCacheDir(cacheDir, '1.2.3')).toBe(false) + }) + it('should return false when cache directory is missing package metadata', () => { const cacheDir = path.join(tmpDir, 'cache-missing-package') fs.mkdirSync(cacheDir, { recursive: true }) @@ -150,6 +160,20 @@ describe('templates-cache', () => { }) }) + describe('templateRegistryArgs', () => { + it('pins scoped package lookup to the selected registry at package and scope level', () => { + expect(templateRegistryArgs({ packageName: '@acme/templates', registry: 'https://npm.acme.test/' })).toEqual([ + '--registry=https://npm.acme.test/', '--@acme:registry=https://npm.acme.test/', + ]) + }) + + it('pins unscoped package lookup to the selected registry', () => { + expect(templateRegistryArgs({ packageName: 'acme-templates', registry: 'https://npm.acme.test/' })).toEqual([ + '--registry=https://npm.acme.test/', + ]) + }) + }) + describe('resolveRequestedTemplatesVersion', () => { it('should return explicit version without npm lookup', () => { const version = resolveRequestedTemplatesVersion( diff --git a/tests/templates.test.ts b/tests/templates.test.ts index f059540..4ce23e6 100644 --- a/tests/templates.test.ts +++ b/tests/templates.test.ts @@ -37,6 +37,29 @@ describe('templates', () => { .toBe(true) }) + it('should distribute reachable architecture knowledge guidance with domain-init', () => { + const target = path.join(tmpDir, 'skills') + copyTemplateSkills(target) + + const skill = fs.readFileSync(path.join(target, 'domain-init', 'SKILL.md'), 'utf-8') + expect(skill).toContain('references/architecture-knowledge.md') + + for (const relative of [ + 'SKILL.md', + 'references/architecture-knowledge.md', + 'references/output-formats.md', + 'references/dimension-pool.md', + ]) { + const relativePath = path.join('domain-init', relative) + const packaged = fs.readFileSync(path.join(target, relativePath), 'utf-8') + expect(packaged, relative).toBe(readTemplateFile(`skills/${relativePath}`)) + expect(packaged, relative).toBe(fs.readFileSync( + path.join(process.cwd(), '.harness', 'skills', relativePath), + 'utf-8', + )) + } + }) + it('should distribute Chinese Codex prompts with the intended invocation policy', () => { const target = path.join(tmpDir, 'skills') copyTemplateSkills(target) diff --git a/tests/update-notifier.test.ts b/tests/update-notifier.test.ts index a7d1ce4..ac8f81a 100644 --- a/tests/update-notifier.test.ts +++ b/tests/update-notifier.test.ts @@ -10,18 +10,31 @@ import { compareVersions, formatUpdatePrompt, } from '../src/lib/update-notifier.js' +import { writeTemplateSource, templateSourceKey } from '../src/lib/template-source.js' import { writeVersions } from '../src/lib/versions.js' +const source = { packageName: '@acme/templates', registry: 'https://npm.acme.test/', configuredRegistry: 'https://npm.acme.test/' } +const sourceKey = templateSourceKey(source) + describe('update-notifier', () => { let projectRoot: string let cachePath: string + const previousHome = process.env['USERPROFILE'] + const previousUnixHome = process.env['HOME'] beforeEach(() => { projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'harness-update-notifier-')) cachePath = path.join(projectRoot, 'cache', 'devkeel-update-check.json') + process.env['USERPROFILE'] = projectRoot + process.env['HOME'] = projectRoot + writeTemplateSource(projectRoot, { ...source, projectConfig: { packageName: source.packageName, registry: source.registry } }) }) afterEach(() => { + if (previousHome === undefined) delete process.env['USERPROFILE'] + else process.env['USERPROFILE'] = previousHome + if (previousUnixHome === undefined) delete process.env['HOME'] + else process.env['HOME'] = previousUnixHome fs.rmSync(projectRoot, { recursive: true, force: true }) }) @@ -112,6 +125,38 @@ describe('update-notifier', () => { }) describe('checkAndNotify', () => { + it('should query the selected source instead of reusing a different source cache', async () => { + writeProjectVersion('2.1.0') + writeUpdateCache({ sourceKey: 'another-source', lastCheck: Date.now(), latestVersion: '99.0.0' }, cachePath) + const script = path.join(projectRoot, 'fake-npm.cjs') + const logPath = path.join(projectRoot, 'npm-call.json') + fs.writeFileSync(script, [ + "const fs = require('node:fs')", + `fs.writeFileSync(${JSON.stringify(logPath)}, JSON.stringify({ args: process.argv.slice(2), cwd: process.cwd() }))`, + 'process.stdout.write(JSON.stringify("2.2.0"))', + ].join('\n')) + const bin = path.join(projectRoot, process.platform === 'win32' ? 'npm.cmd' : 'npm') + fs.writeFileSync(bin, process.platform === 'win32' + ? `@"${process.execPath}" "${script}" %*\r\n` + : `#!/bin/sh\nexec "${process.execPath}" "${script}" "$@"\n`) + if (process.platform !== 'win32') fs.chmodSync(bin, 0o755) + const originalPath = process.env['PATH'] + process.env['PATH'] = `${projectRoot}${path.delimiter}${originalPath ?? ''}` + try { + const prompt = await checkAndNotify(projectRoot, cachePath) + expect(prompt).toContain('2.2.0') + expect(prompt).not.toContain('99.0.0') + expect(readUpdateCache(cachePath)?.sourceKey).toBe(sourceKey) + const call = JSON.parse(fs.readFileSync(logPath, 'utf-8')) + expect(call.cwd).toBe(projectRoot) + expect(call.args).toContain('@acme/templates@latest') + expect(call.args).toContain('--@acme:registry=https://npm.acme.test/') + } finally { + if (originalPath === undefined) delete process.env['PATH'] + else process.env['PATH'] = originalPath + } + }) + it('should return null without project versions', async () => { expect(await checkAndNotify(projectRoot, cachePath)).toBeNull() expect(fs.existsSync(cachePath)).toBe(false) @@ -119,7 +164,7 @@ describe('update-notifier', () => { it('should return a terminal prompt and leave a fresh cache unchanged on repeated checks', async () => { writeProjectVersion('2.1.1-beta.0') - writeUpdateCache({ lastCheck: Date.now(), latestVersion: '2.2.0' }, cachePath) + writeUpdateCache({ sourceKey, lastCheck: Date.now(), latestVersion: '2.2.0' }, cachePath) const cached = fs.readFileSync(cachePath, 'utf-8') const first = await checkAndNotify(projectRoot, cachePath) @@ -138,6 +183,7 @@ describe('update-notifier', () => { lastCheck: Date.now(), latestVersion: '2.2.0', notifiedVersion: '2.2.0', + sourceKey, })) expect(await checkAndNotify(projectRoot, cachePath)).toContain('devkeel update') }) @@ -151,7 +197,7 @@ describe('update-notifier', () => { ['2.2.0', 'not-a-version'], ])('should not advertise an upgrade from %s to %s', async (current, latest) => { writeProjectVersion(current) - writeUpdateCache({ lastCheck: Date.now(), latestVersion: latest }, cachePath) + writeUpdateCache({ sourceKey, lastCheck: Date.now(), latestVersion: latest }, cachePath) expect(await checkAndNotify(projectRoot, cachePath)).toBeNull() }) }) diff --git a/tests/update.test.ts b/tests/update.test.ts index c34ce93..e6f4317 100644 --- a/tests/update.test.ts +++ b/tests/update.test.ts @@ -6,6 +6,7 @@ import crypto from 'node:crypto' import { execFileSync } from 'node:child_process' import YAML from 'yaml' import * as prompts from '@clack/prompts' +import { resolveTemplateSource, templateSourceKey } from '../src/lib/template-source.js' import { detectDeprecatedAssets, removeDeprecatedAssets, copyTemplateSkills, copyTemplateAgents, copyTemplateRules, copyTemplateCommands, copyOpenspecTemplate } from '../src/lib/templates.js' import { filterManagedVersions, getBuiltinVersions, readVersions, writeVersions } from '../src/lib/versions.js' import { setTemplatesDir } from '../src/lib/templates-dir.js' @@ -70,6 +71,8 @@ function createDiscussionTemplatesAt(sourceTemplates: string, version: string): describe.sequential('runUpdate managed asset distribution', () => { const originalCwd = process.cwd() + const originalHome = process.env['USERPROFILE'] + const originalUnixHome = process.env['HOME'] const skillName = 'openspec-update-change' const skillRelativePath = `skills/${skillName}/SKILL.md` const commandRelativePath = 'commands/opsx/update.md' @@ -98,10 +101,16 @@ describe.sequential('runUpdate managed asset distribution', () => { vi.mocked(prompts.confirm).mockReset() vi.mocked(prompts.confirm).mockResolvedValue(false) vi.mocked(prompts.select).mockReset() + process.env['USERPROFILE'] = projectDir + process.env['HOME'] = projectDir process.chdir(projectDir) }) afterEach(() => { + if (originalHome === undefined) delete process.env['USERPROFILE'] + else process.env['USERPROFILE'] = originalHome + if (originalUnixHome === undefined) delete process.env['HOME'] + else process.env['HOME'] = originalUnixHome process.chdir(originalCwd) fs.rmSync(projectDir, { recursive: true, force: true }) }) @@ -407,7 +416,7 @@ describe.sequential('runUpdate managed asset distribution', () => { await runUpdate({ beta: true, force: true }) expect(fs.readFileSync(targetPath, 'utf-8')).toBe(templateContent) - expect(readVersions(projectDir)).toEqual(getBuiltinVersions()) + expect(readVersions(projectDir)).toEqual({ ...getBuiltinVersions(), templateSource: expect.stringMatching(/^[a-f0-9]{64}$/) }) }) it('should keep beta force dry-run read-only when versions match', async () => { @@ -556,7 +565,7 @@ describe.sequential('runUpdate managed asset distribution', () => { it('should auto-commit a clean gitignore-only migration', async () => { copyTemplateSkills(path.join(projectDir, '.harness', 'skills')) copyTemplateCommands(path.join(projectDir, '.harness', 'commands')) - writeVersions(projectDir, getBuiltinVersions()) + writeVersions(projectDir, { ...getBuiltinVersions(), templateSource: templateSourceKey(resolveTemplateSource(projectDir)) }) fs.writeFileSync(path.join(projectDir, '.gitignore'), '.claude/\nnode_modules/\n', 'utf-8') const template = fs.readFileSync(path.join(updateTestState.templatesDir, 'agents-md.md'), 'utf-8') .replace('{{SUBMODULE_SECTION}}', '') diff --git a/tests/version-output.test.ts b/tests/version-output.test.ts index c328b20..31d4a9f 100644 --- a/tests/version-output.test.ts +++ b/tests/version-output.test.ts @@ -4,6 +4,9 @@ import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import { create } from 'tar' +import { templateSourceKey } from '../src/lib/template-source.js' + +const sourceKey = templateSourceKey({ packageName: 'devkeel-templates', registry: 'https://registry.npmjs.org/' }) const HARNESS_BIN = path.resolve('bin/devkeel.js') const harnessPackage = JSON.parse(fs.readFileSync(path.resolve('package.json'), 'utf-8')) as { version: string } @@ -34,6 +37,7 @@ describe('version output', () => { "const path = require('node:path')", 'const args = process.argv.slice(2)', "if (process.env['FAKE_NPM_FAIL'] === '1') process.exit(1)", + "if (args[0] === 'config') { process.stdout.write('https://registry.npmjs.org/'); process.exit(0) }", "if (args[0] === 'view' && args[1] === 'devkeel@beta' && args[2] === 'version') {", " process.stdout.write(JSON.stringify(process.env['FAKE_BETA_HARNESS_VERSION']) + '\\n')", ' process.exit(0)', @@ -42,17 +46,17 @@ describe('version output', () => { " process.stdout.write(JSON.stringify(process.env['FAKE_LATEST_HARNESS_VERSION']) + '\\n')", ' process.exit(0)', '}', - "if (args[0] === 'view' && args[1] === 'devkeel-templates@beta' && args[2] === 'version') {", + "if (args[0] === 'view' && args[1] === (process.env['FAKE_TEMPLATE_PACKAGE'] || 'devkeel-templates') + '@beta' && args[2] === 'version') {", " process.stdout.write(JSON.stringify(process.env['FAKE_BETA_TEMPLATE_VERSION']) + '\\n')", ' process.exit(0)', '}', - "if (args[0] === 'view' && args[1] === 'devkeel-templates@latest' && args[2] === 'version') {", + "if (args[0] === 'view' && args[1] === (process.env['FAKE_TEMPLATE_PACKAGE'] || 'devkeel-templates') + '@latest' && args[2] === 'version') {", " process.stdout.write(JSON.stringify(process.env['FAKE_LATEST_TEMPLATE_VERSION']) + '\\n')", ' process.exit(0)', '}', "if (args[0] === 'pack' && args[1] === 'devkeel-templates@1.4.0') {", " const filename = 'devkeel-templates-1.4.0.tgz'", - " fs.copyFileSync(process.env['FAKE_TEMPLATE_TARBALL'], path.join(process.cwd(), filename))", + " fs.copyFileSync(process.env['FAKE_TEMPLATE_TARBALL'], path.join(args[args.indexOf('--pack-destination') + 1], filename))", " process.stdout.write(filename + '\\n')", ' process.exit(0)', '}', @@ -72,10 +76,11 @@ describe('version output', () => { fs.rmSync(tmpDir, { recursive: true, force: true }) }) - function prepareTemplatesCache(version: string): void { - const cacheDir = path.join(tmpDir, '.harness', 'cache', 'devkeel-templates', version) + function prepareTemplatesCache(version: string, packageName = 'devkeel-templates', registry = 'https://registry.npmjs.org/'): void { + const sourceKey = templateSourceKey({ packageName, registry }) + const cacheDir = path.join(tmpDir, '.harness', 'cache', 'devkeel-templates', sourceKey, version) fs.mkdirSync(cacheDir, { recursive: true }) - fs.writeFileSync(path.join(cacheDir, 'package.json'), JSON.stringify({ name: 'devkeel-templates', version }), 'utf-8') + fs.writeFileSync(path.join(cacheDir, 'package.json'), JSON.stringify({ name: packageName, version }), 'utf-8') fs.writeFileSync(path.join(cacheDir, 'versions-yml.yml'), `harness: "${version}"\n`, 'utf-8') } @@ -134,11 +139,30 @@ describe('version output', () => { '.harness', 'cache', 'devkeel-templates', + sourceKey, '1.4.0', 'package.json', ))).toBe(true) }) + it('should use the user template source and avoid public template fallback on failure', () => { + const source = { packageName: '@acme/templates', registry: 'https://npm.acme.test/' } + const config = path.join(tmpDir, '.harness', 'template-source.json') + fs.mkdirSync(path.dirname(config), { recursive: true }) + fs.writeFileSync(config, JSON.stringify(source)) + prepareTemplatesCache('3.0.0', source.packageName, source.registry) + const result = runVersion(['-V'], { + FAKE_TEMPLATE_PACKAGE: source.packageName, + FAKE_LATEST_HARNESS_VERSION: '0.9.0', + FAKE_LATEST_TEMPLATE_VERSION: '3.0.0', + }) + expect(result.status).toBe(0) + expect(result.stdout).toBe('devkeel 0.9.0\ntemplates 3.0.0\n') + const failed = runVersion(['-V'], { FAKE_NPM_FAIL: '1' }) + expect(failed.status).toBe(0) + expect(failed.stdout).toBe(`devkeel ${harnessPackage.version}\ntemplates unknown\n`) + }) + it('should exit successfully with local version output when registry queries fail', () => { const result = runVersion(['-V'], { FAKE_NPM_FAIL: '1' }) diff --git a/web/public/install.md b/web/public/install.md index f3a571b..6ebbe8e 100644 --- a/web/public/install.md +++ b/web/public/install.md @@ -233,6 +233,21 @@ npx devkeel@latest update ``` CLI 与模板独立发布。`devkeel update` 也会获取模板,但不会升级全局 CLI。 + +初始化或更新时,可指定私有 npm 模板包和 registry: + +```bash +devkeel init --template-package @example/devkeel-templates --template-registry https://npm.example.com/ +# 已初始化项目使用同样的参数执行 update,先用 --dry-run 预览 +devkeel update --template-package @example/devkeel-templates --template-registry https://npm.example.com/ --dry-run +``` + +统一默认来源可手动配置在用户级 `~/.harness/template-source.json`,格式为 +`{"packageName":"@example/devkeel-templates","registry":"https://npm.example.com/"}`。 +优先级为命令行参数 → 项目 `.harness/template-source.json` → 用户配置 → npm 默认值。 +显式来源参数成功执行后保存为项目级覆盖;未覆盖的项目直接继承用户配置,无需逐项目设置。 +`--dry-run` 不保存来源;部分更新或跳过组件后需带原参数重试换源。认证继续由 `.npmrc` 管理。 +未显式配置 registry 时沿用 npm 配置,不会把解析结果固定到来源文件。 全局 CLI 可通过 `npm install -g devkeel@latest --registry=https://registry.npmjs.org/` 单独升级。 普通更新中,“全部更新”会覆盖待更新组件的本地修改;需要逐项跳过时选择“逐个确认”。