docs: record modular refactor acceptance and final verification

This commit is contained in:
abaishu0730 committed 2026-10-19 09:16:17 +08:00
1 parent a420d2d9fb
commit 7f16bd6882
7 files changed
+75 -100

No files matched your search

@@ -1,38 +0,0 @@
# Task 3: Notification transaction boundary and manual recovery
## Changes
- Split combined implementation into `store.cjs` (SQLite, encrypted records and transactions), `service.cjs` (schedule/SMTP orchestration), and `mapping.cjs` (source paths and event validation). Removed combined internal module; API and web public URLs remain unchanged.
- Construction no longer recovers active work. Explicit `NotificationStore.recover()` must run after application ownership acquisition. Recovery cancels prepared batches, returns eligible reservations to queue, exhausts reservations already at the cap, and preserves sending results as unknown for human resolution.
- `beginSending(batchId)` uses BEGIN IMMEDIATE and validates prepared batch state plus the complete reserved item identity set and ownership before changing batch/items to sending. SMTP sendMail happens only after this succeeds. Terminal/cancelled batch state is not overwritten by failure cleanup.
- Final verification failure marks items exhausted with accurate queue and batch errors. Lowering maxAttempts normalizes eligible queue items; increasing it never revives exhausted items automatically. Unknown results retain separate manual resolution semantics.
- Admin POST `/api/notifications/items/:id/retry` accepts `{batchId,note}` (at least five evidence characters). Transactional status + batch identity CAS resets exactly one exhausted item, encrypts durable retry evidence, and rejects duplicate/stale submissions. Successful API requests also record workspace audit with the evidence. BatchId may be null for pre-existing capped rows without a batch.
- UI shows exhausted explicitly and presents evidence/action only to admins. Actual browser regression submits the form and confirms queued state and persisted evidence.
## Red evidence
`NODE_PATH` used original checkout node_modules and temporary review deps only.
1. Core notification suite before implementation: 6 pass / 4 fail. Second store changed reserved -> pending; cancelled batch reached fake SMTP (1 rather than 0 sends); last verification failure stayed pending rather than exhausted; recover method absent.
2. API/UI regressions before implementation: retry returned 404 instead of permission response; real Chrome timed out waiting for exhausted state/action.
3. Final review regression: exhausted batch still said it would retry next slot. Failure observed, then changed batch error to direct users to queue retry status.
## Green verification
Command: `node --test tests/notifications/*.test.cjs`
Environment: `NODE_PATH=Z:\Order Notification Automation\node_modules;C:\Users\ABS\AppData\Local\Temp\order-review-deps-20261019\node_modules`.
Final result: 13 tests passed, 0 failed, 0 skipped (including real local Chrome HTTP/UI).
Coverage includes safe second store construction; cancellation and stolen reservation CAS; cap exhaustion/no subsequent automatic send; actual successful fake SMTP delivery after manual repair; admin/operator/viewer permissions; evidence validation and persisted audit; one-item reset; immediate and later-cycle stale submission rejection; settings cap changes; prepared/sending recovery; and unknown-result non-retry behavior. Existing deduplication, original body, source mapping, slot timing and IMAP exclusivity remain green.
No provider, production state or process access occurred. Tests use temporary SQLite databases and fake SMTP only.
## Integration and exports
- `require('./modules/notifications/store.cjs').NotificationStore`
- `require('./modules/notifications/service.cjs').NotificationService`
- mapping exports DEFAULT_MAP, validateMap, hash, mapEvent.
- New store methods: recover(), beginSending(batchId), retryItem(id,input,actor); new service method retryItem(id,input,actor).
- `src/server.cjs` imports were updated in shared working tree, but deliberately left for Task 5's lifecycle commit; Task 5 must call recover after obtaining the instance lock.
- Added encrypted retry_audit table; existing state paths, vault AAD, secrets and item/batch payload formats remain readable. Batch snapshots add itemIds to enforce the reservation boundary.
@@ -1,33 +0,0 @@
# Task 5 report
## Scope and interface
- `src/server.cjs` remains the formal CLI entry and exports exactly `main`, `createServer`, `startService`.
- `app/application.cjs` owns dependency creation, startup, explicit notification recovery and shutdown. `app/bridge.cjs` owns the extension bridge and extension installation.
- Dashboard HTTP dispatch stays in `app/dashboard.cjs`; `app/request.cjs` owns security headers, transport security and same-origin/body parsing; `app/assets.cjs` owns unchanged public-to-physical asset mapping; dashboard `auth.cjs` owns bootstrap/login/preview/session cookies/failure limits and `api.cjs` owns overview/settings/users/jobs/audit/downloads.
- Preserved ping-first processing, static assets before auth, same-origin/body guards before auth, authenticated business dispatch order, cookie names/options/renewal/revocation, response status/fields and public URLs. Uses centralized PROJECT_ROOT/WEB_ROOT.
## Ownership and cleanup
- `acquireInstanceLock(stateDir)` canonicalizes through realpath (Windows case-folding) and exclusively binds a SHA-256 keyed Windows named pipe before pairing.key or any business store is touched. OS pipe ownership replaces stale-PID files. Linux fixture compatibility uses abstract sockets with the same lifetime behavior.
- Both CLI foreground and supervised child enter the same `main`. Only the owner calls `NotificationStore.recover()`.
- Every constructed resource is inside the startup try. Startup failure and normal stop share idempotent teardown; all teardown steps are attempted and ownership released even after errors. Startup retains original error with cleanupError; stop aggregates teardown errors.
- Session DB closes on listen failure, explicit unbound dashboard cleanup, and asset initialization failure.
## Red evidence
1. Failure-first lock tests: `node --test tests/service/instance-lock.test.cjs` -> 0 pass / 2 fail because ownership module did not yet exist.
2. Initial runtime second-main test failed against old behavior. Its first cleanup hook ordering also caused Windows EBUSY and was corrected before green verification.
3. To isolate the actual failure boundary after correcting hooks, a disposable copy of HEAD server (only notification import adapted to the completed Task 3 split) ran the identical second-main test. `node --test --test-force-exit --test-name-pattern='second main' tests/app/application.red-check.cjs` -> 0 pass / 1 fail: expected ORDER_INSTANCE_OWNED but actual `listen EADDRINUSE` after second startup had entered business initialization. Both temporary source/test copies were removed. Force-exit was only for this old lifecycle reproduction, not green verification.
## Green evidence
Environment: NODE_PATH=`Z:\Order Notification Automation\node_modules;C:\Users\ABS\AppData\Local\Temp\order-review-deps-20261019\node_modules`.
- `node --test tests/service/instance-lock.test.cjs tests/app/application.test.cjs` -> 4/4 before adding further cleanup regressions.
- `node --test tests/app/application.test.cjs` -> 5/5 after cleanup coverage.
- `node --test tests/app/*.test.cjs tests/service/instance-lock.test.cjs` -> 21 pass, 0 fail, 0 skipped; normal exit, no forced exit. Includes local real-Chrome PDF export, dashboard security/login/settings/authorization, preview restart, navigation, health UI/API and asset behavior.
Specific runtime assertions: first main holds a prepared/reserved batch at fake SMTP verify; second main fails with ownership code and zero notification recovery calls; first batch remains prepared, then releases verify and sends exactly once with item sent. Validation/occupied-dashboard-port failure and partial mail construction failure allow subsequent successful main. Windows database rename verifies prior workspace handle closure. Two deliberately throwing teardowns still close remaining DBs/sockets and permit new ownership. Missing asset resolution closes the already-created SessionStore. Separate actual child process holds the named pipe, parent cannot acquire it, SIGKILL releases it and parent acquires it without PID cleanup.
No production config, provider or running production process was accessed; all state and mail are temporary fixtures. Full-suite final acceptance belongs to parent after integration.
+1
View File
@@ -9,6 +9,7 @@
- [开发交接(2026-10-19)](docs/HANDOFF.md):接续分支、当前进度、启动命令、验证边界及下一步建议。
- [设计要求(当前基准)](docs/design-requirements.md):功能范围、架构、数据存储、权限、验收和实施顺序。
- [模块重构方案(2026-10-19)](docs/superpowers/specs/2026-10-19-modular-refactor-design.md):代码职责、兼容约束及七项鲁棒性修复。
- [本轮重构验证](docs/modular-refactor-verification-2026-10-19.md):故障回归、全量结果和实机验证边界。
- [部署说明](docs/deployment.md):安装、HTTPS、状态目录及备份。
- [后续业务资料整理表](docs/business-configuration.md):SMB 参数、来源字段和产业接口人需要整理的信息。
- [扫描验证记录](docs/bpm-scan-verification-2026-10-16.md):最近验证及实际范围。
+4 -2
View File
@@ -56,6 +56,8 @@ npm test
## 验证与容易重复踩的问题
本轮模块化重构、七项修复及额外生命周期补修见 [2026-10-19 重构验证](modular-refactor-verification-2026-10-19.md)。以下守护实机/官方 CLI 记录来自此前阶段,本轮没有重复操作正式服务或真实提供方。
- 服务守护及受影响回归 20/20、额外加密存储 7/7,共 27 项不同测试通过;19 个 JS 语法检查通过。覆盖实际子进程退出/无响应、冷却、手动重启/停止、鉴权及畸形消息、未知端口保护、中文启动器、安装失败/外来快捷方式、健康历史/权限、浏览器断线恢复。
- 实机独立 CLI 重启后守护保持、两个端口恢复、登录会话保留,健康页无脚本错误。没有重启 Windows,也未验收公司真实邮件及正式全业务自动处理。
- ZCode 官方 CLI 的真实请求已核对地址/模型/鉴权及空工具列表;返回未经请求的 Write 调用时没有写文件。供应商真实认证仍待配置。
@@ -66,8 +68,8 @@ npm test
- CLI 工具禁止名单按精确名称,`*` 不代表全部;旧 provider 导入忽略 `tool_call:false` 和输出 token 上限,不能把它们当安全控制。
```powershell
node --test --test-concurrency=1 tests/service-supervisor.test.cjs tests/service-control.test.cjs tests/windows-startup.test.cjs tests/runtime-health.test.cjs tests/health-http-ui.test.cjs tests/server.test.cjs tests/workspace-http.test.cjs tests/bpm-runtime.test.cjs tests/dashboard-http.test.cjs
node --test tests/bpm-vault.test.cjs
npm test
node --test tests/bpm/bpm-vault.test.cjs
```
详细证据见 [验证记录](verification.md)。日志/截图位于本机忽略目录 `output/verification`,新克隆需要重新生成。
@@ -0,0 +1,43 @@
# 模块化重构与鲁棒性修复验证(2026-10-19)
本轮基于 `9854d2d`,开发分支 `codex/modular-refactor`。工作区为 `C:\Users\ABS\.codex\worktrees\modular-refactor\Order Notification Automation`;原工作区源码保持原状,未推送、合并或部署。
## 目录与职责
- `src/app/`:生命周期装配、扩展桥接、HTTP、资源映射和请求约束;`src/server.cjs` 保留正式入口与三个导出。
- `src/modules/<业务>/`:dashboard、workspace、bpm、mail、storage、notifications、assistant、health、pdf。
- `src/platform/`:浏览器、加密与 Windows/守护能力;`src/shared/`:资源路径、时段和脱敏。
- `web/modules/` 与 `tests/<业务>/` 对齐业务边界。通知拆为 store/service/mapping;登录表单交互从 BPM 会话编排中分离。
## 修复与故障回归
| 问题 | 修复 | 验证边界 |
|---|---|---|
| 第二实例恢复活动通知导致重发 | 在业务数据库初始化前获得状态目录独占;显式恢复;发送前事务核实完整预留归属 | 首实例停在假 SMTP verify,第二次 main 被拒且恢复调用为零;首实例继续只发送一次 |
| 已保存 SMB 操作无期限、无法停止 | 可取消工作进程、队列期限、等待实际退出、进程树终止、IPC 大小/二进制校验 | 真实本地子进程及其后代、挂起/错误响应、取消/超时、队列恢复、归档字节及摘要 |
| 浏览器断开后永久复用缓存 | 按浏览器与 Promise 身份失效缓存和租约,并发重建 | 本地真实无头 Chrome 关闭后重建、漏事件兜底、旧事件不清理新实例 |
| 通知次数耗尽无恢复出口 | 明确 exhausted;管理员填写依据单项重新入队;批次 CAS 与加密审计 | 假 SMTP 实际重试成功、角色权限、证据/重复/跨失败周期旧请求、未知发送结果保持人工核验 |
| JSON/Cookie 等凭据脱敏遗漏 | 共享递归 JSON、敏感键规范化、完整头部脱敏,覆盖输入/回复/历史/摘要 | 虚构凭据实际传给 runtime 和写入加密历史前已去除,包含嵌套数组与转义 JSON |
| 改端口后守护误杀健康替代进程 | 每次启动重读校验端口,失败状态明确;控制确认对应新重启状态 | 真实夹具子进程 A→B、未知占用不被终止、修正配置后真实 CLI 等待成功 |
| 中文自启动路径被 ANSI 转换 | Unicode IShellLinkW/IPersistFile 创建与读取 | 本机代码页 1252 的中文项目/状态/启动路径、读回/隐藏执行/外来快捷方式保护 |
总复核另补两项生命周期缺口:关闭入口立即停止接受新导出,等待已接受渲染与自动归档结束再停止依赖并释放锁;数据库初始化中途失败时关闭已分配的句柄/加密资源。回归覆盖晚到请求体、同步渲染失败、重叠归档与新渲染,以及损坏的持久连接 JSON 修复后重新启动。
## 验证环境与范围
使用临时 SQLite、临时文件、假 SMTP、本地 HTTP 和真实本地 Chrome/Node 子进程。依赖版本及 `package-lock.json` 未改;测试通过以下进程级环境使用原工作区依赖和此前临时补齐的依赖,没有修改正式依赖:
```powershell
$env:NODE_PATH='Z:\Order Notification Automation\node_modules;C:\Users\ABS\AppData\Local\Temp\order-review-deps-20261019\node_modules'
npm test
```
迁移静态检查已确认原有 49 个测试文件全部保留,74 个脚本语法正常,56 个模块可加载,18 个公开资源地址可定位。加密 vault 实现与迁移前逐字节相同;原路径、密钥身份与 AAD 保持兼容。
最终代码提交 `a420d2d` 的全量 `npm test` 正常退出(exit 0):**222 项,221 通过、0 失败、1 跳过,236.10 秒**。最终复核两项 P2 均关闭,任务规格与代码质量复核通过,无遗留重要问题。补修定向测试 15/15、受影响模块测试 135/135 通过。首轮集成全量为 207 项、206 通过、0 失败、1 跳过;上述最终结果包含其后新增的生命周期回归。
本地完整日志和复核记录保存在忽略目录 `output/verification/modular-refactor-2026-10-19/`,不随 Git 发布。54 个测试文件包含原有全部 49 个文件。计划六个任务均已完成;代码、方案与本记录保留在本地工作分支供审阅。
未访问真实 BPM、SMB、邮件或模型提供方,未操作正式服务/配置/业务数据。官方 ZCode CLI 测试需要显式提供 `ORDER_TEST_ZCODE_CLI`,未配置时保留跳过。硬终止 SMB 归档可能留下隐藏临时上传文件或已完整发布但未返回结果的文件;记录保持失败,同摘要重试可核对已有发布结果。
渲染任务若永不结束,正常停止会持续等待并保留独占权,避免旧任务在交接后继续写数据;守护仍保留已有的强制停止路径。本轮不代表公司 BPM→导出→SMB→通知的真实端到端验收,来源适配与自动详情/PDF 仍属后续业务工作。
@@ -24,59 +24,59 @@
**Files:** all existing src business files, web feature files, tests; scripts and package.json imports; new src/shared/paths.cjs.
**Interfaces:** preserve exports, except notifications.cjs remains temporarily under modules/notifications until Task 3 splits it. PROJECT_ROOT/WEB_ROOT/SCRIPTS_ROOT/EXTENSION_ROOT exported by shared/paths.
- [ ] Inventory current tests and relative/resource path uses with rg.
- [ ] Move files to approved directories; rewrite imports from resolved original absolute targets, including fixture paths. Keep src/server.cjs as current entry until Task 5. Move dashboard.cjs to app/dashboard.cjs. Temporarily place notifications.cjs at modules/notifications/notifications.cjs.
- [ ] Centralize static roots. Preserve sibling worker lookup and server entry location; map old public web URLs to new physical files.
- [ ] Change test discovery to recursive node --test pattern; verify all original 49 test files remain discovered.
- [ ] Run module import checks and baseline suite. Expected only known Unicode shortcut failure and official CLI skip. Commit isolated migration.
- [x] Inventory current tests and relative/resource path uses with rg.
- [x] Move files to approved directories; rewrite imports from resolved original absolute targets, including fixture paths. Keep src/server.cjs as current entry until Task 5. Move dashboard.cjs to app/dashboard.cjs. Temporarily place notifications.cjs at modules/notifications/notifications.cjs.
- [x] Centralize static roots. Preserve sibling worker lookup and server entry location; map old public web URLs to new physical files.
- [x] Change test discovery to recursive node --test pattern; verify all original 49 test files remain discovered.
- [x] Run module import checks and baseline suite. Record the intermediate baseline honestly; the migration baseline runner ended before a complete result. The final integrated full suite verifies migration with the Unicode fix. Commit isolated migration.
## Task 2: Saved SMB bounded execution
**Files:** src/modules/storage/*, tests/storage/* and owned fixtures.
**Interfaces:** StorageService public methods remain compatible. Worker runner accepts AbortSignal and deadline; SmbClient exposes cancellable bounded operations without passing secrets in command arguments.
- [ ] Add failure-first tests: hung saved list/check terminates; stop cancels active and queued operations; queue works after timeout; archive result preserves bytes; oversized/invalid IPC fails.
- [ ] Execute targeted tests and capture failure before implementation.
- [ ] Route saved operations through isolated worker, reuse FileArea guards, observe process exit on cancel/timeout, enforce binary response limits. Stop rejects queued tasks promptly.
- [ ] Run storage suites including local fake-worker and archive integrity regressions; commit and report commands/results.
- [x] Add failure-first tests: hung saved list/check terminates; stop cancels active and queued operations; queue works after timeout; archive result preserves bytes; oversized/invalid IPC fails.
- [x] Execute targeted tests and capture failure before implementation.
- [x] Route saved operations through isolated worker, reuse FileArea guards, observe process exit on cancel/timeout, enforce binary response limits. Stop rejects queued tasks promptly.
- [x] Run storage suites including local fake-worker and archive integrity regressions; commit and report commands/results.
## Task 3: Notifications transaction boundary and manual recovery
**Files:** src/modules/notifications/{store,service,mapping,api}.cjs, web/modules/notifications/view.js, tests/notifications/*.
**Interfaces:** NotificationStore.recover() explicit, NotificationStore.beginSending(batchId) transactional CAS; NotificationService retains existing API and adds retryItem(id,input,actor). API retains routes and adds admin retry with evidence/audit.
- [ ] Test constructing second store leaves active prepared batch/items unchanged; cancelled reservation fails beginSending and cannot reach SMTP.
- [ ] Test final allowed SMTP failure becomes exhausted; next tick does not send; manual retry requires admin and evidence, audits, resets one item, rejects repeated submission.
- [ ] Split mapping, transactions and SMTP orchestration into separate files. Recovery runs only explicitly after application ownership. Preserve unknown-result manual resolution rules.
- [ ] Implement accurate exhausted display/action; test API and UI with local fixtures. Commit/report targeted results.
- [x] Test constructing second store leaves active prepared batch/items unchanged; cancelled reservation fails beginSending and cannot reach SMTP.
- [x] Test final allowed SMTP failure becomes exhausted; next tick does not send; manual retry requires admin and evidence, audits, resets one item, rejects repeated submission.
- [x] Split mapping, transactions and SMTP orchestration into separate files. Recovery runs only explicitly after application ownership. Preserve unknown-result manual resolution rules.
- [x] Implement accurate exhausted display/action; test API and UI with local fixtures. Commit/report targeted results.
## Task 4: BPM/browser, shared redaction and Windows supervisor
**Files:** modules/bpm/session-manager.cjs and login-form.cjs; shared/redact.cjs; assistant/policy/service and health imports; platform/service/supervisor.cjs and windows-startup.cjs; scripts/service.cjs; relevant tests and fixtures.
**Interfaces:** preserve manager.browser(), extract form helpers with unchanged login security; redact exported centrally; supervisor accepts validated fresh ports provider each launch; Unicode shortcut create/read retain ownership metadata.
- [ ] Test browser close then concurrent reconstruction launches exactly once, invalidates dead leases and ignores stale disconnect events; use real headless Chrome fixture.
- [ ] Test nested quoted JSON password/cookie and complete Cookie/Authorization values are absent from actual runtime input and persisted history.
- [ ] Test real managed child port A to B restart remains healthy, unknown occupants rejected.
- [ ] Retain failing Chinese startup-path regression on codepage1252; replace shortcut COM ANSI path handling using Unicode IShellLinkW/IPersistFile, test readback and foreign ownership.
- [ ] Implement minimal fixes and form responsibility extraction. Run owned suites, commit/report.
- [x] Test browser close then concurrent reconstruction launches exactly once, invalidates dead leases and ignores stale disconnect events; use real headless Chrome fixture.
- [x] Test nested quoted JSON password/cookie and complete Cookie/Authorization values are absent from actual runtime input and persisted history.
- [x] Test real managed child port A to B restart remains healthy, unknown occupants rejected.
- [x] Retain failing Chinese startup-path regression on codepage1252; replace shortcut COM ANSI path handling using Unicode IShellLinkW/IPersistFile, test readback and foreign ownership.
- [x] Implement minimal fixes and form responsibility extraction. Run owned suites, commit/report.
## Task 5: Application/HTTP responsibility split and ownership
**Files:** src/app/{application,bridge,dashboard,assets,request}.cjs; modules/dashboard/{api,auth}.cjs; platform/service/instance-lock.cjs; src/server.cjs; tests/app and tests/service.
**Interfaces:** server exports main/createServer/startService; application acquires acquireInstanceLock(stateDir) before any business store construction and releases on all failure/shutdown paths. notificationStore.recover() called only with ownership acquired.
- [ ] Test second main on same temporary state fails before business recovery while first owns batch; first can send once and item becomes sent. Test startup failure releases ownership.
- [ ] Split existing bridge/createServer from lifecycle, retain thin formal entry. Extract dashboard auth/business routes, request/security helpers and asset mapping with routing/auth order preserved.
- [ ] Implement named-pipe ownership lock keyed by canonical state directory; avoid unsafe stale PID lockfiles. Make cleanup robust after partial initialization.
- [ ] Run auth, HTTP, resources, browser navigation, startup and integration regressions; verify unchanged cookie/URL behavior. Commit/report.
- [x] Test second main on same temporary state fails before business recovery while first owns batch; first can send once and item becomes sent. Test startup failure releases ownership.
- [x] Split existing bridge/createServer from lifecycle, retain thin formal entry. Extract dashboard auth/business routes, request/security helpers and asset mapping with routing/auth order preserved.
- [x] Implement named-pipe ownership lock keyed by canonical state directory; avoid unsafe stale PID lockfiles. Make cleanup robust after partial initialization.
- [x] Run auth, HTTP, resources, browser navigation, startup and integration regressions; verify unchanged cookie/URL behavior. Commit/report.
## Task 6: Review and acceptance
**Files:** README/development docs/HANDOFF as relevant, all changed modules and tests.
- [ ] Independent task reviews and final whole-change review; route meaningful findings back to implementers and verify fixes.
- [ ] Check no dangling old imports/resource paths; verify test discovery and encrypted persistence compatibility using temporary state.
- [ ] Run full npm test with review NODE_PATH; require zero failures, document official CLI skip honestly.
- [ ] Update design/plan progress and architecture documentation. Report exact results and untested real-provider limits; retain reviewable attached checkout.
- [x] Independent task reviews and final whole-change review; route meaningful findings back to implementers and verify fixes.
- [x] Check no dangling old imports/resource paths; verify test discovery and encrypted persistence compatibility using temporary state.
- [x] Run full npm test with review NODE_PATH; require zero failures, document official CLI skip honestly.
- [x] Update design/plan progress and architecture documentation. Report exact results and untested real-provider limits; retain reviewable attached checkout.
@@ -1,6 +1,6 @@
# 按业务模块组织代码:重构设计
日期:2026-10-19。状态:用户已批准实施。
日期:2026-10-19。状态:已实施并验收;最终全量 222 项,221 通过、0 失败、1 跳过。详见 [本轮验证](../../modular-refactor-verification-2026-10-19.md)。
## 目标与范围