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/src/engine.ts CHANGED
@@ -12,6 +12,7 @@ export interface AiCoordinator {
12
12
  const emptyState = (): CollaborationState => ({ schemaVersion: SCHEMA_VERSION, revision: 0, participants: [], requirements: [] })
13
13
 
14
14
  type EngineResult = ActionResult
15
+ type DecisionSourceAnchor = NonNullable<Extract<CollaborationAction, { kind: 'decision.create' }>['sourceAnchors']>[number]
15
16
 
16
17
  export class CollaborationEngine {
17
18
  private state: CollaborationState
@@ -170,7 +171,7 @@ export class CollaborationEngine {
170
171
  const version = this.versions.save({ requirementId: record.id, baseCommit: action.baseCommit, markdown: action.markdown, participant: action.participant, summary: action.summary })
171
172
  const impact = changedScopes(before, action.markdown)
172
173
  record.currentCommit = version.commit; record.updatedAt = now; delete record.readyPackage
173
- invalidateAffected(record, impact.sections, impact.acceptanceIds)
174
+ invalidateAffected(record, impact.sections, impact.acceptanceIds, action.markdown)
174
175
  record.patches.filter(item => item.status === 'pending').forEach(item => { item.status = 'stale' })
175
176
  if (record.stage === 'ready') record.stage = 'joint-review'
176
177
  this.persist()
@@ -216,8 +217,11 @@ export class CollaborationEngine {
216
217
  const patch = record.patches.find(item => item.id === action.patchId)
217
218
  if (patch === undefined || patch.status !== 'pending') throw new Error('pending patch not found')
218
219
  const version = this.versions.save({ requirementId: record.id, baseCommit: patch.baseCommit, markdown: patch.proposedMarkdown, participant: action.participant, summary: action.summary })
220
+ const before = this.versions.read(record.id, record.currentCommit).markdown
221
+ const impact = changedScopes(before, patch.proposedMarkdown)
219
222
  record.currentCommit = version.commit; patch.status = 'accepted'; record.updatedAt = now
220
223
  for (const id of patch.affectedReviewItemIds) { const item = record.reviewItems.find(candidate => candidate.id === id); if (item !== undefined) { item.status = 'resolved'; item.updatedAt = now } }
224
+ invalidateAffected(record, impact.sections, impact.acceptanceIds, patch.proposedMarkdown)
221
225
  record.actionItems.filter(task => task.sourceId === patch.id && task.status === 'pending').forEach(task => { task.status = 'handled'; task.updatedAt = now }); this.persist()
222
226
  this.enqueueReview(record, action.participant, 'change-review')
223
227
  } else if (action.kind === 'patch.reject') {
@@ -225,7 +229,9 @@ export class CollaborationEngine {
225
229
  const patch = record.patches.find(item => item.id === action.patchId); if (patch === undefined) throw new Error('patch not found'); patch.status = 'rejected'; this.persist()
226
230
  } else if (action.kind === 'decision.create') {
227
231
  requireHuman(action.participant)
228
- record.decisions.push({ id: randomUUID(), requirementId: record.id, commit: record.currentCommit, question: action.question, options: action.options, decision: action.decision, rationale: action.rationale, confirmer: action.participant, affectedSections: action.affectedSections, affectedAcceptanceIds: action.affectedAcceptanceIds, createdAt: now, status: 'active' }); this.persist()
232
+ const sourceAnchors = [...(action.sourceAnchors ?? []), ...decisionScopeAnchors(this.versions.read(record.id, record.currentCommit).markdown, action.affectedSections, action.affectedAcceptanceIds)]
233
+ .filter((anchor, index, anchors) => anchor.quote.trim() !== '' && anchors.findIndex(candidate => normalizeAnchorText(candidate.quote) === normalizeAnchorText(anchor.quote) && normalizeAnchorText(candidate.heading ?? '') === normalizeAnchorText(anchor.heading ?? '')) === index)
234
+ record.decisions.push({ id: randomUUID(), requirementId: record.id, commit: record.currentCommit, question: action.question, options: action.options, decision: action.decision, rationale: action.rationale, confirmer: action.participant, affectedSections: action.affectedSections, affectedAcceptanceIds: action.affectedAcceptanceIds, ...(sourceAnchors.length > 0 ? { sourceAnchors } : {}), createdAt: now, status: 'active' }); this.persist()
229
235
  } else if (action.kind === 'confirmation.create') {
230
236
  requireHuman(action.participant)
231
237
  if (action.participant.role !== action.role) throw new Error(`${action.role} role is required`)
@@ -333,7 +339,43 @@ function sections(markdown: string): Map<string, string> { const result = new Ma
333
339
  function acceptance(markdown: string): Map<string, string> { const result = new Map<string, string>(); for (const match of markdown.matchAll(/\*\*(AC-[A-Za-z0-9-]+)(?:\s+[^*]+)?\*\*\s*[::]\s*(.+)/g)) result.set(match[1]!, match[2]!.trim()); return result }
334
340
  function changedScopes(before: string, after: string): { sections: string[]; acceptanceIds: string[] } { const a = sections(before); const b = sections(after); const sectionNames = new Set([...a.keys(), ...b.keys()]); const acA = acceptance(before); const acB = acceptance(after); const acNames = new Set([...acA.keys(), ...acB.keys()]); return { sections: [...sectionNames].filter(key => a.get(key) !== b.get(key)), acceptanceIds: [...acNames].filter(key => acA.get(key) !== acB.get(key)) } }
335
341
  function intersects(left: string[], right: string[]): boolean { return left.some(item => right.includes(item)) }
336
- function invalidateAffected(record: RequirementRecord, changedSections: string[], changedAcceptanceIds: string[]): void {
342
+ function normalizeAnchorText(value: string): string { return value.replace(/[`*_>#\[\]()~-]/g, '').replace(/\s+/g, '').toLocaleLowerCase() }
343
+ function headingForLine(lines: string[], index: number): string | undefined {
344
+ for (let cursor = index; cursor >= 0; cursor -= 1) {
345
+ const match = /^#{1,4}\s+(.+)$/.exec(lines[cursor] ?? '')
346
+ if (match?.[1]) return match[1].trim()
347
+ }
348
+ return undefined
349
+ }
350
+ function decisionScopeAnchors(markdown: string, affectedSections: string[], affectedAcceptanceIds: string[]): DecisionSourceAnchor[] {
351
+ const anchors: DecisionSourceAnchor[] = []
352
+ const sectionMap = sections(markdown)
353
+ for (const section of affectedSections.map(value => value.trim()).filter(Boolean)) {
354
+ const quote = sectionMap.get(section)?.split('\n').map(line => line.trim()).find(line => line && !/^#+\s+/.test(line))
355
+ if (quote) anchors.push({ heading: section, quote })
356
+ }
357
+ const lines = markdown.split('\n')
358
+ for (const acceptanceId of affectedAcceptanceIds.map(value => value.trim()).filter(Boolean)) {
359
+ const index = lines.findIndex(line => normalizeAnchorText(line).includes(normalizeAnchorText(acceptanceId)))
360
+ if (index >= 0) {
361
+ const heading = headingForLine(lines, index)
362
+ anchors.push({ ...(heading ? { heading } : {}), quote: lines[index]!.trim() })
363
+ }
364
+ }
365
+ return anchors
366
+ }
367
+ function decisionAnchorStillExists(markdown: string, anchor: DecisionSourceAnchor): boolean {
368
+ const quote = normalizeAnchorText(anchor.quote)
369
+ if (!quote) return false
370
+ const sectionMap = sections(markdown)
371
+ const candidates = anchor.heading?.trim() ? [sectionMap.get(anchor.heading.trim()) ?? ''] : [markdown]
372
+ const context = normalizeAnchorText(`${anchor.prefix ?? ''}${anchor.quote}${anchor.suffix ?? ''}`)
373
+ return candidates.some(candidate => {
374
+ const normalized = normalizeAnchorText(candidate)
375
+ return normalized.includes(context) || normalized.includes(quote)
376
+ })
377
+ }
378
+ function invalidateAffected(record: RequirementRecord, changedSections: string[], changedAcceptanceIds: string[], currentMarkdown?: string): void {
337
379
  for (const confirmation of record.confirmations) {
338
380
  if (confirmation.status !== 'active') continue
339
381
  const affected = confirmation.scope === 'version' || (confirmation.scope === 'section' && confirmation.scopeId !== undefined && changedSections.includes(confirmation.scopeId)) || (confirmation.scope === 'acceptance-criterion' && confirmation.scopeId !== undefined && changedAcceptanceIds.includes(confirmation.scopeId))
@@ -341,6 +383,7 @@ function invalidateAffected(record: RequirementRecord, changedSections: string[]
341
383
  }
342
384
  record.reviewItems.filter(item => item.status === 'resolved' && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach(item => { item.status = 'invalidated'; item.updatedAt = Date.now() })
343
385
  record.decisions.filter(item => item.status === 'active' && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach(item => { item.status = 'invalidated' })
386
+ if (currentMarkdown !== undefined) record.decisions.filter(item => item.status === 'active' && item.sourceAnchors?.some(anchor => !decisionAnchorStillExists(currentMarkdown, anchor))).forEach(item => { item.status = 'invalidated' })
344
387
  }
345
388
  export function readiness(markdown: string, record: RequirementRecord): ReadinessCheck[] {
346
389
  const sectionMap = sections(markdown); const ac = acceptance(markdown)
package/src/index.ts CHANGED
@@ -8,14 +8,18 @@ import type {} from '@deepseek-ai/dsh-system-prompt'
8
8
  import type {} from '@deepseek-ai/dsh-tools'
9
9
  import { CollaborationEngine } from './engine.ts'
10
10
  import { GitRequirementStore } from './git-store.ts'
11
+ import { DEFAULT_REVIEW_PROMPTS, resolveReviewPrompts, type ReviewPromptConfig } from './prompts.ts'
11
12
  import { DshReviewCoordinator } from './review-runtime.ts'
12
13
  import { ReviewContextCatalog, type ReviewContextConfig } from './review-context.ts'
13
14
  import { makeRoutes } from './routes.ts'
14
15
  import { allSpecTools } from './tools.ts'
15
16
 
17
+ export { DEFAULT_REVIEW_PROMPTS, resolveReviewPrompts }
18
+ export type { ReviewPromptConfig }
19
+
16
20
  export const name = 'spec-collab'
17
21
  export const inject = ['webServer', 'apiProxy', 'tools', 'systemPrompt']
18
- export interface Config extends ReviewContextConfig { dataRoot?: string; repositoryPath?: string }
22
+ export interface Config extends ReviewContextConfig { dataRoot?: string; repositoryPath?: string; prompts?: ReviewPromptConfig }
19
23
 
20
24
  const stringList = () => Schema.array(Schema.string()).default([])
21
25
  const contextFields = () => ({
@@ -24,6 +28,7 @@ const contextFields = () => ({
24
28
  documentPaths: stringList().description('AI 分析前可读取的本地文件或目录路径;相对路径按需求工作区根目录解析。'),
25
29
  agentPreset: Schema.string().description('实际挂载这些 Skill/MCP 工具的 DSH Agent Preset ID。'),
26
30
  })
31
+ const promptText = (value: string, description: string) => Schema.string().role('textarea').default(value).description(description)
27
32
  export const Config: Schema<Config> = Schema.object({
28
33
  dataRoot: Schema.string().description('协作账本数据目录。'),
29
34
  repositoryPath: Schema.string().description('正式 Spec Git 仓库目录。'),
@@ -32,18 +37,31 @@ export const Config: Schema<Config> = Schema.object({
32
37
  workspaceId: Schema.string().required().description('需要追加项目专属 AI 上下文的 DSH workspaceId。'),
33
38
  ...contextFields(),
34
39
  })).default([]).description('按 DSH 工作区追加的 AI 上下文;未列出的工作区仍继承 defaultContext。'),
40
+ prompts: Schema.object({
41
+ system: promptText(DEFAULT_REVIEW_PROMPTS.system, '注入普通 DSH 会话的插件系统说明。'),
42
+ workspaceContext: promptText(DEFAULT_REVIEW_PROMPTS.workspaceContext, '工作区上下文模板。必须保留 {{WORKSPACE_SNAPSHOT}} 和 {{RESOURCE_INSTRUCTIONS}};还可使用 {{WORKSPACE_ID}}、{{WORKSPACE_TITLE}}、{{WORKSPACE_PATH}}。'),
43
+ resourceInstructions: promptText(DEFAULT_REVIEW_PROMPTS.resourceInstructions, 'Skill、MCP 和文档资源说明模板。可用变量:{{RESOURCE_DETAILS}}、{{SKILLS}}、{{MCP_SERVERS}}、{{DOCUMENT_PATHS}}。'),
44
+ common: promptText(DEFAULT_REVIEW_PROMPTS.common, '所有审核和评论分析共享的约束。'),
45
+ productFirst: promptText(DEFAULT_REVIEW_PROMPTS.productFirst, '产品 AI 初审任务提示词。'),
46
+ productSecond: promptText(DEFAULT_REVIEW_PROMPTS.productSecond, '产品回复后的二次审核任务提示词。'),
47
+ engineeringPrecheck: promptText(DEFAULT_REVIEW_PROMPTS.engineeringPrecheck, '研发智能预审任务提示词。'),
48
+ changeReview: promptText(DEFAULT_REVIEW_PROMPTS.changeReview, '保存新版本后的变更审核任务提示词。'),
49
+ comment: promptText(DEFAULT_REVIEW_PROMPTS.comment, '正文评论的 AI 分析任务提示词。'),
50
+ followUp: promptText(DEFAULT_REVIEW_PROMPTS.followUp, 'AI 会话追问模板,必须保留 {{CONTENT}}。'),
51
+ }).description('AI 提示词配置;未填写的字段使用插件内置默认值。'),
35
52
  }) as Schema<Config>
36
53
 
37
54
  export function apply(ctx: Context, config: Config = {}): void {
38
55
  const dataRoot = config.dataRoot ?? join(homedir(), '.dsh', 'spec-collab')
39
56
  const contexts = new ReviewContextCatalog(config)
57
+ const prompts = resolveReviewPrompts(config.prompts)
40
58
  const engine = new CollaborationEngine(join(dataRoot, 'collaboration-v2.json'), new GitRequirementStore(config.repositoryPath ?? join(dataRoot, 'repository')))
41
- const coordinator = new DshReviewCoordinator(ctx.apiProxy, contexts)
59
+ const coordinator = new DshReviewCoordinator(ctx.apiProxy, contexts, prompts)
42
60
  engine.setCoordinator(coordinator)
43
61
  ctx.effect(() => { const disposers = makeRoutes(engine, coordinator).map(route => ctx.webServer.register(route)); return () => { for (const dispose of disposers) dispose() } }, 'spec-collab: routes')
44
62
  ctx.effect(() => { const disposers = allSpecTools(engine).map(tool => ctx.tools.register(tool)); return () => { for (const dispose of disposers) dispose() } }, 'spec-collab: tools')
45
63
  ctx.effect(() => ctx.systemPrompt.section({
46
64
  name: 'plugin:spec-collab', order: 190,
47
- 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 参与审核。',
65
+ text: prompts.system,
48
66
  }), 'spec-collab: prompt')
49
67
  }
package/src/prompts.ts ADDED
@@ -0,0 +1,100 @@
1
+ export interface ReviewPromptConfig {
2
+ system?: string
3
+ workspaceContext?: string
4
+ resourceInstructions?: string
5
+ common?: string
6
+ productFirst?: string
7
+ productSecond?: string
8
+ engineeringPrecheck?: string
9
+ changeReview?: string
10
+ comment?: string
11
+ followUp?: string
12
+ }
13
+
14
+ export type ResolvedReviewPrompts = Required<ReviewPromptConfig>
15
+
16
+ export const DEFAULT_REVIEW_PROMPTS: ResolvedReviewPrompts = {
17
+ 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 参与审核。',
18
+ workspaceContext: [
19
+ '## 本次审核必须使用的上下文',
20
+ 'DSH 工作区:`{{WORKSPACE_ID}}`。当前 AI session 必须挂载该工作区,不得创建未分组会话。',
21
+ '工作区名称:{{WORKSPACE_TITLE}}',
22
+ '工作区根目录:`{{WORKSPACE_PATH}}`',
23
+ '',
24
+ '开始审核前必须先实际读取工作区上下文,不能只读取 Spec:',
25
+ '1. 检查工作区根目录,并读取存在的 AGENTS.md、CONTEXT.md、README/README.md 和 CONTRIBUTING.md。',
26
+ '2. 读取存在的项目清单与构建入口,例如 package.json、pyproject.toml、Cargo.toml、go.mod、pom.xml 或构建脚本。',
27
+ '3. 根据需求关键词定位相关代码、产品文档、测试和 Git 历史;结论引用具体文件路径及 commit 或其他可识别版本。',
28
+ '4. 不得把“已绑定工作区”等同于“已读取上下文”。无法访问文件或历史时,明确说明并使用 TO_VERIFY。',
29
+ '',
30
+ '{{WORKSPACE_SNAPSHOT}}',
31
+ '',
32
+ '{{RESOURCE_INSTRUCTIONS}}',
33
+ ].join('\n'),
34
+ resourceInstructions: [
35
+ '{{RESOURCE_DETAILS}}',
36
+ '任何已配置资源若在当前 Agent Preset 中不可用、无权限或读取失败,必须在结论中明确指出该资源并使用 TO_VERIFY;不得假装已经查询或把不可访问内容写成 FACT。',
37
+ ].join('\n'),
38
+ common: [
39
+ '所有面向用户的输出必须使用简体中文,包括 Review Item 的陈述、影响、问题、成熟度总结、候选 patch 摘要以及评论分析回复。仅保留代码标识、路径、commit SHA、AC ID、FACT / INFERENCE / ASSUMPTION / TO_VERIFY 等固定枚举为原文。',
40
+ '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.',
41
+ 'A FACT must cite an accessible, version-pinned source. If evidence is unavailable, use TO_VERIFY; never invent historical or implementation conflicts.',
42
+ 'Use spec_read to retrieve the exact current data. Do not modify files directly.',
43
+ '每个 Review Item 默认给出三个 recommendedOptions。每个选项只表达一个决定,使用“选择 + 直接结果”的短句,建议不超过 45 个汉字;三个选项必须有真实差异,不得只是“接受、拒绝、待验证”的同义改写。确有四种独立方案时才允许第四项。',
44
+ 'Review Item 的 question 只问一个可以直接回答的问题,建议不超过 40 个汉字。背景放在 statement,后果放在 impact,不要把背景、问题和多个子问题挤进 question 或选项。',
45
+ '每个 Review Item 必须提供 sourceAnchors:优先从当前 Spec 原文逐字复制 1 至 3 段能说明问题的短句,并填写所在 heading;不得改写或概括。问题来自正文缺失、没有可引用原文时,sourceAnchors 使用空数组,并通过 affectedSections / affectedAcceptanceIds 指明应补充的位置。',
46
+ '审核记录与正式文档必须分层:FACT / INFERENCE / ASSUMPTION / TO_VERIFY、commit SHA、run ID 等只用于结构化审核记录,不得堆入候选 Spec 正文。',
47
+ '候选 Spec 必须使用产品和研发都能直接理解的自然中文。避免行业黑话、审计腔和无必要的英文;英文缩写首次出现时必须同时写出中文含义,例如“行动按钮(CTA)”,后续优先使用中文。无法准确解释的缩写不要使用。',
48
+ '优先使用这些通俗说法:操作按钮(不用 CTA)、统一风格标识(不用 canonical key)、点赞(不用 like)、提示词(不用 prompt)、测试数据(不用 fixture)、最终判断依据(不用事实源)、完成状态(不用终态)、重复操作结果一致(不用幂等)。Upgrade、Download、Lite、Plus 等确为界面文案或套餐名时可保留,但首次出现要说明中文含义。',
49
+ '正文不要写“当前唯一可访问来源”“固定于某 commit”“统一记为 TO_VERIFY”这类过程说明。资料不足时,只在“待补充资料”章节按“资料名称:需要补充的内容;负责人(如已知)”列出,不重复背景、不写内部状态枚举。',
50
+ '每段只表达一个结论,优先使用短句和具体业务语言。删除不影响需求理解、研发实现或验收判断的元信息。',
51
+ '候选 patch 直接从文档标题开始,不写“本文为候选 patch”“不代表已确认决策”等免责声明。保留清晰的 Markdown 章节;身份与权限差异优先用表格,验收标准使用“前提 / 操作 / 预期结果”,不要使用 Given / When / Then。',
52
+ '合并重复内容:目标讲用户结果,范围只列做与不做,业务规则只定义规则,验收标准只写可验证场景。同一句规则不要再分别复制到目标、范围、术语、验收和风险章节。',
53
+ ].join('\n'),
54
+ 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.',
55
+ 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.',
56
+ 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.',
57
+ 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.',
58
+ 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.',
59
+ followUp: '请使用简体中文回答以下追问,并继续遵守当前 Spec 审核任务的证据、权限和结构化回写约束。\n\n{{CONTENT}}',
60
+ }
61
+
62
+ export function resolveReviewPrompts(config: ReviewPromptConfig = {}): ResolvedReviewPrompts {
63
+ const prompts = { ...DEFAULT_REVIEW_PROMPTS, ...config }
64
+ validateTemplate('workspaceContext', prompts.workspaceContext,
65
+ ['WORKSPACE_ID', 'WORKSPACE_TITLE', 'WORKSPACE_PATH', 'WORKSPACE_SNAPSHOT', 'RESOURCE_INSTRUCTIONS'],
66
+ ['WORKSPACE_SNAPSHOT', 'RESOURCE_INSTRUCTIONS'])
67
+ validateTemplate('resourceInstructions', prompts.resourceInstructions,
68
+ ['RESOURCE_DETAILS', 'SKILLS', 'MCP_SERVERS', 'DOCUMENT_PATHS'])
69
+ validateTemplate('followUp', prompts.followUp, ['CONTENT'], ['CONTENT'])
70
+ for (const name of ['system', 'common', 'productFirst', 'productSecond', 'engineeringPrecheck', 'changeReview', 'comment'] as const) {
71
+ validateTemplate(name, prompts[name], [])
72
+ }
73
+ return prompts
74
+ }
75
+
76
+ export function renderPrompt(template: string, values: Record<string, string>): string {
77
+ return template.replace(/\{\{([A-Z_]+)\}\}/g, (placeholder, key: string) => values[key] ?? placeholder)
78
+ }
79
+
80
+ export function extractPromptValue(rendered: string, template: string, placeholder: string): string | undefined {
81
+ const token = `{{${placeholder}}}`
82
+ const index = template.indexOf(token)
83
+ if (index < 0) return undefined
84
+ const prefix = template.slice(0, index)
85
+ const suffix = template.slice(index + token.length)
86
+ if (!rendered.startsWith(prefix) || !rendered.endsWith(suffix)) return undefined
87
+ return rendered.slice(prefix.length, rendered.length - suffix.length)
88
+ }
89
+
90
+ function validateTemplate(name: keyof ResolvedReviewPrompts, template: string, allowed: string[], requiredOnce: string[] = []): void {
91
+ const counts = new Map<string, number>()
92
+ for (const match of template.matchAll(/\{\{([A-Z_]+)\}\}/g)) {
93
+ const placeholder = match[1]!
94
+ if (!allowed.includes(placeholder)) throw new Error(`${name} prompt contains unsupported placeholder {{${placeholder}}}`)
95
+ counts.set(placeholder, (counts.get(placeholder) ?? 0) + 1)
96
+ }
97
+ for (const placeholder of requiredOnce) {
98
+ if (counts.get(placeholder) !== 1) throw new Error(`${name} prompt must contain {{${placeholder}}} exactly once`)
99
+ }
100
+ }
package/src/protocol.ts CHANGED
@@ -18,9 +18,11 @@ export interface ParticipantSnapshot { participantId: string; nickname: string;
18
18
  export interface SourceReference { id: string; sourceType: 'text' | 'markdown' | 'prototype' | 'meeting' | 'data' | 'link' | 'feedback' | 'code-scope'; label: string; stableId?: string; version?: string; accessStatus: 'available' | 'unverified' | 'missing' }
19
19
  export interface RequirementVersion { commit: string; parentCommit?: string; markdown: string; author: ParticipantSnapshot; summary: string; createdAt: number }
20
20
  export interface ReviewEvidence { statement: string; source: string; version?: string; accessible: boolean }
21
+ export interface ReviewSourceAnchor { quote: string; heading?: string }
21
22
  export interface ReviewItem {
22
23
  id: string; requirementId: string; commit: string; reviewKind: ReviewKind; type: ReviewItemType; severity: Severity; statement: string
23
24
  evidence: ReviewEvidence[]; epistemicStatus: EpistemicStatus; impact: string; question: string; affectedSections: string[]; affectedAcceptanceIds: string[]
25
+ sourceAnchors?: ReviewSourceAnchor[]
24
26
  recommendedOptions?: string[]
25
27
  ownerRole: ParticipantRole; ownerParticipantId?: string; status: ReviewItemStatus
26
28
  response?: { participant: ParticipantSnapshot; disposition: 'context' | 'evidence' | 'accept' | 'accept-modified' | 'reject' | 'to-verify' | 'joint-review'; body: string; createdAt: number }
@@ -39,7 +41,7 @@ export interface CandidatePatch {
39
41
  }
40
42
  export interface Decision {
41
43
  id: string; requirementId: string; commit: string; question: string; options: string[]; decision: string; rationale: string
42
- confirmer: ParticipantSnapshot; affectedSections: string[]; affectedAcceptanceIds: string[]; createdAt: number; status: 'active' | 'invalidated'
44
+ confirmer: ParticipantSnapshot; affectedSections: string[]; affectedAcceptanceIds: string[]; sourceAnchors?: Array<CommentThread['anchor']>; createdAt: number; status: 'active' | 'invalidated'
43
45
  }
44
46
  export interface Confirmation { id: string; requirementId: string; commit: string; role: ParticipantRole; participant: ParticipantSnapshot; scope: ConfirmationScope; scopeId?: string; status: 'active' | 'invalidated'; createdAt: number }
45
47
  export interface ActionItem {
@@ -81,7 +83,7 @@ export type CollaborationAction =
81
83
  | { kind: 'comment.resolve'; participant: ParticipantSnapshot; requirementId: string; commentId: string; resolution: CommentResolution }
82
84
  | { kind: 'patch.accept'; participant: ParticipantSnapshot; requirementId: string; patchId: string; summary: string }
83
85
  | { kind: 'patch.reject'; participant: ParticipantSnapshot; requirementId: string; patchId: string }
84
- | { kind: 'decision.create'; participant: ParticipantSnapshot; requirementId: string; question: string; options: string[]; decision: string; rationale: string; affectedSections: string[]; affectedAcceptanceIds: string[] }
86
+ | { kind: 'decision.create'; participant: ParticipantSnapshot; requirementId: string; question: string; options: string[]; decision: string; rationale: string; affectedSections: string[]; affectedAcceptanceIds: string[]; sourceAnchors?: Array<CommentThread['anchor']> }
85
87
  | { kind: 'confirmation.create'; participant: ParticipantSnapshot; requirementId: string; role: ParticipantRole; scope: ConfirmationScope; scopeId?: string }
86
88
  | { kind: 'stage.advance'; participant: ParticipantSnapshot; requirementId: string }
87
89
  | { kind: 'ready.generate'; participant: ParticipantSnapshot; requirementId: string }
@@ -1,5 +1,6 @@
1
1
  import { homedir } from 'node:os'
2
2
  import { normalize, resolve } from 'node:path'
3
+ import { DEFAULT_REVIEW_PROMPTS, renderPrompt } from './prompts.ts'
3
4
 
4
5
  export interface ReviewContextResources {
5
6
  skills?: string[]
@@ -56,17 +57,33 @@ export class ReviewContextCatalog {
56
57
  }
57
58
  }
58
59
 
59
- export function reviewContextPrompt(context: ResolvedReviewContext): string {
60
- const rows = [
61
- '## 本次审核必须使用的上下文',
62
- `DSH 工作区:\`${context.workspaceId}\`。当前 AI session 必须挂载该工作区,不得创建未分组会话。`,
63
- ]
60
+ export interface ReviewContextPromptOptions {
61
+ workspace?: { title: string; path: string }
62
+ workspaceSnapshot?: string
63
+ workspaceTemplate?: string
64
+ resourceTemplate?: string
65
+ }
66
+
67
+ export function reviewContextPrompt(context: ResolvedReviewContext, options: ReviewContextPromptOptions = {}): string {
68
+ const workspace = options.workspace ?? { title: context.workspaceId, path: '未提供' }
69
+ const rows: string[] = []
64
70
  if (context.skills.length > 0) rows.push(`Skills:先调用 skill 工具加载 ${context.skills.map(value => `\`${value}\``).join('、')},读取完整说明后再分析。`)
65
71
  if (context.mcpServers.length > 0) rows.push(`MCP:需要事实查询时优先使用 ${context.mcpServers.map(value => `\`mcp__${value}__*\``).join('、')} namespace 下的工具。`)
66
72
  if (context.documentPaths.length > 0) rows.push('本地参考文档:分析前先读取与本需求相关的路径;相对路径基于当前 DSH 工作区根目录,引用时必须带具体文件路径和可识别版本。', ...context.documentPaths.map(value => `- \`${value}\``))
67
73
  if (context.skills.length === 0 && context.mcpServers.length === 0 && context.documentPaths.length === 0) rows.push('当前未配置额外 Skill、MCP 或本地参考文档。')
68
- rows.push('任何已配置资源若在当前 Agent Preset 中不可用、无权限或读取失败,必须在结论中明确指出该资源并使用 TO_VERIFY;不得假装已经查询或把不可访问内容写成 FACT。')
69
- return rows.join('\n')
74
+ const resourceInstructions = renderPrompt(options.resourceTemplate ?? DEFAULT_REVIEW_PROMPTS.resourceInstructions, {
75
+ RESOURCE_DETAILS: rows.join('\n'),
76
+ SKILLS: formatValues(context.skills),
77
+ MCP_SERVERS: formatValues(context.mcpServers.map(value => `mcp__${value}__*`)),
78
+ DOCUMENT_PATHS: formatValues(context.documentPaths),
79
+ })
80
+ return renderPrompt(options.workspaceTemplate ?? DEFAULT_REVIEW_PROMPTS.workspaceContext, {
81
+ WORKSPACE_ID: context.workspaceId,
82
+ WORKSPACE_TITLE: workspace.title,
83
+ WORKSPACE_PATH: workspace.path,
84
+ WORKSPACE_SNAPSHOT: options.workspaceSnapshot ?? '工作区快照尚未生成。',
85
+ RESOURCE_INSTRUCTIONS: resourceInstructions,
86
+ })
70
87
  }
71
88
 
72
89
  function normalizeResources(value: ReviewContextResources | undefined): NormalizedReviewContext {
@@ -80,6 +97,7 @@ function normalizeResources(value: ReviewContextResources | undefined): Normaliz
80
97
 
81
98
  function cleanList(values: string[] | undefined): string[] { return unique((values ?? []).map(value => value.trim()).filter(Boolean)) }
82
99
  function unique(values: string[]): string[] { return [...new Set(values)] }
100
+ function formatValues(values: string[]): string { return values.length > 0 ? values.map(value => `\`${value}\``).join('、') : '未配置' }
83
101
  function resolveDocumentPath(value: string): string {
84
102
  if (value === '~') return homedir()
85
103
  if (value.startsWith('~/') || value.startsWith('~\\')) return normalize(resolve(homedir(), value.slice(2)))
@@ -1,28 +1,38 @@
1
1
  import type { ApiProxy, RpcId } from '@deepseek-ai/dsh-host-apiproxy'
2
2
  import type { AiCoordinator } from './engine.ts'
3
3
  import type { AiReviewRun, CommentThread, RequirementView, ReviewWorkspaceSummary } from './protocol.ts'
4
+ import { DEFAULT_REVIEW_PROMPTS, extractPromptValue, renderPrompt, resolveReviewPrompts, type ResolvedReviewPrompts, type ReviewPromptConfig } from './prompts.ts'
4
5
  import { ReviewContextCatalog, reviewContextPrompt } from './review-context.ts'
6
+ import { readWorkspaceSnapshot } from './workspace-context.ts'
5
7
 
6
8
  function request<T>(payload: T) { return { rpcId: `spec-collab-${crypto.randomUUID()}` as RpcId, payload } }
7
9
  function failure(error: { code: string; message: string }): Error { return new Error(`${error.code}: ${error.message}`) }
10
+ const FOLLOW_UP_METADATA = '\n\n<!-- dsh-spec-collab-follow-up:'
8
11
 
9
12
  export class DshReviewCoordinator implements AiCoordinator {
10
- constructor(private readonly api: ApiProxy, private readonly contexts = new ReviewContextCatalog()) {}
13
+ private readonly prompts: ResolvedReviewPrompts
14
+ constructor(private readonly api: ApiProxy, private readonly contexts = new ReviewContextCatalog(), prompts: ReviewPromptConfig = {}) {
15
+ this.prompts = resolveReviewPrompts(prompts)
16
+ }
11
17
  async reviewWorkspaces(): Promise<ReviewWorkspaceSummary[]> {
12
18
  const listed = await this.api.workspace.list(request({}))
13
19
  if (!listed.result.ok) throw failure(listed.result.error)
14
20
  return listed.result.value.items.map(item => ({ workspaceId: item.workspaceId, title: item.title, path: item.path }))
15
21
  }
16
22
  async assertWorkspaceAvailable(workspaceId: string): Promise<void> {
17
- if (!(await this.reviewWorkspaces()).some(item => item.workspaceId === workspaceId)) throw new Error(`workspace not found: ${workspaceId}`)
23
+ await this.resolveWorkspace(workspaceId)
18
24
  }
19
- requestReview(input: { requirement: RequirementView; run: AiReviewRun }): Promise<string> {
25
+ async requestReview(input: { requirement: RequirementView; run: AiReviewRun }): Promise<string> {
20
26
  const context = this.contexts.resolve(input.requirement.workspaceId)
21
- return this.launch(`Spec ${input.run.kind}: ${input.requirement.title}`, reviewPrompt(input.requirement, input.run, context), context.workspaceId, context.agentPreset)
27
+ const workspace = await this.resolveWorkspace(context.workspaceId)
28
+ const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths)
29
+ return this.launch(`Spec ${input.run.kind}: ${input.requirement.title}`, reviewPrompt(input.requirement, input.run, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset)
22
30
  }
23
- requestCommentReply(input: { requirement: RequirementView; comment: CommentThread }): Promise<string> {
31
+ async requestCommentReply(input: { requirement: RequirementView; comment: CommentThread }): Promise<string> {
24
32
  const context = this.contexts.resolve(input.requirement.workspaceId)
25
- return this.launch(`Spec comment analysis: ${input.requirement.title}`, commentPrompt(input.requirement, input.comment, context), context.workspaceId, context.agentPreset)
33
+ const workspace = await this.resolveWorkspace(context.workspaceId)
34
+ const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths)
35
+ return this.launch(`Spec comment analysis: ${input.requirement.title}`, commentPrompt(input.requirement, input.comment, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset)
26
36
  }
27
37
  async conversation(sessionId: string): Promise<Array<{ role: 'user' | 'assistant'; text: string }>> {
28
38
  const history = await this.api.sessions.history(request({ sessionId: sessionId as never }))
@@ -37,9 +47,11 @@ export class DshReviewCoordinator implements AiCoordinator {
37
47
  const content = isObject(message) && 'content' in message ? message.content : message
38
48
  let messageText = collectText(content).join('\n').trim()
39
49
  if (entry.event.type === 'user/message') {
40
- const marker = '请使用简体中文回答以下追问,并继续遵守当前 Spec 审核任务的证据、权限和结构化回写约束。'
41
- if (!messageText.startsWith(marker)) continue
42
- messageText = messageText.slice(marker.length).trim()
50
+ const followUp = storedFollowUp(messageText)
51
+ ?? extractPromptValue(messageText, this.prompts.followUp.trim(), 'CONTENT')
52
+ ?? extractPromptValue(messageText, DEFAULT_REVIEW_PROMPTS.followUp, 'CONTENT')
53
+ if (followUp === undefined) continue
54
+ messageText = followUp.trim()
43
55
  }
44
56
  if (messageText !== '') rows.push({ role: entry.event.type === 'user/message' ? 'user' : 'assistant', text: messageText })
45
57
  }
@@ -48,11 +60,12 @@ export class DshReviewCoordinator implements AiCoordinator {
48
60
  async followUp(sessionId: string, text: string): Promise<void> {
49
61
  const content = text.trim()
50
62
  if (content === '') throw new Error('追问内容不能为空')
51
- const prompted = await this.api.sessions.prompt(request({ sessionId: sessionId as never, mode: 'queue' as const, content: [{ type: 'text' as const, text: `请使用简体中文回答以下追问,并继续遵守当前 Spec 审核任务的证据、权限和结构化回写约束。\n\n${content}` }] }))
63
+ const metadata = Buffer.from(content, 'utf8').toString('base64url')
64
+ const promptText = `${renderPrompt(this.prompts.followUp, { CONTENT: content }).trim()}${FOLLOW_UP_METADATA}${metadata} -->`
65
+ const prompted = await this.api.sessions.prompt(request({ sessionId: sessionId as never, mode: 'queue' as const, content: [{ type: 'text' as const, text: promptText }] }))
52
66
  if (!prompted.result.ok) throw failure(prompted.result.error)
53
67
  }
54
68
  private async launch(title: string, promptText: string, workspaceId: string, agentPreset?: string): Promise<string> {
55
- await this.assertWorkspaceAvailable(workspaceId)
56
69
  if (agentPreset !== undefined) {
57
70
  const presets = await this.api.agentPresets.list(request({}))
58
71
  if (!presets.result.ok) throw failure(presets.result.error)
@@ -68,6 +81,19 @@ export class DshReviewCoordinator implements AiCoordinator {
68
81
  if (!prompted.result.ok) throw failure(prompted.result.error)
69
82
  return sessionId
70
83
  }
84
+ private async resolveWorkspace(workspaceId: string): Promise<ReviewWorkspaceSummary> {
85
+ const workspace = (await this.reviewWorkspaces()).find(item => item.workspaceId === workspaceId)
86
+ if (workspace === undefined) throw new Error(`workspace not found: ${workspaceId}`)
87
+ return workspace
88
+ }
89
+ }
90
+
91
+ function storedFollowUp(message: string): string | undefined {
92
+ const index = message.lastIndexOf(FOLLOW_UP_METADATA)
93
+ if (index < 0 || !message.endsWith(' -->')) return undefined
94
+ const encoded = message.slice(index + FOLLOW_UP_METADATA.length, -4)
95
+ if (!/^[A-Za-z0-9_-]+$/.test(encoded)) return undefined
96
+ try { return Buffer.from(encoded, 'base64url').toString('utf8') } catch { return undefined }
71
97
  }
72
98
 
73
99
  function isObject(value: unknown): value is Record<string, unknown> { return typeof value === 'object' && value !== null }
@@ -78,37 +104,30 @@ function collectText(value: unknown): string[] {
78
104
  return 'content' in value ? collectText(value.content) : []
79
105
  }
80
106
 
81
- function common(requirement: RequirementView, context: ReturnType<ReviewContextCatalog['resolve']>): string {
107
+ function common(requirement: RequirementView, context: ReturnType<ReviewContextCatalog['resolve']>, workspace: ReviewWorkspaceSummary, workspaceSnapshot: string, prompts: ResolvedReviewPrompts): string {
82
108
  return [
83
109
  `Requirement ID: ${requirement.id}`,
84
110
  `Pinned commit: ${requirement.currentCommit}`,
85
111
  '',
86
- reviewContextPrompt(context),
112
+ reviewContextPrompt(context, {
113
+ workspace,
114
+ workspaceSnapshot,
115
+ workspaceTemplate: prompts.workspaceContext,
116
+ resourceTemplate: prompts.resourceInstructions,
117
+ }),
87
118
  '',
88
- '所有面向用户的输出必须使用简体中文,包括 Review Item 的陈述、影响、问题、成熟度总结、候选 patch 摘要以及评论分析回复。仅保留代码标识、路径、commit SHA、AC ID、FACT / INFERENCE / ASSUMPTION / TO_VERIFY 等固定枚举为原文。',
89
- '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.',
90
- 'A FACT must cite an accessible, version-pinned source. If evidence is unavailable, use TO_VERIFY; never invent historical or implementation conflicts.',
91
- 'Use spec_read to retrieve the exact current data. Do not modify files directly.',
92
- '每个 Review Item 默认给出三个 recommendedOptions。每个选项只表达一个决定,使用“选择 + 直接结果”的短句,建议不超过 45 个汉字;三个选项必须有真实差异,不得只是“接受、拒绝、待验证”的同义改写。确有四种独立方案时才允许第四项。',
93
- 'Review Item 的 question 只问一个可以直接回答的问题,建议不超过 40 个汉字。背景放在 statement,后果放在 impact,不要把背景、问题和多个子问题挤进 question 或选项。',
94
- '审核记录与正式文档必须分层:FACT / INFERENCE / ASSUMPTION / TO_VERIFY、commit SHA、run ID 等只用于结构化审核记录,不得堆入候选 Spec 正文。',
95
- '候选 Spec 必须使用产品和研发都能直接理解的自然中文。避免行业黑话、审计腔和无必要的英文;英文缩写首次出现时必须同时写出中文含义,例如“行动按钮(CTA)”,后续优先使用中文。无法准确解释的缩写不要使用。',
96
- '优先使用这些通俗说法:操作按钮(不用 CTA)、统一风格标识(不用 canonical key)、点赞(不用 like)、提示词(不用 prompt)、测试数据(不用 fixture)、最终判断依据(不用事实源)、完成状态(不用终态)、重复操作结果一致(不用幂等)。Upgrade、Download、Lite、Plus 等确为界面文案或套餐名时可保留,但首次出现要说明中文含义。',
97
- '正文不要写“当前唯一可访问来源”“固定于某 commit”“统一记为 TO_VERIFY”这类过程说明。资料不足时,只在“待补充资料”章节按“资料名称:需要补充的内容;负责人(如已知)”列出,不重复背景、不写内部状态枚举。',
98
- '每段只表达一个结论,优先使用短句和具体业务语言。删除不影响需求理解、研发实现或验收判断的元信息。',
99
- '候选 patch 直接从文档标题开始,不写“本文为候选 patch”“不代表已确认决策”等免责声明。保留清晰的 Markdown 章节;身份与权限差异优先用表格,验收标准使用“前提 / 操作 / 预期结果”,不要使用 Given / When / Then。',
100
- '合并重复内容:目标讲用户结果,范围只列做与不做,业务规则只定义规则,验收标准只写可验证场景。同一句规则不要再分别复制到目标、范围、术语、验收和风险章节。',
119
+ prompts.common,
101
120
  ].join('\n')
102
121
  }
103
- function reviewPrompt(requirement: RequirementView, run: AiReviewRun, context: ReturnType<ReviewContextCatalog['resolve']>): string {
122
+ function reviewPrompt(requirement: RequirementView, run: AiReviewRun, context: ReturnType<ReviewContextCatalog['resolve']>, workspace: ReviewWorkspaceSummary, workspaceSnapshot: string, prompts: ResolvedReviewPrompts): string {
104
123
  const tasks: Record<AiReviewRun['kind'], string> = {
105
- '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.',
106
- '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.',
107
- '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.',
108
- '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.',
124
+ 'product-first': prompts.productFirst,
125
+ 'product-second': prompts.productSecond,
126
+ 'engineering-precheck': prompts.engineeringPrecheck,
127
+ 'change-review': prompts.changeReview,
109
128
  }
110
- return [common(requirement, context), `Review run ID: ${run.id}`, `Review kind: ${run.kind}`, `AI session ID: {{SESSION_ID}}`, '', tasks[run.kind]].join('\n')
129
+ return [common(requirement, context, workspace, workspaceSnapshot, prompts), `Review run ID: ${run.id}`, `Review kind: ${run.kind}`, `AI session ID: {{SESSION_ID}}`, '', tasks[run.kind]].join('\n')
111
130
  }
112
- function commentPrompt(requirement: RequirementView, comment: CommentThread, context: ReturnType<ReviewContextCatalog['resolve']>): string {
113
- return [common(requirement, context), `Comment ID: ${comment.id}`, `Anchor quote: ${comment.anchor.quote}`, `Human comment: ${comment.body}`, `AI session ID: {{SESSION_ID}}`, '', '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.'].join('\n')
131
+ function commentPrompt(requirement: RequirementView, comment: CommentThread, context: ReturnType<ReviewContextCatalog['resolve']>, workspace: ReviewWorkspaceSummary, workspaceSnapshot: string, prompts: ResolvedReviewPrompts): string {
132
+ return [common(requirement, context, workspace, workspaceSnapshot, prompts), `Comment ID: ${comment.id}`, `Anchor quote: ${comment.anchor.quote}`, `Human comment: ${comment.body}`, `AI session ID: {{SESSION_ID}}`, '', prompts.comment].join('\n')
114
133
  }
package/src/tools.ts CHANGED
@@ -25,7 +25,7 @@ export function specReadTool(engine: CollaborationEngine) {
25
25
  const include = new Set(args.include ?? ['spec', 'review-items', 'comments', 'decisions', 'confirmations', 'sources', 'readiness'])
26
26
  const rows = [`# ${view.title}`, `stage: ${view.stage}`, `commit: ${view.currentCommit}`]
27
27
  if (include.has('spec')) rows.push('', '## Spec', view.version.markdown)
28
- 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'}`))
28
+ 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'}`))
29
29
  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'}`))
30
30
  if (include.has('decisions')) rows.push('', '## Decisions', ...view.decisions.map(item => `- ${item.id} [${item.status}] ${item.question}: ${item.decision}`))
31
31
  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}`))
@@ -52,7 +52,7 @@ export function specSubmitReviewTool(engine: CollaborationEngine) {
52
52
  requirementId: { type: 'string', required: true }, commit: { type: 'string', required: true }, runId: { type: 'string', required: true }, reviewKind: { type: 'string', required: true, enum: ['product-first', 'product-second', 'engineering-precheck', 'change-review'] },
53
53
  nickname: { type: 'string', required: true }, role: { type: 'string', required: true, enum: ['product', 'engineering'] }, sessionId: { type: 'string', required: true }, maturitySummary: { type: 'string', required: true },
54
54
  items: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: {
55
- type: { type: 'string', required: true, enum: ['goal', 'evidence', 'history-conflict', 'current-implementation', 'scope', 'semantics', 'completeness', 'acceptance', 'risk'] }, severity: { type: 'string', required: true, enum: ['blocking', 'major', 'minor'] }, statement: { type: 'string', required: true }, epistemicStatus: { type: 'string', required: true, enum: ['FACT', 'INFERENCE', 'ASSUMPTION', 'TO_VERIFY'] }, impact: { type: 'string', required: true }, question: { type: 'string', required: true, description: '只问一个可直接回答的问题,使用简洁中文。' }, recommendedOptions: { type: 'array', required: true, items: { type: 'string' }, description: '默认三个、最多四个互有取舍的中文选项;每项只表达一个决定,建议不超过 45 个汉字。' }, affectedSections: { type: 'array', required: true, items: { type: 'string' } }, affectedAcceptanceIds: { type: 'array', required: true, items: { type: 'string' } }, ownerRole: { type: 'string', required: true, enum: ['product', 'engineering'] }, status: { type: 'string', required: true, enum: ['open', 'joint-review', 'non-blocking-verify'] }, evidence: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: { statement: { type: 'string', required: true }, source: { type: 'string', required: true }, version: { type: 'string' }, accessible: { type: 'boolean', required: true } } } },
55
+ type: { type: 'string', required: true, enum: ['goal', 'evidence', 'history-conflict', 'current-implementation', 'scope', 'semantics', 'completeness', 'acceptance', 'risk'] }, severity: { type: 'string', required: true, enum: ['blocking', 'major', 'minor'] }, statement: { type: 'string', required: true }, epistemicStatus: { type: 'string', required: true, enum: ['FACT', 'INFERENCE', 'ASSUMPTION', 'TO_VERIFY'] }, impact: { type: 'string', required: true }, question: { type: 'string', required: true, description: '只问一个可直接回答的问题,使用简洁中文。' }, recommendedOptions: { type: 'array', required: true, items: { type: 'string' }, description: '默认三个、最多四个互有取舍的中文选项;每项只表达一个决定,建议不超过 45 个汉字。' }, sourceAnchors: { type: 'array', required: true, description: '直接从当前 Spec 原文复制 1-3 段精确短句;问题来自缺失内容时可为空数组。', items: { type: 'object', additionalProperties: false, properties: { quote: { type: 'string', required: true }, heading: { type: 'string' } } } }, affectedSections: { type: 'array', required: true, items: { type: 'string' } }, affectedAcceptanceIds: { type: 'array', required: true, items: { type: 'string' } }, ownerRole: { type: 'string', required: true, enum: ['product', 'engineering'] }, status: { type: 'string', required: true, enum: ['open', 'joint-review', 'non-blocking-verify'] }, evidence: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: { statement: { type: 'string', required: true }, source: { type: 'string', required: true }, version: { type: 'string' }, accessible: { type: 'boolean', required: true } } } },
56
56
  } } },
57
57
  },
58
58
  output: contentOutput('Review submission result.'),
@@ -65,7 +65,7 @@ export function specSubmitReviewTool(engine: CollaborationEngine) {
65
65
  if ([...item.question.trim()].length > 80) throw new Error('review questions must be concise (80 characters maximum)')
66
66
  if (item.epistemicStatus === 'FACT' && !item.evidence.some(evidence => evidence.accessible && typeof evidence.version === 'string' && evidence.version !== '')) throw new Error('FACT requires accessible versioned evidence')
67
67
  }
68
- engine.submitReview({ requirementId: args.requirementId, commit: args.commit, runId: args.runId, ai: ai(args.nickname, args.role as ParticipantRole, args.sessionId), maturitySummary: args.maturitySummary, items: args.items.map(item => ({ type: item.type as ReviewItemType, severity: item.severity as Severity, statement: item.statement, evidence: item.evidence, epistemicStatus: item.epistemicStatus as EpistemicStatus, impact: item.impact, question: item.question, recommendedOptions: item.recommendedOptions, affectedSections: item.affectedSections, affectedAcceptanceIds: item.affectedAcceptanceIds, ownerRole: item.ownerRole as ParticipantRole, status: item.status as ReviewItemStatus })) })
68
+ engine.submitReview({ requirementId: args.requirementId, commit: args.commit, runId: args.runId, ai: ai(args.nickname, args.role as ParticipantRole, args.sessionId), maturitySummary: args.maturitySummary, items: args.items.map(item => ({ type: item.type as ReviewItemType, severity: item.severity as Severity, statement: item.statement, evidence: item.evidence, epistemicStatus: item.epistemicStatus as EpistemicStatus, impact: item.impact, question: item.question, recommendedOptions: item.recommendedOptions, sourceAnchors: item.sourceAnchors.map(anchor => ({ quote: anchor.quote.trim(), ...(anchor.heading?.trim() ? { heading: anchor.heading.trim() } : {}) })).filter(anchor => anchor.quote), affectedSections: item.affectedSections, affectedAcceptanceIds: item.affectedAcceptanceIds, ownerRole: item.ownerRole as ParticipantRole, status: item.status as ReviewItemStatus })) })
69
69
  return { content: `submitted ${args.items.length} review items for ${args.commit}` }
70
70
  },
71
71
  })