nx-kv 0.63.0 → 0.64.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 (183) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/assets/nx-kv/references/A03-/346/226/207/346/241/243/344/270/216/345/275/222/345/261/236.md +6 -5
  3. package/package.json +2 -2
  4. package/src/core/attachmentdb/docs.ts +3 -6
  5. package/src/core/attachmentdb/query.ts +2 -2
  6. package/src/core/attachmentdb/relations.ts +36 -21
  7. package/src/core/db/import-json/refs.ts +17 -19
  8. package/src/core/db/import-json/repos.ts +4 -8
  9. package/src/core/db/migrations/index.ts +2 -0
  10. package/src/core/db/migrations/v13.sql +24 -0
  11. package/src/core/db/seed-templates.ts +15 -4
  12. package/src/core/db/version.ts +3 -1
  13. package/src/modules/docs/actions/_manifest.generated.ts +0 -3
  14. package/src/modules/docs/actions/doc-attach.ts +0 -1
  15. package/src/modules/docs/actions/docs-bindings.ts +2 -5
  16. package/src/modules/docs/actions/docs-link.ts +1 -2
  17. package/src/modules/docs/attach.ts +1 -36
  18. package/src/modules/docs/bound-docs.ts +2 -2
  19. package/src/modules/docs/brief.ts +0 -2
  20. package/src/modules/docs/docref.ts +7 -17
  21. package/src/modules/docs/knowledge-md.ts +1 -1
  22. package/src/modules/docs/knowledge.ts +48 -45
  23. package/src/modules/docs/ref-sync.ts +1 -5
  24. package/src/modules/docs/refs.ts +7 -10
  25. package/src/modules/docs/service.ts +1 -3
  26. package/src/modules/localtask/actions/localtask-config.ts +19 -58
  27. package/src/modules/localtask/actions/localtask-prune.ts +7 -2
  28. package/src/modules/localtask/repo/open.ts +0 -4
  29. package/src/modules/localtask/repo/settings.ts +20 -196
  30. package/src/modules/localtask/task-lifecycle.ts +7 -9
  31. package/src/modules/localtask/task-templates.ts +4 -4
  32. package/src/modules/localtask/task-view.ts +4 -0
  33. package/src/modules/localtask/topics.ts +30 -28
  34. package/src/modules/promptplug/actions/_manifest.generated.ts +0 -3
  35. package/src/modules/promptplug/actions/prompt-registry.ts +19 -30
  36. package/src/modules/promptplug/base.ts +69 -25
  37. package/src/modules/promptplug/compose.ts +40 -23
  38. package/src/modules/promptplug/factory.ts +91 -59
  39. package/src/modules/promptplug/index.ts +25 -11
  40. package/src/modules/promptplug/plugins/ack.ts +28 -0
  41. package/src/modules/promptplug/plugins/attachment.ts +237 -19
  42. package/src/modules/promptplug/plugins/context.ts +124 -30
  43. package/src/modules/promptplug/plugins/doneguard.ts +33 -0
  44. package/src/modules/promptplug/plugins/ext.ts +34 -11
  45. package/src/modules/promptplug/plugins/getloop.ts +29 -8
  46. package/src/modules/promptplug/plugins/goal-shape.ts +34 -0
  47. package/src/modules/promptplug/plugins/goalhint.ts +33 -0
  48. package/src/modules/promptplug/plugins/timecheck.ts +33 -0
  49. package/src/modules/promptplug/registry.ts +99 -0
  50. package/src/modules/promptplug/schema-bridge.ts +77 -13
  51. package/src/modules/repos/actions/board-rekey.ts +1 -1
  52. package/src/modules/repos/actions/repo-doc-add.ts +2 -3
  53. package/src/modules/repos/boards/core.ts +1 -13
  54. package/src/modules/repos/boards/docs.ts +2 -12
  55. package/src/modules/repos/boards/members.ts +2 -14
  56. package/src/modules/repos/boards/transfer.ts +2 -11
  57. package/src/modules/repos/keys.ts +4 -11
  58. package/src/modules/repos/repo/refs.ts +3 -5
  59. package/src/modules/repos/repo/repos.ts +12 -13
  60. package/src/modules/repos/repo/rows.ts +2 -8
  61. package/src/modules/repos/service/context.ts +0 -2
  62. package/src/modules/repos/service/crud.ts +1 -4
  63. package/src/modules/repos/service/store.ts +6 -7
  64. package/src/modules/repos/transfer/export.ts +3 -8
  65. package/src/modules/repos/transfer/import.ts +0 -13
  66. package/src/modules/repos/transfer/layout.ts +2 -2
  67. package/src/modules/tasktool/attach-template.ts +3 -3
  68. package/src/modules/tasktool/groupctx.ts +4 -5
  69. package/src/modules/tasktool/plugins/waitgoal-config.ts +5 -6
  70. package/src/modules/tasktool/preview.ts +20 -23
  71. package/src/modules/tasktool/wait.ts +24 -46
  72. package/src/modules/templates/actions/_manifest.generated.ts +3 -0
  73. package/src/modules/templates/actions/templates-reorder.ts +28 -0
  74. package/src/modules/templates/repo/templates.ts +32 -2
  75. package/src/modules/templates/service.ts +45 -0
  76. package/src/shared/prompt-blocks.ts +7 -173
  77. package/src/shared/prompt-plugin.ts +79 -59
  78. package/src/web/frontend/App.tsx +27 -1
  79. package/src/web/frontend/api/cli-tree.json +20 -35
  80. package/src/web/frontend/api/client.generated.ts +22 -32
  81. package/src/web/frontend/components/Introduction/rail.tsx +2 -2
  82. package/src/web/frontend/components/Introduction/use-intro.ts +2 -5
  83. package/src/web/frontend/components/bindings/bind-tags.tsx +1 -3
  84. package/src/web/frontend/components/list-search.tsx +37 -0
  85. package/src/web/frontend/components/md/attach-area.tsx +10 -15
  86. package/src/web/frontend/components/md/live-block.tsx +5 -14
  87. package/src/web/frontend/components/md/md-panes.tsx +3 -19
  88. package/src/web/frontend/modules/list-filter.ts +37 -0
  89. package/src/web/frontend/modules/md/fill-session.ts +36 -0
  90. package/src/web/frontend/modules/md/manage-session.ts +24 -0
  91. package/src/web/frontend/modules/md/new-task-from-template.ts +22 -0
  92. package/src/web/frontend/modules/md/styles/editor.css +5 -12
  93. package/src/web/frontend/modules/md/styles/shell.css +4 -0
  94. package/src/web/frontend/modules/md/task-intent.ts +29 -0
  95. package/src/web/frontend/modules/md/use-templates.ts +8 -0
  96. package/src/web/frontend/modules/prompts/template-preview.ts +12 -20
  97. package/src/web/frontend/modules/refs/api.ts +0 -1
  98. package/src/web/frontend/page/dir/index.tsx +20 -5
  99. package/src/web/frontend/page/dir/task-actions.ts +14 -0
  100. package/src/web/frontend/page/dir/task-preview-modal.tsx +1 -1
  101. package/src/web/frontend/page/dir/task.tsx +19 -0
  102. package/src/web/frontend/page/doc/api.ts +2 -3
  103. package/src/web/frontend/page/doc/bindings.tsx +46 -16
  104. package/src/web/frontend/page/doc/index.tsx +3 -4
  105. package/src/web/frontend/page/group/index.tsx +65 -117
  106. package/src/web/frontend/page/refs/index.tsx +27 -3
  107. package/src/web/frontend/page/refs/style.css +3 -0
  108. package/src/web/frontend/page/repos/bind-modals.tsx +18 -2
  109. package/src/web/frontend/page/repos/board-admin.tsx +1 -1
  110. package/src/web/frontend/page/repos/index.tsx +4 -8
  111. package/src/web/frontend/page/repos/ref-block.tsx +5 -12
  112. package/src/web/frontend/page/repos/ref-panel.tsx +3 -4
  113. package/src/web/frontend/page/repos/repo-form-modal.tsx +1 -8
  114. package/src/web/frontend/page/repos/repo-table.tsx +4 -29
  115. package/src/web/frontend/page/repos/use-repos-derive.ts +4 -5
  116. package/src/web/frontend/page/settings/api.ts +7 -15
  117. package/src/web/frontend/page/settings/prompt-templates-section.tsx +261 -289
  118. package/src/web/frontend/page/settings/prompt-vars.ts +56 -0
  119. package/src/web/frontend/page/settings/style.css +46 -64
  120. package/src/web/frontend/page/templates/fill.tsx +124 -0
  121. package/src/web/frontend/page/templates/index.tsx +11 -0
  122. package/src/web/frontend/page/templates/manage.tsx +218 -0
  123. package/src/web/frontend/page/templates/style.css +46 -0
  124. package/src/web/frontend/page/templates/template-list.tsx +58 -54
  125. package/src/web/frontend/refs/api.ts +0 -2
  126. package/src/web/frontend/routes/route-eq.ts +22 -0
  127. package/src/web/frontend/routes/templates.ts +20 -0
  128. package/src/web/frontend/style.css +1 -0
  129. package/src/web/frontend/styles/list-search.css +44 -0
  130. package/src/web/frontend/types.ts +5 -1
  131. package/src/web/public/assets/{bar-CYWfxHfm.js → bar-j14ON7uZ.js} +1 -1
  132. package/src/web/public/assets/{composer-launch-Bor4ngrQ.js → composer-launch-DRi9mZE1.js} +1 -1
  133. package/src/web/public/assets/{composer-panel-C7mNI7EW.js → composer-panel-swmDqlPw.js} +1 -1
  134. package/src/web/public/assets/dir-DhsB1ZhL.js +3 -0
  135. package/src/web/public/assets/doc-D4po3sDc.js +6 -0
  136. package/src/web/public/assets/fill-session-fHxQHFaD.js +1 -0
  137. package/src/web/public/assets/group-BxmSNzIB.js +1 -0
  138. package/src/web/public/assets/index-CMjG5NVU.js +2 -0
  139. package/src/web/public/assets/index-uMjSWNVr.css +1 -0
  140. package/src/web/public/assets/list-filter-D-x94TvA.js +1 -0
  141. package/src/web/public/assets/manage-session-CS8UvmUd.js +1 -0
  142. package/src/web/public/assets/md-history-CZUF_FhN.js +39 -0
  143. package/src/web/public/assets/new-task-from-template-DDWu4yR4.js +1 -0
  144. package/src/web/public/assets/refs-TuuoaRs7.js +2 -0
  145. package/src/web/public/assets/refs-zSA2k_45.css +1 -0
  146. package/src/web/public/assets/render-template-body-bXdedFig.js +1 -0
  147. package/src/web/public/assets/repo-form-modal-BD4N37MI.js +1 -0
  148. package/src/web/public/assets/repos-BPeuX4N9.js +12 -0
  149. package/src/web/public/assets/settings-CZJaKLZW.js +1 -0
  150. package/src/web/public/assets/settings-Cc6puKd5.css +1 -0
  151. package/src/web/public/assets/task-DgbbF5gy.js +11 -0
  152. package/src/web/public/assets/task-intent-CX5DZccN.js +1 -0
  153. package/src/web/public/assets/{task-utils-DpnPjZKJ.js → task-utils-bJH1-Cjy.js} +1 -1
  154. package/src/web/public/assets/templates-CBXlwyof.js +11 -0
  155. package/src/web/public/assets/templates-plA8R7jJ.css +1 -0
  156. package/src/web/public/assets/use-rail-drag-ufwy2XZB.js +1 -0
  157. package/src/web/public/index.html +8 -6
  158. package/src/modules/docs/actions/doc-attach-note.ts +0 -32
  159. package/src/modules/promptplug/Template/blockTemplates.json +0 -90
  160. package/src/modules/promptplug/actions/prompt-order.ts +0 -38
  161. package/src/modules/promptplug/ensure.ts +0 -57
  162. package/src/modules/promptplug/keys.ts +0 -9
  163. package/src/modules/promptplug/plugins/readonly-blocks.ts +0 -75
  164. package/src/modules/promptplug/template-bundle.ts +0 -59
  165. package/src/web/frontend/modules/md/template-locks.ts +0 -105
  166. package/src/web/frontend/page/settings/prompt-editor.tsx +0 -279
  167. package/src/web/frontend/page/settings/prompt-rail.tsx +0 -170
  168. package/src/web/public/assets/dir-CcffxXL2.js +0 -3
  169. package/src/web/public/assets/doc-BxWVzWkw.js +0 -6
  170. package/src/web/public/assets/group-C5Yu3oJr.js +0 -1
  171. package/src/web/public/assets/index-BvyZ1MA2.js +0 -2
  172. package/src/web/public/assets/index-Cp-TtHyA.css +0 -1
  173. package/src/web/public/assets/md-history-DejKuR12.js +0 -39
  174. package/src/web/public/assets/refs-DJdKV8_H.css +0 -1
  175. package/src/web/public/assets/refs-VbDnDTV0.js +0 -2
  176. package/src/web/public/assets/repo-form-modal-Dkdvu_uN.js +0 -1
  177. package/src/web/public/assets/repos-CY0eZheu.js +0 -16
  178. package/src/web/public/assets/settings-AwzLRYUu.css +0 -1
  179. package/src/web/public/assets/settings-D3T-vgCl.js +0 -1
  180. package/src/web/public/assets/task-CkCD82h_.js +0 -11
  181. package/src/web/public/assets/templates-BcuCbT4U.js +0 -10
  182. package/src/web/public/assets/templates-gNdtaMI2.css +0 -1
  183. package/src/web/public/assets/use-rail-drag-DMvr8-GE.js +0 -1
@@ -31,7 +31,6 @@ export interface RepoRowUpsert {
31
31
  export interface MemberUpsert {
32
32
  repoKey: string;
33
33
  position: number;
34
- note: string;
35
34
  }
36
35
 
37
36
  /** 组行的行形状(在 RepoRowUpsert 之上多一个 members)。 */
@@ -59,26 +58,26 @@ export function getRowByKey(key: unknown, conn: DbApi = db()): Row | null {
59
58
 
60
59
  /** 全部成员行(跨组;组装配/投影用)。 */
61
60
  export function listAllMembers(conn: DbApi = db()): Row[] {
62
- return conn.all('SELECT group_key, repo_key, position, note FROM repo_group_members ORDER BY group_key, position, rowid');
61
+ return conn.all('SELECT group_key, repo_key, position FROM repo_group_members ORDER BY group_key, position, rowid');
63
62
  }
64
63
 
65
64
  // ─── 组级参考仓库绑定(v4)────────────────────────────────────────────
66
65
 
67
66
  /** 全部组级参考绑定(跨组;store 装配用)。 */
68
67
  export function listAllGroupRefs(conn: DbApi = db()): Row[] {
69
- return conn.all('SELECT group_key, ref_key, note, position FROM group_refs ORDER BY group_key, position, rowid');
68
+ return conn.all('SELECT group_key, ref_key, position FROM group_refs ORDER BY group_key, position, rowid');
70
69
  }
71
70
 
72
71
  /** 一个组的参考绑定(有序)。 */
73
72
  export function listGroupRefs(groupKey: unknown, conn: DbApi = db()): Row[] {
74
73
  return conn.all(
75
- 'SELECT ref_key, note, position FROM group_refs WHERE group_key = :g ORDER BY position, rowid',
74
+ 'SELECT ref_key, position FROM group_refs WHERE group_key = :g ORDER BY position, rowid',
76
75
  { g: String(groupKey || '') }
77
76
  );
78
77
  }
79
78
 
80
79
  /** 整组重建参考绑定(组内共享;ref/组不存在由外键拒绝)。 */
81
- export function replaceGroupRefs(conn: DbApi, groupKey: unknown, refs: Array<{ id?: unknown; note?: unknown }>, atMs: number): void {
80
+ export function replaceGroupRefs(conn: DbApi, groupKey: unknown, refs: Array<{ id?: unknown }>, atMs: number): void {
82
81
  conn.run('DELETE FROM group_refs WHERE group_key = :g', { g: String(groupKey || '') });
83
82
  const seen = new Set<string>();
84
83
  refs.forEach((ref, position) => {
@@ -86,9 +85,9 @@ export function replaceGroupRefs(conn: DbApi, groupKey: unknown, refs: Array<{ i
86
85
  if (!key || seen.has(key)) return;
87
86
  seen.add(key);
88
87
  conn.run(
89
- `INSERT OR IGNORE INTO group_refs (group_key, ref_key, note, position, created_at)
90
- VALUES (:g, :r, :n, :p, :at)`,
91
- { g: String(groupKey || ''), r: key, n: String((ref && ref.note) || ''), p: position, at: atMs }
88
+ `INSERT OR IGNORE INTO group_refs (group_key, ref_key, position, created_at)
89
+ VALUES (:g, :r, :p, :at)`,
90
+ { g: String(groupKey || ''), r: key, p: position, at: atMs }
92
91
  );
93
92
  });
94
93
  }
@@ -101,14 +100,14 @@ export function clearGroupRefs(conn: DbApi, groupKey: unknown): void {
101
100
  /** 一个组的成员行(有序)。 */
102
101
  export function listMembers(groupKey: unknown, conn: DbApi = db()): Row[] {
103
102
  return conn.all(
104
- 'SELECT group_key, repo_key, position, note FROM repo_group_members WHERE group_key = :g ORDER BY position, rowid',
103
+ 'SELECT group_key, repo_key, position FROM repo_group_members WHERE group_key = :g ORDER BY position, rowid',
105
104
  { g: String(groupKey || '') }
106
105
  );
107
106
  }
108
107
 
109
108
  /** 这个仓库被哪些组包含(反查,走 ix_members_repo)。 */
110
109
  export function listGroupsOfRepo(repoKey: unknown, conn: DbApi = db()): Row[] {
111
- return conn.all('SELECT group_key, position, note FROM repo_group_members WHERE repo_key = :r ORDER BY group_key, position', {
110
+ return conn.all('SELECT group_key, position FROM repo_group_members WHERE repo_key = :r ORDER BY group_key, position', {
112
111
  r: String(repoKey || ''),
113
112
  });
114
113
  }
@@ -188,9 +187,9 @@ export function replaceMembers(conn: DbApi, groupKey: unknown, members: MemberUp
188
187
  conn.run('DELETE FROM repo_group_members WHERE group_key = :g', { g: String(groupKey || '') });
189
188
  for (const m of members) {
190
189
  conn.run(
191
- `INSERT OR IGNORE INTO repo_group_members (group_key, repo_key, position, note, created_at)
192
- VALUES (:g, :r, :p, :n, :at)`,
193
- { g: String(groupKey || ''), r: String(m.repoKey || ''), p: Number(m.position) || 0, n: String(m.note || ''), at: atMs }
190
+ `INSERT OR IGNORE INTO repo_group_members (group_key, repo_key, position, created_at)
191
+ VALUES (:g, :r, :p, :at)`,
192
+ { g: String(groupKey || ''), r: String(m.repoKey || ''), p: Number(m.position) || 0, at: atMs }
194
193
  );
195
194
  }
196
195
  }
@@ -21,7 +21,6 @@
21
21
  // repo.addedAt/.updatedAt(ISO UTC)→ created_at / updated_at(epoch ms)
22
22
  // board.id → ext.ext_legacy_id (b_xxx)
23
23
  // board.repoKeys[] → repo_group_members 行(真实成员)+ ext.ext_placeholders(占位)
24
- // board.repoNotes → repo_group_members.note / 占位条目的 note
25
24
  // board.repoHints → ext.ext_repo_hints
26
25
  // board.doc/.docLinks/.repoDocs → ext.ext_doc / ext_doc_links / ext_repo_docs
27
26
  // board 的 key → repos.key(冻结的 group/<slug>;JSON 形态多带一个 key 字段)
@@ -95,7 +94,6 @@ export interface BoardEntry {
95
94
  createdAt: string;
96
95
  /** 成员按 key 存(有序) */
97
96
  repoKeys: string[];
98
- repoNotes?: Record<string, string>;
99
97
  repoHints?: Record<string, RepoHint>;
100
98
  repoDocs?: Record<string, any>;
101
99
  doc?: any;
@@ -219,18 +217,15 @@ export function groupRowToStore(row: Row, allMembers: Row[], allGroupRefs: Row[]
219
217
  const ext = parseExt(row.ext);
220
218
  const real = allMembers
221
219
  .filter((m: Row) => m.group_key === row.key)
222
- .map((m: Row, i: number) => ({ key: String(m.repo_key || ''), note: String(m.note || ''), pos: Number(m.position) || 0, ord: i }));
220
+ .map((m: Row, i: number) => ({ key: String(m.repo_key || ''), pos: Number(m.position) || 0, ord: i }));
223
221
  const phRaw = Array.isArray(ext[GROUP_EXT.PLACEHOLDERS]) ? ext[GROUP_EXT.PLACEHOLDERS] : [];
224
222
  const ph = phRaw.map((p: any, i: number) => ({
225
223
  key: String((p && p.key) || ''),
226
- note: String((p && p.note) || ''),
227
224
  pos: Number.isFinite(Number(p && p.pos)) ? Number(p.pos) : Number.MAX_SAFE_INTEGER,
228
225
  ord: real.length + i,
229
226
  }));
230
227
  const merged = [...real, ...ph].sort((a, b) => a.pos - b.pos || a.ord - b.ord);
231
228
  const repoKeys = merged.map((m) => m.key);
232
- const repoNotes: Record<string, string> = {};
233
- for (const m of merged) if (m.note) repoNotes[m.key] = m.note;
234
229
 
235
230
  const out: BoardEntry = {
236
231
  id: String(ext[GROUP_EXT.LEGACY_ID] || ''),
@@ -243,9 +238,8 @@ export function groupRowToStore(row: Row, allMembers: Row[], allGroupRefs: Row[]
243
238
  repoKeys,
244
239
  refs: allGroupRefs
245
240
  .filter((l: Row) => l.group_key === row.key)
246
- .map((l: Row) => (l.note ? { id: String(l.ref_key || ''), note: String(l.note) } : { id: String(l.ref_key || '') })),
241
+ .map((l: Row) => ({ id: String(l.ref_key || '') })),
247
242
  };
248
- if (Object.keys(repoNotes).length) out.repoNotes = repoNotes;
249
243
  if (ext[GROUP_EXT.REPO_HINTS] && typeof ext[GROUP_EXT.REPO_HINTS] === 'object') {
250
244
  out.repoHints = ext[GROUP_EXT.REPO_HINTS];
251
245
  }
@@ -149,7 +149,6 @@ export interface ContextBoardBrief {
149
149
  name: string;
150
150
  desc: string;
151
151
  key: string;
152
- note: string;
153
152
  }
154
153
 
155
154
  /** contextMap 的一行:仓库本体投影 + 它所在的看板。 */
@@ -197,7 +196,6 @@ export async function contextMap(): Promise<Map<string, ContextEntry>> {
197
196
  name: b.name,
198
197
  desc: b.desc || '',
199
198
  key: storedBoardKey(b),
200
- note: (b.repoNotes || {})[rk] || '',
201
199
  });
202
200
  }
203
201
  }
@@ -16,13 +16,12 @@ import {
16
16
  import type { RepoEntry, RepoLink } from '../repo/rows.js';
17
17
  import type { RepoInputFields } from './identity.js';
18
18
 
19
- /** 中心清单里的看板投影(仓库属于哪些看板 + 组内描述)。 */
19
+ /** 中心清单里的看板投影(仓库属于哪些看板 + 组内描述文档)。 */
20
20
  export interface RepoBoardBrief {
21
21
  id: string;
22
22
  name: string;
23
23
  desc: string;
24
24
  key: string;
25
- note: string;
26
25
  /** 组内描述文档(ref:<refId>);没有绑定为空串 */
27
26
  noteDocId: string;
28
27
  }
@@ -102,7 +101,6 @@ export async function listRepos(): Promise<RepoListRow[]> {
102
101
  name: b.name,
103
102
  desc: b.desc || '',
104
103
  key: bkey,
105
- note: (b.repoNotes || {})[rk] || '',
106
104
  // 组内描述也是文档:前端点「描述」直接开这篇(ref:<refId>)
107
105
  noteDocId: noteDocOf.get(`${bkey}|${rk}`) || '',
108
106
  });
@@ -310,7 +308,6 @@ export async function removeRepo(id: unknown): Promise<RepoEntry> {
310
308
  // 看板里同步摘引用(看板成员存 key,登记没了就是死引用)
311
309
  for (const b of s.boards) {
312
310
  if (Array.isArray(b.repoKeys)) b.repoKeys = b.repoKeys.filter((k) => k !== deadKey);
313
- if (b.repoNotes && b.repoNotes[deadKey]) delete b.repoNotes[deadKey];
314
311
  // 组级参考绑定:删掉的是参考仓库 → 它从所有组里消失
315
312
  if (Array.isArray(b.refs)) b.refs = b.refs.filter((r) => r.id !== deadKey);
316
313
  }
@@ -131,17 +131,16 @@ function groupToRow(b: BoardEntry, atMs: number, knownRepoKeys: Set<string>): Gr
131
131
  if (!key) throw badInput('看板 key 不能为空');
132
132
  if (key === SENTINEL_REPO_KEY) throw badInput('哨兵仓库不能入组: ' + SENTINEL_REPO_KEY);
133
133
  const repoKeys = Array.isArray(b.repoKeys) ? b.repoKeys.map((k) => String(k || '').trim()).filter(Boolean) : [];
134
- const notes = b.repoNotes && typeof b.repoNotes === 'object' ? b.repoNotes : {};
135
134
  const members: MemberUpsert[] = [];
136
- // 占位成员(本地未拥有,进 ext.ext_placeholders):key/note/pos 落库形状
137
- const placeholders: Array<{ key: string; note: string; pos: number }> = [];
135
+ // 占位成员(本地未拥有,进 ext.ext_placeholders):key/pos 落库形状
136
+ const placeholders: Array<{ key: string; pos: number }> = [];
138
137
  const seen = new Set<string>();
139
138
  repoKeys.forEach((rk, position) => {
140
139
  if (seen.has(rk)) return; // 重复成员去重(位次取首次出现)
141
140
  seen.add(rk);
142
141
  if (rk === SENTINEL_REPO_KEY) throw badInput('哨兵仓库不能入组: ' + SENTINEL_REPO_KEY);
143
- if (knownRepoKeys.has(rk)) members.push({ repoKey: rk, position, note: String(notes[rk] ?? '') });
144
- else placeholders.push({ key: rk, note: String(notes[rk] ?? ''), pos: position });
142
+ if (knownRepoKeys.has(rk)) members.push({ repoKey: rk, position });
143
+ else placeholders.push({ key: rk, pos: position });
145
144
  });
146
145
  const hints = b.repoHints && typeof b.repoHints === 'object' ? b.repoHints : null;
147
146
  const repoDocs = b.repoDocs && typeof b.repoDocs === 'object' && Object.keys(b.repoDocs).length ? b.repoDocs : null;
@@ -248,7 +247,7 @@ function normalizeDocRefs(store: Store): void {
248
247
  .map((l: any) => {
249
248
  const d = sanitizeDocRef(l);
250
249
  if (!d) return null;
251
- return withLinkMeta(d, l);
250
+ return withLinkMeta(d);
252
251
  })
253
252
  .filter(Boolean);
254
253
  if (links.length) r.docLinks = links;
@@ -262,7 +261,7 @@ function normalizeDocRefs(store: Store): void {
262
261
  .map((l: any) => {
263
262
  const d = sanitizeDocRef(l);
264
263
  if (!d) return null;
265
- return withLinkMeta(d, l);
264
+ return withLinkMeta(d);
266
265
  })
267
266
  .filter(Boolean);
268
267
  if (links.length) b.docLinks = links;
@@ -38,7 +38,6 @@ export interface ExportRepoEntry {
38
38
  /** 导出布局里看板的成员条目。 */
39
39
  export interface ExportBoardRepoEntry {
40
40
  key: string;
41
- note?: string;
42
41
  }
43
42
 
44
43
  /** 导出布局里的看板条目。 */
@@ -138,7 +137,7 @@ export async function repoExport({ repoKeys, boardKeys, includeUnassigned = true
138
137
  .map((l: any) => {
139
138
  const d = sanitizeDocRef(l);
140
139
  if (!d) return null;
141
- return withLinkMeta(d, l);
140
+ return withLinkMeta(d);
142
141
  })
143
142
  .filter(Boolean);
144
143
  if (repoLinks.length) entry.docLinks = repoLinks;
@@ -157,11 +156,7 @@ export async function repoExport({ repoKeys, boardKeys, includeUnassigned = true
157
156
  name: b.name,
158
157
  desc: b.desc || '',
159
158
  // 成员按 key 引用(占位成员也在——本地没有的仓库照样导出,导入端会标「本地未拥有」)
160
- repos: service.boardRepoKeys(b, s)
161
- .map((k) => {
162
- const note = (b.repoNotes || {})[k] || '';
163
- return note ? { key: k, note } : { key: k };
164
- }),
159
+ repos: service.boardRepoKeys(b, s).map((k) => ({ key: k })),
165
160
  };
166
161
  // 文档绑定(v4):组介绍覆盖 / 组级附加列表 / 组内描述覆盖
167
162
  const bdoc = sanitizeDocRef(b.doc);
@@ -171,7 +166,7 @@ export async function repoExport({ repoKeys, boardKeys, includeUnassigned = true
171
166
  .map((l: any) => {
172
167
  const d = sanitizeDocRef(l);
173
168
  if (!d) return null;
174
- return withLinkMeta(d, l);
169
+ return withLinkMeta(d);
175
170
  })
176
171
  .filter(Boolean);
177
172
  if (links.length) entry.docLinks = links;
@@ -274,19 +274,6 @@ export async function repoImport({
274
274
  .setMemberHint({ board: b.id, key: m.key, name: m.name, remote: m.remote, desc: m.desc, type: m.type })
275
275
  .catch(() => {});
276
276
  }
277
- if (m.note) {
278
- // 组内描述挂在 key 上:占位成员也保留描述,等仓库补齐后自动生效。
279
- // **直接写摘要字段**,不走 setBoardRepoNote —— 后者会把这句话写进
280
- // group 文档,覆盖刚从 zip 还原的正文(描述以文档为准,文字只是影子)。
281
- await service
282
- .mutateStore((s) => {
283
- const bb = s.boards.find((x) => x.id === b!.id);
284
- if (!bb) return;
285
- if (!bb.repoNotes) bb.repoNotes = {};
286
- bb.repoNotes[m.key] = m.note;
287
- })
288
- .catch(() => {});
289
- }
290
277
  if (!known) {
291
278
  unmatched.push({
292
279
  board: inc.name,
@@ -91,8 +91,8 @@ export function parseLayout(json: unknown): Layout {
91
91
  const refOf = (raw: unknown): any => {
92
92
  const d = sanitizeDocRef(raw);
93
93
  if (!d) return null;
94
- // sanitizeDocRef 通过即说明 raw 是 DocRef 形状对象(note 注解原样带出)
95
- return withLinkMeta(d, raw as { note?: unknown });
94
+ // sanitizeDocRef 通过即说明 raw 是 DocRef 形状对象
95
+ return withLinkMeta(d);
96
96
  };
97
97
 
98
98
  function normalizeLayout(data: any): Layout {
@@ -8,9 +8,9 @@ import { isImageName } from '../../core/filekind.js';
8
8
  import { hostOfUrl, kindLabelOf, ORIGIN_LABEL, sizeTextOf, STATUS_LABEL } from './attach-resource.js';
9
9
 
10
10
  /**
11
- * 内置附件段模板(v6 起唯一归属在本文件——shared/prompt-blocks 不再持有任何模板正文,
12
- * 模板真相在出厂快照 blockTemplates.json)。这里的文本 ≡ 快照 attachment 段内置文本,
13
- * 一致性由 tests/unit/prompt-ensure.test.mjs 对账;改任何一处都要同步另一处并跑单测。
11
+ * 内置附件段模板(#152 起模板正文的唯一真相是插件类:attachment 插件的内置模板
12
+ * 包了 `{{#if attach}}`,这里是不带外壳的内文,供「不走插件链」的直渲染入口用)。
13
+ * 两处文本必须逐字一致(tests/unit/attach-template.test.mjs 钉住渲染结果)。
14
14
  */
15
15
  export const DEFAULT_ATTACH_TEMPLATE = [
16
16
  '{{#if attach}}',
@@ -46,7 +46,6 @@ interface DocLink {
46
46
  hasBody?: boolean;
47
47
  type?: string;
48
48
  groupKey?: string | null;
49
- note?: string;
50
49
  }
51
50
 
52
51
  /** 单个项目组的一段上下文 */
@@ -143,8 +142,8 @@ export function renderGroupContext(ctx: GroupContext | null): string {
143
142
  if (repo.docLinks && repo.docLinks.length) {
144
143
  lines.push('项目文档(按需取用):');
145
144
  for (const d of repo.docLinks) {
146
- const label = d.desc || d.title || '未命名文档';
147
- lines.push(` - ${label}${d.refId ? `(nx-kv docs get --ref ${d.refId})` : ''}${d.note ? ` # ${d.note}` : ''}`);
145
+ const label = d.title || d.desc || '未命名文档';
146
+ lines.push(` - ${label}${d.refId ? `(nx-kv docs get --ref ${d.refId})` : ''}`);
148
147
  }
149
148
  lines.push('');
150
149
  }
@@ -165,8 +164,8 @@ export function renderGroupContext(ctx: GroupContext | null): string {
165
164
  if (g.docLinks && g.docLinks.length) {
166
165
  lines.push('组文档(按需取用):');
167
166
  for (const d of g.docLinks) {
168
- const label = d.desc || d.title || '未命名文档';
169
- lines.push(` - ${label}${d.refId ? `(nx-kv docs get --ref ${d.refId})` : ''}${d.note ? ` # ${d.note}` : ''}`);
167
+ const label = d.title || d.desc || '未命名文档';
168
+ lines.push(` - ${label}${d.refId ? `(nx-kv docs get --ref ${d.refId})` : ''}`);
170
169
  }
171
170
  }
172
171
  lines.push('');
@@ -2,8 +2,8 @@
2
2
  //
3
3
  // 落点:repos.json 的 repo 记录字段 getLoop = { enabled, waitMinutes }。
4
4
  // **#182 起仓库级配置只剩「开关 + 阻塞分钟」**:交付里那段「继续 get」的**文案**
5
- // 统一由 设置 → 提示词模板 → 持续 get 区块提供(默认值即 src/shared/prompt-blocks.ts
6
- // 的 DEFAULT_GETLOOP_TEMPLATE)。此前这里还存一份 repo 级 template(v0.14 起 string[]),
5
+ // 统一由 getloop 插件类的内置模板提供(#152 起正文进代码,不再有「全局模板区块」可配)。
6
+ // 此前这里还存一份 repo 级 template(v0.14 起 string[]),
7
7
  // 与全局模板两处各写一遍必然漂移——那个口子已下线;老数据里的 template 字段
8
8
  // 读入时一律忽略,下次写回 getLoop 时自然被 sanitizeGetLoop 丢掉。
9
9
  //
@@ -19,10 +19,9 @@
19
19
  import { badInput } from '../../../core/errors.js';
20
20
 
21
21
  /**
22
- * 持续 get 内文的默认文案(v6 起唯一归属在本文件——shared/prompt-blocks 不再持有
23
- * 任何模板正文,模板真相在出厂快照 blockTemplates.json)。这里的文本是快照 getloop
24
- * 段内置模板的**内文**(快照模板 = `{{#if getloop}}\n<本段>\n{{/if}}`),一致性由
25
- * tests/unit/prompt-ensure.test.mjs 对账;改任何一处都要同步另一处并跑单测。
22
+ * 持续 get 内文的默认文案(#152 起模板正文的唯一真相是插件类:getloop 插件的内置
23
+ * 模板 = `{{#if getloop}}\n<本段>\n{{/if}}`,这里是其中的**内文**,由
24
+ * getLoopInstruction() 渲染后作为 loopText 供给插件)。改文案请改插件类。
26
25
  */
27
26
  export const DEFAULT_GETLOOP_INSTRUCTION =
28
27
  '{{#if task}}不要直接结束本轮:完成上面的任务({{task.id}})之后,继续调用 nx-kv localtask get 领取下一条任务。队列里有活会立即返回;{{#if (gt getloop.waitMinutes 0)}}没活时每次最多阻塞 {{getloop.waitMinutes}} 分钟,直到 get 返回 timeout 为止。{{/if}}{{/if}}';
@@ -14,11 +14,7 @@
14
14
  // 持续 get),并附带各项开关的当前状态——用户要能看出「这段是哪来的、
15
15
  // 想关该关哪个开关」。
16
16
  import { getSettings } from '../localtask/service.js';
17
- import {
18
- PROMPT_BLOCK_IDS,
19
- resolveBlockTemplates,
20
- type ResolvedBlockTemplate,
21
- } from '../../shared/prompt-blocks.js';
17
+ import { PLUGIN_IDS, groupIndex, pluginMeta } from '../promptplug/index.js';
22
18
  import { deliveryPlainText } from './delivery-text.js';
23
19
  import { getLoopForCwd, getLoopInstruction, type GetLoopState } from './getloop.js';
24
20
  import { buildTaskDelivery } from './wait.js';
@@ -65,10 +61,18 @@ export async function previewTaskDelivery({ task, cwd, key, summary, params }: P
65
61
  const previewTask = delivery.task || task;
66
62
  const instruction = delivery.instruction || '';
67
63
 
64
+ // #152:模板正文全部内置在插件类里,DB 不再存模板 —— 这里的 switches 只是
65
+ // 「当前生效的是哪段正文」的只读回显,形状保持旧版以便预览面板不必改读法。
68
66
  const ackList: any[] = settings.ackPromptList || [];
69
- const active: Record<string, ResolvedBlockTemplate> = resolveBlockTemplates(settings.blockTemplates);
70
- const contextTpl = active['context'] as ResolvedBlockTemplate;
71
- const attachTpl = active['attachment'] as ResolvedBlockTemplate;
67
+ const builtinBlock = (id: string) => {
68
+ const meta = pluginMeta(id);
69
+ return {
70
+ id: 'builtin',
71
+ name: meta ? meta.label : id,
72
+ custom: false,
73
+ builtin: true,
74
+ };
75
+ };
72
76
  return {
73
77
  task: previewTask,
74
78
  instruction,
@@ -82,22 +86,15 @@ export async function previewTaskDelivery({ task, cwd, key, summary, params }: P
82
86
  },
83
87
  switches: {
84
88
  ack: { on: ackList.length > 0, count: ackList.length },
85
- // 兼容旧预览面板:这两个开关表示对应区块当前是否用了自定义模板
86
- deliveryTemplate: { custom: !contextTpl.builtin, name: contextTpl.name },
87
- attachTemplate: { custom: !attachTpl.builtin, name: attachTpl.name },
89
+ // 两个旧开关保留:模板已全部内置,custom 恒为 false
90
+ deliveryTemplate: builtinBlock('context'),
91
+ attachTemplate: builtinBlock('attachment'),
88
92
  appendMode: settings.appendMode || 'xml',
89
- // 每个区块各自选中的生效模板(内置 / 自定义)
90
- blockTemplates: Object.fromEntries(
91
- PROMPT_BLOCK_IDS.map((id) => [
92
- id,
93
- {
94
- id: (active[id] as ResolvedBlockTemplate).id,
95
- name: (active[id] as ResolvedBlockTemplate).name,
96
- custom: !(active[id] as ResolvedBlockTemplate).builtin,
97
- builtin: (active[id] as ResolvedBlockTemplate).builtin,
98
- },
99
- ])
100
- ),
93
+ // 每个区块当前生效的模板(全部内置)
94
+ blockTemplates: Object.fromEntries(PLUGIN_IDS.map((id) => [id, builtinBlock(id)])),
95
+ // 时机链(#152):get / check / done 各自的插件顺序
96
+ groups: groupIndex(),
97
+ plugins: [...PLUGIN_IDS],
101
98
  },
102
99
  };
103
100
  }
@@ -12,10 +12,6 @@ import { DEFAULT_PORT } from '../../core/paths.js';
12
12
  import { formatGoalTiming, renderInstruction } from '../../core/instruction-template.js';
13
13
  import { parseFrontmatter } from '../../shared/frontmatter.js';
14
14
  import { reorderRoundsForDelivery } from '../../shared/feedback-text.js';
15
- import {
16
- resolveBlockTemplates,
17
- type ResolvedBlockTemplate,
18
- } from '../../shared/prompt-blocks.js';
19
15
  import {
20
16
  clampTimeoutSec,
21
17
  clearWaiting,
@@ -41,25 +37,12 @@ import { formatDuration } from '../../core/instruction-template.js';
41
37
  import { readGroupContext } from './groupctx.js';
42
38
  import { annotateTaskDelivery, attachTemplateCtx } from './attach.js';
43
39
  import { compose, type RenderTraceEntry, type SegmentMeta } from '../promptplug/compose.js';
44
- import { buildDeliveryPlugins } from '../promptplug/index.js';
45
- import { PROMPT_ORDER_KEY } from '../promptplug/keys.js';
46
- import { getDb } from '../../core/db/index.js';
47
- import { readSettingRaw } from '../../core/db/settings.js';
40
+ import { buildPlugins } from '../promptplug/index.js';
48
41
  import * as timegoal from './timegoal.js';
49
42
 
50
43
  // 跨进程兜底轮询间隔(只定这里的读取节奏;队列写入节奏与它无关)
51
44
  const POLL_MS = 500;
52
45
 
53
- /** 顺序数组(prompt.pluginOrder)的运行期读取:库没开 / 读失败 → undefined(compose 播种)。 */
54
- function storedPromptOrder(): readonly string[] | undefined {
55
- try {
56
- const v = readSettingRaw(getDb(), PROMPT_ORDER_KEY);
57
- return Array.isArray(v) ? (v as string[]) : undefined;
58
- } catch {
59
- return undefined;
60
- }
61
- }
62
-
63
46
  // 「YYYY-MM-DD HH:mm:ss」→ epoch ms(任务级 goal 的起点 = consumedAt);解析不了返回 NaN
64
47
  function parseStampMs(v: unknown): number {
65
48
  const m = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})$/.exec(String(v || ''));
@@ -297,31 +280,31 @@ export async function buildTaskDelivery(
297
280
  }
298
281
 
299
282
  const mode: 'xml' | 'plain' = settings.appendMode === 'plain' ? 'plain' : 'xml';
300
- // 每个区块按各自列表中选中的生效模板渲染(内置常驻,找不到就回落内置)
301
- const blockTemplates = resolveBlockTemplates(settings.blockTemplates);
302
- const plugins = buildDeliveryPlugins(blockTemplates, {
303
- groupCtx,
304
- attach,
305
- queueInfo,
306
- loopText,
307
- waitMinutes: Number(getLoopWaitMinutes) || 0,
308
- });
283
+ // #152:模板是插件类的内置正文(不再从 settings 解析)。
284
+ // 交付一次给全三条链(get → check → done,合并后按类声明的 order 全局排序):
285
+ // - check(时间目标 / 进度提示)与 done(完成门禁)没有独立的注入点——
286
+ // 它们本来就是「领取时告诉 agent 每轮怎么检查、什么时候才能收口」,
287
+ // 等 agent 真去 done 再给已经晚了;三者链内都是条件渲染,无数据即不出段。
288
+ const plugins = [...buildPlugins('get', {
289
+ groupCtx: () => groupCtx,
290
+ attach: () => attach,
291
+ queueInfo: () => queueInfo,
292
+ loopText: () => loopText,
293
+ waitMinutes: () => Number(getLoopWaitMinutes) || 0,
294
+ }), ...buildPlugins('check'), ...buildPlugins('done')];
309
295
  const segments: SegmentMeta[] = [
310
- { id: 'context', label: '组 / 项目上下文(模板)', traceId: 'delivery', templateName: blockTemplates['context']?.name },
311
- { id: 'attachment', label: '附件段(清单 / 本地路径)', traceId: 'attach', templateName: blockTemplates['attachment']?.name },
312
- { id: 'timecheck', label: '时间目标(状态 / check 指令)', traceId: 'goal', templateName: blockTemplates['timecheck']?.name },
313
- { id: 'goalhint', label: '特殊功能提示(timegoal)', templateName: blockTemplates['goalhint']?.name },
314
- { id: 'doneguard', label: '完成门禁提示(timegoal)', templateName: blockTemplates['doneguard']?.name },
315
- { id: 'ext', label: '待领取队列(ext)', traceId: 'ext', templateName: blockTemplates['ext']?.name },
316
- { id: 'ack', label: 'ack 完成总结提示词', traceId: 'ack', templateName: blockTemplates['ack']?.name },
317
- { id: 'getloop', label: '持续 get 指令(项目级)', traceId: 'getloop', templateName: blockTemplates['getloop']?.name },
296
+ { id: 'context', label: '组 / 项目上下文(模板)', traceId: 'delivery' },
297
+ { id: 'attachment', label: '附件段(清单 / 本地路径)', traceId: 'attach' },
298
+ { id: 'timecheck', label: '时间目标(状态 / check 指令)', traceId: 'goal' },
299
+ { id: 'goalhint', label: '特殊功能提示(timegoal)', traceId: 'goalhint' },
300
+ { id: 'doneguard', label: '完成门禁提示(timegoal)', traceId: 'doneguard' },
301
+ { id: 'ext', label: '待领取队列(ext)', traceId: 'ext' },
302
+ { id: 'ack', label: 'ack 完成总结提示词', traceId: 'ack' },
303
+ { id: 'getloop', label: '持续 get 指令(项目级)', traceId: 'getloop' },
318
304
  ];
319
305
  const full = await compose({
320
306
  plugins,
321
- // 顺序数组唯一真相(方案 §5.1):settings['prompt.pluginOrder'] 存在且合法
322
- // → 按它渲染(拖动排序后 CLI 渲染顺序同步变化);缺失/坏值由 compose 的
323
- // resolveOrderIds 按插件 order 播种一次(加载期单点修复)。
324
- orderIds: storedPromptOrder(),
307
+ groups: ['get', 'check', 'done'],
325
308
  seed: seedCtx,
326
309
  mode,
327
310
  trace,
@@ -331,12 +314,12 @@ export async function buildTaskDelivery(
331
314
  if (!full) {
332
315
  return { task, ...warnField };
333
316
  }
334
- // coversBody = 启用区块的任一模板含 {{task.text}}(instruction 自包含任务正文)。
317
+ // coversBody = 本次交付链的任一模板含 {{task.text}}(instruction 自包含任务正文)。
335
318
  // 由服务端判定,避免 CLI 端做子串猜测。
336
319
  return {
337
320
  task,
338
321
  instruction: full,
339
- coversBody: blocksCoverBody(blockTemplates),
322
+ coversBody: plugins.some((p) => /\{\{\s*task\.text\s*\}\}/.test(p.get())),
340
323
  ...warnField,
341
324
  };
342
325
  } catch {
@@ -344,11 +327,6 @@ export async function buildTaskDelivery(
344
327
  }
345
328
  }
346
329
 
347
- /** 当前生效模板里是否有模板写了 {{task.text}}(instruction 自包含任务正文)。 */
348
- function blocksCoverBody(templates: Record<string, ResolvedBlockTemplate>): boolean {
349
- return Object.values(templates).some((t) => /\{\{\s*task\.text\s*\}\}/.test(String(t?.template || '')));
350
- }
351
-
352
330
  export interface WaitForTaskOptions {
353
331
  /** 工作目录(主题按目录名识别);缺省 → 进程当前 cwd。显式传 cwd **不会**关闭全局兜底 */
354
332
  cwd?: unknown;
@@ -10,6 +10,7 @@ import { TemplatesAddAction } from './templates-add.js';
10
10
  import { TemplatesDefaultAction } from './templates-default.js';
11
11
  import { TemplatesListAction } from './templates-list.js';
12
12
  import { TemplatesRemoveAction } from './templates-remove.js';
13
+ import { TemplatesReorderAction } from './templates-reorder.js';
13
14
  import { TemplatesUpdateAction } from './templates-update.js';
14
15
 
15
16
  /** 本模块的全部 action 类(容器按这个顺序建实例)。 */
@@ -18,6 +19,7 @@ export const ACTIONS: readonly (new (deps: Container) => ActionBase)[] = [
18
19
  TemplatesDefaultAction,
19
20
  TemplatesListAction,
20
21
  TemplatesRemoveAction,
22
+ TemplatesReorderAction,
21
23
  TemplatesUpdateAction,
22
24
  ];
23
25
 
@@ -26,4 +28,5 @@ export { TemplatesAddAction };
26
28
  export { TemplatesDefaultAction };
27
29
  export { TemplatesListAction };
28
30
  export { TemplatesRemoveAction };
31
+ export { TemplatesReorderAction };
29
32
  export { TemplatesUpdateAction };
@@ -0,0 +1,28 @@
1
+ // templates.reorder —— #151:topic 管理页拖拽排序落库。
2
+ //
3
+ // 契约(zod schema)声明在本文件,业务在服务层。ids 是 newtask 类目模板的
4
+ // 完整期望顺序(前端拖完后按新序传进来);不在 ids 里的行被挪到末尾。
5
+ import { action } from '../../../runtime/action-decorator.js';
6
+ import { z } from 'zod';
7
+ import { ActionBase, type ActionInput } from '../../../runtime/action-base.js';
8
+ import * as serviceNs from '../service.js';
9
+ const service: any = serviceNs;
10
+
11
+ /** templates.reorder 的入参契约(CLI 与 HTTP 共用同一份)。 */
12
+ const input = z.object({
13
+ ids: z.array(z.string()).describe("模板 id 的完整有序数组(CLI 用 --ids a,b,c 逗号分隔)"),
14
+ });
15
+
16
+ export class TemplatesReorderAction extends ActionBase<typeof input> {
17
+ @action({
18
+ id: 'templates.reorder',
19
+ cli: ['template', 'reorder'],
20
+ http: ['PATCH', '/api/templates/reorder'],
21
+ summary: '调整任务模板顺序(--ids a,b,c 按新序落库 sort_order;未列出的模板保持原位)',
22
+ input,
23
+ render: (d: any) => `模板顺序已更新(共 ${(d.templates || []).length} 条)`,
24
+ })
25
+ override async run(ctx: ActionInput<this['_input']>) {
26
+ return service.reorderTemplates({ ids: ctx.ids });
27
+ }
28
+ }
@@ -131,10 +131,40 @@ export function deleteRow(conn: any, id: any): boolean {
131
131
 
132
132
  /** 该类目下一个可用的 sort_order(追加到末尾)。 */
133
133
  export function nextSortOrder(conn: any, category: any): number {
134
- const row = conn.get('SELECT COALESCE(MAX(sort_order), -1) AS m FROM templates WHERE category = :c', {
134
+ const row = conn.get('SELECT MAX(sort_order) AS m FROM templates WHERE category = :c', {
135
135
  c: String(category || ''),
136
136
  });
137
- return Number((row && row.m) || -1) + 1;
137
+ // ⚠️ 不能写 `(row && row.m) || -1`:m 为 0(第一条模板)时会被当成假值,
138
+ // 于是新模板全落 sort_order=0、排序永远无效(#151 拖拽排序踩到)。
139
+ const max = row && row.m !== null && row.m !== undefined ? Number(row.m) : -1;
140
+ return (Number.isFinite(max) ? max : -1) + 1;
141
+ }
142
+
143
+ /**
144
+ * 按给定 id 顺序重排 sort_order(#151):ids 里的行依次得 0..n-1;
145
+ * 不在 ids 里的同类目行顺序不变,但为避免唯一/并列歧义,整体从 0 重排:
146
+ * 先写传入的 orderedIds,再把剩余行按原 sort_order 追加在后。
147
+ * 返回受影响行数。
148
+ */
149
+ export function reorderRows(conn: any, orderedIds: string[], atMs: number, slots?: number[]): number {
150
+ const seen = new Set<string>();
151
+ const clean: string[] = [];
152
+ for (const raw of orderedIds) {
153
+ const id = String(raw || '').trim();
154
+ if (id && !seen.has(id)) {
155
+ seen.add(id);
156
+ clean.push(id);
157
+ }
158
+ }
159
+ let changed = 0;
160
+ clean.forEach((id, i) => {
161
+ const r = conn.run(
162
+ 'UPDATE templates SET sort_order = :sort, updated_at = :at WHERE id = :id AND deleted_at IS NULL',
163
+ { id, sort: slots && slots[i] !== undefined ? slots[i] : i, at: atMs }
164
+ );
165
+ changed += Number(r.changes) > 0 ? 1 : 0;
166
+ });
167
+ return changed;
138
168
  }
139
169
 
140
170
  /**