dsh-spec-collab 0.2.2 → 0.3.0

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 (49) hide show
  1. package/README.md +28 -7
  2. package/docs/assets/demo-01-workspace.png +0 -0
  3. package/docs/assets/demo-02-ai-review.png +0 -0
  4. package/docs/assets/demo-03-patches.png +0 -0
  5. package/docs/assets/demo-04-decisions.png +0 -0
  6. package/docs/assets/demo-05-ready.png +0 -0
  7. package/docs/experience-review-checklist-2026-08-24.md +72 -45
  8. package/docs/insight-import-template.csv +3 -0
  9. package/docs/insight-import-template.md +19 -0
  10. package/docs/migration-v3.md +23 -0
  11. package/lib/client.js +10825 -1163
  12. package/lib/index.js +1279 -89
  13. package/lib/types/client/AccessibleDialog.d.ts +9 -0
  14. package/lib/types/client/AccessibleDialog.d.ts.map +1 -0
  15. package/lib/types/client/SpecWorkbench.d.ts +42 -2
  16. package/lib/types/client/SpecWorkbench.d.ts.map +1 -1
  17. package/lib/types/client/api.d.ts +26 -3
  18. package/lib/types/client/api.d.ts.map +1 -1
  19. package/lib/types/client/drafts.d.ts +8 -0
  20. package/lib/types/client/drafts.d.ts.map +1 -0
  21. package/lib/types/client/mount.d.ts.map +1 -1
  22. package/lib/types/client/review-anchors.d.ts.map +1 -1
  23. package/lib/types/engine.d.ts +37 -3
  24. package/lib/types/engine.d.ts.map +1 -1
  25. package/lib/types/git-store.d.ts +6 -0
  26. package/lib/types/git-store.d.ts.map +1 -1
  27. package/lib/types/protocol.d.ts +245 -10
  28. package/lib/types/protocol.d.ts.map +1 -1
  29. package/lib/types/review-runtime.d.ts +6 -0
  30. package/lib/types/review-runtime.d.ts.map +1 -1
  31. package/lib/types/routes.d.ts.map +1 -1
  32. package/lib/types/structured-diff.d.ts +3 -0
  33. package/lib/types/structured-diff.d.ts.map +1 -0
  34. package/package.json +5 -2
  35. package/src/client/AccessibleDialog.tsx +42 -0
  36. package/src/client/SpecWorkbench.tsx +776 -87
  37. package/src/client/api.ts +8 -3
  38. package/src/client/drafts.ts +51 -0
  39. package/src/client/mount.tsx +11 -6
  40. package/src/client/review-anchors.ts +1 -0
  41. package/src/client/workbench.module.css +223 -79
  42. package/src/engine.ts +439 -41
  43. package/src/git-store.ts +87 -18
  44. package/src/index.ts +1 -1
  45. package/src/protocol.ts +64 -13
  46. package/src/review-runtime.ts +39 -11
  47. package/src/routes.ts +33 -4
  48. package/src/structured-diff.ts +75 -0
  49. package/src/tools.ts +1 -1
package/src/engine.ts CHANGED
@@ -1,15 +1,16 @@
1
1
  import { createHash, randomUUID } from 'node:crypto'
2
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
3
- import { dirname } from 'node:path'
2
+ import { closeSync, copyFileSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
3
+ import { basename, dirname, extname, join } from 'node:path'
4
4
  import { GitRequirementStore, VersionConflictError } from './git-store.ts'
5
- import { SCHEMA_VERSION, type ActionItem, type ActionResult, type AiReviewRun, type CandidatePatch, type CollaborationAction, type CollaborationState, type CommentThread, type MyActionItem, type MyItemCategory, type ParticipantSnapshot, type ReadinessCheck, type RequirementRecord, type RequirementVersion, type RequirementView, type ReviewItem, type ReviewKind, type SaveConflict } from './protocol.ts'
5
+ import { SCHEMA_VERSION, type ActionItem, type ActionResult, type AiReviewRun, type CandidatePatch, type CollaborationAction, type CollaborationEvent, type CollaborationState, type CommentThread, type FeedbackSource, type Insight, type InsightImportance, type InsightLink, type MyActionItem, type MyItemCategory, type Notification, type ParticipantSnapshot, type ReadinessCheck, type RequirementMetrics, type RequirementRecord, type RequirementSummary, type RequirementVersion, type RequirementView, type ReviewItem, type ReviewKind, type SaveConflict, type StructuredDiff } from './protocol.ts'
6
+ import { buildStructuredDiff } from './structured-diff.ts'
6
7
 
7
8
  export interface AiCoordinator {
8
- requestReview(input: { requirement: RequirementView; run: AiReviewRun }): Promise<string>
9
- requestCommentReply(input: { requirement: RequirementView; comment: CommentThread }): Promise<string>
9
+ requestReview(input: { requirement: RequirementView; run: AiReviewRun; sessionId?: string }): Promise<string>
10
+ requestCommentReply(input: { requirement: RequirementView; comment: CommentThread; sessionId?: string }): Promise<string>
10
11
  }
11
12
 
12
- const emptyState = (): CollaborationState => ({ schemaVersion: SCHEMA_VERSION, revision: 0, participants: [], requirements: [] })
13
+ const emptyState = (): CollaborationState => ({ schemaVersion: SCHEMA_VERSION, revision: 0, participants: [], requirements: [], companies: [], customers: [], feedbackSources: [], insights: [], insightLinks: [], notifications: [] })
13
14
 
14
15
  type EngineResult = ActionResult
15
16
  type DecisionSourceAnchor = NonNullable<Extract<CollaborationAction, { kind: 'decision.create' }>['sourceAnchors']>[number]
@@ -17,19 +18,53 @@ type DecisionSourceAnchor = NonNullable<Extract<CollaborationAction, { kind: 'de
17
18
  export class CollaborationEngine {
18
19
  private state: CollaborationState
19
20
  private coordinator?: AiCoordinator
20
- private readonly listeners = new Set<() => void>()
21
+ private readonly listeners = new Set<(event: CollaborationEvent) => void>()
21
22
  private readonly seen = new Map<string, EngineResult>()
23
+ private eventContext: Omit<CollaborationEvent, 'revision'> | undefined
22
24
 
23
- constructor(private readonly eventPath: string, private readonly versions: GitRequirementStore) { this.state = this.load() }
25
+ constructor(private readonly eventPath: string, private readonly versions: GitRequirementStore, private readonly options: { legacyPath?: string } = {}) { this.state = this.load() }
24
26
  setCoordinator(coordinator: AiCoordinator): void { this.coordinator = coordinator }
25
27
  snapshot(): CollaborationState { return structuredClone(this.state) }
26
- subscribe(listener: () => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener) }
28
+ directory(): ParticipantSnapshot[] { return structuredClone(this.state.participants).sort((left, right) => left.nickname.localeCompare(right.nickname, 'zh-CN')) }
29
+ notifications(participantId: string, page = 1, pageSize = 50): { items: Notification[]; total: number; unread: number } {
30
+ const rows = this.state.notifications.filter(item => item.recipientParticipantId === participantId).sort((left, right) => right.createdAt - left.createdAt)
31
+ const safePage = Number.isFinite(page) ? Math.max(1, Math.trunc(page)) : 1
32
+ const safePageSize = Number.isFinite(pageSize) ? Math.min(100, Math.max(1, Math.trunc(pageSize))) : 50
33
+ const start = (safePage - 1) * safePageSize
34
+ return { items: structuredClone(rows.slice(start, start + safePageSize)), total: rows.length, unread: rows.filter(item => item.readAt === undefined).length }
35
+ }
36
+ insights(query: { requirementId?: string; customerId?: string; companyId?: string; sourceId?: string; importance?: InsightImportance; page?: number; pageSize?: number } = {}): { items: Insight[]; total: number; links: CollaborationState['insightLinks']; customers: CollaborationState['customers']; companies: CollaborationState['companies']; sources: CollaborationState['feedbackSources'] } {
37
+ const linkedIds = query.requirementId === undefined ? undefined : new Set(this.state.insightLinks.filter(link => link.requirementId === query.requirementId).map(link => link.insightId))
38
+ const rows = this.state.insights.filter(item => { const companyId = item.companyId ?? (item.customerId ? this.state.customers.find(customer => customer.id === item.customerId)?.companyId : undefined); return (linkedIds === undefined || linkedIds.has(item.id)) && (query.customerId === undefined || item.customerId === query.customerId) && (query.companyId === undefined || companyId === query.companyId) && (query.sourceId === undefined || item.sourceId === query.sourceId) && (query.importance === undefined || item.importance === query.importance) }).sort((left, right) => right.capturedAt - left.capturedAt)
39
+ const pageSize = Math.min(100, Math.max(1, query.pageSize ?? 50)); const start = Math.max(0, (query.page ?? 1) - 1) * pageSize
40
+ const page = rows.slice(start, start + pageSize); const ids = new Set(page.map(item => item.id)); const customerIds = new Set(page.flatMap(item => item.customerId ? [item.customerId] : [])); const companyIds = new Set(page.flatMap(item => item.companyId ? [item.companyId] : [])); for (const customer of this.state.customers.filter(item => customerIds.has(item.id))) if (customer.companyId) companyIds.add(customer.companyId)
41
+ return { items: structuredClone(page), total: rows.length, links: structuredClone(this.state.insightLinks.filter(item => ids.has(item.insightId))), customers: structuredClone(this.state.customers.filter(item => customerIds.has(item.id))), companies: structuredClone(this.state.companies.filter(item => companyIds.has(item.id))), sources: structuredClone(this.state.feedbackSources.filter(item => page.some(insight => insight.sourceId === item.id))) }
42
+ }
43
+ subscribe(listener: (event: CollaborationEvent) => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener) }
27
44
  list(): RequirementView[] { return this.state.requirements.map(item => this.view(item.id)) }
45
+ summaries(): RequirementSummary[] {
46
+ return this.state.requirements.map(record => ({
47
+ id: record.id,
48
+ title: record.title,
49
+ stage: record.stage,
50
+ currentCommit: record.currentCommit,
51
+ ...(record.workspaceId ? { workspaceId: record.workspaceId } : {}),
52
+ ...(record.archivedAt ? { archivedAt: record.archivedAt } : {}),
53
+ updatedAt: record.updatedAt,
54
+ metrics: requirementMetrics(record, this.state),
55
+ participantIds: requirementParticipantIds(record, this.versions.history(record.id)),
56
+ }))
57
+ }
28
58
  version(requirementId: string, commit: string): RequirementVersion {
29
59
  const record = this.record(requirementId)
30
60
  if (!this.versions.history(record.id).some(version => version.commit === commit)) throw new Error('requirement version not found')
31
61
  return this.versions.read(record.id, commit)
32
62
  }
63
+ diff(requirementId: string, baseCommit: string, headCommit?: string): StructuredDiff {
64
+ const record = this.record(requirementId); const head = headCommit ?? record.currentCommit
65
+ const before = this.version(requirementId, baseCommit); const after = this.version(requirementId, head)
66
+ return buildStructuredDiff(before.markdown, after.markdown, baseCommit.slice(0, 10), head.slice(0, 10))
67
+ }
33
68
  myItems(participant: ParticipantSnapshot, category?: MyItemCategory): MyActionItem[] {
34
69
  const rows: MyActionItem[] = []
35
70
  for (const record of this.state.requirements) {
@@ -38,7 +73,7 @@ export class CollaborationEngine {
38
73
  const assigned = item.assigneeParticipantId === participant.participantId || (item.assigneeParticipantId === undefined && item.assigneeRole === participant.role)
39
74
  if (assigned) categories.push(item.type === 'confirm' || item.type === 'reconfirm' ? 'awaiting-my-confirmation' : 'awaiting-my-response')
40
75
  if (sourceParticipantId(record, item) === participant.participantId) categories.push('initiated-by-me')
41
- for (const current of categories) if (category === undefined || category === current) rows.push({ ...structuredClone(item), category: current, requirementTitle: record.title, target: actionTarget(item) })
76
+ for (const current of categories) if (category === undefined || category === current) rows.push({ ...structuredClone(item), category: current, requirementTitle: record.title, objectTitle: actionObjectTitle(record, item), target: actionTarget(item) })
42
77
  }
43
78
  }
44
79
  return rows.sort((left, right) => Number(right.blocking) - Number(left.blocking) || right.updatedAt - left.updatedAt)
@@ -50,13 +85,17 @@ export class CollaborationEngine {
50
85
  view(id: string): RequirementView {
51
86
  const record = this.record(id)
52
87
  const version = this.versions.read(id, record.currentCommit)
53
- return { ...structuredClone(record), version, history: this.versions.history(id), readiness: readiness(version.markdown, record) }
88
+ const commitUrl = this.versions.commitUrl(record.currentCommit)
89
+ return { ...structuredClone(record), version, history: this.versions.history(id), readiness: readiness(version.markdown, record), metrics: requirementMetrics(record, this.state), ...(commitUrl ? { commitUrl } : {}) }
54
90
  }
55
91
 
56
92
  apply(requestId: string, action: CollaborationAction): EngineResult {
57
93
  const cached = this.seen.get(requestId)
58
94
  if (cached !== undefined) return structuredClone(cached)
59
95
  let result: EngineResult
96
+ const beforeState = structuredClone(this.state)
97
+ const previousEventContext = this.eventContext
98
+ this.eventContext = eventForAction(action)
60
99
  try {
61
100
  const registered = action.participant.kind === 'human' ? this.state.participants.find(item => item.participantId === action.participant.participantId) : undefined
62
101
  if (registered !== undefined && registered.role !== action.participant.role) throw new Error(`participant role is bound to ${registered.role}`)
@@ -65,13 +104,15 @@ export class CollaborationEngine {
65
104
  this.state.participants.push(structuredClone(action.participant)); this.persist()
66
105
  result = result.deletedRequirementId
67
106
  ? { ...result, revision: this.state.revision }
68
- : { ok: true, revision: this.state.revision, requirement: this.view(result.requirement.id) }
107
+ : { ok: true, revision: this.state.revision, requirement: result.requirement }
69
108
  }
70
109
  }
71
110
  catch (error) {
111
+ this.state = beforeState
72
112
  const conflict = error instanceof VersionConflictError && action.kind === 'version.save' ? this.saveConflict(action) : undefined
73
113
  result = { ok: false, revision: this.state.revision, error: error instanceof Error ? error.message : String(error), ...(conflict === undefined ? {} : { conflict }) }
74
114
  }
115
+ this.eventContext = previousEventContext
75
116
  this.seen.set(requestId, result)
76
117
  return structuredClone(result)
77
118
  }
@@ -91,7 +132,7 @@ export class CollaborationEngine {
91
132
  record.actionItems.push(actionForReview(created))
92
133
  }
93
134
  run.status = 'completed'; run.maturitySummary = input.maturitySummary; run.updatedAt = now
94
- this.persist()
135
+ this.persist({ types: ['ai.status', 'metrics.changed'], requirementId: record.id, objectId: run.id })
95
136
  }
96
137
 
97
138
  submitPatch(input: { requirementId: string; baseCommit: string; reviewKind: ReviewKind; ai: ParticipantSnapshot; proposedMarkdown: string; summary: string; affectedReviewItemIds: string[]; affectedSections: string[]; affectedAcceptanceIds: string[] }): void {
@@ -101,16 +142,16 @@ export class CollaborationEngine {
101
142
  const patch: CandidatePatch = { id: randomUUID(), requirementId: record.id, baseCommit: input.baseCommit, reviewKind: input.reviewKind, proposedMarkdown: input.proposedMarkdown, summary: input.summary, affectedReviewItemIds: input.affectedReviewItemIds, affectedSections: input.affectedSections, affectedAcceptanceIds: input.affectedAcceptanceIds, createdBy: input.ai, status: 'pending', createdAt: Date.now() }
102
143
  record.patches.push(patch)
103
144
  record.actionItems.push({ id: randomUUID(), requirementId: record.id, sourceType: 'patch', sourceId: patch.id, type: 'confirm', assigneeRole: input.reviewKind === 'engineering-precheck' ? 'engineering' : 'product', blocking: true, status: 'pending', dueStage: record.stage, createdAt: Date.now(), updatedAt: Date.now() })
104
- this.persist()
145
+ this.persist({ types: ['ai.status', 'metrics.changed'], requirementId: record.id, objectId: patch.id })
105
146
  }
106
147
 
107
148
  submitAiReply(input: { requirementId: string; commentId: string; ai: ParticipantSnapshot; body: string }): void {
108
149
  assertChineseFeedback(input.body)
109
150
  const record = this.record(input.requirementId)
110
151
  const comment = this.comment(record, input.commentId)
111
- comment.replies.push({ id: randomUUID(), author: input.ai, body: input.body, createdAt: Date.now() })
152
+ comment.replies.push({ id: randomUUID(), author: input.ai, body: input.body, mentions: [], createdAt: Date.now() })
112
153
  comment.aiStatus = 'completed'; comment.updatedAt = Date.now()
113
- this.persist()
154
+ this.persist({ types: ['ai.status', 'comment.changed', 'metrics.changed'], requirementId: record.id, objectId: comment.id })
114
155
  }
115
156
 
116
157
  markAiFailure(requirementId: string, sourceId: string, error: string): void {
@@ -119,7 +160,7 @@ export class CollaborationEngine {
119
160
  if (run !== undefined) { run.status = 'failed'; run.error = error; run.updatedAt = Date.now() }
120
161
  const comment = record.comments.find(item => item.id === sourceId)
121
162
  if (comment !== undefined) { comment.aiStatus = 'failed'; comment.updatedAt = Date.now() }
122
- this.persist()
163
+ this.persist({ types: ['ai.status', 'metrics.changed'], requirementId, objectId: sourceId })
123
164
  }
124
165
 
125
166
  private applyFresh(action: CollaborationAction): EngineResult {
@@ -131,8 +172,8 @@ export class CollaborationEngine {
131
172
  const workspaceId = action.workspaceId?.trim()
132
173
  if (workspaceId === undefined || workspaceId === '') throw new Error('review workspace is required')
133
174
  const created = this.versions.create({ title, rawRequirement: action.rawRequirement, sources: action.sources, participant: action.participant })
134
- const record: RequirementRecord = { id: created.requirementId, title, stage: 'product-review', currentCommit: created.version.commit, workspaceId, sources: action.sources, reviewItems: [], comments: [], patches: [], decisions: [], confirmations: [], actionItems: [], aiRuns: [], createdAt: now, updatedAt: now }
135
- this.state.requirements.unshift(record); this.persist()
175
+ const record: RequirementRecord = { id: created.requirementId, title, stage: 'product-review', stageCycle: 0, currentCommit: created.version.commit, workspaceId, sources: action.sources, reviewItems: [], comments: [], patches: [], decisions: [], confirmations: [], actionItems: [], aiRuns: [], aiConversations: [], createdAt: now, updatedAt: now }
176
+ this.state.requirements.unshift(record); this.persist(undefined, true)
136
177
  this.enqueueReview(record, action.participant, 'product-first')
137
178
  return { ok: true, revision: this.state.revision, requirement: this.view(record.id) }
138
179
  }
@@ -152,10 +193,10 @@ export class CollaborationEngine {
152
193
  const markdown = /^# .+$/m.test(before) ? before.replace(/^# .+$/m, `# ${title}`) : `# ${title}\n\n${before}`
153
194
  const version = this.versions.save({ requirementId: record.id, baseCommit: record.currentCommit, markdown, participant: action.participant, summary: `Rename requirement: ${title}` })
154
195
  record.title = title; record.currentCommit = version.commit; record.updatedAt = now
155
- invalidateAffected(record, [], []); this.persist(); this.enqueueReview(record, action.participant, 'change-review')
156
- } else if (action.kind === 'requirement.archive') {
196
+ invalidateAffected(record, [], []); this.persist(undefined, true); this.enqueueReview(record, action.participant, 'change-review')
197
+ } else if (action.kind === 'requirement.archive' || action.kind === 'requirement.unarchive') {
157
198
  requireHuman(action.participant)
158
- if (action.archived) record.archivedAt = now
199
+ if (action.kind === 'requirement.archive' && action.archived) record.archivedAt = now
159
200
  else delete record.archivedAt
160
201
  record.updatedAt = now; this.persist()
161
202
  } else if (action.kind === 'requirement.delete') {
@@ -163,7 +204,8 @@ export class CollaborationEngine {
163
204
  const deleted = this.view(record.id)
164
205
  this.versions.remove(record.id, action.participant)
165
206
  this.state.requirements.splice(this.state.requirements.indexOf(record), 1)
166
- this.persist()
207
+ this.state.insightLinks = this.state.insightLinks.filter(item => item.requirementId !== record.id)
208
+ this.persist(undefined, true)
167
209
  return { ok: true, revision: this.state.revision, requirement: deleted, deletedRequirementId: record.id }
168
210
  } else if (action.kind === 'version.save') {
169
211
  requireHuman(action.participant)
@@ -173,9 +215,21 @@ export class CollaborationEngine {
173
215
  record.currentCommit = version.commit; record.updatedAt = now; delete record.readyPackage
174
216
  invalidateAffected(record, impact.sections, impact.acceptanceIds, action.markdown)
175
217
  record.patches.filter(item => item.status === 'pending').forEach(item => { item.status = 'stale' })
176
- if (record.stage === 'ready') record.stage = 'joint-review'
177
- this.persist()
218
+ if (record.stage === 'ready') enterStage(record, 'joint-review')
219
+ this.persist(undefined, true)
178
220
  this.enqueueReview(record, action.participant, 'change-review')
221
+ } else if (action.kind === 'version.restore') {
222
+ requireHuman(action.participant)
223
+ const historical = this.version(record.id, action.commit)
224
+ if (historical.commit === record.currentCommit) throw new Error('selected version is already current')
225
+ const before = this.versions.read(record.id, record.currentCommit).markdown
226
+ const version = this.versions.save({ requirementId: record.id, baseCommit: record.currentCommit, markdown: historical.markdown, participant: action.participant, summary: action.summary.trim() || `恢复版本 ${historical.commit.slice(0, 8)}` })
227
+ const impact = changedScopes(before, historical.markdown)
228
+ record.currentCommit = version.commit; record.updatedAt = now; delete record.readyPackage
229
+ invalidateAffected(record, impact.sections, impact.acceptanceIds, historical.markdown)
230
+ record.patches.filter(item => item.status === 'pending').forEach(item => { item.status = 'stale' })
231
+ if (record.stage === 'ready') enterStage(record, 'joint-review')
232
+ this.persist(undefined, true); this.enqueueReview(record, action.participant, 'change-review')
179
233
  } else if (action.kind === 'review.request') {
180
234
  requireHuman(action.participant)
181
235
  this.enqueueReview(record, action.participant, action.reviewKind)
@@ -191,27 +245,46 @@ export class CollaborationEngine {
191
245
  } else if (action.kind === 'comment.create') {
192
246
  requireHuman(action.participant)
193
247
  if (action.commit !== record.currentCommit) throw new VersionConflictError(record.currentCommit)
194
- const comment: CommentThread = { id: randomUUID(), requirementId: record.id, commit: action.commit, anchor: action.anchor, author: action.participant, body: action.body.trim(), replies: [], aiStatus: 'queued', status: 'open', createdAt: now, updatedAt: now }
195
- if (comment.body === '' || comment.anchor.quote.trim() === '') throw new Error('comment and anchor are required')
248
+ const scope = action.scope ?? 'inline'; const mentions = validMentions(action.mentions, this.state.participants)
249
+ const comment: CommentThread = { id: randomUUID(), requirementId: record.id, commit: action.commit, scope, ...(action.anchor === undefined ? {} : { anchor: action.anchor }), author: action.participant, body: action.body.trim(), mentions, replies: [], aiStatus: 'queued', status: 'open', createdAt: now, updatedAt: now }
250
+ if (comment.body === '' || (scope === 'inline' && action.anchor?.quote.trim() === '')) throw new Error(scope === 'inline' ? 'comment and anchor are required' : 'comment is required')
251
+ if (scope === 'inline' && action.anchor === undefined) throw new Error('comment and anchor are required')
196
252
  record.comments.push(comment)
197
253
  record.actionItems.push({ id: randomUUID(), requirementId: record.id, sourceType: 'comment', sourceId: comment.id, type: 'reply', assigneeRole: action.participant.role === 'product' ? 'engineering' : 'product', blocking: true, status: 'pending', dueStage: record.stage, createdAt: now, updatedAt: now })
254
+ for (const participantId of mentions) this.notify(participantId, 'mention', record, 'comment', comment.id, `${action.participant.nickname} 在评论中提到了你`)
198
255
  this.persist()
199
256
  const coordinator = this.coordinator
200
257
  if (coordinator !== undefined) {
201
258
  const view = this.view(record.id)
202
- void coordinator.requestCommentReply({ requirement: view, comment }).then(sessionId => {
203
- comment.aiStatus = 'running'; comment.aiSessionId = sessionId; comment.updatedAt = Date.now(); this.persist()
259
+ const requestedStage = record.stage; const requestedStageCycle = record.stageCycle
260
+ const existingSession = record.aiConversations.find(item => item.stage === requestedStage && item.stageCycle === requestedStageCycle)?.sessionId
261
+ void coordinator.requestCommentReply({ requirement: view, comment, ...(existingSession ? { sessionId: existingSession } : {}) }).then(sessionId => {
262
+ comment.aiStatus = 'running'; comment.aiSessionId = sessionId; comment.updatedAt = Date.now(); this.rememberStageConversation(record, sessionId, requestedStage, requestedStageCycle); this.persist({ types: ['ai.status', 'comment.changed', 'metrics.changed'], requirementId: record.id, objectId: comment.id })
204
263
  }, error => this.markAiFailure(record.id, comment.id, error instanceof Error ? error.message : String(error)))
205
264
  }
206
265
  } else if (action.kind === 'comment.reply') {
207
266
  requireHuman(action.participant)
208
267
  const comment = this.comment(record, action.commentId)
209
- comment.replies.push({ id: randomUUID(), author: action.participant, body: action.body.trim(), createdAt: now }); comment.updatedAt = now; this.persist()
268
+ const body = action.body.trim(); if (body === '') throw new Error('reply is required')
269
+ const mentions = validMentions(action.mentions, this.state.participants)
270
+ comment.replies.push({ id: randomUUID(), author: action.participant, body, mentions, createdAt: now }); comment.updatedAt = now
271
+ if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, 'reply', record, 'comment', comment.id, `${action.participant.nickname} 回复了你的评论`)
272
+ for (const participantId of mentions) this.notify(participantId, 'mention', record, 'comment', comment.id, `${action.participant.nickname} 在回复中提到了你`)
273
+ this.persist()
210
274
  } else if (action.kind === 'comment.resolve') {
211
275
  requireHuman(action.participant)
212
276
  const comment = this.comment(record, action.commentId)
213
277
  comment.status = 'resolved'; comment.resolution = action.resolution; comment.updatedAt = now
278
+ if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, 'status-change', record, 'comment', comment.id, `${action.participant.nickname} 已解决你的评论`)
214
279
  record.actionItems.filter(task => task.sourceId === comment.id && task.status === 'pending').forEach(task => { task.status = 'handled'; task.updatedAt = now }); this.persist()
280
+ } else if (action.kind === 'comment.reopen') {
281
+ requireHuman(action.participant)
282
+ const comment = this.comment(record, action.commentId)
283
+ if (comment.status !== 'resolved') throw new Error('resolved comment not found')
284
+ comment.status = 'open'; delete comment.resolution; comment.updatedAt = now
285
+ record.actionItems.push({ id: randomUUID(), requirementId: record.id, sourceType: 'comment', sourceId: comment.id, type: 'reply', assigneeRole: comment.author.role === 'product' ? 'engineering' : 'product', blocking: false, status: 'pending', dueStage: record.stage, createdAt: now, updatedAt: now })
286
+ if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, 'status-change', record, 'comment', comment.id, `${action.participant.nickname} 重新打开了你的评论`)
287
+ this.persist()
215
288
  } else if (action.kind === 'patch.accept') {
216
289
  requireHuman(action.participant)
217
290
  const patch = record.patches.find(item => item.id === action.patchId)
@@ -219,10 +292,12 @@ export class CollaborationEngine {
219
292
  const version = this.versions.save({ requirementId: record.id, baseCommit: patch.baseCommit, markdown: patch.proposedMarkdown, participant: action.participant, summary: action.summary })
220
293
  const before = this.versions.read(record.id, record.currentCommit).markdown
221
294
  const impact = changedScopes(before, patch.proposedMarkdown)
222
- record.currentCommit = version.commit; patch.status = 'accepted'; record.updatedAt = now
295
+ record.currentCommit = version.commit; patch.status = 'accepted'; record.updatedAt = now; delete record.readyPackage
296
+ record.patches.filter(item => item.id !== patch.id && item.status === 'pending').forEach(item => { item.status = 'stale' })
297
+ if (record.stage === 'ready') enterStage(record, 'joint-review')
223
298
  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
299
  invalidateAffected(record, impact.sections, impact.acceptanceIds, patch.proposedMarkdown)
225
- record.actionItems.filter(task => task.sourceId === patch.id && task.status === 'pending').forEach(task => { task.status = 'handled'; task.updatedAt = now }); this.persist()
300
+ record.actionItems.filter(task => task.sourceId === patch.id && task.status === 'pending').forEach(task => { task.status = 'handled'; task.updatedAt = now }); this.persist(undefined, true)
226
301
  this.enqueueReview(record, action.participant, 'change-review')
227
302
  } else if (action.kind === 'patch.reject') {
228
303
  requireHuman(action.participant)
@@ -249,7 +324,79 @@ export class CollaborationEngine {
249
324
  if (!hasVersionConfirmation(record, 'product') || !hasVersionConfirmation(record, 'engineering')) throw new Error('current version needs product and engineering confirmation')
250
325
  const markdown = readyMarkdown(this.view(record.id))
251
326
  record.readyPackage = { requirementId: record.id, commit: record.currentCommit, packageHash: createHash('sha256').update(markdown).digest('hex'), generatedAt: now, generatedBy: action.participant, markdown }
252
- record.stage = 'ready'; this.persist()
327
+ enterStage(record, 'ready'); this.persist()
328
+ } else if (action.kind === 'participant.register') {
329
+ requireHuman(action.participant)
330
+ const participant = this.state.participants.find(item => item.participantId === action.participant.participantId)
331
+ if (participant !== undefined) { participant.nickname = action.participant.nickname; participant.role = action.participant.role; this.persist() }
332
+ } else if (action.kind === 'action.assign') {
333
+ requireHuman(action.participant)
334
+ const task = record.actionItems.find(item => item.id === action.actionItemId)
335
+ if (task === undefined) throw new Error('action item not found')
336
+ if (action.assigneeParticipantId !== undefined && !this.state.participants.some(item => item.participantId === action.assigneeParticipantId && item.role === action.assigneeRole)) throw new Error('assignee is not a registered participant with the selected role')
337
+ task.assigneeRole = action.assigneeRole
338
+ if (action.dueStage !== undefined) task.dueStage = action.dueStage
339
+ if (action.assigneeParticipantId === undefined) delete task.assigneeParticipantId
340
+ else { task.assigneeParticipantId = action.assigneeParticipantId; this.notify(action.assigneeParticipantId, 'assignment', record, 'action', task.id, `${action.participant.nickname} 向你指派了一个待办`) }
341
+ task.updatedAt = now; this.persist()
342
+ } else if (action.kind === 'notification.mark-read') {
343
+ requireHuman(action.participant)
344
+ const ids = new Set(action.notificationIds)
345
+ this.state.notifications.filter(item => item.recipientParticipantId === action.participant.participantId && item.requirementId === record.id && ids.has(item.id)).forEach(item => { item.readAt ??= now })
346
+ this.persist()
347
+ } else if (action.kind === 'source.upsert') {
348
+ requireHuman(action.participant)
349
+ const input = cleanSource(action.source); const existing = this.state.feedbackSources.find(item => item.id === input.id)
350
+ const source: FeedbackSource = { ...input, createdAt: existing?.createdAt ?? now, updatedAt: now }
351
+ validateSource(source)
352
+ if (existing === undefined) this.state.feedbackSources.push(source); else Object.assign(existing, source)
353
+ this.persist()
354
+ } else if (action.kind === 'company.upsert') {
355
+ requireHuman(action.participant)
356
+ const input = cleanCompany(action.company); validateCompany(input)
357
+ const existing = this.state.companies.find(item => item.id === input.id); const company = { ...input, createdAt: existing?.createdAt ?? now, updatedAt: now }
358
+ if (existing === undefined) this.state.companies.push(company); else Object.assign(existing, company)
359
+ this.persist()
360
+ } else if (action.kind === 'customer.upsert') {
361
+ requireHuman(action.participant)
362
+ const input = cleanCustomer(action.customer); validateCustomer(input, this.state)
363
+ const existing = this.state.customers.find(item => item.id === input.id); const customer = { ...input, createdAt: existing?.createdAt ?? now, updatedAt: now }
364
+ if (existing === undefined) this.state.customers.push(customer); else Object.assign(existing, customer)
365
+ this.persist()
366
+ } else if (action.kind === 'insight.create') {
367
+ requireHuman(action.participant); const insight = this.createInsight(record.id, action.insight, action.participant, now)
368
+ for (const link of action.links ?? []) this.addInsightLink(insight.id, link, action.participant, now)
369
+ this.persist()
370
+ } else if (action.kind === 'insight.update') {
371
+ requireHuman(action.participant)
372
+ const insight = this.state.insights.find(item => item.id === action.insightId); if (insight === undefined) throw new Error('insight not found')
373
+ Object.assign(insight, action.changes); validateInsight(insight, this.state); insight.dedupeHash = insightHash(insight.sourceId, insight.body); insight.updatedAt = now; this.persist()
374
+ } else if (action.kind === 'insight.delete') {
375
+ requireHuman(action.participant)
376
+ const index = this.state.insights.findIndex(item => item.id === action.insightId); if (index < 0) throw new Error('insight not found')
377
+ this.state.insights.splice(index, 1); this.state.insightLinks = this.state.insightLinks.filter(item => item.insightId !== action.insightId); this.persist()
378
+ } else if (action.kind === 'insight.link') {
379
+ requireHuman(action.participant)
380
+ this.addInsightLink(action.insightId, action.link, action.participant, now)
381
+ this.persist()
382
+ } else if (action.kind === 'insight.unlink') {
383
+ requireHuman(action.participant)
384
+ const link = this.state.insightLinks.find(item => item.id === action.linkId); if (link === undefined) throw new Error('insight link not found')
385
+ this.state.insightLinks = this.state.insightLinks.filter(item => item.id !== action.linkId); this.persist()
386
+ } else if (action.kind === 'insight.import') {
387
+ requireHuman(action.participant)
388
+ if (action.rows.length > 2_000 || Buffer.byteLength(JSON.stringify(action.rows), 'utf8') > 5 * 1024 * 1024) throw new Error('insight import exceeds 2,000 rows or 5 MB')
389
+ const before = structuredClone(this.state)
390
+ try {
391
+ for (const row of [...(action.source ? [action.source] : []), ...(action.sources ?? [])]) { const source = { ...cleanSource(row), createdAt: now, updatedAt: now }; validateSource(source); const existing = this.state.feedbackSources.find(item => item.id === source.id); if (existing) Object.assign(existing, source, { createdAt: existing.createdAt }); else this.state.feedbackSources.push(source) }
392
+ for (const row of action.companies ?? []) { const company = cleanCompany(row); validateCompany(company); const existing = this.state.companies.find(item => item.id === company.id); if (existing) Object.assign(existing, company, { createdAt: existing.createdAt, updatedAt: now }); else this.state.companies.push({ ...company, createdAt: now, updatedAt: now }) }
393
+ for (const row of action.customers ?? []) { const customer = cleanCustomer(row); validateCustomer(customer, this.state); const existing = this.state.customers.find(item => item.id === customer.id); if (existing) Object.assign(existing, customer, { createdAt: existing.createdAt, updatedAt: now }); else this.state.customers.push({ ...customer, createdAt: now, updatedAt: now }) }
394
+ const actualIds = new Map<string, string>()
395
+ for (const row of action.rows) actualIds.set(row.id, this.createInsight(record.id, row, action.participant, now).id)
396
+ for (const link of action.links ?? []) this.addInsightLink(actualIds.get(link.insightId) ?? link.insightId, link, action.participant, now)
397
+ }
398
+ catch (error) { this.state = before; throw error }
399
+ this.persist()
253
400
  } else if (action.kind === 'downstream.return') {
254
401
  requireHuman(action.participant)
255
402
  if (action.summary.trim() === '') throw new Error('downstream issue summary is required')
@@ -264,12 +411,42 @@ export class CollaborationEngine {
264
411
  record.actionItems.push(actionForReview(item))
265
412
  invalidateAffected(record, item.affectedSections, item.affectedAcceptanceIds)
266
413
  delete record.readyPackage
267
- record.stage = 'joint-review'; record.updatedAt = now; this.persist()
414
+ enterStage(record, 'joint-review'); record.updatedAt = now; this.persist()
268
415
  this.enqueueReview(record, action.participant, 'change-review')
269
416
  }
270
417
  return { ok: true, revision: this.state.revision, requirement: this.view(record.id) }
271
418
  }
272
419
 
420
+ private createInsight(requirementId: string, input: Omit<Insight, 'dedupeHash' | 'createdBy' | 'createdAt' | 'updatedAt'>, participant: ParticipantSnapshot, now: number): Insight {
421
+ const draft: Insight = { ...input, title: input.title.trim(), body: input.body.trim(), dedupeHash: insightHash(input.sourceId, input.body), createdBy: participant, createdAt: now, updatedAt: now }
422
+ validateInsight(draft, this.state)
423
+ const existing = this.state.insights.find(item => item.dedupeHash === draft.dedupeHash)
424
+ const insight = existing ?? draft
425
+ if (existing === undefined) this.state.insights.push(insight)
426
+ if (!this.state.insightLinks.some(item => item.insightId === insight.id && item.requirementId === requirementId && item.targetType === 'requirement')) this.state.insightLinks.push({ id: randomUUID(), insightId: insight.id, requirementId, targetType: 'requirement', createdBy: participant, createdAt: now })
427
+ return insight
428
+ }
429
+
430
+ private addInsightLink(insightId: string, link: Pick<InsightLink, 'requirementId' | 'targetType' | 'targetId'>, participant: ParticipantSnapshot, now: number): void {
431
+ if (!this.state.insights.some(item => item.id === insightId)) throw new Error('insight not found')
432
+ this.record(link.requirementId)
433
+ if (!['requirement', 'section', 'acceptance-criterion'].includes(link.targetType)) throw new Error('invalid insight link target type')
434
+ if (link.targetType !== 'requirement' && !link.targetId?.trim()) throw new Error('linked section or acceptance criterion id is required')
435
+ const duplicate = this.state.insightLinks.some(item => item.insightId === insightId && item.requirementId === link.requirementId && item.targetType === link.targetType && item.targetId === link.targetId)
436
+ if (!duplicate) this.state.insightLinks.push({ id: randomUUID(), insightId, ...link, createdBy: participant, createdAt: now })
437
+ }
438
+
439
+ private rememberStageConversation(record: RequirementRecord, sessionId: string, stage = record.stage, stageCycle = record.stageCycle): void {
440
+ const now = Date.now(); const existing = record.aiConversations.find(item => item.stage === stage && item.stageCycle === stageCycle)
441
+ if (existing) { existing.sessionId = sessionId; existing.updatedAt = now } else record.aiConversations.push({ stage, stageCycle, sessionId, createdAt: now, updatedAt: now })
442
+ }
443
+
444
+ private notify(recipientParticipantId: string, kind: Notification['kind'], record: RequirementRecord, objectType: Notification['objectType'], objectId: string, message: string): void {
445
+ if (!this.state.participants.some(item => item.participantId === recipientParticipantId)) return
446
+ const deepLink = `#spec-collab/${encodeURIComponent(record.id)}/${objectType === 'comment' ? 'discussion' : 'tasks'}/${encodeURIComponent(objectId)}?commit=${encodeURIComponent(record.currentCommit)}`
447
+ this.state.notifications.push({ id: randomUUID(), recipientParticipantId, kind, requirementId: record.id, objectType, objectId, message, deepLink, createdAt: Date.now() })
448
+ }
449
+
273
450
  private saveConflict(action: Extract<CollaborationAction, { kind: 'version.save' }>): SaveConflict {
274
451
  const record = this.record(action.requirementId)
275
452
  const baseMarkdown = this.versions.read(record.id, action.baseCommit).markdown
@@ -281,19 +458,221 @@ export class CollaborationEngine {
281
458
  const now = Date.now()
282
459
  const run: AiReviewRun = { id: randomUUID(), requirementId: record.id, commit: record.currentCommit, kind, status: 'queued', requestedBy: participant, createdAt: now, updatedAt: now }
283
460
  record.aiRuns.push(run)
284
- this.persist()
461
+ this.persist({ types: ['ai.status', 'metrics.changed'], requirementId: record.id, objectId: run.id })
285
462
  const coordinator = this.coordinator
286
463
  if (coordinator === undefined) { this.markAiFailure(record.id, run.id, 'AI coordinator unavailable'); return }
287
464
  const view = this.view(record.id)
288
- void coordinator.requestReview({ requirement: view, run }).then(sessionId => {
289
- run.status = 'running'; run.sessionId = sessionId; run.updatedAt = Date.now(); this.persist()
465
+ const requestedStage = record.stage; const requestedStageCycle = record.stageCycle
466
+ const existingSession = record.aiConversations.find(item => item.stage === requestedStage && item.stageCycle === requestedStageCycle)?.sessionId
467
+ void coordinator.requestReview({ requirement: view, run, ...(existingSession ? { sessionId: existingSession } : {}) }).then(sessionId => {
468
+ run.status = 'running'; run.sessionId = sessionId; run.updatedAt = Date.now(); this.rememberStageConversation(record, sessionId, requestedStage, requestedStageCycle); this.persist({ types: ['ai.status', 'metrics.changed'], requirementId: record.id, objectId: run.id })
290
469
  }, error => this.markAiFailure(record.id, run.id, error instanceof Error ? error.message : String(error)))
291
470
  }
292
471
 
293
472
  private record(id: string): RequirementRecord { const value = this.state.requirements.find(item => item.id === id); if (value === undefined) throw new Error('requirement not found'); return value }
294
473
  private comment(record: RequirementRecord, id: string): CommentThread { const value = record.comments.find(item => item.id === id); if (value === undefined) throw new Error('comment not found'); return value }
295
- private persist(): void { this.state.revision += 1; mkdirSync(dirname(this.eventPath), { recursive: true, mode: 0o700 }); const tmp = `${this.eventPath}.tmp`; writeFileSync(tmp, JSON.stringify(this.state, null, 2), { mode: 0o600 }); renameSync(tmp, this.eventPath); for (const listener of this.listeners) listener() }
296
- private load(): CollaborationState { try { const value = JSON.parse(readFileSync(this.eventPath, 'utf8')) as CollaborationState; if (value.schemaVersion === SCHEMA_VERSION) { value.participants ??= []; return value } } catch {} return emptyState() }
474
+ private persist(event = this.eventContext ?? { types: ['metrics.changed'] as const }, recoverable = false): void {
475
+ this.state.revision += 1
476
+ const pendingPath = `${this.eventPath}.pending`
477
+ if (recoverable) atomicWrite(pendingPath, this.state, true)
478
+ atomicWrite(this.eventPath, this.state, recoverable)
479
+ if (recoverable && existsSync(pendingPath)) unlinkSync(pendingPath)
480
+ const payload: CollaborationEvent = { ...event, types: [...event.types], revision: this.state.revision }
481
+ for (const listener of this.listeners) listener(payload)
482
+ }
483
+ private load(): CollaborationState {
484
+ const pendingPath = `${this.eventPath}.pending`
485
+ if (existsSync(pendingPath)) {
486
+ let pending: unknown
487
+ try { pending = JSON.parse(readFileSync(pendingPath, 'utf8')); validateV3Ledger(pending); atomicWrite(this.eventPath, pending, true); unlinkSync(pendingPath); return normalizeV3(pending) }
488
+ catch (error) { throw new Error(`pending collaboration transaction is corrupted: ${error instanceof Error ? error.message : String(error)}`) }
489
+ }
490
+ const sourcePath = existsSync(this.eventPath) ? this.eventPath : this.options.legacyPath !== undefined && existsSync(this.options.legacyPath) ? this.options.legacyPath : undefined
491
+ if (sourcePath === undefined) return emptyState()
492
+ let parsed: unknown
493
+ try { parsed = JSON.parse(readFileSync(sourcePath, 'utf8')) }
494
+ catch (error) { throw new Error(`collaboration ledger is corrupted: ${error instanceof Error ? error.message : String(error)}`) }
495
+ if (typeof parsed !== 'object' || parsed === null || typeof (parsed as { schemaVersion?: unknown }).schemaVersion !== 'number') throw new Error('collaboration ledger has no schema version')
496
+ const version = (parsed as { schemaVersion: number }).schemaVersion
497
+ if (version === SCHEMA_VERSION) { validateV3Ledger(parsed); return normalizeV3(parsed as CollaborationState) }
498
+ if (version !== 2) throw new Error(`unsupported collaboration schema: ${version}`)
499
+ validateV2Ledger(parsed)
500
+ const migrated = migrateV2(parsed as Record<string, unknown>)
501
+ const extension = extname(sourcePath); const stem = basename(sourcePath, extension).replace(/-v2$/, '')
502
+ const backupPath = join(dirname(sourcePath), `${stem}-v2.backup-${Date.now()}${extension || '.json'}`)
503
+ copyFileSync(sourcePath, backupPath)
504
+ atomicWrite(this.eventPath, migrated, true)
505
+ return migrated
506
+ }
507
+ }
508
+
509
+ function eventForAction(action: CollaborationAction): Omit<CollaborationEvent, 'revision'> {
510
+ const types = new Set<CollaborationEvent['types'][number]>(['metrics.changed'])
511
+ if (action.kind.startsWith('comment.')) types.add('comment.changed')
512
+ if (action.kind === 'comment.create' || action.kind === 'comment.reply') {
513
+ if ((action.mentions?.length ?? 0) > 0) types.add('mention.created')
514
+ types.add('notification.changed')
515
+ }
516
+ if (action.kind === 'comment.resolve' || action.kind === 'comment.reopen') types.add('notification.changed')
517
+ if (action.kind === 'action.assign') { types.add('assignment.changed'); types.add('notification.changed') }
518
+ if (action.kind === 'notification.mark-read') types.add('notification.changed')
519
+ if (action.kind === 'review.request') types.add('ai.status')
520
+ const requirementId = 'requirementId' in action ? action.requirementId : undefined
521
+ return { types: [...types], ...(requirementId ? { requirementId } : {}) }
522
+ }
523
+
524
+ function isRecord(value: unknown): value is Record<string, unknown> { return typeof value === 'object' && value !== null && !Array.isArray(value) }
525
+ function validateV2Ledger(value: unknown): asserts value is Record<string, unknown> {
526
+ if (!isRecord(value) || !Array.isArray(value.requirements) || (value.participants !== undefined && !Array.isArray(value.participants))) throw new Error('invalid collaboration v2 ledger: requirements and participants must be arrays')
527
+ }
528
+ function validateV3Ledger(value: unknown): asserts value is CollaborationState {
529
+ if (!isRecord(value)) throw new Error('invalid collaboration v3 ledger: object required')
530
+ const arrays = ['participants', 'requirements', 'companies', 'customers', 'feedbackSources', 'insights', 'insightLinks', 'notifications'] as const
531
+ if (!Number.isFinite(value.revision) || arrays.some(key => !Array.isArray(value[key]))) throw new Error('invalid collaboration v3 ledger: required collections are missing or invalid')
532
+ for (const candidate of value.requirements as unknown[]) {
533
+ if (!isRecord(candidate) || typeof candidate.id !== 'string' || typeof candidate.title !== 'string' || typeof candidate.currentCommit !== 'string' || !['product-review', 'product-confirmation', 'joint-review', 'ready'].includes(String(candidate.stage))) throw new Error('invalid collaboration v3 ledger: malformed requirement')
534
+ const recordArrays = ['sources', 'reviewItems', 'comments', 'patches', 'decisions', 'confirmations', 'actionItems', 'aiRuns'] as const
535
+ if (recordArrays.some(key => !Array.isArray(candidate[key])) || (candidate.aiConversations !== undefined && !Array.isArray(candidate.aiConversations))) throw new Error('invalid collaboration v3 ledger: malformed requirement collections')
536
+ }
537
+ }
538
+
539
+ function atomicWrite(path: string, value: unknown, durable = false): void {
540
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
541
+ const tmp = `${path}.tmp`
542
+ writeFileSync(tmp, JSON.stringify(value, null, 2), { mode: 0o600 })
543
+ if (durable) {
544
+ const descriptor = openSync(tmp, 'r')
545
+ try { fsyncSync(descriptor) } finally { closeSync(descriptor) }
546
+ }
547
+ renameSync(tmp, path)
548
+ }
549
+
550
+ function normalizeV3(value: CollaborationState): CollaborationState {
551
+ value.participants ??= []
552
+ value.requirements ??= []
553
+ value.companies ??= []
554
+ value.customers ??= []
555
+ value.feedbackSources ??= []
556
+ value.insights ??= []
557
+ value.insightLinks ??= []
558
+ value.notifications ??= []
559
+ for (const record of value.requirements) {
560
+ record.sources ??= []; record.reviewItems ??= []; record.comments ??= []; record.patches ??= []; record.decisions ??= []; record.confirmations ??= []; record.actionItems ??= []; record.aiRuns ??= []; record.aiConversations ??= []; record.stageCycle ??= 0
561
+ for (const conversation of record.aiConversations) conversation.stageCycle ??= record.stageCycle
562
+ if (record.aiConversations.length === 0 && (record.stage === 'product-review' || record.stage === 'joint-review')) {
563
+ const recent = [
564
+ ...record.aiRuns.filter(item => item.sessionId && (item.kind === 'change-review' || (record.stage === 'product-review' ? item.kind === 'product-first' || item.kind === 'product-second' : item.kind === 'engineering-precheck'))).map(item => ({ sessionId: item.sessionId!, createdAt: item.createdAt, updatedAt: item.updatedAt })),
565
+ ...record.comments.filter(item => item.aiSessionId).map(item => ({ sessionId: item.aiSessionId!, createdAt: item.createdAt, updatedAt: item.updatedAt })),
566
+ ].sort((left, right) => right.updatedAt - left.updatedAt)[0]
567
+ if (recent) record.aiConversations.push({ stage: record.stage, stageCycle: record.stageCycle, ...recent })
568
+ }
569
+ for (const comment of record.comments) {
570
+ comment.scope ??= comment.anchor === undefined ? 'page' : 'inline'
571
+ comment.mentions ??= []
572
+ comment.replies ??= []
573
+ for (const reply of comment.replies) reply.mentions ??= []
574
+ }
575
+ }
576
+ return value
577
+ }
578
+
579
+ function migrateV2(value: Record<string, unknown>): CollaborationState {
580
+ const legacyRequirements = Array.isArray(value.requirements) ? value.requirements as RequirementRecord[] : []
581
+ const requirements = structuredClone(legacyRequirements)
582
+ const feedbackSources: CollaborationState['feedbackSources'] = []
583
+ const insights: CollaborationState['insights'] = []
584
+ const insightLinks: CollaborationState['insightLinks'] = []
585
+ const migrationActor: ParticipantSnapshot = { participantId: 'migration-v2', nickname: '数据迁移', role: 'product', kind: 'ai', sessionId: 'migration-v2' }
586
+ for (const record of requirements) {
587
+ record.sources ??= []; record.reviewItems ??= []; record.comments ??= []; record.patches ??= []; record.decisions ??= []; record.confirmations ??= []; record.actionItems ??= []; record.aiRuns ??= []; record.aiConversations ??= []; record.stageCycle ??= 0
588
+ for (const conversation of record.aiConversations) conversation.stageCycle ??= record.stageCycle
589
+ for (const comment of record.comments) {
590
+ comment.scope = comment.anchor === undefined ? 'page' : 'inline'; comment.mentions = []; comment.replies ??= []
591
+ for (const reply of comment.replies) reply.mentions = []
592
+ }
593
+ for (const source of record.sources) {
594
+ const sourceId = `legacy-${createHash('sha256').update(`${record.id}:${source.id}`).digest('hex').slice(0, 16)}`
595
+ const insightId = `legacy-${createHash('sha256').update(`${record.id}:${source.id}:insight`).digest('hex').slice(0, 16)}`
596
+ feedbackSources.push({ id: sourceId, kind: source.sourceType === 'link' ? 'url' : source.sourceType === 'markdown' ? 'markdown' : 'text', label: source.label, ...(source.sourceType === 'link' && safeHttpUrl(source.stableId) ? { url: source.stableId } : {}), ...(source.stableId ? { externalRef: source.stableId } : {}), accessStatus: source.accessStatus, createdAt: record.createdAt, updatedAt: record.updatedAt })
597
+ insights.push({ id: insightId, sourceId, title: source.label, body: `历史来源:${source.label}`, importance: 'unknown', capturedAt: record.createdAt, dedupeHash: insightHash(sourceId, source.label), createdBy: migrationActor, createdAt: record.createdAt, updatedAt: record.updatedAt })
598
+ insightLinks.push({ id: randomUUID(), insightId, requirementId: record.id, targetType: 'requirement', createdBy: migrationActor, createdAt: record.createdAt })
599
+ }
600
+ }
601
+ return normalizeV3({ schemaVersion: SCHEMA_VERSION, revision: typeof value.revision === 'number' ? value.revision : 0, participants: Array.isArray(value.participants) ? value.participants as ParticipantSnapshot[] : [], requirements, companies: [], customers: [], feedbackSources, insights, insightLinks, notifications: [] })
602
+ }
603
+
604
+ function safeHttpUrl(value: string | undefined): boolean {
605
+ if (!value) return false
606
+ try { const url = new URL(value); return url.protocol === 'http:' || url.protocol === 'https:' } catch { return false }
607
+ }
608
+
609
+ function cleanSource(input: Omit<FeedbackSource, 'createdAt' | 'updatedAt'>): Omit<FeedbackSource, 'createdAt' | 'updatedAt'> {
610
+ return { id: input.id, kind: input.kind, label: input.label, ...(input.url === undefined ? {} : { url: input.url }), ...(input.externalRef === undefined ? {} : { externalRef: input.externalRef }), accessStatus: input.accessStatus }
611
+ }
612
+ function cleanCompany(input: { id: string; name: string; externalRef?: string }): { id: string; name: string; externalRef?: string } {
613
+ return { id: input.id, name: input.name, ...(input.externalRef === undefined ? {} : { externalRef: input.externalRef }) }
614
+ }
615
+ function cleanCustomer(input: { id: string; displayName: string; companyId?: string; externalRef?: string }): { id: string; displayName: string; companyId?: string; externalRef?: string } {
616
+ return { id: input.id, displayName: input.displayName, ...(input.companyId === undefined ? {} : { companyId: input.companyId }), ...(input.externalRef === undefined ? {} : { externalRef: input.externalRef }) }
617
+ }
618
+ function validateSource(source: Pick<FeedbackSource, 'id' | 'kind' | 'label' | 'url' | 'accessStatus'>): void {
619
+ if (!source.id.trim() || !source.label.trim() || !['text', 'url', 'csv', 'markdown'].includes(source.kind) || !['available', 'unverified', 'missing'].includes(source.accessStatus) || (source.kind === 'url' && !safeHttpUrl(source.url))) throw new Error('valid source id, label and http(s) URL are required')
620
+ }
621
+ function validateCompany(company: Pick<CollaborationState['companies'][number], 'id' | 'name'>): void {
622
+ if (!company.id.trim() || !company.name.trim()) throw new Error('company id and name are required')
623
+ }
624
+ function validateCustomer(customer: Pick<CollaborationState['customers'][number], 'id' | 'displayName' | 'companyId'>, state: CollaborationState): void {
625
+ if (!customer.id.trim() || !customer.displayName.trim()) throw new Error('customer id and display name are required')
626
+ if (customer.companyId !== undefined && !state.companies.some(item => item.id === customer.companyId)) throw new Error('company not found')
627
+ }
628
+
629
+ function validMentions(values: string[] | undefined, participants: ParticipantSnapshot[]): string[] {
630
+ const registered = new Set(participants.map(item => item.participantId))
631
+ return [...new Set(values ?? [])].filter(value => registered.has(value))
632
+ }
633
+
634
+ function insightHash(sourceId: string, body: string): string { return createHash('sha256').update(`${sourceId}\n${body.normalize('NFKC').trim().replace(/\s+/g, ' ').toLocaleLowerCase()}`).digest('hex') }
635
+ function validateInsight(insight: Insight, state: CollaborationState): void {
636
+ if (!insight.id.trim() || !insight.sourceId.trim() || !insight.body.trim()) throw new Error('insight id, source and body are required')
637
+ if (!state.feedbackSources.some(item => item.id === insight.sourceId)) throw new Error('feedback source not found')
638
+ if (insight.customerId !== undefined && !state.customers.some(item => item.id === insight.customerId)) throw new Error('customer not found')
639
+ if (insight.companyId !== undefined && !state.companies.some(item => item.id === insight.companyId)) throw new Error('company not found')
640
+ if (!['unknown', 'want', 'important', 'critical'].includes(insight.importance)) throw new Error('invalid insight importance')
641
+ }
642
+
643
+ function requirementMetrics(record: RequirementRecord, state: CollaborationState): RequirementMetrics {
644
+ const insightIds = new Set(state.insightLinks.filter(link => link.requirementId === record.id).map(link => link.insightId))
645
+ const insights = state.insights.filter(insight => insightIds.has(insight.id))
646
+ const customers = new Set<string>(); const companies = new Set<string>(); const entityScores = new Map<string, number>(); let anonymousInsightCount = 0
647
+ const weights: Record<InsightImportance, number> = { unknown: 1, want: 1, important: 2, critical: 3 }
648
+ for (const insight of insights) {
649
+ const customer = insight.customerId === undefined ? undefined : state.customers.find(item => item.id === insight.customerId)
650
+ const companyId = insight.companyId ?? customer?.companyId
651
+ if (insight.customerId !== undefined) customers.add(insight.customerId)
652
+ if (companyId !== undefined) companies.add(companyId)
653
+ const entity = insight.customerId !== undefined ? `customer:${insight.customerId}` : companyId !== undefined ? `company:${companyId}` : undefined
654
+ if (entity === undefined) anonymousInsightCount += 1
655
+ else entityScores.set(entity, Math.max(entityScores.get(entity) ?? 0, weights[insight.importance]))
656
+ }
657
+ return {
658
+ openReviewCount: record.reviewItems.filter(item => item.commit === record.currentCommit && !['resolved', 'invalidated'].includes(item.status)).length,
659
+ openCommentCount: record.comments.filter(item => item.commit === record.currentCommit && item.status === 'open').length,
660
+ pendingActionCount: record.actionItems.filter(item => item.status === 'pending').length,
661
+ activeDecisionCount: record.decisions.filter(item => item.status === 'active').length,
662
+ riskCount: record.reviewItems.filter(item => item.commit === record.currentCommit && ['blocking', 'major'].includes(item.severity) && !['resolved', 'invalidated'].includes(item.status)).length,
663
+ insightCount: insights.length, customerImportanceScore: [...entityScores.values()].reduce((sum, value) => sum + value, 0), customerCount: customers.size, companyCount: companies.size, anonymousInsightCount,
664
+ }
665
+ }
666
+
667
+ function requirementParticipantIds(record: RequirementRecord, history: Array<Omit<RequirementVersion, 'markdown'>>): string[] {
668
+ return [...new Set([
669
+ ...history.map(item => item.author.participantId),
670
+ ...record.reviewItems.flatMap(item => item.response ? [item.response.participant.participantId] : []),
671
+ ...record.comments.flatMap(item => [item.author.participantId, ...item.replies.map(reply => reply.author.participantId)]),
672
+ ...record.decisions.map(item => item.confirmer.participantId),
673
+ ...record.confirmations.map(item => item.participant.participantId),
674
+ ...record.actionItems.flatMap(item => item.assigneeParticipantId ? [item.assigneeParticipantId] : []),
675
+ ])]
297
676
  }
298
677
 
299
678
  function sourceParticipantId(record: RequirementRecord, item: ActionItem): string | undefined {
@@ -307,6 +686,20 @@ function actionTarget(item: ActionItem): MyActionItem['target'] {
307
686
  const tabs = { 'review-item': 'review', comment: 'discussion', patch: 'patches', decision: 'decisions', confirmation: 'ready' } as const
308
687
  return { tab: tabs[item.sourceType], objectId: item.sourceId }
309
688
  }
689
+ function actionObjectTitle(record: RequirementRecord, item: ActionItem): string {
690
+ if (item.sourceType === 'review-item') {
691
+ const review = record.reviewItems.find(value => value.id === item.sourceId)
692
+ return review?.question.trim() || review?.statement.trim() || '待处理问题'
693
+ }
694
+ if (item.sourceType === 'comment') {
695
+ const comment = record.comments.find(value => value.id === item.sourceId)
696
+ return comment?.anchor?.quote.trim() || comment?.body.trim() || '待回复评论'
697
+ }
698
+ if (item.sourceType === 'patch') return record.patches.find(value => value.id === item.sourceId)?.summary.trim() || '待审核正文改动'
699
+ if (item.sourceType === 'decision') return record.decisions.find(value => value.id === item.sourceId)?.question.trim() || '待确认决策'
700
+ const confirmation = record.confirmations.find(value => value.id === item.sourceId)
701
+ return confirmation ? `${confirmation.role === 'product' ? '产品' : '研发'}需要重新确认当前版本` : '待确认当前版本'
702
+ }
310
703
  function textDiff(before: string, after: string): string {
311
704
  if (before === after) return ''
312
705
  const left = before.split('\n'); const right = after.split('\n')
@@ -323,15 +716,20 @@ function assertChineseFeedback(...values: string[]): void {
323
716
  function requireHuman(participant: ParticipantSnapshot): void { if (participant.kind !== 'human') throw new Error('human participant is required') }
324
717
  function actionForReview(item: ReviewItem): ActionItem { const now = Date.now(); return { id: randomUUID(), requirementId: item.requirementId, sourceType: 'review-item', sourceId: item.id, type: 'reply', assigneeRole: item.ownerRole, blocking: item.severity === 'blocking', status: 'pending', dueStage: item.reviewKind.startsWith('product') ? 'product-review' : 'joint-review', createdAt: now, updatedAt: now } }
325
718
  function hasVersionConfirmation(record: RequirementRecord, role: 'product' | 'engineering'): boolean { return record.confirmations.some(item => item.role === role && item.scope === 'version' && item.commit === record.currentCommit && item.status === 'active') }
719
+ function enterStage(record: RequirementRecord, stage: RequirementRecord['stage']): void {
720
+ if (record.stage === stage) return
721
+ record.stage = stage
722
+ record.stageCycle += 1
723
+ }
326
724
  function advance(record: RequirementRecord, participant: ParticipantSnapshot): void {
327
725
  if (record.stage === 'product-review') {
328
726
  if (record.reviewItems.some(item => item.commit === record.currentCommit && item.severity === 'blocking' && !['resolved', 'non-blocking-verify', 'joint-review'].includes(item.status))) throw new Error('product blocking review items remain')
329
727
  if (!record.aiRuns.some(run => run.kind === 'product-second' && run.commit === record.currentCommit && run.status === 'completed')) throw new Error('product second review is required')
330
- record.stage = 'product-confirmation'; return
728
+ enterStage(record, 'product-confirmation'); return
331
729
  }
332
730
  if (record.stage === 'product-confirmation') {
333
731
  if (participant.role !== 'product' || !hasVersionConfirmation(record, 'product')) throw new Error('product must confirm the current version')
334
- record.stage = 'joint-review'; return
732
+ enterStage(record, 'joint-review'); return
335
733
  }
336
734
  throw new Error('stage cannot advance directly')
337
735
  }