dsh-spec-collab 0.2.0 → 0.2.2

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 (38) hide show
  1. package/README.md +35 -0
  2. package/docs/experience-review-checklist-2026-08-24.md +115 -0
  3. package/lib/client.js +1391 -388
  4. package/lib/index.js +408 -50
  5. package/lib/types/client/SpecWorkbench.d.ts +69 -0
  6. package/lib/types/client/SpecWorkbench.d.ts.map +1 -1
  7. package/lib/types/client/mount.d.ts.map +1 -1
  8. package/lib/types/client/review-anchors.d.ts +21 -0
  9. package/lib/types/client/review-anchors.d.ts.map +1 -0
  10. package/lib/types/client/workflow.d.ts +1 -0
  11. package/lib/types/client/workflow.d.ts.map +1 -1
  12. package/lib/types/engine.d.ts.map +1 -1
  13. package/lib/types/index.d.ts +4 -0
  14. package/lib/types/index.d.ts.map +1 -1
  15. package/lib/types/prompts.d.ts +18 -0
  16. package/lib/types/prompts.d.ts.map +1 -0
  17. package/lib/types/protocol.d.ts +7 -0
  18. package/lib/types/protocol.d.ts.map +1 -1
  19. package/lib/types/review-context.d.ts +10 -1
  20. package/lib/types/review-context.d.ts.map +1 -1
  21. package/lib/types/review-runtime.d.ts +4 -1
  22. package/lib/types/review-runtime.d.ts.map +1 -1
  23. package/lib/types/workspace-context.d.ts +2 -0
  24. package/lib/types/workspace-context.d.ts.map +1 -0
  25. package/package.json +1 -1
  26. package/src/client/SpecWorkbench.tsx +456 -47
  27. package/src/client/mount.tsx +31 -5
  28. package/src/client/review-anchors.ts +134 -0
  29. package/src/client/workbench.module.css +234 -45
  30. package/src/client/workflow.ts +7 -7
  31. package/src/engine.ts +46 -3
  32. package/src/index.ts +21 -3
  33. package/src/prompts.ts +100 -0
  34. package/src/protocol.ts +4 -2
  35. package/src/review-context.ts +25 -7
  36. package/src/review-runtime.ts +53 -34
  37. package/src/tools.ts +3 -3
  38. package/src/workspace-context.ts +114 -0
package/lib/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { homedir } from "node:os";
2
- import { dirname, join, normalize, resolve } from "node:path";
2
+ import { dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
3
3
  import Schema from "schemastery";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
6
6
  import { execFileSync } from "node:child_process";
7
+ import { readFile, readdir, stat } from "node:fs/promises";
7
8
  import { defineTool } from "@deepseek-ai/dsh-tools";
8
9
  //#region src/git-store.ts
9
10
  var VersionConflictError = class extends Error {
@@ -551,7 +552,7 @@ var CollaborationEngine = class {
551
552
  record.currentCommit = version.commit;
552
553
  record.updatedAt = now;
553
554
  delete record.readyPackage;
554
- invalidateAffected(record, impact.sections, impact.acceptanceIds);
555
+ invalidateAffected(record, impact.sections, impact.acceptanceIds, action.markdown);
555
556
  record.patches.filter((item) => item.status === "pending").forEach((item) => {
556
557
  item.status = "stale";
557
558
  });
@@ -649,13 +650,16 @@ var CollaborationEngine = class {
649
650
  requireHuman(action.participant);
650
651
  const patch = record.patches.find((item) => item.id === action.patchId);
651
652
  if (patch === void 0 || patch.status !== "pending") throw new Error("pending patch not found");
652
- record.currentCommit = this.versions.save({
653
+ const version = this.versions.save({
653
654
  requirementId: record.id,
654
655
  baseCommit: patch.baseCommit,
655
656
  markdown: patch.proposedMarkdown,
656
657
  participant: action.participant,
657
658
  summary: action.summary
658
- }).commit;
659
+ });
660
+ const before = this.versions.read(record.id, record.currentCommit).markdown;
661
+ const impact = changedScopes(before, patch.proposedMarkdown);
662
+ record.currentCommit = version.commit;
659
663
  patch.status = "accepted";
660
664
  record.updatedAt = now;
661
665
  for (const id of patch.affectedReviewItemIds) {
@@ -665,6 +669,7 @@ var CollaborationEngine = class {
665
669
  item.updatedAt = now;
666
670
  }
667
671
  }
672
+ invalidateAffected(record, impact.sections, impact.acceptanceIds, patch.proposedMarkdown);
668
673
  record.actionItems.filter((task) => task.sourceId === patch.id && task.status === "pending").forEach((task) => {
669
674
  task.status = "handled";
670
675
  task.updatedAt = now;
@@ -679,6 +684,7 @@ var CollaborationEngine = class {
679
684
  this.persist();
680
685
  } else if (action.kind === "decision.create") {
681
686
  requireHuman(action.participant);
687
+ const sourceAnchors = [...action.sourceAnchors ?? [], ...decisionScopeAnchors(this.versions.read(record.id, record.currentCommit).markdown, action.affectedSections, action.affectedAcceptanceIds)].filter((anchor, index, anchors) => anchor.quote.trim() !== "" && anchors.findIndex((candidate) => normalizeAnchorText(candidate.quote) === normalizeAnchorText(anchor.quote) && normalizeAnchorText(candidate.heading ?? "") === normalizeAnchorText(anchor.heading ?? "")) === index);
682
688
  record.decisions.push({
683
689
  id: randomUUID(),
684
690
  requirementId: record.id,
@@ -690,6 +696,7 @@ var CollaborationEngine = class {
690
696
  confirmer: action.participant,
691
697
  affectedSections: action.affectedSections,
692
698
  affectedAcceptanceIds: action.affectedAcceptanceIds,
699
+ ...sourceAnchors.length > 0 ? { sourceAnchors } : {},
693
700
  createdAt: now,
694
701
  status: "active"
695
702
  });
@@ -960,7 +967,50 @@ function changedScopes(before, after) {
960
967
  function intersects(left, right) {
961
968
  return left.some((item) => right.includes(item));
962
969
  }
963
- function invalidateAffected(record, changedSections, changedAcceptanceIds) {
970
+ function normalizeAnchorText(value) {
971
+ return value.replace(/[`*_>#\[\]()~-]/g, "").replace(/\s+/g, "").toLocaleLowerCase();
972
+ }
973
+ function headingForLine(lines, index) {
974
+ for (let cursor = index; cursor >= 0; cursor -= 1) {
975
+ const match = /^#{1,4}\s+(.+)$/.exec(lines[cursor] ?? "");
976
+ if (match?.[1]) return match[1].trim();
977
+ }
978
+ }
979
+ function decisionScopeAnchors(markdown, affectedSections, affectedAcceptanceIds) {
980
+ const anchors = [];
981
+ const sectionMap = sections(markdown);
982
+ for (const section of affectedSections.map((value) => value.trim()).filter(Boolean)) {
983
+ const quote = sectionMap.get(section)?.split("\n").map((line) => line.trim()).find((line) => line && !/^#+\s+/.test(line));
984
+ if (quote) anchors.push({
985
+ heading: section,
986
+ quote
987
+ });
988
+ }
989
+ const lines = markdown.split("\n");
990
+ for (const acceptanceId of affectedAcceptanceIds.map((value) => value.trim()).filter(Boolean)) {
991
+ const index = lines.findIndex((line) => normalizeAnchorText(line).includes(normalizeAnchorText(acceptanceId)));
992
+ if (index >= 0) {
993
+ const heading = headingForLine(lines, index);
994
+ anchors.push({
995
+ ...heading ? { heading } : {},
996
+ quote: lines[index].trim()
997
+ });
998
+ }
999
+ }
1000
+ return anchors;
1001
+ }
1002
+ function decisionAnchorStillExists(markdown, anchor) {
1003
+ const quote = normalizeAnchorText(anchor.quote);
1004
+ if (!quote) return false;
1005
+ const sectionMap = sections(markdown);
1006
+ const candidates = anchor.heading?.trim() ? [sectionMap.get(anchor.heading.trim()) ?? ""] : [markdown];
1007
+ const context = normalizeAnchorText(`${anchor.prefix ?? ""}${anchor.quote}${anchor.suffix ?? ""}`);
1008
+ return candidates.some((candidate) => {
1009
+ const normalized = normalizeAnchorText(candidate);
1010
+ return normalized.includes(context) || normalized.includes(quote);
1011
+ });
1012
+ }
1013
+ function invalidateAffected(record, changedSections, changedAcceptanceIds, currentMarkdown) {
964
1014
  for (const confirmation of record.confirmations) {
965
1015
  if (confirmation.status !== "active") continue;
966
1016
  if (confirmation.scope === "version" || confirmation.scope === "section" && confirmation.scopeId !== void 0 && changedSections.includes(confirmation.scopeId) || confirmation.scope === "acceptance-criterion" && confirmation.scopeId !== void 0 && changedAcceptanceIds.includes(confirmation.scopeId)) {
@@ -987,6 +1037,9 @@ function invalidateAffected(record, changedSections, changedAcceptanceIds) {
987
1037
  record.decisions.filter((item) => item.status === "active" && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach((item) => {
988
1038
  item.status = "invalidated";
989
1039
  });
1040
+ if (currentMarkdown !== void 0) record.decisions.filter((item) => item.status === "active" && item.sourceAnchors?.some((anchor) => !decisionAnchorStillExists(currentMarkdown, anchor))).forEach((item) => {
1041
+ item.status = "invalidated";
1042
+ });
990
1043
  }
991
1044
  function readiness(markdown, record) {
992
1045
  const sectionMap = sections(markdown);
@@ -1060,6 +1113,101 @@ function readyMarkdown(view) {
1060
1113
  ].join("\n");
1061
1114
  }
1062
1115
  //#endregion
1116
+ //#region src/prompts.ts
1117
+ const DEFAULT_REVIEW_PROMPTS = {
1118
+ system: "本机已安装 dsh-spec-collab「AI 需求澄清与 Spec 共创工作台」。产品输入原始需求后,产品 AI 初审并生成结构化 Review Item,产品逐项回应,AI 二次审核并提出候选 patch;产品确认后进入产研与双方 AI 共审,最终通过 Ready 质量门输出 commit 绑定的 Ready Spec。正式 Spec 版本只存 Git+Markdown;AI 只能提出 Review Item、分析回复和候选 patch,不能确认产品/技术语义,也不能直接写 Git 或标记 Ready。该产品严格止于 Ready Spec,不执行代码开发、测试、worktree、部署或发布。使用 spec_list/spec_read 读取,spec_reply/spec_submit_review/spec_propose_patch 参与审核。",
1119
+ workspaceContext: [
1120
+ "## 本次审核必须使用的上下文",
1121
+ "DSH 工作区:`{{WORKSPACE_ID}}`。当前 AI session 必须挂载该工作区,不得创建未分组会话。",
1122
+ "工作区名称:{{WORKSPACE_TITLE}}",
1123
+ "工作区根目录:`{{WORKSPACE_PATH}}`",
1124
+ "",
1125
+ "开始审核前必须先实际读取工作区上下文,不能只读取 Spec:",
1126
+ "1. 检查工作区根目录,并读取存在的 AGENTS.md、CONTEXT.md、README/README.md 和 CONTRIBUTING.md。",
1127
+ "2. 读取存在的项目清单与构建入口,例如 package.json、pyproject.toml、Cargo.toml、go.mod、pom.xml 或构建脚本。",
1128
+ "3. 根据需求关键词定位相关代码、产品文档、测试和 Git 历史;结论引用具体文件路径及 commit 或其他可识别版本。",
1129
+ "4. 不得把“已绑定工作区”等同于“已读取上下文”。无法访问文件或历史时,明确说明并使用 TO_VERIFY。",
1130
+ "",
1131
+ "{{WORKSPACE_SNAPSHOT}}",
1132
+ "",
1133
+ "{{RESOURCE_INSTRUCTIONS}}"
1134
+ ].join("\n"),
1135
+ resourceInstructions: ["{{RESOURCE_DETAILS}}", "任何已配置资源若在当前 Agent Preset 中不可用、无权限或读取失败,必须在结论中明确指出该资源并使用 TO_VERIFY;不得假装已经查询或把不可访问内容写成 FACT。"].join("\n"),
1136
+ common: [
1137
+ "所有面向用户的输出必须使用简体中文,包括 Review Item 的陈述、影响、问题、成熟度总结、候选 patch 摘要以及评论分析回复。仅保留代码标识、路径、commit SHA、AC ID、FACT / INFERENCE / ASSUMPTION / TO_VERIFY 等固定枚举为原文。",
1138
+ "You are a review worker for a requirements clarification product. You must not implement code, generate downstream test delivery, create worktrees, deploy, or mark the requirement Ready. AI output is proposal data only and requires human confirmation.",
1139
+ "A FACT must cite an accessible, version-pinned source. If evidence is unavailable, use TO_VERIFY; never invent historical or implementation conflicts.",
1140
+ "Use spec_read to retrieve the exact current data. Do not modify files directly.",
1141
+ "每个 Review Item 默认给出三个 recommendedOptions。每个选项只表达一个决定,使用“选择 + 直接结果”的短句,建议不超过 45 个汉字;三个选项必须有真实差异,不得只是“接受、拒绝、待验证”的同义改写。确有四种独立方案时才允许第四项。",
1142
+ "Review Item 的 question 只问一个可以直接回答的问题,建议不超过 40 个汉字。背景放在 statement,后果放在 impact,不要把背景、问题和多个子问题挤进 question 或选项。",
1143
+ "每个 Review Item 必须提供 sourceAnchors:优先从当前 Spec 原文逐字复制 1 至 3 段能说明问题的短句,并填写所在 heading;不得改写或概括。问题来自正文缺失、没有可引用原文时,sourceAnchors 使用空数组,并通过 affectedSections / affectedAcceptanceIds 指明应补充的位置。",
1144
+ "审核记录与正式文档必须分层:FACT / INFERENCE / ASSUMPTION / TO_VERIFY、commit SHA、run ID 等只用于结构化审核记录,不得堆入候选 Spec 正文。",
1145
+ "候选 Spec 必须使用产品和研发都能直接理解的自然中文。避免行业黑话、审计腔和无必要的英文;英文缩写首次出现时必须同时写出中文含义,例如“行动按钮(CTA)”,后续优先使用中文。无法准确解释的缩写不要使用。",
1146
+ "优先使用这些通俗说法:操作按钮(不用 CTA)、统一风格标识(不用 canonical key)、点赞(不用 like)、提示词(不用 prompt)、测试数据(不用 fixture)、最终判断依据(不用事实源)、完成状态(不用终态)、重复操作结果一致(不用幂等)。Upgrade、Download、Lite、Plus 等确为界面文案或套餐名时可保留,但首次出现要说明中文含义。",
1147
+ "正文不要写“当前唯一可访问来源”“固定于某 commit”“统一记为 TO_VERIFY”这类过程说明。资料不足时,只在“待补充资料”章节按“资料名称:需要补充的内容;负责人(如已知)”列出,不重复背景、不写内部状态枚举。",
1148
+ "每段只表达一个结论,优先使用短句和具体业务语言。删除不影响需求理解、研发实现或验收判断的元信息。",
1149
+ "候选 patch 直接从文档标题开始,不写“本文为候选 patch”“不代表已确认决策”等免责声明。保留清晰的 Markdown 章节;身份与权限差异优先用表格,验收标准使用“前提 / 操作 / 预期结果”,不要使用 Given / When / Then。",
1150
+ "合并重复内容:目标讲用户结果,范围只列做与不做,业务规则只定义规则,验收标准只写可验证场景。同一句规则不要再分别复制到目标、范围、术语、验收和风险章节。"
1151
+ ].join("\n"),
1152
+ productFirst: "Perform the initial product review across goal, evidence, history-conflict, current-implementation, scope, semantics, completeness, acceptance, and risk. Submit structured findings with spec_submit_review. If the draft needs changes, also submit a candidate patch with spec_propose_patch. The candidate document must follow the plain-language and audit-metadata separation rules above.",
1153
+ productSecond: "Review product responses against their original Review Items. Do not close vague answers. Submit remaining/new findings with spec_submit_review and a reviewable candidate patch with spec_propose_patch. Rewrite awkward inherited wording instead of copying internal review terminology into the document.",
1154
+ engineeringPrecheck: "Read the product-confirmed Spec and inspect relevant current code/history available in the workspace. Find implementation fact conflicts, affected entries/roles/states, technical ambiguity, compatibility/permission/data boundaries, and unverifiable acceptance criteria. Submit with spec_submit_review and propose a patch only when needed.",
1155
+ changeReview: "Review only the latest saved commit against its parent. Identify materiality, affected sections/ACs, confirmations or decisions that need reconfirmation, and new conflicts. Submit with spec_submit_review; propose a patch only when needed.",
1156
+ comment: "Analyze this substantive comment. First query any code/document facts you can obtain. Then use spec_reply exactly once with your understanding, versioned evidence or TO_VERIFY status, affected sections/ACs, and recommended disposition. Do not silently modify the Spec or choose between conflicting product and engineering positions.",
1157
+ followUp: "请使用简体中文回答以下追问,并继续遵守当前 Spec 审核任务的证据、权限和结构化回写约束。\n\n{{CONTENT}}"
1158
+ };
1159
+ function resolveReviewPrompts(config = {}) {
1160
+ const prompts = {
1161
+ ...DEFAULT_REVIEW_PROMPTS,
1162
+ ...config
1163
+ };
1164
+ validateTemplate("workspaceContext", prompts.workspaceContext, [
1165
+ "WORKSPACE_ID",
1166
+ "WORKSPACE_TITLE",
1167
+ "WORKSPACE_PATH",
1168
+ "WORKSPACE_SNAPSHOT",
1169
+ "RESOURCE_INSTRUCTIONS"
1170
+ ], ["WORKSPACE_SNAPSHOT", "RESOURCE_INSTRUCTIONS"]);
1171
+ validateTemplate("resourceInstructions", prompts.resourceInstructions, [
1172
+ "RESOURCE_DETAILS",
1173
+ "SKILLS",
1174
+ "MCP_SERVERS",
1175
+ "DOCUMENT_PATHS"
1176
+ ]);
1177
+ validateTemplate("followUp", prompts.followUp, ["CONTENT"], ["CONTENT"]);
1178
+ for (const name of [
1179
+ "system",
1180
+ "common",
1181
+ "productFirst",
1182
+ "productSecond",
1183
+ "engineeringPrecheck",
1184
+ "changeReview",
1185
+ "comment"
1186
+ ]) validateTemplate(name, prompts[name], []);
1187
+ return prompts;
1188
+ }
1189
+ function renderPrompt(template, values) {
1190
+ return template.replace(/\{\{([A-Z_]+)\}\}/g, (placeholder, key) => values[key] ?? placeholder);
1191
+ }
1192
+ function extractPromptValue(rendered, template, placeholder) {
1193
+ const token = `{{${placeholder}}}`;
1194
+ const index = template.indexOf(token);
1195
+ if (index < 0) return void 0;
1196
+ const prefix = template.slice(0, index);
1197
+ const suffix = template.slice(index + token.length);
1198
+ if (!rendered.startsWith(prefix) || !rendered.endsWith(suffix)) return void 0;
1199
+ return rendered.slice(prefix.length, rendered.length - suffix.length);
1200
+ }
1201
+ function validateTemplate(name, template, allowed, requiredOnce = []) {
1202
+ const counts = /* @__PURE__ */ new Map();
1203
+ for (const match of template.matchAll(/\{\{([A-Z_]+)\}\}/g)) {
1204
+ const placeholder = match[1];
1205
+ if (!allowed.includes(placeholder)) throw new Error(`${name} prompt contains unsupported placeholder {{${placeholder}}}`);
1206
+ counts.set(placeholder, (counts.get(placeholder) ?? 0) + 1);
1207
+ }
1208
+ for (const placeholder of requiredOnce) if (counts.get(placeholder) !== 1) throw new Error(`${name} prompt must contain {{${placeholder}}} exactly once`);
1209
+ }
1210
+ //#endregion
1063
1211
  //#region src/review-context.ts
1064
1212
  const MCP_SERVER = /^[A-Za-z0-9_-]{1,32}$/;
1065
1213
  var ReviewContextCatalog = class {
@@ -1092,14 +1240,29 @@ var ReviewContextCatalog = class {
1092
1240
  };
1093
1241
  }
1094
1242
  };
1095
- function reviewContextPrompt(context) {
1096
- const rows = ["## 本次审核必须使用的上下文", `DSH 工作区:\`${context.workspaceId}\`。当前 AI session 必须挂载该工作区,不得创建未分组会话。`];
1243
+ function reviewContextPrompt(context, options = {}) {
1244
+ const workspace = options.workspace ?? {
1245
+ title: context.workspaceId,
1246
+ path: "未提供"
1247
+ };
1248
+ const rows = [];
1097
1249
  if (context.skills.length > 0) rows.push(`Skills:先调用 skill 工具加载 ${context.skills.map((value) => `\`${value}\``).join("、")},读取完整说明后再分析。`);
1098
1250
  if (context.mcpServers.length > 0) rows.push(`MCP:需要事实查询时优先使用 ${context.mcpServers.map((value) => `\`mcp__${value}__*\``).join("、")} namespace 下的工具。`);
1099
1251
  if (context.documentPaths.length > 0) rows.push("本地参考文档:分析前先读取与本需求相关的路径;相对路径基于当前 DSH 工作区根目录,引用时必须带具体文件路径和可识别版本。", ...context.documentPaths.map((value) => `- \`${value}\``));
1100
1252
  if (context.skills.length === 0 && context.mcpServers.length === 0 && context.documentPaths.length === 0) rows.push("当前未配置额外 Skill、MCP 或本地参考文档。");
1101
- rows.push("任何已配置资源若在当前 Agent Preset 中不可用、无权限或读取失败,必须在结论中明确指出该资源并使用 TO_VERIFY;不得假装已经查询或把不可访问内容写成 FACT。");
1102
- return rows.join("\n");
1253
+ const resourceInstructions = renderPrompt(options.resourceTemplate ?? DEFAULT_REVIEW_PROMPTS.resourceInstructions, {
1254
+ RESOURCE_DETAILS: rows.join("\n"),
1255
+ SKILLS: formatValues(context.skills),
1256
+ MCP_SERVERS: formatValues(context.mcpServers.map((value) => `mcp__${value}__*`)),
1257
+ DOCUMENT_PATHS: formatValues(context.documentPaths)
1258
+ });
1259
+ return renderPrompt(options.workspaceTemplate ?? DEFAULT_REVIEW_PROMPTS.workspaceContext, {
1260
+ WORKSPACE_ID: context.workspaceId,
1261
+ WORKSPACE_TITLE: workspace.title,
1262
+ WORKSPACE_PATH: workspace.path,
1263
+ WORKSPACE_SNAPSHOT: options.workspaceSnapshot ?? "工作区快照尚未生成。",
1264
+ RESOURCE_INSTRUCTIONS: resourceInstructions
1265
+ });
1103
1266
  }
1104
1267
  function normalizeResources(value) {
1105
1268
  const skills = cleanList(value?.skills);
@@ -1120,12 +1283,154 @@ function cleanList(values) {
1120
1283
  function unique(values) {
1121
1284
  return [...new Set(values)];
1122
1285
  }
1286
+ function formatValues(values) {
1287
+ return values.length > 0 ? values.map((value) => `\`${value}\``).join("、") : "未配置";
1288
+ }
1123
1289
  function resolveDocumentPath(value) {
1124
1290
  if (value === "~") return homedir();
1125
1291
  if (value.startsWith("~/") || value.startsWith("~\\")) return normalize(resolve(homedir(), value.slice(2)));
1126
1292
  return normalize(value);
1127
1293
  }
1128
1294
  //#endregion
1295
+ //#region src/workspace-context.ts
1296
+ const MAX_FILES = 20;
1297
+ const MAX_FILE_BYTES = 16 * 1024;
1298
+ const MAX_TOTAL_BYTES = 64 * 1024;
1299
+ const MAX_DIRECTORY_DEPTH = 4;
1300
+ const MAX_ROOT_ENTRIES = 80;
1301
+ const PROJECT_CONTEXT_FILES = /* @__PURE__ */ new Set([
1302
+ "agents.md",
1303
+ "context.md",
1304
+ "contributing.md",
1305
+ "package.json",
1306
+ "pyproject.toml",
1307
+ "cargo.toml",
1308
+ "go.mod",
1309
+ "pom.xml",
1310
+ "build.gradle",
1311
+ "build.gradle.kts",
1312
+ "requirements.txt",
1313
+ "gemfile"
1314
+ ]);
1315
+ const TEXT_EXTENSIONS = /* @__PURE__ */ new Set([
1316
+ ".md",
1317
+ ".mdx",
1318
+ ".txt",
1319
+ ".json",
1320
+ ".jsonc",
1321
+ ".yaml",
1322
+ ".yml",
1323
+ ".toml",
1324
+ ".xml",
1325
+ ".ini",
1326
+ ".cfg",
1327
+ ".conf",
1328
+ ".properties",
1329
+ ".gradle",
1330
+ ".kts",
1331
+ ".mod",
1332
+ ".rst",
1333
+ ".adoc"
1334
+ ]);
1335
+ const SKIP_DIRECTORIES = /* @__PURE__ */ new Set([
1336
+ ".git",
1337
+ "node_modules",
1338
+ "dist",
1339
+ "build",
1340
+ "lib",
1341
+ "coverage",
1342
+ ".next",
1343
+ ".cache"
1344
+ ]);
1345
+ async function readWorkspaceSnapshot(workspaceRoot, documentPaths) {
1346
+ const root = resolve(workspaceRoot);
1347
+ const rows = ["## 插件已读取的工作区快照", `工作区根目录:\`${root}\``];
1348
+ const notices = [];
1349
+ const candidates = [];
1350
+ const seen = /* @__PURE__ */ new Set();
1351
+ try {
1352
+ const rootEntries = await readdir(root, { withFileTypes: true });
1353
+ const visibleEntries = rootEntries.filter((entry) => !SKIP_DIRECTORIES.has(entry.name)).sort((left, right) => left.name.localeCompare(right.name)).slice(0, MAX_ROOT_ENTRIES).map((entry) => entry.isDirectory() ? `${entry.name}/` : entry.name);
1354
+ rows.push(`根目录条目:${visibleEntries.join("、") || "空目录"}`);
1355
+ for (const entry of rootEntries) {
1356
+ if (!entry.isFile() || !isProjectContextFile(entry.name)) continue;
1357
+ addCandidate(candidates, seen, resolve(root, entry.name), entry.name);
1358
+ }
1359
+ } catch (error) {
1360
+ rows.push("根目录条目:无法读取");
1361
+ notices.push(`- 工作区根目录无法读取:${errorMessage(error)}`);
1362
+ }
1363
+ for (const configuredPath of documentPaths) {
1364
+ const path = isAbsolute(configuredPath) ? resolve(configuredPath) : resolve(root, configuredPath);
1365
+ const displayPath = displayWorkspacePath(root, path);
1366
+ try {
1367
+ const value = await stat(path);
1368
+ if (value.isFile()) addCandidate(candidates, seen, path, displayPath);
1369
+ else if (value.isDirectory()) await collectDirectory(path, root, candidates, seen, 0);
1370
+ else notices.push(`- 无法读取 \`${displayPath}\`:不是普通文件或目录。`);
1371
+ } catch (error) {
1372
+ notices.push(`- 无法读取 \`${displayPath}\`:${errorMessage(error)}`);
1373
+ }
1374
+ }
1375
+ let totalBytes = 0;
1376
+ let renderedFiles = 0;
1377
+ for (const candidate of candidates) {
1378
+ if (renderedFiles >= MAX_FILES || totalBytes >= MAX_TOTAL_BYTES) break;
1379
+ try {
1380
+ const buffer = await readFile(candidate.path);
1381
+ if (buffer.subarray(0, Math.min(buffer.length, 4096)).includes(0)) {
1382
+ notices.push(`- 跳过二进制文件 \`${candidate.displayPath}\`。`);
1383
+ continue;
1384
+ }
1385
+ const availableBytes = Math.min(MAX_FILE_BYTES, MAX_TOTAL_BYTES - totalBytes);
1386
+ const content = buffer.subarray(0, availableBytes).toString("utf8");
1387
+ const truncated = buffer.length > availableBytes;
1388
+ rows.push("", `### \`${candidate.displayPath}\``, "<workspace-file>", content, truncated ? "\n[内容已截断]" : "", "</workspace-file>");
1389
+ totalBytes += Buffer.byteLength(content);
1390
+ renderedFiles += 1;
1391
+ } catch (error) {
1392
+ notices.push(`- 无法读取 \`${candidate.displayPath}\`:${errorMessage(error)}`);
1393
+ }
1394
+ }
1395
+ if (candidates.length > renderedFiles) notices.push(`- 工作区快照达到上限,仅注入前 ${renderedFiles} 个可读文本文件。`);
1396
+ if (renderedFiles === 0) rows.push("", "未发现可注入的标准项目上下文文件。");
1397
+ if (notices.length > 0) rows.push("", "### 读取说明", ...notices);
1398
+ return rows.join("\n");
1399
+ }
1400
+ async function collectDirectory(directory, root, candidates, seen, depth) {
1401
+ if (depth > MAX_DIRECTORY_DEPTH || candidates.length >= MAX_FILES) return;
1402
+ const entries = await readdir(directory, { withFileTypes: true });
1403
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
1404
+ if (candidates.length >= MAX_FILES) return;
1405
+ const path = resolve(directory, entry.name);
1406
+ if (entry.isDirectory() && !SKIP_DIRECTORIES.has(entry.name)) await collectDirectory(path, root, candidates, seen, depth + 1);
1407
+ else if (entry.isFile() && isTextFile(entry.name)) addCandidate(candidates, seen, path, displayWorkspacePath(root, path));
1408
+ }
1409
+ }
1410
+ function addCandidate(candidates, seen, path, displayPath) {
1411
+ if (seen.has(path) || candidates.length >= MAX_FILES) return;
1412
+ seen.add(path);
1413
+ candidates.push({
1414
+ path,
1415
+ displayPath
1416
+ });
1417
+ }
1418
+ function isProjectContextFile(name) {
1419
+ const lower = name.toLowerCase();
1420
+ return PROJECT_CONTEXT_FILES.has(lower) || lower === "readme" || lower.startsWith("readme.");
1421
+ }
1422
+ function isTextFile(name) {
1423
+ return isProjectContextFile(name) || TEXT_EXTENSIONS.has(extname(name).toLowerCase());
1424
+ }
1425
+ function displayWorkspacePath(root, path) {
1426
+ const value = relative(root, path);
1427
+ return value !== "" && !value.startsWith("..") ? value : path;
1428
+ }
1429
+ function errorMessage(error) {
1430
+ if (error instanceof Error && "code" in error && typeof error.code === "string") return error.code;
1431
+ return error instanceof Error ? error.message : String(error);
1432
+ }
1433
+ //#endregion
1129
1434
  //#region src/review-runtime.ts
1130
1435
  function request(payload) {
1131
1436
  return {
@@ -1136,12 +1441,15 @@ function request(payload) {
1136
1441
  function failure(error) {
1137
1442
  return /* @__PURE__ */ new Error(`${error.code}: ${error.message}`);
1138
1443
  }
1444
+ const FOLLOW_UP_METADATA = "\n\n<!-- dsh-spec-collab-follow-up:";
1139
1445
  var DshReviewCoordinator = class {
1140
1446
  api;
1141
1447
  contexts;
1142
- constructor(api, contexts = new ReviewContextCatalog()) {
1448
+ prompts;
1449
+ constructor(api, contexts = new ReviewContextCatalog(), prompts = {}) {
1143
1450
  this.api = api;
1144
1451
  this.contexts = contexts;
1452
+ this.prompts = resolveReviewPrompts(prompts);
1145
1453
  }
1146
1454
  async reviewWorkspaces() {
1147
1455
  const listed = await this.api.workspace.list(request({}));
@@ -1153,15 +1461,19 @@ var DshReviewCoordinator = class {
1153
1461
  }));
1154
1462
  }
1155
1463
  async assertWorkspaceAvailable(workspaceId) {
1156
- if (!(await this.reviewWorkspaces()).some((item) => item.workspaceId === workspaceId)) throw new Error(`workspace not found: ${workspaceId}`);
1464
+ await this.resolveWorkspace(workspaceId);
1157
1465
  }
1158
- requestReview(input) {
1466
+ async requestReview(input) {
1159
1467
  const context = this.contexts.resolve(input.requirement.workspaceId);
1160
- return this.launch(`Spec ${input.run.kind}: ${input.requirement.title}`, reviewPrompt(input.requirement, input.run, context), context.workspaceId, context.agentPreset);
1468
+ const workspace = await this.resolveWorkspace(context.workspaceId);
1469
+ const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths);
1470
+ return this.launch(`Spec ${input.run.kind}: ${input.requirement.title}`, reviewPrompt(input.requirement, input.run, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset);
1161
1471
  }
1162
- requestCommentReply(input) {
1472
+ async requestCommentReply(input) {
1163
1473
  const context = this.contexts.resolve(input.requirement.workspaceId);
1164
- return this.launch(`Spec comment analysis: ${input.requirement.title}`, commentPrompt(input.requirement, input.comment, context), context.workspaceId, context.agentPreset);
1474
+ const workspace = await this.resolveWorkspace(context.workspaceId);
1475
+ const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths);
1476
+ return this.launch(`Spec comment analysis: ${input.requirement.title}`, commentPrompt(input.requirement, input.comment, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset);
1165
1477
  }
1166
1478
  async conversation(sessionId) {
1167
1479
  const history = await this.api.sessions.history(request({ sessionId }));
@@ -1178,8 +1490,9 @@ var DshReviewCoordinator = class {
1178
1490
  const message = isObject(value) && "message" in value ? value.message : value;
1179
1491
  let messageText = collectText(isObject(message) && "content" in message ? message.content : message).join("\n").trim();
1180
1492
  if (entry.event.type === "user/message") {
1181
- if (!messageText.startsWith("请使用简体中文回答以下追问,并继续遵守当前 Spec 审核任务的证据、权限和结构化回写约束。")) continue;
1182
- messageText = messageText.slice(46).trim();
1493
+ const followUp = storedFollowUp(messageText) ?? extractPromptValue(messageText, this.prompts.followUp.trim(), "CONTENT") ?? extractPromptValue(messageText, DEFAULT_REVIEW_PROMPTS.followUp, "CONTENT");
1494
+ if (followUp === void 0) continue;
1495
+ messageText = followUp.trim();
1183
1496
  }
1184
1497
  if (messageText !== "") rows.push({
1185
1498
  role: entry.event.type === "user/message" ? "user" : "assistant",
@@ -1191,18 +1504,19 @@ var DshReviewCoordinator = class {
1191
1504
  async followUp(sessionId, text) {
1192
1505
  const content = text.trim();
1193
1506
  if (content === "") throw new Error("追问内容不能为空");
1507
+ const metadata = Buffer.from(content, "utf8").toString("base64url");
1508
+ const promptText = `${renderPrompt(this.prompts.followUp, { CONTENT: content }).trim()}${FOLLOW_UP_METADATA}${metadata} -->`;
1194
1509
  const prompted = await this.api.sessions.prompt(request({
1195
1510
  sessionId,
1196
1511
  mode: "queue",
1197
1512
  content: [{
1198
1513
  type: "text",
1199
- text: `请使用简体中文回答以下追问,并继续遵守当前 Spec 审核任务的证据、权限和结构化回写约束。\n\n${content}`
1514
+ text: promptText
1200
1515
  }]
1201
1516
  }));
1202
1517
  if (!prompted.result.ok) throw failure(prompted.result.error);
1203
1518
  }
1204
1519
  async launch(title, promptText, workspaceId, agentPreset) {
1205
- await this.assertWorkspaceAvailable(workspaceId);
1206
1520
  if (agentPreset !== void 0) {
1207
1521
  const presets = await this.api.agentPresets.list(request({}));
1208
1522
  if (!presets.result.ok) throw failure(presets.result.error);
@@ -1231,7 +1545,23 @@ var DshReviewCoordinator = class {
1231
1545
  if (!prompted.result.ok) throw failure(prompted.result.error);
1232
1546
  return sessionId;
1233
1547
  }
1548
+ async resolveWorkspace(workspaceId) {
1549
+ const workspace = (await this.reviewWorkspaces()).find((item) => item.workspaceId === workspaceId);
1550
+ if (workspace === void 0) throw new Error(`workspace not found: ${workspaceId}`);
1551
+ return workspace;
1552
+ }
1234
1553
  };
1554
+ function storedFollowUp(message) {
1555
+ const index = message.lastIndexOf(FOLLOW_UP_METADATA);
1556
+ if (index < 0 || !message.endsWith(" -->")) return void 0;
1557
+ const encoded = message.slice(index + 33, -4);
1558
+ if (!/^[A-Za-z0-9_-]+$/.test(encoded)) return void 0;
1559
+ try {
1560
+ return Buffer.from(encoded, "base64url").toString("utf8");
1561
+ } catch {
1562
+ return;
1563
+ }
1564
+ }
1235
1565
  function isObject(value) {
1236
1566
  return typeof value === "object" && value !== null;
1237
1567
  }
@@ -1241,52 +1571,46 @@ function collectText(value) {
1241
1571
  if (value.type === "text" && typeof value.text === "string") return [value.text];
1242
1572
  return "content" in value ? collectText(value.content) : [];
1243
1573
  }
1244
- function common(requirement, context) {
1574
+ function common(requirement, context, workspace, workspaceSnapshot, prompts) {
1245
1575
  return [
1246
1576
  `Requirement ID: ${requirement.id}`,
1247
1577
  `Pinned commit: ${requirement.currentCommit}`,
1248
1578
  "",
1249
- reviewContextPrompt(context),
1579
+ reviewContextPrompt(context, {
1580
+ workspace,
1581
+ workspaceSnapshot,
1582
+ workspaceTemplate: prompts.workspaceContext,
1583
+ resourceTemplate: prompts.resourceInstructions
1584
+ }),
1250
1585
  "",
1251
- "所有面向用户的输出必须使用简体中文,包括 Review Item 的陈述、影响、问题、成熟度总结、候选 patch 摘要以及评论分析回复。仅保留代码标识、路径、commit SHA、AC ID、FACT / INFERENCE / ASSUMPTION / TO_VERIFY 等固定枚举为原文。",
1252
- "You are a review worker for a requirements clarification product. You must not implement code, generate downstream test delivery, create worktrees, deploy, or mark the requirement Ready. AI output is proposal data only and requires human confirmation.",
1253
- "A FACT must cite an accessible, version-pinned source. If evidence is unavailable, use TO_VERIFY; never invent historical or implementation conflicts.",
1254
- "Use spec_read to retrieve the exact current data. Do not modify files directly.",
1255
- "每个 Review Item 默认给出三个 recommendedOptions。每个选项只表达一个决定,使用“选择 + 直接结果”的短句,建议不超过 45 个汉字;三个选项必须有真实差异,不得只是“接受、拒绝、待验证”的同义改写。确有四种独立方案时才允许第四项。",
1256
- "Review Item 的 question 只问一个可以直接回答的问题,建议不超过 40 个汉字。背景放在 statement,后果放在 impact,不要把背景、问题和多个子问题挤进 question 或选项。",
1257
- "审核记录与正式文档必须分层:FACT / INFERENCE / ASSUMPTION / TO_VERIFY、commit SHA、run ID 等只用于结构化审核记录,不得堆入候选 Spec 正文。",
1258
- "候选 Spec 必须使用产品和研发都能直接理解的自然中文。避免行业黑话、审计腔和无必要的英文;英文缩写首次出现时必须同时写出中文含义,例如“行动按钮(CTA)”,后续优先使用中文。无法准确解释的缩写不要使用。",
1259
- "优先使用这些通俗说法:操作按钮(不用 CTA)、统一风格标识(不用 canonical key)、点赞(不用 like)、提示词(不用 prompt)、测试数据(不用 fixture)、最终判断依据(不用事实源)、完成状态(不用终态)、重复操作结果一致(不用幂等)。Upgrade、Download、Lite、Plus 等确为界面文案或套餐名时可保留,但首次出现要说明中文含义。",
1260
- "正文不要写“当前唯一可访问来源”“固定于某 commit”“统一记为 TO_VERIFY”这类过程说明。资料不足时,只在“待补充资料”章节按“资料名称:需要补充的内容;负责人(如已知)”列出,不重复背景、不写内部状态枚举。",
1261
- "每段只表达一个结论,优先使用短句和具体业务语言。删除不影响需求理解、研发实现或验收判断的元信息。",
1262
- "候选 patch 直接从文档标题开始,不写“本文为候选 patch”“不代表已确认决策”等免责声明。保留清晰的 Markdown 章节;身份与权限差异优先用表格,验收标准使用“前提 / 操作 / 预期结果”,不要使用 Given / When / Then。",
1263
- "合并重复内容:目标讲用户结果,范围只列做与不做,业务规则只定义规则,验收标准只写可验证场景。同一句规则不要再分别复制到目标、范围、术语、验收和风险章节。"
1586
+ prompts.common
1264
1587
  ].join("\n");
1265
1588
  }
1266
- function reviewPrompt(requirement, run, context) {
1589
+ function reviewPrompt(requirement, run, context, workspace, workspaceSnapshot, prompts) {
1590
+ const tasks = {
1591
+ "product-first": prompts.productFirst,
1592
+ "product-second": prompts.productSecond,
1593
+ "engineering-precheck": prompts.engineeringPrecheck,
1594
+ "change-review": prompts.changeReview
1595
+ };
1267
1596
  return [
1268
- common(requirement, context),
1597
+ common(requirement, context, workspace, workspaceSnapshot, prompts),
1269
1598
  `Review run ID: ${run.id}`,
1270
1599
  `Review kind: ${run.kind}`,
1271
1600
  `AI session ID: {{SESSION_ID}}`,
1272
1601
  "",
1273
- {
1274
- "product-first": "Perform the initial product review across goal, evidence, history-conflict, current-implementation, scope, semantics, completeness, acceptance, and risk. Submit structured findings with spec_submit_review. If the draft needs changes, also submit a candidate patch with spec_propose_patch. The candidate document must follow the plain-language and audit-metadata separation rules above.",
1275
- "product-second": "Review product responses against their original Review Items. Do not close vague answers. Submit remaining/new findings with spec_submit_review and a reviewable candidate patch with spec_propose_patch. Rewrite awkward inherited wording instead of copying internal review terminology into the document.",
1276
- "engineering-precheck": "Read the product-confirmed Spec and inspect relevant current code/history available in the workspace. Find implementation fact conflicts, affected entries/roles/states, technical ambiguity, compatibility/permission/data boundaries, and unverifiable acceptance criteria. Submit with spec_submit_review and propose a patch only when needed.",
1277
- "change-review": "Review only the latest saved commit against its parent. Identify materiality, affected sections/ACs, confirmations or decisions that need reconfirmation, and new conflicts. Submit with spec_submit_review; propose a patch only when needed."
1278
- }[run.kind]
1602
+ tasks[run.kind]
1279
1603
  ].join("\n");
1280
1604
  }
1281
- function commentPrompt(requirement, comment, context) {
1605
+ function commentPrompt(requirement, comment, context, workspace, workspaceSnapshot, prompts) {
1282
1606
  return [
1283
- common(requirement, context),
1607
+ common(requirement, context, workspace, workspaceSnapshot, prompts),
1284
1608
  `Comment ID: ${comment.id}`,
1285
1609
  `Anchor quote: ${comment.anchor.quote}`,
1286
1610
  `Human comment: ${comment.body}`,
1287
1611
  `AI session ID: {{SESSION_ID}}`,
1288
1612
  "",
1289
- "Analyze this substantive comment. First query any code/document facts you can obtain. Then use spec_reply exactly once with your understanding, versioned evidence or TO_VERIFY status, affected sections/ACs, and recommended disposition. Do not silently modify the Spec or choose between conflicting product and engineering positions."
1613
+ prompts.comment
1290
1614
  ].join("\n");
1291
1615
  }
1292
1616
  //#endregion
@@ -1623,7 +1947,7 @@ function specReadTool(engine) {
1623
1947
  `commit: ${view.currentCommit}`
1624
1948
  ];
1625
1949
  if (include.has("spec")) rows.push("", "## Spec", view.version.markdown);
1626
- if (include.has("review-items")) rows.push("", "## Review Items", ...view.reviewItems.map((item) => `- ${item.id} [${item.severity}/${item.status}/${item.epistemicStatus}] ${item.statement}\n Question: ${item.question}\n Recommended options: ${(item.recommendedOptions ?? []).join(" / ") || "none"}\n Evidence: ${item.evidence.map((evidence) => `${evidence.source}${evidence.version ? `@${evidence.version}` : ""}`).join(", ") || "none"}`));
1950
+ if (include.has("review-items")) rows.push("", "## Review Items", ...view.reviewItems.map((item) => `- ${item.id} [${item.severity}/${item.status}/${item.epistemicStatus}] ${item.statement}\n Question: ${item.question}\n Spec anchors: ${(item.sourceAnchors ?? []).map((anchor) => `${anchor.heading ? `${anchor.heading}: ` : ""}${anchor.quote}`).join(" / ") || "none"}\n Recommended options: ${(item.recommendedOptions ?? []).join(" / ") || "none"}\n Evidence: ${item.evidence.map((evidence) => `${evidence.source}${evidence.version ? `@${evidence.version}` : ""}`).join(", ") || "none"}`));
1627
1951
  if (include.has("comments")) rows.push("", "## Comments", ...view.comments.map((item) => `- ${item.id} [${item.status}] “${item.anchor.quote}” ${item.author.nickname}: ${item.body}\n Replies: ${item.replies.map((reply) => `${reply.author.nickname}: ${reply.body}`).join(" / ") || "none"}`));
1628
1952
  if (include.has("decisions")) rows.push("", "## Decisions", ...view.decisions.map((item) => `- ${item.id} [${item.status}] ${item.question}: ${item.decision}`));
1629
1953
  if (include.has("confirmations")) rows.push("", "## Confirmations", ...view.confirmations.map((item) => `- ${item.role}/${item.scope}/${item.scopeId ?? "document"} [${item.status}] ${item.participant.nickname} @ ${item.commit}`));
@@ -1780,6 +2104,22 @@ function specSubmitReviewTool(engine) {
1780
2104
  items: { type: "string" },
1781
2105
  description: "默认三个、最多四个互有取舍的中文选项;每项只表达一个决定,建议不超过 45 个汉字。"
1782
2106
  },
2107
+ sourceAnchors: {
2108
+ type: "array",
2109
+ required: true,
2110
+ description: "直接从当前 Spec 原文复制 1-3 段精确短句;问题来自缺失内容时可为空数组。",
2111
+ items: {
2112
+ type: "object",
2113
+ additionalProperties: false,
2114
+ properties: {
2115
+ quote: {
2116
+ type: "string",
2117
+ required: true
2118
+ },
2119
+ heading: { type: "string" }
2120
+ }
2121
+ }
2122
+ },
1783
2123
  affectedSections: {
1784
2124
  type: "array",
1785
2125
  required: true,
@@ -1856,6 +2196,10 @@ function specSubmitReviewTool(engine) {
1856
2196
  impact: item.impact,
1857
2197
  question: item.question,
1858
2198
  recommendedOptions: item.recommendedOptions,
2199
+ sourceAnchors: item.sourceAnchors.map((anchor) => ({
2200
+ quote: anchor.quote.trim(),
2201
+ ...anchor.heading?.trim() ? { heading: anchor.heading.trim() } : {}
2202
+ })).filter((anchor) => anchor.quote),
1859
2203
  affectedSections: item.affectedSections,
1860
2204
  affectedAcceptanceIds: item.affectedAcceptanceIds,
1861
2205
  ownerRole: item.ownerRole,
@@ -1971,6 +2315,7 @@ const contextFields = () => ({
1971
2315
  documentPaths: stringList().description("AI 分析前可读取的本地文件或目录路径;相对路径按需求工作区根目录解析。"),
1972
2316
  agentPreset: Schema.string().description("实际挂载这些 Skill/MCP 工具的 DSH Agent Preset ID。")
1973
2317
  });
2318
+ const promptText = (value, description) => Schema.string().role("textarea").default(value).description(description);
1974
2319
  const Config = Schema.object({
1975
2320
  dataRoot: Schema.string().description("协作账本数据目录。"),
1976
2321
  repositoryPath: Schema.string().description("正式 Spec Git 仓库目录。"),
@@ -1978,13 +2323,26 @@ const Config = Schema.object({
1978
2323
  workspaces: Schema.array(Schema.object({
1979
2324
  workspaceId: Schema.string().required().description("需要追加项目专属 AI 上下文的 DSH workspaceId。"),
1980
2325
  ...contextFields()
1981
- })).default([]).description("按 DSH 工作区追加的 AI 上下文;未列出的工作区仍继承 defaultContext。")
2326
+ })).default([]).description("按 DSH 工作区追加的 AI 上下文;未列出的工作区仍继承 defaultContext。"),
2327
+ prompts: Schema.object({
2328
+ system: promptText(DEFAULT_REVIEW_PROMPTS.system, "注入普通 DSH 会话的插件系统说明。"),
2329
+ workspaceContext: promptText(DEFAULT_REVIEW_PROMPTS.workspaceContext, "工作区上下文模板。必须保留 {{WORKSPACE_SNAPSHOT}} 和 {{RESOURCE_INSTRUCTIONS}};还可使用 {{WORKSPACE_ID}}、{{WORKSPACE_TITLE}}、{{WORKSPACE_PATH}}。"),
2330
+ resourceInstructions: promptText(DEFAULT_REVIEW_PROMPTS.resourceInstructions, "Skill、MCP 和文档资源说明模板。可用变量:{{RESOURCE_DETAILS}}、{{SKILLS}}、{{MCP_SERVERS}}、{{DOCUMENT_PATHS}}。"),
2331
+ common: promptText(DEFAULT_REVIEW_PROMPTS.common, "所有审核和评论分析共享的约束。"),
2332
+ productFirst: promptText(DEFAULT_REVIEW_PROMPTS.productFirst, "产品 AI 初审任务提示词。"),
2333
+ productSecond: promptText(DEFAULT_REVIEW_PROMPTS.productSecond, "产品回复后的二次审核任务提示词。"),
2334
+ engineeringPrecheck: promptText(DEFAULT_REVIEW_PROMPTS.engineeringPrecheck, "研发智能预审任务提示词。"),
2335
+ changeReview: promptText(DEFAULT_REVIEW_PROMPTS.changeReview, "保存新版本后的变更审核任务提示词。"),
2336
+ comment: promptText(DEFAULT_REVIEW_PROMPTS.comment, "正文评论的 AI 分析任务提示词。"),
2337
+ followUp: promptText(DEFAULT_REVIEW_PROMPTS.followUp, "AI 会话追问模板,必须保留 {{CONTENT}}。")
2338
+ }).description("AI 提示词配置;未填写的字段使用插件内置默认值。")
1982
2339
  });
1983
2340
  function apply(ctx, config = {}) {
1984
2341
  const dataRoot = config.dataRoot ?? join(homedir(), ".dsh", "spec-collab");
1985
2342
  const contexts = new ReviewContextCatalog(config);
2343
+ const prompts = resolveReviewPrompts(config.prompts);
1986
2344
  const engine = new CollaborationEngine(join(dataRoot, "collaboration-v2.json"), new GitRequirementStore(config.repositoryPath ?? join(dataRoot, "repository")));
1987
- const coordinator = new DshReviewCoordinator(ctx.apiProxy, contexts);
2345
+ const coordinator = new DshReviewCoordinator(ctx.apiProxy, contexts, prompts);
1988
2346
  engine.setCoordinator(coordinator);
1989
2347
  ctx.effect(() => {
1990
2348
  const disposers = makeRoutes(engine, coordinator).map((route) => ctx.webServer.register(route));
@@ -2001,8 +2359,8 @@ function apply(ctx, config = {}) {
2001
2359
  ctx.effect(() => ctx.systemPrompt.section({
2002
2360
  name: "plugin:spec-collab",
2003
2361
  order: 190,
2004
- text: "本机已安装 dsh-spec-collab「AI 需求澄清与 Spec 共创工作台」。产品输入原始需求后,产品 AI 初审并生成结构化 Review Item,产品逐项回应,AI 二次审核并提出候选 patch;产品确认后进入产研与双方 AI 共审,最终通过 Ready 质量门输出 commit 绑定的 Ready Spec。正式 Spec 版本只存 Git+Markdown;AI 只能提出 Review Item、分析回复和候选 patch,不能确认产品/技术语义,也不能直接写 Git 或标记 Ready。该产品严格止于 Ready Spec,不执行代码开发、测试、worktree、部署或发布。使用 spec_list/spec_read 读取,spec_reply/spec_submit_review/spec_propose_patch 参与审核。"
2362
+ text: prompts.system
2005
2363
  }), "spec-collab: prompt");
2006
2364
  }
2007
2365
  //#endregion
2008
- export { Config, apply, inject, name };
2366
+ export { Config, DEFAULT_REVIEW_PROMPTS, apply, inject, name, resolveReviewPrompts };