@suifei/dsh-ai-team 0.4.27 → 0.4.29

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 (42) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/index.js +57 -5
  3. package/lib/host/decision-report.js +2 -2
  4. package/lib/host/project-registry.js +6 -2
  5. package/lib/host/service.js +33 -8
  6. package/lib/host/waker.js +2 -2
  7. package/lib/ledger/writer.js +49 -12
  8. package/lib/runtime/host-agent.js +3 -0
  9. package/lib/runtime/host-repair.js +3 -0
  10. package/lib/runtime/member-runtime.js +20 -0
  11. package/lib/runtime/skill-provider.js +4 -1
  12. package/lib/skillopt/gate-wiring.js +24 -4
  13. package/package.json +3 -3
  14. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/__init__.cpython-311.pyc +0 -0
  15. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/__main__.cpython-311.pyc +0 -0
  16. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/backend.cpython-311.pyc +0 -0
  17. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/budget.cpython-311.pyc +0 -0
  18. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/config.cpython-311.pyc +0 -0
  19. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/consolidate.cpython-311.pyc +0 -0
  20. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/cycle.cpython-311.pyc +0 -0
  21. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/dream.cpython-311.pyc +0 -0
  22. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/evidence.cpython-311.pyc +0 -0
  23. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/gate.cpython-311.pyc +0 -0
  24. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/handoff_backend.cpython-311.pyc +0 -0
  25. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest.cpython-311.pyc +0 -0
  26. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_codex.cpython-311.pyc +0 -0
  27. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_copilot.cpython-311.pyc +0 -0
  28. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_copilot_cli.cpython-311.pyc +0 -0
  29. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_cursor.cpython-311.pyc +0 -0
  30. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_opencode.cpython-311.pyc +0 -0
  31. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_pi.cpython-311.pyc +0 -0
  32. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/harvest_sources.cpython-311.pyc +0 -0
  33. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/judges.cpython-311.pyc +0 -0
  34. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/memory.cpython-311.pyc +0 -0
  35. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/mine.cpython-311.pyc +0 -0
  36. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/multi_skill.cpython-311.pyc +0 -0
  37. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/replay.cpython-311.pyc +0 -0
  38. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/skill_resolver.cpython-311.pyc +0 -0
  39. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/staging.cpython-311.pyc +0 -0
  40. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/state.cpython-311.pyc +0 -0
  41. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/tasks_file.cpython-311.pyc +0 -0
  42. package/lib/vendor/skillopt/skillopt_sleep/__pycache__/types.cpython-311.pyc +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.29 - 2026-11-12
4
+
5
+ **第二轮审计批次 3:成员唤醒与归档修复补全**
6
+
7
+ - **第二次唤醒不再丢上下文**:冷恢复拿到的 AgentHandle 现在由 runtime 自己记住;此前 session 变 live 后第二次唤醒会回退到 `subagent.sendMessage`,manager 再做一次冷恢复并以 `NOT_RESUMABLE` 失败,触发上层强制重建、丢掉成员历史(handle 失效时才回退并清理)。
8
+ - **归档修复覆盖成员会话自身**:sweep 之前只处理 host 一代;成员会话被单独归档时该成员每回合仍永久 `blocked`。现在 member session 本身也进 victims。
9
+ - **roots() 快路径也解归档**:选中 Human 根会话时若它已归档,成员血缘被 gate 永久拒绝,而 sweep 因没有 hostSessionId 看不到它。
10
+ - **面板作者名**:`bootstrap` 的 stream 投影补 `author`(客户端读 `item.author`,账本只有 `authorId`),主对话与 Thread 不再恒显示「—」。
11
+ - **决策表章节号**:识别中文序号「六」,以 `## 六、…` 写的第 6 节决策表不再解析不出问题。
12
+ - **唤醒 prompt 截断**:Main stream 的 Human 正文截到 2000 字符,1MB 级粘贴不再整段进入 Project owner 上下文。
13
+ - 测试:`node --test` **203/203**。
14
+
15
+ ## 0.4.28 - 2026-11-12
16
+
17
+ **第二轮审计:8 条 HIGH + 工作台 409 修复**
18
+
19
+ - **工作台不可达(409)**:`bootstrap` 曾用「过滤掉归档项目」的列表判定存在性,于是账本里存在、只是已归档的项目被报成 `E_NOT_FOUND`,与 `board()`/`quadrants()` 口径矛盾;归档当前 active 项目时 `booted.activeProjectId` 仍指向已归档账本,刷新后工作台停在错误页。现在存在性按未过滤记录判定,归档项目返回只读视图;无参 bootstrap 使用「该 runtime 账本里真实存在的项目」;归档 active 后自动切到 registry 的 fallback;`ProjectRegistry.setActive` 拒绝归档项目。
20
+ - **账本**:poison 闸门移入写队列——同一 tick 并发的两个批次曾同时通过入口检查,先失败者置毒后另一个仍按旧 head 写出重复 seq,账本此后永久打不开;`lock.takeover` 标记现在带 pid/startedAt 且超过 10s 可回收,清理失败会告警而非静默。
21
+ - **技能加载**:frontmatter 按 `\r\n|\r|\n` 切分。此前 CRLF 文件的最后一行整行失配(`\r` 是 JS 行终止符,`^…$` 越不过),description 位于末尾的 SKILL.md 会被当成「缺少 description」丢弃——包括插件自带的 skillopt-sleep。
22
+ - **命令注入**:SkillOpt gate 新增 `assertSafeProjectDir`,模型可控的 project 必须是真实存在的绝对目录且不含 shell 元字符;仅靠 `quoteArgv` 的双引号挡不住 `$(...)`/反引号。
23
+ - **项目创建**:`project.create` 先校验工作目录再写 registry,避免一个打不开的项目让下次 boot 全线 503;`project.activate` 透传 `workspacePath`,否则账本把它写成空、成员激活永远 `E_WORKSPACE_REQUIRED`。
24
+ - **adopt 门**:keep 记录的查找覆盖工作区与所有 runtime 数据目录(optimize 写在后者,adopt 之前只查前者,导致恒被拒)。引擎 staging 与评审通道两条流水线的候选仍不同源,失败关闭并记录为设计缺口。
25
+ - **打包**:vendor 通配收窄为 `*.py`,`__pycache__/*.pyc` 不再进入发布包(142 → 113 文件、796 → 468 kB)。
26
+ - 测试:`node --test` **200/200**。
27
+
3
28
  ## 0.4.27 - 2026-11-12
4
29
 
5
30
  **审计 LOW 收尾(195/195)**
package/index.js CHANGED
@@ -11,7 +11,7 @@
11
11
  import { homedir } from 'node:os';
12
12
  import { join } from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
- import { existsSync, readFileSync, writeFileSync } from 'node:fs';
14
+ import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';
15
15
  import z from '@deepseek-ai/schemastery';
16
16
  import { ProjectRuntime } from './lib/host/project-runtime.js';
17
17
  import { ProjectRegistry } from './lib/host/project-registry.js';
@@ -991,7 +991,21 @@ export function apply(ctx, config = {}) {
991
991
  readPair,
992
992
  // 两阶段异步模式:工具 execute 内无法等待子代理,判据改为
993
993
  // results.tsv 中该 skill 已存在 paired keep 记录(同步可查)。
994
- hasKeepRecord: async ({ projectDir, skillPath, candidate }) => hasPairedKeepRecord(projectDir, skillPath, candidate),
994
+ // results.tsv 的写入根是插件数据目录(job.project = runtime.dir),而
995
+ // adopt 门拿到的是模型传入的 args.project(通常是工作区)。只查后者的
996
+ // 话,keep 记录永远找不到、adopt 恒被拒——这里把两个根都查。
997
+ hasKeepRecord: async ({ projectDir, skillPath, candidate }) => {
998
+ const roots = new Set();
999
+ if (typeof projectDir === 'string' && projectDir !== '') roots.add(projectDir);
1000
+ for (const runtime of booted?.runtimes?.values() ?? []) {
1001
+ if (typeof runtime?.dir === 'string' && runtime.dir !== '') roots.add(runtime.dir);
1002
+ }
1003
+ for (const root of roots) {
1004
+ if (hasPairedKeepRecord(root, skillPath, candidate)) return true;
1005
+ }
1006
+ diag.append({ ev: 'skillopt.adoptgate.norecord.fail', projectDir: projectDir ?? null, skillPath: skillPath ?? null, roots: roots.size });
1007
+ return false;
1008
+ },
995
1009
  diag: (line, extra) => diag.append({
996
1010
  ev: extra?.ev ?? 'skillopt.adoptgate',
997
1011
  message: line,
@@ -1847,8 +1861,16 @@ export function apply(ctx, config = {}) {
1847
1861
  if (req.method === 'GET' && url.pathname === '/ai-team/api/bootstrap') {
1848
1862
  const requested = url.searchParams.get('project');
1849
1863
  const requestedRuntime = requested === null ? null : projectRuntime(requested);
1850
- const bootstrapRuntime = requestedRuntime ?? currentRuntime();
1851
- const bootstrap = bootstrapRuntime.service.bootstrap(bootstrapRuntime.id);
1864
+ // 账本里真实存在的项目(registry 的 active 可能与正在服务的账本脱钩)。
1865
+ const servedProjects = (runtime) => Object.keys(runtime?.service?.state?.projects ?? {});
1866
+ let bootstrapRuntime = requestedRuntime ?? currentRuntime();
1867
+ if (requested === null && servedProjects(bootstrapRuntime).length === 0 && servedProjects(booted?.runtime).length > 0) {
1868
+ bootstrapRuntime = booted.runtime;
1869
+ }
1870
+ // 隐式请求用该 runtime 账本里的第一个项目;显式传了不存在的 id 仍由
1871
+ // service 的严格校验报错(保留审计修复,不再静默返回空壳)。
1872
+ const servedProjectId = servedProjects(bootstrapRuntime)[0] ?? bootstrapRuntime.id;
1873
+ const bootstrap = bootstrapRuntime.service.bootstrap(requested === null ? servedProjectId : bootstrapRuntime.id);
1852
1874
  // 跨项目收件箱聚合:其它项目只读 state.inbox 过滤(此前对每个
1853
1875
  // 项目整调 bootstrap——board+quadrants+threads 全算,O(项目数×
1854
1876
  // 全视图)/请求)。
@@ -2035,7 +2057,20 @@ export function apply(ctx, config = {}) {
2035
2057
  if (name === '') return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: 'project name is required' } }, 400);
2036
2058
  // 工作目录可空(稍后设置):讨论与建卡不受限;成员激活在
2037
2059
  // activateMember 处 fail-closed,绝不落到宿主默认目录执行。
2060
+ // 但给了就必须真实存在:非法路径若先写进 registry,boot 会在
2061
+ // 该项上抛出,导致整个插件起不来(所有路由 503),只能手工改
2062
+ // projects.json 才能恢复。
2063
+ if (workspacePath !== '') {
2064
+ let stat = null;
2065
+ try { stat = statSync(workspacePath); } catch { stat = null; }
2066
+ if (stat === null || (typeof stat.isDirectory === 'function' && stat.isDirectory() !== true)) {
2067
+ return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: `工作目录不存在或不是目录:${workspacePath}` } }, 400);
2068
+ }
2069
+ }
2038
2070
  const id = ids.project();
2071
+ // 先校验工作目录(上面已做),再写 registry、最后开 runtime:
2072
+ // activateProject 内部会调用 registry.setActive(id),因此该行必须已
2073
+ // 存在。校验前置后,不会再把一个打不开的项目写进 projects.json。
2039
2074
  booted.registry.add({ id, name, goal, workspacePath });
2040
2075
  const next = await activateProject(id, name, goal, workspacePath);
2041
2076
  return send(res, { ok: true, project: next.service.state.projects[id] ?? { id, name } });
@@ -2046,7 +2081,9 @@ export function apply(ctx, config = {}) {
2046
2081
  return send(res, { error: { code: 'NOT_FOUND', message: 'project not found' } }, 404);
2047
2082
  }
2048
2083
  const record = booted.registry.list().find((project) => project.id === target);
2049
- const next = await activateProject(target, record?.name, record?.goal);
2084
+ // 透传 workspacePath:否则账本里的 project/created 会把工作目录写成空,
2085
+ // 之后该项目的成员激活永远 E_WORKSPACE_REQUIRED。
2086
+ const next = await activateProject(target, record?.name, record?.goal, record?.workspacePath);
2050
2087
  return send(res, { ok: true, project: next.service.state.projects[target] ?? record });
2051
2088
  }
2052
2089
  if (body.type === 'member.activate') {
@@ -2125,6 +2162,21 @@ export function apply(ctx, config = {}) {
2125
2162
  } catch (error) {
2126
2163
  diag.append({ ev: 'project.archive.registry.fail', projectId: runtime.id, message: error?.message ?? String(error) });
2127
2164
  }
2165
+ // 归档的正是当前 active:必须同步把 booted 指向 registry 选出的
2166
+ // fallback,否则无参 bootstrap 仍落在已归档 runtime 上 → 工作台
2167
+ // 直接 UNREACHABLE,刷新后也没有项目树可切走,只能重启宿主。
2168
+ if (booted.activeProjectId === runtime.id) {
2169
+ const fallbackId = booted.registry.activeProjectId;
2170
+ const fallback = booted.registry.list().find((project) => project.id === fallbackId);
2171
+ if (fallback !== undefined && fallback.id !== runtime.id) {
2172
+ try {
2173
+ await activateProject(fallback.id, fallback.name, fallback.goal, fallback.workspacePath);
2174
+ diag.append({ ev: 'project.archive.reactivated', from: runtime.id, to: fallback.id });
2175
+ } catch (error) {
2176
+ diag.append({ ev: 'project.archive.reactivate.fail', from: runtime.id, to: fallback.id, message: error?.message ?? String(error) });
2177
+ }
2178
+ }
2179
+ }
2128
2180
  }
2129
2181
  // 退役/离队后必须释放常驻子代理:否则 activation 句柄只在 force
2130
2182
  // 重建或插件卸载时才回收,退役成员的会话会一直挂在进程里。
@@ -1,4 +1,4 @@
1
- /**
1
+ /**
2
2
  * Read the Human-decision table from a linked Markdown report.
3
3
  *
4
4
  * This is deliberately narrow: only a report containing a section titled
@@ -37,7 +37,7 @@ export function findReportPath(text) {
37
37
 
38
38
  export function parseDecisionQuestions(markdown) {
39
39
  const lines = String(markdown ?? '').split(/\r?\n/);
40
- const start = lines.findIndex((line) => /^##\s*6[.、\s]/.test(line) || /^##\s*6\s*$/.test(line));
40
+ const start = lines.findIndex((line) => /^##\s*(6|六)[.、\s]/.test(line) || /^##\s*(6|六)\s*$/.test(line));
41
41
  if (start < 0) return [];
42
42
  let end = lines.length;
43
43
  for (let index = start + 1; index < lines.length; index += 1) {
@@ -1,4 +1,4 @@
1
- /** Lightweight Project index. The ledger remains the source of truth for Project state. */
1
+ /** Lightweight Project index. The ledger remains the source of truth for Project state. */
2
2
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { DEFAULT_PROJECT_ID } from './project-runtime.js';
@@ -56,7 +56,11 @@ export class ProjectRegistry {
56
56
  }
57
57
 
58
58
  setActive(id) {
59
- if (!this.projects.some((project) => project.id === id)) throw new Error(`unknown project: ${id}`);
59
+ const project = this.projects.find((entry) => entry.id === id);
60
+ if (project === undefined) throw new Error(`unknown project: ${id}`);
61
+ // 归档项目不能成为 active:registry 的 active 会被 bootstrap 当作「默认项目」,
62
+ // 指向一个已归档/无账本的项目会让工作台直接不可达。
63
+ if (project.archived === true) throw new Error(`project ${id} is archived`);
60
64
  this.activeProjectId = id;
61
65
  this.save();
62
66
  }
@@ -154,7 +154,11 @@ export class TeamService {
154
154
  /** One page of workbench state; the UI reads this instead of the ledger. */
155
155
  bootstrap(projectId, threadTaskId) {
156
156
  const state = this.state;
157
- const projects = Object.values(state.projects ?? {})
157
+ // 归档项目仍要被「看见」:列表里过滤掉它们,但存在性判定必须用未过滤的
158
+ // 记录——否则归归档项目会被报成 E_NOT_FOUND,与 board()/quadrants() 的口径
159
+ // 打架,且客户端把归档项目渲染成可点的只读行,选中即失败。
160
+ const allProjectRecords = Object.values(state.projects ?? {});
161
+ const projects = allProjectRecords
158
162
  .filter((p) => p.status !== 'archived')
159
163
  .map((p) => ({
160
164
  id: p.id, name: p.name, goal: p.goal ?? '', owner: p.ownerName ?? p.ownerMemberId ?? p.ownerId, workspacePath: p.workspacePath ?? '', pmoAuto: p.pmoAuto !== false, active: p.status !== 'archived',
@@ -190,16 +194,37 @@ export class TeamService {
190
194
  .filter((task) => task.tombstone !== true && task.status !== 'deleted')
191
195
  .map((task) => ({ ...taskCard(state, task), qaChecks: task.qaChecks ?? [] }));
192
196
  const project = projectId === undefined ? projects[0] : projects.find((p) => p.id === projectId);
193
- // 与 board/quadrants 同口径:显式给了不存在的 projectId 必须报错,不能返回
197
+ // 与 board/quadrants 同口径:显式给了**不存在**的 projectId 必须报错,不能返回
194
198
  // 一个 project:null 的空壳让调用方分不清「项目不存在」和「空项目」。
195
- if (projectId !== undefined && project === undefined) {
199
+ // 存在性按未过滤记录判定:归档项目是「已归档」,不是「不存在」。
200
+ if (projectId !== undefined && state.projects?.[projectId] === undefined) {
196
201
  fail(ERRORS.NOT_FOUND, `project ${String(projectId)} not found`);
197
202
  }
203
+ // 归档项目:仍返回它的只读视图(列表里不出现,但请求它时可用)。
204
+ const archivedProject = projectId !== undefined && project === undefined
205
+ ? {
206
+ id: projectId,
207
+ name: state.projects[projectId].name ?? projectId,
208
+ goal: state.projects[projectId].goal ?? '',
209
+ owner: state.projects[projectId].ownerName ?? state.projects[projectId].ownerMemberId ?? null,
210
+ workspacePath: state.projects[projectId].workspacePath ?? '',
211
+ pmoAuto: state.projects[projectId].pmoAuto !== false,
212
+ active: false,
213
+ archived: true,
214
+ runState: state.projects[projectId].runState === 'stopped' ? 'stopped' : 'running',
215
+ }
216
+ : null;
217
+ const selectedProject = project ?? archivedProject ?? undefined;
198
218
  // 大规模/长迭代裁剪:面板只需要最近的窗口,全史在账本里按需取。
199
219
  // stream 投影本身已封顶(≤500),bootstrap 再按窗口切尾。
200
- const stream = project === undefined
220
+ const stream = selectedProject === undefined
201
221
  ? []
202
- : (state.stream ?? []).filter((entry) => entry.projectId === project.id).slice(-200);
222
+ : (state.stream ?? [])
223
+ .filter((entry) => entry.projectId === selectedProject.id)
224
+ .slice(-200)
225
+ // 客户端渲染作者名(item.author),而账本只有 authorId:在这里补上,
226
+ // 否则主对话与 Thread 的作者永远显示「—」。
227
+ .map((entry) => ({ ...entry, author: state.members?.[entry.authorId]?.name ?? entry.authorId ?? '' }));
203
228
  const selected = threadTaskId ?? tasks.find((task) => task.status === 'in_progress')?.id ?? tasks[0]?.id;
204
229
  const threadOf = (taskId) => {
205
230
  const full = taskId === undefined || taskId === null ? undefined : state.threads?.[taskId];
@@ -213,7 +238,7 @@ export class TeamService {
213
238
  (item.memberId === this.humanId())
214
239
  && !isInformationalThreadMention(item));
215
240
  return {
216
- project: project ?? null,
241
+ project: selectedProject ?? null,
217
242
  projects,
218
243
  agents,
219
244
  members,
@@ -222,8 +247,8 @@ export class TeamService {
222
247
  thread,
223
248
  threads,
224
249
  inbox,
225
- board: project === undefined ? null : this.board(project.id),
226
- quadrants: project === undefined ? null : this.quadrants(project.id),
250
+ board: selectedProject === undefined ? null : this.board(selectedProject.id),
251
+ quadrants: selectedProject === undefined ? null : this.quadrants(selectedProject.id),
227
252
  };
228
253
  }
229
254
 
package/lib/host/waker.js CHANGED
@@ -1,4 +1,4 @@
1
- /**
1
+ /**
2
2
  * Event-driven wake planner. No timers: a command produces at most one plan,
3
3
  * and the Host delivers it with `subagents.sendMessage`/MemberRuntime.wake.
4
4
  *
@@ -193,7 +193,7 @@ export function planWakes(state, result, actor = {}, options = {}) {
193
193
  null,
194
194
  'human_message',
195
195
  `human_message:${event.seq ?? event.payload?.seq}`,
196
- `你是 Project owner。Human 在 Main stream 说:“${body}”。本轮必须先用 team action=members 查看成员,再用 action=create 创建至少一个 Task;ownerId 必须使用成员 id,写明可验证的 resultDefinition。可用成员:${roster || '无'}。如果需求很大或外部链接只是参考,先创建“调研/澄清/拆解”Task,不要直接开始实现。先做复盘/头脑风暴/深度研究,再产出验收标准;不要等 Human、不要把决策推回 Human。需要记录决策时调用 team action=askHuman,PMO 会自动按最高价值建议处理;不要只写“见报告/§6/已提交 Human”。resultDefinition 只写验收标准,不要写“等待 Human 验收”;不要只读文件或只回一段话结束。`,
196
+ `你是 Project owner。Human 在 Main stream 说:“${body.slice(0, 2000)}”。本轮必须先用 team action=members 查看成员,再用 action=create 创建至少一个 Task;ownerId 必须使用成员 id,写明可验证的 resultDefinition。可用成员:${roster || '无'}。如果需求很大或外部链接只是参考,先创建“调研/澄清/拆解”Task,不要直接开始实现。先做复盘/头脑风暴/深度研究,再产出验收标准;不要等 Human、不要把决策推回 Human。需要记录决策时调用 team action=askHuman,PMO 会自动按最高价值建议处理;不要只写“见报告/§6/已提交 Human”。resultDefinition 只写验收标准,不要写“等待 Human 验收”;不要只读文件或只回一段话结束。`,
197
197
  );
198
198
  }
199
199
  if (event?.type === 'pmo/review') {
@@ -420,6 +420,16 @@ export class LedgerWriter {
420
420
 
421
421
  _appendBatch(drafts) {
422
422
  if (this._closed) throw new LedgerError('E_LEDGER_CLOSED', 'ledger is closed');
423
+ // poison 必须在**队列内**复核:appendMany 入口的检查发生在入队之前,
424
+ // 同一 tick 内并发提交的两个批次会同时通过入口检查,先失败的那个把
425
+ // writer 置为 poisoned 后,后一个已经排在队列里,仍会按旧 head 算出重复
426
+ // seq 写进新段——账本此后永久打不开。
427
+ if (this._poisoned !== null && this._poisoned !== undefined) {
428
+ throw new LedgerError('E_LEDGER_POISONED',
429
+ `ledger writer is unusable after a failed rollback (${this._poisoned}); close and open it again`, {
430
+ rollbackError: this._poisoned,
431
+ });
432
+ }
423
433
 
424
434
  const plans = [];
425
435
  // 批内查重只用临时小集合;全局查重直接查 _ids(O(1)),避免每次
@@ -882,19 +892,39 @@ export class LedgerWriter {
882
892
  }
883
893
  // 单赢家接管:只有成功创建 takeover 标记的进程可以删除陈旧锁。
884
894
  // 否则两个进程会各自"读到陈旧 → unlink → 新建",把对方的活锁删掉。
885
- let marker;
886
- try {
887
- marker = this._fs.openSync(takeoverPath, 'wx');
888
- } catch (markerError) {
889
- throw new LedgerError('E_LOCKED', markerError.code === 'EEXIST'
890
- ? 'another writer is taking over the ledger lock'
891
- : `cannot create ledger takeover marker: ${markerError.message}`, {
892
- pid: existing.data?.pid ?? null,
893
- sysCode: markerError.code ?? null,
894
- });
895
+ // 标记必须带所有者且可判陈旧:否则一次崩溃(或 unlink 失败)留下的
896
+ // 空标记会让该项目**永久** E_LOCKED,只能手工删文件才能恢复。
897
+ let held = false;
898
+ for (let markerAttempt = 0; markerAttempt < 2 && !held; markerAttempt += 1) {
899
+ try {
900
+ const marker = this._fs.openSync(takeoverPath, 'wx');
901
+ try {
902
+ writeAll(this._fs, marker, Buffer.from(`${canonicalJson({ pid: process.pid, startedAt: this._clock() })}\n`, 'utf8'));
903
+ } finally {
904
+ this._fs.closeSync(marker);
905
+ }
906
+ held = true;
907
+ } catch (markerError) {
908
+ if (markerError.code !== 'EEXIST') {
909
+ throw new LedgerError('E_LOCKED', `cannot create ledger takeover marker: ${markerError.message}`, {
910
+ pid: existing.data?.pid ?? null,
911
+ sysCode: markerError.code ?? null,
912
+ });
913
+ }
914
+ // 陈旧标记(创建者已死或超时)直接回收,避免永久卡死。
915
+ if (this._lockRecordAge(takeoverPath) > LOCK_WRITE_GRACE_MS) {
916
+ try { this._fs.unlinkSync(takeoverPath); } catch { /* someone else reclaimed it */ }
917
+ continue;
918
+ }
919
+ throw new LedgerError('E_LOCKED', 'another writer is taking over the ledger lock', {
920
+ pid: existing.data?.pid ?? null,
921
+ });
922
+ }
923
+ }
924
+ if (!held) {
925
+ throw new LedgerError('E_LOCKED', 'ledger takeover marker could not be acquired', {});
895
926
  }
896
927
  try {
897
- this._fs.closeSync(marker);
898
928
  // 标记生效后重新读取:原主可能已经写完(或已被别人接管成新锁)。
899
929
  const fresh = this._readLock(lockPath);
900
930
  if (fresh.error !== 'missing' && !this._isStaleLock(fresh.data, lockPath)) {
@@ -917,7 +947,14 @@ export class LedgerWriter {
917
947
  reason: existing.error ?? 'owner-not-running',
918
948
  });
919
949
  } finally {
920
- try { this._fs.unlinkSync(takeoverPath); } catch { /* marker already gone */ }
950
+ try {
951
+ this._fs.unlinkSync(takeoverPath);
952
+ } catch (markerCleanupError) {
953
+ // 不静默:残留标记会被陈旧回收逻辑接管,但要在日志里留痕。
954
+ if (markerCleanupError.code !== 'ENOENT') {
955
+ console.warn(`[ai-team] ledger takeover marker could not be removed (${takeoverPath}): ${markerCleanupError.message}`);
956
+ }
957
+ }
921
958
  }
922
959
  }
923
960
  }
@@ -110,6 +110,9 @@ export async function ensureHostAgent(options) {
110
110
  if (header === undefined) return true;
111
111
  return header.origin !== 'subagent' && header.parentSession === undefined;
112
112
  }) ?? roots[0];
113
+ // 被选中的 Human 根会话若已归档,成员血缘会被 gate 永久拒绝——这条快路径
114
+ // 也必须解归档,否则 boot 期的 sweep 由于没有 hostSessionId 看不到它。
115
+ await unarchiveHost(rootAgent.id);
113
116
  return { agent: rootAgent, created: false, sessionId: rootAgent.id, dispose: async () => {} };
114
117
  }
115
118
 
@@ -50,6 +50,9 @@ export async function repairArchivedHosts(options = {}) {
50
50
  for (const member of Object.values(runtime?.service?.state?.members ?? {})) {
51
51
  const sessionId = member?.sessionId;
52
52
  if (typeof sessionId !== 'string' || sessionId === '') continue;
53
+ // 成员会话自己也可能被归档(例如用户手动归档了那条会话):gate 会直接
54
+ // 拒绝它,只有 host 一代的解归档覆盖不到。
55
+ victims.add(sessionId);
53
56
  try {
54
57
  const header = options.sessions?.get?.(sessionId)?.header;
55
58
  if (typeof header?.parentSession === 'string') victims.add(header.parentSession);
@@ -101,6 +101,10 @@ export class MemberRuntime {
101
101
  // Cold resumes produce AgentHandles the caller does not store; the owner
102
102
  // tracks them here so teardown can dispose every member activation.
103
103
  this.trackHandle = typeof options.trackHandle === 'function' ? options.trackHandle : null;
104
+ // 冷恢复得到的 handle 必须自己记住:第二次唤醒时 session 已经 live,但
105
+ // subagent manager 并不把这次 resume 当成 resident activation,再走
106
+ // sendMessage 会触发二次冷恢复 → NOT_RESUMABLE → 上层强制重建丢上下文。
107
+ this.resumedHandles = new Map();
104
108
  this.clock = options.clock ?? (() => Date.now());
105
109
  }
106
110
 
@@ -267,6 +271,7 @@ export class MemberRuntime {
267
271
  } catch { handle = null; }
268
272
  if (handle?.agent !== undefined && handle?.agent !== null && typeof handle.agent.followup === 'function') {
269
273
  this.trackHandle?.(member.sessionId, handle);
274
+ this.resumedHandles.set(member.sessionId, handle);
270
275
  await this.ensurePermission(member.sessionId);
271
276
  const message = userMessage(typeof options.prompt === 'string' ? options.prompt : '继续');
272
277
  handle.agent.followup(message);
@@ -281,6 +286,21 @@ export class MemberRuntime {
281
286
  });
282
287
  return { messageId, sessionId: member.sessionId, cold: true };
283
288
  }
289
+ // 之前由我们 resume 过的会话:继续用同一个 handle 投递,避免掉回
290
+ // sendMessage 的冷恢复路径(见构造函数里的说明)。
291
+ const resumed = this.resumedHandles.get(member.sessionId);
292
+ if (resumed?.agent !== undefined && resumed?.agent !== null && typeof resumed.agent.followup === 'function') {
293
+ try {
294
+ await this.ensurePermission(member.sessionId);
295
+ const message = userMessage(typeof options.prompt === 'string' ? options.prompt : '继续');
296
+ resumed.agent.followup(message);
297
+ if (typeof this.sessions.flush === 'function') await this.sessions.flush(session);
298
+ return { messageId: message.id, sessionId: member.sessionId, cold: false, resumed: true };
299
+ } catch {
300
+ // handle 已失效:清掉后回退到 manager 通道。
301
+ this.resumedHandles.delete(member.sessionId);
302
+ }
303
+ }
284
304
  await this.ensurePermission(member.sessionId);
285
305
  const messageId = await this.subagents.sendMessage(this.parent, member.sessionId, content, {
286
306
  signal: options.signal ?? new AbortController().signal,
@@ -29,7 +29,10 @@ function parseFrontmatter(text) {
29
29
  if (!text.startsWith('---')) return {};
30
30
  const end = text.indexOf('\n---', 3);
31
31
  if (end < 0) return {};
32
- const lines = text.slice(3, end).split(/\r?\n/);
32
+ // CRLF 必须在这里断干净:`\r` 在 JS 里是行终止符,`.$` 无法越过它,
33
+ // 带尾 `\r` 的最后一行(常见于 Windows 编辑器)会整行失配——
34
+ // description 恰好位于末尾时,整个技能被当成「缺少 description」丢弃。
35
+ const lines = text.slice(3, end).split(/\r\n|\r|\n/);
33
36
  const fields = {};
34
37
  let key = null;
35
38
  for (const line of lines) {
@@ -1,12 +1,12 @@
1
- /**
1
+ /**
2
2
  * SkillOpt adopt gate 的宿主接线:把「读候选/基线」和「独立 judge」落到
3
3
  * DSH 服务上。与 adopt-gate.js(纯协议)分离,便于单测协议、集成测接线。
4
4
  *
5
5
  * baseline 取 live SKILL.md 当前内容:adopt 之前 live 文件就是改前版本
6
6
  * (staging 只写候选项),因此不需要 git 历史即可对比。
7
7
  */
8
- import { existsSync, readFileSync, readdirSync } from 'node:fs';
9
- import { join } from 'node:path';
8
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
9
+ import { isAbsolute, join } from 'node:path';
10
10
  import { judgePair } from './judge-runner.js';
11
11
 
12
12
  /** 引号一个 argv 元素(Windows cmd 与 POSIX sh 通用单引号形式)。 */
@@ -19,6 +19,25 @@ export function quoteArgv(argv) {
19
19
  return argv.map(quote).join(' ');
20
20
  }
21
21
 
22
+ /**
23
+ * 模型可控的 project 会被拼进 shell 命令,因此必须在进 shell 前校验。
24
+ * `quoteArgv` 只是引号包裹:`$(...)`、反引号在双引号内仍会被 shell 展开,
25
+ * 而 pwsh 下 `\"` 也不是转义——只靠引号挡不住注入。这里要求它是一个
26
+ * 真实存在的绝对目录,且不含任何 shell 元字符。
27
+ */
28
+ export function assertSafeProjectDir(dir) {
29
+ if (typeof dir !== 'string' || dir.trim() === '') throw new Error('project directory is required');
30
+ const text = dir.trim();
31
+ if (!isAbsolute(text)) throw new Error('project directory must be an absolute path');
32
+ if (/[\u0000-\u001f`$;|&<>(){}[\]*?"'!^%\r\n]/.test(text)) {
33
+ throw new Error('project directory must not contain shell metacharacters');
34
+ }
35
+ if (!existsSync(text) || statSync(text).isDirectory() !== true) {
36
+ throw new Error('project directory does not exist');
37
+ }
38
+ return text;
39
+ }
40
+
22
41
  /** 跑引擎 CLI(status 等只读命令);返回 {exitCode, stdout, stderr}。 */
23
42
  export async function runEngineCli(shell, args, options = {}) {
24
43
  const request = {
@@ -48,7 +67,8 @@ export async function runEngineCli(shell, args, options = {}) {
48
67
  export function makeReadPair(deps) {
49
68
  const { shell, engineScript, python = 'python', diag } = deps;
50
69
  return async (projectDir) => {
51
- const status = await runEngineCli(shell, [python, engineScript, 'status', '--json', '--project', projectDir]);
70
+ const safeDir = assertSafeProjectDir(projectDir);
71
+ const status = await runEngineCli(shell, [python, engineScript, 'status', '--json', '--project', safeDir]);
52
72
  if (status.timedOut) throw new Error('engine status timed out');
53
73
  const raw = status.stdout.slice(status.stdout.indexOf('{'));
54
74
  let payload;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.27",
3
+ "version": "0.4.29",
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",
@@ -44,8 +44,8 @@
44
44
  "icon.svg",
45
45
  "locale/*.json",
46
46
  "lib/**/*.js",
47
- "lib/vendor/skillopt/scripts/**/*",
48
- "lib/vendor/skillopt/skillopt_sleep/**/*",
47
+ "lib/vendor/skillopt/scripts/*.py",
48
+ "lib/vendor/skillopt/skillopt_sleep/**/*.py",
49
49
  "lib/vendor/skillopt/requirements.txt",
50
50
  "lib/vendor/skillopt/LICENSE",
51
51
  "skills/**/*",