Commit d6e7c5b3 by 张立顺

docs: plan project knowledge graph migration

1 parent 5d7d5703
# Project Knowledge Graph Migration Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Migrate the reference project's knowledge graph, impact analysis, affected testing, documentation workflow, and guarded Live profiles into `regional-assistant`, adapted to its six real domains and existing test/upload boundaries.
**Architecture:** Copy the generic scanner/query contracts from fixed reference commit `e4fc97927e631208fb33af77ac47ea38892026fc`, then isolate all project-specific semantics in `domain-catalog.json`, affected-test roots, documentation, and Live profile definitions. Build graphs deterministically from the current worktree, keep generated artifacts under upload-excluded `docs/`, and conservatively escalate uncertain or shared changes to the full offline suite.
**Tech Stack:** Node.js 24, `node:test`, ECMAScript modules, `@babel/parser`, WeChat Mini Program `app.json`/WXML/component JSON, Markdown/JSON docs-as-code, PowerShell, Git.
**Spec:** `docs/superpowers/specs/2026-08-21-project-knowledge-graph-migration-design.md`
## Global Constraints
- Source implementation is pinned to `dj-car-boutique-work-wechat` commit `e4fc97927e631208fb33af77ac47ea38892026fc`.
- Do not store either user-provided phone number, any verification code, session, signature, secret, or app key in code, tests, docs, manifests, generated artifacts, or logs.
- `regional-dev-login` is login-only and must never authorize business writes.
- `regional-test` writes require `RUN_ORDER_E2E=1`, an exact test URL allowlist, and `LIVE_ALLOW_WRITES=1`.
- Ordinary `npm test`, `test:affected`, and project-quality checks must skip Live tests by default.
- Generated knowledge files remain under upload-excluded `docs/`; `.agents/` must be added to the explicit upload exclusions.
- Do not modify Mini Program runtime behavior except the approved `filterOrderMerchantOptions` baseline fix.
- Build output is deterministic: no timestamps, Git SHA fields, source snippets, or credential values.
- Dynamic imports, routes, and endpoints are reported as `unresolved`; they are never guessed.
- All migration work must pass the manifest pre gate before runtime or migration script changes and the post gate after verification.
---
### Task 1: Migration Evidence and Pre Gate
**Files:**
- Create: `docs/migrations/project-knowledge-graph/manifest.json`
- Create: `docs/migrations/project-knowledge-graph/api-inventory.md`
- Create: `docs/migrations/project-knowledge-graph/test-acceptance.md`
- Test: `tests/migration-readiness/checkMigrationReadiness.test.mjs`
- Test: `tests/migration-readiness/uploadExclusions.test.mjs`
**Interfaces:**
- Consumes: Design commit `5d7d57032ad31517c56fb4f53a00b01e1905728b` and reference commit `e4fc97927e631208fb33af77ac47ea38892026fc`.
- Produces: A pre-approved migration manifest at `docs/migrations/project-knowledge-graph/manifest.json` that every later task uses.
- [ ] **Step 1: Record the exact migration surface**
Create `api-inventory.md` with these public development interfaces and their expected behavior:
```markdown
# 项目知识图谱迁移接口清单
## 来源
- 项目:dj-car-boutique-work-wechat
- 提交:e4fc97927e631208fb33af77ac47ea38892026fc
## 命令接口
| 接口 | 输入 | 输出/行为 |
|---|---|---|
| `npm run knowledge:build` | 当前仓库 | 重建稳定图谱和 Markdown 索引 |
| `npm run knowledge:check` | 当前仓库 | 只读比较生成物,漂移时非零退出 |
| `npm run impact -- --keyword <value>` | 1–5 个关键词 | 返回上下游、测试、文档、风险和证据 |
| `npm run test:affected -- --list --format json` | Git 变更集 | 返回 none/docs-only/targeted/full 计划 |
| `npm test` | 无 | 运行全部离线测试,Live 默认跳过 |
## 图谱契约
顶层字段固定为 `schemaVersion`、`nodes`、`edges`、`unresolved`、`stats`。每条边必须包含 `from`、`to`、`type`、`confidence` 和文件行列证据。
```
- [ ] **Step 2: Write the acceptance matrix**
Create `test-acceptance.md` with concrete pre/post states:
```markdown
# 项目知识图谱迁移验收
| ID | 验收项 | Pre | Post |
|---|---|---|---|
| KG-001 | migration readiness contract | pass | pass |
| KG-002 | existing merchant search contract | fail: park name is not searched | pass |
| KG-003 | knowledge graph fixture contracts | absent | pass |
| KG-004 | all 71 app pages are indexed | probe only | pass |
| KG-005 | generated artifacts are byte-stable | absent | pass |
| KG-006 | affected selection escalates shared/cross-domain/unresolved changes | absent | pass |
| KG-007 | Live profiles contain no credential literals and default to skipped | absent | pass |
| KG-008 | full offline suite | blocked by KG-002 | pass |
| KG-009 | knowledge artifacts remain outside upload package | docs/scripts/tests pass; .agents absent | pass |
```
- [ ] **Step 3: Write the manifest**
Create valid JSON with these exact fields. Use the design commit as the runtime baseline so the result is stable even though this plan is a later docs-only commit:
```json
{
"id": "project-knowledge-graph",
"title": "项目知识图谱与增量测试迁移",
"sourceProject": "dj-car-boutique-work-wechat@e4fc97927e631208fb33af77ac47ea38892026fc",
"affectedPaths": [
"components/orderPromptPop/orderMerchantContext.helpers.js",
"package.json",
"project.config.json",
"README.md",
"docs",
"scripts",
"tests"
],
"interfaces": [
"npm run knowledge:build",
"npm run knowledge:check",
"npm run impact",
"npm run test:affected",
"npm test"
],
"tests": [
{
"id": "migration-readiness-contract",
"file": "tests/migration-readiness/checkMigrationReadiness.test.mjs",
"level": "contract",
"expectedBefore": "pass",
"status": "pass"
},
{
"id": "upload-exclusions-contract",
"file": "tests/migration-readiness/uploadExclusions.test.mjs",
"level": "contract",
"expectedBefore": "pass",
"status": "pass"
}
],
"baseline": {
"command": "git rev-parse --short 5d7d57032ad31517c56fb4f53a00b01e1905728b",
"result": "5d7d570"
},
"apiInventory": "docs/migrations/project-knowledge-graph/api-inventory.md",
"acceptance": "docs/migrations/project-knowledge-graph/test-acceptance.md",
"verification": {
"commands": [
{
"command": "node scripts/run-node-tests.mjs tests/knowledge-graph tests/project-governance tests/order-lifecycle/liveProfiles.test.mjs tests/order-lifecycle/e2e/liveCleanup.test.mjs",
"status": "pass"
},
{
"command": "npm run knowledge:check",
"status": "pass"
},
{
"command": "npm test",
"status": "pass"
}
]
}
}
```
- [ ] **Step 4: Run migration preparation tests**
Run:
```powershell
node scripts/run-node-tests.mjs tests/migration-readiness/checkMigrationReadiness.test.mjs tests/migration-readiness/uploadExclusions.test.mjs
```
Expected: all readiness and current upload-exclusion tests pass.
- [ ] **Step 5: Run the required pre gate**
Run:
```powershell
npm run check:migration -- --manifest docs/migrations/project-knowledge-graph/manifest.json --phase pre
```
Expected: `Migration readiness pre check passed` for the new manifest.
- [ ] **Step 6: Commit migration evidence**
```powershell
git add -- docs/migrations/project-knowledge-graph
git commit -m "docs: gate project knowledge graph migration"
```
---
### Task 2: Restore a Green Offline Baseline
**Files:**
- Modify: `components/orderPromptPop/orderMerchantContext.helpers.js:106`
- Test: `tests/work-order-migration/low-price-order-flow.test.mjs:80`
**Interfaces:**
- Consumes: Existing `filterOrderMerchantOptions(options, keyword)` contract.
- Produces: The same function signature, now matching both `merchantName` and `yqMerchantName` without changing returned objects.
- [ ] **Step 1: Reproduce the approved failing contract**
Run:
```powershell
node scripts/run-node-tests.mjs tests/work-order-migration/low-price-order-flow.test.mjs
```
Expected: exactly the `搜索同时匹配 4S 店与园区名称` subtest fails because the `北区` query returns `[]` instead of merchant `202`.
- [ ] **Step 2: Implement the minimal search fix**
Change the filter body to search a normalized combined label:
```js
export function filterOrderMerchantOptions(options, keyword) {
const normalizedKeyword = String(keyword || '').trim().toLowerCase()
if (!normalizedKeyword) return [...(options || [])]
return (options || []).filter(item =>
`${item.merchantName || ''} ${item.yqMerchantName || ''}`
.toLowerCase()
.includes(normalizedKeyword)
)
}
```
- [ ] **Step 3: Verify the focused test passes**
Run the Step 1 command again.
Expected: 13 tests pass, 0 fail.
- [ ] **Step 4: Establish the full current baseline**
Run:
```powershell
npm run test:workOrder
```
Expected: migration, createOrder, order-lifecycle, and closure checks all pass; Live tests remain skipped unless their explicit environment flags are present.
- [ ] **Step 5: Commit the baseline fix**
```powershell
git add -- components/orderPromptPop/orderMerchantContext.helpers.js
git commit -m "fix: match park names in merchant search"
```
---
### Task 3: Knowledge Graph Core and Fixture Contract
**Files:**
- Create: `scripts/knowledge-graph/build-knowledge-graph.mjs`
- Create: `tests/knowledge-graph/buildKnowledgeGraph.test.mjs`
- Create: `tests/knowledge-graph/fixtures/mini-program/**`
**Interfaces:**
- Consumes: `buildKnowledgeGraph({ rootDir: string }): Promise<Graph>` and `serializeGraph(graph): string` from the pinned reference.
- Produces: Graph schema version `1.0.0`, deterministic nodes/edges/unresolved/stats, and a self-contained fixture contract.
- [ ] **Step 1: Read the pinned source files**
Run these read-only commands and use their exact committed contents as the migration source:
```powershell
git -C C:\Users\admin\Desktop\工作\dj-car-boutique-work-wechat show e4fc97927e631208fb33af77ac47ea38892026fc:scripts/knowledge-graph/build-knowledge-graph.mjs
git -C C:\Users\admin\Desktop\工作\dj-car-boutique-work-wechat show e4fc97927e631208fb33af77ac47ea38892026fc:tests/knowledge-graph/buildKnowledgeGraph.test.mjs
git -C C:\Users\admin\Desktop\工作\dj-car-boutique-work-wechat ls-tree -r --name-only e4fc97927e631208fb33af77ac47ea38892026fc tests/knowledge-graph/fixtures/mini-program
```
Expected: the builder exports the two stated functions and the fixture list contains app/page/component/API/test/docs examples plus ignored tool/temp directories.
- [ ] **Step 2: Add the test and fixture before the builder**
Use `apply_patch` to add the pinned fixture and test files. Add two current-design regressions to `buildKnowledgeGraph.test.mjs`:
1. Create generated Markdown fixtures under `docs/generated/ignored.md` and `docs/COMPONENT-PAGE-INDEX.md`, then assert neither generated location becomes a document node.
2. Assert the component node for `components/card/card` contains both registration aliases `app-card` and `local-card`, so impact queries can start from the WXML/app.json tag name.
The added assertion must be:
```js
assert.equal(
graph.nodes.some(
node =>
node.type === 'document' &&
(node.path.startsWith('docs/generated/') ||
node.path === 'docs/COMPONENT-PAGE-INDEX.md')
),
false
)
assert.deepEqual(
graph.nodes.find(node => node.id === 'component:components/card/card').aliases,
['app-card', 'local-card']
)
```
- [ ] **Step 3: Verify RED**
Run:
```powershell
node scripts/run-node-tests.mjs tests/knowledge-graph/buildKnowledgeGraph.test.mjs
```
Expected: fail because `scripts/knowledge-graph/build-knowledge-graph.mjs` does not exist.
- [ ] **Step 4: Add and adapt the generic builder**
Use `apply_patch` to add the pinned builder. Preserve its public schema and parsing behavior. Add `docs/generated/` to `IGNORED_PATH_PREFIXES` so generated Markdown cannot become an input to the next graph build:
```js
const IGNORED_PATH_PREFIXES = [
'docs/COMPONENT-PAGE-INDEX.md',
'docs/generated/',
'tests/.migration-readiness-',
'tests/knowledge-graph/fixtures/'
]
```
In `registerComponents`, merge each JSON registration tag into the target component node's sorted `aliases` array before adding the `usesComponent` edge:
```js
const currentAliases = collector.nodes.get(targetId)?.aliases || []
collector.mergeNode(targetId, {
aliases: [...new Set([...currentAliases, alias])].sort(compareText)
})
```
- [ ] **Step 5: Verify GREEN and deterministic output**
Run the Step 3 command twice.
Expected: all builder tests pass both times; the serialized outputs compared by the test are byte-identical.
- [ ] **Step 6: Commit the core contract**
```powershell
git add -- scripts/knowledge-graph/build-knowledge-graph.mjs tests/knowledge-graph
git commit -m "feat: add miniprogram knowledge graph core"
```
---
### Task 4: Artifact Generation and Impact Query
**Files:**
- Create: `scripts/knowledge-graph/knowledge-artifacts.mjs`
- Create: `scripts/knowledge-graph/knowledge-build.mjs`
- Create: `scripts/knowledge-graph/knowledge-check.mjs`
- Create: `scripts/knowledge-graph/query-knowledge-graph.mjs`
- Create: `tests/knowledge-graph/artifactsAndImpact.test.mjs`
- Create: `tests/knowledge-graph/cli.test.mjs`
**Interfaces:**
- Consumes: `Graph` from Task 3.
- Produces: `createKnowledgeArtifactContents`, `writeKnowledgeArtifacts`, `checkKnowledgeArtifacts`, `queryKnowledgeGraph`, and build/check/query CLIs.
- [ ] **Step 1: Add pinned RED tests**
Read the exact source with:
```powershell
git -C C:\Users\admin\Desktop\工作\dj-car-boutique-work-wechat show e4fc97927e631208fb33af77ac47ea38892026fc:tests/knowledge-graph/artifactsAndImpact.test.mjs
git -C C:\Users\admin\Desktop\工作\dj-car-boutique-work-wechat show e4fc97927e631208fb33af77ac47ea38892026fc:tests/knowledge-graph/cli.test.mjs
```
Add both files with `apply_patch` and retain assertions for generated paths, stable output, upstream/downstream results, cross-domain risks, tests, documents, and unsupported CLI arguments.
- [ ] **Step 2: Verify RED**
Run:
```powershell
node scripts/run-node-tests.mjs tests/knowledge-graph/artifactsAndImpact.test.mjs tests/knowledge-graph/cli.test.mjs
```
Expected: fail because the artifact/query modules do not exist.
- [ ] **Step 3: Add the four pinned modules**
Read the exact implementations with these commands, then use `apply_patch` to add them:
```powershell
git -C C:\Users\admin\Desktop\工作\dj-car-boutique-work-wechat show e4fc97927e631208fb33af77ac47ea38892026fc:scripts/knowledge-graph/knowledge-artifacts.mjs
git -C C:\Users\admin\Desktop\工作\dj-car-boutique-work-wechat show e4fc97927e631208fb33af77ac47ea38892026fc:scripts/knowledge-graph/knowledge-build.mjs
git -C C:\Users\admin\Desktop\工作\dj-car-boutique-work-wechat show e4fc97927e631208fb33af77ac47ea38892026fc:scripts/knowledge-graph/knowledge-check.mjs
git -C C:\Users\admin\Desktop\工作\dj-car-boutique-work-wechat show e4fc97927e631208fb33af77ac47ea38892026fc:scripts/knowledge-graph/query-knowledge-graph.mjs
```
Keep `--depth` limited to 0–3, directions limited to `both|upstream|downstream`, formats limited to `json|md`, and check mode read-only.
- [ ] **Step 4: Verify GREEN**
Run the Step 2 command.
Expected: all artifact, query, and CLI tests pass.
- [ ] **Step 5: Commit artifact/query support**
```powershell
git add -- scripts/knowledge-graph tests/knowledge-graph
git commit -m "feat: generate and query project knowledge"
```
---
### Task 5: Current-Project Domain Catalog and Real Queries
**Files:**
- Create: `docs/knowledge/domain-catalog.json`
- Create: `docs/knowledge/known-gaps.json`
- Create: `tests/knowledge-graph/domainCatalog.test.mjs`
- Create: `tests/knowledge-graph/realQueries.test.mjs`
- Create: `docs/generated/**` via `knowledge:build`
- Create: `docs/COMPONENT-PAGE-INDEX.md` via `knowledge:build`
**Interfaces:**
- Consumes: Graph builder, artifact renderer, and query API.
- Produces: Six stable domain names—`application`, `workspace`, `study`, `matters`, `workOrder`, `shared`—and generated evidence for all 71 pages.
- [ ] **Step 1: Write failing domain tests**
Adapt the pinned `domainCatalog.test.mjs` and `realQueries.test.mjs` to assert:
```js
assert.deepEqual(
catalog.domains.map(domain => domain.name),
['application', 'workspace', 'study', 'matters', 'workOrder', 'shared']
)
assert.equal(graph.stats.nodeTypes.page, 71)
```
Real query cases must use these exact keywords and expectations:
- `createOrder`: direct matches include the createOrder page/module and return work-order tests/documents.
- `wx.$orderListRefresh`: result includes the write in `utils/util.js` and the read/reset in `pages/tabWorkOrder/pages/index/index.js`, while exposing related unresolved entries instead of guessing.
- `packageWorkspace`: direct matches include workspace pages/modules and domain `workspace`.
- `gl-cust-form`: results include the global component registration and packageWorkspace consumer evidence.
- [ ] **Step 2: Verify RED**
Run:
```powershell
node scripts/run-node-tests.mjs tests/knowledge-graph/domainCatalog.test.mjs tests/knowledge-graph/realQueries.test.mjs
```
Expected: fail because the catalog and known-gaps files do not exist.
- [ ] **Step 3: Create the six-domain catalog**
Use this exact domain catalog; every document path already exists in the current repository:
```json
{
"schemaVersion": 1,
"domains": [
{
"name": "application",
"aliases": ["主包", "登录", "账号选择", "场景切换"],
"roots": ["app", "pages"],
"entrypoints": ["pages/loading/loading", "pages/sceneIndex/sceneIndex", "pages/wxLogin/wxLogin"],
"riskKeywords": ["App", "globalData", "login", "scene"],
"documents": ["docs/README.md"]
},
{
"name": "workspace",
"aliases": ["工作台", "区域督导", "业务工作区"],
"roots": ["packageWorkspace", "pages/tab/index", "pages/tab/workspace"],
"entrypoints": ["pages/tab/workspace/workspace"],
"riskKeywords": ["workspace", "supervisor", "workOrder", "pending"],
"documents": ["docs/README.md", "docs/order-creation/README.md"]
},
{
"name": "study",
"aliases": ["学习", "课程", "教学申请", "专项辅导"],
"roots": ["packageStudy", "pages/tab/study", "pages/teachApply", "pages/teachApplyDetail", "pages/teachApplyCreate", "pages/specialMentoring"],
"entrypoints": ["pages/tab/study/study"],
"riskKeywords": ["study", "course", "teachApply", "specialMentoring"],
"documents": ["docs/README.md"]
},
{
"name": "matters",
"aliases": ["事项", "待办", "审批"],
"roots": ["pages/tab/matters", "pages/mattersHandle", "pages/mattersSubmitResult"],
"entrypoints": ["pages/tab/matters/matters"],
"riskKeywords": ["matters", "handle", "submit"],
"documents": ["docs/README.md"]
},
{
"name": "workOrder",
"aliases": ["精品工单", "低价单", "开单", "订单详情"],
"roots": ["tabWorkOrder", "pages/tabWorkOrder"],
"entrypoints": ["pages/tabWorkOrder/pages/index/index", "tabWorkOrder/pages/createOrder/createOrder", "tabWorkOrder/pages/orderDetail/orderDetail"],
"riskKeywords": ["createOrder", "lowPriceFlag", "wx.$orderListRefresh", "OCR"],
"documents": ["docs/order-creation/README.md", "docs/order-lifecycle/README.md", "docs/tabWorkOrder/createOrder.md", "docs/tabWorkOrder/精品工单页面接口清单.md"]
},
{
"name": "shared",
"aliases": ["共享层", "公共组件", "公共接口", "全局状态"],
"roots": ["components", "api", "store", "utils", "behaviors", "wxs"],
"entrypoints": [],
"riskKeywords": ["GLCustForm", "Popup", "wx.$", "globalData", "area-data"],
"documents": ["docs/README.md"]
}
]
}
```
- [ ] **Step 4: Create explicit known gaps**
Write this explicit `known-gaps.json`; it documents the two static-analysis boundaries without suppressing underlying `unresolved` records:
```json
{
"schemaVersion": 1,
"gaps": [
{
"domain": "application",
"kind": "route",
"reason": "部分主框架跳转目标由运行时参数计算,静态图谱保留 unresolved。",
"nextStep": "涉及跳转需求时用 rg 复核 navigateTo、redirectTo、reLaunch、switchTab 和 wx.$router.go 的目标构造。"
},
{
"domain": "shared",
"kind": "endpoint",
"reason": "部分 ROP 方法或服务路径由请求封装在运行时组合,静态图谱不猜测最终接口。",
"nextStep": "涉及接口需求时用 rg 复核 API 方法、请求封装参数和调用页面。"
}
]
}
```
- [ ] **Step 5: Verify catalog and real queries**
Run the Step 2 command.
Expected: all tests pass and page count is exactly 71.
- [ ] **Step 6: Build real artifacts twice**
Run:
```powershell
node scripts/knowledge-graph/knowledge-build.mjs
node scripts/knowledge-graph/knowledge-check.mjs
```
Expected: build reports 71 pages; check passes immediately without a second-build drift caused by `docs/generated/` self-ingestion.
- [ ] **Step 7: Verify performance**
Run:
```powershell
Measure-Command { node scripts/knowledge-graph/knowledge-build.mjs } | Select-Object TotalSeconds
Measure-Command { node scripts/knowledge-graph/query-knowledge-graph.mjs --keyword createOrder --depth 2 --direction both --format json *> $null } | Select-Object TotalSeconds
```
Expected: cold build under 30 seconds; generated-graph query under 2 seconds.
- [ ] **Step 8: Commit catalog and artifacts**
```powershell
git add -- docs/knowledge docs/generated docs/COMPONENT-PAGE-INDEX.md tests/knowledge-graph
git commit -m "docs: generate regional assistant knowledge indexes"
```
---
### Task 6: Affected Tests, Package Commands, and Upload Boundary
**Files:**
- Create: `scripts/knowledge-graph/affected-tests.mjs`
- Create: `tests/knowledge-graph/affectedTests.test.mjs`
- Modify: `package.json`
- Modify: `project.config.json`
- Modify: `tests/migration-readiness/uploadExclusions.test.mjs`
**Interfaces:**
- Consumes: Current-worktree graph and Git changes.
- Produces: `selectAffectedTests`, `readChangedFiles`, `buildCurrentGraph`, `npm test`, `test:affected`, `test:knowledge`, `knowledge:build`, `knowledge:check`, `impact`, and `gen:component-index`.
- [ ] **Step 1: Add failing affected and upload tests**
Adapt the pinned `affectedTests.test.mjs`. Set the expected full roots to:
```js
[
'tests',
'tabWorkOrder/pages/createOrder/tests'
]
```
Add an assertion to `uploadExclusions.test.mjs` that `project.config.json` contains `{ value: '.agents', type: 'folder' }` in `packOptions.ignore`.
- [ ] **Step 2: Verify RED**
Run:
```powershell
node scripts/run-node-tests.mjs tests/knowledge-graph/affectedTests.test.mjs tests/migration-readiness/uploadExclusions.test.mjs
```
Expected: affected test fails because the selector is absent; upload test fails because `.agents` is not explicitly ignored.
- [ ] **Step 3: Add and adapt the selector**
Use the pinned `affected-tests.mjs` as the base. Make these project-specific constants exact:
```js
export const FULL_TEST_ROOTS = [
'tests',
'tabWorkOrder/pages/createOrder/tests'
]
const DOCS_TESTS = [
'tests/knowledge-graph/artifactsAndImpact.test.mjs',
'tests/knowledge-graph/buildKnowledgeGraph.test.mjs',
'tests/project-governance/knowledgeWorkflow.test.mjs'
]
```
Preserve conservative full escalation for global entries, dependencies, shared runtime roots, cross-domain changes, unresolved changed paths, unclassified runtime/tooling, and missing test candidates.
- [ ] **Step 4: Add stable package commands**
Merge these scripts into the existing `scripts` object without removing any current command:
```json
{
"test": "node --experimental-detect-module --test --test-reporter=dot tests tabWorkOrder/pages/createOrder/tests",
"test:affected": "node scripts/knowledge-graph/affected-tests.mjs",
"test:knowledge": "node scripts/run-node-tests.mjs tests/knowledge-graph",
"knowledge:build": "node scripts/knowledge-graph/knowledge-build.mjs",
"knowledge:check": "node scripts/knowledge-graph/knowledge-check.mjs",
"impact": "node scripts/knowledge-graph/query-knowledge-graph.mjs",
"gen:component-index": "npm run knowledge:build"
}
```
- [ ] **Step 5: Add `.agents` to upload exclusions**
Insert exactly one folder rule into `project.config.json`:
```json
{ "value": ".agents", "type": "folder" }
```
Do not change `miniprogramRoot`, `ignoreUploadUnusedFiles`, npm output rules, or runtime includes.
- [ ] **Step 6: Verify GREEN and selection modes**
Run:
```powershell
node scripts/run-node-tests.mjs tests/knowledge-graph/affectedTests.test.mjs tests/migration-readiness/uploadExclusions.test.mjs
npm run test:affected -- --list --format json
```
Expected: tests pass; current working changes produce a deterministic `targeted` or `full` JSON plan with explicit reasons.
- [ ] **Step 7: Commit affected orchestration**
```powershell
git add -- scripts/knowledge-graph/affected-tests.mjs tests/knowledge-graph/affectedTests.test.mjs tests/migration-readiness/uploadExclusions.test.mjs package.json project.config.json
git commit -m "test: select affected miniprogram tests"
```
---
### Task 7: Requirement Analysis Skill and Maintenance Documentation
**Files:**
- Create: `.agents/skills/requirement-impact-analysis/SKILL.md`
- Create: `.agents/skills/requirement-impact-analysis/references/reference.md`
- Create: `.agents/skills/requirement-impact-analysis/references/reference-full.md`
- Create: `tests/project-governance/knowledgeWorkflow.test.mjs`
- Modify: `README.md`
- Modify: `docs/README.md`
- Modify: `docs/DOMAIN-INDEX.md`
**Interfaces:**
- Consumes: Stable commands and generated artifacts from Tasks 4–6.
- Produces: A project-local workflow that always uses DOMAIN-INDEX → knowledge check/query → semantic `rg` review → affected tests.
- [ ] **Step 1: Load the required skill-authoring guidance**
Before editing `.agents/skills/**`, read `superpowers:writing-skills` completely and follow its RED/GREEN verification workflow.
- [ ] **Step 2: Add failing governance tests**
Adapt the pinned `tests/project-governance/knowledgeWorkflow.test.mjs` to assert that:
- root README contains `knowledge:build`, `impact`, and `test:affected`;
- docs README describes generated artifacts, unresolved behavior, upload exclusion, and Live safety;
- DOMAIN-INDEX lists all six domains and links generated indexes;
- the Skill requires `knowledge:check`, `impact`, semantic `rg`, impact classification, and `test:affected`;
- none of the new profile/Skill/docs files contains an 11-digit mobile literal. The repository test must use only this generic pattern and must not contain either user-provided value:
```js
assert.doesNotMatch(content, /\b1\d{10}\b/)
```
- [ ] **Step 3: Verify RED**
Run:
```powershell
node scripts/run-node-tests.mjs tests/project-governance/knowledgeWorkflow.test.mjs
```
Expected: fail because the project Skill and documentation entrypoints do not exist.
- [ ] **Step 4: Add the adapted Skill**
Read the three pinned source files with `git show`, add them using `apply_patch`, and replace source-project domain/examples with:
- `workspace`, `study`, `matters`, `workOrder`, `shared`, `application`;
- `createOrder`, `wx.$orderListRefresh`, `packageWorkspace`, `gl-cust-form`;
- current docs paths under `docs/order-creation`, `docs/order-lifecycle`, and `docs/tabWorkOrder`.
Keep the rule that graph adjacency is evidence, not an automatic must-change list.
- [ ] **Step 5: Rewrite documentation entrypoints**
Replace the root README account-only content with a concise project setup and knowledge workflow. Extend `docs/README.md` with the complete build/query/affected/profile/maintenance guide. Expand `docs/DOMAIN-INDEX.md` from the current work-order-only table to the six-domain map while preserving all existing work-order links.
- [ ] **Step 6: Verify GREEN and rebuild docs**
Run:
```powershell
node scripts/run-node-tests.mjs tests/project-governance/knowledgeWorkflow.test.mjs
npm run knowledge:build
npm run knowledge:check
```
Expected: governance tests and knowledge drift check pass.
- [ ] **Step 7: Commit Skill and docs**
```powershell
git add -- .agents README.md docs/README.md docs/DOMAIN-INDEX.md docs/generated docs/COMPONENT-PAGE-INDEX.md tests/project-governance
git commit -m "docs: add knowledge-driven requirement workflow"
```
---
### Task 8: Guarded Development and Test Live Profiles
**Files:**
- Create: `tests/order-lifecycle/liveProfiles.mjs`
- Create: `tests/order-lifecycle/liveProfiles.test.mjs`
- Create: `tests/order-lifecycle/ui/loginSmokeConfig.mjs`
- Create: `tests/order-lifecycle/ui/loginSmokeConfig.test.mjs`
- Create: `tests/order-lifecycle/ui/loginSmoke.live.test.mjs`
- Create: `tests/order-lifecycle/e2e/liveCleanup.mjs`
- Create: `tests/order-lifecycle/e2e/liveCleanup.test.mjs`
- Modify: `tests/order-lifecycle/e2e/testConfig.mjs`
- Modify: `tests/order-lifecycle/support/environmentGuard.mjs`
- Modify: `tests/order-lifecycle/e2e/orderLifecycle.live.test.mjs`
- Modify: `package.json`
**Interfaces:**
- Consumes: Existing ROP/UI harness and user-owned secrets supplied at runtime.
- Produces: `resolveLiveProfile`, `assertLiveWriteAllowed`, `cleanupTrackedOrders`, a login-only UI smoke, and profile-aware order E2E config.
- [ ] **Step 1: Write profile and cleanup RED tests**
Adapt the pinned profile/cleanup tests with these exact definitions:
```js
{
'regional-dev-login': {
environment: 'development',
mode: 'login-only',
baseUrl: 'http://dj.dev.glsx.com.cn/rop-dj-car-boutique',
mobileEnv: 'LIVE_REGIONAL_DEV_MOBILE',
codeEnv: 'LIVE_REGIONAL_DEV_CODE'
},
'regional-test': {
environment: 'test',
mode: 'functional',
baseUrl: 'http://dj.test.glsx.com.cn/rop-dj-car-boutique',
mobileEnv: 'LIVE_REGIONAL_TEST_MOBILE',
codeEnv: 'LIVE_REGIONAL_TEST_CODE',
yqName: '流程测试园区门店',
storeName: '波波的单店门店',
sceneName: '精品升级'
}
}
```
Tests must prove:
- credentials are read only from the declared env names;
- metadata has no 11-digit mobile values;
- dev profile rejects `assertLiveWriteAllowed` even when the flag is set;
- test profile requires `LIVE_ALLOW_WRITES=1` for order E2E;
- login smoke config requires `LOGIN_UI_PROFILE=regional-dev-login`, validates the loopback WebSocket/DevTools launch settings, and rejects `regional-test`;
- cleanup reverses all tracked orders and never returns/logs session values;
- all Live tests are skipped when their explicit run flags are absent.
- [ ] **Step 2: Verify RED**
Run:
```powershell
node scripts/run-node-tests.mjs tests/order-lifecycle/liveProfiles.test.mjs tests/order-lifecycle/ui/loginSmokeConfig.test.mjs tests/order-lifecycle/e2e/liveCleanup.test.mjs
```
Expected: fail because the profile resolver and cleanup helper do not exist.
- [ ] **Step 3: Implement profile resolution and write gates**
Use the pinned resolver as a base, rename profiles/env variables as above, add `mode`, and implement this stricter gate:
```js
export function assertLiveWriteAllowed(profile, env = process.env) {
if (!LIVE_PROFILE_DEFINITIONS[profile?.name]) {
throw new Error('Approved Live profile is required')
}
if (profile.mode !== 'functional') {
throw new Error(`${profile.name} does not allow Live writes`)
}
if (env.LIVE_ALLOW_WRITES !== '1') {
throw new Error('LIVE_ALLOW_WRITES=1 is required for Live write tests')
}
return true
}
```
- [ ] **Step 4: Keep order E2E test-only**
Update `loadE2EConfig` so `ORDER_E2E_PROFILE=regional-test` resolves the test profile and requires the independent write gate. Reject `regional-dev-login` before creating an ROP order harness. Preserve the existing legacy test-environment variables only as a compatibility path, also guarded by `LIVE_ALLOW_WRITES=1`.
Update `assertAllowedE2EEnvironment` to accept an explicit exact `allowedBases` list without weakening URL protocol, hostname, port, path, query, fragment, username, or password checks.
- [ ] **Step 5: Add login-only UI configuration**
Implement `loginSmokeConfig.mjs` with the same DevTools connection fields already used by `uiSmokeConfig.mjs`: `ORDER_UI_LAUNCH`, `ORDER_UI_CLI_PATH`, `ORDER_UI_PROJECT_PATH`, `ORDER_UI_PORT`, and `ORDER_UI_WS_ENDPOINT`. Its separate enable/profile fields are `RUN_LOGIN_UI_E2E` and `LOGIN_UI_PROFILE`.
`requireLoginSmokeConfig` must call `resolveLiveProfile`, require profile mode `login-only`, require `regional-dev-login`, validate port 1024–65535, require a loopback `ws:` endpoint, and require `ORDER_UI_CLI_PATH` only when launching DevTools. It returns the profile's runtime mobile/code together with the existing launcher fields.
- [ ] **Step 6: Add login-only UI smoke**
Implement `loginSmoke.live.test.mjs` with `miniprogram-automator`. It must:
- skip unless `RUN_LOGIN_UI_E2E=1`;
- require `LOGIN_UI_PROFILE=regional-dev-login`;
- resolve credentials at runtime;
- use `openMiniProgram(automator, config)` and always close the connection in `finally`;
- reLaunch `/pages/wxLogin/wxLogin`, set `loginType: 1`, accept the privacy checkbox, populate the two inputs, and tap `.login_btn`;
- wait for the exact page `pages/accountItems/accountItems`, read `loginUserInfoList`, and assert it is a non-empty array without serializing its contents;
- stop immediately after that assertion, before tapping any `.items` entry, selecting a park/store/scene, or opening an order page;
- never include credential values in assertion messages or diagnostics.
- [ ] **Step 7: Add best-effort order cleanup**
Add the pinned `liveCleanup.mjs` and adapt `orderLifecycle.live.test.mjs` with this exact cleanup mapping:
- cancel flow: track every created order and call cleanup in `catch`; the successful flow already revokes its own order;
- correction flow: track source and corrected orders and call cleanup in `finally`;
- no-construction flow: track the paid order and call cleanup in `finally`;
- construction flow: track the paid order and call cleanup in `finally` even when construction or rework fails;
- cleanup iterates tracked orders in reverse order, continues after a failed revoke, and emits only `orderCode`, role, and a normalized failure reason.
- [ ] **Step 8: Add the login script**
Merge this package command:
```json
{
"test:login:ui": "node scripts/run-node-tests.mjs tests/order-lifecycle/ui/loginSmoke.live.test.mjs"
}
```
- [ ] **Step 9: Verify GREEN without Live credentials**
Run:
```powershell
node scripts/run-node-tests.mjs tests/order-lifecycle/liveProfiles.test.mjs tests/order-lifecycle/ui/loginSmokeConfig.test.mjs tests/order-lifecycle/e2e/liveCleanup.test.mjs tests/order-lifecycle/environmentGuard.test.mjs tests/order-lifecycle/e2e/orderLifecycle.live.test.mjs tests/order-lifecycle/ui/loginSmoke.live.test.mjs
```
Expected: offline contracts pass; Live cases report skipped; no network requests or Mini Program writes occur.
- [ ] **Step 10: Scan the entire migration diff for credentials**
Use PowerShell's regex engine without printing matching contents:
```powershell
$changed = git diff --name-only 5d7d57032ad31517c56fb4f53a00b01e1905728b --
$hits = foreach ($file in $changed) {
if (Test-Path -LiteralPath $file -PathType Leaf) {
if (Select-String -Quiet -Pattern '\b1\d{10}\b' -LiteralPath $file) { $file }
}
}
if ($hits) { throw "Credential-like mobile values found in changed files: $($hits -join ', ')" }
```
Expected: no hits.
- [ ] **Step 11: Commit Live safety profiles**
```powershell
git add -- tests/order-lifecycle package.json
git commit -m "test: guard regional live profiles"
```
Do not execute either Live profile during this task; user credentials and verification codes are runtime-only.
---
### Task 9: Integration Verification and Migration Post Gate
**Files:**
- Modify: `docs/migrations/project-knowledge-graph/manifest.json`
- Modify: `docs/migrations/project-knowledge-graph/test-acceptance.md`
- Modify: generated artifacts only if verification detects legitimate drift.
**Interfaces:**
- Consumes: All prior task deliverables.
- Produces: Evidence that the prerequisite migration is complete and safe to use before main-package optimization begins.
- [ ] **Step 1: Run the complete knowledge contract**
```powershell
node scripts/run-node-tests.mjs tests/knowledge-graph tests/project-governance
```
Expected: all knowledge and governance tests pass.
- [ ] **Step 2: Prove artifact stability**
```powershell
npm run knowledge:build
$firstHashes = @(
Get-ChildItem -LiteralPath docs/generated -File -Recurse
Get-Item -LiteralPath docs/COMPONENT-PAGE-INDEX.md
) | Sort-Object FullName | ForEach-Object { "$(Resolve-Path -LiteralPath $_.FullName -Relative) $((Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash)" }
npm run knowledge:build
$secondHashes = @(
Get-ChildItem -LiteralPath docs/generated -File -Recurse
Get-Item -LiteralPath docs/COMPONENT-PAGE-INDEX.md
) | Sort-Object FullName | ForEach-Object { "$(Resolve-Path -LiteralPath $_.FullName -Relative) $((Get-FileHash -Algorithm SHA256 -LiteralPath $_.FullName).Hash)" }
if (Compare-Object $firstHashes $secondHashes) { throw 'Knowledge artifacts changed across consecutive builds' }
npm run knowledge:check
git diff --stat -- docs/generated docs/COMPONENT-PAGE-INDEX.md
```
Expected: consecutive builds have identical hashes, check passes, and the displayed diff contains only expected Task 8 test/profile graph changes that will be committed as final evidence.
- [ ] **Step 3: Run the complete offline suite**
```powershell
npm test
```
Expected: all offline tests pass; every Live test is skipped by default.
- [ ] **Step 4: Exercise the public CLI contracts**
```powershell
npm run impact -- --keyword createOrder --depth 2 --direction both --format json
npm run impact -- --keyword packageWorkspace --depth 2 --direction both --format json
npm run test:affected -- --list --format json
```
Expected: both queries return non-empty evidence; affected output has mode, reasons, changedFiles, domains, tests, commands, and unresolved fields.
- [ ] **Step 5: Verify upload exclusions and tree hygiene**
```powershell
node scripts/run-node-tests.mjs tests/migration-readiness/uploadExclusions.test.mjs
node scripts/wx-upload-guard.js
git diff --check
git status --short
```
Expected: docs/tests/scripts/.agents are excluded, upload guard passes, no whitespace errors, and status contains only final migration evidence updates.
- [ ] **Step 6: Update acceptance evidence**
Change every Post entry in `test-acceptance.md` to `pass` only when the corresponding command above has actually passed. Update manifest test entries and verification statuses to match the observed results; do not mark a blocked command as pass.
- [ ] **Step 7: Run the required post gate**
```powershell
npm run check:migration -- --manifest docs/migrations/project-knowledge-graph/manifest.json --phase post
```
Expected: `Migration readiness post check passed` and every non-blocked verification command is re-executed successfully by the gate.
- [ ] **Step 8: Commit final evidence**
```powershell
git add -- docs/migrations/project-knowledge-graph docs/generated docs/COMPONENT-PAGE-INDEX.md
git commit -m "docs: record knowledge graph migration evidence"
```
- [ ] **Step 9: Hand off to main-package optimization**
Run these read-only seed queries and save their JSON results outside the repository or summarize them in the next design discussion:
```powershell
npm run impact -- --keyword wxcharts --depth 3 --direction both --format json
npm run impact -- --keyword wxqrcode --depth 3 --direction both --format json
npm run impact -- --keyword gl-cust-form --depth 3 --direction both --format json
npm run impact -- --keyword area-data --depth 3 --direction both --format json
```
Expected: the next main-package optimization design starts from current graph evidence and the existing byte audit, not from copied assumptions.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!