@suifei/dsh-ai-team 0.4.99 → 0.4.103

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,65 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.103 - 2026-11-16
4
+
5
+ **夜间 SkillOpt 环能从 DSH 会话里学习**
6
+
7
+ - **新增 `dsh` 会话来源**:引擎此前只认 claude/codex/copilot/cursor/pi/opencode,DeepSeek Harness 的会话
8
+ (含文渊阁成员)一条也读不到——il2c 里 agent 写进 `~/.skillopt-sleep/config.json` 的
9
+ `transcript_source: "dsh_team"` 让引擎每晚报 `Unknown transcript source`,删掉后又只扫到 0 个会话。
10
+ `harvest_dsh.py` 读 `<DSH_HOME>/sessions/*/*/session.v4.jsonl.zstd`:按会话头的 `cwd` 匹配项目(只解码
11
+ 首行即可排除别的项目)。`user/message` 按 `source.kind` 取意图:`user`(人)、`agent-message`(文渊阁的
12
+ 任务唤醒以 relay 投递,il2c 成员会话 37 条 relay 对 1 条 user)、`ai-team`(插件纠偏,同时记为负反馈
13
+ `neg:ai-team-correction`);`time-context` / `runtime-context` / `skill-catalog` / `subagent-settled` 等宿主
14
+ 记账不算意图。激活提示词开头的成员身份段(「你是 X(角色)。你的个性与工作方式:…」)剥掉再挖——未剥时
15
+ il2c 16 个任务里 6 个是个性描述。助手只收 `text`(`reasoning` 不进摘要),工具只记名字不抄参数;上次
16
+ 采集之后未写过的日志不解码;正在写的会话末尾半帧安全跳过(逐帧解码,整流解码会连带丢掉同块已解出的帧)。
17
+ zstd 由 Node 解码(`dsh_decode.mjs`;Python 3.11 标准库无 zstd),Node 取 `dsh_node` 配置 / `DSH_NODE` /
18
+ PATH(DSH 自带 `resources/runtime/primary-runtime/dependencies/node/bin/node.exe`);会话目录取 `dsh_home` /
19
+ `DSH_HOME` / `~/.dsh`。实测 il2c 最近 72 小时:只读 `harvest --source dsh` 18 秒挖出 13 个任务;
20
+ - **schtasks 输出按控制台代码页解码**:UTF-8 模式下(`-X utf8`)`text=True` 把 CP936 输出按 UTF-8 解,
21
+ 读线程抛 `UnicodeDecodeError`、`stdout` 为 `None`,「列出已排程的项目」静默返回空。三处调用改走
22
+ `_run_schtasks`(OEM 代码页 + `errors="replace"`);
23
+ - 打包:`files` 补 `lib/vendor/skillopt/skillopt_sleep/**/*.mjs`(`lib/**/*.js` 不含 `.mjs`);
24
+ - 测试:新增 `test/skillopt-dsh-source.test.js`(多帧 zstd + 半帧尾、项目匹配、注入与推理过滤、身份段剥离、
25
+ 按修改时间跳过、CLI 接受 `dsh`、schtasks UTF-8 模式);
26
+
27
+ ## 0.4.102 - 2026-11-16
28
+
29
+ **DSH Desktop 侧边栏缺「文渊阁」入口(#26)**
30
+
31
+ - `package.json` 的 `exports` 补上 `"./package.json"`。DSH Desktop 宿主没有 `loader.internal` 时,
32
+ `dsh-client-modules` 的 `locatePkgJson` 走 CJS 回退 `createRequire(baseUrl).resolve('<pkg>/package.json')`;
33
+ 本包未导出该子路径 → `ERR_PACKAGE_PATH_NOT_EXPORTED` 被 `catch {}` 吞掉 → 客户端行静默丢弃,宿主半边照常,
34
+ 只是侧边栏没有入口。CLI 宿主走 `loader.internal.resolveSync`,不受影响。
35
+ - 测试:`test/manifest-locate.test.js` 用同一回退调用解析 manifest 与 `./client`(修复前 `ERR_PACKAGE_PATH_NOT_EXPORTED`)。
36
+ `node --test` 345 pass / 1 skip。
37
+ - E2E(独立 `DSH_HOME`,dsh CLI 新建 profile 装包):rc.1 / rc.2 / rc.3 上照搬回退分支判定,0.4.99 全部 `dropped`、
38
+ 0.4.100 全部 `kept`;三个宿主带会话 cookie 启动,health 回读 0.4.100,页面清单含 `dsh-ai-team/client.js`,无 client-modules 报错。
39
+
40
+ ## 0.4.101 - 2026-11-16
41
+
42
+ **团队推进:不等钟点、不提前收兵、个性不膨胀、夜间环真跑**
43
+
44
+ - **不把行动挂在钟点上**:il2c 实机 PMO 回复「评审官并已立约今夜 03:17 自然相裁决点……明早盯一眼结果」,
45
+ 把一件当场就能跑的事推迟 16 小时。新增 `lib/runtime/deferral-guard.js`:
46
+ - 纪律段 `ai-team:team-discipline` 经 `systemPrompt.section` 注入每个团队会话(PMO 宿主、成员、由它们派生
47
+ 的子智能体;按父会话识别,覆盖成员激活首回合):立即行动、等待要有边界、不提前收兵、先核实再宣称、平实中文;
48
+ - `agent/turn-stopping` 上识别「今夜/明早/等到 22:00/03:17 自然相」类推迟,`agent.steer` 递一条纠偏让同一回合
49
+ 继续(每回合最多一次,留「真实时钟依赖」出口;已停止的项目不推);诊断 `team.deferral.steered`;
50
+ - 识别规则用 il2c 7413 条助手回复校准:4 条命中全部属实,过去时刻叙述、「不用盯」、有截止的持续盯均不命中;
51
+ - **看板空了不再停摆**:`wave_done` 旧提示词「只汇报,不要在本回合续开新任务」,且 wave_done 计为 PMO 已看过
52
+ 局面,定时推进不再触发——il2c 11-16 看板空转 7 小时。现在自动推进开启时,汇报完同一回合判断下一步(与
53
+ `pmo_continue` 共用一份规则,批次上限仍由建卡门禁把关);自动推进关闭时只汇报并写明建议;
54
+ - **个性长度上限 600 字**:il2c 成员个性只增不减(玄策 58 → 2386 字,堆满单卡教训与「候验窗冻树不写」类等待
55
+ 规则)。`checkPersonality` 为 evolve / distill 唯一校验,超限拒绝并要求整段重写;复盘提示词改为整段重写、
56
+ 删等待/冻结规则,已超长的成员会被点明当前字数;
57
+ - **夜间 skillopt 环每晚失败**:vendored `scheduler.py` 生成的 run.ps1 用 `$ErrorActionPreference='Stop'` 加
58
+ `*>>`,PS 5.1 下引擎第一行 stderr 即中止,`cron.log` 一字不写、任务结果恒为 1。改为调用期间 `Continue`、
59
+ `2>&1` 逐行写日志、`exit $LASTEXITCODE`;skill 写明「排程只是兜底,要结果就现在 `skillopt_run` 并读退出码」;
60
+ - 测试:新增 `test/team-discipline.test.js`(7 例)、`test/skillopt-scheduler.test.js`(Windows,去掉修复即失败);
61
+ `test/pmo-voice.test.js` 覆盖 wave_done 自动推进开 / 关两种提示词;
62
+
3
63
  ## 0.4.99 - 2026-11-15
4
64
 
5
65
  **宿主边界:两处代码审视发现的缺陷**
package/index.js CHANGED
@@ -11,6 +11,7 @@
11
11
  import { planDispatch, planTaskNudges } from './lib/host/pmo.js';
12
12
  import { pmoHasNews } from './lib/ledger/fold.js';
13
13
  import { homedir } from 'node:os';
14
+ import { randomUUID } from 'node:crypto';
14
15
  import { join, sep } from 'node:path';
15
16
  import { fileURLToPath } from 'node:url';
16
17
  import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
@@ -55,6 +56,7 @@ import { describeCauseChain } from './lib/runtime/error-chain.js';
55
56
  import { classifyWakeFailure, isMalformedTurnError } from './lib/runtime/wake-failure.js';
56
57
  import { registerShellGuard } from './lib/runtime/shell-guard.js';
57
58
  import { registerStopGuard } from './lib/runtime/stop-guard.js';
59
+ import { registerTeamDiscipline } from './lib/runtime/deferral-guard.js';
58
60
  import { createActivationBudget } from './lib/runtime/activation-budget.js';
59
61
  import { blocksActivation, probeProviderRegistration } from './lib/runtime/subagent-probe.js';
60
62
  import { isRuntimeUnavailableFailure, resolveSubagentProviderName } from './lib/runtime/subagent-provider.js';
@@ -69,7 +71,7 @@ export const name = 'ai-team';
69
71
  /** The workbench only makes sense where the Web carrier exists. */
70
72
  // cordis 按 inject 保证属性注入;未声明的属性访问会抛错,因此这里列全插件
71
73
  // 实际使用的服务(含可选服务:缺失时 serviceOf 回退 ctx.get 并返回 undefined)。
72
- export const inject = ['webServer', 'connection', 'permissionPresets', 'sandboxPolicy', 'tools', 'shell', 'agents', 'subagents', 'sessions'];
74
+ export const inject = ['webServer', 'connection', 'permissionPresets', 'sandboxPolicy', 'tools', 'shell', 'agents', 'subagents', 'sessions', 'systemPrompt'];
73
75
 
74
76
  // 版本号只有一处真源:package.json。硬编码字面量曾让 /health 在升版后仍报旧版本,
75
77
  // 误导「运行实例是否加载了新代码」的判断。
@@ -357,6 +359,18 @@ export function apply(ctx, config = {}) {
357
359
  }
358
360
  return null;
359
361
  };
362
+ /** 会话属于哪个团队(PMO 宿主会话或成员会话):停止守卫与推进纪律共用这一份判定。 */
363
+ const teamProjectOf = (sessionId) => {
364
+ for (const runtime of booted?.runtimes?.values() ?? []) {
365
+ const state = runtime.service.state;
366
+ const inTeam = state.hostSessionId === sessionId
367
+ || Object.values(state.members ?? {}).some((member) => member?.sessionId === sessionId);
368
+ if (!inTeam) continue;
369
+ const project = state.projects?.[runtime.id];
370
+ return { projectId: runtime.id, projectName: project?.name ?? '', stopped: project?.runState === 'stopped' };
371
+ }
372
+ return null;
373
+ };
360
374
  const workspaceForProject = async (projectRuntime) => {
361
375
  const registry = serviceOf(ctx, 'workspaceRegistry');
362
376
  const path = projectRuntime?.service?.state?.projects?.[projectRuntime.id]?.workspacePath;
@@ -673,8 +687,22 @@ export function apply(ctx, config = {}) {
673
687
  // 成员投影一旦 session-bound 就永远是 running;补派若拿它判忙,就永远不派(#18:
674
688
  // il2c 2997 次唤醒里 pmo_dispatch 为 0)。进程内状态,重启即清空——重启时本就没有回合在跑。
675
689
  const turnsInFlight = new Set();
690
+ // 团队推进纪律:系统提示词段 + 回合收尾时纠偏「把行动挂在钟点上」(il2c:「今夜 03:17 自然相裁决点」)。
691
+ let teamDiscipline = { observe: () => {}, dispose: () => {} };
692
+ try {
693
+ teamDiscipline = registerTeamDiscipline({
694
+ systemPrompt: serviceOf(ctx, 'systemPrompt'),
695
+ on: typeof ctx.on === 'function' ? (name, listener) => ctx.on(name, listener) : undefined,
696
+ teamProjectOf,
697
+ diag,
698
+ newId: randomUUID,
699
+ });
700
+ } catch (error) {
701
+ diag.append({ ev: 'team.discipline.fail', message: error?.message ?? String(error) });
702
+ }
676
703
  const offSessionEvent = typeof ctx.on === 'function'
677
704
  ? ctx.on('session/event', async (session, event) => {
705
+ try { teamDiscipline.observe(session, event); } catch { /* 观察失败不影响事件流 */ }
678
706
  if (typeof session?.id === 'string') {
679
707
  if (event?.type === 'turn/start') turnsInFlight.add(session.id);
680
708
  else if (event?.type === 'turn/end') turnsInFlight.delete(session.id);
@@ -1777,17 +1805,6 @@ export function apply(ctx, config = {}) {
1777
1805
  // 子智能体——实机停止后 PMO 收到「成员被停」通知,又用 send_message 把成员续跑了 25 分钟。
1778
1806
  let disposeStopGuard = () => {};
1779
1807
  try {
1780
- const teamProjectOf = (sessionId) => {
1781
- for (const runtime of booted?.runtimes?.values() ?? []) {
1782
- const state = runtime.service.state;
1783
- const inTeam = state.hostSessionId === sessionId
1784
- || Object.values(state.members ?? {}).some((member) => member?.sessionId === sessionId);
1785
- if (!inTeam) continue;
1786
- const project = state.projects?.[runtime.id];
1787
- return { projectId: runtime.id, projectName: project?.name ?? '', stopped: project?.runState === 'stopped' };
1788
- }
1789
- return null;
1790
- };
1791
1808
  disposeStopGuard = registerStopGuard({ tools: tools ?? serviceOf(ctx, 'tools'), projectOf: teamProjectOf, diag });
1792
1809
  } catch (error) {
1793
1810
  diag.append({ ev: 'stop.guard.fail', message: error?.message ?? String(error) });
@@ -2878,6 +2895,7 @@ export function apply(ctx, config = {}) {
2878
2895
  try { removeDiagSink(); } catch { /* sink already replaced */ }
2879
2896
  try { disposeShellGuard(); } catch { /* already disposed */ }
2880
2897
  try { disposeStopGuard(); } catch { /* already disposed */ }
2898
+ try { teamDiscipline.dispose(); } catch { /* already disposed */ }
2881
2899
  // 在途的 boot 也算本组合的资源:等它落定(落定时见 disposed 会自行关账本),
2882
2900
  // 否则下一组合抢在关锁之前打开同一账本。
2883
2901
  const cleanup = [ready.then(() => undefined, () => undefined)];
@@ -1,46 +1,71 @@
1
- /** Member profile semantics shared by the ledger, service, Waker and UI. */
2
-
3
- const QA_PATTERN = /(^|[^a-z])(qa|quality|test|verification)([^a-z]|$)|质量|测试|验收/i;
4
- const REVIEW_PATTERN = /review|验收|评审|审查/i;
5
-
6
- export function isQaMember(member) {
7
- return typeof member?.role === 'string' && QA_PATTERN.test(member.role);
8
- }
9
-
10
- export function isReviewerMember(member) {
11
- return isQaMember(member) || (typeof member?.role === 'string' && REVIEW_PATTERN.test(member.role));
12
- }
13
-
14
- /** Prompt prefix that makes a member's name/role/personality effective on wake. */
15
- export function memberIdentity(member) {
16
- if (member === undefined || member === null) return '';
17
- const parts = [`你是 ${member.name ?? member.id}(${member.role || 'Team member'})。`];
18
- if (typeof member.personality === 'string' && member.personality.trim() !== '') {
19
- parts.push(`你的个性与工作方式:${member.personality.trim()}`);
20
- }
21
- if (Array.isArray(member.skills) && member.skills.length > 0) {
22
- parts.push(`你的技能:${member.skills.join('、')}`);
23
- }
24
- if (Array.isArray(member.notes) && member.notes.length > 0) {
25
- parts.push(`你最近的备忘:${member.notes.slice(-5).join(';')}`);
26
- }
27
- if (isQaMember(member)) parts.push('你承担 QA 职责:优先独立复跑门禁、核对证据,再决定是否验收。');
28
- return parts.join('\n');
29
- }
30
-
31
- /** Unfinished work a leaving member leaves behind. */
32
- export function unfinishedTasksFor(state, memberId) {
33
- return Object.values(state.tasks ?? {}).filter((task) => {
34
- if (task.tombstone === true || ['done', 'cancelled', 'deleted'].includes(task.status)) return false;
35
- return task.ownerId === memberId || task.assigneeId === memberId;
36
- });
37
- }
38
-
39
- /**
40
- * Pick an Agent eligible to review this task: not the assignee, never claimed,
41
- * active, QA first, then any reviewer-role member, then any other Agent.
42
- *
43
- * The rule itself lives in `policy.js` (single implementation for ledger,
44
- * views and Waker); this re-export keeps the historical import path stable.
45
- */
46
- export { eligibleReviewers } from './policy.js';
1
+ /** Member profile semantics shared by the ledger, service, Waker and UI. */
2
+
3
+ const QA_PATTERN = /(^|[^a-z])(qa|quality|test|verification)([^a-z]|$)|质量|测试|验收/i;
4
+ const REVIEW_PATTERN = /review|验收|评审|审查/i;
5
+
6
+ export function isQaMember(member) {
7
+ return typeof member?.role === 'string' && QA_PATTERN.test(member.role);
8
+ }
9
+
10
+ export function isReviewerMember(member) {
11
+ return isQaMember(member) || (typeof member?.role === 'string' && REVIEW_PATTERN.test(member.role));
12
+ }
13
+
14
+ /**
15
+ * 成员工作个性的长度上限(字符)。
16
+ *
17
+ * il2c 实账本:复盘后的 evolve 只增不减,玄策从 58 字长到 2386 字、墨渊 41 → 1604、评审官 1601,
18
+ * 条目里堆满单张卡的教训与「候票零写窗」「候验窗冻树不写」这类等待规则,每次激活全部注入。
19
+ * 个性是「多数任务都适用的工作方式」,不是事故台账。
20
+ */
21
+ export const PERSONALITY_LIMIT = 600;
22
+
23
+ /**
24
+ * evolve / distill 写入前的唯一校验:去空白、非空、不超过上限。
25
+ * @returns {{ ok: true, personality: string } | { ok: false, reason: string }}
26
+ */
27
+ export function checkPersonality(value) {
28
+ const personality = typeof value === 'string' ? value.trim() : '';
29
+ if (personality === '') return { ok: false, reason: 'personality is required' };
30
+ if (personality.length > PERSONALITY_LIMIT) {
31
+ return {
32
+ ok: false,
33
+ reason: `personality is ${personality.length} characters; the limit is ${PERSONALITY_LIMIT}. Rewrite the whole personality instead of appending: merge overlapping items, keep only ways of working that apply to most future tasks, drop single-task lessons and waiting/freeze rules, write plain Chinese.`,
34
+ };
35
+ }
36
+ return { ok: true, personality };
37
+ }
38
+
39
+ /** Prompt prefix that makes a member's name/role/personality effective on wake. */
40
+ export function memberIdentity(member) {
41
+ if (member === undefined || member === null) return '';
42
+ const parts = [`你是 ${member.name ?? member.id}(${member.role || 'Team member'})。`];
43
+ if (typeof member.personality === 'string' && member.personality.trim() !== '') {
44
+ parts.push(`你的个性与工作方式:${member.personality.trim()}`);
45
+ }
46
+ if (Array.isArray(member.skills) && member.skills.length > 0) {
47
+ parts.push(`你的技能:${member.skills.join('、')}`);
48
+ }
49
+ if (Array.isArray(member.notes) && member.notes.length > 0) {
50
+ parts.push(`你最近的备忘:${member.notes.slice(-5).join(';')}`);
51
+ }
52
+ if (isQaMember(member)) parts.push('你承担 QA 职责:优先独立复跑门禁、核对证据,再决定是否验收。');
53
+ return parts.join('\n');
54
+ }
55
+
56
+ /** Unfinished work a leaving member leaves behind. */
57
+ export function unfinishedTasksFor(state, memberId) {
58
+ return Object.values(state.tasks ?? {}).filter((task) => {
59
+ if (task.tombstone === true || ['done', 'cancelled', 'deleted'].includes(task.status)) return false;
60
+ return task.ownerId === memberId || task.assigneeId === memberId;
61
+ });
62
+ }
63
+
64
+ /**
65
+ * Pick an Agent eligible to review this task: not the assignee, never claimed,
66
+ * active, QA first, then any reviewer-role member, then any other Agent.
67
+ *
68
+ * The rule itself lives in `policy.js` (single implementation for ledger,
69
+ * views and Waker); this re-export keeps the historical import path stable.
70
+ */
71
+ export { eligibleReviewers } from './policy.js';
@@ -25,7 +25,7 @@ import { applyMemberConfigPatch, normalizeMemberConfig } from '../domain/member-
25
25
  import { MEMBER_STATUS, isBoardIdle } from '../ledger/fold.js';
26
26
 
27
27
  const MEMBER_STATUS_VALUES = new Set(Object.values(MEMBER_STATUS));
28
- import { isQaMember, unfinishedTasksFor } from '../domain/member-profile.js';
28
+ import { checkPersonality, isQaMember, unfinishedTasksFor } from '../domain/member-profile.js';
29
29
 
30
30
  function mentionsHuman(body) {
31
31
  return typeof body === 'string'
@@ -829,11 +829,11 @@ export class TeamService {
829
829
  if (payload.memberId !== undefined && payload.memberId !== member.id) {
830
830
  fail(ERRORS.UNAUTHORIZED, 'an Agent may only evolve itself');
831
831
  }
832
- const personality = typeof payload.personality === 'string' ? payload.personality.trim() : '';
833
- if (personality === '') fail(ERRORS.INVALID_ARGUMENT, 'personality is required');
832
+ const checked = checkPersonality(payload.personality);
833
+ if (!checked.ok) fail(ERRORS.INVALID_ARGUMENT, checked.reason);
834
834
  await this.append(command, 'member/distilled', {
835
835
  memberId: member.id,
836
- personality,
836
+ personality: checked.personality,
837
837
  updatedBy: member.id,
838
838
  reason: payload.reason ?? 'self-evolution',
839
839
  });
@@ -849,13 +849,12 @@ export class TeamService {
849
849
  if (command.actor.kind !== 'human' && !lead && command.actor.memberId !== member.id) {
850
850
  fail(ERRORS.UNAUTHORIZED, 'only Human, the Project owner or the member may distill');
851
851
  }
852
- const personality = typeof payload.personality === 'string' && payload.personality.trim() !== ''
853
- ? payload.personality.trim()
854
- : member.personality ?? '';
855
- if (personality === '') fail(ERRORS.INVALID_ARGUMENT, 'personality is required for distillation');
852
+ const supplied = typeof payload.personality === 'string' && payload.personality.trim() !== '';
853
+ const checked = checkPersonality(supplied ? payload.personality : member.personality);
854
+ if (!checked.ok) fail(ERRORS.INVALID_ARGUMENT, supplied ? checked.reason : `distillation needs a personality: ${checked.reason}`);
856
855
  await this.append(command, 'member/distilled', {
857
856
  memberId: member.id,
858
- personality,
857
+ personality: checked.personality,
859
858
  updatedBy: command.actor.memberId,
860
859
  reason: payload.reason ?? 're-distill',
861
860
  });
package/lib/host/waker.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * deduplication and permission checks stay in the Host.
7
7
  */
8
8
 
9
- import { eligibleReviewers, isQaMember, unfinishedTasksFor } from '../domain/member-profile.js';
9
+ import { PERSONALITY_LIMIT, eligibleReviewers, isQaMember, unfinishedTasksFor } from '../domain/member-profile.js';
10
10
  import { isReviewCandidate } from '../domain/policy.js';
11
11
  import { isBoardIdle } from '../ledger/fold.js';
12
12
 
@@ -31,6 +31,15 @@ function taskTitle(state, taskId) {
31
31
  return `#${task.number ?? '?'} ${task.title ?? ''}`.trim();
32
32
  }
33
33
 
34
+ /**
35
+ * 看板空了之后「要不要续开、怎么续开」的唯一规则:pmo_continue 与 wave_done(自动推进开启时)共用。
36
+ *
37
+ * il2c 实账本(11-16):03:04 最后一张卡验收,wave_done 的旧提示词是「只汇报,不要在本回合续开新任务」,
38
+ * 主理人照做(「遵令未开新任务」);wave_done 又算作 PMO 已看过局面,定时推进于是一直不触发——
39
+ * 看板空转 7 小时,直到 10 点 Human 加了一名成员才被叫醒。判断下一步不该等钟点,也不该等 Human 说「继续」。
40
+ */
41
+ const CONTINUE_RULES = '对照 Human 最近一次的指令判断目标是否已经达成:已达成且没有明确的后续价值 → 用 team action=say 在主对话简短说明「已完成、暂无后续」,然后结束本回合,不开新卡。确有必要继续时,现在就产出下一批 Task(读取已完成 Task、Thread 与核心 skill,需要成员意见就在 Thread @ 相关成员),并用 action=say 告诉 Human 新一批做什么、为什么;resultDefinition 必须可验证,qaRequired 必须有 qaChecklist。不要重复已完成卡,不要扩大到 Human 没要求的范围,也不要把下一步推迟到某个时间点或等 Human 说「继续」。自主续开有批次上限,用尽时建卡会被拒绝,那时停下等 Human。';
42
+
34
43
  function promptFor(reason, state, taskId) {
35
44
  const task = state.tasks?.[taskId];
36
45
  const title = taskTitle(state, taskId);
@@ -47,7 +56,11 @@ function promptFor(reason, state, taskId) {
47
56
  return `Team event: ${title} 已提交待验收,你是独立 reviewer。调用 team 工具读 thread 与证据;若你从未认领该卡,请验收或写明返工理由。QA 角色优先复跑门禁。`;
48
57
  }
49
58
  if (reason === 'reflection_requested') {
50
- return `Team event: ${title} 已被验收完成。做一次简短复盘:哪一步做得好、哪一步下次要改;如果你发现了持久的工作方式改进,可以调用 team 工具 evolve 更新自己的 personality(只能改个性,不改名字/角色)。不要重开已完成的卡。`;
59
+ const current = state.members?.[task?.assigneeId]?.personality ?? '';
60
+ const over = current.length > PERSONALITY_LIMIT
61
+ ? `你的个性现在 ${current.length} 字,已超过 ${PERSONALITY_LIMIT} 字上限:这次复盘必须用 evolve 把它精简重写到上限以内。`
62
+ : '';
63
+ return `Team event: ${title} 已被验收完成。做一次简短复盘:哪一步做得好、哪一步下次要改。${over}如果有对以后多数任务都适用的工作方式改进,调用 team 工具 evolve 更新 personality:整段重写而不是追加,不超过 ${PERSONALITY_LIMIT} 字,用平实中文,合并重复条目,删掉只针对某张卡的教训和「等待/冻结」类规则(只能改个性,不改名字/角色)。不要重开已完成的卡。`;
51
64
  }
52
65
  if (reason === 'member_message') {
53
66
  return 'Human 给你发了一条私信。先读消息,再用 team 工具按当前 tasks/thread 行动;不要把它当成新 Task。';
@@ -86,10 +99,15 @@ function promptFor(reason, state, taskId) {
86
99
  return 'PMO 会议进行中,你是正式参会成员。读取已完成 Task、Thread 与项目目标,从你的专业视角(UX/业务/执行/验收/编程)在 Thread 发表意见并 @owner;指出被忽略的用户体验、运营需求或风险,不重复他人结论,不自行开卡,不等待 Human。';
87
100
  }
88
101
  if (reason === 'wave_done') {
89
- return `Team event: 本批任务已全部验收(最后一张:${title}),看板已空。你是 PMO:用 team action=say 在主对话向 Human 汇报结果——完成了什么、产物在哪(路径)、怎么验证(命令与结果),并用 taskIds 附上这批卡。只汇报,不要在本回合续开新任务;是否继续由 PMO 推进节奏与 Human 决定。`;
102
+ const report = `Team event: 本批任务已全部验收(最后一张:${title}),看板已空。你是 PMO:先用 team action=say 在主对话向 Human 汇报结果——完成了什么、产物在哪(路径)、怎么验证(命令与结果),并用 taskIds 附上这批卡。`;
103
+ const project = Object.values(state.projects ?? {})[0];
104
+ if (project?.pmoAuto === false) {
105
+ return `${report}PMO 自动推进已关闭:汇报里写明你建议的下一批做什么,然后结束本回合,由 Human 决定是否继续。`;
106
+ }
107
+ return `${report}汇报完在同一回合里接着判断下一步:${CONTINUE_RULES}`;
90
108
  }
91
109
  if (reason === 'pmo_continue') {
92
- return 'PMO 自动推进:当前没有 active Task。先对照 Human 最近一次的指令判断目标是否已经达成:已达成且没有明确的后续价值 → 用 team action=say 在主对话简短说明「已完成、暂无后续」,然后结束本回合,不开新卡。确有必要继续时,先开一次复盘会议(读取已完成 Task、Thread 与核心 skill;在 Thread/@ 相关成员形成意见),据此产出验收标准与下一批 Task,并用 action=say 告诉 Human 新一批做什么、为什么;resultDefinition 必须可验证,qaRequired 必须有 qaChecklist。不要重复已完成卡,不要扩大到 Human 没要求的范围。自主续开有批次上限,用尽后 PMO 会暂停等 Human。';
110
+ return `PMO 自动推进:当前没有 active Task。${CONTINUE_RULES}`;
93
111
  }
94
112
  return `Team event: ${task?.title ?? taskId}。调用 team 工具查看 tasks/thread 后行动。`;
95
113
  }
@@ -0,0 +1,172 @@
1
+ /**
2
+ * 推迟到自然时间点的识别与纠偏(团队会话:PMO 宿主会话 + 成员)。
3
+ *
4
+ * 实机(il2c,11-16 10:39,PMO):「评审官并已立约今夜 03:17 自然相裁决点……这条我也会在明早盯一眼结果」。
5
+ * 那件事本可以当场手动跑一次(skillopt_run)并读退出码;而 03:17 的计划任务实际上每晚都以退出码 1 失败,
6
+ * 「等今夜自然跑」既推迟了 16 个小时,又把一个坏掉的环判成了「无需人工修」。同一类话术在 il2c 团队会话
7
+ * 里反复出现(「今夜」「明早」「夜拍」「03:17 自然相」「02:59 前」)。
8
+ *
9
+ * 规则只认「把行动挂在钟点上」:今夜/明早/某时某分 + 等待或行动的动词,或者「自然相/裁决点/夜拍」这类
10
+ * 把钟点当触发条件的说法。相对时长(「每 2 分钟查一次、最多 20 分钟」)是持续盯,不在此列。
11
+ */
12
+
13
+ // 只收本身就指向未来的日界词。「凌晨窗口离线」「夜间你不用盯了」「下一窗」这类叙述或黑话不算
14
+ // (r35 语料校准:il2c 198 条团队回复,宽规则 13 命中里 8 条是这类误报)。
15
+ const FUTURE_DAY = '今夜|今晚|今天晚上|明早|明晨|明天|明日|次日|后天';
16
+ const ACT = '(?:再|才|看|盯|复查|复核|裁决|裁定|处理|跑|执行|触发|开工|继续|推进|验收|检查|结果|自然(?:相|时点|时刻|触发))';
17
+ // 钟点只在带「等到/推迟到/届时」时才算推迟:「白砚在 23:03:05 被唤醒」「已于 02:44 派发」是叙述过去,
18
+ // 「02:59 前无票我即催办」是有截止的持续盯,都不该纠偏。
19
+ const WAIT_TO = '(?:等到|候到|待到|留到|推迟到|延到|延后到|改到|放到|挪到|到点|届时)';
20
+ const CLOCK = '[0-2]?\\d[::][0-5]\\d';
21
+ const NOT_NEGATED = '(?:(?!不用|无需|不必|不要|别)[^。;;\\n])';
22
+
23
+ const PATTERNS = [
24
+ // 等到今夜 / 候明早 / 届时明天
25
+ new RegExp(`(?:等到?|候|待|留到|推迟到|延到|延后到|改到|放到|挪到|届时|到)\\s*(?:${FUTURE_DAY})`),
26
+ // 今夜再跑 / 明早盯一眼 / 明天复查 / 今夜自然相(中间夹着「不用/无需」的不算)
27
+ new RegExp(`(?:${FUTURE_DAY})${NOT_NEGATED}{0,16}?${ACT}`),
28
+ // 等到 03:17 / 推迟到明早 09:00
29
+ new RegExp(`${WAIT_TO}\\s*(?:${FUTURE_DAY})?\\s*${CLOCK}`),
30
+ // 把钟点当触发条件:03:17 自然相 / 03:17 裁决点
31
+ new RegExp(`${CLOCK}\\s*的?\\s*(?:自然(?:相|时点|时刻|触发)|裁决点)`),
32
+ /\b(?:tonight|tomorrow(?: morning)?|overnight)\b|\bwait (?:until|till) \d{1,2}(?::\d{2})?\b/i,
33
+ ];
34
+
35
+ /**
36
+ * @param {string} text 一条助手回复
37
+ * @returns {{ phrase: string } | null} 命中的原文片段(便于纠偏消息引用与诊断)
38
+ */
39
+ export function detectDeferral(text) {
40
+ if (typeof text !== 'string' || text === '') return null;
41
+ for (const pattern of PATTERNS) {
42
+ const match = pattern.exec(text);
43
+ if (match !== null) {
44
+ const start = Math.max(0, match.index - 12);
45
+ const end = Math.min(text.length, match.index + match[0].length + 12);
46
+ return { phrase: text.slice(start, end).replace(/\s+/g, ' ').trim() };
47
+ }
48
+ }
49
+ return null;
50
+ }
51
+
52
+ /**
53
+ * 团队推进纪律:注入每个团队会话(PMO 宿主会话 + 成员)的系统提示词。
54
+ *
55
+ * 宿主 PMO 会话此前没有任何插件规程——它直接面对 Human,却从未被告知「不等钟点、不提前收兵、
56
+ * 先核实再宣称」。成员的规程散在三份 SKILL 里,也没有这几条。这里是这几条规则的唯一出处。
57
+ */
58
+ export const TEAM_DISCIPLINE_TEXT = [
59
+ '## 文渊阁团队推进纪律',
60
+ '- 立即行动:能现在做的事现在做,不把行动挂在钟点上(今夜、明早、某时某分、下个窗口)。定时任务和夜间环只是兜底;需要它的结果,就现在手动跑一次,读退出码和日志。',
61
+ '- 等待要有边界:等别人交付或外部进程时,现在就开始盯,说清隔多久查一次、最多盯多久;到时没结果就升级或换路,不空等。',
62
+ '- 不提前收兵:还有能推进的事,或下一步的前置条件已经满足,就继续做。只有三种情况可以停:目标已达成、自主批次已用尽、需要 Human 拍板;停的时候写明是哪一种。',
63
+ '- 先核实再宣称:说「正常」「已恢复」「会自动跑」之前,先读状态、退出码、日志时间戳,不凭推断。',
64
+ '- 用平实中文写:不自创术语和缩写,Human 和其他成员要能直接看懂。',
65
+ ].join('\n');
66
+
67
+ /**
68
+ * 把纪律段注册进宿主提示词组装,并在团队会话的回合即将结束时纠偏「推迟到钟点」。
69
+ *
70
+ * 用官方两个接缝,不另造通道:
71
+ * - `systemPrompt.section`:文本函数按本次组装的 agent 判定,只对团队会话返回正文;
72
+ * - `agent/turn-stopping`:回合要收尾时若最后一条回复把行动挂在钟点上,`agent.steer` 递一条纠偏,
73
+ * 同一回合继续(同一回合最多一次,第二次收尾放行——模型若写明了真实的时钟依赖,就不再纠缠)。
74
+ *
75
+ * @param {{
76
+ * systemPrompt?: any,
77
+ * on?: (name: string, listener: Function) => (() => void),
78
+ * teamProjectOf: (sessionId: string) => ({ projectId: string, stopped: boolean } | null),
79
+ * diag?: { append?: (row: object) => void },
80
+ * newId: () => string,
81
+ * }} options
82
+ * @returns {{ observe: (session: any, event: any) => void, stopping: (payload: any) => Promise<void>, dispose: () => void }}
83
+ */
84
+ export function registerTeamDiscipline({ systemPrompt, on, teamProjectOf, diag, newId }) {
85
+ const disposers = [];
86
+ // 团队会话 = 自己在账本里(PMO 宿主 / 已绑定成员),或父会话在账本里。后者覆盖两种情况:
87
+ // 成员激活时的第一个回合(提示词组装早于账本记下 sessionId,r36 实测成员首窗缺纪律段),
88
+ // 以及 PMO / 成员派生的临时子智能体(il2c:PMO 派生的 moyuan-tail267 承担了整个波尾)。
89
+ const projectFor = (sessionId, parentId) => {
90
+ if (typeof sessionId !== 'string') return null;
91
+ return teamProjectOf(sessionId) ?? (typeof parentId === 'string' && parentId !== '' ? teamProjectOf(parentId) : null);
92
+ };
93
+ const parentOf = (holder) => holder?.session?.header?.parentSession ?? holder?.header?.parentSession;
94
+ if (typeof systemPrompt?.section === 'function') {
95
+ let order = 600;
96
+ try { order = systemPrompt.getSectionOrder?.('TEAM_POLICY') ?? order; } catch { /* 旧宿主没有这个命名位置 */ }
97
+ disposers.push(systemPrompt.section({
98
+ name: 'ai-team:team-discipline',
99
+ order,
100
+ interpolate: false,
101
+ text: (context) => (projectFor(context?.agent?.id, parentOf(context?.agent)) !== null ? TEAM_DISCIPLINE_TEXT : ''),
102
+ }));
103
+ } else {
104
+ diag?.append?.({ ev: 'team.discipline.section.unavailable.fail' });
105
+ }
106
+ /** 每个团队会话本回合最后一条助手回复。 */
107
+ const lastText = new Map();
108
+ /** 本回合已纠偏过的会话(sessionId → turn)。 */
109
+ const steered = new Map();
110
+ /** @param {{ id?: string, header?: { parentSession?: string } }} session 宿主 session/event 的会话 */
111
+ const observe = (session, event) => {
112
+ const sessionId = session?.id;
113
+ if (typeof sessionId !== 'string') return;
114
+ if (event?.type === 'turn/start') {
115
+ lastText.delete(sessionId);
116
+ return;
117
+ }
118
+ if (event?.type !== 'assistant/message' || projectFor(sessionId, parentOf(session)) === null) return;
119
+ const content = event?.data?.message?.content;
120
+ const text = (Array.isArray(content) ? content : [])
121
+ .map((block) => (block?.type === 'text' ? block.text : ''))
122
+ .filter(Boolean)
123
+ .join('\n');
124
+ if (text !== '') lastText.set(sessionId, text);
125
+ };
126
+ const stopping = async (payload) => {
127
+ const agent = payload?.agent;
128
+ const sessionId = agent?.id;
129
+ if (typeof sessionId !== 'string' || typeof agent?.steer !== 'function') return;
130
+ const project = projectFor(sessionId, parentOf(agent));
131
+ if (project === null || project.stopped === true) return;
132
+ if (steered.get(sessionId) === payload?.turn) return;
133
+ const hit = detectDeferral(lastText.get(sessionId));
134
+ if (hit === null) return;
135
+ steered.set(sessionId, payload?.turn);
136
+ try {
137
+ agent.steer({
138
+ id: newId(),
139
+ role: 'user',
140
+ content: [{ type: 'text', text: deferralCorrection(hit.phrase) }],
141
+ source: { kind: 'ai-team' },
142
+ });
143
+ diag?.append?.({ ev: 'team.deferral.steered', projectId: project.projectId, sessionId, turn: payload?.turn ?? null, phrase: hit.phrase });
144
+ } catch (error) {
145
+ diag?.append?.({ ev: 'team.deferral.steer.fail', projectId: project.projectId, sessionId, message: error?.message ?? String(error) });
146
+ }
147
+ };
148
+ if (typeof on === 'function') disposers.push(on('agent/turn-stopping', stopping));
149
+ return {
150
+ observe,
151
+ stopping,
152
+ dispose: () => {
153
+ for (const dispose of disposers.splice(0)) {
154
+ try { dispose?.(); } catch { /* already disposed */ }
155
+ }
156
+ lastText.clear();
157
+ steered.clear();
158
+ },
159
+ };
160
+ }
161
+
162
+ /** 纠偏消息:同一回合最多一次,给出明确的「例外」出口,防止与真实钟点任务死磕。 */
163
+ export function deferralCorrection(phrase) {
164
+ return [
165
+ `【文渊阁·推进纪律】你刚才把行动推迟到了一个自然时间点:「${phrase}」。`,
166
+ '团队工作不等钟点:',
167
+ '1. 能现在做的,现在就做。定时任务、夜间环只是兜底;要用它的结果,就现在手动跑一次,并读退出码和日志。',
168
+ '2. 在等别人交付或外部进程,就现在开始盯:说清隔多久查一次、最多盯多久,到时没结果就升级或换路。',
169
+ '3. 只有事情本身依赖真实时钟(对方约定的时间、定时发布)才可以等,并用一句话写明依赖的是什么。',
170
+ '现在继续:要么立即执行,要么给出持续盯的安排,要么写明真实的时钟依赖。',
171
+ ].join('\n');
172
+ }
@@ -15,7 +15,7 @@ Common flags:
15
15
  --target-skill-path PATH explicit live SKILL.md to stage/adopt
16
16
  --tasks-file PATH reviewed TaskRecord JSON file to replay instead of harvesting
17
17
  --backend mock|claude|codex|copilot|cursor|pi|opencode|handoff|azure_openai
18
- --source claude|codex|copilot|copilot_cli|cursor|pi|opencode|auto
18
+ --source claude|codex|copilot|copilot_cli|cursor|pi|opencode|dsh|auto
19
19
  --vscode-workspace-storage PATH
20
20
  --copilot-cli-session-store PATH
21
21
  --opencode-db PATH
@@ -117,7 +117,7 @@ def _add_common(p: argparse.ArgumentParser) -> None:
117
117
  p.add_argument("--cursor-home", default="", help="override ~/.cursor for Cursor session harvest")
118
118
  p.add_argument("--pi-home", default="", help="override ~/.pi for Pi session harvest")
119
119
  p.add_argument("--source", default="",
120
- choices=["", "claude", "codex", "copilot", "copilot_cli", "cursor", "pi", "opencode", "auto"],
120
+ choices=["", "claude", "codex", "copilot", "copilot_cli", "cursor", "pi", "opencode", "dsh", "auto"],
121
121
  help="session transcript source")
122
122
  p.add_argument("--vscode-workspace-storage", default="",
123
123
  help="override VS Code User/workspaceStorage root for copilot source")
@@ -34,6 +34,8 @@ DEFAULTS: Dict[str, Any] = {
34
34
  "vscode_workspace_storage": "", # "" => auto-detect platform defaults
35
35
  "copilot_cli_session_store": "", # "" => ~/.copilot/session-store.db
36
36
  "opencode_db": "", # "" => OPENCODE_DB or the OpenCode XDG data path
37
+ "dsh_home": "", # "" => DSH_HOME or ~/.dsh (DeepSeek Harness sessions)
38
+ "dsh_node": "", # "" => DSH_NODE or `node` on PATH (decodes zstd session logs)
37
39
  # Explicit sources also include copilot, copilot_cli, cursor, pi, and opencode.
38
40
  # ``auto`` keeps the established Codex-then-Claude precedence.
39
41
  "transcript_source": "claude",
@@ -150,6 +152,11 @@ class SleepConfig:
150
152
  cursor_home = os.path.abspath(os.path.expanduser(str(self.data["cursor_home"])))
151
153
  return os.path.join(cursor_home, "projects")
152
154
 
155
+ @property
156
+ def dsh_sessions_dir(self) -> str:
157
+ home = self.data.get("dsh_home", "") or os.environ.get("DSH_HOME", "") or "~/.dsh"
158
+ return os.path.join(os.path.abspath(os.path.expanduser(str(home))), "sessions")
159
+
153
160
  @property
154
161
  def copilot_cli_session_store(self) -> str:
155
162
  value = self.data.get("copilot_cli_session_store", "") or ""
@@ -0,0 +1,61 @@
1
+ // SkillOpt-Sleep — decode one DeepSeek Harness session log to stdout.
2
+ //
3
+ // DSH stores every session as `<DSH_HOME>/sessions/<key>/<id>/session.v4.jsonl.zstd`:
4
+ // JSONL compressed as a series of zstd frames (one per flush). The Python
5
+ // standard library has no zstd decoder before 3.14, while every DSH install
6
+ // ships a Node runtime whose zlib has one — so the `dsh` transcript source runs
7
+ // this script and parses the JSONL it streams.
8
+ //
9
+ // Frames are decoded one at a time and written as soon as each completes:
10
+ // * the reader can stop after the header line (first frame) of a session that
11
+ // belongs to another project;
12
+ // * a session still being written ends in a partial frame — everything before
13
+ // it is emitted, the torn tail is dropped (a whole-stream decoder discards the
14
+ // already-decoded output of the read chunk that holds the error).
15
+ // A frame-magic match inside compressed bytes is not a boundary: such a segment
16
+ // fails to decode alone and is carried into the next one.
17
+ //
18
+ // Usage: node dsh_decode.mjs <session.v4.jsonl.zstd>
19
+ // Exit codes: 0 ok · 2 Node without zstd · 3 torn/corrupt tail dropped · 4 unreadable file.
20
+ import { readFileSync, writeSync } from 'node:fs';
21
+ import { zstdDecompressSync } from 'node:zlib';
22
+
23
+ const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
24
+ const [file] = process.argv.slice(2);
25
+ if (typeof zstdDecompressSync !== 'function') {
26
+ process.stderr.write(`dsh_decode: Node ${process.version} has no zstd support (needs >= 22.15)\n`);
27
+ process.exit(2);
28
+ }
29
+ let buffer;
30
+ try {
31
+ buffer = readFileSync(file);
32
+ } catch (error) {
33
+ process.stderr.write(`dsh_decode: ${error?.message ?? error}\n`);
34
+ process.exit(4);
35
+ }
36
+
37
+ const starts = [];
38
+ for (let at = buffer.indexOf(MAGIC); at !== -1; at = buffer.indexOf(MAGIC, at + 4)) starts.push(at);
39
+ let carryFrom = null;
40
+ for (let i = 0; i < starts.length; i += 1) {
41
+ const from = carryFrom ?? starts[i];
42
+ const to = starts[i + 1] ?? buffer.length;
43
+ let text;
44
+ try {
45
+ text = zstdDecompressSync(buffer.subarray(from, to));
46
+ } catch {
47
+ carryFrom = from;
48
+ continue;
49
+ }
50
+ carryFrom = null;
51
+ try {
52
+ writeSync(1, text);
53
+ } catch {
54
+ // The reader closed the pipe: it has what it needs.
55
+ process.exit(0);
56
+ }
57
+ }
58
+ if (carryFrom !== null) {
59
+ process.stderr.write('dsh_decode: torn or corrupt tail dropped\n');
60
+ process.exitCode = 3;
61
+ }
@@ -0,0 +1,279 @@
1
+ """SkillOpt-Sleep — DeepSeek Harness (DSH) session harvesting.
2
+
3
+ DSH keeps one append-only event log per session at
4
+ ``<DSH_HOME>/sessions/<key>/<sessionId>/session.v4.jsonl.zstd``. The JSONL is
5
+ zstd-compressed; it is decoded by ``dsh_decode.mjs`` under a Node runtime
6
+ (every DSH install ships one; Python's stdlib has no zstd before 3.14).
7
+
8
+ Schema (DSH session v4, ``packages/core/session/src/types.ts``):
9
+ * line 1 is the header: ``{"type": "session", "version": 4, "id", "createdAt",
10
+ "cwd", "parentSession"?, "origin"?}`` — ``cwd`` is the project the session
11
+ was opened in;
12
+ * every other line is ``{"type", "seq", "time" (epoch ms), "data"}``:
13
+ - ``user/message``: ``data.content`` blocks plus ``data.source.kind`` —
14
+ a human prompt or a host wake, or synthetic context (skill text,
15
+ reminders) under other kinds, which is not user intent;
16
+ - ``assistant/message``: ``data.message.content`` blocks — ``text`` is
17
+ kept, ``reasoning`` (private) is skipped;
18
+ - ``tool/call``: ``data.name`` (arguments are never copied).
19
+
20
+ AI-team member sessions are ordinary DSH sessions opened in the team's
21
+ workspace, so they match the invoked project like any other session.
22
+
23
+ This module performs NO writes and NO network calls.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import os
29
+ import re
30
+ import shutil
31
+ import subprocess
32
+ import time
33
+ from typing import Any, Iterator, List, Optional
34
+
35
+ from skillopt_sleep.harvest import (
36
+ _detect_feedback,
37
+ _is_headless_replay,
38
+ _is_meta_prompt,
39
+ _project_matches,
40
+ _text_from_content,
41
+ )
42
+ from skillopt_sleep.staging import redact_secrets
43
+ from skillopt_sleep.types import SessionDigest
44
+
45
+ SESSION_FILE = "session.v4.jsonl.zstd"
46
+ DECODER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dsh_decode.mjs")
47
+ # ``user/message`` sources that carry intent (counted on il2c, 11-16: a member
48
+ # session holds 1 ``user`` prompt and 37 ``agent-message`` relays):
49
+ # * ``user`` — the human's own prompt;
50
+ # * ``agent-message`` — messages relayed from another session; AI-team task
51
+ # wakes reach members this way ("Agent lead sent a message: … Team event: …");
52
+ # * ``ai-team`` — the plugin's in-turn correction (e.g. an action deferred to a
53
+ # clock time); it is kept and also recorded as negative feedback, because it
54
+ # marks the preceding reply as the wrong way to work.
55
+ # Host bookkeeping (``time-context``, ``runtime-context``, ``skill-catalog``,
56
+ # ``agent-instructions``, ``subagent-settled``, ``tool-jobs``, …) is not intent.
57
+ _INTENT_SOURCES = {"", "user", "agent-message", "ai-team"}
58
+ _RELAY_PREFIX = re.compile(r"^Agent \S+ sent a message:\s*")
59
+ # AI-team activation prompts start with the member's identity block
60
+ # (``memberIdentity`` in lib/domain/member-profile.js: "你是 <名>(<角色>)。"
61
+ # plus personality / skills / notes lines, then a blank line, then the
62
+ # prompt). Mined as intent, the identity is what every member session "asks
63
+ # for" (il2c harvest, 11-16: 6 of 16 tasks were personalities). Only the part
64
+ # after the block is the request.
65
+ _IDENTITY_HEAD = re.compile(r"^你是 [^\n]+([^\n]*)。\n")
66
+
67
+
68
+ def _strip_member_identity(text: str) -> str:
69
+ if not _IDENTITY_HEAD.match(text):
70
+ return text
71
+ _block, sep, rest = text.partition("\n\n")
72
+ return rest.strip() if sep else ""
73
+ # Host bookkeeping the loop delivers as user messages.
74
+ _HOST_NOISE = re.compile(
75
+ r"^(?:Time sampled while preparing turn|The working directory changed from|<system-reminder>)"
76
+ )
77
+
78
+
79
+ class DshSourceError(RuntimeError):
80
+ """The DSH source cannot run (no usable Node runtime)."""
81
+
82
+
83
+ def resolve_node(configured: str = "") -> str:
84
+ """Node used to decode sessions: config ``dsh_node`` > ``DSH_NODE`` > PATH."""
85
+ for candidate in (configured, os.environ.get("DSH_NODE", "")):
86
+ if candidate:
87
+ return candidate
88
+ found = shutil.which("node")
89
+ if found:
90
+ return found
91
+ raise DshSourceError(
92
+ "transcript_source 'dsh' needs a Node runtime (>= 22.15) to decode DSH sessions: "
93
+ "set dsh_node in ~/.skillopt-sleep/config.json or DSH_NODE "
94
+ "(DSH ships one at <install>/resources/runtime/primary-runtime/dependencies/node/bin/node.exe)"
95
+ )
96
+
97
+
98
+ def _iso_local(ms: Any) -> str:
99
+ if not isinstance(ms, (int, float)) or isinstance(ms, bool):
100
+ return ""
101
+ return time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(ms / 1000.0))
102
+
103
+
104
+ def _since_epoch(since_iso: Optional[str]) -> Optional[float]:
105
+ if not since_iso:
106
+ return None
107
+ try:
108
+ return time.mktime(time.strptime(since_iso[:19], "%Y-%m-%dT%H:%M:%S"))
109
+ except (ValueError, OverflowError):
110
+ return None
111
+
112
+
113
+ def _decoded_lines(node: str, path: str) -> Iterator[dict]:
114
+ """Stream the session's JSON records; closing the generator stops Node."""
115
+ proc = subprocess.Popen(
116
+ [node, DECODER, path],
117
+ stdout=subprocess.PIPE,
118
+ stderr=subprocess.DEVNULL,
119
+ )
120
+ try:
121
+ assert proc.stdout is not None
122
+ for raw in proc.stdout:
123
+ raw = raw.strip()
124
+ if not raw:
125
+ continue
126
+ try:
127
+ record = json.loads(raw.decode("utf-8"))
128
+ except (UnicodeDecodeError, ValueError):
129
+ # A session still being written ends in a partial line.
130
+ continue
131
+ if isinstance(record, dict):
132
+ yield record
133
+ finally:
134
+ if proc.poll() is None:
135
+ proc.kill()
136
+ if proc.stdout is not None:
137
+ proc.stdout.close()
138
+ proc.wait()
139
+
140
+
141
+ def _dedup(xs: List[str]) -> List[str]:
142
+ seen: set = set()
143
+ out: List[str] = []
144
+ for x in xs:
145
+ if x not in seen:
146
+ seen.add(x)
147
+ out.append(x)
148
+ return out
149
+
150
+
151
+ def digest_dsh_session(path: str, *, node: str, project: str = "") -> Optional[SessionDigest]:
152
+ """Build a :class:`SessionDigest` from one DSH session log.
153
+
154
+ With ``project`` set, the header's ``cwd`` is checked first and the rest of
155
+ the log is never decoded for sessions of other projects.
156
+ """
157
+ records = _decoded_lines(node, path)
158
+ try:
159
+ header = next(records, None)
160
+ if not isinstance(header, dict) or header.get("type") != "session":
161
+ return None
162
+ cwd = header.get("cwd") if isinstance(header.get("cwd"), str) else ""
163
+ # An empty cwd would resolve against the engine's own working directory.
164
+ if project and (not cwd or not _project_matches(cwd, "invoked", project)):
165
+ return None
166
+ session_id = str(header.get("id") or os.path.basename(os.path.dirname(path)))
167
+ started = _iso_local(header.get("createdAt"))
168
+ ended = started
169
+ user_prompts: List[str] = []
170
+ assistant_finals: List[str] = []
171
+ tools: List[str] = []
172
+ feedback: List[str] = []
173
+ n_user = 0
174
+ n_asst = 0
175
+ for rec in records:
176
+ stamp = _iso_local(rec.get("time"))
177
+ if stamp:
178
+ ended = stamp
179
+ rtype = rec.get("type")
180
+ data = rec.get("data") if isinstance(rec.get("data"), dict) else {}
181
+ if rtype == "user/message":
182
+ source = data.get("source") if isinstance(data.get("source"), dict) else {}
183
+ kind = str(source.get("kind") or "")
184
+ if kind not in _INTENT_SOURCES:
185
+ continue
186
+ text = str(redact_secrets(_text_from_content(data.get("content")))).strip()
187
+ if kind == "agent-message":
188
+ text = _RELAY_PREFIX.sub("", text, count=1)
189
+ text = _strip_member_identity(text)
190
+ if not text or _HOST_NOISE.match(text) or _is_meta_prompt(text):
191
+ continue
192
+ n_user += 1
193
+ user_prompts.append(text)
194
+ feedback.extend(_detect_feedback(text))
195
+ if kind == "ai-team":
196
+ feedback.append("neg:ai-team-correction")
197
+ elif rtype == "assistant/message":
198
+ message = data.get("message") if isinstance(data.get("message"), dict) else {}
199
+ n_asst += 1
200
+ text = _text_from_content(message.get("content")).strip()
201
+ if text:
202
+ assistant_finals.append(str(redact_secrets(text)).strip())
203
+ elif rtype == "tool/call":
204
+ name = data.get("name")
205
+ if isinstance(name, str) and name:
206
+ tools.append(re.sub(r"[^A-Za-z0-9_.:-]+", "_", name)[:80])
207
+ finally:
208
+ records.close()
209
+
210
+ if n_user == 0 and n_asst == 0:
211
+ return None
212
+ digest = SessionDigest(
213
+ session_id=session_id,
214
+ project=cwd,
215
+ started_at=started,
216
+ ended_at=ended,
217
+ user_prompts=user_prompts,
218
+ assistant_finals=assistant_finals[-5:],
219
+ tools_used=_dedup(tools),
220
+ files_touched=[],
221
+ feedback_signals=_dedup(feedback),
222
+ n_user_turns=n_user,
223
+ n_assistant_turns=n_asst,
224
+ raw_path=path,
225
+ )
226
+ if _is_headless_replay(digest):
227
+ return None
228
+ return digest
229
+
230
+
231
+ def harvest_dsh(
232
+ sessions_dir: str,
233
+ *,
234
+ node: str = "",
235
+ scope: Any = "all",
236
+ invoked_project: str = "",
237
+ since_iso: Optional[str] = None,
238
+ limit: int = 0,
239
+ ) -> List[SessionDigest]:
240
+ """Walk ``<DSH_HOME>/sessions`` (newest first) and return digests.
241
+
242
+ Parameters mirror :func:`skillopt_sleep.harvest.harvest`. Sessions whose log
243
+ has not been written since ``since_iso`` are skipped without decoding.
244
+ """
245
+ digests: List[SessionDigest] = []
246
+ if not os.path.isdir(sessions_dir):
247
+ return digests
248
+ node = resolve_node(node)
249
+ since = _since_epoch(since_iso)
250
+
251
+ paths: List[tuple[float, str]] = []
252
+ for key in os.listdir(sessions_dir):
253
+ key_dir = os.path.join(sessions_dir, key)
254
+ if not os.path.isdir(key_dir):
255
+ continue
256
+ for session in os.listdir(key_dir):
257
+ path = os.path.join(key_dir, session, SESSION_FILE)
258
+ try:
259
+ mtime = os.path.getmtime(path)
260
+ except OSError:
261
+ continue
262
+ if since is not None and mtime < since:
263
+ continue
264
+ paths.append((mtime, path))
265
+ paths.sort(key=lambda item: item[0], reverse=True)
266
+
267
+ project_hint = invoked_project if scope == "invoked" else ""
268
+ for _mtime, path in paths:
269
+ digest = digest_dsh_session(path, node=node, project=project_hint)
270
+ if digest is None:
271
+ continue
272
+ if not _project_matches(digest.project or "", scope, invoked_project):
273
+ continue
274
+ if since_iso and digest.ended_at and digest.ended_at < since_iso:
275
+ continue
276
+ digests.append(digest)
277
+ if limit and len(digests) >= limit:
278
+ break
279
+ return digests
@@ -8,6 +8,7 @@ from skillopt_sleep.harvest_codex import harvest_codex
8
8
  from skillopt_sleep.harvest_copilot import harvest_copilot
9
9
  from skillopt_sleep.harvest_copilot_cli import harvest_copilot_cli
10
10
  from skillopt_sleep.harvest_cursor import harvest_cursor
11
+ from skillopt_sleep.harvest_dsh import harvest_dsh
11
12
  from skillopt_sleep.harvest_opencode import harvest_opencode
12
13
  from skillopt_sleep.harvest_pi import harvest_pi
13
14
  from skillopt_sleep.types import SessionDigest
@@ -20,6 +21,7 @@ SUPPORTED_SOURCES = (
20
21
  "cursor",
21
22
  "pi",
22
23
  "opencode",
24
+ "dsh",
23
25
  "auto",
24
26
  )
25
27
 
@@ -114,6 +116,15 @@ def harvest_for_config(
114
116
  since_iso=since_iso,
115
117
  limit=limit,
116
118
  )
119
+ if source == "dsh":
120
+ return harvest_dsh(
121
+ cfg.dsh_sessions_dir,
122
+ node=cfg.get("dsh_node", "") or "",
123
+ scope=scope,
124
+ invoked_project=invoked_project,
125
+ since_iso=since_iso,
126
+ limit=limit,
127
+ )
117
128
  if source == "auto":
118
129
  codex_digests = harvest_codex(
119
130
  cfg.codex_archived_sessions_dir,
@@ -65,11 +65,37 @@ def _win_task_name(project: str) -> str:
65
65
  return f"SkillOpt-Sleep-{digest}"
66
66
 
67
67
 
68
+ def _console_encoding() -> str:
69
+ """The code page schtasks.exe writes its output in.
70
+
71
+ schtasks prints in the console OEM code page (CP936 on a Chinese system),
72
+ not in Python's preferred encoding. Under UTF-8 mode (``-X utf8`` /
73
+ ``PYTHONUTF8=1``) ``text=True`` decoded that output as UTF-8: the reader
74
+ thread raised UnicodeDecodeError and ``proc.stdout`` came back ``None``, so
75
+ ``_list_win_tasks`` silently listed nothing.
76
+ """
77
+ try:
78
+ import ctypes
79
+
80
+ return f"cp{ctypes.windll.kernel32.GetOEMCP()}"
81
+ except Exception:
82
+ return "mbcs" if sys.platform == "win32" else "utf-8"
83
+
84
+
85
+ def _run_schtasks(args: List[str]) -> subprocess.CompletedProcess:
86
+ return subprocess.run(
87
+ ["schtasks", *args],
88
+ capture_output=True,
89
+ text=True,
90
+ encoding=_console_encoding(),
91
+ errors="replace",
92
+ )
93
+
94
+
68
95
  def _create_win_task(task_name: str, command: str, hour: int, minute: int) -> bool:
69
96
  try:
70
97
  st = f"{hour:02d}:{minute:02d}"
71
- cmd = ["schtasks", "/create", "/tn", task_name, "/tr", command, "/sc", "daily", "/st", st, "/f"]
72
- proc = subprocess.run(cmd, capture_output=True, text=True)
98
+ proc = _run_schtasks(["/create", "/tn", task_name, "/tr", command, "/sc", "daily", "/st", st, "/f"])
73
99
  return proc.returncode == 0
74
100
  except Exception:
75
101
  return False
@@ -77,8 +103,7 @@ def _create_win_task(task_name: str, command: str, hour: int, minute: int) -> bo
77
103
 
78
104
  def _delete_win_task(task_name: str) -> bool:
79
105
  try:
80
- cmd = ["schtasks", "/delete", "/tn", task_name, "/f"]
81
- proc = subprocess.run(cmd, capture_output=True, text=True)
106
+ proc = _run_schtasks(["/delete", "/tn", task_name, "/f"])
82
107
  return proc.returncode == 0
83
108
  except Exception:
84
109
  return False
@@ -86,7 +111,7 @@ def _delete_win_task(task_name: str) -> bool:
86
111
 
87
112
  def _list_win_tasks() -> List[str]:
88
113
  try:
89
- proc = subprocess.run(["schtasks", "/query", "/fo", "csv"], capture_output=True, text=True)
114
+ proc = _run_schtasks(["/query", "/fo", "csv"])
90
115
  if proc.returncode != 0:
91
116
  return []
92
117
  tasks = []
@@ -129,14 +154,29 @@ def _runner_cmd(project: str, backend: str, extra: str, python: str) -> str:
129
154
  helper_script = os.path.join(logdir, "run.ps1")
130
155
  try:
131
156
  os.makedirs(logdir, exist_ok=True)
132
- quoted = " ".join(_powershell_literal(value) for value in args[1:])
157
+ # `-X utf8`: the engine's output is decoded as UTF-8 below, whatever the
158
+ # system code page is (CP936 here garbled every Chinese log line).
159
+ quoted = " ".join(_powershell_literal(value) for value in ["-X", "utf8", *args[1:]])
160
+ # Windows PowerShell 5.1 turns every native stderr line into an
161
+ # ErrorRecord; under `Stop` the first one aborts the script with exit 1
162
+ # before it is even logged. The engine reports progress on stderr
163
+ # (`[sleep] ...`), so the old `Stop` + `*>>` helper failed every night
164
+ # (Task Scheduler LastTaskResult=1, cron.log never written). `Stop`
165
+ # only guards Set-Location; the engine runs under `Continue`, both
166
+ # streams land in the log as plain lines, and the task reports the
167
+ # engine's own exit code.
133
168
  content = (
134
169
  "$ErrorActionPreference = 'Stop'\n"
170
+ "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\n"
135
171
  f"Set-Location -LiteralPath {_powershell_literal(_repo_root())}\n"
136
- f"& {_powershell_literal(python)} {quoted} "
137
- f"*>> {_powershell_literal(log)}\n"
172
+ "$ErrorActionPreference = 'Continue'\n"
173
+ f"& {_powershell_literal(python)} {quoted} 2>&1 "
174
+ f"| ForEach-Object {{ \"$_\" }} >> {_powershell_literal(log)}\n"
175
+ "exit $LASTEXITCODE\n"
138
176
  )
139
- with open(helper_script, "w", encoding="utf-8") as f:
177
+ # BOM: Windows PowerShell 5.1 reads a BOM-less script in the ANSI code
178
+ # page, which breaks non-ASCII project paths.
179
+ with open(helper_script, "w", encoding="utf-8-sig") as f:
140
180
  f.write(content)
141
181
  except OSError as exc:
142
182
  raise ValueError(f"could not create the Windows scheduler helper: {exc}") from exc
@@ -286,7 +286,7 @@ export function apply(ctx, config = {}) {
286
286
  'Preview a full sleep cycle without staging anything: harvest, mine, replay, report.',
287
287
  parameters: {
288
288
  project: { type: 'string', description: 'Project directory' },
289
- source: { type: 'string', description: 'Transcript source: claude|codex|copilot|cursor|pi|opencode|auto' },
289
+ source: { type: 'string', description: 'Transcript source: claude|codex|copilot|cursor|pi|opencode|dsh|auto (dsh = DeepSeek Harness sessions, incl. AI-team members)' },
290
290
  backend: { type: 'string', description: 'Backend: mock|claude|codex|copilot|cursor|pi|opencode|handoff|azure_openai' },
291
291
  model: { type: 'string', description: 'Backend model override' },
292
292
  maxTasks: { type: 'number', description: 'Cap mined tasks (default 40)' },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.99",
3
+ "version": "0.4.103",
4
4
  "type": "module",
5
5
  "description": "文渊阁 (Wenyuan Pavilion) — AI Team mode for DeepSeek Harness: concurrent projects, owned tasks, threads, inbox and an append-only team ledger",
6
6
  "license": "MIT",
@@ -30,6 +30,7 @@
30
30
  "exports": {
31
31
  ".": "./index.js",
32
32
  "./client": "./client.js",
33
+ "./package.json": "./package.json",
33
34
  "./lib/*": "./lib/*",
34
35
  "./locale/*.json": "./locale/*.json",
35
36
  "./icon": "./icon.svg"
@@ -46,6 +47,7 @@
46
47
  "lib/**/*.js",
47
48
  "lib/vendor/skillopt/scripts/*.py",
48
49
  "lib/vendor/skillopt/skillopt_sleep/**/*.py",
50
+ "lib/vendor/skillopt/skillopt_sleep/**/*.mjs",
49
51
  "lib/vendor/skillopt/requirements.txt",
50
52
  "lib/vendor/skillopt/LICENSE",
51
53
  "skills/**/*",
@@ -60,17 +60,24 @@ skillopt_run project=<dir> backend=<codex|claude|…> preferences="Prefer pytest
60
60
  # 4. review the report, then adopt
61
61
  skillopt_adopt project=<dir>
62
62
 
63
- # 5. schedule nightly at 03:17
63
+ # 5. (optional) schedule nightly at 03:17 as a background safety net
64
64
  skillopt_schedule project=<dir> hour=3 minute=17 backend=<codex>
65
65
  ```
66
66
 
67
+ **A schedule is a safety net, never a plan.** When the team needs a cycle's
68
+ result — to verify a fix, unblock a card, or answer "did the loop work?" — run
69
+ `skillopt_run` now and read its exit code and report. Do not wait for the next
70
+ 03:17 trigger, and do not declare a scheduled loop healthy without reading the
71
+ task's last result and the `cron.log` timestamp: a trigger that fires every
72
+ night can still fail every night.
73
+
67
74
  ## Parameters
68
75
 
69
76
  | Parameter | Default | Meaning |
70
77
  |---|---|---|
71
78
  | `project` | config or cwd | project directory to evolve |
72
79
  | `backend` | `mock` | `mock\|claude\|codex\|copilot\|cursor\|pi\|opencode\|handoff\|azure_openai` (mock = no model calls) |
73
- | `source` | config | transcript source: `claude\|codex\|copilot\|cursor\|pi\|opencode\|auto` |
80
+ | `source` | config | transcript source: `claude\|codex\|copilot\|cursor\|pi\|opencode\|dsh\|auto` — `dsh` reads DeepSeek Harness sessions (AI-team members included) whose working directory is the project; schedule it with `project=<workspace>` |
74
81
  | `model` | backend default | replay model override |
75
82
  | `maxTasks` | 40 | mined-task cap |
76
83
  | `preferences` | empty | house rules for the reflection prior (e.g. "always use async/await") |