@suifei/dsh-ai-team 0.4.87 → 0.4.89

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,53 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.89 - 2026-11-14
4
+
5
+ **有界自主:Human 每次操作后团队最多自主续开 `pmoMaxRounds` 批任务;心跳不再掩盖卡死任务(Issue #1 主因之二)**
6
+
7
+ 一句「在吗」之后,看板一清空 PMO 就每 10 分钟开会、自拟下一批 Task,没有上限;主理人回收结果后
8
+ 也会自己接着开卡。两条路径都不受控,是「7 小时 / 两百多个子代理」的另一半成因。
9
+
10
+ - 轮次口径(`lib/ledger/fold.js`,`FOLD_STATE_VERSION` 3→4,旧检查点作废重折):一「轮」=
11
+ 看板清空后成员开出的新一批 Task,PMO 定时推进与主理人自己续开同一口径。任何 Human 作者事件
12
+ 续满预算;Human 那一批不计轮;预算只由 Human 续,成员不能给自己续;
13
+ - 闸门(`lib/host/service.js`):成员在空看板上建卡且预算用尽 → `E_PMO_PAUSED`;PMO 定时推进
14
+ 前同样查预算(`pmoGate`)。用尽时账本记 `project/pmo-capped`、主流发一条 milestone 告知暂停,
15
+ 每份预算只告知一次,之后静默。Human 建卡不受限;
16
+ - 配置 `pmoMaxRounds`(默认 3,0 = 只做 Human 那一批);
17
+ - 心跳与巡检分时钟(`lib/host/pmo.js` `planTaskNudges`):心跳看 Thread 是否空闲,巡检(30 分钟)
18
+ 与升级(60 分钟)只看 Task 状态是否变化。此前执行人每次回心跳都刷新唯一的时钟,卡死在
19
+ in_progress 的任务永远不会升级给 owner(实测每小时 6 次心跳,无尽头);
20
+ - 测试:`node --test` **314 通过 / 1 跳过**;新增 `pmo-rounds`(6 条:免费批、同批多卡不计轮、
21
+ 定时推进与自主续开共用预算、只有 Human 能续、Human 建卡不受限、重启后保留)与
22
+ `pmo-nudges`(5 条,含 r06 卡死场景:30 分钟巡检、60 分钟升级);
23
+ - E2E(rc.1,隔离 DSH_HOME,上限 0):「在吗」→ 1 张卡 → 验收 → PMO 推进被挡、主流告知 1 次,
24
+ 之后 12 分钟 0 次唤醒、0 张成员新卡、0 次重建。修复前(只闸定时推进)主理人在暂停后 4 秒
25
+ 自己续开了 3 张卡并引发 27 次唤醒。
26
+
27
+ 未覆盖:主流「在吗」仍会被唤醒提示逼着建卡(先对话后开卡);rc.2+ `startActivation` 参数形状。
28
+
29
+ ## 0.4.88 - 2026-11-14
30
+
31
+ **成员唤醒只走 `subagents.sendMessage`,根除「唤醒即重建会话」(Issue #1 主因之一)**
32
+
33
+ 旧 `wake()` 对离线成员先由插件自己 `agents.resume()` 冷恢复,再对在线成员走 `sendMessage`。
34
+ 插件持有的恢复句柄就是写租约:同一成员第二次唤醒(建卡时 owner=assignee 的双唤醒、PMO 催办撞上运行中回合)
35
+ 时 manager 冷恢复报 `NOT_RESUMABLE`,Host 把它当会话损坏,中止回合并重建成员——新会话丢失全部上下文,
36
+ 重建出来的会话又被下一次唤醒重建(桌面实机 24h 内 200 次重建,其中 191 次落在重建出来的会话上)。
37
+ `resumedHandles` 是按 runtime 实例创建的 Map,永远为空,清理从未生效。
38
+
39
+ - `lib/runtime/member-runtime.js`:`wake()` 只有一条投递路径 `subagents.sendMessage`(官方契约:manager
40
+ 负责转向运行中、启动空闲、冷恢复离线子代理);在线会话投递前复核 danger-full-access;
41
+ 删除 `activateDirect`、插件侧 `agents.resume` 与 `trackHandle`;
42
+ - `index.js`:删除 `resumedHandles` 及其三处 dispose;`NOT_RESUMABLE` 自动重建保留为预算内兜底;
43
+ - 测试:`node --test` **303 通过 / 1 跳过**;新增 3 条回归(有 `agents.resume` 也不调用、冷→热连续唤醒
44
+ 同一会话、无子代理运行时显式报错),在 0.4.87 上失败;
45
+ - E2E(rc.1,隔离 DSH_HOME):主理人连收 3 条私信,修复前会话被重建且失忆,修复后会话不变并记得前两次回复;
46
+ 6 成员满员 25 分钟:64 次唤醒,autoreseat / NOT_RESUMABLE / 中止回合均为 0,会话数恒为 7
47
+ (修复前同场景 40 分钟 14 会话、7 次重建)。
48
+
49
+ 未覆盖:PMO 无界自主开卡、rc.2+ `startActivation` 参数形状。
50
+
3
51
  ## 0.4.73 - 2026-11-12
4
52
 
5
53
  **skillopt_jobs 每执必炸的块级作用域缺陷,与 failed 终态不写 results.tsv 两案同修**
package/index.js CHANGED
@@ -8,6 +8,7 @@
8
8
  * The member runtime (real Agent sessions) lands in M2. Until then the
9
9
  * ledger/domain service is the only writer and the Host never fakes work.
10
10
  */
11
+ import { planTaskNudges } from './lib/host/pmo.js';
11
12
  import { homedir } from 'node:os';
12
13
  import { join, sep } from 'node:path';
13
14
  import { fileURLToPath } from 'node:url';
@@ -109,6 +110,9 @@ export const Config = z.object({
109
110
  // 成员 shell 风险守卫:'warn' 只记诊断(默认),'block' 直接拒绝,'off' 不介入。
110
111
  // 实机事故:成员写 serve.ps1 并用隐藏窗口拉起常驻进程,触发杀软报毒。
111
112
  shellGuard: z.union(['off', 'warn', 'block']).default('warn'),
113
+ // 有界自主:Human 每次操作后,PMO 最多自主推进(无 active Task 时开会、自拟下一批卡)几轮;
114
+ // 用尽即暂停并在主流告知,等 Human 续。0 = 从不自主推进。Issue #1:一句「在吗」跑 7 小时。
115
+ pmoMaxRounds: z.number().step(1).min(0).max(100).default(3),
112
116
  });
113
117
 
114
118
  /**
@@ -224,6 +228,7 @@ async function boot(diag, config = {}) {
224
228
  projectGoal: project.goal,
225
229
  workspacePath: project.workspacePath ?? '',
226
230
  diag,
231
+ pmoMaxRounds: config.pmoMaxRounds,
227
232
  });
228
233
  runtimes.set(project.id, runtime);
229
234
  }
@@ -738,10 +743,6 @@ export function apply(ctx, config = {}) {
738
743
  const pmoLastDispatch = new Map();
739
744
  const pmoLastEscalate = new Map();
740
745
  const pmoLastReview = new Map();
741
- // Members resumed from cold sessions produce AgentHandles nobody stored;
742
- // track them by session id so teardown — and session reseat — can
743
- // dispose exactly the handle they own.
744
- const resumedHandles = new Map();
745
746
  let pmoTimer = null;
746
747
  // 项目工作目录(显式,无兜底):null 表示尚未设置。历史版本在此处用
747
748
  // runtime.dir(账本目录)兜底,曾把成员会话 cwd 钉进插件数据目录。
@@ -795,13 +796,10 @@ export function apply(ctx, config = {}) {
795
796
  permissionPresets: serviceOf(ctx, 'permissionPresets'),
796
797
  sandboxPolicy: serviceOf(ctx, 'sandboxPolicy'),
797
798
  agents: serviceOf(ctx, 'agents'),
798
- agentPresets: serviceOf(ctx, 'agentPresets'),
799
- direct: false,
800
799
  parent: parentInfo.agent,
801
800
  provider: resolveSubagentProviderName(subagents, config?.subagentProviderName),
802
801
  preset: 'standard',
803
802
  cwd,
804
- trackHandle: (sessionId, handle) => resumedHandles.set(sessionId, handle),
805
803
  });
806
804
  const delivered = await sessionRuntime.wake(member, {
807
805
  prompt: [
@@ -927,13 +925,10 @@ export function apply(ctx, config = {}) {
927
925
  const runtime = new MemberRuntime({
928
926
  subagents, sessions, permissionPresets, sandboxPolicy,
929
927
  agents: serviceOf(ctx, 'agents'),
930
- agentPresets: serviceOf(ctx, 'agentPresets'),
931
- direct: false,
932
928
  parent: parentInfo.agent,
933
929
  provider: resolveSubagentProviderName(serviceOf(ctx, 'subagents'), config?.subagentProviderName),
934
930
  preset: 'standard',
935
931
  cwd,
936
- trackHandle: (sessionId, handle) => resumedHandles.set(sessionId, handle),
937
932
  });
938
933
  const delivered = await runtime.wake(member, {
939
934
  // 冷路径(会话不在线)才附 Thread 尾巴:成员靠它续跑,不必从零回忆;
@@ -1148,67 +1143,21 @@ export function apply(ctx, config = {}) {
1148
1143
  event: { type: 'pmo/dispatch', payload: { taskId: task.id, bucket: Math.floor(now / 60_000) } },
1149
1144
  }, {});
1150
1145
  }
1146
+ // 巡检提醒:两个时钟(Thread 闲 / 状态停滞)的判定在 planTaskNudges(lib/host/pmo.js)。
1147
+ const nudgeClocks = { review: pmoLastReview, heartbeat: pmoLastHeartbeat, escalate: pmoLastEscalate, stall: pmoLastStall };
1148
+ const nudgeEvent = {
1149
+ review: (task) => ({ type: 'pmo/review', payload: { taskId: task.id, bucket: Math.floor(now / 600_000) } }),
1150
+ heartbeat: (task) => ({ type: 'pmo/heartbeat', payload: { taskId: task.id, memberId: task.assigneeId ?? task.ownerId, bucket: Math.floor(now / 600_000) } }),
1151
+ escalate: (task) => ({ type: 'pmo/escalate', payload: { taskId: task.id, bucket: Math.floor(now / 3_600_000) } }),
1152
+ stall: (task) => ({ type: 'pmo/stall', payload: { taskId: task.id, bucket: Math.floor(now / 1_800_000) } }),
1153
+ };
1151
1154
  for (const task of active) {
1152
- const thread = state.threads?.[task.id];
1153
- const threadAt = thread?.entries?.at(-1)?.at;
1154
- const taskAt = Number.isFinite(task.updatedAt) ? task.updatedAt : 0;
1155
- // For acceptance, assignee Thread chatter must not mask a silent QA.
1156
- // Use the submission timestamp (task.updatedAt) as the review clock.
1157
- const updatedAt = task.status === 'pending_acceptance'
1158
- ? taskAt
1159
- : Math.max(taskAt, Number.isFinite(threadAt) ? threadAt : 0);
1160
- if (updatedAt === 0) continue;
1161
- const idleFor = now - updatedAt;
1162
- if (task.status === 'pending_acceptance' && task.qaRequired === true && idleFor >= 10 * 60_000) {
1163
- const lastReview = pmoLastReview.get(task.id) ?? 0;
1164
- if (now - lastReview >= 10 * 60_000) {
1165
- pmoLastReview.set(task.id, now);
1166
- await wakeFromResult(projectRuntime, {
1167
- event: { type: 'pmo/review', payload: { taskId: task.id, bucket: Math.floor(now / 600_000) } },
1168
- }, {});
1169
- }
1170
- // Acceptance waiting on a Thread-only handoff needs the same
1171
- // hourly escalation as in-progress work, or the review loop
1172
- // nudges QA forever while the decided executor never wakes.
1173
- if (idleFor >= 60 * 60_000) {
1174
- const lastEscalate = pmoLastEscalate.get(task.id) ?? 0;
1175
- if (now - lastEscalate >= 60 * 60_000) {
1176
- pmoLastEscalate.set(task.id, now);
1177
- await wakeFromResult(projectRuntime, {
1178
- event: { type: 'pmo/escalate', payload: { taskId: task.id, bucket: Math.floor(now / 3_600_000) } },
1179
- }, {});
1180
- }
1181
- }
1182
- continue;
1155
+ const threadAt = state.threads?.[task.id]?.entries?.at(-1)?.at ?? null;
1156
+ const last = Object.fromEntries(Object.entries(nudgeClocks).map(([kind, map]) => [kind, map.get(task.id) ?? 0]));
1157
+ for (const kind of planTaskNudges(task, { threadAt, now, last })) {
1158
+ nudgeClocks[kind].set(task.id, now);
1159
+ await wakeFromResult(projectRuntime, { event: nudgeEvent[kind](task) }, {});
1183
1160
  }
1184
- if (idleFor >= 10 * 60_000 && idleFor < 30 * 60_000) {
1185
- const lastHeartbeat = pmoLastHeartbeat.get(task.id) ?? 0;
1186
- if (now - lastHeartbeat >= 10 * 60_000) {
1187
- pmoLastHeartbeat.set(task.id, now);
1188
- await wakeFromResult(projectRuntime, {
1189
- event: {
1190
- type: 'pmo/heartbeat',
1191
- payload: { taskId: task.id, memberId: task.assigneeId ?? task.ownerId, bucket: Math.floor(now / 600_000) },
1192
- },
1193
- }, {});
1194
- }
1195
- }
1196
- if (idleFor >= 60 * 60_000) {
1197
- const lastEscalate = pmoLastEscalate.get(task.id) ?? 0;
1198
- if (now - lastEscalate >= 60 * 60_000) {
1199
- pmoLastEscalate.set(task.id, now);
1200
- await wakeFromResult(projectRuntime, {
1201
- event: { type: 'pmo/escalate', payload: { taskId: task.id, bucket: Math.floor(now / 3_600_000) } },
1202
- }, {});
1203
- }
1204
- }
1205
- if (idleFor < 30 * 60_000) continue;
1206
- const lastPing = pmoLastStall.get(task.id) ?? 0;
1207
- if (now - lastPing < 30 * 60_000) continue;
1208
- pmoLastStall.set(task.id, now);
1209
- await wakeFromResult(projectRuntime, {
1210
- event: { type: 'pmo/stall', payload: { taskId: task.id, bucket: Math.floor(now / 1_800_000) } },
1211
- }, {});
1212
1161
  }
1213
1162
  if (active.length > 0) {
1214
1163
  // Prune per-task clock entries whose task left the active set, so
@@ -1228,6 +1177,9 @@ export function apply(ctx, config = {}) {
1228
1177
  const last = pmoLastKick.get(projectRuntime.id) ?? 0;
1229
1178
  if (now - last < 10 * 60_000) return;
1230
1179
  pmoLastKick.set(projectRuntime.id, now);
1180
+ const gate = await projectRuntime.service.pmoGate(projectRuntime.id);
1181
+ diag.append({ ev: gate.admitted ? 'pmo.continue' : 'pmo.continue.paused', projectId: projectRuntime.id, used: gate.used, cap: gate.cap, freeWave: gate.freeWave, announcedNow: gate.announcedNow });
1182
+ if (!gate.admitted) return;
1231
1183
  await wakeFromResult(projectRuntime, {
1232
1184
  event: { type: 'pmo/continue', payload: { bucket: Math.floor(now / 600_000) } },
1233
1185
  }, {});
@@ -1909,7 +1861,7 @@ export function apply(ctx, config = {}) {
1909
1861
  };
1910
1862
  }
1911
1863
  // 会话重建(reseat):成员已有会话且本次为 force 时,先释放旧会话的
1912
- // 运行时句柄(activation / resume handle),旧 DSH 会话本体由宿主持
1864
+ // activation(插件只持有 startActivation 的回执,冷恢复归 manager),旧 DSH 会话本体由宿主持
1913
1865
  // 久管理,插件不再持有或唤醒它;新会话落在当前项目工作目录。这是
1914
1866
  // 修复历史"账本目录兜底 cwd"游离会话的唯一路径(会话 cwd 创建时
1915
1867
  // 钉死,resume 不覆盖,DSH 不提供原地改 cwd 的 API)。
@@ -1920,11 +1872,6 @@ export function apply(ctx, config = {}) {
1920
1872
  activations.delete(staleId);
1921
1873
  try { await staleActivation.dispose?.(); } catch { /* already gone */ }
1922
1874
  }
1923
- const staleHandle = resumedHandles.get(staleId);
1924
- if (staleHandle !== undefined) {
1925
- resumedHandles.delete(staleId);
1926
- try { await staleHandle.dispose?.(); } catch { /* already gone */ }
1927
- }
1928
1875
  diag?.append({ ev: 'member.reseat', memberId: member.id, oldSessionId: staleId, projectId: projectRuntime.id });
1929
1876
  }
1930
1877
  const subagents = serviceOf(ctx, 'subagents');
@@ -1962,13 +1909,10 @@ export function apply(ctx, config = {}) {
1962
1909
  permissionPresets,
1963
1910
  sandboxPolicy,
1964
1911
  agents: serviceOf(ctx, 'agents'),
1965
- agentPresets: serviceOf(ctx, 'agentPresets'),
1966
- direct: false,
1967
1912
  parent: parentInfo.agent,
1968
1913
  provider: resolveSubagentProviderName(serviceOf(ctx, 'subagents'), config?.subagentProviderName),
1969
1914
  preset: 'standard',
1970
1915
  cwd: effectiveDir,
1971
- trackHandle: (sessionId, handle) => resumedHandles.set(sessionId, handle),
1972
1916
  });
1973
1917
  const result = await runtime.activate(activationMember, {
1974
1918
  prompt: `${memberIdentity(activationMember)}\n\n${typeof body.payload?.prompt === 'string'
@@ -2009,7 +1953,6 @@ export function apply(ctx, config = {}) {
2009
1953
  member: bound.member,
2010
1954
  sessionId: result.childId,
2011
1955
  messageId: result.messageId,
2012
- debug: result.debug ?? null,
2013
1956
  };
2014
1957
  } catch (error) {
2015
1958
  // 并发场景:激活进行中成员被退役,bind 会以 retired 拒绝。这里若无条件
@@ -2131,6 +2074,7 @@ export function apply(ctx, config = {}) {
2131
2074
  projectGoal,
2132
2075
  workspacePath,
2133
2076
  diag,
2077
+ pmoMaxRounds: config.pmoMaxRounds,
2134
2078
  });
2135
2079
  booted.runtimes.set(nextProjectId, next);
2136
2080
  attachRuntime(next);
@@ -2762,14 +2706,6 @@ export function apply(ctx, config = {}) {
2762
2706
  try { await activation.dispose?.(); } catch { /* already gone */ }
2763
2707
  diag.append({ ev: 'member.activation.disposed', memberId: retiredId, sessionId: retiredSession, reason: body.type });
2764
2708
  }
2765
- // 冷恢复得到的 handle 也要回收:它同样常驻进程,且不会因为
2766
- // activation 被 dispose 而消失(两套句柄分开登记)。
2767
- const resumed = resumedHandles.get(retiredSession);
2768
- if (resumed !== undefined) {
2769
- resumedHandles.delete(retiredSession);
2770
- try { await resumed.dispose?.(); } catch { /* already gone */ }
2771
- diag.append({ ev: 'member.resumed-handle.disposed', memberId: retiredId, sessionId: retiredSession, reason: body.type });
2772
- }
2773
2709
  }
2774
2710
  }
2775
2711
  send(res, { ok: true, ...result });
@@ -2812,12 +2748,6 @@ export function apply(ctx, config = {}) {
2812
2748
  }));
2813
2749
  }
2814
2750
  activations.clear();
2815
- for (const handle of resumedHandles.values()) {
2816
- cleanup.push(Promise.resolve().then(async () => {
2817
- try { await handle?.dispose?.(); } catch { /* already gone */ }
2818
- }));
2819
- }
2820
- resumedHandles.clear();
2821
2751
  if (host !== null) cleanup.push(Promise.resolve().then(async () => {
2822
2752
  try { await host.dispose?.(); } catch { /* already gone */ }
2823
2753
  }));
@@ -1,36 +1,37 @@
1
- /** Stable domain errors; HTTP/tool adapters map `code` to user-facing text. */
2
- export class DomainError extends Error {
3
- /**
4
- * @param {string} code - stable machine code, e.g. E_TASK_BLOCKED.
5
- * @param {string} message - developer-readable message.
6
- * @param {{ status?: number, details?: unknown }} [options]
7
- */
8
- constructor(code, message, options = {}) {
9
- super(message);
10
- this.name = 'DomainError';
11
- this.code = code;
12
- this.status = options.status ?? 409;
13
- this.details = options.details;
14
- }
15
- }
16
-
17
- export const ERRORS = {
18
- NOT_FOUND: 'E_NOT_FOUND',
19
- INVALID_STATE: 'E_INVALID_STATE',
20
- UNAUTHORIZED: 'E_UNAUTHORIZED',
21
- CONFLICT: 'E_CONFLICT',
22
- REVISION: 'E_REVISION',
23
- ALREADY_CLAIMED: 'E_ALREADY_CLAIMED',
24
- BLOCKED: 'E_TASK_BLOCKED',
25
- NOT_READY: 'E_TASK_NOT_READY',
26
- NOT_ELIGIBLE: 'E_REVIEWER_NOT_ELIGIBLE',
27
- STALE_REPLY: 'E_STALE_REPLY',
28
- LIMIT: 'E_LIMIT',
29
- IRREVERSIBLE_CONFIRM: 'E_IRREVERSIBLE_CONFIRM_REQUIRED',
30
- INVALID_ARGUMENT: 'E_INVALID_ARGUMENT',
31
- CONFIG_POLICY: 'E_CONFIG_POLICY',
32
- };
33
-
34
- export function fail(code, message, options) {
35
- throw new DomainError(code, message, options);
36
- }
1
+ /** Stable domain errors; HTTP/tool adapters map `code` to user-facing text. */
2
+ export class DomainError extends Error {
3
+ /**
4
+ * @param {string} code - stable machine code, e.g. E_TASK_BLOCKED.
5
+ * @param {string} message - developer-readable message.
6
+ * @param {{ status?: number, details?: unknown }} [options]
7
+ */
8
+ constructor(code, message, options = {}) {
9
+ super(message);
10
+ this.name = 'DomainError';
11
+ this.code = code;
12
+ this.status = options.status ?? 409;
13
+ this.details = options.details;
14
+ }
15
+ }
16
+
17
+ export const ERRORS = {
18
+ NOT_FOUND: 'E_NOT_FOUND',
19
+ INVALID_STATE: 'E_INVALID_STATE',
20
+ UNAUTHORIZED: 'E_UNAUTHORIZED',
21
+ CONFLICT: 'E_CONFLICT',
22
+ REVISION: 'E_REVISION',
23
+ ALREADY_CLAIMED: 'E_ALREADY_CLAIMED',
24
+ BLOCKED: 'E_TASK_BLOCKED',
25
+ NOT_READY: 'E_TASK_NOT_READY',
26
+ NOT_ELIGIBLE: 'E_REVIEWER_NOT_ELIGIBLE',
27
+ STALE_REPLY: 'E_STALE_REPLY',
28
+ LIMIT: 'E_LIMIT',
29
+ IRREVERSIBLE_CONFIRM: 'E_IRREVERSIBLE_CONFIRM_REQUIRED',
30
+ INVALID_ARGUMENT: 'E_INVALID_ARGUMENT',
31
+ CONFIG_POLICY: 'E_CONFIG_POLICY',
32
+ PMO_PAUSED: 'E_PMO_PAUSED',
33
+ };
34
+
35
+ export function fail(code, message, options) {
36
+ throw new DomainError(code, message, options);
37
+ }
package/lib/host/pmo.js CHANGED
@@ -1,75 +1,114 @@
1
- /**
2
- * PMO decision policy.
3
- *
4
- * Human is not in the loop when PMO auto mode is on: choose the recommendation
5
- * when one exists, otherwise choose the option that protects delivery value
6
- * (complete/core) over minimum-effort options. The answer is intentionally
7
- * explicit so it is auditable in the Task Thread.
8
- */
9
-
10
- const LOW_VALUE = /最小|暂缓|延后|不做|暂停|维持现状|先不|仅文档|只做骨架/i;
11
- const HIGH_VALUE = /完整|核心|全量|推荐|生产可用|全平台|优先/i;
12
-
13
- function clean(value) {
14
- return typeof value === 'string' ? value.trim() : '';
15
- }
16
-
17
- /** 选项开头的字母编号(`B.` / `B、` / `B)` / `B:`)。 */
18
- function optionLetter(value) {
19
- const match = /^\s*[((]?([A-Za-z])[))..、::]/.exec(value);
20
- return match === null ? null : match[1].toUpperCase();
21
- }
22
-
23
- /** 建议里点名的选项字母(`建议 B` / `推荐:C` / `选 A`)。 */
24
- function recommendationLetter(recommendation) {
25
- const match = /(?:建议|推荐|选择|选|option|choose)\s*[::]?\s*[((]?([A-Za-z])\b/i.exec(recommendation)
26
- ?? /^\s*[((]?([A-Za-z])[))..、::]/.exec(recommendation);
27
- return match === null ? null : match[1].toUpperCase();
28
- }
29
-
30
- /** 显式建议命中哪个选项:字母编号优先,其次双向包含。 */
31
- function explicitPick(options, recommendation) {
32
- if (recommendation === '') return null;
33
- const letter = recommendationLetter(recommendation);
34
- if (letter !== null) {
35
- const byLetter = options.find((option) => optionLetter(option) === letter);
36
- if (byLetter !== undefined) return byLetter;
37
- }
38
- return options.find((option) => recommendation.includes(option) || option.includes(recommendation)) ?? null;
39
- }
40
-
41
- function scoreOption(option, question) {
42
- const value = clean(option);
43
- if (value === '') return -100;
44
- let score = 0;
45
- if (/推荐/i.test(value)) score += 20;
46
- if (HIGH_VALUE.test(value)) score += 12;
47
- if (/B\b|C\b|核心|完整/i.test(value)) score += 6;
48
- if (LOW_VALUE.test(value)) score -= 20;
49
- if (/A\b|最小/i.test(value)) score -= 8;
50
- const recommendation = clean(question?.recommendation);
51
- if (recommendation !== '' && recommendation.includes(value)) score += 30;
52
- if (recommendation !== '' && value.includes(recommendation)) score += 20;
53
- return score;
54
- }
55
-
56
- /** Return [ { id, value } ] for every question. */
57
- export function chooseDecisionAnswers(questions) {
58
- return (Array.isArray(questions) ? questions : []).map((question, index) => {
59
- const id = typeof question?.id === 'string' && question.id !== '' ? question.id : `q${index + 1}`;
60
- const options = Array.isArray(question?.options) ? question.options.map(clean).filter(Boolean) : [];
61
- const recommendation = clean(question?.recommendation);
62
- if (options.length > 0) {
63
- // 问题里给了明确建议就按建议选——只有没有建议、或建议对不上任何选项时,
64
- // 才退回关键字打分。否则「建议 A」可能被关键词打分选成 B,PMO 自动决策
65
- // 就与问题给出的建议相反。
66
- const explicit = explicitPick(options, recommendation);
67
- if (explicit !== null) return { id, value: explicit };
68
- const picked = options
69
- .map((option) => ({ option, score: scoreOption(option, question) }))
70
- .sort((left, right) => right.score - left.score)[0];
71
- return { id, value: picked?.option || recommendation || '按完整核心方案执行' };
72
- }
73
- return { id, value: recommendation || '按完整、可验收、长期价值最高的方案执行' };
74
- });
75
- }
1
+ /**
2
+ * PMO decision policy.
3
+ *
4
+ * Human is not in the loop when PMO auto mode is on: choose the recommendation
5
+ * when one exists, otherwise choose the option that protects delivery value
6
+ * (complete/core) over minimum-effort options. The answer is intentionally
7
+ * explicit so it is auditable in the Task Thread.
8
+ */
9
+
10
+ const LOW_VALUE = /最小|暂缓|延后|不做|暂停|维持现状|先不|仅文档|只做骨架/i;
11
+ const HIGH_VALUE = /完整|核心|全量|推荐|生产可用|全平台|优先/i;
12
+
13
+ function clean(value) {
14
+ return typeof value === 'string' ? value.trim() : '';
15
+ }
16
+
17
+ /** 选项开头的字母编号(`B.` / `B、` / `B)` / `B:`)。 */
18
+ function optionLetter(value) {
19
+ const match = /^\s*[((]?([A-Za-z])[))..、::]/.exec(value);
20
+ return match === null ? null : match[1].toUpperCase();
21
+ }
22
+
23
+ /** 建议里点名的选项字母(`建议 B` / `推荐:C` / `选 A`)。 */
24
+ function recommendationLetter(recommendation) {
25
+ const match = /(?:建议|推荐|选择|选|option|choose)\s*[::]?\s*[((]?([A-Za-z])\b/i.exec(recommendation)
26
+ ?? /^\s*[((]?([A-Za-z])[))..、::]/.exec(recommendation);
27
+ return match === null ? null : match[1].toUpperCase();
28
+ }
29
+
30
+ /** 显式建议命中哪个选项:字母编号优先,其次双向包含。 */
31
+ function explicitPick(options, recommendation) {
32
+ if (recommendation === '') return null;
33
+ const letter = recommendationLetter(recommendation);
34
+ if (letter !== null) {
35
+ const byLetter = options.find((option) => optionLetter(option) === letter);
36
+ if (byLetter !== undefined) return byLetter;
37
+ }
38
+ return options.find((option) => recommendation.includes(option) || option.includes(recommendation)) ?? null;
39
+ }
40
+
41
+ function scoreOption(option, question) {
42
+ const value = clean(option);
43
+ if (value === '') return -100;
44
+ let score = 0;
45
+ if (/推荐/i.test(value)) score += 20;
46
+ if (HIGH_VALUE.test(value)) score += 12;
47
+ if (/B\b|C\b|核心|完整/i.test(value)) score += 6;
48
+ if (LOW_VALUE.test(value)) score -= 20;
49
+ if (/A\b|最小/i.test(value)) score -= 8;
50
+ const recommendation = clean(question?.recommendation);
51
+ if (recommendation !== '' && recommendation.includes(value)) score += 30;
52
+ if (recommendation !== '' && value.includes(recommendation)) score += 20;
53
+ return score;
54
+ }
55
+
56
+ /** Return [ { id, value } ] for every question. */
57
+ export function chooseDecisionAnswers(questions) {
58
+ return (Array.isArray(questions) ? questions : []).map((question, index) => {
59
+ const id = typeof question?.id === 'string' && question.id !== '' ? question.id : `q${index + 1}`;
60
+ const options = Array.isArray(question?.options) ? question.options.map(clean).filter(Boolean) : [];
61
+ const recommendation = clean(question?.recommendation);
62
+ if (options.length > 0) {
63
+ // 问题里给了明确建议就按建议选——只有没有建议、或建议对不上任何选项时,
64
+ // 才退回关键字打分。否则「建议 A」可能被关键词打分选成 B,PMO 自动决策
65
+ // 就与问题给出的建议相反。
66
+ const explicit = explicitPick(options, recommendation);
67
+ if (explicit !== null) return { id, value: explicit };
68
+ const picked = options
69
+ .map((option) => ({ option, score: scoreOption(option, question) }))
70
+ .sort((left, right) => right.score - left.score)[0];
71
+ return { id, value: picked?.option || recommendation || '按完整核心方案执行' };
72
+ }
73
+ return { id, value: recommendation || '按完整、可验收、长期价值最高的方案执行' };
74
+ });
75
+ }
76
+
77
+ const MINUTE = 60_000;
78
+
79
+ /**
80
+ * PMO 巡检对一张 active Task 该发哪些提醒(按序:review / heartbeat / escalate / stall)。
81
+ *
82
+ * 两个时钟分开:
83
+ * - threadIdle:Thread 最后一条或 Task 状态变化以来——只用来判断「该发心跳了」;
84
+ * - stateIdle:Task 状态(claim/submit/accept…)最后一次变化以来——判断巡检与升级。
85
+ * 实机(r06):执行人把交付写在 Thread 里 @ 评审、没有 submit,于是每 10 分钟的心跳
86
+ * 回帖都刷新了单一时钟,巡检(30 分钟)与升级(60 分钟)永远不触发,owner 从未被叫来,
87
+ * 心跳每小时 6 次无休止。回帖不是进展,状态变化才是。
88
+ * 验收中的 Task 只认状态时钟(执行人的 Thread 闲聊不能掩盖沉默的 QA)。
89
+ *
90
+ * @param {any} task
91
+ * @param {{ threadAt?: number|null, now: number, last?: Record<string, number> }} options
92
+ * last:每种提醒上次发出的时间(review/heartbeat/escalate/stall)。
93
+ * @returns {Array<'review'|'heartbeat'|'escalate'|'stall'>}
94
+ */
95
+ export function planTaskNudges(task, { threadAt = null, now, last = {} }) {
96
+ const taskAt = Number.isFinite(task?.updatedAt) ? task.updatedAt : 0;
97
+ if (taskAt === 0) return [];
98
+ const stateIdle = now - taskAt;
99
+ const threadIdle = task.status === 'pending_acceptance'
100
+ ? stateIdle
101
+ : now - Math.max(taskAt, Number.isFinite(threadAt) ? threadAt : 0);
102
+ const due = (kind, every) => now - (last[kind] ?? 0) >= every;
103
+ const out = [];
104
+ if (task.status === 'pending_acceptance' && task.qaRequired === true) {
105
+ if (stateIdle < 10 * MINUTE) return out;
106
+ if (due('review', 10 * MINUTE)) out.push('review');
107
+ if (stateIdle >= 60 * MINUTE && due('escalate', 60 * MINUTE)) out.push('escalate');
108
+ return out;
109
+ }
110
+ if (threadIdle >= 10 * MINUTE && stateIdle < 30 * MINUTE && due('heartbeat', 10 * MINUTE)) out.push('heartbeat');
111
+ if (stateIdle >= 60 * MINUTE && due('escalate', 60 * MINUTE)) out.push('escalate');
112
+ if (stateIdle >= 30 * MINUTE && due('stall', 30 * MINUTE)) out.push('stall');
113
+ return out;
114
+ }