dsh-spec-collab 0.2.2 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/README.md +84 -18
- package/docs/assets/demo-01-workspace.png +0 -0
- package/docs/assets/demo-02-ai-review.png +0 -0
- package/docs/assets/demo-03-patches.png +0 -0
- package/docs/assets/demo-04-decisions.png +0 -0
- package/docs/assets/demo-05-ready.png +0 -0
- package/docs/experience-review-checklist-2026-08-24.md +72 -45
- package/docs/insight-import-template.csv +3 -0
- package/docs/insight-import-template.md +19 -0
- package/docs/migration-v3.md +23 -0
- package/docs/usage-walkthrough.md +25 -43
- package/lib/client.js +10854 -1168
- package/lib/index.js +1313 -98
- package/lib/types/client/AccessibleDialog.d.ts +9 -0
- package/lib/types/client/AccessibleDialog.d.ts.map +1 -0
- package/lib/types/client/SpecWorkbench.d.ts +42 -2
- package/lib/types/client/SpecWorkbench.d.ts.map +1 -1
- package/lib/types/client/api.d.ts +26 -3
- package/lib/types/client/api.d.ts.map +1 -1
- package/lib/types/client/drafts.d.ts +8 -0
- package/lib/types/client/drafts.d.ts.map +1 -0
- package/lib/types/client/mount.d.ts.map +1 -1
- package/lib/types/client/review-anchors.d.ts.map +1 -1
- package/lib/types/client/workflow.d.ts.map +1 -1
- package/lib/types/engine.d.ts +37 -3
- package/lib/types/engine.d.ts.map +1 -1
- package/lib/types/git-store.d.ts +6 -0
- package/lib/types/git-store.d.ts.map +1 -1
- package/lib/types/protocol.d.ts +245 -10
- package/lib/types/protocol.d.ts.map +1 -1
- package/lib/types/ready-admission.d.ts +14 -0
- package/lib/types/ready-admission.d.ts.map +1 -0
- package/lib/types/review-runtime.d.ts +6 -0
- package/lib/types/review-runtime.d.ts.map +1 -1
- package/lib/types/routes.d.ts.map +1 -1
- package/lib/types/structured-diff.d.ts +3 -0
- package/lib/types/structured-diff.d.ts.map +1 -0
- package/package.json +14 -4
- package/src/client/AccessibleDialog.tsx +42 -0
- package/src/client/SpecWorkbench.tsx +776 -87
- package/src/client/api.ts +8 -3
- package/src/client/drafts.ts +51 -0
- package/src/client/mount.tsx +11 -6
- package/src/client/review-anchors.ts +1 -0
- package/src/client/workbench.module.css +223 -79
- package/src/client/workflow.ts +8 -9
- package/src/engine.ts +448 -46
- package/src/git-store.ts +87 -18
- package/src/index.ts +1 -1
- package/src/protocol.ts +64 -13
- package/src/ready-admission.ts +29 -0
- package/src/review-runtime.ts +39 -11
- package/src/routes.ts +33 -4
- package/src/structured-diff.ts +75 -0
- package/src/tools.ts +1 -1
- package/docs/assets/spec-collab-walkthrough.mp4 +0 -0
package/src/engine.ts
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
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'
|
|
7
|
+
import { hasCompletedCurrentReview, hasVersionConfirmation, readyAdmission } from './ready-admission.ts'
|
|
6
8
|
|
|
7
9
|
export interface AiCoordinator {
|
|
8
|
-
requestReview(input: { requirement: RequirementView; run: AiReviewRun }): Promise<string>
|
|
9
|
-
requestCommentReply(input: { requirement: RequirementView; comment: CommentThread }): Promise<string>
|
|
10
|
+
requestReview(input: { requirement: RequirementView; run: AiReviewRun; sessionId?: string }): Promise<string>
|
|
11
|
+
requestCommentReply(input: { requirement: RequirementView; comment: CommentThread; sessionId?: string }): Promise<string>
|
|
10
12
|
}
|
|
11
13
|
|
|
12
|
-
const emptyState = (): CollaborationState => ({ schemaVersion: SCHEMA_VERSION, revision: 0, participants: [], requirements: [] })
|
|
14
|
+
const emptyState = (): CollaborationState => ({ schemaVersion: SCHEMA_VERSION, revision: 0, participants: [], requirements: [], companies: [], customers: [], feedbackSources: [], insights: [], insightLinks: [], notifications: [] })
|
|
13
15
|
|
|
14
16
|
type EngineResult = ActionResult
|
|
15
17
|
type DecisionSourceAnchor = NonNullable<Extract<CollaborationAction, { kind: 'decision.create' }>['sourceAnchors']>[number]
|
|
@@ -17,19 +19,53 @@ type DecisionSourceAnchor = NonNullable<Extract<CollaborationAction, { kind: 'de
|
|
|
17
19
|
export class CollaborationEngine {
|
|
18
20
|
private state: CollaborationState
|
|
19
21
|
private coordinator?: AiCoordinator
|
|
20
|
-
private readonly listeners = new Set<() => void>()
|
|
22
|
+
private readonly listeners = new Set<(event: CollaborationEvent) => void>()
|
|
21
23
|
private readonly seen = new Map<string, EngineResult>()
|
|
24
|
+
private eventContext: Omit<CollaborationEvent, 'revision'> | undefined
|
|
22
25
|
|
|
23
|
-
constructor(private readonly eventPath: string, private readonly versions: GitRequirementStore) { this.state = this.load() }
|
|
26
|
+
constructor(private readonly eventPath: string, private readonly versions: GitRequirementStore, private readonly options: { legacyPath?: string } = {}) { this.state = this.load() }
|
|
24
27
|
setCoordinator(coordinator: AiCoordinator): void { this.coordinator = coordinator }
|
|
25
28
|
snapshot(): CollaborationState { return structuredClone(this.state) }
|
|
26
|
-
|
|
29
|
+
directory(): ParticipantSnapshot[] { return structuredClone(this.state.participants).sort((left, right) => left.nickname.localeCompare(right.nickname, 'zh-CN')) }
|
|
30
|
+
notifications(participantId: string, page = 1, pageSize = 50): { items: Notification[]; total: number; unread: number } {
|
|
31
|
+
const rows = this.state.notifications.filter(item => item.recipientParticipantId === participantId).sort((left, right) => right.createdAt - left.createdAt)
|
|
32
|
+
const safePage = Number.isFinite(page) ? Math.max(1, Math.trunc(page)) : 1
|
|
33
|
+
const safePageSize = Number.isFinite(pageSize) ? Math.min(100, Math.max(1, Math.trunc(pageSize))) : 50
|
|
34
|
+
const start = (safePage - 1) * safePageSize
|
|
35
|
+
return { items: structuredClone(rows.slice(start, start + safePageSize)), total: rows.length, unread: rows.filter(item => item.readAt === undefined).length }
|
|
36
|
+
}
|
|
37
|
+
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'] } {
|
|
38
|
+
const linkedIds = query.requirementId === undefined ? undefined : new Set(this.state.insightLinks.filter(link => link.requirementId === query.requirementId).map(link => link.insightId))
|
|
39
|
+
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)
|
|
40
|
+
const pageSize = Math.min(100, Math.max(1, query.pageSize ?? 50)); const start = Math.max(0, (query.page ?? 1) - 1) * pageSize
|
|
41
|
+
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)
|
|
42
|
+
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))) }
|
|
43
|
+
}
|
|
44
|
+
subscribe(listener: (event: CollaborationEvent) => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener) }
|
|
27
45
|
list(): RequirementView[] { return this.state.requirements.map(item => this.view(item.id)) }
|
|
46
|
+
summaries(): RequirementSummary[] {
|
|
47
|
+
return this.state.requirements.map(record => ({
|
|
48
|
+
id: record.id,
|
|
49
|
+
title: record.title,
|
|
50
|
+
stage: record.stage,
|
|
51
|
+
currentCommit: record.currentCommit,
|
|
52
|
+
...(record.workspaceId ? { workspaceId: record.workspaceId } : {}),
|
|
53
|
+
...(record.archivedAt ? { archivedAt: record.archivedAt } : {}),
|
|
54
|
+
updatedAt: record.updatedAt,
|
|
55
|
+
metrics: requirementMetrics(record, this.state),
|
|
56
|
+
participantIds: requirementParticipantIds(record, this.versions.history(record.id)),
|
|
57
|
+
}))
|
|
58
|
+
}
|
|
28
59
|
version(requirementId: string, commit: string): RequirementVersion {
|
|
29
60
|
const record = this.record(requirementId)
|
|
30
61
|
if (!this.versions.history(record.id).some(version => version.commit === commit)) throw new Error('requirement version not found')
|
|
31
62
|
return this.versions.read(record.id, commit)
|
|
32
63
|
}
|
|
64
|
+
diff(requirementId: string, baseCommit: string, headCommit?: string): StructuredDiff {
|
|
65
|
+
const record = this.record(requirementId); const head = headCommit ?? record.currentCommit
|
|
66
|
+
const before = this.version(requirementId, baseCommit); const after = this.version(requirementId, head)
|
|
67
|
+
return buildStructuredDiff(before.markdown, after.markdown, baseCommit.slice(0, 10), head.slice(0, 10))
|
|
68
|
+
}
|
|
33
69
|
myItems(participant: ParticipantSnapshot, category?: MyItemCategory): MyActionItem[] {
|
|
34
70
|
const rows: MyActionItem[] = []
|
|
35
71
|
for (const record of this.state.requirements) {
|
|
@@ -38,7 +74,7 @@ export class CollaborationEngine {
|
|
|
38
74
|
const assigned = item.assigneeParticipantId === participant.participantId || (item.assigneeParticipantId === undefined && item.assigneeRole === participant.role)
|
|
39
75
|
if (assigned) categories.push(item.type === 'confirm' || item.type === 'reconfirm' ? 'awaiting-my-confirmation' : 'awaiting-my-response')
|
|
40
76
|
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) })
|
|
77
|
+
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
78
|
}
|
|
43
79
|
}
|
|
44
80
|
return rows.sort((left, right) => Number(right.blocking) - Number(left.blocking) || right.updatedAt - left.updatedAt)
|
|
@@ -50,13 +86,17 @@ export class CollaborationEngine {
|
|
|
50
86
|
view(id: string): RequirementView {
|
|
51
87
|
const record = this.record(id)
|
|
52
88
|
const version = this.versions.read(id, record.currentCommit)
|
|
53
|
-
|
|
89
|
+
const commitUrl = this.versions.commitUrl(record.currentCommit)
|
|
90
|
+
return { ...structuredClone(record), version, history: this.versions.history(id), readiness: readiness(version.markdown, record), metrics: requirementMetrics(record, this.state), ...(commitUrl ? { commitUrl } : {}) }
|
|
54
91
|
}
|
|
55
92
|
|
|
56
93
|
apply(requestId: string, action: CollaborationAction): EngineResult {
|
|
57
94
|
const cached = this.seen.get(requestId)
|
|
58
95
|
if (cached !== undefined) return structuredClone(cached)
|
|
59
96
|
let result: EngineResult
|
|
97
|
+
const beforeState = structuredClone(this.state)
|
|
98
|
+
const previousEventContext = this.eventContext
|
|
99
|
+
this.eventContext = eventForAction(action)
|
|
60
100
|
try {
|
|
61
101
|
const registered = action.participant.kind === 'human' ? this.state.participants.find(item => item.participantId === action.participant.participantId) : undefined
|
|
62
102
|
if (registered !== undefined && registered.role !== action.participant.role) throw new Error(`participant role is bound to ${registered.role}`)
|
|
@@ -65,13 +105,15 @@ export class CollaborationEngine {
|
|
|
65
105
|
this.state.participants.push(structuredClone(action.participant)); this.persist()
|
|
66
106
|
result = result.deletedRequirementId
|
|
67
107
|
? { ...result, revision: this.state.revision }
|
|
68
|
-
: { ok: true, revision: this.state.revision, requirement:
|
|
108
|
+
: { ok: true, revision: this.state.revision, requirement: result.requirement }
|
|
69
109
|
}
|
|
70
110
|
}
|
|
71
111
|
catch (error) {
|
|
112
|
+
this.state = beforeState
|
|
72
113
|
const conflict = error instanceof VersionConflictError && action.kind === 'version.save' ? this.saveConflict(action) : undefined
|
|
73
114
|
result = { ok: false, revision: this.state.revision, error: error instanceof Error ? error.message : String(error), ...(conflict === undefined ? {} : { conflict }) }
|
|
74
115
|
}
|
|
116
|
+
this.eventContext = previousEventContext
|
|
75
117
|
this.seen.set(requestId, result)
|
|
76
118
|
return structuredClone(result)
|
|
77
119
|
}
|
|
@@ -91,7 +133,7 @@ export class CollaborationEngine {
|
|
|
91
133
|
record.actionItems.push(actionForReview(created))
|
|
92
134
|
}
|
|
93
135
|
run.status = 'completed'; run.maturitySummary = input.maturitySummary; run.updatedAt = now
|
|
94
|
-
this.persist()
|
|
136
|
+
this.persist({ types: ['ai.status', 'metrics.changed'], requirementId: record.id, objectId: run.id })
|
|
95
137
|
}
|
|
96
138
|
|
|
97
139
|
submitPatch(input: { requirementId: string; baseCommit: string; reviewKind: ReviewKind; ai: ParticipantSnapshot; proposedMarkdown: string; summary: string; affectedReviewItemIds: string[]; affectedSections: string[]; affectedAcceptanceIds: string[] }): void {
|
|
@@ -101,16 +143,16 @@ export class CollaborationEngine {
|
|
|
101
143
|
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
144
|
record.patches.push(patch)
|
|
103
145
|
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()
|
|
146
|
+
this.persist({ types: ['ai.status', 'metrics.changed'], requirementId: record.id, objectId: patch.id })
|
|
105
147
|
}
|
|
106
148
|
|
|
107
149
|
submitAiReply(input: { requirementId: string; commentId: string; ai: ParticipantSnapshot; body: string }): void {
|
|
108
150
|
assertChineseFeedback(input.body)
|
|
109
151
|
const record = this.record(input.requirementId)
|
|
110
152
|
const comment = this.comment(record, input.commentId)
|
|
111
|
-
comment.replies.push({ id: randomUUID(), author: input.ai, body: input.body, createdAt: Date.now() })
|
|
153
|
+
comment.replies.push({ id: randomUUID(), author: input.ai, body: input.body, mentions: [], createdAt: Date.now() })
|
|
112
154
|
comment.aiStatus = 'completed'; comment.updatedAt = Date.now()
|
|
113
|
-
this.persist()
|
|
155
|
+
this.persist({ types: ['ai.status', 'comment.changed', 'metrics.changed'], requirementId: record.id, objectId: comment.id })
|
|
114
156
|
}
|
|
115
157
|
|
|
116
158
|
markAiFailure(requirementId: string, sourceId: string, error: string): void {
|
|
@@ -119,7 +161,7 @@ export class CollaborationEngine {
|
|
|
119
161
|
if (run !== undefined) { run.status = 'failed'; run.error = error; run.updatedAt = Date.now() }
|
|
120
162
|
const comment = record.comments.find(item => item.id === sourceId)
|
|
121
163
|
if (comment !== undefined) { comment.aiStatus = 'failed'; comment.updatedAt = Date.now() }
|
|
122
|
-
this.persist()
|
|
164
|
+
this.persist({ types: ['ai.status', 'metrics.changed'], requirementId, objectId: sourceId })
|
|
123
165
|
}
|
|
124
166
|
|
|
125
167
|
private applyFresh(action: CollaborationAction): EngineResult {
|
|
@@ -131,8 +173,8 @@ export class CollaborationEngine {
|
|
|
131
173
|
const workspaceId = action.workspaceId?.trim()
|
|
132
174
|
if (workspaceId === undefined || workspaceId === '') throw new Error('review workspace is required')
|
|
133
175
|
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()
|
|
176
|
+
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 }
|
|
177
|
+
this.state.requirements.unshift(record); this.persist(undefined, true)
|
|
136
178
|
this.enqueueReview(record, action.participant, 'product-first')
|
|
137
179
|
return { ok: true, revision: this.state.revision, requirement: this.view(record.id) }
|
|
138
180
|
}
|
|
@@ -152,10 +194,10 @@ export class CollaborationEngine {
|
|
|
152
194
|
const markdown = /^# .+$/m.test(before) ? before.replace(/^# .+$/m, `# ${title}`) : `# ${title}\n\n${before}`
|
|
153
195
|
const version = this.versions.save({ requirementId: record.id, baseCommit: record.currentCommit, markdown, participant: action.participant, summary: `Rename requirement: ${title}` })
|
|
154
196
|
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') {
|
|
197
|
+
invalidateAffected(record, [], []); this.persist(undefined, true); this.enqueueReview(record, action.participant, 'change-review')
|
|
198
|
+
} else if (action.kind === 'requirement.archive' || action.kind === 'requirement.unarchive') {
|
|
157
199
|
requireHuman(action.participant)
|
|
158
|
-
if (action.archived) record.archivedAt = now
|
|
200
|
+
if (action.kind === 'requirement.archive' && action.archived) record.archivedAt = now
|
|
159
201
|
else delete record.archivedAt
|
|
160
202
|
record.updatedAt = now; this.persist()
|
|
161
203
|
} else if (action.kind === 'requirement.delete') {
|
|
@@ -163,7 +205,8 @@ export class CollaborationEngine {
|
|
|
163
205
|
const deleted = this.view(record.id)
|
|
164
206
|
this.versions.remove(record.id, action.participant)
|
|
165
207
|
this.state.requirements.splice(this.state.requirements.indexOf(record), 1)
|
|
166
|
-
this.
|
|
208
|
+
this.state.insightLinks = this.state.insightLinks.filter(item => item.requirementId !== record.id)
|
|
209
|
+
this.persist(undefined, true)
|
|
167
210
|
return { ok: true, revision: this.state.revision, requirement: deleted, deletedRequirementId: record.id }
|
|
168
211
|
} else if (action.kind === 'version.save') {
|
|
169
212
|
requireHuman(action.participant)
|
|
@@ -173,9 +216,21 @@ export class CollaborationEngine {
|
|
|
173
216
|
record.currentCommit = version.commit; record.updatedAt = now; delete record.readyPackage
|
|
174
217
|
invalidateAffected(record, impact.sections, impact.acceptanceIds, action.markdown)
|
|
175
218
|
record.patches.filter(item => item.status === 'pending').forEach(item => { item.status = 'stale' })
|
|
176
|
-
if (record.stage === 'ready') record
|
|
177
|
-
this.persist()
|
|
219
|
+
if (record.stage === 'ready') enterStage(record, 'joint-review')
|
|
220
|
+
this.persist(undefined, true)
|
|
178
221
|
this.enqueueReview(record, action.participant, 'change-review')
|
|
222
|
+
} else if (action.kind === 'version.restore') {
|
|
223
|
+
requireHuman(action.participant)
|
|
224
|
+
const historical = this.version(record.id, action.commit)
|
|
225
|
+
if (historical.commit === record.currentCommit) throw new Error('selected version is already current')
|
|
226
|
+
const before = this.versions.read(record.id, record.currentCommit).markdown
|
|
227
|
+
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)}` })
|
|
228
|
+
const impact = changedScopes(before, historical.markdown)
|
|
229
|
+
record.currentCommit = version.commit; record.updatedAt = now; delete record.readyPackage
|
|
230
|
+
invalidateAffected(record, impact.sections, impact.acceptanceIds, historical.markdown)
|
|
231
|
+
record.patches.filter(item => item.status === 'pending').forEach(item => { item.status = 'stale' })
|
|
232
|
+
if (record.stage === 'ready') enterStage(record, 'joint-review')
|
|
233
|
+
this.persist(undefined, true); this.enqueueReview(record, action.participant, 'change-review')
|
|
179
234
|
} else if (action.kind === 'review.request') {
|
|
180
235
|
requireHuman(action.participant)
|
|
181
236
|
this.enqueueReview(record, action.participant, action.reviewKind)
|
|
@@ -191,27 +246,46 @@ export class CollaborationEngine {
|
|
|
191
246
|
} else if (action.kind === 'comment.create') {
|
|
192
247
|
requireHuman(action.participant)
|
|
193
248
|
if (action.commit !== record.currentCommit) throw new VersionConflictError(record.currentCommit)
|
|
194
|
-
const
|
|
195
|
-
|
|
249
|
+
const scope = action.scope ?? 'inline'; const mentions = validMentions(action.mentions, this.state.participants)
|
|
250
|
+
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 }
|
|
251
|
+
if (comment.body === '' || (scope === 'inline' && action.anchor?.quote.trim() === '')) throw new Error(scope === 'inline' ? 'comment and anchor are required' : 'comment is required')
|
|
252
|
+
if (scope === 'inline' && action.anchor === undefined) throw new Error('comment and anchor are required')
|
|
196
253
|
record.comments.push(comment)
|
|
197
254
|
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 })
|
|
255
|
+
for (const participantId of mentions) this.notify(participantId, 'mention', record, 'comment', comment.id, `${action.participant.nickname} 在评论中提到了你`)
|
|
198
256
|
this.persist()
|
|
199
257
|
const coordinator = this.coordinator
|
|
200
258
|
if (coordinator !== undefined) {
|
|
201
259
|
const view = this.view(record.id)
|
|
202
|
-
|
|
203
|
-
|
|
260
|
+
const requestedStage = record.stage; const requestedStageCycle = record.stageCycle
|
|
261
|
+
const existingSession = record.aiConversations.find(item => item.stage === requestedStage && item.stageCycle === requestedStageCycle)?.sessionId
|
|
262
|
+
void coordinator.requestCommentReply({ requirement: view, comment, ...(existingSession ? { sessionId: existingSession } : {}) }).then(sessionId => {
|
|
263
|
+
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
264
|
}, error => this.markAiFailure(record.id, comment.id, error instanceof Error ? error.message : String(error)))
|
|
205
265
|
}
|
|
206
266
|
} else if (action.kind === 'comment.reply') {
|
|
207
267
|
requireHuman(action.participant)
|
|
208
268
|
const comment = this.comment(record, action.commentId)
|
|
209
|
-
|
|
269
|
+
const body = action.body.trim(); if (body === '') throw new Error('reply is required')
|
|
270
|
+
const mentions = validMentions(action.mentions, this.state.participants)
|
|
271
|
+
comment.replies.push({ id: randomUUID(), author: action.participant, body, mentions, createdAt: now }); comment.updatedAt = now
|
|
272
|
+
if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, 'reply', record, 'comment', comment.id, `${action.participant.nickname} 回复了你的评论`)
|
|
273
|
+
for (const participantId of mentions) this.notify(participantId, 'mention', record, 'comment', comment.id, `${action.participant.nickname} 在回复中提到了你`)
|
|
274
|
+
this.persist()
|
|
210
275
|
} else if (action.kind === 'comment.resolve') {
|
|
211
276
|
requireHuman(action.participant)
|
|
212
277
|
const comment = this.comment(record, action.commentId)
|
|
213
278
|
comment.status = 'resolved'; comment.resolution = action.resolution; comment.updatedAt = now
|
|
279
|
+
if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, 'status-change', record, 'comment', comment.id, `${action.participant.nickname} 已解决你的评论`)
|
|
214
280
|
record.actionItems.filter(task => task.sourceId === comment.id && task.status === 'pending').forEach(task => { task.status = 'handled'; task.updatedAt = now }); this.persist()
|
|
281
|
+
} else if (action.kind === 'comment.reopen') {
|
|
282
|
+
requireHuman(action.participant)
|
|
283
|
+
const comment = this.comment(record, action.commentId)
|
|
284
|
+
if (comment.status !== 'resolved') throw new Error('resolved comment not found')
|
|
285
|
+
comment.status = 'open'; delete comment.resolution; comment.updatedAt = now
|
|
286
|
+
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 })
|
|
287
|
+
if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, 'status-change', record, 'comment', comment.id, `${action.participant.nickname} 重新打开了你的评论`)
|
|
288
|
+
this.persist()
|
|
215
289
|
} else if (action.kind === 'patch.accept') {
|
|
216
290
|
requireHuman(action.participant)
|
|
217
291
|
const patch = record.patches.find(item => item.id === action.patchId)
|
|
@@ -219,10 +293,12 @@ export class CollaborationEngine {
|
|
|
219
293
|
const version = this.versions.save({ requirementId: record.id, baseCommit: patch.baseCommit, markdown: patch.proposedMarkdown, participant: action.participant, summary: action.summary })
|
|
220
294
|
const before = this.versions.read(record.id, record.currentCommit).markdown
|
|
221
295
|
const impact = changedScopes(before, patch.proposedMarkdown)
|
|
222
|
-
record.currentCommit = version.commit; patch.status = 'accepted'; record.updatedAt = now
|
|
296
|
+
record.currentCommit = version.commit; patch.status = 'accepted'; record.updatedAt = now; delete record.readyPackage
|
|
297
|
+
record.patches.filter(item => item.id !== patch.id && item.status === 'pending').forEach(item => { item.status = 'stale' })
|
|
298
|
+
if (record.stage === 'ready') enterStage(record, 'joint-review')
|
|
223
299
|
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
300
|
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()
|
|
301
|
+
record.actionItems.filter(task => task.sourceId === patch.id && task.status === 'pending').forEach(task => { task.status = 'handled'; task.updatedAt = now }); this.persist(undefined, true)
|
|
226
302
|
this.enqueueReview(record, action.participant, 'change-review')
|
|
227
303
|
} else if (action.kind === 'patch.reject') {
|
|
228
304
|
requireHuman(action.participant)
|
|
@@ -244,12 +320,83 @@ export class CollaborationEngine {
|
|
|
244
320
|
advance(record, action.participant); this.persist()
|
|
245
321
|
} else if (action.kind === 'ready.generate') {
|
|
246
322
|
requireHuman(action.participant)
|
|
247
|
-
const
|
|
248
|
-
if (
|
|
249
|
-
if (!hasVersionConfirmation(record, 'product') || !hasVersionConfirmation(record, 'engineering')) throw new Error('current version needs product and engineering confirmation')
|
|
323
|
+
const admission = readyAdmission(record, readiness(this.versions.read(record.id, record.currentCommit).markdown, record))
|
|
324
|
+
if (admission.error) throw new Error(admission.error)
|
|
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
|
|
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
|
|
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,226 @@ 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
|
-
|
|
289
|
-
|
|
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
|
+
// Rejected actions restore a cloned state while this launch can still be pending.
|
|
469
|
+
const currentRecord = this.state.requirements.find(item => item.id === record.id)
|
|
470
|
+
const currentRun = currentRecord?.aiRuns.find(item => item.id === run.id)
|
|
471
|
+
if (currentRecord === undefined || currentRun === undefined) return
|
|
472
|
+
if (currentRun.status === 'queued') currentRun.status = 'running'
|
|
473
|
+
currentRun.sessionId = sessionId; currentRun.updatedAt = Date.now(); this.rememberStageConversation(currentRecord, sessionId, requestedStage, requestedStageCycle); this.persist({ types: ['ai.status', 'metrics.changed'], requirementId: currentRecord.id, objectId: currentRun.id })
|
|
290
474
|
}, error => this.markAiFailure(record.id, run.id, error instanceof Error ? error.message : String(error)))
|
|
291
475
|
}
|
|
292
476
|
|
|
293
477
|
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
478
|
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(
|
|
296
|
-
|
|
479
|
+
private persist(event = this.eventContext ?? { types: ['metrics.changed'] as const }, recoverable = false): void {
|
|
480
|
+
this.state.revision += 1
|
|
481
|
+
const pendingPath = `${this.eventPath}.pending`
|
|
482
|
+
if (recoverable) atomicWrite(pendingPath, this.state, true)
|
|
483
|
+
atomicWrite(this.eventPath, this.state, recoverable)
|
|
484
|
+
if (recoverable && existsSync(pendingPath)) unlinkSync(pendingPath)
|
|
485
|
+
const payload: CollaborationEvent = { ...event, types: [...event.types], revision: this.state.revision }
|
|
486
|
+
for (const listener of this.listeners) listener(payload)
|
|
487
|
+
}
|
|
488
|
+
private load(): CollaborationState {
|
|
489
|
+
const pendingPath = `${this.eventPath}.pending`
|
|
490
|
+
if (existsSync(pendingPath)) {
|
|
491
|
+
let pending: unknown
|
|
492
|
+
try { pending = JSON.parse(readFileSync(pendingPath, 'utf8')); validateV3Ledger(pending); atomicWrite(this.eventPath, pending, true); unlinkSync(pendingPath); return normalizeV3(pending) }
|
|
493
|
+
catch (error) { throw new Error(`pending collaboration transaction is corrupted: ${error instanceof Error ? error.message : String(error)}`) }
|
|
494
|
+
}
|
|
495
|
+
const sourcePath = existsSync(this.eventPath) ? this.eventPath : this.options.legacyPath !== undefined && existsSync(this.options.legacyPath) ? this.options.legacyPath : undefined
|
|
496
|
+
if (sourcePath === undefined) return emptyState()
|
|
497
|
+
let parsed: unknown
|
|
498
|
+
try { parsed = JSON.parse(readFileSync(sourcePath, 'utf8')) }
|
|
499
|
+
catch (error) { throw new Error(`collaboration ledger is corrupted: ${error instanceof Error ? error.message : String(error)}`) }
|
|
500
|
+
if (typeof parsed !== 'object' || parsed === null || typeof (parsed as { schemaVersion?: unknown }).schemaVersion !== 'number') throw new Error('collaboration ledger has no schema version')
|
|
501
|
+
const version = (parsed as { schemaVersion: number }).schemaVersion
|
|
502
|
+
if (version === SCHEMA_VERSION) { validateV3Ledger(parsed); return normalizeV3(parsed as CollaborationState) }
|
|
503
|
+
if (version !== 2) throw new Error(`unsupported collaboration schema: ${version}`)
|
|
504
|
+
validateV2Ledger(parsed)
|
|
505
|
+
const migrated = migrateV2(parsed as Record<string, unknown>)
|
|
506
|
+
const extension = extname(sourcePath); const stem = basename(sourcePath, extension).replace(/-v2$/, '')
|
|
507
|
+
const backupPath = join(dirname(sourcePath), `${stem}-v2.backup-${Date.now()}${extension || '.json'}`)
|
|
508
|
+
copyFileSync(sourcePath, backupPath)
|
|
509
|
+
atomicWrite(this.eventPath, migrated, true)
|
|
510
|
+
return migrated
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function eventForAction(action: CollaborationAction): Omit<CollaborationEvent, 'revision'> {
|
|
515
|
+
const types = new Set<CollaborationEvent['types'][number]>(['metrics.changed'])
|
|
516
|
+
if (action.kind.startsWith('comment.')) types.add('comment.changed')
|
|
517
|
+
if (action.kind === 'comment.create' || action.kind === 'comment.reply') {
|
|
518
|
+
if ((action.mentions?.length ?? 0) > 0) types.add('mention.created')
|
|
519
|
+
types.add('notification.changed')
|
|
520
|
+
}
|
|
521
|
+
if (action.kind === 'comment.resolve' || action.kind === 'comment.reopen') types.add('notification.changed')
|
|
522
|
+
if (action.kind === 'action.assign') { types.add('assignment.changed'); types.add('notification.changed') }
|
|
523
|
+
if (action.kind === 'notification.mark-read') types.add('notification.changed')
|
|
524
|
+
if (action.kind === 'review.request') types.add('ai.status')
|
|
525
|
+
const requirementId = 'requirementId' in action ? action.requirementId : undefined
|
|
526
|
+
return { types: [...types], ...(requirementId ? { requirementId } : {}) }
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function isRecord(value: unknown): value is Record<string, unknown> { return typeof value === 'object' && value !== null && !Array.isArray(value) }
|
|
530
|
+
function validateV2Ledger(value: unknown): asserts value is Record<string, unknown> {
|
|
531
|
+
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')
|
|
532
|
+
}
|
|
533
|
+
function validateV3Ledger(value: unknown): asserts value is CollaborationState {
|
|
534
|
+
if (!isRecord(value)) throw new Error('invalid collaboration v3 ledger: object required')
|
|
535
|
+
const arrays = ['participants', 'requirements', 'companies', 'customers', 'feedbackSources', 'insights', 'insightLinks', 'notifications'] as const
|
|
536
|
+
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')
|
|
537
|
+
for (const candidate of value.requirements as unknown[]) {
|
|
538
|
+
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')
|
|
539
|
+
const recordArrays = ['sources', 'reviewItems', 'comments', 'patches', 'decisions', 'confirmations', 'actionItems', 'aiRuns'] as const
|
|
540
|
+
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')
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function atomicWrite(path: string, value: unknown, durable = false): void {
|
|
545
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
|
|
546
|
+
const tmp = `${path}.tmp`
|
|
547
|
+
writeFileSync(tmp, JSON.stringify(value, null, 2), { mode: 0o600 })
|
|
548
|
+
if (durable) {
|
|
549
|
+
const descriptor = openSync(tmp, 'r')
|
|
550
|
+
try { fsyncSync(descriptor) } finally { closeSync(descriptor) }
|
|
551
|
+
}
|
|
552
|
+
renameSync(tmp, path)
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function normalizeV3(value: CollaborationState): CollaborationState {
|
|
556
|
+
value.participants ??= []
|
|
557
|
+
value.requirements ??= []
|
|
558
|
+
value.companies ??= []
|
|
559
|
+
value.customers ??= []
|
|
560
|
+
value.feedbackSources ??= []
|
|
561
|
+
value.insights ??= []
|
|
562
|
+
value.insightLinks ??= []
|
|
563
|
+
value.notifications ??= []
|
|
564
|
+
for (const record of value.requirements) {
|
|
565
|
+
record.sources ??= []; record.reviewItems ??= []; record.comments ??= []; record.patches ??= []; record.decisions ??= []; record.confirmations ??= []; record.actionItems ??= []; record.aiRuns ??= []; record.aiConversations ??= []; record.stageCycle ??= 0
|
|
566
|
+
for (const conversation of record.aiConversations) conversation.stageCycle ??= record.stageCycle
|
|
567
|
+
if (record.aiConversations.length === 0 && (record.stage === 'product-review' || record.stage === 'joint-review')) {
|
|
568
|
+
const recent = [
|
|
569
|
+
...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 })),
|
|
570
|
+
...record.comments.filter(item => item.aiSessionId).map(item => ({ sessionId: item.aiSessionId!, createdAt: item.createdAt, updatedAt: item.updatedAt })),
|
|
571
|
+
].sort((left, right) => right.updatedAt - left.updatedAt)[0]
|
|
572
|
+
if (recent) record.aiConversations.push({ stage: record.stage, stageCycle: record.stageCycle, ...recent })
|
|
573
|
+
}
|
|
574
|
+
for (const comment of record.comments) {
|
|
575
|
+
comment.scope ??= comment.anchor === undefined ? 'page' : 'inline'
|
|
576
|
+
comment.mentions ??= []
|
|
577
|
+
comment.replies ??= []
|
|
578
|
+
for (const reply of comment.replies) reply.mentions ??= []
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return value
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function migrateV2(value: Record<string, unknown>): CollaborationState {
|
|
585
|
+
const legacyRequirements = Array.isArray(value.requirements) ? value.requirements as RequirementRecord[] : []
|
|
586
|
+
const requirements = structuredClone(legacyRequirements)
|
|
587
|
+
const feedbackSources: CollaborationState['feedbackSources'] = []
|
|
588
|
+
const insights: CollaborationState['insights'] = []
|
|
589
|
+
const insightLinks: CollaborationState['insightLinks'] = []
|
|
590
|
+
const migrationActor: ParticipantSnapshot = { participantId: 'migration-v2', nickname: '数据迁移', role: 'product', kind: 'ai', sessionId: 'migration-v2' }
|
|
591
|
+
for (const record of requirements) {
|
|
592
|
+
record.sources ??= []; record.reviewItems ??= []; record.comments ??= []; record.patches ??= []; record.decisions ??= []; record.confirmations ??= []; record.actionItems ??= []; record.aiRuns ??= []; record.aiConversations ??= []; record.stageCycle ??= 0
|
|
593
|
+
for (const conversation of record.aiConversations) conversation.stageCycle ??= record.stageCycle
|
|
594
|
+
for (const comment of record.comments) {
|
|
595
|
+
comment.scope = comment.anchor === undefined ? 'page' : 'inline'; comment.mentions = []; comment.replies ??= []
|
|
596
|
+
for (const reply of comment.replies) reply.mentions = []
|
|
597
|
+
}
|
|
598
|
+
for (const source of record.sources) {
|
|
599
|
+
const sourceId = `legacy-${createHash('sha256').update(`${record.id}:${source.id}`).digest('hex').slice(0, 16)}`
|
|
600
|
+
const insightId = `legacy-${createHash('sha256').update(`${record.id}:${source.id}:insight`).digest('hex').slice(0, 16)}`
|
|
601
|
+
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 })
|
|
602
|
+
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 })
|
|
603
|
+
insightLinks.push({ id: randomUUID(), insightId, requirementId: record.id, targetType: 'requirement', createdBy: migrationActor, createdAt: record.createdAt })
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
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: [] })
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
function safeHttpUrl(value: string | undefined): boolean {
|
|
610
|
+
if (!value) return false
|
|
611
|
+
try { const url = new URL(value); return url.protocol === 'http:' || url.protocol === 'https:' } catch { return false }
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
function cleanSource(input: Omit<FeedbackSource, 'createdAt' | 'updatedAt'>): Omit<FeedbackSource, 'createdAt' | 'updatedAt'> {
|
|
615
|
+
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 }
|
|
616
|
+
}
|
|
617
|
+
function cleanCompany(input: { id: string; name: string; externalRef?: string }): { id: string; name: string; externalRef?: string } {
|
|
618
|
+
return { id: input.id, name: input.name, ...(input.externalRef === undefined ? {} : { externalRef: input.externalRef }) }
|
|
619
|
+
}
|
|
620
|
+
function cleanCustomer(input: { id: string; displayName: string; companyId?: string; externalRef?: string }): { id: string; displayName: string; companyId?: string; externalRef?: string } {
|
|
621
|
+
return { id: input.id, displayName: input.displayName, ...(input.companyId === undefined ? {} : { companyId: input.companyId }), ...(input.externalRef === undefined ? {} : { externalRef: input.externalRef }) }
|
|
622
|
+
}
|
|
623
|
+
function validateSource(source: Pick<FeedbackSource, 'id' | 'kind' | 'label' | 'url' | 'accessStatus'>): void {
|
|
624
|
+
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')
|
|
625
|
+
}
|
|
626
|
+
function validateCompany(company: Pick<CollaborationState['companies'][number], 'id' | 'name'>): void {
|
|
627
|
+
if (!company.id.trim() || !company.name.trim()) throw new Error('company id and name are required')
|
|
628
|
+
}
|
|
629
|
+
function validateCustomer(customer: Pick<CollaborationState['customers'][number], 'id' | 'displayName' | 'companyId'>, state: CollaborationState): void {
|
|
630
|
+
if (!customer.id.trim() || !customer.displayName.trim()) throw new Error('customer id and display name are required')
|
|
631
|
+
if (customer.companyId !== undefined && !state.companies.some(item => item.id === customer.companyId)) throw new Error('company not found')
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function validMentions(values: string[] | undefined, participants: ParticipantSnapshot[]): string[] {
|
|
635
|
+
const registered = new Set(participants.map(item => item.participantId))
|
|
636
|
+
return [...new Set(values ?? [])].filter(value => registered.has(value))
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
function insightHash(sourceId: string, body: string): string { return createHash('sha256').update(`${sourceId}\n${body.normalize('NFKC').trim().replace(/\s+/g, ' ').toLocaleLowerCase()}`).digest('hex') }
|
|
640
|
+
function validateInsight(insight: Insight, state: CollaborationState): void {
|
|
641
|
+
if (!insight.id.trim() || !insight.sourceId.trim() || !insight.body.trim()) throw new Error('insight id, source and body are required')
|
|
642
|
+
if (!state.feedbackSources.some(item => item.id === insight.sourceId)) throw new Error('feedback source not found')
|
|
643
|
+
if (insight.customerId !== undefined && !state.customers.some(item => item.id === insight.customerId)) throw new Error('customer not found')
|
|
644
|
+
if (insight.companyId !== undefined && !state.companies.some(item => item.id === insight.companyId)) throw new Error('company not found')
|
|
645
|
+
if (!['unknown', 'want', 'important', 'critical'].includes(insight.importance)) throw new Error('invalid insight importance')
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
function requirementMetrics(record: RequirementRecord, state: CollaborationState): RequirementMetrics {
|
|
649
|
+
const insightIds = new Set(state.insightLinks.filter(link => link.requirementId === record.id).map(link => link.insightId))
|
|
650
|
+
const insights = state.insights.filter(insight => insightIds.has(insight.id))
|
|
651
|
+
const customers = new Set<string>(); const companies = new Set<string>(); const entityScores = new Map<string, number>(); let anonymousInsightCount = 0
|
|
652
|
+
const weights: Record<InsightImportance, number> = { unknown: 1, want: 1, important: 2, critical: 3 }
|
|
653
|
+
for (const insight of insights) {
|
|
654
|
+
const customer = insight.customerId === undefined ? undefined : state.customers.find(item => item.id === insight.customerId)
|
|
655
|
+
const companyId = insight.companyId ?? customer?.companyId
|
|
656
|
+
if (insight.customerId !== undefined) customers.add(insight.customerId)
|
|
657
|
+
if (companyId !== undefined) companies.add(companyId)
|
|
658
|
+
const entity = insight.customerId !== undefined ? `customer:${insight.customerId}` : companyId !== undefined ? `company:${companyId}` : undefined
|
|
659
|
+
if (entity === undefined) anonymousInsightCount += 1
|
|
660
|
+
else entityScores.set(entity, Math.max(entityScores.get(entity) ?? 0, weights[insight.importance]))
|
|
661
|
+
}
|
|
662
|
+
return {
|
|
663
|
+
openReviewCount: record.reviewItems.filter(item => item.commit === record.currentCommit && !['resolved', 'invalidated'].includes(item.status)).length,
|
|
664
|
+
openCommentCount: record.comments.filter(item => item.commit === record.currentCommit && item.status === 'open').length,
|
|
665
|
+
pendingActionCount: record.actionItems.filter(item => item.status === 'pending').length,
|
|
666
|
+
activeDecisionCount: record.decisions.filter(item => item.status === 'active').length,
|
|
667
|
+
riskCount: record.reviewItems.filter(item => item.commit === record.currentCommit && ['blocking', 'major'].includes(item.severity) && !['resolved', 'invalidated'].includes(item.status)).length,
|
|
668
|
+
insightCount: insights.length, customerImportanceScore: [...entityScores.values()].reduce((sum, value) => sum + value, 0), customerCount: customers.size, companyCount: companies.size, anonymousInsightCount,
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
function requirementParticipantIds(record: RequirementRecord, history: Array<Omit<RequirementVersion, 'markdown'>>): string[] {
|
|
673
|
+
return [...new Set([
|
|
674
|
+
...history.map(item => item.author.participantId),
|
|
675
|
+
...record.reviewItems.flatMap(item => item.response ? [item.response.participant.participantId] : []),
|
|
676
|
+
...record.comments.flatMap(item => [item.author.participantId, ...item.replies.map(reply => reply.author.participantId)]),
|
|
677
|
+
...record.decisions.map(item => item.confirmer.participantId),
|
|
678
|
+
...record.confirmations.map(item => item.participant.participantId),
|
|
679
|
+
...record.actionItems.flatMap(item => item.assigneeParticipantId ? [item.assigneeParticipantId] : []),
|
|
680
|
+
])]
|
|
297
681
|
}
|
|
298
682
|
|
|
299
683
|
function sourceParticipantId(record: RequirementRecord, item: ActionItem): string | undefined {
|
|
@@ -307,6 +691,20 @@ function actionTarget(item: ActionItem): MyActionItem['target'] {
|
|
|
307
691
|
const tabs = { 'review-item': 'review', comment: 'discussion', patch: 'patches', decision: 'decisions', confirmation: 'ready' } as const
|
|
308
692
|
return { tab: tabs[item.sourceType], objectId: item.sourceId }
|
|
309
693
|
}
|
|
694
|
+
function actionObjectTitle(record: RequirementRecord, item: ActionItem): string {
|
|
695
|
+
if (item.sourceType === 'review-item') {
|
|
696
|
+
const review = record.reviewItems.find(value => value.id === item.sourceId)
|
|
697
|
+
return review?.question.trim() || review?.statement.trim() || '待处理问题'
|
|
698
|
+
}
|
|
699
|
+
if (item.sourceType === 'comment') {
|
|
700
|
+
const comment = record.comments.find(value => value.id === item.sourceId)
|
|
701
|
+
return comment?.anchor?.quote.trim() || comment?.body.trim() || '待回复评论'
|
|
702
|
+
}
|
|
703
|
+
if (item.sourceType === 'patch') return record.patches.find(value => value.id === item.sourceId)?.summary.trim() || '待审核正文改动'
|
|
704
|
+
if (item.sourceType === 'decision') return record.decisions.find(value => value.id === item.sourceId)?.question.trim() || '待确认决策'
|
|
705
|
+
const confirmation = record.confirmations.find(value => value.id === item.sourceId)
|
|
706
|
+
return confirmation ? `${confirmation.role === 'product' ? '产品' : '研发'}需要重新确认当前版本` : '待确认当前版本'
|
|
707
|
+
}
|
|
310
708
|
function textDiff(before: string, after: string): string {
|
|
311
709
|
if (before === after) return ''
|
|
312
710
|
const left = before.split('\n'); const right = after.split('\n')
|
|
@@ -322,16 +720,20 @@ function assertChineseFeedback(...values: string[]): void {
|
|
|
322
720
|
}
|
|
323
721
|
function requireHuman(participant: ParticipantSnapshot): void { if (participant.kind !== 'human') throw new Error('human participant is required') }
|
|
324
722
|
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
|
-
function
|
|
723
|
+
function enterStage(record: RequirementRecord, stage: RequirementRecord['stage']): void {
|
|
724
|
+
if (record.stage === stage) return
|
|
725
|
+
record.stage = stage
|
|
726
|
+
record.stageCycle += 1
|
|
727
|
+
}
|
|
326
728
|
function advance(record: RequirementRecord, participant: ParticipantSnapshot): void {
|
|
327
729
|
if (record.stage === 'product-review') {
|
|
328
730
|
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
|
-
if (!record
|
|
330
|
-
record
|
|
731
|
+
if (!hasCompletedCurrentReview(record, 'product-second')) throw new Error('product second review is required')
|
|
732
|
+
enterStage(record, 'product-confirmation'); return
|
|
331
733
|
}
|
|
332
734
|
if (record.stage === 'product-confirmation') {
|
|
333
735
|
if (participant.role !== 'product' || !hasVersionConfirmation(record, 'product')) throw new Error('product must confirm the current version')
|
|
334
|
-
record
|
|
736
|
+
enterStage(record, 'joint-review'); return
|
|
335
737
|
}
|
|
336
738
|
throw new Error('stage cannot advance directly')
|
|
337
739
|
}
|