dsh-spec-collab 0.4.0 → 0.5.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.
- package/CHANGELOG.md +14 -0
- package/README.md +16 -16
- 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/core-refactor-ablation.md +59 -0
- package/docs/usage-walkthrough.md +7 -7
- package/lib/client.js +247 -236
- package/lib/index.js +1481 -1376
- package/lib/types/collaboration-ledger.d.ts +14 -0
- package/lib/types/collaboration-ledger.d.ts.map +1 -0
- package/lib/types/engine.d.ts +19 -29
- package/lib/types/engine.d.ts.map +1 -1
- package/lib/types/git-store.d.ts +24 -10
- package/lib/types/git-store.d.ts.map +1 -1
- package/lib/types/insights.d.ts +29 -0
- package/lib/types/insights.d.ts.map +1 -0
- package/lib/types/ready-admission.d.ts +1 -0
- package/lib/types/ready-admission.d.ts.map +1 -1
- package/lib/types/review-runtime.d.ts +32 -2
- package/lib/types/review-runtime.d.ts.map +1 -1
- package/lib/types/routes.d.ts.map +1 -1
- package/lib/types/spec-lifecycle.d.ts +18 -0
- package/lib/types/spec-lifecycle.d.ts.map +1 -0
- package/package.json +34 -29
- package/src/collaboration-ledger.ts +168 -0
- package/src/engine.ts +306 -516
- package/src/git-store.ts +212 -141
- package/src/insights.ts +186 -0
- package/src/ready-admission.ts +5 -1
- package/src/review-runtime.ts +37 -3
- package/src/routes.ts +6 -4
- package/src/spec-lifecycle.ts +126 -0
package/src/engine.ts
CHANGED
|
@@ -1,31 +1,67 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
2
|
+
import { CollaborationLedger } from './collaboration-ledger.ts'
|
|
3
|
+
import { GitRequirementStore, VersionConflictError, type PreparedSpecCommit } from './git-store.ts'
|
|
4
|
+
import { applyInsightAction, insightMetrics, isInsightAction, queryInsights, type InsightPage, type InsightQuery } from './insights.ts'
|
|
5
|
+
import { type ActionItem, type ActionResult, type AiReviewRun, type CandidatePatch, type CollaborationAction, type CollaborationEvent, type CollaborationState, type CommentThread, type MyActionItem, type MyItemCategory, type Notification, type ParticipantSnapshot, type RequirementMetrics, type RequirementRecord, type RequirementSummary, type RequirementVersion, type RequirementView, type ReviewItem, type ReviewKind, type SaveConflict, type StructuredDiff } from './protocol.ts'
|
|
6
6
|
import { buildStructuredDiff } from './structured-diff.ts'
|
|
7
|
-
import {
|
|
7
|
+
import { readyAdmission } from './ready-admission.ts'
|
|
8
|
+
import { advance, decisionScopeAnchors, enterStage, invalidateAffected, normalizeAnchorText, readiness, readyMarkdown, retireActionItems, versionChanged } from './spec-lifecycle.ts'
|
|
9
|
+
|
|
10
|
+
export { readiness } from './spec-lifecycle.ts'
|
|
8
11
|
|
|
9
12
|
export interface AiCoordinator {
|
|
10
13
|
requestReview(input: { requirement: RequirementView; run: AiReviewRun; sessionId?: string }): Promise<string>
|
|
11
14
|
requestCommentReply(input: { requirement: RequirementView; comment: CommentThread; sessionId?: string }): Promise<string>
|
|
12
15
|
}
|
|
13
16
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
type
|
|
17
|
-
type
|
|
17
|
+
type EventDraft = Omit<CollaborationEvent, 'revision'>
|
|
18
|
+
type AiTask = { kind: 'review' | 'comment'; id: string }
|
|
19
|
+
type ActionChange = { requirementId: string; spec?: PreparedSpecCommit; task?: AiTask; deleted?: RequirementView; unchanged?: true }
|
|
20
|
+
type VersionAction = Extract<CollaborationAction, { kind: 'requirement.rename' | 'version.save' | 'version.restore' | 'patch.accept' }>
|
|
18
21
|
|
|
19
22
|
export class CollaborationEngine {
|
|
20
23
|
private state: CollaborationState
|
|
24
|
+
private readonly ledger: CollaborationLedger
|
|
21
25
|
private coordinator?: AiCoordinator
|
|
22
26
|
private readonly listeners = new Set<(event: CollaborationEvent) => void>()
|
|
23
|
-
private readonly seen = new Map<string,
|
|
24
|
-
private eventContext: Omit<CollaborationEvent, 'revision'> | undefined
|
|
27
|
+
private readonly seen = new Map<string, ActionResult>()
|
|
25
28
|
|
|
26
|
-
constructor(
|
|
27
|
-
|
|
29
|
+
constructor(eventPath: string, private readonly versions: GitRequirementStore, options: { legacyPath?: string } = {}) {
|
|
30
|
+
this.ledger = new CollaborationLedger(eventPath, change => versions.publish(change), options.legacyPath)
|
|
31
|
+
this.state = this.ledger.load()
|
|
32
|
+
}
|
|
33
|
+
setCoordinator(coordinator: AiCoordinator): void {
|
|
34
|
+
if (this.coordinator === undefined) {
|
|
35
|
+
// A queued task loaded from disk has no durable acknowledgement from DSH.
|
|
36
|
+
// Allow an explicit retry without dispatching a possibly admitted prompt twice.
|
|
37
|
+
this.changeAi(() => {
|
|
38
|
+
let interrupted = false
|
|
39
|
+
const now = Date.now()
|
|
40
|
+
for (const record of this.state.requirements) {
|
|
41
|
+
for (const run of record.aiRuns) {
|
|
42
|
+
if (run.status !== 'queued') continue
|
|
43
|
+
run.status = 'failed'
|
|
44
|
+
run.error = 'AI launch was interrupted before acknowledgement'
|
|
45
|
+
run.updatedAt = now
|
|
46
|
+
interrupted = true
|
|
47
|
+
}
|
|
48
|
+
for (const comment of record.comments) {
|
|
49
|
+
if (comment.aiStatus !== 'queued') continue
|
|
50
|
+
comment.aiStatus = 'failed'
|
|
51
|
+
comment.updatedAt = now
|
|
52
|
+
interrupted = true
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (interrupted) return { types: ['ai.status', 'comment.changed', 'metrics.changed'] }
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
this.coordinator = coordinator
|
|
59
|
+
}
|
|
60
|
+
get revision(): number { return this.state.revision }
|
|
28
61
|
snapshot(): CollaborationState { return structuredClone(this.state) }
|
|
62
|
+
overview() {
|
|
63
|
+
return { revision: this.revision, participants: structuredClone(this.state.participants), requirements: this.summaries() }
|
|
64
|
+
}
|
|
29
65
|
directory(): ParticipantSnapshot[] { return structuredClone(this.state.participants).sort((left, right) => left.nickname.localeCompare(right.nickname, 'zh-CN')) }
|
|
30
66
|
notifications(participantId: string, page = 1, pageSize = 50): { items: Notification[]; total: number; unread: number } {
|
|
31
67
|
const rows = this.state.notifications.filter(item => item.recipientParticipantId === participantId).sort((left, right) => right.createdAt - left.createdAt)
|
|
@@ -34,13 +70,7 @@ export class CollaborationEngine {
|
|
|
34
70
|
const start = (safePage - 1) * safePageSize
|
|
35
71
|
return { items: structuredClone(rows.slice(start, start + safePageSize)), total: rows.length, unread: rows.filter(item => item.readAt === undefined).length }
|
|
36
72
|
}
|
|
37
|
-
insights(query
|
|
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
|
-
}
|
|
73
|
+
insights(query?: InsightQuery): InsightPage { return queryInsights(this.state, query) }
|
|
44
74
|
subscribe(listener: (event: CollaborationEvent) => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener) }
|
|
45
75
|
list(): RequirementView[] { return this.state.requirements.map(item => this.view(item.id)) }
|
|
46
76
|
summaries(): RequirementSummary[] {
|
|
@@ -53,12 +83,12 @@ export class CollaborationEngine {
|
|
|
53
83
|
...(record.archivedAt ? { archivedAt: record.archivedAt } : {}),
|
|
54
84
|
updatedAt: record.updatedAt,
|
|
55
85
|
metrics: requirementMetrics(record, this.state),
|
|
56
|
-
participantIds: requirementParticipantIds(record, this.versions.history(record.id)),
|
|
86
|
+
participantIds: requirementParticipantIds(record, this.versions.history(record.id, record.currentCommit)),
|
|
57
87
|
}))
|
|
58
88
|
}
|
|
59
89
|
version(requirementId: string, commit: string): RequirementVersion {
|
|
60
90
|
const record = this.record(requirementId)
|
|
61
|
-
if (!this.versions.history(record.id).some(version => version.commit === commit)) throw new Error('requirement version not found')
|
|
91
|
+
if (!this.versions.history(record.id, record.currentCommit).some(version => version.commit === commit)) throw new Error('requirement version not found')
|
|
62
92
|
return this.versions.read(record.id, commit)
|
|
63
93
|
}
|
|
64
94
|
diff(requirementId: string, baseCommit: string, headCommit?: string): StructuredDiff {
|
|
@@ -85,252 +115,208 @@ export class CollaborationEngine {
|
|
|
85
115
|
}
|
|
86
116
|
view(id: string): RequirementView {
|
|
87
117
|
const record = this.record(id)
|
|
118
|
+
const history = this.versions.history(id, record.currentCommit)
|
|
88
119
|
const version = this.versions.read(id, record.currentCommit)
|
|
89
120
|
const commitUrl = this.versions.commitUrl(record.currentCommit)
|
|
90
|
-
return { ...structuredClone(record), version, history
|
|
121
|
+
return { ...structuredClone(record), version, history, readiness: readiness(version.markdown, record), metrics: requirementMetrics(record, this.state), ...(commitUrl ? { commitUrl } : {}) }
|
|
91
122
|
}
|
|
92
123
|
|
|
93
|
-
apply(requestId: string, action: CollaborationAction):
|
|
124
|
+
apply(requestId: string, action: CollaborationAction): ActionResult {
|
|
94
125
|
const cached = this.seen.get(requestId)
|
|
95
126
|
if (cached !== undefined) return structuredClone(cached)
|
|
96
|
-
let result:
|
|
97
|
-
|
|
98
|
-
const previousEventContext = this.eventContext
|
|
99
|
-
this.eventContext = eventForAction(action)
|
|
127
|
+
let result: ActionResult
|
|
128
|
+
let committed: { value: { requirement: RequirementView; change: ActionChange }; event?: CollaborationEvent } | undefined
|
|
100
129
|
try {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
130
|
+
committed = this.transact(() => {
|
|
131
|
+
const participant = action.participant
|
|
132
|
+
requireHuman(participant)
|
|
133
|
+
const registered = this.state.participants.find(item => item.participantId === participant.participantId)
|
|
134
|
+
if (registered !== undefined && registered.role !== participant.role) throw new Error(`participant role is bound to ${registered.role}`)
|
|
135
|
+
const change = this.applyFresh(action)
|
|
136
|
+
if (registered === undefined) this.state.participants.push(structuredClone(participant))
|
|
137
|
+
const event = change.unchanged && registered !== undefined ? undefined : eventForAction(action, change)
|
|
138
|
+
return { value: { requirement: change.deleted ?? this.view(change.requirementId), change }, event, spec: change.spec }
|
|
139
|
+
})
|
|
140
|
+
const { requirement, change } = committed.value
|
|
141
|
+
result = { ok: true, revision: committed.event?.revision ?? this.state.revision, requirement, ...(change.deleted ? { deletedRequirementId: change.requirementId } : {}) }
|
|
142
|
+
} catch (error) {
|
|
143
|
+
const conflict = error instanceof VersionConflictError && action.kind === 'version.save' ? this.saveConflict(action, error.currentCommit) : undefined
|
|
144
|
+
result = { ok: false, revision: this.state.revision, error: errorMessage(error), ...(conflict ? { conflict } : {}) }
|
|
110
145
|
}
|
|
111
|
-
catch (error) {
|
|
112
|
-
this.state = beforeState
|
|
113
|
-
const conflict = error instanceof VersionConflictError && action.kind === 'version.save' ? this.saveConflict(action) : undefined
|
|
114
|
-
result = { ok: false, revision: this.state.revision, error: error instanceof Error ? error.message : String(error), ...(conflict === undefined ? {} : { conflict }) }
|
|
115
|
-
}
|
|
116
|
-
this.eventContext = previousEventContext
|
|
117
146
|
this.seen.set(requestId, result)
|
|
147
|
+
if (committed !== undefined) {
|
|
148
|
+
this.emit(committed.event)
|
|
149
|
+
const { requirement, change } = committed.value
|
|
150
|
+
if (change.task) this.launchAiTask(requirement, change.task)
|
|
151
|
+
}
|
|
118
152
|
return structuredClone(result)
|
|
119
153
|
}
|
|
120
154
|
|
|
121
155
|
submitReview(input: { requirementId: string; commit: string; runId: string; ai: ParticipantSnapshot; items: Omit<ReviewItem, 'id' | 'requirementId' | 'commit' | 'reviewKind' | 'createdAt' | 'updatedAt'>[]; maturitySummary: string }): void {
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
156
|
+
this.changeAi(() => {
|
|
157
|
+
const record = this.record(input.requirementId)
|
|
158
|
+
const run = record.aiRuns.find(item => item.id === input.runId)
|
|
159
|
+
if (run === undefined || run.commit !== input.commit || record.currentCommit !== input.commit) throw new Error('review run is stale')
|
|
160
|
+
if (run.status === 'completed') return
|
|
161
|
+
assertChineseFeedback(input.maturitySummary)
|
|
162
|
+
const now = Date.now()
|
|
163
|
+
for (const item of input.items) {
|
|
164
|
+
assertChineseFeedback(item.statement, item.impact, item.question)
|
|
165
|
+
if (item.epistemicStatus === 'FACT' && !item.evidence.some(evidence => evidence.accessible && evidence.version?.trim())) throw new Error('FACT requires accessible versioned evidence')
|
|
166
|
+
const recommendedOptions = item.recommendedOptions?.map(option => option.trim()).filter(Boolean)
|
|
167
|
+
const created: ReviewItem = { ...item, ...(recommendedOptions ? { recommendedOptions } : {}), id: randomUUID(), requirementId: record.id, commit: input.commit, reviewKind: run.kind, createdAt: now, updatedAt: now }
|
|
168
|
+
record.reviewItems.push(created)
|
|
169
|
+
record.actionItems.push(actionForReview(created))
|
|
170
|
+
}
|
|
171
|
+
run.status = 'completed'
|
|
172
|
+
run.maturitySummary = input.maturitySummary
|
|
173
|
+
run.updatedAt = now
|
|
174
|
+
delete run.error
|
|
175
|
+
return aiEvent(record.id, run.id)
|
|
176
|
+
})
|
|
137
177
|
}
|
|
138
178
|
|
|
139
179
|
submitPatch(input: { requirementId: string; baseCommit: string; reviewKind: ReviewKind; ai: ParticipantSnapshot; proposedMarkdown: string; summary: string; affectedReviewItemIds: string[]; affectedSections: string[]; affectedAcceptanceIds: string[] }): void {
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
180
|
+
this.changeAi(() => {
|
|
181
|
+
const record = this.record(input.requirementId)
|
|
182
|
+
if (record.currentCommit !== input.baseCommit) throw new Error('patch base commit is stale')
|
|
183
|
+
assertChineseFeedback(input.summary, input.proposedMarkdown)
|
|
184
|
+
const now = Date.now()
|
|
185
|
+
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: now }
|
|
186
|
+
record.patches.push(patch)
|
|
187
|
+
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: now, updatedAt: now })
|
|
188
|
+
return aiEvent(record.id, patch.id)
|
|
189
|
+
})
|
|
147
190
|
}
|
|
148
191
|
|
|
149
192
|
submitAiReply(input: { requirementId: string; commentId: string; ai: ParticipantSnapshot; body: string }): void {
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
193
|
+
this.changeAi(() => {
|
|
194
|
+
assertChineseFeedback(input.body)
|
|
195
|
+
const record = this.record(input.requirementId)
|
|
196
|
+
const comment = this.comment(record, input.commentId)
|
|
197
|
+
const now = Date.now()
|
|
198
|
+
comment.replies.push({ id: randomUUID(), author: input.ai, body: input.body, mentions: [], createdAt: now })
|
|
199
|
+
comment.aiStatus = 'completed'
|
|
200
|
+
comment.updatedAt = now
|
|
201
|
+
return aiEvent(record.id, comment.id, true)
|
|
202
|
+
})
|
|
156
203
|
}
|
|
157
204
|
|
|
158
205
|
markAiFailure(requirementId: string, sourceId: string, error: string): void {
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
206
|
+
this.changeAi(() => {
|
|
207
|
+
const record = this.state.requirements.find(item => item.id === requirementId)
|
|
208
|
+
if (record === undefined) return
|
|
209
|
+
const run = record.aiRuns.find(item => item.id === sourceId)
|
|
210
|
+
const comment = record.comments.find(item => item.id === sourceId)
|
|
211
|
+
if (run !== undefined && (run.status === 'queued' || run.status === 'running')) {
|
|
212
|
+
run.status = 'failed'
|
|
213
|
+
run.error = error
|
|
214
|
+
run.updatedAt = Date.now()
|
|
215
|
+
return aiEvent(record.id, run.id)
|
|
216
|
+
}
|
|
217
|
+
if (comment !== undefined && (comment.aiStatus === 'queued' || comment.aiStatus === 'running')) {
|
|
218
|
+
comment.aiStatus = 'failed'
|
|
219
|
+
comment.updatedAt = Date.now()
|
|
220
|
+
return aiEvent(record.id, comment.id, true)
|
|
221
|
+
}
|
|
222
|
+
})
|
|
165
223
|
}
|
|
166
224
|
|
|
167
|
-
private applyFresh(action: CollaborationAction):
|
|
225
|
+
private applyFresh(action: CollaborationAction): ActionChange {
|
|
168
226
|
const now = Date.now()
|
|
169
227
|
if (action.kind === 'requirement.create') {
|
|
170
|
-
requireHuman(action.participant)
|
|
171
228
|
const title = action.title.trim()
|
|
172
229
|
if (title === '' || action.rawRequirement.trim() === '') throw new Error('title and original requirement are required')
|
|
173
230
|
const workspaceId = action.workspaceId?.trim()
|
|
174
231
|
if (workspaceId === undefined || workspaceId === '') throw new Error('review workspace is required')
|
|
175
|
-
const
|
|
176
|
-
const record: RequirementRecord = { id:
|
|
177
|
-
this.state.requirements.unshift(record)
|
|
178
|
-
this.
|
|
179
|
-
return { ok: true, revision: this.state.revision, requirement: this.view(record.id) }
|
|
232
|
+
const spec = this.versions.prepareCreate({ title, rawRequirement: action.rawRequirement, sources: action.sources, participant: action.participant })
|
|
233
|
+
const record: RequirementRecord = { id: spec.requirementId, title, stage: 'product-review', stageCycle: 0, currentCommit: spec.commit, workspaceId, sources: action.sources, reviewItems: [], comments: [], patches: [], decisions: [], confirmations: [], actionItems: [], aiRuns: [], aiConversations: [], createdAt: now, updatedAt: now }
|
|
234
|
+
this.state.requirements.unshift(record)
|
|
235
|
+
return { requirementId: record.id, spec, task: this.queueReview(record, action.participant, 'product-first', now) }
|
|
180
236
|
}
|
|
181
237
|
const record = this.record(action.requirementId)
|
|
182
238
|
if (action.kind === 'requirement.bind-workspace') {
|
|
183
|
-
requireHuman(action.participant)
|
|
184
239
|
const workspaceId = action.workspaceId.trim()
|
|
185
240
|
if (workspaceId === '') throw new Error('review workspace is required')
|
|
186
241
|
if (record.workspaceId !== undefined) throw new Error('review workspace is already bound')
|
|
187
|
-
record.workspaceId = workspaceId
|
|
188
|
-
|
|
189
|
-
requireHuman(action.participant)
|
|
190
|
-
const title = action.title.trim()
|
|
191
|
-
if (title === '' || title.length > 120 || /[\r\n]/.test(title)) throw new Error('valid requirement title is required')
|
|
192
|
-
if (title === record.title) return { ok: true, revision: this.state.revision, requirement: this.view(record.id) }
|
|
193
|
-
const before = this.versions.read(record.id, record.currentCommit).markdown
|
|
194
|
-
const markdown = /^# .+$/m.test(before) ? before.replace(/^# .+$/m, `# ${title}`) : `# ${title}\n\n${before}`
|
|
195
|
-
const version = this.versions.save({ requirementId: record.id, baseCommit: record.currentCommit, markdown, participant: action.participant, summary: `Rename requirement: ${title}` })
|
|
196
|
-
record.title = title; record.currentCommit = version.commit; record.updatedAt = now
|
|
197
|
-
invalidateAffected(record, [], []); this.persist(undefined, true); this.enqueueReview(record, action.participant, 'change-review')
|
|
242
|
+
record.workspaceId = workspaceId
|
|
243
|
+
record.updatedAt = now
|
|
198
244
|
} else if (action.kind === 'requirement.archive' || action.kind === 'requirement.unarchive') {
|
|
199
|
-
requireHuman(action.participant)
|
|
200
245
|
if (action.kind === 'requirement.archive' && action.archived) record.archivedAt = now
|
|
201
246
|
else delete record.archivedAt
|
|
202
|
-
record.updatedAt = now
|
|
247
|
+
record.updatedAt = now
|
|
203
248
|
} else if (action.kind === 'requirement.delete') {
|
|
204
|
-
requireHuman(action.participant)
|
|
205
249
|
const deleted = this.view(record.id)
|
|
206
|
-
this.versions.
|
|
250
|
+
const spec = this.versions.prepareRemove(record.id, record.currentCommit, action.participant)
|
|
207
251
|
this.state.requirements.splice(this.state.requirements.indexOf(record), 1)
|
|
208
252
|
this.state.insightLinks = this.state.insightLinks.filter(item => item.requirementId !== record.id)
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
requireHuman(action.participant)
|
|
213
|
-
const before = this.versions.read(record.id, record.currentCommit).markdown
|
|
214
|
-
const version = this.versions.save({ requirementId: record.id, baseCommit: action.baseCommit, markdown: action.markdown, participant: action.participant, summary: action.summary })
|
|
215
|
-
const impact = changedScopes(before, action.markdown)
|
|
216
|
-
record.currentCommit = version.commit; record.updatedAt = now; delete record.readyPackage
|
|
217
|
-
invalidateAffected(record, impact.sections, impact.acceptanceIds, action.markdown)
|
|
218
|
-
record.patches.filter(item => item.status === 'pending').forEach(item => { item.status = 'stale' })
|
|
219
|
-
if (record.stage === 'ready') enterStage(record, 'joint-review')
|
|
220
|
-
this.persist(undefined, true)
|
|
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')
|
|
253
|
+
return { requirementId: record.id, spec, deleted }
|
|
254
|
+
} else if (action.kind === 'requirement.rename' || action.kind === 'version.save' || action.kind === 'version.restore' || action.kind === 'patch.accept') {
|
|
255
|
+
return this.changeVersion(record, action, now)
|
|
234
256
|
} else if (action.kind === 'review.request') {
|
|
235
|
-
|
|
236
|
-
this.enqueueReview(record, action.participant, action.reviewKind)
|
|
257
|
+
return { requirementId: record.id, task: this.queueReview(record, action.participant, action.reviewKind, now) }
|
|
237
258
|
} else if (action.kind === 'review.respond') {
|
|
238
|
-
requireHuman(action.participant)
|
|
239
259
|
const item = record.reviewItems.find(candidate => candidate.id === action.reviewItemId)
|
|
240
260
|
if (item === undefined) throw new Error('review item not found')
|
|
241
261
|
item.response = { participant: action.participant, disposition: action.disposition, body: action.body.trim(), createdAt: now }
|
|
242
262
|
item.status = action.disposition === 'joint-review' ? 'joint-review' : action.disposition === 'to-verify' ? 'non-blocking-verify' : action.disposition === 'accept' ? 'resolved' : 'answered'
|
|
243
263
|
item.updatedAt = now
|
|
244
264
|
record.actionItems.filter(task => task.sourceId === item.id && task.status === 'pending').forEach(task => { task.status = 'handled'; task.updatedAt = now })
|
|
245
|
-
this.persist()
|
|
246
265
|
} else if (action.kind === 'comment.create') {
|
|
247
|
-
requireHuman(action.participant)
|
|
248
266
|
if (action.commit !== record.currentCommit) throw new VersionConflictError(record.currentCommit)
|
|
249
267
|
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 }
|
|
268
|
+
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: this.coordinator ? 'queued' : 'failed', status: 'open', createdAt: now, updatedAt: now }
|
|
251
269
|
if (comment.body === '' || (scope === 'inline' && action.anchor?.quote.trim() === '')) throw new Error(scope === 'inline' ? 'comment and anchor are required' : 'comment is required')
|
|
252
270
|
if (scope === 'inline' && action.anchor === undefined) throw new Error('comment and anchor are required')
|
|
253
271
|
record.comments.push(comment)
|
|
254
272
|
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
273
|
for (const participantId of mentions) this.notify(participantId, 'mention', record, 'comment', comment.id, `${action.participant.nickname} 在评论中提到了你`)
|
|
256
|
-
|
|
257
|
-
const coordinator = this.coordinator
|
|
258
|
-
if (coordinator !== undefined) {
|
|
259
|
-
const view = this.view(record.id)
|
|
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 })
|
|
264
|
-
}, error => this.markAiFailure(record.id, comment.id, error instanceof Error ? error.message : String(error)))
|
|
265
|
-
}
|
|
274
|
+
return { requirementId: record.id, task: { kind: 'comment', id: comment.id } }
|
|
266
275
|
} else if (action.kind === 'comment.reply') {
|
|
267
|
-
requireHuman(action.participant)
|
|
268
276
|
const comment = this.comment(record, action.commentId)
|
|
269
277
|
const body = action.body.trim(); if (body === '') throw new Error('reply is required')
|
|
270
278
|
const mentions = validMentions(action.mentions, this.state.participants)
|
|
271
279
|
comment.replies.push({ id: randomUUID(), author: action.participant, body, mentions, createdAt: now }); comment.updatedAt = now
|
|
272
280
|
if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, 'reply', record, 'comment', comment.id, `${action.participant.nickname} 回复了你的评论`)
|
|
273
281
|
for (const participantId of mentions) this.notify(participantId, 'mention', record, 'comment', comment.id, `${action.participant.nickname} 在回复中提到了你`)
|
|
274
|
-
this.persist()
|
|
275
282
|
} else if (action.kind === 'comment.resolve') {
|
|
276
|
-
requireHuman(action.participant)
|
|
277
283
|
const comment = this.comment(record, action.commentId)
|
|
278
284
|
comment.status = 'resolved'; comment.resolution = action.resolution; comment.updatedAt = now
|
|
279
285
|
if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, 'status-change', record, 'comment', comment.id, `${action.participant.nickname} 已解决你的评论`)
|
|
280
|
-
record.actionItems.filter(task => task.sourceId === comment.id && task.status === 'pending').forEach(task => { task.status = 'handled'; task.updatedAt = now })
|
|
286
|
+
record.actionItems.filter(task => task.sourceId === comment.id && task.status === 'pending').forEach(task => { task.status = 'handled'; task.updatedAt = now })
|
|
281
287
|
} else if (action.kind === 'comment.reopen') {
|
|
282
|
-
requireHuman(action.participant)
|
|
283
288
|
const comment = this.comment(record, action.commentId)
|
|
284
289
|
if (comment.status !== 'resolved') throw new Error('resolved comment not found')
|
|
285
290
|
comment.status = 'open'; delete comment.resolution; comment.updatedAt = now
|
|
286
291
|
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
292
|
if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, 'status-change', record, 'comment', comment.id, `${action.participant.nickname} 重新打开了你的评论`)
|
|
288
|
-
this.persist()
|
|
289
|
-
} else if (action.kind === 'patch.accept') {
|
|
290
|
-
requireHuman(action.participant)
|
|
291
|
-
const patch = record.patches.find(item => item.id === action.patchId)
|
|
292
|
-
if (patch === undefined || patch.status !== 'pending') throw new Error('pending patch not found')
|
|
293
|
-
const version = this.versions.save({ requirementId: record.id, baseCommit: patch.baseCommit, markdown: patch.proposedMarkdown, participant: action.participant, summary: action.summary })
|
|
294
|
-
const before = this.versions.read(record.id, record.currentCommit).markdown
|
|
295
|
-
const impact = changedScopes(before, patch.proposedMarkdown)
|
|
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')
|
|
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 } }
|
|
300
|
-
invalidateAffected(record, impact.sections, impact.acceptanceIds, patch.proposedMarkdown)
|
|
301
|
-
record.actionItems.filter(task => task.sourceId === patch.id && task.status === 'pending').forEach(task => { task.status = 'handled'; task.updatedAt = now }); this.persist(undefined, true)
|
|
302
|
-
this.enqueueReview(record, action.participant, 'change-review')
|
|
303
293
|
} else if (action.kind === 'patch.reject') {
|
|
304
|
-
|
|
305
|
-
|
|
294
|
+
const patch = record.patches.find(item => item.id === action.patchId && item.status === 'pending')
|
|
295
|
+
if (patch === undefined) throw new Error('pending patch not found')
|
|
296
|
+
patch.status = 'rejected'
|
|
297
|
+
retireActionItems(record, 'patch', patch.id, 'handled', now)
|
|
306
298
|
} else if (action.kind === 'decision.create') {
|
|
307
|
-
requireHuman(action.participant)
|
|
308
299
|
const sourceAnchors = [...(action.sourceAnchors ?? []), ...decisionScopeAnchors(this.versions.read(record.id, record.currentCommit).markdown, action.affectedSections, action.affectedAcceptanceIds)]
|
|
309
300
|
.filter((anchor, index, anchors) => anchor.quote.trim() !== '' && anchors.findIndex(candidate => normalizeAnchorText(candidate.quote) === normalizeAnchorText(anchor.quote) && normalizeAnchorText(candidate.heading ?? '') === normalizeAnchorText(anchor.heading ?? '')) === index)
|
|
310
|
-
record.decisions.push({ id: randomUUID(), requirementId: record.id, commit: record.currentCommit, question: action.question, options: action.options, decision: action.decision, rationale: action.rationale, confirmer: action.participant, affectedSections: action.affectedSections, affectedAcceptanceIds: action.affectedAcceptanceIds, ...(sourceAnchors.length > 0 ? { sourceAnchors } : {}), createdAt: now, status: 'active' })
|
|
301
|
+
record.decisions.push({ id: randomUUID(), requirementId: record.id, commit: record.currentCommit, question: action.question, options: action.options, decision: action.decision, rationale: action.rationale, confirmer: action.participant, affectedSections: action.affectedSections, affectedAcceptanceIds: action.affectedAcceptanceIds, ...(sourceAnchors.length > 0 ? { sourceAnchors } : {}), createdAt: now, status: 'active' })
|
|
311
302
|
} else if (action.kind === 'confirmation.create') {
|
|
312
|
-
requireHuman(action.participant)
|
|
313
303
|
if (action.participant.role !== action.role) throw new Error(`${action.role} role is required`)
|
|
314
304
|
record.confirmations.push({ id: randomUUID(), requirementId: record.id, commit: record.currentCommit, role: action.role, participant: action.participant, scope: action.scope, ...(action.scopeId === undefined ? {} : { scopeId: action.scopeId }), status: 'active', createdAt: now })
|
|
315
305
|
if (action.role === 'product' && action.scope === 'version') record.productConfirmedCommit = record.currentCommit
|
|
316
306
|
if (action.role === 'engineering' && action.scope === 'version') record.jointConfirmedCommit = record.currentCommit
|
|
317
|
-
this.persist()
|
|
318
307
|
} else if (action.kind === 'stage.advance') {
|
|
319
|
-
|
|
320
|
-
advance(record, action.participant); this.persist()
|
|
308
|
+
advance(record, action.participant)
|
|
321
309
|
} else if (action.kind === 'ready.generate') {
|
|
322
|
-
|
|
323
|
-
const admission = readyAdmission(record, readiness(
|
|
310
|
+
const body = this.versions.read(record.id, record.currentCommit).markdown
|
|
311
|
+
const admission = readyAdmission(record, readiness(body, record))
|
|
324
312
|
if (admission.error) throw new Error(admission.error)
|
|
325
|
-
const markdown = readyMarkdown(
|
|
313
|
+
const markdown = readyMarkdown(record, body)
|
|
326
314
|
record.readyPackage = { requirementId: record.id, commit: record.currentCommit, packageHash: createHash('sha256').update(markdown).digest('hex'), generatedAt: now, generatedBy: action.participant, markdown }
|
|
327
|
-
enterStage(record, 'ready')
|
|
315
|
+
enterStage(record, 'ready')
|
|
328
316
|
} else if (action.kind === 'participant.register') {
|
|
329
|
-
requireHuman(action.participant)
|
|
330
317
|
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
|
|
318
|
+
if (participant !== undefined) { participant.nickname = action.participant.nickname; participant.role = action.participant.role }
|
|
332
319
|
} else if (action.kind === 'action.assign') {
|
|
333
|
-
requireHuman(action.participant)
|
|
334
320
|
const task = record.actionItems.find(item => item.id === action.actionItemId)
|
|
335
321
|
if (task === undefined) throw new Error('action item not found')
|
|
336
322
|
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')
|
|
@@ -338,67 +324,13 @@ export class CollaborationEngine {
|
|
|
338
324
|
if (action.dueStage !== undefined) task.dueStage = action.dueStage
|
|
339
325
|
if (action.assigneeParticipantId === undefined) delete task.assigneeParticipantId
|
|
340
326
|
else { task.assigneeParticipantId = action.assigneeParticipantId; this.notify(action.assigneeParticipantId, 'assignment', record, 'action', task.id, `${action.participant.nickname} 向你指派了一个待办`) }
|
|
341
|
-
task.updatedAt = now
|
|
327
|
+
task.updatedAt = now
|
|
342
328
|
} else if (action.kind === 'notification.mark-read') {
|
|
343
|
-
requireHuman(action.participant)
|
|
344
329
|
const ids = new Set(action.notificationIds)
|
|
345
330
|
this.state.notifications.filter(item => item.recipientParticipantId === action.participant.participantId && item.requirementId === record.id && ids.has(item.id)).forEach(item => { item.readAt ??= now })
|
|
346
|
-
|
|
347
|
-
|
|
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()
|
|
331
|
+
} else if (isInsightAction(action)) {
|
|
332
|
+
applyInsightAction(this.state, action, now)
|
|
400
333
|
} else if (action.kind === 'downstream.return') {
|
|
401
|
-
requireHuman(action.participant)
|
|
402
334
|
if (action.summary.trim() === '') throw new Error('downstream issue summary is required')
|
|
403
335
|
if (action.affectedSections.length === 0 && action.affectedAcceptanceIds.length === 0) throw new Error('downstream return requires an affected section or AC')
|
|
404
336
|
const item: ReviewItem = {
|
|
@@ -411,29 +343,54 @@ export class CollaborationEngine {
|
|
|
411
343
|
record.actionItems.push(actionForReview(item))
|
|
412
344
|
invalidateAffected(record, item.affectedSections, item.affectedAcceptanceIds)
|
|
413
345
|
delete record.readyPackage
|
|
414
|
-
enterStage(record, 'joint-review')
|
|
415
|
-
|
|
346
|
+
enterStage(record, 'joint-review')
|
|
347
|
+
record.updatedAt = now
|
|
348
|
+
return { requirementId: record.id, task: this.queueReview(record, action.participant, 'change-review', now) }
|
|
416
349
|
}
|
|
417
|
-
return {
|
|
418
|
-
}
|
|
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
|
|
350
|
+
return { requirementId: record.id }
|
|
428
351
|
}
|
|
429
352
|
|
|
430
|
-
private
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
if (
|
|
353
|
+
private changeVersion(record: RequirementRecord, action: VersionAction, now: number): ActionChange {
|
|
354
|
+
const before = this.versions.read(record.id, record.currentCommit).markdown
|
|
355
|
+
let baseCommit = record.currentCommit
|
|
356
|
+
let markdown: string
|
|
357
|
+
let summary: string
|
|
358
|
+
let acceptedPatch: CandidatePatch | undefined
|
|
359
|
+
if (action.kind === 'requirement.rename') {
|
|
360
|
+
const title = action.title.trim()
|
|
361
|
+
if (title === '' || title.length > 120 || /[\r\n]/.test(title)) throw new Error('valid requirement title is required')
|
|
362
|
+
if (title === record.title) return { requirementId: record.id, unchanged: true }
|
|
363
|
+
markdown = /^# .+$/m.test(before) ? before.replace(/^# .+$/m, () => `# ${title}`) : `# ${title}\n\n${before}`
|
|
364
|
+
summary = `Rename requirement: ${title}`
|
|
365
|
+
record.title = title
|
|
366
|
+
} else if (action.kind === 'version.restore') {
|
|
367
|
+
const historical = this.version(record.id, action.commit)
|
|
368
|
+
if (historical.commit === record.currentCommit) throw new Error('selected version is already current')
|
|
369
|
+
markdown = historical.markdown
|
|
370
|
+
summary = action.summary.trim() || `恢复版本 ${historical.commit.slice(0, 8)}`
|
|
371
|
+
} else if (action.kind === 'patch.accept') {
|
|
372
|
+
acceptedPatch = record.patches.find(item => item.id === action.patchId && item.status === 'pending')
|
|
373
|
+
if (acceptedPatch === undefined) throw new Error('pending patch not found')
|
|
374
|
+
baseCommit = acceptedPatch.baseCommit
|
|
375
|
+
markdown = acceptedPatch.proposedMarkdown
|
|
376
|
+
summary = action.summary
|
|
377
|
+
} else {
|
|
378
|
+
baseCommit = action.baseCommit
|
|
379
|
+
markdown = action.markdown
|
|
380
|
+
summary = action.summary
|
|
381
|
+
}
|
|
382
|
+
const spec = this.versions.prepareSave({ requirementId: record.id, baseCommit, markdown, participant: action.participant, summary })
|
|
383
|
+
if (acceptedPatch) {
|
|
384
|
+
acceptedPatch.status = 'accepted'
|
|
385
|
+
retireActionItems(record, 'patch', acceptedPatch.id, 'handled', now)
|
|
386
|
+
for (const item of record.reviewItems.filter(item => acceptedPatch.affectedReviewItemIds.includes(item.id))) {
|
|
387
|
+
item.status = 'resolved'
|
|
388
|
+
item.updatedAt = now
|
|
389
|
+
retireActionItems(record, 'review-item', item.id, 'handled', now)
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
versionChanged(record, before, { commit: spec.commit, markdown }, now)
|
|
393
|
+
return { requirementId: record.id, spec, task: this.queueReview(record, action.participant, 'change-review', now) }
|
|
437
394
|
}
|
|
438
395
|
|
|
439
396
|
private rememberStageConversation(record: RequirementRecord, sessionId: string, stage = record.stage, stageCycle = record.stageCycle): void {
|
|
@@ -447,188 +404,124 @@ export class CollaborationEngine {
|
|
|
447
404
|
this.state.notifications.push({ id: randomUUID(), recipientParticipantId, kind, requirementId: record.id, objectType, objectId, message, deepLink, createdAt: Date.now() })
|
|
448
405
|
}
|
|
449
406
|
|
|
450
|
-
private saveConflict(action: Extract<CollaborationAction, { kind: 'version.save' }
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
407
|
+
private saveConflict(action: Extract<CollaborationAction, { kind: 'version.save' }>, currentCommit: string): SaveConflict | undefined {
|
|
408
|
+
try {
|
|
409
|
+
const baseMarkdown = this.versions.read(action.requirementId, action.baseCommit).markdown
|
|
410
|
+
const currentMarkdown = this.versions.read(action.requirementId, currentCommit).markdown
|
|
411
|
+
return { requirementId: action.requirementId, baseCommit: action.baseCommit, currentCommit, baseMarkdown, currentMarkdown, draftMarkdown: action.markdown, baseToCurrentDiff: textDiff(baseMarkdown, currentMarkdown), baseToDraftDiff: textDiff(baseMarkdown, action.markdown) }
|
|
412
|
+
} catch {
|
|
413
|
+
return undefined
|
|
414
|
+
}
|
|
455
415
|
}
|
|
456
416
|
|
|
457
|
-
private
|
|
458
|
-
const now = Date.now()
|
|
417
|
+
private queueReview(record: RequirementRecord, participant: ParticipantSnapshot, kind: ReviewKind, now: number): AiTask {
|
|
459
418
|
const run: AiReviewRun = { id: randomUUID(), requirementId: record.id, commit: record.currentCommit, kind, status: 'queued', requestedBy: participant, createdAt: now, updatedAt: now }
|
|
419
|
+
if (!this.coordinator) {
|
|
420
|
+
run.status = 'failed'
|
|
421
|
+
run.error = 'AI coordinator unavailable'
|
|
422
|
+
}
|
|
460
423
|
record.aiRuns.push(run)
|
|
461
|
-
|
|
462
|
-
const coordinator = this.coordinator
|
|
463
|
-
if (coordinator === undefined) { this.markAiFailure(record.id, run.id, 'AI coordinator unavailable'); return }
|
|
464
|
-
const view = this.view(record.id)
|
|
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 })
|
|
474
|
-
}, error => this.markAiFailure(record.id, run.id, error instanceof Error ? error.message : String(error)))
|
|
424
|
+
return { kind: 'review', id: run.id }
|
|
475
425
|
}
|
|
476
426
|
|
|
477
|
-
private
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
const
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
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)}`) }
|
|
427
|
+
private launchAiTask(view: RequirementView, task: AiTask): void {
|
|
428
|
+
const coordinator = this.coordinator
|
|
429
|
+
if (coordinator === undefined) return
|
|
430
|
+
const session = view.aiConversations.find(item => item.stage === view.stage && item.stageCycle === view.stageCycle)
|
|
431
|
+
const context = { requirement: view, ...(session ? { sessionId: session.sessionId } : {}) }
|
|
432
|
+
let pending: Promise<string>
|
|
433
|
+
try {
|
|
434
|
+
pending = task.kind === 'review'
|
|
435
|
+
? coordinator.requestReview({ ...context, run: view.aiRuns.find(item => item.id === task.id)! })
|
|
436
|
+
: coordinator.requestCommentReply({ ...context, comment: view.comments.find(item => item.id === task.id)! })
|
|
437
|
+
} catch (error) {
|
|
438
|
+
pending = Promise.reject(error)
|
|
494
439
|
}
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
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')
|
|
440
|
+
void pending.then(
|
|
441
|
+
sessionId => this.recordAiSession(view, task, sessionId),
|
|
442
|
+
error => this.markAiFailure(view.id, task.id, errorMessage(error)),
|
|
443
|
+
).catch(error => console.error('spec-collab: could not persist AI task update', error))
|
|
520
444
|
}
|
|
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
445
|
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
446
|
+
private recordAiSession(view: Pick<RequirementView, 'id' | 'stage' | 'stageCycle'>, task: AiTask, sessionId: string): void {
|
|
447
|
+
this.changeAi(() => {
|
|
448
|
+
const record = this.state.requirements.find(item => item.id === view.id)
|
|
449
|
+
if (record === undefined) return
|
|
450
|
+
const now = Date.now()
|
|
451
|
+
if (task.kind === 'review') {
|
|
452
|
+
const run = record.aiRuns.find(item => item.id === task.id)
|
|
453
|
+
if (run === undefined) return
|
|
454
|
+
if (run.status === 'queued') run.status = 'running'
|
|
455
|
+
run.sessionId = sessionId
|
|
456
|
+
run.updatedAt = now
|
|
457
|
+
} else {
|
|
458
|
+
const comment = record.comments.find(item => item.id === task.id)
|
|
459
|
+
if (comment === undefined) return
|
|
460
|
+
if (comment.aiStatus === 'queued') comment.aiStatus = 'running'
|
|
461
|
+
comment.aiSessionId = sessionId
|
|
462
|
+
comment.updatedAt = now
|
|
463
|
+
}
|
|
464
|
+
this.rememberStageConversation(record, sessionId, view.stage, view.stageCycle)
|
|
465
|
+
return aiEvent(record.id, task.id, task.kind === 'comment')
|
|
466
|
+
})
|
|
541
467
|
}
|
|
542
|
-
}
|
|
543
468
|
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
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) }
|
|
469
|
+
private changeAi(update: () => EventDraft | undefined): void {
|
|
470
|
+
const committed = this.transact(() => ({ value: undefined, event: update() }))
|
|
471
|
+
this.emit(committed.event)
|
|
551
472
|
}
|
|
552
|
-
renameSync(tmp, path)
|
|
553
|
-
}
|
|
554
473
|
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
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 ??= []
|
|
474
|
+
private transact<T>(update: () => { value: T; event?: EventDraft | undefined; spec?: PreparedSpecCommit | undefined }): { value: T; event?: CollaborationEvent } {
|
|
475
|
+
const before = this.state
|
|
476
|
+
this.state = structuredClone(before)
|
|
477
|
+
try {
|
|
478
|
+
const { value, event, spec } = update()
|
|
479
|
+
if (event === undefined) {
|
|
480
|
+
this.state = before
|
|
481
|
+
return { value }
|
|
482
|
+
}
|
|
483
|
+
const revision = before.revision + 1
|
|
484
|
+
this.state.revision = revision
|
|
485
|
+
this.ledger.save(this.state, spec)
|
|
486
|
+
return { value, event: { ...event, revision } }
|
|
487
|
+
} catch (error) {
|
|
488
|
+
this.state = before
|
|
489
|
+
throw error
|
|
579
490
|
}
|
|
580
491
|
}
|
|
581
|
-
return value
|
|
582
|
-
}
|
|
583
492
|
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
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 })
|
|
493
|
+
private emit(event: CollaborationEvent | undefined): void {
|
|
494
|
+
if (event === undefined) return
|
|
495
|
+
for (const listener of this.listeners) {
|
|
496
|
+
try { listener(event) }
|
|
497
|
+
catch { this.listeners.delete(listener) }
|
|
604
498
|
}
|
|
605
499
|
}
|
|
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
500
|
|
|
609
|
-
|
|
610
|
-
if (
|
|
611
|
-
try { const url = new URL(value); return url.protocol === 'http:' || url.protocol === 'https:' } catch { return false }
|
|
501
|
+
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 }
|
|
502
|
+
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 }
|
|
612
503
|
}
|
|
613
504
|
|
|
614
|
-
function
|
|
615
|
-
return
|
|
505
|
+
function errorMessage(error: unknown): string {
|
|
506
|
+
return error instanceof Error ? error.message : String(error)
|
|
616
507
|
}
|
|
617
|
-
|
|
618
|
-
|
|
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')
|
|
508
|
+
|
|
509
|
+
function aiEvent(requirementId: string, objectId: string, comment = false): EventDraft {
|
|
510
|
+
return { requirementId, objectId, types: comment ? ['ai.status', 'comment.changed', 'metrics.changed'] : ['ai.status', 'metrics.changed'] }
|
|
628
511
|
}
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
512
|
+
|
|
513
|
+
function eventForAction(action: CollaborationAction, change: ActionChange): EventDraft {
|
|
514
|
+
const types = new Set<CollaborationEvent['types'][number]>(['metrics.changed'])
|
|
515
|
+
if (action.kind.startsWith('comment.')) types.add('comment.changed')
|
|
516
|
+
if (action.kind === 'comment.create' || action.kind === 'comment.reply') {
|
|
517
|
+
if ((action.mentions?.length ?? 0) > 0) types.add('mention.created')
|
|
518
|
+
types.add('notification.changed')
|
|
519
|
+
}
|
|
520
|
+
if (action.kind === 'comment.resolve' || action.kind === 'comment.reopen') types.add('notification.changed')
|
|
521
|
+
if (action.kind === 'action.assign') { types.add('assignment.changed'); types.add('notification.changed') }
|
|
522
|
+
if (action.kind === 'notification.mark-read') types.add('notification.changed')
|
|
523
|
+
if (change.task) types.add('ai.status')
|
|
524
|
+
return { types: [...types], requirementId: change.requirementId, ...(change.task ? { objectId: change.task.id } : {}) }
|
|
632
525
|
}
|
|
633
526
|
|
|
634
527
|
function validMentions(values: string[] | undefined, participants: ParticipantSnapshot[]): string[] {
|
|
@@ -636,36 +529,14 @@ function validMentions(values: string[] | undefined, participants: ParticipantSn
|
|
|
636
529
|
return [...new Set(values ?? [])].filter(value => registered.has(value))
|
|
637
530
|
}
|
|
638
531
|
|
|
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
532
|
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
533
|
return {
|
|
663
534
|
openReviewCount: record.reviewItems.filter(item => item.commit === record.currentCommit && !['resolved', 'invalidated'].includes(item.status)).length,
|
|
664
535
|
openCommentCount: record.comments.filter(item => item.commit === record.currentCommit && item.status === 'open').length,
|
|
665
536
|
pendingActionCount: record.actionItems.filter(item => item.status === 'pending').length,
|
|
666
537
|
activeDecisionCount: record.decisions.filter(item => item.status === 'active').length,
|
|
667
538
|
riskCount: record.reviewItems.filter(item => item.commit === record.currentCommit && ['blocking', 'major'].includes(item.severity) && !['resolved', 'invalidated'].includes(item.status)).length,
|
|
668
|
-
|
|
539
|
+
...insightMetrics(state, record.id),
|
|
669
540
|
}
|
|
670
541
|
}
|
|
671
542
|
|
|
@@ -720,84 +591,3 @@ function assertChineseFeedback(...values: string[]): void {
|
|
|
720
591
|
}
|
|
721
592
|
function requireHuman(participant: ParticipantSnapshot): void { if (participant.kind !== 'human') throw new Error('human participant is required') }
|
|
722
593
|
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 } }
|
|
723
|
-
function enterStage(record: RequirementRecord, stage: RequirementRecord['stage']): void {
|
|
724
|
-
if (record.stage === stage) return
|
|
725
|
-
record.stage = stage
|
|
726
|
-
record.stageCycle += 1
|
|
727
|
-
}
|
|
728
|
-
function advance(record: RequirementRecord, participant: ParticipantSnapshot): void {
|
|
729
|
-
if (record.stage === 'product-review') {
|
|
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')
|
|
731
|
-
if (!hasCompletedCurrentReview(record, 'product-second')) throw new Error('product second review is required')
|
|
732
|
-
enterStage(record, 'product-confirmation'); return
|
|
733
|
-
}
|
|
734
|
-
if (record.stage === 'product-confirmation') {
|
|
735
|
-
if (participant.role !== 'product' || !hasVersionConfirmation(record, 'product')) throw new Error('product must confirm the current version')
|
|
736
|
-
enterStage(record, 'joint-review'); return
|
|
737
|
-
}
|
|
738
|
-
throw new Error('stage cannot advance directly')
|
|
739
|
-
}
|
|
740
|
-
function sections(markdown: string): Map<string, string> { const result = new Map<string, string>(); let heading = ''; for (const line of markdown.split('\n')) { if (/^##\s+/.test(line)) { heading = line.replace(/^##\s+/, '').trim(); result.set(heading, '') } else if (heading) result.set(heading, `${result.get(heading) ?? ''}\n${line}`) } return result }
|
|
741
|
-
function acceptance(markdown: string): Map<string, string> { const result = new Map<string, string>(); for (const match of markdown.matchAll(/\*\*(AC-[A-Za-z0-9-]+)(?:\s+[^*]+)?\*\*\s*[::]\s*(.+)/g)) result.set(match[1]!, match[2]!.trim()); return result }
|
|
742
|
-
function changedScopes(before: string, after: string): { sections: string[]; acceptanceIds: string[] } { const a = sections(before); const b = sections(after); const sectionNames = new Set([...a.keys(), ...b.keys()]); const acA = acceptance(before); const acB = acceptance(after); const acNames = new Set([...acA.keys(), ...acB.keys()]); return { sections: [...sectionNames].filter(key => a.get(key) !== b.get(key)), acceptanceIds: [...acNames].filter(key => acA.get(key) !== acB.get(key)) } }
|
|
743
|
-
function intersects(left: string[], right: string[]): boolean { return left.some(item => right.includes(item)) }
|
|
744
|
-
function normalizeAnchorText(value: string): string { return value.replace(/[`*_>#\[\]()~-]/g, '').replace(/\s+/g, '').toLocaleLowerCase() }
|
|
745
|
-
function headingForLine(lines: string[], index: number): string | undefined {
|
|
746
|
-
for (let cursor = index; cursor >= 0; cursor -= 1) {
|
|
747
|
-
const match = /^#{1,4}\s+(.+)$/.exec(lines[cursor] ?? '')
|
|
748
|
-
if (match?.[1]) return match[1].trim()
|
|
749
|
-
}
|
|
750
|
-
return undefined
|
|
751
|
-
}
|
|
752
|
-
function decisionScopeAnchors(markdown: string, affectedSections: string[], affectedAcceptanceIds: string[]): DecisionSourceAnchor[] {
|
|
753
|
-
const anchors: DecisionSourceAnchor[] = []
|
|
754
|
-
const sectionMap = sections(markdown)
|
|
755
|
-
for (const section of affectedSections.map(value => value.trim()).filter(Boolean)) {
|
|
756
|
-
const quote = sectionMap.get(section)?.split('\n').map(line => line.trim()).find(line => line && !/^#+\s+/.test(line))
|
|
757
|
-
if (quote) anchors.push({ heading: section, quote })
|
|
758
|
-
}
|
|
759
|
-
const lines = markdown.split('\n')
|
|
760
|
-
for (const acceptanceId of affectedAcceptanceIds.map(value => value.trim()).filter(Boolean)) {
|
|
761
|
-
const index = lines.findIndex(line => normalizeAnchorText(line).includes(normalizeAnchorText(acceptanceId)))
|
|
762
|
-
if (index >= 0) {
|
|
763
|
-
const heading = headingForLine(lines, index)
|
|
764
|
-
anchors.push({ ...(heading ? { heading } : {}), quote: lines[index]!.trim() })
|
|
765
|
-
}
|
|
766
|
-
}
|
|
767
|
-
return anchors
|
|
768
|
-
}
|
|
769
|
-
function decisionAnchorStillExists(markdown: string, anchor: DecisionSourceAnchor): boolean {
|
|
770
|
-
const quote = normalizeAnchorText(anchor.quote)
|
|
771
|
-
if (!quote) return false
|
|
772
|
-
const sectionMap = sections(markdown)
|
|
773
|
-
const candidates = anchor.heading?.trim() ? [sectionMap.get(anchor.heading.trim()) ?? ''] : [markdown]
|
|
774
|
-
const context = normalizeAnchorText(`${anchor.prefix ?? ''}${anchor.quote}${anchor.suffix ?? ''}`)
|
|
775
|
-
return candidates.some(candidate => {
|
|
776
|
-
const normalized = normalizeAnchorText(candidate)
|
|
777
|
-
return normalized.includes(context) || normalized.includes(quote)
|
|
778
|
-
})
|
|
779
|
-
}
|
|
780
|
-
function invalidateAffected(record: RequirementRecord, changedSections: string[], changedAcceptanceIds: string[], currentMarkdown?: string): void {
|
|
781
|
-
for (const confirmation of record.confirmations) {
|
|
782
|
-
if (confirmation.status !== 'active') continue
|
|
783
|
-
const affected = confirmation.scope === 'version' || (confirmation.scope === 'section' && confirmation.scopeId !== undefined && changedSections.includes(confirmation.scopeId)) || (confirmation.scope === 'acceptance-criterion' && confirmation.scopeId !== undefined && changedAcceptanceIds.includes(confirmation.scopeId))
|
|
784
|
-
if (affected) { confirmation.status = 'invalidated'; record.actionItems.push({ id: randomUUID(), requirementId: record.id, sourceType: 'confirmation', sourceId: confirmation.id, type: 'reconfirm', assigneeRole: confirmation.role, blocking: true, status: 'pending', dueStage: record.stage, createdAt: Date.now(), updatedAt: Date.now() }) }
|
|
785
|
-
}
|
|
786
|
-
record.reviewItems.filter(item => item.status === 'resolved' && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach(item => { item.status = 'invalidated'; item.updatedAt = Date.now() })
|
|
787
|
-
record.decisions.filter(item => item.status === 'active' && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach(item => { item.status = 'invalidated' })
|
|
788
|
-
if (currentMarkdown !== undefined) record.decisions.filter(item => item.status === 'active' && item.sourceAnchors?.some(anchor => !decisionAnchorStillExists(currentMarkdown, anchor))).forEach(item => { item.status = 'invalidated' })
|
|
789
|
-
}
|
|
790
|
-
export function readiness(markdown: string, record: RequirementRecord): ReadinessCheck[] {
|
|
791
|
-
const sectionMap = sections(markdown); const ac = acceptance(markdown)
|
|
792
|
-
const meaningful = (name: string): boolean => { const value = sectionMap.get(name)?.replace(/<!--.*?-->/gs, '').trim() ?? ''; return value.length >= 12 && !/待澄清|待补充|TODO/i.test(value) }
|
|
793
|
-
const blockers = record.reviewItems.filter(item => item.commit === record.currentCommit && item.severity === 'blocking' && !['resolved', 'non-blocking-verify'].includes(item.status)).map(item => item.statement)
|
|
794
|
-
return [
|
|
795
|
-
{ key: 'goal', passed: meaningful('目标与用户结果'), reasons: meaningful('目标与用户结果') ? [] : ['缺少可观察的目标与用户结果'] },
|
|
796
|
-
{ key: 'acceptance', passed: ac.size > 0 && [...ac.values()].every(value => !/待澄清|待补充|TODO/i.test(value)), reasons: ac.size === 0 ? ['缺少稳定 AC ID 与可判定结果'] : [...ac.values()].some(value => /待澄清|待补充|TODO/i.test(value)) ? ['验收标准仍含占位内容'] : [] },
|
|
797
|
-
{ key: 'scope', passed: meaningful('范围与非范围'), reasons: meaningful('范围与非范围') ? [] : ['范围与非范围不完整'] },
|
|
798
|
-
{ key: 'semantics', passed: meaningful('业务术语与规则'), reasons: meaningful('业务术语与规则') ? [] : ['关键术语和规则不完整'] },
|
|
799
|
-
{ key: 'evidence', passed: record.sources.every(source => source.accessStatus !== 'missing') && blockers.length === 0, reasons: [...record.sources.filter(source => source.accessStatus === 'missing').map(source => `来源不可访问:${source.label}`), ...blockers] },
|
|
800
|
-
{ key: 'test-constraints', passed: meaningful('测试约束'), reasons: meaningful('测试约束') ? [] : ['测试环境、账号、权限或 fixture 约束不完整'] },
|
|
801
|
-
]
|
|
802
|
-
}
|
|
803
|
-
function readyMarkdown(view: RequirementView): string { const open = view.reviewItems.filter(item => item.status === 'non-blocking-verify'); const sourceStatus = { available: '可查阅', unverified: '待核对', missing: '待补充' } as const; return [`# 就绪需求:${view.title}`, '', '## 版本信息', '', `- 需求编号:${view.id}`, `- 文档版本:${view.currentCommit}`, `- 产品确认:${view.confirmations.filter(item => item.role === 'product' && item.status === 'active').map(item => item.participant.nickname).join('、')}`, `- 研发确认:${view.confirmations.filter(item => item.role === 'engineering' && item.status === 'active').map(item => item.participant.nickname).join('、')}`, '', view.version.markdown, '', '## 已确认决策', ...view.decisions.filter(item => item.status === 'active').map(item => `- ${item.question}:${item.decision}(原因:${item.rationale})`), '', '## 参考资料', ...view.sources.map(source => `- [${sourceStatus[source.accessStatus]}] ${source.label}${source.stableId ? `:${source.stableId}` : ''}${source.version ? `(版本:${source.version})` : ''}`), '', '## 待确认问题', ...open.map(item => `- ${item.question};负责人:${item.ownerParticipantId ?? (item.ownerRole === 'product' ? '产品' : '研发')};影响:${item.impact}`), ''].join('\n') }
|