nx-kv 0.18.0 → 0.20.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 (126) hide show
  1. package/CHANGELOG.md +167 -0
  2. package/assets/kv-get/references/wait-workflow.md +6 -1
  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 +114 -0
  10. package/src/core/workflow/readiness.js +193 -0
  11. package/src/core/workflow/snapshot.example.json +46 -0
  12. package/src/core/workflow/types.js +172 -0
  13. package/src/modules/localtask/bus/index.js +41 -0
  14. package/src/modules/localtask/dag.js +8 -0
  15. package/src/modules/localtask/engine.js +49 -0
  16. package/src/modules/localtask/index.js +81 -7
  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 +306 -31
  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 +131 -0
  27. package/src/modules/tasktool/add.js +12 -23
  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/group-store.js +28 -0
  34. package/src/modules/tasktool/plugins/base.js +92 -0
  35. package/src/modules/tasktool/plugins/blockgoal.js +23 -0
  36. package/src/modules/tasktool/plugins/container.js +47 -0
  37. package/src/modules/tasktool/plugins/discover.js +45 -0
  38. package/src/modules/tasktool/plugins/index.js +20 -0
  39. package/src/modules/tasktool/plugins/runtime.js +69 -0
  40. package/src/modules/tasktool/plugins/taskgoal-store.js +100 -0
  41. package/src/modules/tasktool/plugins/taskgoal.js +17 -0
  42. package/src/modules/tasktool/plugins/timegoal-store.js +748 -0
  43. package/src/modules/tasktool/plugins/timegoal.js +51 -0
  44. package/src/modules/tasktool/plugins/waitgoal-config.js +84 -0
  45. package/src/modules/tasktool/plugins/waitgoal.js +75 -0
  46. package/src/modules/tasktool/taskgoal.js +2 -100
  47. package/src/modules/tasktool/timegoal.js +2 -748
  48. package/src/modules/tasktool/update.js +70 -0
  49. package/src/modules/tasktool/wait.js +25 -0
  50. package/src/modules/templates/index.js +21 -0
  51. package/src/modules/templates/service.js +62 -9
  52. package/src/shared/frontmatter.js +28 -1
  53. package/src/web/frontend/App.jsx +20 -50
  54. package/src/web/frontend/components/icons.jsx +11 -0
  55. package/src/web/frontend/components/layout/breadcrumb.jsx +38 -0
  56. package/src/web/frontend/components/layout/crumbs.js +85 -0
  57. package/src/web/frontend/components/layout/route-crumb.jsx +33 -0
  58. package/src/web/frontend/components/layout/route-history.js +27 -0
  59. package/src/web/frontend/components/md/md-panes.jsx +10 -6
  60. package/src/web/frontend/components/md/shortcut-sheet.jsx +1 -0
  61. package/src/web/frontend/components/md/tool-bar.jsx +11 -0
  62. package/src/web/frontend/components/sidebar/index.jsx +6 -5
  63. package/src/web/frontend/components/sidebar/side-state.js +3 -2
  64. package/src/web/frontend/modules/md/md-parse.js +122 -3
  65. package/src/web/frontend/modules/md/style.css +54 -5
  66. package/src/web/frontend/modules/md/use-templates.js +7 -3
  67. package/src/web/frontend/modules/prompts/placeholders.js +98 -0
  68. package/src/web/frontend/modules/prompts/prompt-editor.jsx +253 -0
  69. package/src/web/frontend/modules/prompts/style.css +78 -0
  70. package/src/web/frontend/modules/prompts/template-slots.jsx +87 -0
  71. package/src/web/frontend/page/cloud/index.jsx +2 -0
  72. package/src/web/frontend/page/dag/index.jsx +775 -0
  73. package/src/web/frontend/page/dir/dag-editor.jsx +180 -0
  74. package/src/web/frontend/page/dir/index.jsx +77 -2
  75. package/src/web/frontend/page/dir/landing.jsx +175 -55
  76. package/src/web/frontend/page/dir/task.jsx +239 -40
  77. package/src/web/frontend/page/group/index.jsx +196 -24
  78. package/src/web/frontend/page/overview/index.jsx +2 -0
  79. package/src/web/frontend/page/progress/index.jsx +19 -3
  80. package/src/web/frontend/page/repos/index.jsx +2 -0
  81. package/src/web/frontend/page/settings/index.jsx +113 -172
  82. package/src/web/frontend/page/settings/prompts-section.jsx +239 -0
  83. package/src/web/frontend/page/settings/style.css +85 -6
  84. package/src/web/frontend/page/templates/index.jsx +29 -0
  85. package/src/web/frontend/panels.jsx +25 -10
  86. package/src/web/frontend/style-v2.css +244 -7
  87. package/src/web/frontend/workspace/areas.js +56 -0
  88. package/src/web/frontend/workspace.js +286 -11
  89. package/src/web/public/assets/Introduction-BnbM3LXZ.js +1 -0
  90. package/src/web/public/assets/attach-BZrdOH46.css +1 -0
  91. package/src/web/public/assets/attach-v8BxRJ7p.js +1 -0
  92. package/src/web/public/assets/cloud-DlVOlEuX.js +3 -0
  93. package/src/web/public/assets/dag-B_EovnBK.js +1 -0
  94. package/src/web/public/assets/dir-DOQkmLNI.js +3 -0
  95. package/src/web/public/assets/group-CQ9U4NiQ.js +1 -0
  96. package/src/web/public/assets/index-Cg0WaaAi.css +1 -0
  97. package/src/web/public/assets/index-DFHqf4ue.js +50 -0
  98. package/src/web/public/assets/md-history-DDQvoTFy.js +5 -0
  99. package/src/web/public/assets/member-picker-zypl1Wuc.js +1 -0
  100. package/src/web/public/assets/overview-uWj8gdmN.js +1 -0
  101. package/src/web/public/assets/progress-D2cyYcIw.js +3 -0
  102. package/src/web/public/assets/repos-lSywsxfo.js +10 -0
  103. package/src/web/public/assets/route-crumb-BI31PVXo.js +1 -0
  104. package/src/web/public/assets/settings-BVcCJUvg.js +3 -0
  105. package/src/web/public/assets/settings-CRK86fnJ.css +1 -0
  106. package/src/web/public/assets/task-Dj77xNZX.js +2 -0
  107. package/src/web/public/assets/template-slots-BjfVnHFQ.js +1 -0
  108. package/src/web/public/assets/template-slots-UVa4FnPn.css +1 -0
  109. package/src/web/public/assets/templates-B9VLtDMa.js +2 -0
  110. package/src/web/public/assets/{upload-BupH8dMK.js → upload-DvoSV9Cl.js} +1 -1
  111. package/src/web/public/index.html +4 -2
  112. package/src/web/public/assets/Introduction-CLTMLBZ5.js +0 -1
  113. package/src/web/public/assets/cloud-B9_h1Ym7.js +0 -3
  114. package/src/web/public/assets/dir-BLUQranN.js +0 -3
  115. package/src/web/public/assets/group-DIeOm80x.js +0 -1
  116. package/src/web/public/assets/index-DA98QEzx.css +0 -1
  117. package/src/web/public/assets/index-t7PgSf_t.js +0 -50
  118. package/src/web/public/assets/md-history-CDVA0KIl.js +0 -5
  119. package/src/web/public/assets/member-picker-9MAmKm9d.js +0 -1
  120. package/src/web/public/assets/overview-DNLRHNzP.js +0 -1
  121. package/src/web/public/assets/progress-C0MiaOW0.js +0 -3
  122. package/src/web/public/assets/repos--i4W5fzj.js +0 -10
  123. package/src/web/public/assets/settings-DM779jcF.css +0 -1
  124. package/src/web/public/assets/settings-DSx2Wsto.js +0 -1
  125. package/src/web/public/assets/task-D2-CWZXv.js +0 -2
  126. package/src/web/public/assets/templates-DD6m8DT4.js +0 -2
@@ -0,0 +1,193 @@
1
+ // 拓扑就绪(自 localtask/dag.js 下沉)。任务行与快照节点两套入口。
2
+ //
3
+ // blockBy 支持:
4
+ // - 本地 id(number)——同队列依赖(兼容旧存盘)
5
+ // - 跨队列引用 `"<topicKey>:<taskId>"`——组编排跨项目边;get 时跨 topic 解析
6
+
7
+ /** topicKey:id —— key 允许字母数字与 _-(含 __GLOBAL__) */
8
+ const FOREIGN_RE = /^([A-Za-z0-9_-]+):(\d+)$/;
9
+
10
+ /**
11
+ * @typedef {{ kind: 'local', id: number } | { kind: 'foreign', key: string, id: number }} DepRef
12
+ */
13
+
14
+ /**
15
+ * 解析单条依赖引用。
16
+ * @param {unknown} x
17
+ * @returns {DepRef | null}
18
+ */
19
+ export function parseDepRef(x) {
20
+ if (typeof x === 'number' && Number.isFinite(x) && x > 0) {
21
+ return { kind: 'local', id: Math.trunc(x) };
22
+ }
23
+ const s = String(x ?? '').trim();
24
+ if (!s) return null;
25
+ const m = FOREIGN_RE.exec(s);
26
+ if (m) return { kind: 'foreign', key: m[1], id: Number(m[2]) };
27
+ // 纯数字字符串 → 本地 id(避免把 "12" 当 foreign)
28
+ if (/^\d+$/.test(s)) {
29
+ const n = Number(s);
30
+ if (Number.isFinite(n) && n > 0) return { kind: 'local', id: n };
31
+ }
32
+ return null;
33
+ }
34
+
35
+ /** @param {DepRef} ref @returns {number|string} */
36
+ export function formatDepRef(ref) {
37
+ if (!ref) return '';
38
+ if (ref.kind === 'foreign') return `${ref.key}:${ref.id}`;
39
+ return ref.id;
40
+ }
41
+
42
+ /**
43
+ * 规范化 blockBy:本地正整数 id + 跨队列 "key:id"、去重、丢掉本地自身。
44
+ * @param {unknown} raw
45
+ * @param {number|string} [selfId]
46
+ * @returns {Array<number|string>}
47
+ */
48
+ export function normalizeBlockBy(raw, selfId) {
49
+ const self = Number(selfId);
50
+ const seen = new Set();
51
+ const out = [];
52
+
53
+ /** @type {unknown[]} */
54
+ let items = [];
55
+ if (raw == null || raw === '') items = [];
56
+ else if (Array.isArray(raw)) items = raw;
57
+ else if (typeof raw === 'string' && /[,,\s]/.test(raw) && !FOREIGN_RE.test(raw.trim())) {
58
+ items = raw.split(/[,,\s]+/).filter(Boolean);
59
+ } else {
60
+ items = [raw];
61
+ }
62
+
63
+ // 数组元素里也可能是逗号串(HTTP 偶发)
64
+ const flat = [];
65
+ for (const x of items) {
66
+ if (typeof x === 'string' && /[,,]/.test(x) && !FOREIGN_RE.test(x.trim())) {
67
+ flat.push(...x.split(/[,,\s]+/).filter(Boolean));
68
+ } else {
69
+ flat.push(x);
70
+ }
71
+ }
72
+
73
+ for (const x of flat) {
74
+ const ref = parseDepRef(x);
75
+ if (!ref) continue;
76
+ if (ref.kind === 'local') {
77
+ if (Number.isFinite(self) && ref.id === self) continue;
78
+ const token = String(ref.id);
79
+ if (seen.has(`L:${token}`)) continue;
80
+ seen.add(`L:${token}`);
81
+ out.push(ref.id);
82
+ } else {
83
+ const token = `${ref.key}:${ref.id}`;
84
+ if (seen.has(`F:${token}`)) continue;
85
+ seen.add(`F:${token}`);
86
+ out.push(token);
87
+ }
88
+ }
89
+ return out;
90
+ }
91
+
92
+ function isAlive(t) {
93
+ return t && !t.deletedAt && !t.migratedTo;
94
+ }
95
+
96
+ function isCompleted(t) {
97
+ return isAlive(t) && !!t.completedAt;
98
+ }
99
+
100
+ function isPendingLike(t) {
101
+ return isAlive(t) && t.status !== 'consumed';
102
+ }
103
+
104
+ /**
105
+ * @typedef {object} ReadyOpts
106
+ * @property {(topicKey: string, taskId: number) => object|null|undefined} [resolveForeign]
107
+ * 跨队列依赖解析;缺席或返回空 = fail-open(挡不住)
108
+ */
109
+
110
+ /**
111
+ * 某条 pending 现在能不能领(任务行模型)。
112
+ * @param {object} task
113
+ * @param {object[]} all
114
+ * @param {ReadyOpts} [opts]
115
+ */
116
+ export function isReadyToClaim(task, all = [], opts = {}) {
117
+ if (!isPendingLike(task)) return false;
118
+ const byId = new Map((all || []).filter(isAlive).map((t) => [Number(t.id), t]));
119
+
120
+ const deps = normalizeBlockBy(task.blockBy, task.id);
121
+ for (const d of deps) {
122
+ const ref = parseDepRef(d);
123
+ if (!ref) continue;
124
+ let dep = null;
125
+ if (ref.kind === 'local') {
126
+ dep = byId.get(ref.id) || null;
127
+ } else if (typeof opts.resolveForeign === 'function') {
128
+ const found = opts.resolveForeign(ref.key, ref.id);
129
+ dep = found && isAlive(found) ? found : null;
130
+ } else {
131
+ // 无解析器:跨队列依赖无法验证 → fail-open(与「依赖缺失」同口径)
132
+ continue;
133
+ }
134
+ if (!dep) continue;
135
+ if (!isCompleted(dep)) return false;
136
+ }
137
+
138
+ const idx = (all || []).indexOf(task);
139
+ const order = all || [];
140
+ const myPos = idx >= 0 ? idx : order.findIndex((t) => Number(t.id) === Number(task.id));
141
+ if (myPos < 0) return true;
142
+ for (let i = 0; i < myPos; i += 1) {
143
+ const prev = order[i];
144
+ if (!isAlive(prev) || !prev.blocksFollowing) continue;
145
+ if (!isCompleted(prev)) return false;
146
+ }
147
+ return true;
148
+ }
149
+
150
+ /**
151
+ * 按数组序找第一条可领取的 pending;没有 → null
152
+ * @param {object[]} tasks
153
+ * @param {ReadyOpts} [opts]
154
+ */
155
+ export function findFirstReadyPending(tasks = [], opts = {}) {
156
+ for (const t of tasks || []) {
157
+ if (isReadyToClaim(t, tasks, opts)) return t;
158
+ }
159
+ return null;
160
+ }
161
+
162
+ /**
163
+ * 快照节点是否就绪(边 + control/blockgoal 前驱须 success)。
164
+ * @param {import('./types.js').WorkflowSnapshot} snap
165
+ * @param {import('./types.js').WfNode} node
166
+ * @param {(snap: import('./types.js').WorkflowSnapshot, nodeId: string|number) => boolean} [isBarrierOpen]
167
+ */
168
+ export function isNodeReady(snap, node, isBarrierOpen) {
169
+ if (!node || node.state === 'success' || node.state === 'failed' || node.state === 'running') {
170
+ return false;
171
+ }
172
+ if (node.state !== 'pending' && node.state !== 'ready') return false;
173
+
174
+ const preds = (snap.edges || []).filter((e) => String(e.to) === String(node.id));
175
+ const byId = new Map((snap.nodes || []).map((n) => [String(n.id), n]));
176
+
177
+ for (const e of preds) {
178
+ const pred = byId.get(String(e.from));
179
+ if (!pred) continue;
180
+ const isControl =
181
+ pred.kind === 'control' ||
182
+ (pred.plugins || []).some((p) => p.name === 'blockgoal' || p.scope === 'control');
183
+ if (isControl) {
184
+ const open = isBarrierOpen
185
+ ? isBarrierOpen(snap, pred.id)
186
+ : pred.state === 'success';
187
+ if (!open) return false;
188
+ continue;
189
+ }
190
+ if (pred.state !== 'success') return false;
191
+ }
192
+ return true;
193
+ }
@@ -0,0 +1,46 @@
1
+ {
2
+ "workflowId": "local/nx-kv",
3
+ "state": "active",
4
+ "revision": 1,
5
+ "updatedAt": "2026-11-04T08:00:00.000Z",
6
+ "workflowPlugins": [
7
+ {
8
+ "name": "timegoal",
9
+ "scope": "workflow",
10
+ "config": { "duration": "45m", "prompt": "目录级静默超时示例" }
11
+ }
12
+ ],
13
+ "nodes": [
14
+ {
15
+ "id": 10,
16
+ "kind": "task",
17
+ "state": "success",
18
+ "plugins": [],
19
+ "payload": { "textRef": true }
20
+ },
21
+ {
22
+ "id": 11,
23
+ "kind": "control",
24
+ "state": "running",
25
+ "plugins": [{ "name": "blockgoal", "scope": "control", "config": {} }],
26
+ "payload": { "textRef": true }
27
+ },
28
+ {
29
+ "id": 12,
30
+ "kind": "task",
31
+ "state": "pending",
32
+ "plugins": [
33
+ {
34
+ "name": "waitgoal",
35
+ "scope": "node",
36
+ "config": { "waitMinutes": 3 }
37
+ }
38
+ ],
39
+ "payload": { "textRef": true }
40
+ }
41
+ ],
42
+ "edges": [
43
+ { "from": 10, "to": 11 },
44
+ { "from": 11, "to": 12 }
45
+ ]
46
+ }
@@ -0,0 +1,172 @@
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
+ // 引擎快照只认本队列数字边;跨队列 "key:id" 留给 get/ready 解析
159
+ const n = Number(dep);
160
+ if (!Number.isFinite(n) || n <= 0 || String(dep).includes(':')) continue;
161
+ edges.push({ from: n, to: t.id });
162
+ }
163
+ }
164
+ for (let i = 0; i < alive.length; i += 1) {
165
+ const gate = alive[i];
166
+ if (!gate.blocksFollowing) continue;
167
+ for (let j = i + 1; j < alive.length; j += 1) {
168
+ edges.push({ from: gate.id, to: alive[j].id });
169
+ }
170
+ }
171
+ return edges;
172
+ };
@@ -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,8 @@
1
+ // 过渡再导出:实现已下沉 core/workflow/readiness.js
2
+ export {
3
+ parseDepRef,
4
+ formatDepRef,
5
+ normalizeBlockBy,
6
+ isReadyToClaim,
7
+ findFirstReadyPending,
8
+ } 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
+ }
@@ -203,8 +203,14 @@ export default {
203
203
  key: KEY,
204
204
  text: { type: 'string', hint: '修改后的任务正文(Markdown);不给则只重开不改内容' },
205
205
  },
206
- run: (ctx) => service.reopenTask({ id: ctx.id, cwd: ctx.cwd, key: ctx.key, text: ctx.text }),
207
- render: (d) => `已重开任务 #${d.id} @ ${d.name}(回到待领取,第 ${d.task.reopenCount} 次重开)`,
206
+ run: async (ctx) => {
207
+ // 重开也可能带着改过的归属(--text 的 frontmatter.project 变了)→ 同样搬家
208
+ const { reopenTask } = await import('../tasktool/update.js');
209
+ return reopenTask({ id: ctx.id, cwd: ctx.cwd, key: ctx.key, text: ctx.text });
210
+ },
211
+ render: (d) =>
212
+ `已重开任务 #${d.id} @ ${d.name}(回到待领取,第 ${d.task.reopenCount} 次重开)` +
213
+ (d.moved && d.movedFrom ? `;已改归属项目,原 ${d.movedFrom.name} #${d.movedFrom.id}` : ''),
208
214
  },
209
215
  {
210
216
  // 完成门禁:带时间目标的任务未到点拒绝标记完成(提示派 sub agent 重提需求)。
@@ -298,12 +304,27 @@ export default {
298
304
  },
299
305
  'goal-prompt': { type: 'string', hint: '时间目标的附加要求(随 check 指令一起固化,可省)' },
300
306
  goalPrompt: { type: 'string', hint: '同 --goal-prompt(驼峰写法)' },
307
+ 'block-by': {
308
+ type: 'string',
309
+ hint: 'DAG 依赖:逗号分隔的任务 id(如 12,13)——这些任务全部完成后本条才可领取',
310
+ },
311
+ blockBy: { type: 'string', hint: '同 --block-by(驼峰 / HTTP body)' },
312
+ gate: {
313
+ type: 'boolean',
314
+ hint: '闸门任务:自身未完成(无 completedAt)时,队列里排在它后面的 pending 都不可领',
315
+ },
301
316
  },
302
317
  run: async (ctx) => {
303
318
  // 派任务编排已迁 tasktool/add.js(任务工具语义归 tasktool;命令名不变)。
304
319
  // 落点判定(--board/--project 严格口径 / 正文 frontmatter fail-open)只此一份实现,
305
320
  // CLI、HTTP、面板提交同走这一条链路。
306
321
  const { submitTask } = await import('../tasktool/add.js');
322
+ const rawBlock = ctx.blockBy ?? ctx['block-by'];
323
+ // 支持本地 id 与跨队列 "topicKey:id"(组编排边);空 → undefined
324
+ const { normalizeBlockBy } = await import('./dag.js');
325
+ const blockBy = rawBlock != null && String(rawBlock).trim()
326
+ ? normalizeBlockBy(String(rawBlock), 0)
327
+ : [];
307
328
  return submitTask({
308
329
  text: ctx.text,
309
330
  cwd: ctx.cwd,
@@ -313,6 +334,8 @@ export default {
313
334
  project: ctx.project,
314
335
  duration: ctx.duration,
315
336
  goalPrompt: ctx.goalPrompt ?? ctx['goal-prompt'],
337
+ blockBy: blockBy.length ? blockBy : undefined,
338
+ blocksFollowing: !!ctx.gate,
316
339
  });
317
340
  },
318
341
  render: renderAdd,
@@ -333,26 +356,54 @@ export default {
333
356
  goalPrompt: { type: 'string', hint: '同 --goal-prompt(驼峰写法,HTTP body 用)' },
334
357
  'clear-goal': { type: 'boolean', hint: '清掉时间目标声明(未领取时)' },
335
358
  clearGoal: { type: 'boolean', hint: '同 --clear-goal(驼峰写法,HTTP body 用)' },
359
+ 'block-by': { type: 'string', hint: '改 DAG 依赖(逗号分隔 id);空串等同 --clear-block-by' },
360
+ blockBy: { type: 'string', hint: '同 --block-by' },
361
+ 'clear-block-by': { type: 'boolean', hint: '清掉 blockBy 依赖' },
362
+ clearBlockBy: { type: 'boolean', hint: '同 --clear-block-by' },
363
+ gate: { type: 'boolean', hint: '设/清闸门(true=挡住后续;false=取消闸门)' },
336
364
  },
337
- run: (ctx) => {
365
+ run: async (ctx) => {
338
366
  const gp = ctx.goalPrompt ?? ctx['goal-prompt'];
339
367
  const cg = ctx.clearGoal ?? ctx['clear-goal'];
340
368
  const hasGoalInput = ctx.duration != null || gp != null || cg;
341
- return service.updateTask({
369
+ const rawBlock = ctx.blockBy ?? ctx['block-by'];
370
+ const clearBlockBy = !!(ctx.clearBlockBy ?? ctx['clear-block-by']);
371
+ let blockBy;
372
+ if (!clearBlockBy && rawBlock !== undefined) {
373
+ // 本地 id + "topicKey:id";数组 body(面板)与逗号串都走 normalizeBlockBy
374
+ const { normalizeBlockBy } = await import('./dag.js');
375
+ blockBy = normalizeBlockBy(
376
+ Array.isArray(rawBlock) ? rawBlock : String(rawBlock || ''),
377
+ ctx.id,
378
+ );
379
+ }
380
+ // 改归属即搬家(任务 #43):正文 effective project 变了 → 任务迁到新项目的队列。
381
+ // 编排在 tasktool/update.js,与派任务(tasktool/add.js)同一套落点判定。
382
+ const { updateTask: editTask } = await import('../tasktool/update.js');
383
+ return editTask({
342
384
  id: ctx.id,
343
385
  text: ctx.text,
344
386
  cwd: ctx.cwd,
345
387
  key: ctx.key,
346
388
  goal: hasGoalInput ? { duration: ctx.duration, prompt: gp, clear: !!cg } : undefined,
389
+ blockBy,
390
+ clearBlockBy,
391
+ blocksFollowing: ctx.gate,
347
392
  });
348
393
  },
349
394
  render: (d) =>
350
- `已更新主题「${d.name}」#${d.task.id}: ${d.task.text}` +
395
+ (d.moved
396
+ ? `已改归属项目:迁到主题「${d.name}」#${d.task.id}` +
397
+ (d.movedFrom ? `(原 ${d.movedFrom.name} #${d.movedFrom.id})` : '')
398
+ : `已更新主题「${d.name}」#${d.task.id}`) +
399
+ `: ${d.task.text}` +
351
400
  (d.goalChanged === 'set'
352
401
  ? `(时间目标:${d.task.timegoal.duration}${d.task.timegoal.prompt ? ' · 附加要求已固化' : ''})`
353
402
  : d.goalChanged === 'cleared'
354
403
  ? '(时间目标已清除)'
355
- : ''),
404
+ : '') +
405
+ (d.task.blocksFollowing ? '(闸门)' : '') +
406
+ (d.task.blockBy && d.task.blockBy.length ? `(依赖 #${d.task.blockBy.join(',#')})` : ''),
356
407
  },
357
408
  {
358
409
  // 附件追加(与云端 todo attach 同构):--path 落**本机附件仓**(零云端)→ 嵌入正文末尾;
@@ -514,9 +565,31 @@ export default {
514
565
  type: 'number',
515
566
  hint: '按序号删除一条收尾指令(--json settings.taskSuffixList 的 1 基序号)——与 --suffix/--no-suffix/--reset-suffix 互斥',
516
567
  },
568
+ ack: {
569
+ type: 'string',
570
+ hint: 'ack 完成总结提示词(agent 完成任务时写完成总结的格式要求;随领取交付的 instruction 给到 agent)。占位符同 --suffix;传空 = 关闭。设置面板「提示词 / 模板」一栏也能配',
571
+ },
572
+ // **整体替换**多条列表(面板「提示词 / 模板」一栏用这个保存;服务层本就吃列表,
573
+ // 但此前 action 只暴露单条 flag → 面板保存 400 且静默无效,2026-11-04 #41 实测发现)。
574
+ 'suffix-list': { type: 'array', hint: '整体替换收尾指令列表(多条,一项一条)' },
575
+ suffixList: { type: 'array', hint: '同 --suffix-list(驼峰写法,HTTP body 用)' },
576
+ 'ack-list': { type: 'array', hint: '整体替换 ack 完成总结提示词列表(多条)' },
577
+ ackList: { type: 'array', hint: '同 --ack-list(驼峰写法,HTTP body 用)' },
517
578
  },
518
579
  run: async (ctx) => {
519
580
  const patch = { timeoutSec: ctx.timeout };
581
+ if (ctx.ack !== undefined) patch.ackPrompt = ctx.ack;
582
+ const suffixList = ctx.suffixList ?? ctx['suffix-list'];
583
+ const ackList = ctx.ackList ?? ctx['ack-list'];
584
+ if (suffixList !== undefined || ackList !== undefined) {
585
+ if (ctx.suffix !== undefined || ctx['no-suffix'] || ctx['reset-suffix']
586
+ || ctx['suffix-add'] !== undefined || ctx['suffix-remove'] !== undefined) {
587
+ throw badInput('--suffix-list 不能与 --suffix / --no-suffix / --reset-suffix / --suffix-add / --suffix-remove 同用');
588
+ }
589
+ if (ctx.ack !== undefined) throw badInput('--ack-list 不能与 --ack 同用');
590
+ if (suffixList !== undefined) patch.taskSuffix = suffixList;
591
+ if (ackList !== undefined) patch.ackPrompt = ackList;
592
+ }
520
593
  const add = ctx['suffix-add'];
521
594
  const removeN = ctx['suffix-remove'];
522
595
  if (add !== undefined || removeN !== undefined) {
@@ -544,7 +617,8 @@ export default {
544
617
  const x = s.suffixEnabled
545
618
  ? `收尾指令已开启(${s.taskSuffixList.length} 条)`
546
619
  : '收尾指令已关闭';
547
- return `已配置等待超时 ${s.timeoutSec} 秒(推荐 ${s.recommendedSec},最大 ${s.maxSec})· ${x}`;
620
+ const ack = s.ackPromptList && s.ackPromptList.length ? ` · ack 提示词 ${s.ackPromptList.length} 条` : '';
621
+ return `已配置等待超时 ${s.timeoutSec} 秒(推荐 ${s.recommendedSec},最大 ${s.maxSec})· ${x}${ack}`;
548
622
  },
549
623
  },
550
624