nx-kv 0.33.0 → 0.34.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 (113) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/package.json +1 -1
  3. package/src/core/db/migrations/index.js +2 -0
  4. package/src/core/db/migrations/v3.sql +20 -0
  5. package/src/core/db/version.js +4 -1
  6. package/src/modules/localtask/task-ops.js +9 -0
  7. package/src/modules/localtask/task-view.js +4 -0
  8. package/src/modules/templates/index.js +65 -9
  9. package/src/modules/templates/repo/templates.js +24 -2
  10. package/src/modules/templates/scope.js +107 -0
  11. package/src/modules/templates/service.js +83 -4
  12. package/src/runtime/spec.js +6 -1
  13. package/src/web/frontend/App.jsx +34 -2
  14. package/src/web/frontend/components/button/index.jsx +34 -7
  15. package/src/web/frontend/components/button/style.css +1 -1
  16. package/src/web/frontend/components/doc/doc-head.jsx +164 -48
  17. package/src/web/frontend/components/layout/crumbs.js +4 -1
  18. package/src/web/frontend/components/md/attach-area.jsx +20 -11
  19. package/src/web/frontend/components/md/attach-modal.jsx +3 -2
  20. package/src/web/frontend/components/md/attach-picker.jsx +37 -7
  21. package/src/web/frontend/components/md/md-panes.jsx +102 -23
  22. package/src/web/frontend/components/md/sel-menu.jsx +11 -0
  23. package/src/web/frontend/components/md/tool-bar.jsx +151 -94
  24. package/src/web/frontend/components/sidebar/task-children.jsx +6 -20
  25. package/src/web/frontend/components/status-tag/index.jsx +30 -0
  26. package/src/web/frontend/components/status-tag/model.js +53 -0
  27. package/src/web/frontend/components/tool-acts/bar.jsx +156 -0
  28. package/src/web/frontend/components/tool-acts/dnd.js +59 -0
  29. package/src/web/frontend/components/tool-acts/layout-panel.jsx +289 -0
  30. package/src/web/frontend/components/tool-acts/modules.js +162 -0
  31. package/src/web/frontend/components/tool-acts/style.css +108 -0
  32. package/src/web/frontend/components/tool-acts/use-layout.js +27 -0
  33. package/src/web/frontend/modules/md/attach-mention.js +11 -0
  34. package/src/web/frontend/modules/md/md-edit-ops.js +10 -7
  35. package/src/web/frontend/modules/md/md-parse.js +8 -21
  36. package/src/web/frontend/modules/md/progress-search.js +96 -0
  37. package/src/web/frontend/modules/md/style.css +52 -19
  38. package/src/web/frontend/modules/md/use-templates.js +65 -2
  39. package/src/web/frontend/page/dir/index.jsx +51 -38
  40. package/src/web/frontend/page/dir/landing.jsx +50 -70
  41. package/src/web/frontend/page/dir/task.jsx +45 -10
  42. package/src/web/frontend/page/group/index.jsx +194 -88
  43. package/src/web/frontend/page/overview/index.jsx +168 -269
  44. package/src/web/frontend/page/progress/index.jsx +59 -9
  45. package/src/web/frontend/page/repos/index.jsx +95 -103
  46. package/src/web/frontend/page/settings/index.jsx +4 -3
  47. package/src/web/frontend/page/settings/style.css +59 -31
  48. package/src/web/frontend/page/settings/task-templates-section.jsx +94 -99
  49. package/src/web/frontend/page/templates/index.jsx +221 -203
  50. package/src/web/frontend/page/templates/scope-chips.jsx +211 -0
  51. package/src/web/frontend/panels.jsx +28 -4
  52. package/src/web/frontend/route-map.js +42 -2
  53. package/src/web/frontend/style-v2.css +33 -77
  54. package/src/web/frontend/style.css +127 -319
  55. package/src/web/frontend/workspace/areas.js +1 -1
  56. package/src/web/public/assets/Introduction-DU27b_b_.js +1 -0
  57. package/src/web/public/assets/bar-CNuQf706.js +1 -0
  58. package/src/web/public/assets/board-view-t8CKtq17.js +1 -0
  59. package/src/web/public/assets/button-BPYMY-zh.js +1 -0
  60. package/src/web/public/assets/button-DA4lNJeC.css +1 -0
  61. package/src/web/public/assets/cloud-DgNCxJsL.js +3 -0
  62. package/src/web/public/assets/{composer-launch-CfVAwzTt.js → composer-launch-BKeKTPp4.js} +1 -1
  63. package/src/web/public/assets/composer-panel-DP322mVs.js +1 -0
  64. package/src/web/public/assets/dag-C4702bOt.js +1 -0
  65. package/src/web/public/assets/dir-Cipgyv3a.js +5 -0
  66. package/src/web/public/assets/group-m61-WL4C.js +1 -0
  67. package/src/web/public/assets/index-BEkITE6q.css +1 -0
  68. package/src/web/public/assets/index-CeIJd4ee.js +30 -0
  69. package/src/web/public/assets/md-history-Uo6U7hYS.js +1 -0
  70. package/src/web/public/assets/md-panes-PS7K93Lg.js +28 -0
  71. package/src/web/public/assets/md-parse-DN9INgZn.js +25 -0
  72. package/src/web/public/assets/member-picker--32VkTmv.js +1 -0
  73. package/src/web/public/assets/overview-BmoTQJuu.js +1 -0
  74. package/src/web/public/assets/progress-CWy9bYKr.js +3 -0
  75. package/src/web/public/assets/refs-DAy1kYGf.js +1 -0
  76. package/src/web/public/assets/repos-D_NT51Dq.js +9 -0
  77. package/src/web/public/assets/route-crumb-lOriqwxP.js +1 -0
  78. package/src/web/public/assets/settings-CBrQ3Iz5.css +1 -0
  79. package/src/web/public/assets/settings-Vp3ZMC1M.js +7 -0
  80. package/src/web/public/assets/status-tag-DGlwjAg2.js +1 -0
  81. package/src/web/public/assets/task-CRpctHxx.js +9 -0
  82. package/src/web/public/assets/task-status-BP6y8MVu.js +1 -0
  83. package/src/web/public/assets/templates-D900RS5b.js +1 -0
  84. package/src/web/public/assets/tool-bar-1h2zairf.css +1 -0
  85. package/src/web/public/assets/tool-bar-C-rnP0vv.js +1 -0
  86. package/src/web/public/assets/upload-L1g-pfvZ.js +1 -0
  87. package/src/web/public/index.html +6 -5
  88. package/src/web/public/assets/Introduction-C5sQqMIg.js +0 -1
  89. package/src/web/public/assets/attach-evLB-_o-.js +0 -1
  90. package/src/web/public/assets/cloud-B_LvtXsR.js +0 -3
  91. package/src/web/public/assets/composer-panel-DIbBPnrY.js +0 -1
  92. package/src/web/public/assets/dag-B9ujKuhg.js +0 -1
  93. package/src/web/public/assets/dir-us1qOb74.js +0 -5
  94. package/src/web/public/assets/group-BV9RUHL2.js +0 -1
  95. package/src/web/public/assets/index-B3bvje4X.css +0 -1
  96. package/src/web/public/assets/index-Dw5qvd3H.js +0 -54
  97. package/src/web/public/assets/md-edit-ops-ZwnwtEax.js +0 -22
  98. package/src/web/public/assets/md-history-DXAULvOG.js +0 -1
  99. package/src/web/public/assets/md-panes-XVBqxolq.js +0 -7
  100. package/src/web/public/assets/member-picker-caRH-T0U.js +0 -1
  101. package/src/web/public/assets/overview-BuK893nH.js +0 -1
  102. package/src/web/public/assets/progress-CXDMbg9t.js +0 -3
  103. package/src/web/public/assets/refs-CRV9oVjk.js +0 -1
  104. package/src/web/public/assets/repos-B4Kzl-pe.js +0 -9
  105. package/src/web/public/assets/route-crumb-BBKKZ3aI.js +0 -1
  106. package/src/web/public/assets/settings-BaiD0fFN.js +0 -7
  107. package/src/web/public/assets/settings-qCi-niJC.css +0 -1
  108. package/src/web/public/assets/task-CLl1Jg0v.js +0 -7
  109. package/src/web/public/assets/task-status-Bgo2Nfiw.js +0 -1
  110. package/src/web/public/assets/template-editor-D_rc4c19.js +0 -1
  111. package/src/web/public/assets/templates-G3voUFjL.js +0 -2
  112. package/src/web/public/assets/upload-DV28XAi0.js +0 -1
  113. /package/src/web/public/assets/{attach-BZrdOH46.css → task-status-BZrdOH46.css} +0 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,50 @@
2
2
 
3
3
  本文件记录对外可见的变更。格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/)。
4
4
 
5
+ ## [0.34.0] - 2026-11-09 模板可见域 + 全屏编辑 / 工具区编排 / 进程搜索口径
6
+
7
+ ### Added
8
+
9
+ - **模板可见域(#128)**:模板带 scope(全局 `*` / 目录 `topic:` / 项目 `repo:` / 组 `group:`)
10
+ 与创建来源 origin_topic;设置页 scope chips(全局开关 + 定向加删 + 创建于标记);
11
+ 组页 hover 出模板下拉面板——列该 topic 可用的模板、面板右下角新增模板;
12
+ `GET /api/templates?topic=` 按可见域过滤(use ≠ edit:全局/项目/组条目只给用不给改)。
13
+ 存储迁移 v2→v3(`templates` 加 `scope`(默认 `["*"]`)与 `origin_topic`,零破坏)。
14
+ 运行时 flag 新增 `raw` 类型(值本身是数组/对象的透传,修「清空可见域被静默吞掉」)。
15
+ - **模板全屏编辑与工具区编排**:模板改为 settings 卡片 + `#/templates` 路由编辑;
16
+ group/dir/task/doc 工具栏按 nx-ft 支持顺序/显隐编排(隐藏收入「更多」)。
17
+ - **进程面板搜索口径(#129)**:纯数字查询命中编号等值(#12)、编号前缀(12 → #120–#129)
18
+ 与标题逐位通配(12 ≡ 1*2,位序在即可);带 `*` 按段顺序匹配;普通文本标题子串不变。
19
+
20
+ ### Changed
21
+
22
+ - **进程卡右侧显示任务编号 #id(#127)**:原按重开轮次渲染「N楼」的口径纠正为编号本身。
23
+
24
+ ### Fixed
25
+
26
+ - CI lint:group/settings 页两处 eslint 错误(未用解构 / 未定义 openPanel);
27
+ check-tdz 补齐「跳过多行解构参数」——解构模式的属性键(`catalog: catalogProp`)不是引用。
28
+ - 小修:repos 页 chip 选中态黑块改绿(#126);总览收组任务(#125);
29
+ md 实时预览跨块选区统一删除/复制(#124)。
30
+
31
+ ## [0.33.1] - 2026-11-09 skill 文档按 0.33.0 实况校准(仅文档)
32
+
33
+ ### Changed
34
+
35
+ - **客户端 skill(assets/)**:kv-get 重写为「领取 → 读正文 → 取附件 → 完成」流程,
36
+ 补齐 wait 四种出口、任务级 timegoal、`close-many --ids`、reopen 派生新任务;kv-submit
37
+ 修正 `--global` 位置与 `--project/--board`,`delivered/queued` 为布尔;kv-repo / nx-kv
38
+ 校正 `board list` 字段、`repo ref` 命令与 `--matchTopic`。删除与 waitloop / timegoal
39
+ 重复且过期的 wait-workflow、timegoal-workflow。
40
+ - **开发 skill(.claude/skills/dev-nxkv)**:SOP 压缩为一条规则一句;领域模型改为 v2
41
+ 表结构(`attachments` / `task_attach` / `ref_attach`,`refs` 仅收 `.md`);迁移规则改为
42
+ `vN.sql` + `index.js` 边映射;提示词补共享 ctx 与区块模板列表;settings 页与底部
43
+ 状态栏只点结构变化。
44
+ - 命令与返回字段全部按 `help --json` / 临时库实跑校准:`instruction` 非任务正文、
45
+ 附件 `area` 取 `inline|area`、`close-many` 的 `--ids` 必填、`todo list` 返回对象等。
46
+ - 无业务代码、schema 或存储变更;并入 origin/main 尚未发版的改动(#111–#114:
47
+ md 草稿与 @ 面板、撤掉 frontmatter 属性卡、总览扁平清单、仓库页按钮规范)。
48
+
5
49
  ## [0.33.0] - 2026-11-08 底部信息面板 / check 日志 / 用户侧收口 / 状态配色
6
50
 
7
51
  ### Added
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nx-kv",
3
- "version": "0.33.0",
3
+ "version": "0.34.0",
4
4
  "description": "nx-kv — KV 清单管理中枢(远程)+ 本机本地任务队列(localtask):serve 驱动 CLI 与 Web 面板,同源同构,附带可安装 skill 供 agent 提交 / 领取 / 阻塞接收任务",
5
5
  "type": "module",
6
6
  "bin": {
@@ -17,12 +17,14 @@ import { CURRENT_SCHEMA_VERSION } from '../version.js';
17
17
  export const DIRECT_EDGES = [
18
18
  { from: 0, to: 1, file: 'v1.sql', title: '初始 schema(topics/tasks/refs/…)' },
19
19
  { from: 1, to: 2, file: 'v2.sql', title: '附件/资源统一模型', apply: migrateAttachments },
20
+ { from: 2, to: 3, file: 'v3.sql', title: '模板可见域(scope/origin_topic)' },
20
21
  ];
21
22
 
22
23
  // 人读版本说明(docs/decisions 是决策的唯一权威位置,里面对应一份 date 化的 .md)
23
24
  export const VERSION_NOTES = {
24
25
  1: 'docs/decisions/versions/2026-11-08-v1.md',
25
26
  2: 'docs/decisions/versions/2026-11-08-v2.md',
27
+ 3: 'docs/decisions/versions/2026-11-09-v3.md',
26
28
  };
27
29
 
28
30
  const keyOf = (from, to) => `${from}->${to}`;
@@ -0,0 +1,20 @@
1
+ -- schema v3:任务模板的可见域(scope)与创建来源(origin_topic)
2
+ --
3
+ -- 设计口径(2026-11-09,任务 #128,评估见 plan/2026-11-09-template-architecture-eval.md §2):
4
+ -- · 模板从「全机共享」升级为「带可见域」:scope 是 JSON 数组,条目三种前缀——
5
+ -- "*" 全局可见(缺省,行为与 v2 完全一致)
6
+ -- "topic:<key>" 指定队列主题可见(topics.key)
7
+ -- "repo:<key>" 指定项目可见(repos.key)
8
+ -- "group:<key>" 指定项目组可见(组也是 repos.key)
9
+ -- 可见判定 = scope 含 "*",或命中主题行的 key / repo_key / group_key 任一。
10
+ -- · origin_topic 记录「在哪个主题里创建的」:从主题页新建模板时默认只在该主题
11
+ -- 可见(scope 默认 [topic:<key>]),origin 是创建事实、不随 scope 改写;
12
+ -- 它同时是「编辑权」的锚(canEdit = origin 命中或 scope 显式点名本主题)。
13
+ --
14
+ -- 两列都带 NOT NULL DEFAULT:存量模板(含内置 seed 的四类目)原地升级为全局
15
+ -- 可见,零破坏——不跑数据回填脚本。
16
+
17
+ -- @decision docs/decisions/versions/2026-11-09-v3.md
18
+ ALTER TABLE templates ADD COLUMN scope TEXT NOT NULL DEFAULT '["*"]'
19
+ CHECK (json_valid(scope) AND json_type(scope) = 'array');
20
+ ALTER TABLE templates ADD COLUMN origin_topic TEXT NOT NULL DEFAULT '';
@@ -8,8 +8,11 @@
8
8
  *
9
9
  * v2(2026-11-08):新增 attachments / task_attach / ref_attach,删除 task_refs /
10
10
  * ref_relations;旧 manifest.json 与正文 fileId 引用在迁移阶段落库。
11
+ *
12
+ * v3(2026-11-09):templates 加 scope(可见域 JSON 数组,默认 '["*"]')与
13
+ * origin_topic(创建来源主题,默认 '')——存量行原地升为全局可见,零破坏。
11
14
  */
12
- export const CURRENT_SCHEMA_VERSION = 2;
15
+ export const CURRENT_SCHEMA_VERSION = 3;
13
16
 
14
17
  /**
15
18
  * 运行时最低 Node 版本。
@@ -79,16 +79,25 @@ export async function addTask({
79
79
  // forkKind 缺省按 comment(评论/随手派生)——reopen 有自己的写入口(task-lifecycle)。
80
80
  let forkOf = null; // 解析结果 { key, seq } —— 插入后写链
81
81
  let forkKind = '';
82
+ // 楼数(#122):schema 语义(v1.sql tasks.round)「派生任务 = 来源任务的 round + 1」。
83
+ // 以前 add --fork-of 不带 round、落盘默认 1——链上第二轮会显示「1楼」,与 reopen
84
+ // 写入口(task-lifecycle:新 round = 父 round + 1)不一致。发布时按父任务算好。
85
+ let forkRound;
82
86
  if (rawForkOf !== undefined && rawForkOf !== null && String(rawForkOf).trim() !== '') {
83
87
  const ref = resolveForkRef(rawForkOf, key);
84
88
  forkOf = { ref };
85
89
  forkKind = rawForkKind === 'reopen' ? 'reopen' : 'comment';
90
+ const at = ref.lastIndexOf(':');
91
+ const parent = topicsRepo.getTopic(ref.slice(0, at));
92
+ const prow = parent && (parent.tasks || []).find((x) => Number(x.id) === Number(ref.slice(at + 1)));
93
+ if (prow) forkRound = (Number(prow.reopenCount) || 0) + 1 + 1; // 父 round(=reopenCount+1) + 1
86
94
  }
87
95
  const taskDraft = {
88
96
  // 不写 id:真实编号由 insertTask 在事务内分配,避免事务外读号撞车
89
97
  text: body,
90
98
  status: 'pending',
91
99
  timegoal,
100
+ round: forkRound,
92
101
  blockBy: normalizeBlockBy(rawBlockBy, provisionalId),
93
102
  blocksFollowing: !!blocksFollowing,
94
103
  forkOf,
@@ -228,6 +228,10 @@ export function normalizeTask(t, siblings, readyOpts = {}) {
228
228
  archivedAt: String(t.archivedAt ?? ''),
229
229
  archivedReason: String(t.archivedReason ?? ''),
230
230
  reopenCount: Number(t.reopenCount) || 0,
231
+ // 链上第几轮(#122 进程面板「楼数」):根任务 = 1,派生 = 来源 + 1(schema 语义
232
+ // 见 v1.sql tasks.round)。库里存的是 round 列,JSON 形态只带 reopenCount = round-1
233
+ // (repo/rows.js),这里换算回来 —— 前端显示「第 N 楼」/按楼搜索不必再回溯链。
234
+ round: Math.max(1, (Number(t.reopenCount) || 0) + 1),
231
235
  // DAG / 闸门(#34):blockBy=依赖 id;blocksFollowing=挡住数组其后所有 pending
232
236
  blockBy,
233
237
  blocksFollowing,
@@ -7,12 +7,17 @@
7
7
  // 直接改默认),不凑 CRUD 五件的数,免得为了凑数造出没人用的命令。
8
8
  import * as service from './service.js';
9
9
  import { badInput } from '../../core/errors.js';
10
+ import { topicKeyOf } from '../../core/topic-key.js';
11
+ import { resolve as resolvePath } from 'node:path';
10
12
 
11
13
  const renderList = (d) => {
12
14
  const lines = [`模板 ${d.templates.length} 个(默认: ${d.defaultId})`];
13
15
  for (const t of d.templates) {
14
16
  const head = String(t.body || '').split('\n').find((l) => l.trim()) || '(空)';
15
- lines.push(` ${t.id === d.defaultId ? '★' : ' '} ${t.id}${t.builtin ? ' [内置]' : ''} ${t.name} · ${head.trim().slice(0, 40)}`);
17
+ const scopeMark = d.scoped
18
+ ? ` · ${t.perm && t.perm.edit ? '本主题可编辑' : '仅可用'}`
19
+ : '';
20
+ lines.push(` ${t.id === d.defaultId ? '★' : ' '} ${t.id}${t.builtin ? ' [内置]' : ''} ${t.name} · ${head.trim().slice(0, 40)}${scopeMark}`);
16
21
  }
17
22
  return lines.join('\n');
18
23
  };
@@ -32,6 +37,24 @@ function parseValues(raw) {
32
37
  }
33
38
  }
34
39
 
40
+ // 可见域:CLI 传 JSON 数组字符串(或逗号分隔短写),HTTP 传数组——归一(含非法
41
+ // 条目校验)在 service 层。cmd.exe 里塞 JSON 引号太痛苦,裸条目按逗号拆。
42
+ function parseScope(raw) {
43
+ if (raw === undefined || raw === null) return undefined;
44
+ if (typeof raw !== 'string') return raw;
45
+ const s = raw.trim();
46
+ if (!s) return undefined;
47
+ if (s.startsWith('[')) return s; // JSON 数组
48
+ return s.split(',').map((x) => x.trim()).filter(Boolean);
49
+ }
50
+
51
+ // --cwd → 创建主题锚(与 localtask 同一派生:完整 cwd 小写折叠、无组上下文)。
52
+ function topicFromCwd(raw) {
53
+ const s = String(raw || '').trim();
54
+ if (!s) return undefined;
55
+ return topicKeyOf(resolvePath(s), '');
56
+ }
57
+
35
58
  export default {
36
59
  id: 'templates',
37
60
  title: '任务模板(MD 工作台新建页的起始正文)',
@@ -44,14 +67,22 @@ export default {
44
67
  cli: ['template', 'list'],
45
68
  http: ['GET', '/api/templates'],
46
69
  summary: '列出任务模板(含默认模板 id;新建页的起始正文按默认模板取)',
47
- run: () => service.listTemplates(),
70
+ flags: {
71
+ topic: { type: 'string', hint: '按队列 topics.key 过滤(可与 --group/--repo 组合;响应带 scoped:true)' },
72
+ group: { type: 'string', hint: '按项目组 repos.key 过滤(#132:组本身是可见主体,与 topic/repo 平级)' },
73
+ repo: { type: 'string', hint: '按项目 repos.key 过滤' },
74
+ },
75
+ run: (ctx) =>
76
+ ctx.topic || ctx.group || ctx.repo
77
+ ? service.listTemplatesForTopic({ topic: ctx.topic, group: ctx.group, repo: ctx.repo })
78
+ : service.listTemplates(),
48
79
  render: renderList,
49
80
  },
50
81
  {
51
82
  id: 'templates.add',
52
83
  cli: ['template', 'add'],
53
84
  http: ['POST', '/api/templates'],
54
- summary: '新增任务模板(--body 给 Markdown 正文;多行正文用 --body-file <文件> 或 --body - 读管道;--setDefault 同时设为默认)',
85
+ summary: '新增任务模板(--body 给 Markdown 正文;多行正文用 --body-file <文件> 或 --body - 读管道;--setDefault 同时设为默认;--scope 设可见域、--topic 记创建主题并默认仅该主题可见)',
55
86
  args: ['name'],
56
87
  flags: {
57
88
  body: { type: 'string', hint: '模板正文(Markdown;首行写 `# 标题` 则提交时作为任务标题)' },
@@ -59,6 +90,9 @@ export default {
59
90
  'body-file': { type: 'string', hint: '同 --bodyFile(连字符写法)' },
60
91
  setDefault: { type: 'boolean', hint: '新增后立即设为默认模板' },
61
92
  'set-default': { type: 'boolean', hint: '同 --setDefault(连字符写法)' },
93
+ scope: { type: 'raw', hint: '可见域(#128/#131):* 全局 / topic:<key> 队列 / repo:<key> 项目 / group:<key> 组——JSON 数组或逗号短写;缺省空(未配置,不默认全局);带 --topic 时默认仅该主题' },
94
+ topic: { type: 'string', hint: '创建主题锚(topics.key):默认仅该主题可见,origin_topic 记它' },
95
+ cwd: { type: 'string', hint: '同 --topic,但给工作目录(按目录派生主题 key)' },
62
96
  },
63
97
  // 读文件/读管道只给 CLI:HTTP 是面板的通道,不该变成「任意读本机文件」的入口
64
98
  run: (ctx, opts) =>
@@ -67,20 +101,28 @@ export default {
67
101
  body: ctx.body,
68
102
  bodyFile: opts && opts.transport === 'http' ? undefined : (ctx.bodyFile ?? ctx['body-file']),
69
103
  setDefault: ctx.setDefault ?? ctx['set-default'],
104
+ scope: parseScope(ctx.scope),
105
+ topic: ctx.topic || topicFromCwd(ctx.cwd),
70
106
  }),
71
- render: (d) => `已新增模板「${d.template.name}」(${d.template.id})${d.defaultId === d.template.id ? ',并设为默认' : ''}`,
107
+ render: (d) =>
108
+ `已新增模板「${d.template.name}」(${d.template.id})${d.defaultId === d.template.id ? ',并设为默认' : ''}${
109
+ Array.isArray(d.template.scope) && !d.template.scope.includes('*')
110
+ ? `,可见域 ${JSON.stringify(d.template.scope)}`
111
+ : ''
112
+ }`,
72
113
  },
73
114
  {
74
115
  id: 'templates.update',
75
116
  cli: ['template', 'update'],
76
117
  http: ['PATCH', '/api/templates/:id'],
77
- summary: '编辑任务模板(--name 改名 / --body 改正文,只改传入项;多行正文用 --body-file;内置模板的正文也可改)',
118
+ summary: '编辑任务模板(--name 改名 / --body 改正文 / --scope 改可见域,只改传入项;多行正文用 --body-file;内置模板的正文也可改)',
78
119
  args: ['id'],
79
120
  flags: {
80
121
  name: { type: 'string', hint: '新名字(不传保持不变)' },
81
122
  body: { type: 'string', hint: '新正文(Markdown;不传保持不变)' },
82
123
  bodyFile: { type: 'string', hint: '从文件读新正文(--body 优先);`-` = 读标准输入' },
83
124
  'body-file': { type: 'string', hint: '同 --bodyFile(连字符写法)' },
125
+ scope: { type: 'raw', hint: '可见域(#128):* / topic:<key> / repo:<key> / group:<key>,JSON 数组或逗号短写(不传保持不变)' },
84
126
  values: {
85
127
  type: 'string',
86
128
  hint: '槽位值 JSON(形如 {"背景":"要做的事"})——老模板正文里的 {{槽位名}} 处填这段文字(新模板直接写正文即可)',
@@ -92,6 +134,7 @@ export default {
92
134
  name: ctx.name,
93
135
  body: ctx.body,
94
136
  bodyFile: opts && opts.transport === 'http' ? undefined : (ctx.bodyFile ?? ctx['body-file']),
137
+ scope: parseScope(ctx.scope),
95
138
  values: parseValues(ctx.values),
96
139
  }),
97
140
  render: (d) => `已更新模板「${d.template.name}」(${d.template.id})`,
@@ -111,18 +154,31 @@ export default {
111
154
  http: ['PATCH', '/api/templates/default'],
112
155
  // 这条路由同时管两件事——**字面量路由优先于 :id**(runtime/api.js 的路由排序:
113
156
  // 字面量段在前),所以 id 恰是 'default' 的模板,正文更新会被这条路由截走:
114
- // 带 name/body/values → 改**默认模板本身**(id 就是 default)
115
- // 只带 id → 把默认模板换成它
157
+ // 带 name/body/values/scope → 改**默认模板本身**(id 就是 default)
158
+ // 只带 id → 把默认模板换成它
116
159
  // 不分派的话,「默认模板」永远存不进去(面板里改默认模板 400,2026-11-07 任务 #87 实锤)。
117
- summary: '设置默认模板(新建页的起始正文换成它);带 --body/--name 则改默认模板本身',
160
+ summary: '设置默认模板(新建页的起始正文换成它);带 --body/--name/--scope 则改默认模板本身',
118
161
  args: ['id'],
162
+ // flag 声明补齐(之前一个都没声明):CLI 的 --body/--name/--scope 会撞
163
+ // 「未知参数」;声明之后 CLI 能传,HTTP 的 body 字段也照常落在 ctx 上。
164
+ // values/scope 用 raw:值本身是对象/数组,不能被 String() 压掉。
165
+ flags: {
166
+ name: { type: 'string', hint: '新名字(配合 --body/--scope 时改默认模板本身)' },
167
+ body: { type: 'string', hint: '新正文(配合时改默认模板本身)' },
168
+ values: { type: 'raw', hint: '槽位值 JSON(CLI 传 JSON 串;HTTP 可直接给对象)' },
169
+ scope: { type: 'raw', hint: '可见域(#128):* / topic:<key> / repo:<key> / group:<key>,JSON 数组或逗号短写' },
170
+ },
119
171
  run: (ctx) => {
120
- if (ctx.body !== undefined || ctx.name !== undefined || ctx.values !== undefined) {
172
+ if (
173
+ ctx.body !== undefined || ctx.name !== undefined ||
174
+ ctx.values !== undefined || ctx.scope !== undefined
175
+ ) {
121
176
  return service.updateTemplate({
122
177
  id: ctx.id || 'default',
123
178
  name: ctx.name,
124
179
  body: ctx.body,
125
180
  values: parseValues(ctx.values),
181
+ scope: parseScope(ctx.scope),
126
182
  });
127
183
  }
128
184
  return service.setDefaultTemplate({ id: ctx.id });
@@ -47,9 +47,9 @@ export function insertIfAbsent(conn, row) {
47
47
  conn.run(
48
48
  `INSERT INTO templates (id, category, name, slot, body, vars_schema, vars, is_default,
49
49
  enabled, sort_order, builtin, state, version, deleted_at,
50
- created_at, updated_at)
50
+ created_at, updated_at, scope, origin_topic)
51
51
  VALUES (:id, :category, :name, :slot, :body, :schema, :vars, :isDefault,
52
- :enabled, :sort, :builtin, '', 0, NULL, :created, :updated)
52
+ :enabled, :sort, :builtin, '', 0, NULL, :created, :updated, :scope, :originTopic)
53
53
  ON CONFLICT(id) DO NOTHING`,
54
54
  {
55
55
  id: row.id,
@@ -65,6 +65,9 @@ export function insertIfAbsent(conn, row) {
65
65
  builtin: row.builtin ? 1 : 0,
66
66
  created: row.createdAtMs,
67
67
  updated: row.updatedAtMs,
68
+ // 可见域(v3):数组归一在 service 层做完,这里只管落库形状
69
+ scope: rowJson(row.scope, '["*"]'),
70
+ originTopic: String(row.originTopic || ''),
68
71
  }
69
72
  );
70
73
  }
@@ -89,6 +92,11 @@ export function updateRow(conn, id, patch, atMs) {
89
92
  sets.push('enabled = :enabled');
90
93
  params.enabled = patch.enabled ? 1 : 0;
91
94
  }
95
+ if (patch.scope !== undefined) {
96
+ sets.push('scope = :scope');
97
+ params.scope = rowJson(patch.scope, '["*"]');
98
+ }
99
+ // origin_topic 不进 updateRow:它是创建事实(v3 裁决),不随编辑改写
92
100
  if (!sets.length) return !!getRow(id, conn);
93
101
  sets.push('updated_at = :at');
94
102
  const r = conn.run(`UPDATE templates SET ${sets.join(', ')} WHERE id = :id AND deleted_at IS NULL`, params);
@@ -129,5 +137,19 @@ export function nextSortOrder(conn, category) {
129
137
  return Number((row && row.m) || -1) + 1;
130
138
  }
131
139
 
140
+ /**
141
+ * 主题的三把钥匙(key / repo_key / group_key)——scope 判定只认这三列。
142
+ * 查无此主题返回 null(service 层降级为「只按裸 key 命中 + 全局」)。
143
+ * topics 是共享存储,这里只读三列,不复制 localtask 的仓储逻辑。
144
+ */
145
+ export function getTopicKeys(key, conn = db()) {
146
+ return (
147
+ conn.get(
148
+ 'SELECT key, repo_key, group_key FROM topics WHERE key = :key AND deleted_at IS NULL',
149
+ { key: String(key || '') }
150
+ ) || null
151
+ );
152
+ }
153
+
132
154
  /** 事务入口的窄转发。 */
133
155
  export { txw };
@@ -0,0 +1,107 @@
1
+ // 模板可见域(scope)纯解析:无 DB、无 IO,service 与前端可共享同一套判定。
2
+ //
3
+ // 评估与裁决见 plan/2026-11-09-template-architecture-eval.md §2(任务 #123/#128):
4
+ // 不做 policy 引擎,一条可见性规则 + 一条编辑权规则,全是纯函数。
5
+ //
6
+ // scope 条目词表(写库前经 normalizeScope 归一,非法条目进不来):
7
+ // "*" 全局可见
8
+ // "topic:<key>" 指定队列主题(topics.key,含全局池 __GLOBAL__)
9
+ // "repo:<key>" 指定项目(repos.key)
10
+ // "group:<key>" 指定项目组(组也是 repos.key,type='group')
11
+ //
12
+ // 判定口径:
13
+ // 可见(use) = scope 含 "*",或命中主题行三把钥匙(key / repoKey / groupKey)之一;
14
+ // 可编辑(edit)= origin_topic 命中本主题,或 scope 显式点名本主题——比 use 严:
15
+ // "*" 只给「能用」,不给「能改」;repo/group 域同样不给改
16
+ // (改模板是全机影响,只有创建处与显式点名处可以动)。
17
+ import { badInput } from '../../core/errors.js';
18
+
19
+ export const GLOBAL_SCOPE = '*';
20
+ const KINDS = ['topic', 'repo', 'group'];
21
+ const SCOPE_MAX_ENTRIES = 32;
22
+ const KEY_MAX_LEN = 200;
23
+
24
+ /** 单条 scope 条目是否合法("*" 或 <kind>:<非空无空白 key>)。 */
25
+ export function isScopeEntry(s) {
26
+ const v = String(s ?? '');
27
+ if (v === GLOBAL_SCOPE) return true;
28
+ const i = v.indexOf(':');
29
+ if (i <= 0) return false;
30
+ const kind = v.slice(0, i);
31
+ const key = v.slice(i + 1);
32
+ return KINDS.includes(kind) && !!key && key.length <= KEY_MAX_LEN && !/\s/.test(key);
33
+ }
34
+
35
+ /**
36
+ * 归一化 scope:收数组(或 JSON 串),去重保序、丢弃非法条目、限 32 条。
37
+ * strict=true(CLI/HTTP 写入路径)时遇到非法条目直接报错——静默丢弃会让
38
+ * 「我以为设了域其实没设上」;读取路径(DB 行反解)用宽松档兜脏数据。
39
+ */
40
+ export function normalizeScope(raw, { strict = false } = {}) {
41
+ let arr = raw;
42
+ if (typeof arr === 'string') {
43
+ const s = arr.trim();
44
+ if (!s) return [];
45
+ try {
46
+ arr = JSON.parse(s);
47
+ } catch (e) {
48
+ if (strict) throw badInput(`--scope 要传 JSON 数组(形如 ["*"] 或 ["topic:<key>"]):${e.message || e}`);
49
+ return [];
50
+ }
51
+ }
52
+ if (arr == null) return strict ? [] : [];
53
+ if (!Array.isArray(arr)) {
54
+ if (strict) throw badInput('--scope 要传 JSON 数组(形如 ["*"] 或 ["topic:<key>"])');
55
+ return [];
56
+ }
57
+ const out = [];
58
+ for (const item of arr) {
59
+ const v = String(item ?? '').trim();
60
+ if (!isScopeEntry(v)) {
61
+ if (strict) {
62
+ throw badInput(
63
+ `--scope 里有不认识的条目「${v}」——合法写法:* / topic:<key> / repo:<key> / group:<key>`
64
+ );
65
+ }
66
+ continue;
67
+ }
68
+ if (!out.includes(v)) out.push(v);
69
+ if (out.length >= SCOPE_MAX_ENTRIES) break;
70
+ }
71
+ return out;
72
+ }
73
+
74
+ /** 主题判定上下文:三把钥匙(topics 行的 camelCase 影子)。 */
75
+ export function topicCtx({ key = '', repoKey = '', groupKey = '' } = {}) {
76
+ return { key: String(key || ''), repoKey: String(repoKey || ''), groupKey: String(groupKey || '') };
77
+ }
78
+
79
+ /** 条目是否命中主题上下文("*" 不在此判——它是可见性的全局短路,见 canUse)。 */
80
+ function entryHits(entry, ctx) {
81
+ const i = entry.indexOf(':');
82
+ const kind = entry.slice(0, i);
83
+ const key = entry.slice(i + 1);
84
+ if (kind === 'topic') return key === ctx.key;
85
+ if (kind === 'repo') return key === ctx.repoKey;
86
+ if (kind === 'group') return key === ctx.groupKey;
87
+ return false;
88
+ }
89
+
90
+ /** 该模板对主题 ctx 是否可用(菜单里出不出来)。 */
91
+ export function canUse(t, ctx) {
92
+ const scope = Array.isArray(t && t.scope) ? t.scope : [];
93
+ if (scope.includes(GLOBAL_SCOPE)) return true;
94
+ return scope.some((s) => isScopeEntry(s) && entryHits(s, ctx));
95
+ }
96
+
97
+ /** 该模板在主题 ctx 是否可编辑(origin 命中或 scope 显式点名;比 use 严)。 */
98
+ export function canEdit(t, ctx) {
99
+ if (t && t.originTopic && t.originTopic === ctx.key) return true;
100
+ const scope = Array.isArray(t && t.scope) ? t.scope : [];
101
+ return scope.includes(`topic:${ctx.key}`);
102
+ }
103
+
104
+ /** 一列模板按可见域过滤(保持原顺序)。 */
105
+ export function visibleTemplates(list, ctx) {
106
+ return (list || []).filter((t) => canUse(t, ctx));
107
+ }
@@ -24,12 +24,15 @@
24
24
  // — → category 固定 'newtask'(本文件只管新建页骨架;
25
25
  // delivery/enhance/context 三个 tab 的内置模板由
26
26
  // seed 提供,编辑走同一张表)
27
+ // — → scope(v3,#128):可见域 JSON 数组,缺省 ["*"];
28
+ // origin_topic 记创建主题。判定规则在 scope.js(纯函数)
27
29
  import crypto from 'node:crypto';
28
30
  import fsp from 'node:fs/promises'; // 仅用于读用户 --body-file(存储已进库)
29
31
  import { readFileSync } from 'node:fs';
30
32
  import { badInput, notFound } from '../../core/errors.js';
31
33
  import { nowMs } from '../../core/db/time.js';
32
34
  import { NEWTASK_BODY, NEWTASK_VARS } from '../../core/db/seed-templates.js';
35
+ import { normalizeScope, topicCtx, canUse, canEdit } from './scope.js';
33
36
  import repoLayer from './repo/index.js';
34
37
 
35
38
  export const BUILTIN_ID = 'default';
@@ -51,6 +54,10 @@ function rowToView(row) {
51
54
  body: String(row.body || ''),
52
55
  values: vars,
53
56
  builtin: !!row.builtin,
57
+ // 可见域(v3,#128):scope 数组 + 创建来源主题。全为 '*' / '' 时消费方
58
+ // 可以当它不存在(与 v2 行为一致),带值的才需要展示/判定。
59
+ scope: normalizeScope(row.scope),
60
+ originTopic: String(row.origin_topic || ''),
54
61
  };
55
62
  if (row.category && row.category !== NEWTASK_CATEGORY) out.category = String(row.category);
56
63
  if (row.enabled === 0) out.enabled = false;
@@ -83,6 +90,54 @@ export async function listTemplates() {
83
90
  });
84
91
  }
85
92
 
93
+ /**
94
+ * 按可见上下文列可用模板(v3,#128 / #132):
95
+ * GET /api/templates?topic=&group=&repo=
96
+ *
97
+ * 三把钥匙平级(#132):topic / repo / group 与 `*` 都是 scope 绑定条目,
98
+ * 不是「全局 vs 定向」。组页可只传 group(项目组本身就是一个可见主体)。
99
+ *
100
+ * 返回 `scoped: true` 让前端识别「服务端确实按域过滤了」——旧 serve 不认识
101
+ * 这些参数时无 scoped 字段,前端退化回全量菜单。
102
+ */
103
+ export async function listTemplatesForTopic({
104
+ topic: rawTopic,
105
+ group: rawGroup,
106
+ repo: rawRepo,
107
+ } = {}) {
108
+ const key = String(rawTopic || '').trim();
109
+ const groupKey = String(rawGroup || '').trim();
110
+ const repoKey = String(rawRepo || '').trim();
111
+ if (!key && !groupKey && !repoKey) return { ...(await listTemplates()), scoped: false };
112
+ return repo.txw((conn) => {
113
+ const row = key ? repo.templates.getTopicKeys(key, conn) : null;
114
+ const ctx = topicCtx({
115
+ key: (row && row.key) || key,
116
+ // 显式 query 优先:组页会带 group/repo,即使成员队列行上 group_key 为空
117
+ repoKey: repoKey || (row && row.repo_key) || '',
118
+ groupKey: groupKey || (row && row.group_key) || '',
119
+ });
120
+ const defaultId = defaultIdOf(conn);
121
+ const templates = repo.templates
122
+ .listRows(conn)
123
+ .filter((r) => r.category === NEWTASK_CATEGORY)
124
+ .map((r) => {
125
+ const v = rowToView(r);
126
+ v.perm = { use: canUse(v, ctx), edit: canEdit(v, ctx) };
127
+ return v;
128
+ })
129
+ .filter((v) => v.perm.use);
130
+ return {
131
+ defaultId,
132
+ templates,
133
+ scoped: true,
134
+ topic: key || undefined,
135
+ group: groupKey || undefined,
136
+ repo: repoKey || undefined,
137
+ };
138
+ });
139
+ }
140
+
86
141
  function normalizeName(raw) {
87
142
  const name = String(raw || '').trim();
88
143
  if (!name) throw badInput('需要模板名 <name>');
@@ -140,10 +195,30 @@ async function resolveBody({ body, bodyFile } = {}) {
140
195
  }
141
196
  }
142
197
 
143
- /** 新增模板(--set-default 同时设为默认)。幂等性不做:同名允许存在,靠 id 区分。 */
144
- export async function addTemplate({ name: rawName, body: rawBody, bodyFile, values, setDefault = false } = {}) {
198
+ /**
199
+ * 新增模板(--set-default 同时设为默认)。幂等性不做:同名允许存在,靠 id 区分。
200
+ *
201
+ * 可见域(v3,#128 / #131):显式 scope 优先;否则带创建主题 topic 时默认只在
202
+ * 该主题可见(scope=[topic:<key>],origin_topic 记锚);都没有 = 空数组(未配置),
203
+ * **不再默认全局**——全局必须显式 `--scope *` / UI 勾选。内置模板仍是 `["*"]`。
204
+ */
205
+ export async function addTemplate({
206
+ name: rawName,
207
+ body: rawBody,
208
+ bodyFile,
209
+ values,
210
+ setDefault = false,
211
+ scope: rawScope,
212
+ topic: rawTopic,
213
+ } = {}) {
145
214
  const name = normalizeName(rawName);
146
215
  const body = normalizeBody(await resolveBody({ body: rawBody, bodyFile }));
216
+ const topicKey = String(rawTopic || '').trim();
217
+ const scope = rawScope !== undefined
218
+ ? normalizeScope(rawScope, { strict: true })
219
+ : topicKey
220
+ ? [`topic:${topicKey}`]
221
+ : [];
147
222
  const at = nowMs();
148
223
  return repo.txw((conn) => {
149
224
  const t = {
@@ -163,6 +238,9 @@ export async function addTemplate({ name: rawName, body: rawBody, bodyFile, valu
163
238
  isDefault: 0,
164
239
  sortOrder: repo.templates.nextSortOrder(conn, NEWTASK_CATEGORY),
165
240
  builtin: 0,
241
+ scope,
242
+ // 创建来源是事实,不随 scope 策略走:显式给了 topic 才记
243
+ originTopic: topicKey,
166
244
  createdAtMs: at,
167
245
  updatedAtMs: at,
168
246
  });
@@ -199,8 +277,8 @@ export async function removeTemplate({ id } = {}) {
199
277
  });
200
278
  }
201
279
 
202
- /** 编辑模板(改名 / 改正文 / 改槽位;只改传入的字段)。 */
203
- export async function updateTemplate({ id, name: rawName, body: rawBody, bodyFile, values } = {}) {
280
+ /** 编辑模板(改名 / 改正文 / 改槽位 / 改可见域;只改传入的字段)。 */
281
+ export async function updateTemplate({ id, name: rawName, body: rawBody, bodyFile, values, scope: rawScope } = {}) {
204
282
  const want = String(id || '').trim();
205
283
  if (!want) throw badInput('需要模板 id');
206
284
  const bodyIn = rawBody !== undefined || bodyFile ? await resolveBody({ body: rawBody, bodyFile }) : undefined;
@@ -210,6 +288,7 @@ export async function updateTemplate({ id, name: rawName, body: rawBody, bodyFil
210
288
  const patch = {};
211
289
  if (rawName !== undefined) patch.name = normalizeName(rawName);
212
290
  if (bodyIn !== undefined) patch.body = normalizeBody(bodyIn);
291
+ if (rawScope !== undefined) patch.scope = normalizeScope(rawScope, { strict: true });
213
292
  if (values !== undefined) {
214
293
  // 内置模板:槽位未给的项回落出厂默认(渲染时的兜底语义与 JSON 时代一致)
215
294
  patch.vars = normalizeValues(values, row.builtin ? BUILTIN_VALUES : rowToView(row).values);
@@ -5,7 +5,7 @@
5
5
  // 迟早分叉。现在 depth 只在 action 声明里写一次 `{ type: 'number', default: 3 }`。
6
6
  import { badInput } from '../core/errors.js';
7
7
 
8
- const TYPES = new Set(['string', 'number', 'boolean', 'array']);
8
+ const TYPES = new Set(['string', 'number', 'boolean', 'array', 'raw']);
9
9
 
10
10
  // 取 action 的 CLI 路径列表。支持两种写法:
11
11
  // 单路径 cli: ['repo', 'list']
@@ -72,6 +72,11 @@ function coerceOne(name, spec, raw) {
72
72
  if (Array.isArray(raw)) return raw.map((x) => String(x).trim()).filter(Boolean);
73
73
  return String(raw).split(',').map((x) => x.trim()).filter(Boolean);
74
74
  }
75
+ // raw = 原样透传,不做字符串化。给「值本身是数组/对象」的 flag 用
76
+ // (模板可见域 scope 就是这种:JSON 数组串、逗号短写、HTTP 直接发数组,
77
+ // 三种形态都要活着走到 action 里)。走 string 会被 String([]) 压成 ''
78
+ // ——「清空可见域」就变成了「不传」,静默吞掉一次写入。
79
+ if (type === 'raw') return raw;
75
80
  return String(raw);
76
81
  }
77
82