nx-kv 0.18.0 → 0.19.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 (111) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/assets/kv-get/references/wait-workflow.md +4 -0
  3. package/package.json +1 -1
  4. package/src/core/workflow/edges.js +31 -0
  5. package/src/core/workflow/event-names.js +10 -0
  6. package/src/core/workflow/layout.js +119 -0
  7. package/src/core/workflow/lifecycle.js +58 -0
  8. package/src/core/workflow/plugin-registry.js +47 -0
  9. package/src/core/workflow/project.js +108 -0
  10. package/src/core/workflow/readiness.js +98 -0
  11. package/src/core/workflow/snapshot.example.json +46 -0
  12. package/src/core/workflow/types.js +169 -0
  13. package/src/modules/localtask/bus/index.js +41 -0
  14. package/src/modules/localtask/dag.js +6 -0
  15. package/src/modules/localtask/engine.js +49 -0
  16. package/src/modules/localtask/index.js +43 -2
  17. package/src/modules/localtask/mutator/index.js +153 -0
  18. package/src/modules/localtask/mutator/validate.js +62 -0
  19. package/src/modules/localtask/scheduler/index.js +55 -0
  20. package/src/modules/localtask/scheduler/state-drive.js +30 -0
  21. package/src/modules/localtask/service.js +140 -15
  22. package/src/modules/localtask/store/file-adapter.js +51 -0
  23. package/src/modules/localtask/store/index.js +100 -0
  24. package/src/modules/localtask/store/memory-adapter.js +26 -0
  25. package/src/modules/localtask/store/topic-adapter.js +43 -0
  26. package/src/modules/localtask/writes.js +120 -0
  27. package/src/modules/tasktool/add.js +11 -1
  28. package/src/modules/tasktool/facade/get.js +46 -0
  29. package/src/modules/tasktool/facade/index.js +4 -0
  30. package/src/modules/tasktool/facade/submit.js +49 -0
  31. package/src/modules/tasktool/facade/wait.js +3 -0
  32. package/src/modules/tasktool/getloop.js +2 -84
  33. package/src/modules/tasktool/plugins/base.js +92 -0
  34. package/src/modules/tasktool/plugins/blockgoal.js +23 -0
  35. package/src/modules/tasktool/plugins/container.js +47 -0
  36. package/src/modules/tasktool/plugins/discover.js +45 -0
  37. package/src/modules/tasktool/plugins/index.js +20 -0
  38. package/src/modules/tasktool/plugins/runtime.js +69 -0
  39. package/src/modules/tasktool/plugins/taskgoal-store.js +100 -0
  40. package/src/modules/tasktool/plugins/taskgoal.js +17 -0
  41. package/src/modules/tasktool/plugins/timegoal-store.js +748 -0
  42. package/src/modules/tasktool/plugins/timegoal.js +51 -0
  43. package/src/modules/tasktool/plugins/waitgoal-config.js +84 -0
  44. package/src/modules/tasktool/plugins/waitgoal.js +75 -0
  45. package/src/modules/tasktool/taskgoal.js +2 -100
  46. package/src/modules/tasktool/timegoal.js +2 -748
  47. package/src/modules/tasktool/wait.js +25 -0
  48. package/src/modules/templates/index.js +21 -0
  49. package/src/modules/templates/service.js +62 -9
  50. package/src/shared/frontmatter.js +28 -1
  51. package/src/web/frontend/App.jsx +15 -46
  52. package/src/web/frontend/components/layout/breadcrumb.jsx +26 -0
  53. package/src/web/frontend/components/layout/crumbs.js +34 -0
  54. package/src/web/frontend/components/md/md-panes.jsx +10 -6
  55. package/src/web/frontend/components/md/shortcut-sheet.jsx +1 -0
  56. package/src/web/frontend/components/md/tool-bar.jsx +11 -0
  57. package/src/web/frontend/components/sidebar/index.jsx +4 -3
  58. package/src/web/frontend/modules/md/md-parse.js +122 -3
  59. package/src/web/frontend/modules/md/style.css +54 -5
  60. package/src/web/frontend/modules/md/use-templates.js +7 -3
  61. package/src/web/frontend/modules/prompts/placeholders.js +98 -0
  62. package/src/web/frontend/modules/prompts/prompt-editor.jsx +169 -0
  63. package/src/web/frontend/modules/prompts/style.css +63 -0
  64. package/src/web/frontend/modules/prompts/template-slots.jsx +87 -0
  65. package/src/web/frontend/page/dir/landing.jsx +11 -0
  66. package/src/web/frontend/page/dir/task.jsx +203 -38
  67. package/src/web/frontend/page/group/index.jsx +8 -2
  68. package/src/web/frontend/page/progress/index.jsx +19 -3
  69. package/src/web/frontend/page/settings/index.jsx +14 -133
  70. package/src/web/frontend/page/settings/prompts-section.jsx +249 -0
  71. package/src/web/frontend/page/settings/style.css +39 -0
  72. package/src/web/frontend/page/templates/index.jsx +27 -0
  73. package/src/web/frontend/panels.jsx +19 -10
  74. package/src/web/frontend/style-v2.css +20 -1
  75. package/src/web/frontend/workspace/areas.js +55 -0
  76. package/src/web/frontend/workspace.js +272 -7
  77. package/src/web/public/assets/Introduction-C4qC8N7g.js +1 -0
  78. package/src/web/public/assets/attach-BZrdOH46.css +1 -0
  79. package/src/web/public/assets/attach-DcyGhCUW.js +1 -0
  80. package/src/web/public/assets/cloud-D0SRl665.js +3 -0
  81. package/src/web/public/assets/dir-B4egV6kV.js +3 -0
  82. package/src/web/public/assets/group-Cbd1PVuv.js +1 -0
  83. package/src/web/public/assets/index-DidFyMnw.js +50 -0
  84. package/src/web/public/assets/index-fhYYxphP.css +1 -0
  85. package/src/web/public/assets/md-history-C29-dF29.js +5 -0
  86. package/src/web/public/assets/member-picker-B7dnMq25.js +1 -0
  87. package/src/web/public/assets/overview-CX9XZ5EO.js +1 -0
  88. package/src/web/public/assets/progress-CnHK_jKP.js +3 -0
  89. package/src/web/public/assets/repos-CyxHTr1L.js +10 -0
  90. package/src/web/public/assets/{settings-DM779jcF.css → settings-C5xCFk_y.css} +1 -1
  91. package/src/web/public/assets/settings-DIvkm7lx.js +1 -0
  92. package/src/web/public/assets/task-CsEvkBW7.js +2 -0
  93. package/src/web/public/assets/template-slots-BybxMN3v.js +1 -0
  94. package/src/web/public/assets/template-slots-CNdlIB1I.css +1 -0
  95. package/src/web/public/assets/templates-BtdK84si.js +2 -0
  96. package/src/web/public/assets/{upload-BupH8dMK.js → upload-jOng3KOU.js} +1 -1
  97. package/src/web/public/index.html +4 -2
  98. package/src/web/public/assets/Introduction-CLTMLBZ5.js +0 -1
  99. package/src/web/public/assets/cloud-B9_h1Ym7.js +0 -3
  100. package/src/web/public/assets/dir-BLUQranN.js +0 -3
  101. package/src/web/public/assets/group-DIeOm80x.js +0 -1
  102. package/src/web/public/assets/index-DA98QEzx.css +0 -1
  103. package/src/web/public/assets/index-t7PgSf_t.js +0 -50
  104. package/src/web/public/assets/md-history-CDVA0KIl.js +0 -5
  105. package/src/web/public/assets/member-picker-9MAmKm9d.js +0 -1
  106. package/src/web/public/assets/overview-DNLRHNzP.js +0 -1
  107. package/src/web/public/assets/progress-C0MiaOW0.js +0 -3
  108. package/src/web/public/assets/repos--i4W5fzj.js +0 -10
  109. package/src/web/public/assets/settings-DSx2Wsto.js +0 -1
  110. package/src/web/public/assets/task-D2-CWZXv.js +0 -2
  111. package/src/web/public/assets/templates-DD6m8DT4.js +0 -2
@@ -0,0 +1,169 @@
1
+ // workflow 契约(#34 阶段 0)—— 冻结类型,尚未接线到 localtask / tasktool。
2
+ //
3
+ // 对照参考方案(Node+TS DAG 动态工作流)在 nx-kv 上的映射:
4
+ // workflowId → 主题 key(cwd 归一化 / repos key;全局 '__GLOBAL__')
5
+ // submit(init) → localtask add / tasktool submitTask(只入队,不构造全图)
6
+ // get(id,node?) → tasktool get / wait(AsyncIterable ≈ 单次或 waitgoal 长轮询)
7
+ // Node → localtask 一条任务(id 数字;状态用 status+completedAt)
8
+ // Edge / blockBy → task.blockBy[] + task.blocksFollowing(闸门)
9
+ // blockgoal → scope=control;onSchedule 决定后继是否 ready(见 localtask/dag.js)
10
+ // waitgoal → scope=node;onGet = getLoop 开启后的阻塞窗口
11
+ // timegoal → scope=workflow|node;目录级 timegoal / 任务级 taskgoal
12
+ //
13
+ // 硬约束(与参考一致,落地时不得破坏):
14
+ // 1. 对外稳定门面只有 submit / get(CLI/HTTP 名可别名,语义不变)
15
+ // 2. 调用方无感内部 DAG / goal 变更
16
+ // 3. goal 是插件族:block=调度侧,wait/time=消费侧
17
+ // 4. 单向依赖、无环;唯一写快照入口 = DagMutator(待抽,现散落在 localtask/service)
18
+ // 5. 快照原子覆盖,不做增量 patch 存储
19
+ // 6. PluginContext 只读;插件不持可变状态
20
+ //
21
+ // 工程约束(相对参考方案的刻意偏离):
22
+ // - 仓库保持 JS ESM + JSDoc,不上平行 TypeScript 引擎
23
+ // - 契约落在 core/;业务仍在 modules/localtask + modules/tasktool
24
+ // - 存储沿用本机 JSON 主题快照;RedisAdapter 属阶段 6,不挡主线
25
+ // - 目标目录规范见同目录 layout.js(禁止平行 src/{facade,store,mutator,…})
26
+
27
+ /** @typedef {'pending'|'ready'|'running'|'success'|'failed'} NodeState */
28
+ /** @typedef {'active'|'completed'|'failed'} WorkflowState */
29
+ /** @typedef {'workflow'|'node'|'control'} GoalScope */
30
+
31
+ /**
32
+ * @typedef {object} PluginSpec
33
+ * @property {string} name blockgoal | waitgoal | timegoal | …
34
+ * @property {GoalScope} scope
35
+ * @property {Record<string, unknown>} [config]
36
+ */
37
+
38
+ /**
39
+ * @typedef {object} WfNode
40
+ * @property {string|number} id
41
+ * @property {'task'|'control'} kind
42
+ * @property {NodeState} state
43
+ * @property {PluginSpec[]} [plugins]
44
+ * @property {unknown} [payload] 业务正文外置时可只留引用
45
+ */
46
+
47
+ /**
48
+ * @typedef {object} WfEdge
49
+ * @property {string|number} from
50
+ * @property {string|number} to
51
+ */
52
+
53
+ /**
54
+ * @typedef {object} WorkflowSnapshot
55
+ * @property {string} workflowId 主题 key
56
+ * @property {WorkflowState} state
57
+ * @property {WfNode[]} nodes
58
+ * @property {WfEdge[]} edges
59
+ * @property {PluginSpec[]} [workflowPlugins]
60
+ * @property {number} revision CAS / 防写撕裂
61
+ * @property {string} [updatedAt]
62
+ */
63
+
64
+ /**
65
+ * @typedef {object} InitMeta
66
+ * @property {string} [cwd]
67
+ * @property {string} [key]
68
+ * @property {string} [text] 首条任务可选;空 submit = 只建主题
69
+ * @property {Record<string, unknown>} [meta]
70
+ */
71
+
72
+ /**
73
+ * 插件只读上下文(禁止写快照;变更必须走 DagMutator)。
74
+ * @typedef {object} PluginContext
75
+ * @property {Readonly<WorkflowSnapshot>} snapshot
76
+ * @property {string|number} [nodeId]
77
+ * @property {AbortSignal} [signal]
78
+ */
79
+
80
+ /**
81
+ * @typedef {object} BasePlugin
82
+ * @property {string} name
83
+ * @property {GoalScope} scope
84
+ * @property {(ctx: PluginContext, config: Record<string, unknown>) => void} [onBind]
85
+ * @property {(ctx: PluginContext) => void} [onSchedule]
86
+ * @property {(ctx: PluginContext) => AsyncGenerator<unknown>} [onGet]
87
+ */
88
+
89
+ /** @type {readonly NodeState[]} */
90
+ export const NODE_STATES = Object.freeze([
91
+ 'pending',
92
+ 'ready',
93
+ 'running',
94
+ 'success',
95
+ 'failed',
96
+ ]);
97
+
98
+ /** @type {readonly WorkflowState[]} */
99
+ export const WORKFLOW_STATES = Object.freeze(['active', 'completed', 'failed']);
100
+
101
+ /** @type {readonly GoalScope[]} */
102
+ export const GOAL_SCOPES = Object.freeze(['workflow', 'node', 'control']);
103
+
104
+ /** 内置 goal 名(注册表校验用) */
105
+ export const BUILTIN_GOALS = Object.freeze({
106
+ blockgoal: 'blockgoal',
107
+ waitgoal: 'waitgoal',
108
+ timegoal: 'timegoal',
109
+ });
110
+
111
+ /**
112
+ * 把现有 localtask 任务行投影成契约节点(只读适配,不改存盘形状)。
113
+ * @param {object} task
114
+ * @returns {WfNode}
115
+ */
116
+ export function taskToNode(task) {
117
+ const completed = !!task?.completedAt;
118
+ const consumed = task?.status === 'consumed';
119
+ /** @type {NodeState} */
120
+ let state = 'pending';
121
+ if (completed) state = 'success';
122
+ else if (consumed) state = 'running';
123
+ else if (task?.ready === true) state = 'ready';
124
+
125
+ /** @type {PluginSpec[]} */
126
+ const plugins = [];
127
+ if (task?.blocksFollowing) {
128
+ plugins.push({ name: BUILTIN_GOALS.blockgoal, scope: 'control', config: {} });
129
+ }
130
+ if (task?.timegoal) {
131
+ plugins.push({
132
+ name: BUILTIN_GOALS.timegoal,
133
+ scope: 'node',
134
+ config: { ...(typeof task.timegoal === 'object' ? task.timegoal : {}) },
135
+ });
136
+ }
137
+
138
+ return {
139
+ id: task?.id,
140
+ kind: task?.blocksFollowing ? 'control' : 'task',
141
+ state,
142
+ plugins,
143
+ payload: { textRef: true },
144
+ };
145
+ }
146
+
147
+ /**
148
+ * 从任务列表推隐式边:显式 blockBy + 闸门 blocksFollowing 的「挡后续」。
149
+ * @param {object[]} tasks
150
+ * @returns {WfEdge[]}
151
+ */
152
+ export const edgesFromTasks = (tasks = []) => {
153
+ /** @type {WfEdge[]} */
154
+ const edges = [];
155
+ const alive = (tasks || []).filter((t) => t && !t.deletedAt && !t.migratedTo);
156
+ for (const t of alive) {
157
+ for (const dep of Array.isArray(t.blockBy) ? t.blockBy : []) {
158
+ edges.push({ from: dep, to: t.id });
159
+ }
160
+ }
161
+ for (let i = 0; i < alive.length; i += 1) {
162
+ const gate = alive[i];
163
+ if (!gate.blocksFollowing) continue;
164
+ for (let j = i + 1; j < alive.length; j += 1) {
165
+ edges.push({ from: gate.id, to: alive[j].id });
166
+ }
167
+ }
168
+ return edges;
169
+ };
@@ -0,0 +1,41 @@
1
+ import { EVENTS } from '../../../core/workflow/event-names.js';
2
+
3
+ /**
4
+ * 轻量 EventBus(进程内)。scheduler 听 dag:mutated。
5
+ */
6
+ export function createEventBus() {
7
+ /** @type {Map<string, Set<Function>>} */
8
+ const listeners = new Map();
9
+
10
+ return {
11
+ EVENTS,
12
+
13
+ on(event, fn) {
14
+ if (!listeners.has(event)) listeners.set(event, new Set());
15
+ listeners.get(event).add(fn);
16
+ return () => listeners.get(event)?.delete(fn);
17
+ },
18
+
19
+ off(event, fn) {
20
+ listeners.get(event)?.delete(fn);
21
+ },
22
+
23
+ emit(event, payload) {
24
+ const set = listeners.get(event);
25
+ if (!set) return;
26
+ for (const fn of [...set]) {
27
+ try {
28
+ fn(payload);
29
+ } catch {
30
+ /* 单订阅者失败不拖垮总线 */
31
+ }
32
+ }
33
+ },
34
+
35
+ clear() {
36
+ listeners.clear();
37
+ },
38
+ };
39
+ }
40
+
41
+ export { EVENTS };
@@ -0,0 +1,6 @@
1
+ // 过渡再导出:实现已下沉 core/workflow/readiness.js
2
+ export {
3
+ normalizeBlockBy,
4
+ isReadyToClaim,
5
+ findFirstReadyPending,
6
+ } from '../../core/workflow/readiness.js';
@@ -0,0 +1,49 @@
1
+ // 主题队列上的引擎装配:SnapshotStore(topic) + bus + mutator + scheduler
2
+ import '../tasktool/plugins/index.js'; // IoC:加载即注册全部 goal
3
+ import { createEventBus } from './bus/index.js';
4
+ import { createDagMutator } from './mutator/index.js';
5
+ import { createScheduler } from './scheduler/index.js';
6
+ import { createTopicSnapshotStore } from './store/index.js';
7
+
8
+ /**
9
+ * @param {{ debounceMs?: number }} [opts]
10
+ */
11
+ export async function createTopicEngine(opts = {}) {
12
+ const store = await createTopicSnapshotStore();
13
+ const bus = createEventBus();
14
+ const mutator = createDagMutator({ store, bus });
15
+ const scheduler = createScheduler({
16
+ store,
17
+ bus,
18
+ debounceMs: opts.debounceMs ?? 10,
19
+ });
20
+ scheduler.start();
21
+ return {
22
+ store,
23
+ bus,
24
+ mutator,
25
+ scheduler,
26
+ async close() {
27
+ scheduler.stop();
28
+ bus.clear();
29
+ },
30
+ };
31
+ }
32
+
33
+ /**
34
+ * 完成任务后:把主题投影进引擎跑一轮就绪(fail-open)。
35
+ * 现网领取仍靠 isReadyToClaim;此步同步 workflowRevision / 闸门投影。
36
+ */
37
+ export async function refreshTopicAfterComplete(topicKey) {
38
+ try {
39
+ const { store, scheduler, close } = await createTopicEngine({ debounceMs: 0 });
40
+ try {
41
+ await store.load(topicKey);
42
+ await scheduler.runOnce(topicKey);
43
+ } finally {
44
+ await close();
45
+ }
46
+ } catch {
47
+ /* 主题不存在或引擎故障不挡 complete */
48
+ }
49
+ }
@@ -298,12 +298,26 @@ export default {
298
298
  },
299
299
  'goal-prompt': { type: 'string', hint: '时间目标的附加要求(随 check 指令一起固化,可省)' },
300
300
  goalPrompt: { type: 'string', hint: '同 --goal-prompt(驼峰写法)' },
301
+ 'block-by': {
302
+ type: 'string',
303
+ hint: 'DAG 依赖:逗号分隔的任务 id(如 12,13)——这些任务全部完成后本条才可领取',
304
+ },
305
+ blockBy: { type: 'string', hint: '同 --block-by(驼峰 / HTTP body)' },
306
+ gate: {
307
+ type: 'boolean',
308
+ hint: '闸门任务:自身未完成(无 completedAt)时,队列里排在它后面的 pending 都不可领',
309
+ },
301
310
  },
302
311
  run: async (ctx) => {
303
312
  // 派任务编排已迁 tasktool/add.js(任务工具语义归 tasktool;命令名不变)。
304
313
  // 落点判定(--board/--project 严格口径 / 正文 frontmatter fail-open)只此一份实现,
305
314
  // CLI、HTTP、面板提交同走这一条链路。
306
315
  const { submitTask } = await import('../tasktool/add.js');
316
+ const rawBlock = ctx.blockBy ?? ctx['block-by'];
317
+ const blockBy = String(rawBlock || '')
318
+ .split(/[,,\s]+/)
319
+ .map((s) => Number(s))
320
+ .filter((n) => Number.isFinite(n) && n > 0);
307
321
  return submitTask({
308
322
  text: ctx.text,
309
323
  cwd: ctx.cwd,
@@ -313,6 +327,8 @@ export default {
313
327
  project: ctx.project,
314
328
  duration: ctx.duration,
315
329
  goalPrompt: ctx.goalPrompt ?? ctx['goal-prompt'],
330
+ blockBy: blockBy.length ? blockBy : undefined,
331
+ blocksFollowing: !!ctx.gate,
316
332
  });
317
333
  },
318
334
  render: renderAdd,
@@ -333,17 +349,34 @@ export default {
333
349
  goalPrompt: { type: 'string', hint: '同 --goal-prompt(驼峰写法,HTTP body 用)' },
334
350
  'clear-goal': { type: 'boolean', hint: '清掉时间目标声明(未领取时)' },
335
351
  clearGoal: { type: 'boolean', hint: '同 --clear-goal(驼峰写法,HTTP body 用)' },
352
+ 'block-by': { type: 'string', hint: '改 DAG 依赖(逗号分隔 id);空串等同 --clear-block-by' },
353
+ blockBy: { type: 'string', hint: '同 --block-by' },
354
+ 'clear-block-by': { type: 'boolean', hint: '清掉 blockBy 依赖' },
355
+ clearBlockBy: { type: 'boolean', hint: '同 --clear-block-by' },
356
+ gate: { type: 'boolean', hint: '设/清闸门(true=挡住后续;false=取消闸门)' },
336
357
  },
337
358
  run: (ctx) => {
338
359
  const gp = ctx.goalPrompt ?? ctx['goal-prompt'];
339
360
  const cg = ctx.clearGoal ?? ctx['clear-goal'];
340
361
  const hasGoalInput = ctx.duration != null || gp != null || cg;
362
+ const rawBlock = ctx.blockBy ?? ctx['block-by'];
363
+ const clearBlockBy = !!(ctx.clearBlockBy ?? ctx['clear-block-by']);
364
+ let blockBy;
365
+ if (!clearBlockBy && rawBlock !== undefined) {
366
+ blockBy = String(rawBlock || '')
367
+ .split(/[,,\s]+/)
368
+ .map((s) => Number(s))
369
+ .filter((n) => Number.isFinite(n) && n > 0);
370
+ }
341
371
  return service.updateTask({
342
372
  id: ctx.id,
343
373
  text: ctx.text,
344
374
  cwd: ctx.cwd,
345
375
  key: ctx.key,
346
376
  goal: hasGoalInput ? { duration: ctx.duration, prompt: gp, clear: !!cg } : undefined,
377
+ blockBy,
378
+ clearBlockBy,
379
+ blocksFollowing: ctx.gate,
347
380
  });
348
381
  },
349
382
  render: (d) =>
@@ -352,7 +385,9 @@ export default {
352
385
  ? `(时间目标:${d.task.timegoal.duration}${d.task.timegoal.prompt ? ' · 附加要求已固化' : ''})`
353
386
  : d.goalChanged === 'cleared'
354
387
  ? '(时间目标已清除)'
355
- : ''),
388
+ : '') +
389
+ (d.task.blocksFollowing ? '(闸门)' : '') +
390
+ (d.task.blockBy && d.task.blockBy.length ? `(依赖 #${d.task.blockBy.join(',#')})` : ''),
356
391
  },
357
392
  {
358
393
  // 附件追加(与云端 todo attach 同构):--path 落**本机附件仓**(零云端)→ 嵌入正文末尾;
@@ -514,9 +549,14 @@ export default {
514
549
  type: 'number',
515
550
  hint: '按序号删除一条收尾指令(--json settings.taskSuffixList 的 1 基序号)——与 --suffix/--no-suffix/--reset-suffix 互斥',
516
551
  },
552
+ ack: {
553
+ type: 'string',
554
+ hint: 'ack 完成总结提示词(agent 完成任务时写完成总结的格式要求;随领取交付的 instruction 给到 agent)。占位符同 --suffix;传空 = 关闭。设置面板「提示词 / 模板」一栏也能配',
555
+ },
517
556
  },
518
557
  run: async (ctx) => {
519
558
  const patch = { timeoutSec: ctx.timeout };
559
+ if (ctx.ack !== undefined) patch.ackPrompt = ctx.ack;
520
560
  const add = ctx['suffix-add'];
521
561
  const removeN = ctx['suffix-remove'];
522
562
  if (add !== undefined || removeN !== undefined) {
@@ -544,7 +584,8 @@ export default {
544
584
  const x = s.suffixEnabled
545
585
  ? `收尾指令已开启(${s.taskSuffixList.length} 条)`
546
586
  : '收尾指令已关闭';
547
- return `已配置等待超时 ${s.timeoutSec} 秒(推荐 ${s.recommendedSec},最大 ${s.maxSec})· ${x}`;
587
+ const ack = s.ackPromptList && s.ackPromptList.length ? ` · ack 提示词 ${s.ackPromptList.length} 条` : '';
588
+ return `已配置等待超时 ${s.timeoutSec} 秒(推荐 ${s.recommendedSec},最大 ${s.maxSec})· ${x}${ack}`;
548
589
  },
549
590
  },
550
591
 
@@ -0,0 +1,153 @@
1
+ // DagMutator —— 全系统唯一允许改 WorkflowSnapshot 的入口
2
+ import { EVENTS } from '../bus/index.js';
3
+ import {
4
+ assertBind,
5
+ assertEdge,
6
+ findNode,
7
+ wouldCreateCycle,
8
+ } from './validate.js';
9
+
10
+ /**
11
+ * @param {{ store: ReturnType<import('../store/index.js').createSnapshotStore>, bus?: { emit: Function } }} deps
12
+ */
13
+ export function createDagMutator({ store, bus }) {
14
+ async function mutate(workflowId, fn) {
15
+ const snap = await store.load(workflowId);
16
+ const expected = snap.revision;
17
+ const draft = structuredClone(snap);
18
+ fn(draft);
19
+ const saved = await store.saveAtomic(draft, { expectedRevision: expected });
20
+ bus?.emit(EVENTS.DAG_MUTATED, { workflowId, revision: saved.revision, snapshot: saved });
21
+ return saved;
22
+ }
23
+
24
+ return {
25
+ async addNode(workflowId, node) {
26
+ if (!node?.id && node?.id !== 0) throw new Error('node.id required');
27
+ return mutate(workflowId, (draft) => {
28
+ if (findNode(draft, node.id)) throw new Error(`node exists: ${node.id}`);
29
+ draft.nodes.push({
30
+ id: node.id,
31
+ kind: node.kind === 'control' ? 'control' : 'task',
32
+ state: node.state || 'pending',
33
+ plugins: Array.isArray(node.plugins) ? node.plugins : [],
34
+ payload: node.payload,
35
+ });
36
+ });
37
+ },
38
+
39
+ async removeNode(workflowId, nodeId) {
40
+ return mutate(workflowId, (draft) => {
41
+ draft.nodes = (draft.nodes || []).filter((n) => String(n.id) !== String(nodeId));
42
+ draft.edges = (draft.edges || []).filter(
43
+ (e) => String(e.from) !== String(nodeId) && String(e.to) !== String(nodeId),
44
+ );
45
+ });
46
+ },
47
+
48
+ async addEdge(workflowId, from, to) {
49
+ return mutate(workflowId, (draft) => {
50
+ assertEdge(draft, from, to);
51
+ if (wouldCreateCycle(draft, from, to)) throw new Error('edge would create cycle');
52
+ const exists = (draft.edges || []).some(
53
+ (e) => String(e.from) === String(from) && String(e.to) === String(to),
54
+ );
55
+ if (!exists) draft.edges.push({ from, to });
56
+ });
57
+ },
58
+
59
+ async removeEdge(workflowId, from, to) {
60
+ return mutate(workflowId, (draft) => {
61
+ draft.edges = (draft.edges || []).filter(
62
+ (e) => !(String(e.from) === String(from) && String(e.to) === String(to)),
63
+ );
64
+ });
65
+ },
66
+
67
+ async bindPlugin(workflowId, target, spec) {
68
+ // target: { workflow: true } | { nodeId }
69
+ // 动态加载 plugins 桶 → IoC 自注册;再调 onBind 规范化 config
70
+ const { getPlugin } = await import('../../tasktool/plugins/index.js');
71
+ return mutate(workflowId, (draft) => {
72
+ const ctx = { snapshot: Object.freeze(structuredClone(draft)) };
73
+ if (target?.workflow) {
74
+ const normalized = assertBind(null, spec, 'workflow');
75
+ const impl = getPlugin(normalized.name);
76
+ if (impl) {
77
+ normalized.config = impl.onBind(
78
+ { ...ctx, nodeId: undefined },
79
+ normalized.config || {},
80
+ );
81
+ }
82
+ const list = draft.workflowPlugins || (draft.workflowPlugins = []);
83
+ if (normalized.name === 'timegoal' && list.some((p) => p.name === 'timegoal')) {
84
+ throw new Error('workflow may bind at most one timegoal');
85
+ }
86
+ list.push(normalized);
87
+ bus?.emit(EVENTS.GOAL_BOUND, { workflowId, target: 'workflow', plugin: normalized });
88
+ return;
89
+ }
90
+ const node = findNode(draft, target.nodeId);
91
+ const normalized = assertBind(node, spec, 'node');
92
+ const impl = getPlugin(normalized.name);
93
+ if (impl) {
94
+ normalized.config = impl.onBind(
95
+ { ...ctx, nodeId: node.id },
96
+ normalized.config || {},
97
+ );
98
+ }
99
+ node.plugins = node.plugins || [];
100
+ node.plugins.push(normalized);
101
+ if (normalized.scope === 'control') node.kind = 'control';
102
+ bus?.emit(EVENTS.GOAL_BOUND, {
103
+ workflowId,
104
+ target: 'node',
105
+ nodeId: node.id,
106
+ plugin: normalized,
107
+ });
108
+ });
109
+ },
110
+
111
+ async unbindPlugin(workflowId, target, name) {
112
+ return mutate(workflowId, (draft) => {
113
+ if (target?.workflow) {
114
+ draft.workflowPlugins = (draft.workflowPlugins || []).filter((p) => p.name !== name);
115
+ bus?.emit(EVENTS.GOAL_UNBOUND, { workflowId, target: 'workflow', name });
116
+ return;
117
+ }
118
+ const node = findNode(draft, target.nodeId);
119
+ if (!node) throw new Error(`node not found: ${target.nodeId}`);
120
+ node.plugins = (node.plugins || []).filter((p) => p.name !== name);
121
+ bus?.emit(EVENTS.GOAL_UNBOUND, {
122
+ workflowId,
123
+ target: 'node',
124
+ nodeId: node.id,
125
+ name,
126
+ });
127
+ });
128
+ },
129
+
130
+ async updatePluginConfig(workflowId, target, name, config) {
131
+ return mutate(workflowId, (draft) => {
132
+ const list = target?.workflow
133
+ ? draft.workflowPlugins || []
134
+ : findNode(draft, target.nodeId)?.plugins || [];
135
+ const plugin = list.find((p) => p.name === name);
136
+ if (!plugin) throw new Error(`plugin not bound: ${name}`);
137
+ plugin.config = { ...(plugin.config || {}), ...config };
138
+ bus?.emit(EVENTS.GOAL_CONFIG_UPDATED, { workflowId, target, name, config: plugin.config });
139
+ });
140
+ },
141
+
142
+ async setNodeState(workflowId, nodeId, state) {
143
+ return mutate(workflowId, (draft) => {
144
+ const node = findNode(draft, nodeId);
145
+ if (!node) throw new Error(`node not found: ${nodeId}`);
146
+ node.state = state;
147
+ bus?.emit(EVENTS.NODE_STATE_CHANGED, { workflowId, nodeId, state });
148
+ });
149
+ },
150
+ };
151
+ }
152
+
153
+ export { assertBind, assertEdge, wouldCreateCycle } from './validate.js';
@@ -0,0 +1,62 @@
1
+ import { assertPluginSpec } from '../../../core/workflow/plugin-registry.js';
2
+
3
+ /** @typedef {import('../../../core/workflow/types.js').WorkflowSnapshot} WorkflowSnapshot */
4
+ /** @typedef {import('../../../core/workflow/types.js').WfNode} WfNode */
5
+ /** @typedef {import('../../../core/workflow/types.js').PluginSpec} PluginSpec */
6
+
7
+ export function findNode(snap, id) {
8
+ return (snap.nodes || []).find((n) => String(n.id) === String(id)) || null;
9
+ }
10
+
11
+ /** 禁止自环;from/to 须存在(可选严格) */
12
+ export function assertEdge(snap, from, to, { requireNodes = true } = {}) {
13
+ if (String(from) === String(to)) throw new Error('self-loop edge forbidden');
14
+ if (requireNodes) {
15
+ if (!findNode(snap, from)) throw new Error(`edge.from missing node: ${from}`);
16
+ if (!findNode(snap, to)) throw new Error(`edge.to missing node: ${to}`);
17
+ }
18
+ }
19
+
20
+ /**
21
+ * control 节点只能绑 control scope;task 不能绑 control;workflow 级只能挂根。
22
+ * @param {WfNode | null} node
23
+ * @param {PluginSpec} spec
24
+ * @param {'node'|'workflow'} target
25
+ */
26
+ export function assertBind(node, spec, target) {
27
+ const normalized = assertPluginSpec(spec);
28
+ if (target === 'workflow') {
29
+ if (normalized.scope !== 'workflow') {
30
+ throw new Error(`workflow plugin must have scope=workflow, got ${normalized.scope}`);
31
+ }
32
+ return normalized;
33
+ }
34
+ if (!node) throw new Error('node required for node-level bind');
35
+ if (node.kind === 'control' && normalized.scope !== 'control') {
36
+ throw new Error('control node may only bind control-scope plugins');
37
+ }
38
+ // task + control 插件:允许,由 mutator 升级 kind→control(现网闸门常从普通任务打 --gate)
39
+ return normalized;
40
+ }
41
+
42
+ export function wouldCreateCycle(snap, from, to) {
43
+ // DFS:从 to 能否走到 from
44
+ const adj = new Map();
45
+ for (const e of snap.edges || []) {
46
+ const a = String(e.from);
47
+ if (!adj.has(a)) adj.set(a, []);
48
+ adj.get(a).push(String(e.to));
49
+ }
50
+ const start = String(to);
51
+ const target = String(from);
52
+ const stack = [start];
53
+ const seen = new Set();
54
+ while (stack.length) {
55
+ const cur = stack.pop();
56
+ if (cur === target) return true;
57
+ if (seen.has(cur)) continue;
58
+ seen.add(cur);
59
+ for (const n of adj.get(cur) || []) stack.push(n);
60
+ }
61
+ return false;
62
+ }
@@ -0,0 +1,55 @@
1
+ // Scheduler —— 听 bus → 拓扑就绪;永不调用 onGet
2
+ import { EVENTS } from '../bus/index.js';
3
+ import { driveReadyStates } from './state-drive.js';
4
+
5
+ /**
6
+ * @param {{ store: ReturnType<import('../store/index.js').createSnapshotStore>, bus: ReturnType<import('../bus/index.js').createEventBus>, debounceMs?: number }} deps
7
+ */
8
+ export function createScheduler({ store, bus, debounceMs = 10 }) {
9
+ /** @type {Map<string, ReturnType<typeof setTimeout>>} */
10
+ const timers = new Map();
11
+ let unsub = null;
12
+
13
+ async function runOnce(workflowId) {
14
+ const snap = await store.load(workflowId);
15
+ const expected = snap.revision;
16
+ const draft = structuredClone(snap);
17
+ const { changed, readyIds } = driveReadyStates(draft);
18
+ if (!changed) return { changed: false, readyIds };
19
+ const saved = await store.saveAtomic(draft, { expectedRevision: expected });
20
+ for (const nodeId of readyIds) {
21
+ bus.emit(EVENTS.NODE_STATE_CHANGED, { workflowId, nodeId, state: 'ready' });
22
+ }
23
+ return { changed: true, readyIds, revision: saved.revision };
24
+ }
25
+
26
+ function schedule(workflowId) {
27
+ const prev = timers.get(workflowId);
28
+ if (prev) clearTimeout(prev);
29
+ timers.set(
30
+ workflowId,
31
+ setTimeout(() => {
32
+ timers.delete(workflowId);
33
+ runOnce(workflowId).catch(() => {});
34
+ }, debounceMs),
35
+ );
36
+ }
37
+
38
+ function start() {
39
+ if (unsub) return;
40
+ unsub = bus.on(EVENTS.DAG_MUTATED, (payload) => {
41
+ if (payload?.workflowId) schedule(payload.workflowId);
42
+ });
43
+ }
44
+
45
+ function stop() {
46
+ if (unsub) unsub();
47
+ unsub = null;
48
+ for (const t of timers.values()) clearTimeout(t);
49
+ timers.clear();
50
+ }
51
+
52
+ return { start, stop, runOnce, schedule };
53
+ }
54
+
55
+ export { driveReadyStates } from './state-drive.js';
@@ -0,0 +1,30 @@
1
+ import { isNodeReady } from '../../../core/workflow/readiness.js';
2
+ import { isBarrierOpen } from '../../tasktool/plugins/blockgoal.js';
3
+
4
+ /** @typedef {import('../../../core/workflow/types.js').WorkflowSnapshot} WorkflowSnapshot */
5
+
6
+ /**
7
+ * 一轮调度:pending→ready(不自动进 running;running 由业务/领取侧推进)。
8
+ * @param {WorkflowSnapshot} snap
9
+ * @returns {{ changed: boolean, readyIds: Array<string|number> }}
10
+ */
11
+ export function driveReadyStates(snap) {
12
+ const readyIds = [];
13
+ let changed = false;
14
+ for (const node of snap.nodes || []) {
15
+ if (node.state !== 'pending' && node.state !== 'ready') continue;
16
+ const ok = isNodeReady(snap, node, isBarrierOpen);
17
+ if (ok && node.state !== 'ready') {
18
+ node.state = 'ready';
19
+ changed = true;
20
+ readyIds.push(node.id);
21
+ } else if (!ok && node.state === 'ready') {
22
+ // 动态加回屏障 → 退回 pending
23
+ node.state = 'pending';
24
+ changed = true;
25
+ } else if (ok) {
26
+ readyIds.push(node.id);
27
+ }
28
+ }
29
+ return { changed, readyIds };
30
+ }