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