dsh-cohub 0.10.0 → 0.10.1

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 (3) hide show
  1. package/README.md +1 -1
  2. package/lib/index.js +386 -28
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # dsh-cohub
2
2
 
3
- > 本文对应 **v0.10.0**;完整变更历史见 [CHANGELOG.md](./CHANGELOG.md)。
3
+ > 本文对应 **v0.10.1**;完整变更历史见 [CHANGELOG.md](./CHANGELOG.md)。
4
4
 
5
5
  DeepSeek Harness 版(对照 [OpenCode 版](../oh-my-opencode-cohub/)):中文智能体编排插件。
6
6
  把「纯调度模式 + 13 个技能(12 个代理编排体系 + co-cordis 组合创作)+ 多模型共识 + 运行期调度韧性」移植到 DSH 原生能力之上。
package/lib/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  // src/index.ts
2
2
  import z2 from "@deepseek-ai/schemastery";
3
- import { readFileSync as readFileSync4 } from "node:fs";
3
+ import { readFileSync as readFileSync5 } from "node:fs";
4
4
  import { fileURLToPath } from "node:url";
5
- import { dshHomePath as dshHomePath4 } from "@deepseek-ai/dsh-home-paths";
5
+ import { dshHomePath as dshHomePath5 } from "@deepseek-ai/dsh-home-paths";
6
6
 
7
7
  // src/preset-install.ts
8
8
  import { createHash } from "node:crypto";
@@ -5092,9 +5092,9 @@ function createReviewCollector(ctx, opts = {}) {
5092
5092
 
5093
5093
  // src/review-command.ts
5094
5094
  import { createHash as createHash4 } from "node:crypto";
5095
- import { existsSync as existsSync4, mkdirSync as mkdirSync4, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "node:fs";
5096
- import { dirname as dirname4 } from "node:path";
5097
- import { dshHomePath as dshHomePath3 } from "@deepseek-ai/dsh-home-paths";
5095
+ import { appendFileSync, existsSync as existsSync5, mkdirSync as mkdirSync5, renameSync as renameSync3, writeFileSync as writeFileSync5 } from "node:fs";
5096
+ import { dirname as dirname5 } from "node:path";
5097
+ import { dshHomePath as dshHomePath4 } from "@deepseek-ai/dsh-home-paths";
5098
5098
 
5099
5099
  // src/review-report.ts
5100
5100
  import { createHash as createHash3 } from "node:crypto";
@@ -5345,9 +5345,18 @@ function excerptOf(raw, limit) {
5345
5345
  const flat = raw.replace(/\s+/g, " ").trim();
5346
5346
  return flat.length > limit ? `${flat.slice(0, limit)}…` : flat;
5347
5347
  }
5348
+ var SEVERITY_RANK = { high: 0, medium: 1, low: 2 };
5349
+ var SEVERITY_ORDER = ["high", "medium", "low"];
5350
+ function severityOf(finding) {
5351
+ if (finding?.kind !== "issue")
5352
+ return null;
5353
+ const s = finding?.severity;
5354
+ return s === "high" || s === "medium" || s === "low" ? s : null;
5355
+ }
5348
5356
  function renderFinding(finding, opts, excerptLimit) {
5349
5357
  const out = [];
5350
- out.push(`- **${text(finding?.text)}**`);
5358
+ const sev = severityOf(finding);
5359
+ out.push(sev !== null ? `- **issue · ${sev}** — ${text(finding?.text)}` : `- **${text(finding?.text)}**`);
5351
5360
  const evidence = Array.isArray(finding?.evidence) ? finding.evidence : [];
5352
5361
  for (const ev of evidence)
5353
5362
  out.push(` - 锚点:${anchorOf(ev)}`);
@@ -5464,10 +5473,28 @@ function renderMarkdown(report, opts = {}) {
5464
5473
  if (verified.length === 0) {
5465
5474
  lines.push(`- 本报告没有带证据的结论(findings 为空,${DASH});原因见「分析状态」与「限制说明」。`, "");
5466
5475
  } else {
5476
+ const issueCounts = new Map;
5477
+ for (const f of verified) {
5478
+ const sev = severityOf(f);
5479
+ if (sev !== null)
5480
+ issueCounts.set(sev, (issueCounts.get(sev) ?? 0) + 1);
5481
+ }
5482
+ const totalIssues = [...issueCounts.values()].reduce((a, b) => a + b, 0);
5483
+ if (totalIssues > 0) {
5484
+ const dist = SEVERITY_ORDER.filter((s) => (issueCounts.get(s) ?? 0) > 0).map((s) => `${s} ${issueCounts.get(s)}`).join(" / ");
5485
+ lines.push(`- 问题分布:${dist}`, "");
5486
+ }
5467
5487
  for (const kind of KIND_ORDER) {
5468
- const group = verified.filter((f) => f?.kind === kind);
5488
+ let group = verified.filter((f) => f?.kind === kind);
5469
5489
  if (group.length === 0)
5470
5490
  continue;
5491
+ if (kind === "issue") {
5492
+ group = [...group].sort((a, b) => {
5493
+ const ra = SEVERITY_RANK[severityOf(a) ?? ""] ?? SEVERITY_ORDER.length;
5494
+ const rb = SEVERITY_RANK[severityOf(b) ?? ""] ?? SEVERITY_ORDER.length;
5495
+ return ra - rb;
5496
+ });
5497
+ }
5471
5498
  lines.push(`### ${KIND_TITLE[kind] ?? kind}`, "");
5472
5499
  for (const f of group)
5473
5500
  lines.push(...renderFinding(f, opts, excerptLimit));
@@ -5528,11 +5555,216 @@ function renderMarkdown(report, opts = {}) {
5528
5555
  `);
5529
5556
  }
5530
5557
 
5558
+ // src/review-index.ts
5559
+ import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync4, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "node:fs";
5560
+ import { basename, dirname as dirname4, join as join2 } from "node:path";
5561
+ import { dshHomePath as dshHomePath3 } from "@deepseek-ai/dsh-home-paths";
5562
+ var REVIEW_INDEX_VERSION = 1;
5563
+ function reviewIndexDir() {
5564
+ return dshHomePath3("cohub", "reviews");
5565
+ }
5566
+ function indexPath() {
5567
+ return join2(reviewIndexDir(), "index.json");
5568
+ }
5569
+ function indexMarkdownPath() {
5570
+ return join2(reviewIndexDir(), "INDEX.md");
5571
+ }
5572
+ function projectReviewDir(cwd) {
5573
+ return join2(cwd, ".cohub", "reviews");
5574
+ }
5575
+ function projectCopyPath(cwd, stamp) {
5576
+ if (typeof cwd !== "string" || cwd.length === 0)
5577
+ return null;
5578
+ return join2(projectReviewDir(cwd), "report-" + stamp + ".md");
5579
+ }
5580
+ function writeTextAtomic(file, text) {
5581
+ const tmp = file + ".tmp";
5582
+ try {
5583
+ mkdirSync4(dirname4(file), { recursive: true });
5584
+ writeFileSync4(tmp, text, "utf8");
5585
+ renameSync2(tmp, file);
5586
+ return true;
5587
+ } catch {
5588
+ try {
5589
+ if (existsSync4(tmp))
5590
+ renameSync2(tmp, tmp + ".failed");
5591
+ } catch {}
5592
+ return false;
5593
+ }
5594
+ }
5595
+ function ensureProjectGitignore(cwd) {
5596
+ const file = join2(cwd, ".cohub", ".gitignore");
5597
+ try {
5598
+ if (existsSync4(file)) {
5599
+ const text = readFileSync4(file, "utf8");
5600
+ if (!text.includes("*")) {
5601
+ return "已存在 " + file + ' 且内容不含 "*",未覆盖;如需忽略整个 .cohub/ 请手动加入一行 *';
5602
+ }
5603
+ return null;
5604
+ }
5605
+ mkdirSync4(dirname4(file), { recursive: true });
5606
+ writeFileSync4(file, `*
5607
+ `, "utf8");
5608
+ return null;
5609
+ } catch (error) {
5610
+ return "写入 " + file + " 失败(" + String(error?.message ?? error) + "),项目内副本可能被 git 跟踪";
5611
+ }
5612
+ }
5613
+ function writeProjectCopy(cwd, markdown, stamp) {
5614
+ const file = projectCopyPath(cwd, stamp);
5615
+ if (file === null)
5616
+ return { path: null, note: "cwd 为空,跳过项目内副本" };
5617
+ const notes = [];
5618
+ try {
5619
+ if (!writeTextAtomic(file, markdown)) {
5620
+ return { path: null, note: "项目内副本写入失败(目录只读或无权限):" + file };
5621
+ }
5622
+ } catch (error) {
5623
+ return {
5624
+ path: null,
5625
+ note: "项目内副本写入失败(目录只读或无权限):" + String(error?.message ?? error)
5626
+ };
5627
+ }
5628
+ const gitignoreNote = ensureProjectGitignore(cwd);
5629
+ if (gitignoreNote !== null)
5630
+ notes.push(gitignoreNote);
5631
+ return { path: file, note: notes.length > 0 ? notes.join(";") : null };
5632
+ }
5633
+ function emptyIndex() {
5634
+ return { version: REVIEW_INDEX_VERSION, updatedAt: new Date().toISOString(), projects: {} };
5635
+ }
5636
+ function loadIndex() {
5637
+ const file = indexPath();
5638
+ try {
5639
+ if (!existsSync4(file))
5640
+ return emptyIndex();
5641
+ const parsed = JSON.parse(readFileSync4(file, "utf8"));
5642
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
5643
+ throw new Error("index.json 结构不合法");
5644
+ if (parsed.version !== REVIEW_INDEX_VERSION)
5645
+ throw new Error("index.json 版本不符");
5646
+ if (parsed.projects === null || typeof parsed.projects !== "object" || Array.isArray(parsed.projects)) {
5647
+ throw new Error("index.json projects 不合法");
5648
+ }
5649
+ return {
5650
+ version: REVIEW_INDEX_VERSION,
5651
+ updatedAt: typeof parsed.updatedAt === "string" ? parsed.updatedAt : new Date().toISOString(),
5652
+ projects: parsed.projects
5653
+ };
5654
+ } catch {
5655
+ isolateCorrupt2(file);
5656
+ return emptyIndex();
5657
+ }
5658
+ }
5659
+ function isolateCorrupt2(file) {
5660
+ try {
5661
+ if (!existsSync4(file))
5662
+ return;
5663
+ renameSync2(file, file + ".corrupt");
5664
+ } catch {}
5665
+ }
5666
+ function slashed(p) {
5667
+ return typeof p === "string" && p.length > 0 ? p.replace(/\\/g, "/") : null;
5668
+ }
5669
+ function updateIndex(entry) {
5670
+ try {
5671
+ const index = loadIndex();
5672
+ const key = cwdDirName(entry.cwd);
5673
+ const cwd = typeof entry.cwd === "string" && entry.cwd.length > 0 ? entry.cwd : null;
5674
+ const at = typeof entry.at === "string" && entry.at.length > 0 ? entry.at : new Date().toISOString();
5675
+ const prev = index.projects[key];
5676
+ const lastReport = {
5677
+ at,
5678
+ sessionId: entry.sessionId,
5679
+ status: entry.status,
5680
+ findings: Number.isFinite(entry.findings) ? entry.findings : 0,
5681
+ sessions: Number.isFinite(entry.sessions) ? entry.sessions : 0,
5682
+ jsonPath: slashed(entry.jsonPath) ?? "",
5683
+ mdPath: slashed(entry.mdPath ?? null),
5684
+ projectCopyPath: slashed(entry.projectCopyPath ?? null)
5685
+ };
5686
+ if (typeof entry.note === "string" && entry.note.length > 0)
5687
+ lastReport.note = entry.note;
5688
+ index.projects[key] = {
5689
+ cwd: slashed(cwd) ?? prev?.cwd ?? "",
5690
+ name: cwd !== null ? basename(cwd) : prev?.name ?? "(未知项目)",
5691
+ lastReport
5692
+ };
5693
+ index.version = REVIEW_INDEX_VERSION;
5694
+ index.updatedAt = new Date().toISOString();
5695
+ const jsonOk = writeTextAtomic(indexPath(), JSON.stringify(index, null, 2));
5696
+ writeTextAtomic(indexMarkdownPath(), renderIndexMarkdown(index));
5697
+ return jsonOk;
5698
+ } catch {
5699
+ return false;
5700
+ }
5701
+ }
5702
+ function formatLocalTime(iso) {
5703
+ const d = new Date(iso);
5704
+ if (Number.isNaN(d.getTime()))
5705
+ return iso;
5706
+ const pad = (n) => String(n).padStart(2, "0");
5707
+ return d.getFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getDate()) + " " + pad(d.getHours()) + ":" + pad(d.getMinutes()) + ":" + pad(d.getSeconds());
5708
+ }
5709
+ function sortedProjects(index) {
5710
+ const rows = Object.entries(index.projects);
5711
+ rows.sort((a, b) => {
5712
+ const ta = Date.parse(a[1]?.lastReport?.at ?? "") || 0;
5713
+ const tb = Date.parse(b[1]?.lastReport?.at ?? "") || 0;
5714
+ if (tb !== ta)
5715
+ return tb - ta;
5716
+ return String(a[1]?.name ?? "").localeCompare(String(b[1]?.name ?? ""));
5717
+ });
5718
+ return rows;
5719
+ }
5720
+ function renderIndexMarkdown(index) {
5721
+ const rows = sortedProjects(index);
5722
+ const lines = [];
5723
+ lines.push("# CoHub 复盘索引");
5724
+ lines.push("");
5725
+ lines.push("自动生成,勿手工编辑(每次 `/cohub-review` 落盘后全量重写)。");
5726
+ lines.push("");
5727
+ lines.push("索引更新时间:" + formatLocalTime(index.updatedAt) + "(本地时间) 项目数:" + rows.length);
5728
+ lines.push("");
5729
+ if (rows.length === 0) {
5730
+ lines.push("_暂无复盘记录。_");
5731
+ lines.push("");
5732
+ return lines.join(`
5733
+ `);
5734
+ }
5735
+ lines.push("| 项目 | 状态 | findings | 会话数 | 最近报告(本地时间) |");
5736
+ lines.push("| --- | --- | --- | --- | --- |");
5737
+ for (const [, p] of rows) {
5738
+ const r = p.lastReport;
5739
+ lines.push("| " + p.name + " | " + r.status + " | " + r.findings + " | " + r.sessions + " | " + formatLocalTime(r.at) + " |");
5740
+ }
5741
+ lines.push("");
5742
+ for (const [key, p] of rows) {
5743
+ const r = p.lastReport;
5744
+ lines.push("## " + p.name + "(" + key + ")");
5745
+ lines.push("");
5746
+ lines.push("- 项目路径:`" + (p.cwd.length > 0 ? p.cwd : "(未知)") + "`");
5747
+ lines.push("- 最近报告:" + formatLocalTime(r.at) + "(本地时间)");
5748
+ lines.push("- 状态:" + r.status + " findings:" + r.findings + " 会话数:" + r.sessions);
5749
+ lines.push("- 会话:" + r.sessionId);
5750
+ lines.push("- 报告(DSH):`" + (r.jsonPath.length > 0 ? r.jsonPath : "(无)") + "`");
5751
+ lines.push("- 报告 MD:`" + (r.mdPath ?? "(无)") + "`");
5752
+ lines.push("- 项目内副本:" + (r.projectCopyPath !== null ? "`" + r.projectCopyPath + "`" : "(无)"));
5753
+ if (typeof r.note === "string" && r.note.length > 0)
5754
+ lines.push("- 提示:" + r.note);
5755
+ lines.push("");
5756
+ }
5757
+ return lines.join(`
5758
+ `);
5759
+ }
5760
+
5531
5761
  // src/review-command.ts
5532
5762
  var DIGEST_LIMIT_CHARS = 12000;
5533
5763
  var ANALYSIS_MAX_TOKENS = 5000;
5534
5764
  var RAW_OUTPUT_KEEP_CHARS = 2000;
5535
5765
  var MAX_CHILD_SESSIONS = 50;
5766
+ var MAX_CHILD_FILTER_CALLS = 20;
5767
+ var ANALYSIS_TIMEOUT_MS = 60000;
5536
5768
  var MAX_ROOT_ASCEND = 32;
5537
5769
  function idOf(rec) {
5538
5770
  const v = rec?.session?.id ?? rec?.id ?? rec?.sessionId;
@@ -5592,6 +5824,32 @@ async function findChildIds(ctx, rootId, signal) {
5592
5824
  } catch (error) {
5593
5825
  ctx.logger?.warn?.("[cohub review] traceSession 失败:" + String(error?.message ?? error));
5594
5826
  }
5827
+ if (ids.size > 0)
5828
+ return [...ids].slice(0, MAX_CHILD_SESSIONS);
5829
+ try {
5830
+ const filter = ctx?.sessionQuery?.filterSessions;
5831
+ if (typeof filter === "function") {
5832
+ const queue = [rootId];
5833
+ let calls = 0;
5834
+ while (queue.length > 0 && ids.size < MAX_CHILD_SESSIONS && calls < MAX_CHILD_FILTER_CALLS) {
5835
+ const parentId = queue.shift();
5836
+ calls++;
5837
+ const listed = await filter.call(ctx.sessionQuery, { parentSessionId: parentId }, signal);
5838
+ const records = Array.isArray(listed) ? listed : [];
5839
+ for (const rec of records) {
5840
+ const id = idOf(rec);
5841
+ if (!id || id === rootId || ids.has(id))
5842
+ continue;
5843
+ ids.add(id);
5844
+ queue.push(id);
5845
+ if (ids.size >= MAX_CHILD_SESSIONS)
5846
+ break;
5847
+ }
5848
+ }
5849
+ }
5850
+ } catch (error) {
5851
+ ctx.logger?.warn?.("[cohub review] filterSessions 失败:" + String(error?.message ?? error));
5852
+ }
5595
5853
  if (ids.size > 0)
5596
5854
  return [...ids].slice(0, MAX_CHILD_SESSIONS);
5597
5855
  try {
@@ -5622,21 +5880,41 @@ async function findChildIds(ctx, rootId, signal) {
5622
5880
  }
5623
5881
  return [...ids];
5624
5882
  }
5625
- function writeTextAtomic(file, text) {
5883
+ function writeTextAtomic2(file, text) {
5626
5884
  const tmp = file + ".tmp";
5627
5885
  try {
5628
- mkdirSync4(dirname4(file), { recursive: true });
5629
- writeFileSync4(tmp, text, "utf8");
5630
- renameSync2(tmp, file);
5886
+ mkdirSync5(dirname5(file), { recursive: true });
5887
+ writeFileSync5(tmp, text, "utf8");
5888
+ renameSync3(tmp, file);
5631
5889
  return true;
5632
5890
  } catch {
5633
5891
  try {
5634
- if (existsSync4(tmp))
5635
- renameSync2(tmp, tmp + ".failed");
5892
+ if (existsSync5(tmp))
5893
+ renameSync3(tmp, tmp + ".failed");
5636
5894
  } catch {}
5637
5895
  return false;
5638
5896
  }
5639
5897
  }
5898
+ function appendErrorLog(cwd, sessionId, message) {
5899
+ try {
5900
+ const logPath = reviewStorePath(cwd, sessionId, "_errors.log");
5901
+ mkdirSync5(dirname5(logPath), { recursive: true });
5902
+ appendFileSync(logPath, new Date().toISOString() + "\t" + sessionId + "\t" + message.replace(/\s+/g, " ").slice(0, 500) + `
5903
+ `, "utf8");
5904
+ } catch {}
5905
+ }
5906
+ function writeErrorRecord(cwd, sessionId, error) {
5907
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
5908
+ const payload = {
5909
+ error: String(error?.message ?? error),
5910
+ stack: typeof error?.stack === "string" ? error.stack : undefined,
5911
+ sessionId,
5912
+ cwd: cwd ?? null,
5913
+ timestamp: new Date().toISOString()
5914
+ };
5915
+ const file = reviewStorePath(cwd, sessionId, "error-" + stamp + ".json");
5916
+ return writeTextAtomic2(file, JSON.stringify(payload, null, 2)) ? file : null;
5917
+ }
5640
5918
  function buildDigest(report) {
5641
5919
  const lines = [];
5642
5920
  lines.push("rootSessionId: " + report.rootSessionId);
@@ -5776,8 +6054,9 @@ function buildEvidenceIndex(sessions) {
5776
6054
  }
5777
6055
  return index;
5778
6056
  }
5779
- function normalizeFindings(raw, index, defaultSessionId) {
6057
+ function normalizeFindings(raw, index, defaultSessionId, warn) {
5780
6058
  const KINDS = new Set(["observation", "praise", "issue", "suggestion"]);
6059
+ const SEVERITIES = new Set(["low", "medium", "high"]);
5781
6060
  const out = [];
5782
6061
  for (const item of raw) {
5783
6062
  const rec = item;
@@ -5807,7 +6086,21 @@ function normalizeFindings(raw, index, defaultSessionId) {
5807
6086
  evidence.push({ sessionId, turn, seq, callId });
5808
6087
  }
5809
6088
  const limitations = Array.isArray(rec?.limitations) ? rec.limitations.filter((x) => typeof x === "string").slice(0, 5) : [];
5810
- out.push({ id: "f-" + String(out.length + 1).padStart(3, "0"), kind, text, evidence, limitations });
6089
+ let severity;
6090
+ if (kind === "issue") {
6091
+ if (SEVERITIES.has(rec?.severity)) {
6092
+ severity = rec.severity;
6093
+ } else {
6094
+ severity = "medium";
6095
+ warn?.("issue 缺合法 severity(" + String(rec?.severity) + "),已降级为 medium:" + text.slice(0, 40));
6096
+ }
6097
+ } else if (SEVERITIES.has(rec?.severity)) {
6098
+ warn?.("非 issue(" + kind + ")带了 severity=" + String(rec?.severity) + ",已丢弃:" + text.slice(0, 40));
6099
+ }
6100
+ const finding = { id: "f-" + String(out.length + 1).padStart(3, "0"), kind, text, evidence, limitations };
6101
+ if (severity !== undefined)
6102
+ finding.severity = severity;
6103
+ out.push(finding);
5811
6104
  if (out.length >= 30)
5812
6105
  break;
5813
6106
  }
@@ -5902,7 +6195,9 @@ async function callAnalysis(ctx, agent, digest, signal) {
5902
6195
  const prompt = [
5903
6196
  "下面是某会话的统计摘要(每行 turn 含 end 事件 seq、usage、工具状态)。",
5904
6197
  "请输出 JSON 数组,每项形如:",
5905
- '{"kind":"observation|praise|issue|suggestion","text":"中文结论","evidence":[{"sessionId":"...","turn":1,"seq":42,"callId":null}],"limitations":["..."]}',
6198
+ '{"kind":"observation|praise|issue|suggestion","severity":"high|medium|low(仅 kind=issue 时给)","text":"中文结论","evidence":[{"sessionId":"...","turn":1,"seq":42,"callId":null}],"limitations":["..."]}',
6199
+ "severity 规则:kind=issue **必须**给 severity,取值只能是 high / medium / low;kind 为 observation / praise / suggestion 时**不要输出 severity**(会被丢弃)。",
6200
+ "severity 判据:high = 导致任务失败、数据丢失、需人工介入、或明显浪费大量 token/时间(如单轮输入 200+ 倍于输出、整轮中断);" + "medium = 效率明显下降、有返工、需要额外轮次才完成;low = 轻微冗余、可读性/组织性问题、不影响结果。",
5906
6201
  "硬规则:每条必须带至少 1 条 evidence;evidence 的 sessionId/turn/seq 必须来自下方摘要中真实出现的数据;",
5907
6202
  "不要编造 seq,不要给无证据的结论(无证据结论将被丢弃)。最多 12 条。",
5908
6203
  "",
@@ -5936,7 +6231,15 @@ async function callAnalysis(ctx, agent, digest, signal) {
5936
6231
  }
5937
6232
  async function readRootSession(ctx, sessionId, signal) {
5938
6233
  let current = sessionId;
5939
- let read = await ctx.sessionQuery.readSession(current, signal);
6234
+ let read;
6235
+ let failed;
6236
+ try {
6237
+ read = await ctx.sessionQuery.readSession(current, signal);
6238
+ } catch (error) {
6239
+ failed = "根会话读取失败(" + String(error?.message ?? error) + ")";
6240
+ ctx.logger?.warn?.("[cohub review] " + failed + ",降级为空事件继续出报告");
6241
+ read = { session: { id: current }, events: [] };
6242
+ }
5940
6243
  const seen = new Set([current]);
5941
6244
  for (let depth = 0;depth < MAX_ROOT_ASCEND; depth++) {
5942
6245
  const parent = parentOf(read);
@@ -5955,15 +6258,45 @@ async function readRootSession(ctx, sessionId, signal) {
5955
6258
  current = parent;
5956
6259
  read = parentRead;
5957
6260
  }
5958
- return { sessionId: current, read };
6261
+ return { sessionId: current, read, failed };
5959
6262
  }
5960
6263
  async function runAnalysis(ctx, agent, sessionId, cwdHint, withLlm) {
5961
- const signal = undefined;
5962
- const { sessionId: rootId, read: rootRead } = await readRootSession(ctx, sessionId, signal);
6264
+ const controller = new AbortController;
6265
+ const timer = setTimeout(() => controller.abort(), ANALYSIS_TIMEOUT_MS);
6266
+ const signal = controller.signal;
6267
+ try {
6268
+ await runAnalysisInner(ctx, agent, sessionId, cwdHint, withLlm, signal);
6269
+ } catch (error) {
6270
+ const errorPath = writeErrorRecord(cwdHint, sessionId, error);
6271
+ ctx.logger?.warn?.("[cohub review] 分析失败(error-*.json " + (errorPath !== null ? "已" : "未") + "落盘):" + String(error?.message ?? error));
6272
+ if (errorPath !== null) {
6273
+ try {
6274
+ updateIndex({
6275
+ cwd: cwdHint,
6276
+ sessionId,
6277
+ status: "failed",
6278
+ findings: 0,
6279
+ sessions: 0,
6280
+ jsonPath: errorPath,
6281
+ mdPath: null,
6282
+ projectCopyPath: null,
6283
+ note: "本次复盘整体失败,仅落盘 error 记录:" + String(error?.message ?? error).slice(0, 200)
6284
+ });
6285
+ } catch {}
6286
+ }
6287
+ throw error;
6288
+ } finally {
6289
+ clearTimeout(timer);
6290
+ }
6291
+ }
6292
+ async function runAnalysisInner(ctx, agent, sessionId, cwdHint, withLlm, signal) {
6293
+ const { sessionId: rootId, read: rootRead, failed: rootFailed } = await readRootSession(ctx, sessionId, signal);
5963
6294
  const root = toSessionEvents(rootRead, rootId);
5964
6295
  const childIds = await findChildIds(ctx, root.sessionId, signal);
5965
6296
  const children = [];
5966
6297
  const gaps = [];
6298
+ if (rootFailed)
6299
+ gaps.push(rootId + ": " + rootFailed);
5967
6300
  for (const childId of childIds) {
5968
6301
  try {
5969
6302
  const read = await ctx.sessionQuery.readSession(childId, signal);
@@ -5994,7 +6327,7 @@ async function runAnalysis(ctx, agent, sessionId, cwdHint, withLlm) {
5994
6327
  const rawItems = extracted.items;
5995
6328
  if (rawItems !== null) {
5996
6329
  const index = buildEvidenceIndex([root, ...children]);
5997
- report.findings = normalizeFindings(rawItems, index, root.sessionId);
6330
+ report.findings = normalizeFindings(rawItems, index, root.sessionId, (msg) => ctx.logger?.warn?.("[cohub review] " + msg));
5998
6331
  const dropped = rawItems.length - report.findings.length;
5999
6332
  if (extracted.truncated) {
6000
6333
  analysis.status = "interrupted";
@@ -6027,15 +6360,38 @@ async function runAnalysis(ctx, agent, sessionId, cwdHint, withLlm) {
6027
6360
  }
6028
6361
  const md = renderMarkdown(report, { excerptLimit: 120 });
6029
6362
  const stamp = new Date().toISOString().replace(/[:.]/g, "-");
6030
- const jsonPath = reviewStorePath(cwd, root.sessionId, "report-" + stamp + ".json");
6031
- const mdPath = reviewStorePath(cwd, root.sessionId, "report-" + stamp + ".md");
6032
- const jsonOk = writeTextAtomic(jsonPath, JSON.stringify(report, null, 2));
6033
- const mdOk = writeTextAtomic(mdPath, md);
6363
+ const jsonPath = reviewStorePath(cwd, sessionId, "report-" + stamp + ".json");
6364
+ const mdPath = reviewStorePath(cwd, sessionId, "report-" + stamp + ".md");
6365
+ const jsonOk = writeTextAtomic2(jsonPath, JSON.stringify(report, null, 2));
6366
+ const mdOk = writeTextAtomic2(mdPath, md);
6034
6367
  if (!jsonOk || !mdOk) {
6035
6368
  ctx.logger?.warn?.("[cohub review] 报告落盘失败:json=" + jsonPath + " md=" + mdPath);
6036
6369
  } else {
6037
6370
  ctx.logger.info?.("[cohub review] 报告已生成:" + mdPath);
6038
6371
  }
6372
+ const copy = writeProjectCopy(cwd, md, stamp);
6373
+ if (copy.path !== null) {
6374
+ ctx.logger.info?.("[cohub review] 项目内副本:" + copy.path);
6375
+ } else if (copy.note !== null) {
6376
+ ctx.logger?.warn?.("[cohub review] 未写项目内副本:" + copy.note);
6377
+ }
6378
+ try {
6379
+ const indexed = updateIndex({
6380
+ cwd,
6381
+ sessionId,
6382
+ status: analysis.status,
6383
+ findings: Array.isArray(report.findings) ? report.findings.length : 0,
6384
+ sessions: Array.isArray(report.sessions) ? report.sessions.length : 0,
6385
+ jsonPath,
6386
+ mdPath: mdOk ? mdPath : null,
6387
+ projectCopyPath: copy.path,
6388
+ note: copy.note ?? undefined
6389
+ });
6390
+ if (!indexed)
6391
+ ctx.logger?.warn?.("[cohub review] 复盘索引更新失败(不影响报告)");
6392
+ } catch (error) {
6393
+ ctx.logger?.warn?.("[cohub review] 复盘索引更新异常:" + String(error?.message ?? error));
6394
+ }
6039
6395
  }
6040
6396
  function cwdHintOf(inv) {
6041
6397
  const cwd = inv?.agent?.session?.header?.cwd ?? inv?.agent?.session?.meta?.cwd ?? inv?.agent?.options?.cwd ?? null;
@@ -6060,7 +6416,9 @@ function registerReviewCommand(ctx) {
6060
6416
  try {
6061
6417
  await runAnalysis(ctx, inv?.agent, sessionId, cwdHint, withLlm);
6062
6418
  } catch (error) {
6063
- ctx.logger?.warn?.("[cohub review] 报告生成失败:" + String(error?.message ?? error));
6419
+ const message = String(error?.message ?? error);
6420
+ appendErrorLog(cwdHint, sessionId, message);
6421
+ ctx.logger?.warn?.("[cohub review] 报告生成失败:" + message);
6064
6422
  } finally {
6065
6423
  inFlight.delete(sessionId);
6066
6424
  }
@@ -6278,14 +6636,14 @@ var CohubSettingsSchema = z2.object({
6278
6636
  var SHIPPED_PRESETS_DIR = fileURLToPath(new URL("../presets/", import.meta.url));
6279
6637
  function readPackageVersion() {
6280
6638
  try {
6281
- const pkg = JSON.parse(readFileSync4(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8"));
6639
+ const pkg = JSON.parse(readFileSync5(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8"));
6282
6640
  return typeof pkg?.version === "string" ? pkg.version : "0.0.0";
6283
6641
  } catch {
6284
6642
  return "0.0.0";
6285
6643
  }
6286
6644
  }
6287
6645
  function installAgentPresets(logger) {
6288
- return installShippedPresets(SHIPPED_PRESETS_DIR, dshHomePath4(".agent-presets"), readPackageVersion(), logger);
6646
+ return installShippedPresets(SHIPPED_PRESETS_DIR, dshHomePath5(".agent-presets"), readPackageVersion(), logger);
6289
6647
  }
6290
6648
  function apply(ctx, config) {
6291
6649
  ctx.effect(() => ctx.systemPrompt.section({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cohub",
3
- "version": "0.10.0",
3
+ "version": "0.10.1",
4
4
  "description": "DeepSeek Harness 版 CoHub:中文智能体编排——用户可选 2 种工作模式(co-orchestrator 纯调度 / cohub-cordis 创造模式)+ 13 个专职代理技能 + 多模型共识;另由 cohub-subagent-readonly / cohub-subagent-write 两个支撑 preset 实现子代理读写硬隔离(共 4 个 preset)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",