nx-kv 0.45.1 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +11 -5
  3. package/assets/kv-get/SKILL.md +1 -1
  4. package/assets/kv-get/references/timegoal-workflow.md +7 -7
  5. package/assets/kv-get/references/timegoal.md +6 -6
  6. package/bin/{cli.mjs → kv.mjs} +13 -2
  7. package/package.json +23 -11
  8. package/src/core/{command-table.js → command-table.ts} +16 -5
  9. package/src/core/{config.js → config.ts} +46 -27
  10. package/src/core/db/quiet.js +4 -0
  11. package/src/core/{errors.js → errors.ts} +35 -18
  12. package/src/core/{open.js → open.ts} +3 -3
  13. package/src/core/{paths.js → paths.ts} +18 -9
  14. package/src/core/{serve-port.js → serve-port.ts} +43 -17
  15. package/src/index.js +11 -9
  16. package/src/index.ts +10 -0
  17. package/src/modules/localtask/action-lifecycle.js +3 -6
  18. package/src/modules/localtask/repo/goals.js +5 -6
  19. package/src/modules/localtask/task-lifecycle.js +2 -2
  20. package/src/modules/system/actions/_manifest.generated.ts +23 -0
  21. package/src/modules/system/actions/bootstrap.ts +74 -0
  22. package/src/modules/system/actions/health.ts +57 -0
  23. package/src/modules/system/actions/routes.ts +26 -0
  24. package/src/modules/system/index.ts +29 -0
  25. package/src/modules/system/{routes.js → routes.ts} +22 -26
  26. package/src/modules/system/schemas.ts +29 -0
  27. package/src/modules/tasktool/index.js +4 -7
  28. package/src/modules/tasktool/panel-escort.js +1 -1
  29. package/src/modules/tasktool/plugins/goal-template.js +2 -2
  30. package/src/modules/tasktool/plugins/taskgoal-store.js +1 -1
  31. package/src/modules/tasktool/plugins/timegoal-cwd-store.js +8 -11
  32. package/src/modules/tasktool/plugins/timegoal-task-store.js +9 -12
  33. package/src/runtime/action-base.ts +14 -0
  34. package/src/runtime/action-decorator.ts +176 -0
  35. package/src/runtime/api.ts +146 -0
  36. package/src/runtime/{cli.js → cli.ts} +241 -161
  37. package/src/runtime/codegen.ts +243 -0
  38. package/src/runtime/container.ts +53 -0
  39. package/src/runtime/{cors.js → cors.ts} +35 -28
  40. package/src/runtime/help.ts +77 -0
  41. package/src/runtime/registry.ts +139 -0
  42. package/src/runtime/{server.js → server.ts} +65 -24
  43. package/src/runtime/{spec.js → spec.ts} +122 -31
  44. package/src/runtime/types/module.ts +43 -0
  45. package/src/runtime/zod-bridge.ts +198 -0
  46. package/src/shared/prompt-blocks.js +1 -1
  47. package/src/web/frontend/api/cli-tree.json +49 -0
  48. package/src/web/frontend/api/client.generated.ts +39 -0
  49. package/src/web/public/assets/{Introduction-EHroxF1H.js → Introduction-BI8Ohz1l.js} +1 -1
  50. package/src/web/public/assets/{bar-BvS_Jfi4.js → bar-Jfji2mz3.js} +1 -1
  51. package/src/web/public/assets/{cloud-DlWk0wnP.js → cloud-cFewR3CF.js} +1 -1
  52. package/src/web/public/assets/{composer-panel-D3w-CjhN.js → composer-panel-CcK0D4Gd.js} +1 -1
  53. package/src/web/public/assets/{deleted-panel-BMJEEBWD.js → deleted-panel-oN8YlGvq.js} +1 -1
  54. package/src/web/public/assets/{dir-BtjHgH4Q.js → dir-BuAtw08k.js} +1 -1
  55. package/src/web/public/assets/{group-Bxq8JamU.js → group-FRUv4mQ6.js} +1 -1
  56. package/src/web/public/assets/{index-ChlZPTea.js → index-CyF6nNWE.js} +2 -2
  57. package/src/web/public/assets/{md-history-CBqcR086.js → md-history-DErcpXhC.js} +1 -1
  58. package/src/web/public/assets/{overview-BP5sB1WX.js → overview-DZHcrz4u.js} +1 -1
  59. package/src/web/public/assets/{refs-Dt7DQIOo.js → refs-BXIwmL5W.js} +1 -1
  60. package/src/web/public/assets/{repos-Zl1_SfPX.js → repos-DYugJZpl.js} +1 -1
  61. package/src/web/public/assets/{route-crumb-PqhQSVWL.js → route-crumb-C3Ce0rzR.js} +1 -1
  62. package/src/web/public/assets/{settings-CXWFvvvv.js → settings-Bpazt87u.js} +2 -2
  63. package/src/web/public/assets/{status-tag-BK-45ld2.js → status-tag-CHCpOgMP.js} +1 -1
  64. package/src/web/public/assets/{task-COFIPegR.js → task-G58spmPC.js} +1 -1
  65. package/src/web/public/assets/{templates-CIxgTTt-.js → templates-Dr0CunY8.js} +1 -1
  66. package/src/web/public/assets/{tool-bar-TIqYxsQl.js → tool-bar-BSIlsHln.js} +1 -1
  67. package/src/web/public/index.html +1 -1
  68. package/src/modules/system/index.js +0 -96
  69. package/src/runtime/api.js +0 -101
  70. package/src/runtime/registry.js +0 -89
package/CHANGELOG.md CHANGED
@@ -2,6 +2,63 @@
2
2
 
3
3
  本文件记录对外可见的变更。格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/)。
4
4
 
5
+ ## [0.47.0] - 2026-11-11 按 server-cli-web 模板形态 TS 化(阶段一:骨架,#174)
6
+
7
+ ### Added
8
+
9
+ - **模板骨架(对齐 `nx-nx/templates/server-cli-web`)**:`src/runtime/` 全部改写为
10
+ strict TypeScript——`@action` 装饰器(zod schema 即契约)、IoC 容器(`Container` +
11
+ `DependencyMap`)、`Registry` 类、`CliApp` / `ApiRouter` / `PanelServer`、
12
+ `zod-bridge`(CLI/HTTP 共用的归一化 + 校验)、`codegen`(前端 typed client +
13
+ CLI 树快照)。
14
+ - **codegen 工具链**:`pnpm gen:actions` 扫 `modules/<域>/actions/*.ts` 生成
15
+ `_manifest.generated.ts`(加一条 action = 新建一个文件 + 跑一次生成,模块 index 零改动);
16
+ `pnpm gen:api` 生成前端 `api/client.generated.ts` + `api/cli-tree.json`;
17
+ 新鲜度由 `tests/unit/api-client.test.mjs` 对账。
18
+ - **`system` 模块按模板形态重写**:`ModuleBase` 子类 + `schemas.ts`(zod 契约)+
19
+ `actions/<名>.ts` 一条 action 一个文件(bootstrap / health / routes)。
20
+ - **工具链**:三份 tsconfig(`base` / `node` / `web`,strict + `noUncheckedIndexedAccess`)、
21
+ `vite.config.ts`、`pnpm typecheck`、`pnpm dev`(vite + 后端一条命令起,端口先谈定再起进程)。
22
+ - **双通道并存**:legacy flags 表 action 与 zod 通道 action 由同一个 Registry 装载,
23
+ CLI / HTTP / help / routes 对通道无感——存量 166 条 action 行为零回归。
24
+
25
+ ### Changed
26
+
27
+ - **CLI 入口 `bin/cli.mjs` → `bin/kv.mjs`**(模板形态);**直跑 TS 源码**(tsx 注册 loader),
28
+ 不再走 dist——避免「改了源码忘 build」导致全局命令静默跑旧逻辑。
29
+ - `serve` / `help` / `version` 暂留 runtime 内建(help / version 要看注册表全集,
30
+ serve 要挂 localtask 面板占位;迁入 platform 模块列入后续阶段)。
31
+ - `routes` 命令从 runtime 内建迁入 `system` 模块(命令表改由 core 快照格子提供,
32
+ 不再依赖 runtime,解除「模块 ↔ runtime」的历史耦合)。
33
+ - **跨域策略保持不变**(任务 #57 的裁决):HTTP 层不做「Origin 主机名必须是本机」的拒绝,
34
+ 仍走标准 CORS 头 + 预检——模板自带的跨站拒绝会把内网穿透场景的真实用户挡在门外。
35
+ - `src/core/` 的 errors / paths / config / command-table / serve-port / open 改写为 TS。
36
+
37
+ ### Docs
38
+
39
+ - `plan/174-template-ts-refactor-stage1.md`:本次范围、分期与偏离模板之处(含理由)。
40
+ - 项目级 skill `dev-nxkv` 同步新结构:分层树、action 双形态契约、验证命令(typecheck / gen)。
41
+
42
+ ## [0.46.0] - 2026-11-10 progress 参数彻底退役(#92)
43
+
44
+ ### Removed
45
+
46
+ - **`localtask done --progress`**:flag 彻底删除(0.31.x 起已废弃不生效)——done 只携带
47
+ `--summary`,完成总结就是本轮终态。
48
+ - **`localtask get --summary`**:废弃占位 flag 删除——get 就是单纯的领取语义,不收任何现状。
49
+ - **`timegoal check --progress`**:参数语义废除——check 只要求 `--summary`(当轮现状),
50
+ 日志每轮只记现状 + 剩余时间;CLI 回显、`timegoal log` / `localtask timegoal-log` 输出、
51
+ 任务级 goal 交付模板与 doneguard 默认文案同步去掉 progress 段。
52
+ - **存储写入简化**:任务级 `goal_checks.summary` 列改为纯文本(旧库 JSON `{summary, progress}`
53
+ 编码在读取侧兼容解析,web 任务页 check 标签的历史 progress 行仍可显示,新行不再产生);
54
+ 目录级 timegoal blob 的 check 流水同样不再写入 progress 字段(历史字段原样透出)。
55
+
56
+ ### Docs
57
+
58
+ - `assets/kv-get`(SKILL.md / timegoal / timegoal-workflow)、`README`、
59
+ `docs/project&projectsCli.md`:全部 check/done 命令示例去掉 `--progress`;
60
+ - 单测:`timegoal.test.mjs`、`taskgoal.test.mjs` 按「check 只要 summary」更新断言。
61
+
5
62
  ## [0.45.1] - 2026-11-10 残留 -shm 打开自愈 + 打开失败错误指路
6
63
 
7
64
  ### Fixed
package/README.md CHANGED
@@ -34,17 +34,23 @@
34
34
  ```bash
35
35
  pnpm install
36
36
 
37
- # 开发模式(需要两个终端)
38
- pnpm run dev:serve # 终端 1:后端 :7877
39
- pnpm run dev # 终端 2:Vite :5181,/api 代理到 7877
37
+ # 开发模式(一条命令:vite + 后端一起起,ctrl-c 一起退)
38
+ pnpm dev # vite :5181 + 后端 :7877,/api 自动代理到后端实际端口
39
+
40
+ # 只想跑其中一半时
41
+ pnpm run dev:serve # 只起后端 :7877
42
+ pnpm run vite # 只起 Vite :5181(等价于 npx vite)
40
43
 
41
44
  # 生产模式
42
45
  pnpm start # 构建 + 起面板
43
46
 
44
- # 校验:lint + 构建 + 94 项端到端冒烟 + 33 项单元/一致性测试
47
+ # 校验:lint + 类型检查 + 构建 + 194 项端到端冒烟 + 894 项单元/一致性测试
45
48
  pnpm test
46
49
  ```
47
50
 
51
+ > 代码是 TypeScript(strict):`pnpm typecheck` 跑 `tsc -b`,
52
+ > `pnpm gen` 重新生成 action 清单与前端 typed client(改了 action 声明就要跑)。
53
+
48
54
  冒烟测试**对着假后端跑**(`tests/fake-backend.mjs`),不会碰生产服务器上的真实数据。
49
55
 
50
56
  `nx-kv serve` 默认会打开浏览器;**端口被占时不会报错退出**:
@@ -231,7 +237,7 @@ nx-kv timegoal set --cwd "$PWD" --duration 10800 --prompt "<完整全局提示
231
237
  nx-kv timegoal set --cwd "$PWD" --duration 5h --prompt "<完整全局提示词>" --json
232
238
 
233
239
  # 每轮调一次:算出还剩多少时间,并把提示词【原文】回显给你
234
- nx-kv timegoal check --cwd "$PWD" --summary "<当前现状>" --progress "<完成度/下一步>" --json
240
+ nx-kv timegoal check --cwd "$PWD" --summary "<当前现状>" --json
235
241
  # → { reached:false, remainingSec:10780, prompt:"<完整提示词原文>", deadline, ... }
236
242
 
237
243
  # 提示词要改(agent 自我迭代 / 用户在面板上改)——只换提示词,保住计时起点
@@ -44,7 +44,7 @@ nx-kv localtask get --json
44
44
  **自动起表**,交付文本里带一条固定指令:
45
45
 
46
46
  ```bash
47
- nx-kv timegoal check --task task:<topicKey>:<taskId> --summary "<本轮现状>" --progress "<进展/下一步>"
47
+ nx-kv timegoal check --task task:<topicKey>:<taskId> --summary "<本轮现状>"
48
48
  ```
49
49
 
50
50
  每轮推进先跑一次 check(它会原文回显时间目标提示词,防长对话漂移)。
@@ -37,7 +37,7 @@
37
37
  ▼
38
38
  ┌───────────────────────────────────────────────────────┐
39
39
  │ 1. nx-kv timegoal check --cwd "$PWD" \ │
40
- │ --summary "<本轮现状>" --progress "<完成度/下一步>" │
40
+ │ --summary "<本轮现状>" │
41
41
  │ ↓ 拿到 {remainingSec, prompt} │
42
42
  │ 2. 把 prompt 字段当本轮根指令 │
43
43
  │ 3. 干活(按 prompt 指令): │
@@ -82,7 +82,7 @@
82
82
  硬性约束:
83
83
  - 严禁超过本轮剩余时间预算(remainingSec < 30 时立刻停手、写总结、不开新轮)
84
84
  - 严禁自己改 deadline;想缩短就 `timegoal clear` 再 `timegoal set`
85
- - 每轮开始时先 `nx-kv timegoal check --cwd "$PWD" --summary "<本轮现状>" --progress "<完成度/下一步>" --json`,
85
+ - 每轮开始时先 `nx-kv timegoal check --cwd "$PWD" --summary "<本轮现状>" --json`,
86
86
  把返回里的 `prompt` 字段当作本轮根指令;**不要从对话历史里重新拼**——以 store 为准
87
87
  - 写代码必须随附测试;测试失败的修补不计入本轮成果
88
88
  ```
@@ -100,24 +100,24 @@ nx-kv timegoal set --cwd "$PWD" --duration 10800 \
100
100
  --prompt "..." --json
101
101
 
102
102
  # 2. 立刻 check:reached:false
103
- nx-kv timegoal check --cwd "$PWD" --summary "刚起步" --progress "刚 set 完" --json
103
+ nx-kv timegoal check --cwd "$PWD" --summary "刚起步" --json
104
104
 
105
105
  # 3. sleep 6s
106
106
  sleep 6
107
107
 
108
108
  # 4. 再 check:注意 elapsedSec 增加
109
- nx-kv timegoal check --cwd "$PWD" --summary "跑了一轮" --progress "继续" --json
109
+ nx-kv timegoal check --cwd "$PWD" --summary "跑了一轮" --json
110
110
 
111
111
  # 5. update:只换 prompt,deadline 不动
112
112
  nx-kv timegoal update --cwd "$PWD" --prompt "V2 改得更简洁" --json
113
113
 
114
114
  # 6. check:prompt 已是 V2,deadline 仍是 1 小时后
115
- nx-kv timegoal check --cwd "$PWD" --summary "改完 prompt" --progress "继续" --json
115
+ nx-kv timegoal check --cwd "$PWD" --summary "改完 prompt" --json
116
116
 
117
117
  # 7. 等到点后:reached:true
118
118
  # 到点后目标立即失效,但保留期内 show/check 仍查得到 —— 最后一轮照样能读到 prompt
119
119
 
120
- # 8. 回看每轮日志(现状 / 完成度 / 剩余)
120
+ # 8. 回看每轮日志(现状 / 剩余)
121
121
  nx-kv timegoal log --cwd "$PWD" --json
122
122
 
123
123
  # 9. clear
@@ -131,7 +131,7 @@ nx-kv timegoal clear --cwd "$PWD" --json
131
131
  | 现象 | 原因 / 做法 |
132
132
  | --------------------------------------- | ---------------------------------------------------------------------------- |
133
133
  | `reached` 没翻 | 检查客户端时区或 set 时是否给了 `--duration` 过短(默认下限 60s) |
134
- | check 报"缺少参数 --summary" | 每次 check 都要写一条日志,必须带 `--summary` 与 `--progress` |
134
+ | check 报"缺少参数 --summary" | 每次 check 都要写一条日志,必须带 `--summary` |
135
135
  | `reached` 翻 true 但 list 里看不到目标 | 到点即失效(活动列表只留未到点的);保留期内 `show`/`check` 仍查得到,`list --json` 看 `archived` |
136
136
  | update 报"已经到点失效" | 目标已失效不可复活;要继续请用 `set` 开新一局(起点从现在重算) |
137
137
  | update 失败"主题「X」尚未设置 timegoal" | 先 `set` 再 `update`;`update` 不创建 |
@@ -45,7 +45,7 @@ nx-kv timegoal set --cwd "$PWD" \
45
45
 
46
46
  ```
47
47
  每轮开始:
48
- nx-kv timegoal check --cwd "$PWD" --summary "<当前现状>" --progress "<完成度/下一步>" --json
48
+ nx-kv timegoal check --cwd "$PWD" --summary "<当前现状>" --json
49
49
  → { remainingSec, prompt, ... }
50
50
  → 把 prompt 字段当作本轮根指令(不要从对话历史里重新拼)
51
51
 
@@ -108,14 +108,14 @@ nx-kv timegoal set --cwd "$PWD" \
108
108
  nx-kv timegoal set --cwd <dir> --duration <5h|10800> --prompt "<...>" # 设/换(新起点)
109
109
  nx-kv timegoal update --cwd <dir> --prompt "<新版>" [--duration <5h|秒>] # 改提示词/时长(保起点)
110
110
  nx-kv timegoal show --cwd <dir> # 仅查(不算时间)
111
- nx-kv timegoal check --cwd <dir> --summary "<现状>" --progress "<完成度/下一步>" # 算时间 + 回显 prompt + 写一条日志
111
+ nx-kv timegoal check --cwd <dir> --summary "<现状>" # 算时间 + 回显 prompt + 写一条日志
112
112
  nx-kv timegoal clear --cwd <dir> # 清空
113
113
  nx-kv timegoal list # 所有有 timegoal 的目录(到点的单列在归档区)
114
- nx-kv timegoal log --cwd <dir> # 回看每轮 check 的记录(现状/完成度/剩余)
114
+ nx-kv timegoal log --cwd <dir> # 回看每轮 check 的记录(现状/剩余)
115
115
  ```
116
116
 
117
- > `check` **必须**带 `--summary` 与 `--progress`:每次检查都会往该目录的 timegoal
118
- > 日志里追加一条(现状 + 完成度 + 剩余时间)。缺参数会直接报
117
+ > `check` **必须**带 `--summary`:每次检查都会往该目录的 timegoal
118
+ > 日志里追加一条(现状 + 剩余时间)。缺参数会直接报
119
119
  > `缺少参数 --summary`——这是刻意设计的:没有现状的日志等于没记。
120
120
  > 日志只保留**最近 200 条**,长跑任务不会把 store 撑爆。
121
121
 
@@ -154,7 +154,7 @@ nx-kv timegoal log --cwd <dir> # 回看每
154
154
  - **两种 timegoal**:目录级(`--cwd`,与目录一对一)与**任务级**(`--task
155
155
  task:<topicKey>:<taskId>`,发布时 `localtask add --duration 2h` 随任务携带,
156
156
  **领取即计时**)。任务级的 goal key 会随任务交付的 instruction 一起给你,
157
- 直接照抄执行即可;`timegoal check --task <key> --summary … --progress …` 记日志,
157
+ 直接照抄执行即可;`timegoal check --task <key> --summary …` 记日志,
158
158
  未到点 `localtask done` 会拒绝标记完成。
159
159
  - 不阻塞任何东西:可以同时跑人机接力、派任务给别的 agent、外部 cron
160
160
  - 不需要登录 KV 后端:纯本机
@@ -1,7 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
  // nx-kv 唯一入口。
3
3
  // 设计约定:Web 面板上每个按钮,都对应这里的一条 CLI 命令——二者由同一份 action
4
- // 声明派生(见 src/modules/*/index.js),不是靠人维护两份清单。
4
+ // 声明派生(见 src/modules/*/),不是靠人维护两份清单。
5
+ //
6
+ // 运行的是 TS 源码(tsx 注册 loader 后动态 import)——与 `pnpm dev`、smoke 测试
7
+ // 同一条执行路径,**没有第二个真相源**。刻意不走 dist:bin 跑构建产物的话,
8
+ // 「改了源码忘了 build」会让全局 `nx-kv` 静默跑旧逻辑,这类 bug 没有任何报错指向根因。
9
+ // tsx 在 devDependencies:本仓库以 pnpm link 方式安装(scripts/link-local.mjs),
10
+ // bin 从仓库自己的 node_modules 解析 tsx,不需要装进 dependencies。
5
11
 
6
12
  // ── Node 版本硬拦(必须在任何业务 import 之前)──────────────────────────
7
13
  //
@@ -19,7 +25,12 @@ if (!versionCheck.ok) {
19
25
  process.exit(1);
20
26
  }
21
27
 
22
- const { runCli } = await import('../src/runtime/cli.js');
28
+ import { register } from 'tsx/esm/api';
29
+
30
+ // 注册 tsx loader(返回 unregister,进程退出无需清理)
31
+ register();
32
+
33
+ const { runCli } = await import('../src/runtime/cli.ts');
23
34
 
24
35
  runCli(process.argv.slice(2)).catch((err) => {
25
36
  console.error(err && err.stack ? err.stack : String(err));
package/package.json CHANGED
@@ -1,28 +1,33 @@
1
1
  {
2
2
  "name": "nx-kv",
3
- "version": "0.45.1",
3
+ "version": "0.47.0",
4
4
  "description": "nx-kv — KV 清单管理中枢(远程)+ 本机本地任务队列(localtask):serve 驱动 CLI 与 Web 面板,同源同构,附带可安装 skill 供 agent 提交 / 领取 / 阻塞接收任务",
5
5
  "type": "module",
6
6
  "bin": {
7
- "nx-kv": "bin/cli.mjs"
7
+ "nx-kv": "bin/kv.mjs"
8
8
  },
9
9
  "main": "src/index.js",
10
10
  "exports": {
11
11
  ".": "./src/index.js"
12
12
  },
13
13
  "scripts": {
14
- "build": "vite build && node scripts/link-local.mjs --auto",
15
- "dev": "vite",
16
- "dev:serve": "node bin/cli.mjs serve --no-open",
17
- "start": "pnpm run build && node bin/cli.mjs serve",
14
+ "gen:actions": "node --import tsx scripts/gen-actions.mjs",
15
+ "gen:api": "node --import tsx scripts/gen-api-client.mjs",
16
+ "gen": "pnpm run gen:actions && pnpm run gen:api",
17
+ "typecheck": "pnpm run gen && tsc -b tsconfig.node.json tsconfig.web.json",
18
+ "build": "pnpm run gen && tsc -b tsconfig.node.json && vite build && node scripts/link-local.mjs --auto",
19
+ "dev": "node --import tsx scripts/dev.mjs",
20
+ "vite": "vite",
21
+ "dev:serve": "node --import tsx src/runtime/cli.ts serve --no-open",
22
+ "start": "pnpm run build && node --import tsx src/runtime/cli.ts serve",
18
23
  "link:local": "node scripts/link-local.mjs",
19
24
  "unlink:local": "node scripts/link-local.mjs --unlink",
20
25
  "lint": "eslint . && node scripts/check-tdz.mjs --all && node scripts/check-schema-decisions.mjs && node scripts/check-lines.mjs",
21
26
  "check:schema": "node scripts/check-schema-decisions.mjs",
22
- "test": "pnpm run lint && pnpm run build && pnpm run test:smoke && pnpm run test:unit",
23
- "test:smoke": "node tests/smoke.mjs",
24
- "test:unit": "node --test tests/unit/*.test.mjs",
25
- "test:db": "node --test tests/unit/db-*.test.mjs"
27
+ "test": "pnpm run lint && pnpm run typecheck && pnpm run build && pnpm run test:smoke && pnpm run test:unit",
28
+ "test:smoke": "node --import tsx tests/smoke.mjs",
29
+ "test:unit": "node --import tsx --test tests/unit/*.test.mjs",
30
+ "test:db": "node --import tsx --test tests/unit/db-*.test.mjs"
26
31
  },
27
32
  "packageManager": "pnpm@10.33.0",
28
33
  "engines": {
@@ -49,14 +54,21 @@
49
54
  },
50
55
  "license": "MIT",
51
56
  "devDependencies": {
57
+ "@types/node": "^26.6.6",
58
+ "@types/react": "^19.2.7",
59
+ "@types/react-dom": "^19.2.3",
52
60
  "@vitejs/plugin-react": "^6.1.1",
53
61
  "eslint": "^10.10.0",
62
+ "tsx": "^4.23.15",
63
+ "typescript": "^5.9.3",
64
+ "typescript-eslint": "^8.72.2",
54
65
  "vite": "^8.3.0"
55
66
  },
56
67
  "dependencies": {
57
68
  "flexlayout-react": "0.11.1",
58
69
  "handlebars": "^4.7.10",
59
70
  "react": "^19.3.0",
60
- "react-dom": "^19.3.0"
71
+ "react-dom": "^19.3.0",
72
+ "zod": "^4.6.7"
61
73
  }
62
74
  }
@@ -1,7 +1,7 @@
1
1
  // 命令表快照:runtime 装配后写一次,模块只读。
2
2
  //
3
3
  // 为什么需要这个格子:`/api/bootstrap` 要给面板下发「每个操作对应的 CLI 命令」,
4
- // 而这张表由 runtime 装配(cli.js / registry.js)。模块直接 import runtime 会成环
4
+ // 而这张表由 runtime 装配(cli.ts / registry.ts)。模块直接 import runtime 会成环
5
5
  // (registry → modules/system → cli → registry),历史写法是用 `await import(...)`
6
6
  // 绕开:命令能跑,但分层倒了,且 loader 顺序一变就可能拿到半初始化的模块。
7
7
  //
@@ -9,14 +9,25 @@
9
9
  // runtime → core(写快照) modules → core(读快照)
10
10
  // 谁都不再反过来依赖谁。没有快照时返回空数组——调用方(bootstrap)允许空表降级,
11
11
  // 面板仍能打开,只是没有 CLI 提示。
12
- let rows = [];
12
+
13
+ /** 命令表的一行:routes / help / bootstrap 共用,几张表因此必然同源同长。 */
14
+ export interface CommandEntry {
15
+ id: string;
16
+ module: string;
17
+ command: string;
18
+ usage: string;
19
+ http: { method: string; path: string } | null;
20
+ summary?: string;
21
+ }
22
+
23
+ let rows: CommandEntry[] = [];
13
24
 
14
25
  /** 由 runtime 在装配完成时调用。只保留最后一次写入(CLI 的表是注册表的超集)。 */
15
- export function publishCommandTable(list) {
16
- rows = Array.isArray(list) ? list : [];
26
+ export function publishCommandTable(list: readonly CommandEntry[]): void {
27
+ rows = Array.isArray(list) ? [...list] : [];
17
28
  }
18
29
 
19
30
  /** 当前命令表快照(每行 { id, module, command, usage, http, summary })。 */
20
- export function commandTable() {
31
+ export function commandTable(): CommandEntry[] {
21
32
  return rows;
22
33
  }
@@ -33,7 +33,7 @@ import { nowMs } from './db/time.js';
33
33
  export const CONFIG_PATH = join(homedir(), '.nx-kv', 'config.json');
34
34
 
35
35
  // 测试与多实例覆盖:NX_KV_CONFIG 环境变量优先,其次是 NX_KV_STORE 所在目录
36
- export function configPathFromEnv() {
36
+ export function configPathFromEnv(): string {
37
37
  return process.env.NX_KV_CONFIG || CONFIG_PATH;
38
38
  }
39
39
 
@@ -42,15 +42,33 @@ export const DEFAULT_BASE_URL = 'http://192.0.2.47:8988';
42
42
  // ── 显式白名单(#82 的教训:不列出的字段两边都不写)────────────────────
43
43
 
44
44
  /** 留在 config.json 的字段(凭据 + 会话身份)。config.json 的键集合精确等于它。 */
45
- export const CREDENTIAL_KEYS = Object.freeze(['baseUrl', 'token', 'email', 'userId', 'groupId']);
45
+ export const CREDENTIAL_KEYS = Object.freeze(['baseUrl', 'token', 'email', 'userId', 'groupId'] as const);
46
46
 
47
47
  /** 进 settings 表(`app.*` 前缀)的偏好字段。 */
48
- export const PREF_KEYS = Object.freeze(['autoSyncAttachments', 'attachmentsDir', 'gitRepoRoot', 'gitDevRoot']);
48
+ export const PREF_KEYS = Object.freeze([
49
+ 'autoSyncAttachments',
50
+ 'attachmentsDir',
51
+ 'gitRepoRoot',
52
+ 'gitDevRoot',
53
+ ] as const);
49
54
 
50
55
  /** settings 表里偏好字段的键名。 */
51
56
  export const APP_SETTING_KEYS = Object.freeze(PREF_KEYS.map((k) => 'app.' + k));
52
57
 
53
- const EMPTY = () => ({
58
+ /** 归一后的本机配置形状(文件 5 项 + settings 偏好)。 */
59
+ export interface AppConfig {
60
+ baseUrl: string;
61
+ token: string;
62
+ email: string;
63
+ userId: number;
64
+ groupId: number;
65
+ autoSyncAttachments: boolean;
66
+ attachmentsDir: string;
67
+ gitRepoRoot: string;
68
+ gitDevRoot: string;
69
+ }
70
+
71
+ const EMPTY = (): AppConfig => ({
54
72
  baseUrl: process.env.NX_KV_BASE_URL || DEFAULT_BASE_URL,
55
73
  token: '',
56
74
  email: '',
@@ -70,30 +88,31 @@ const EMPTY = () => ({
70
88
  gitDevRoot: '',
71
89
  });
72
90
 
73
- let cache = null;
91
+ let cache: AppConfig | null = null;
74
92
  let cacheMtime = -1;
75
93
 
76
94
  /** 全量归一(文件 5 项 + settings 偏好合并后跑一次,保证形状与类型稳定)。 */
77
- function normalize(data) {
95
+ function normalize(data: unknown): AppConfig {
78
96
  const base = EMPTY();
79
97
  if (!data || typeof data !== 'object') return base;
98
+ const d = data as Record<string, unknown>;
80
99
  return {
81
- baseUrl: String(data.baseUrl || base.baseUrl),
82
- token: String(data.token || ''),
83
- email: String(data.email || ''),
84
- userId: Number(data.userId) || 0,
85
- groupId: Number(data.groupId) || 0,
86
- autoSyncAttachments: data.autoSyncAttachments === true,
87
- attachmentsDir: String(data.attachmentsDir || ''),
88
- gitRepoRoot: String(data.gitRepoRoot || ''),
89
- gitDevRoot: String(data.gitDevRoot || ''),
100
+ baseUrl: String(d.baseUrl || base.baseUrl),
101
+ token: String(d.token || ''),
102
+ email: String(d.email || ''),
103
+ userId: Number(d.userId) || 0,
104
+ groupId: Number(d.groupId) || 0,
105
+ autoSyncAttachments: d.autoSyncAttachments === true,
106
+ attachmentsDir: String(d.attachmentsDir || ''),
107
+ gitRepoRoot: String(d.gitRepoRoot || ''),
108
+ gitDevRoot: String(d.gitDevRoot || ''),
90
109
  };
91
110
  }
92
111
 
93
112
  /** 从 settings 表读偏好(每次现读 —— 不缓存,跨进程改设置立刻可见)。 */
94
- function readPrefs() {
113
+ function readPrefs(): Record<string, unknown> {
95
114
  const db = openStore();
96
- const prefs = {};
115
+ const prefs: Record<string, unknown> = {};
97
116
  for (const key of APP_SETTING_KEYS) {
98
117
  const v = readSettingRaw(db, key);
99
118
  if (v !== undefined) prefs[key.slice('app.'.length)] = v;
@@ -102,7 +121,7 @@ function readPrefs() {
102
121
  }
103
122
 
104
123
  /** 把偏好写进 settings 表(一个事务;只写白名单里的字段)。 */
105
- function writePrefs(next) {
124
+ function writePrefs(next: AppConfig): void {
106
125
  const at = nowMs();
107
126
  tx(
108
127
  (conn) => {
@@ -111,13 +130,13 @@ function writePrefs(next) {
111
130
  writeSettingRaw(conn, 'app.' + k, next[k], at);
112
131
  }
113
132
  },
114
- { db: openStore(), mode: 'IMMEDIATE' }
133
+ { db: openStore(), mode: 'IMMEDIATE' },
115
134
  );
116
135
  }
117
136
 
118
- export async function loadConfig(explicitPath) {
137
+ export async function loadConfig(explicitPath?: string): Promise<AppConfig> {
119
138
  const p = explicitPath || configPathFromEnv();
120
- let filePart;
139
+ let filePart: AppConfig;
121
140
  try {
122
141
  const st = await fsp.stat(p);
123
142
  if (!(cache && cacheMtime === st.mtimeMs)) {
@@ -135,11 +154,11 @@ export async function loadConfig(explicitPath) {
135
154
  return normalize({ ...filePart, ...readPrefs() });
136
155
  }
137
156
 
138
- export async function saveConfig(next, explicitPath) {
157
+ export async function saveConfig(next: unknown, explicitPath?: string): Promise<AppConfig> {
139
158
  const full = normalize(next);
140
159
  // ① 文件:只写凭据白名单里的字段(**键集合精确等于 CREDENTIAL_KEYS** ——
141
160
  // 偏好进了 settings,再写回文件会让「凭据文件」再次长出业务配置)。
142
- const filePart = {};
161
+ const filePart: Record<string, unknown> = {};
143
162
  for (const k of CREDENTIAL_KEYS) filePart[k] = full[k];
144
163
  const p = explicitPath || configPathFromEnv();
145
164
  await fsp.mkdir(dirname(p), { recursive: true });
@@ -157,14 +176,14 @@ export async function saveConfig(next, explicitPath) {
157
176
  return full;
158
177
  }
159
178
 
160
- export async function updateConfig(patch) {
179
+ export async function updateConfig(patch: Partial<AppConfig>): Promise<AppConfig> {
161
180
  const cur = await loadConfig();
162
181
  return saveConfig({ ...cur, ...patch });
163
182
  }
164
183
 
165
184
  // 读配置并要求已登录。所有需要 token 的 action 都先过这里,
166
185
  // 报错文案里的「未登录」是 agent 的失败分类锚点(与 kvcli 保持一致)。
167
- export async function requireAuth() {
186
+ export async function requireAuth(): Promise<AppConfig> {
168
187
  const cfg = await loadConfig();
169
188
  if (!cfg.token) {
170
189
  throw badInput('未登录(先执行 nx-kv auth login <email>)');
@@ -173,7 +192,7 @@ export async function requireAuth() {
173
192
  }
174
193
 
175
194
  // groupId 归一:0 / 负数 / 空 → undefined(不传参,由后端回落默认组)
176
- export function normalizeGroupId(v) {
195
+ export function normalizeGroupId(v: unknown): number | undefined {
177
196
  const n = Number(v);
178
197
  return Number.isFinite(n) && n > 0 ? n : undefined;
179
198
  }
@@ -186,7 +205,7 @@ export function normalizeGroupId(v) {
186
205
  * file 拿它选后端分组与本地附件目录。两处各写一遍的话,一旦有人只改了一处,
187
206
  * 就会出现「从 A 组读任务、往 B 组同步附件」—— 这类错不报错,只是静默地对不上。
188
207
  */
189
- export async function resolveGroupId(groupId) {
208
+ export async function resolveGroupId(groupId: unknown): Promise<number | undefined> {
190
209
  if (groupId !== undefined && groupId !== null && groupId !== '') return normalizeGroupId(groupId);
191
210
  const cfg = await loadConfig();
192
211
  return normalizeGroupId(cfg.groupId);
@@ -17,3 +17,7 @@ process.on('warning', (w) => {
17
17
  const message = (w && w.message) || String(w);
18
18
  console.error(`${name}: ${message}`);
19
19
  });
20
+
21
+ // 让本文件成为 ES 模块(tsconfig 的 isolatedModules 要求每个文件都是模块;
22
+ // 副作用模块的标准写法——不导出任何值)。
23
+ export {};
@@ -26,10 +26,13 @@ export const CODES = {
26
26
  // 单独一个码的理由:迁移失败是"数据没进来、库已回滚"的可恢复状态,
27
27
  // 脚本要能把它与"参数错"区分开(迁移脚本会据此决定是重试还是报人)。
28
28
  STORE_MIGRATION_FAILED: 'STORE_MIGRATION_FAILED',
29
- };
29
+ } as const;
30
+
31
+ export type ErrorCode = (typeof CODES)[keyof typeof CODES];
30
32
 
31
- // code -> HTTP 状态。只在这里映射一次,api.js 不再自行判断。
32
- const HTTP_STATUS = {
33
+ // code -> HTTP 状态。只在这里映射一次,api.ts 不再自行判断。
34
+ // Record 穷尽性:新增错误码漏映射,编译期立即报错。
35
+ const HTTP_STATUS: Record<ErrorCode, number> = {
33
36
  [CODES.INVALID_INPUT]: 400,
34
37
  [CODES.NOT_FOUND]: 404,
35
38
  [CODES.CONFLICT]: 409,
@@ -41,7 +44,7 @@ const HTTP_STATUS = {
41
44
 
42
45
  // code -> 进程退出码。CLI 只区分「成功 / 失败」,保持 agent-workflow.md 声明的契约。
43
46
  // 例外:迁移失败 → 2(见上面的 CODES 注释)。
44
- const EXIT_CODE = {
47
+ const EXIT_CODE: Record<ErrorCode, number> = {
45
48
  [CODES.INVALID_INPUT]: 1,
46
49
  [CODES.NOT_FOUND]: 1,
47
50
  [CODES.CONFLICT]: 1,
@@ -51,38 +54,52 @@ const EXIT_CODE = {
51
54
  [CODES.STORE_MIGRATION_FAILED]: 2,
52
55
  };
53
56
 
57
+ export interface ErrorPayload {
58
+ code: ErrorCode;
59
+ message: string;
60
+ details?: unknown;
61
+ }
62
+
54
63
  export class AppError extends Error {
55
- constructor(code, message, details) {
64
+ code: ErrorCode;
65
+ details?: unknown;
66
+
67
+ constructor(code: ErrorCode, message: string, details?: unknown) {
56
68
  super(message);
57
69
  this.name = 'AppError';
58
- this.code = CODES[code] ? code : CODES.INTERNAL;
70
+ this.code = CODES[code as ErrorCode] ? (code as ErrorCode) : CODES.INTERNAL;
59
71
  if (details !== undefined) this.details = details;
60
72
  }
61
73
  }
62
74
 
63
- export function httpStatusOf(code) {
64
- return HTTP_STATUS[code] || 500;
75
+ export function httpStatusOf(code: ErrorCode): number {
76
+ return HTTP_STATUS[code] ?? 500;
65
77
  }
66
78
 
67
- export function exitCodeOf(code) {
68
- return EXIT_CODE[code] || 1;
79
+ export function exitCodeOf(code: ErrorCode): number {
80
+ return EXIT_CODE[code] ?? 1;
69
81
  }
70
82
 
71
83
  // 把任意抛出物归一成 { code, message, details },供 API / CLI 统一序列化。
72
84
  // 非 AppError 一律归为 INTERNAL——不把内部堆栈细节泄漏给 agent。
73
- export function toErrorPayload(err) {
85
+ export function toErrorPayload(err: unknown): ErrorPayload {
74
86
  if (err instanceof AppError) {
75
- const out = { code: err.code, message: err.message };
87
+ const out: ErrorPayload = { code: err.code, message: err.message };
76
88
  if (err.details !== undefined) out.details = err.details;
77
89
  return out;
78
90
  }
79
- return { code: CODES.INTERNAL, message: String((err && err.message) || err) };
91
+ return { code: CODES.INTERNAL, message: String((err as { message?: string } | null)?.message || err) };
80
92
  }
81
93
 
82
94
  // ---- 构造快捷方式:让 service 层读起来是「为什么失败」而不是「怎么构造」 ----
83
95
 
84
- export const badInput = (message, details) => new AppError(CODES.INVALID_INPUT, message, details);
85
- export const notFound = (message, details) => new AppError(CODES.NOT_FOUND, message, details);
86
- export const conflict = (message, details) => new AppError(CODES.CONFLICT, message, details);
87
- export const blocked = (message, details) => new AppError(CODES.BLOCKED, message, details);
88
- export const external = (message, details) => new AppError(CODES.EXTERNAL, message, details);
96
+ export const badInput = (message: string, details?: unknown): AppError =>
97
+ new AppError(CODES.INVALID_INPUT, message, details);
98
+ export const notFound = (message: string, details?: unknown): AppError =>
99
+ new AppError(CODES.NOT_FOUND, message, details);
100
+ export const conflict = (message: string, details?: unknown): AppError =>
101
+ new AppError(CODES.CONFLICT, message, details);
102
+ export const blocked = (message: string, details?: unknown): AppError =>
103
+ new AppError(CODES.BLOCKED, message, details);
104
+ export const external = (message: string, details?: unknown): AppError =>
105
+ new AppError(CODES.EXTERNAL, message, details);
@@ -2,7 +2,7 @@
2
2
  // 零业务语义,且刻意不抛错——打不开就算了,调用方已经打印了地址。
3
3
  import { spawn } from 'node:child_process';
4
4
 
5
- function open(target) {
5
+ function open(target: string): void {
6
6
  try {
7
7
  const plat = process.platform;
8
8
  if (plat === 'win32') {
@@ -17,10 +17,10 @@ function open(target) {
17
17
  }
18
18
  }
19
19
 
20
- export function openBrowser(url) {
20
+ export function openBrowser(url: string): void {
21
21
  open(url);
22
22
  }
23
23
 
24
- export function openPath(dir) {
24
+ export function openPath(dir: string): void {
25
25
  open(dir);
26
26
  }