dsh-spec-collab 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +28 -7
  2. package/docs/assets/demo-01-workspace.png +0 -0
  3. package/docs/assets/demo-02-ai-review.png +0 -0
  4. package/docs/assets/demo-03-patches.png +0 -0
  5. package/docs/assets/demo-04-decisions.png +0 -0
  6. package/docs/assets/demo-05-ready.png +0 -0
  7. package/docs/experience-review-checklist-2026-08-24.md +72 -45
  8. package/docs/insight-import-template.csv +3 -0
  9. package/docs/insight-import-template.md +19 -0
  10. package/docs/migration-v3.md +23 -0
  11. package/lib/client.js +10825 -1163
  12. package/lib/index.js +1279 -89
  13. package/lib/types/client/AccessibleDialog.d.ts +9 -0
  14. package/lib/types/client/AccessibleDialog.d.ts.map +1 -0
  15. package/lib/types/client/SpecWorkbench.d.ts +42 -2
  16. package/lib/types/client/SpecWorkbench.d.ts.map +1 -1
  17. package/lib/types/client/api.d.ts +26 -3
  18. package/lib/types/client/api.d.ts.map +1 -1
  19. package/lib/types/client/drafts.d.ts +8 -0
  20. package/lib/types/client/drafts.d.ts.map +1 -0
  21. package/lib/types/client/mount.d.ts.map +1 -1
  22. package/lib/types/client/review-anchors.d.ts.map +1 -1
  23. package/lib/types/engine.d.ts +37 -3
  24. package/lib/types/engine.d.ts.map +1 -1
  25. package/lib/types/git-store.d.ts +6 -0
  26. package/lib/types/git-store.d.ts.map +1 -1
  27. package/lib/types/protocol.d.ts +245 -10
  28. package/lib/types/protocol.d.ts.map +1 -1
  29. package/lib/types/review-runtime.d.ts +6 -0
  30. package/lib/types/review-runtime.d.ts.map +1 -1
  31. package/lib/types/routes.d.ts.map +1 -1
  32. package/lib/types/structured-diff.d.ts +3 -0
  33. package/lib/types/structured-diff.d.ts.map +1 -0
  34. package/package.json +5 -2
  35. package/src/client/AccessibleDialog.tsx +42 -0
  36. package/src/client/SpecWorkbench.tsx +776 -87
  37. package/src/client/api.ts +8 -3
  38. package/src/client/drafts.ts +51 -0
  39. package/src/client/mount.tsx +11 -6
  40. package/src/client/review-anchors.ts +1 -0
  41. package/src/client/workbench.module.css +223 -79
  42. package/src/engine.ts +439 -41
  43. package/src/git-store.ts +87 -18
  44. package/src/index.ts +1 -1
  45. package/src/protocol.ts +64 -13
  46. package/src/review-runtime.ts +39 -11
  47. package/src/routes.ts +33 -4
  48. package/src/structured-diff.ts +75 -0
  49. package/src/tools.ts +1 -1
package/lib/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { homedir } from "node:os";
2
- import { dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
2
+ import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
3
3
  import Schema from "schemastery";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
+ import { closeSync, copyFileSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
6
6
  import { execFileSync } from "node:child_process";
7
7
  import { readFile, readdir, stat } from "node:fs/promises";
8
8
  import { defineTool } from "@deepseek-ai/dsh-tools";
@@ -17,6 +17,10 @@ var VersionConflictError = class extends Error {
17
17
  };
18
18
  var GitRequirementStore = class {
19
19
  root;
20
+ versionCache = /* @__PURE__ */ new Map();
21
+ headCache = /* @__PURE__ */ new Map();
22
+ historyCache = /* @__PURE__ */ new Map();
23
+ commitBaseUrl;
20
24
  constructor(root) {
21
25
  this.root = root;
22
26
  this.ensureRepository();
@@ -25,33 +29,57 @@ var GitRequirementStore = class {
25
29
  const requirementId = `${slug(input.title)}-${randomUUID().slice(0, 8)}`;
26
30
  const markdown = initialSpec(input.title, input.rawRequirement, input.sources);
27
31
  const path = this.specPath(requirementId);
28
- mkdirSync(dirname(path), { recursive: true });
29
- writeFileSync(path, markdown, "utf8");
30
- const commit = this.commit(requirementId, input.participant, "Create requirement");
31
- return {
32
- requirementId,
33
- version: this.read(requirementId, commit)
34
- };
32
+ try {
33
+ mkdirSync(dirname(path), { recursive: true });
34
+ writeFileSync(path, markdown, "utf8");
35
+ const commit = this.commit(requirementId, input.participant, "Create requirement");
36
+ return {
37
+ requirementId,
38
+ version: this.rememberCommittedVersion(requirementId, commit, markdown, input.participant, "Create requirement")
39
+ };
40
+ } catch (error) {
41
+ this.git([
42
+ "reset",
43
+ "--",
44
+ this.relativeSpecPath(requirementId)
45
+ ], true);
46
+ rmSync(dirname(path), {
47
+ recursive: true,
48
+ force: true
49
+ });
50
+ throw error;
51
+ }
35
52
  }
36
53
  save(input) {
37
54
  const current = this.head(input.requirementId);
38
55
  if (current !== input.baseCommit) throw new VersionConflictError(current);
39
- if (readFileSync(this.specPath(input.requirementId), "utf8") !== this.read(input.requirementId, current).markdown) throw new Error("spec has external uncommitted changes");
56
+ const onDisk = readFileSync(this.specPath(input.requirementId), "utf8");
57
+ if (onDisk !== this.read(input.requirementId, current).markdown) throw new Error("spec has external uncommitted changes");
40
58
  if (input.summary.trim() === "") throw new Error("change summary is required");
41
59
  if (input.markdown.length > 2e6) throw new Error("spec exceeds 2 MB");
42
- writeFileSync(this.specPath(input.requirementId), input.markdown, "utf8");
43
- this.git(["add", this.relativeSpecPath(input.requirementId)]);
44
- if (this.git([
45
- "diff",
46
- "--cached",
47
- "--quiet"
48
- ], true).status === 0) throw new Error("no changes to save");
49
- const commit = this.commitStaged(input.participant, input.summary.trim());
50
- return this.read(input.requirementId, commit);
60
+ if (input.markdown === onDisk) throw new Error("no changes to save");
61
+ const relativePath = this.relativeSpecPath(input.requirementId);
62
+ try {
63
+ writeFileSync(this.specPath(input.requirementId), input.markdown, "utf8");
64
+ this.git(["add", relativePath]);
65
+ const commit = this.commitStaged(input.participant, input.summary.trim());
66
+ return this.rememberCommittedVersion(input.requirementId, commit, input.markdown, input.participant, input.summary.trim(), current);
67
+ } catch (error) {
68
+ writeFileSync(this.specPath(input.requirementId), onDisk, "utf8");
69
+ this.git([
70
+ "reset",
71
+ "--",
72
+ relativePath
73
+ ], true);
74
+ throw error;
75
+ }
51
76
  }
52
77
  read(requirementId, commit) {
53
78
  assertRequirementId(requirementId);
54
79
  const resolved = commit ?? this.head(requirementId);
80
+ const cacheKey = `${requirementId}:${resolved}`;
81
+ const cached = this.versionCache.get(cacheKey);
82
+ if (cached !== void 0) return structuredClone(cached);
55
83
  const markdown = this.gitText(["show", `${resolved}:${this.relativeSpecPath(requirementId)}`]);
56
84
  const [sha = resolved, parents = "", seconds = "0", nickname = "unknown", email = "", ...bodyParts] = this.gitText([
57
85
  "show",
@@ -62,7 +90,7 @@ var GitRequirementStore = class {
62
90
  const body = bodyParts.join("").trim();
63
91
  const role = /DSH-Role:\s*(product|engineering)/.exec(body)?.[1];
64
92
  const summary = body.split("\n")[0] ?? "Saved version";
65
- return {
93
+ const version = {
66
94
  commit: sha,
67
95
  ...parents.split(" ")[0] ? { parentCommit: parents.split(" ")[0] } : {},
68
96
  markdown,
@@ -75,10 +103,14 @@ var GitRequirementStore = class {
75
103
  summary,
76
104
  createdAt: Number(seconds) * 1e3
77
105
  };
106
+ this.versionCache.set(cacheKey, version);
107
+ return structuredClone(version);
78
108
  }
79
109
  history(requirementId) {
80
110
  assertRequirementId(requirementId);
81
- return this.gitText([
111
+ const cached = this.historyCache.get(requirementId);
112
+ if (cached !== void 0) return structuredClone(cached);
113
+ const history = this.gitText([
82
114
  "log",
83
115
  "--format=%H%x1f%P%x1f%at%x1f%an%x1f%ae%x1f%B%x1e",
84
116
  "--",
@@ -100,6 +132,8 @@ var GitRequirementStore = class {
100
132
  createdAt: Number(seconds) * 1e3
101
133
  };
102
134
  });
135
+ this.historyCache.set(requirementId, history);
136
+ return structuredClone(history);
103
137
  }
104
138
  diff(requirementId, baseCommit, headCommit) {
105
139
  assertRequirementId(requirementId);
@@ -111,25 +145,78 @@ var GitRequirementStore = class {
111
145
  this.relativeSpecPath(requirementId)
112
146
  ]);
113
147
  }
148
+ commitUrl(commit) {
149
+ if (!/^[a-f0-9]{40}$/.test(commit)) return void 0;
150
+ if (this.commitBaseUrl !== void 0) return this.commitBaseUrl === null ? void 0 : `${this.commitBaseUrl}/commit/${commit}`;
151
+ let origin;
152
+ try {
153
+ origin = this.gitText([
154
+ "config",
155
+ "--get",
156
+ "remote.origin.url"
157
+ ]).trim();
158
+ } catch {
159
+ this.commitBaseUrl = null;
160
+ return;
161
+ }
162
+ if (origin === "") {
163
+ this.commitBaseUrl = null;
164
+ return;
165
+ }
166
+ const scp = /^git@([^:]+):(.+)$/.exec(origin);
167
+ const normalized = scp ? `https://${scp[1]}/${scp[2]}` : origin.replace(/^ssh:\/\/git@/, "https://");
168
+ if (!/^https?:\/\//.test(normalized)) {
169
+ this.commitBaseUrl = null;
170
+ return;
171
+ }
172
+ try {
173
+ const url = new URL(normalized);
174
+ url.username = "";
175
+ url.password = "";
176
+ this.commitBaseUrl = url.toString().replace(/\.git$/, "").replace(/\/$/, "");
177
+ } catch {
178
+ this.commitBaseUrl = null;
179
+ return;
180
+ }
181
+ return `${this.commitBaseUrl}/commit/${commit}`;
182
+ }
114
183
  remove(requirementId, participant) {
115
184
  assertRequirementId(requirementId);
116
185
  if (!existsSync(this.specPath(requirementId))) throw new Error("requirement spec not found");
117
- this.git([
118
- "rm",
119
- "-r",
120
- `requirements/${requirementId}`
121
- ]);
122
- this.commitStaged(participant, "Delete requirement");
186
+ const relativeDirectory = `requirements/${requirementId}`;
187
+ try {
188
+ this.git([
189
+ "rm",
190
+ "-r",
191
+ relativeDirectory
192
+ ]);
193
+ this.commitStaged(participant, "Delete requirement");
194
+ } catch (error) {
195
+ this.git([
196
+ "restore",
197
+ "--staged",
198
+ "--worktree",
199
+ relativeDirectory
200
+ ], true);
201
+ throw error;
202
+ }
203
+ this.headCache.delete(requirementId);
204
+ this.historyCache.delete(requirementId);
205
+ for (const key of this.versionCache.keys()) if (key.startsWith(`${requirementId}:`)) this.versionCache.delete(key);
123
206
  }
124
207
  head(requirementId) {
125
208
  assertRequirementId(requirementId);
126
- return this.gitText([
209
+ const cached = this.headCache.get(requirementId);
210
+ if (cached !== void 0) return cached;
211
+ const resolved = this.gitText([
127
212
  "log",
128
213
  "-1",
129
214
  "--format=%H",
130
215
  "--",
131
216
  this.relativeSpecPath(requirementId)
132
217
  ]).trim();
218
+ this.headCache.set(requirementId, resolved);
219
+ return resolved;
133
220
  }
134
221
  commit(requirementId, participant, summary) {
135
222
  this.git(["add", this.relativeSpecPath(requirementId)]);
@@ -144,7 +231,12 @@ var GitRequirementStore = class {
144
231
  GIT_COMMITTER_EMAIL: `${participant.participantId}@dsh.local`
145
232
  };
146
233
  execFileSync("git", [
234
+ "-c",
235
+ "commit.gpgsign=false",
236
+ "-c",
237
+ "core.hooksPath=/dev/null",
147
238
  "commit",
239
+ "--no-verify",
148
240
  "-m",
149
241
  summary,
150
242
  "-m",
@@ -156,6 +248,22 @@ var GitRequirementStore = class {
156
248
  });
157
249
  return this.gitText(["rev-parse", "HEAD"]).trim();
158
250
  }
251
+ rememberCommittedVersion(requirementId, commit, markdown, participant, summary, parentCommit) {
252
+ const version = {
253
+ commit,
254
+ ...parentCommit ? { parentCommit } : {},
255
+ markdown,
256
+ author: participant,
257
+ summary,
258
+ createdAt: Date.now()
259
+ };
260
+ this.headCache.set(requirementId, commit);
261
+ this.versionCache.set(`${requirementId}:${commit}`, version);
262
+ const metadata = withoutMarkdown(version);
263
+ const history = this.historyCache.get(requirementId);
264
+ this.historyCache.set(requirementId, history === void 0 ? [metadata] : [metadata, ...history]);
265
+ return structuredClone(version);
266
+ }
159
267
  ensureRepository() {
160
268
  mkdirSync(this.root, {
161
269
  recursive: true,
@@ -197,6 +305,10 @@ var GitRequirementStore = class {
197
305
  }
198
306
  }
199
307
  };
308
+ function withoutMarkdown(version) {
309
+ const { markdown: _markdown, ...metadata } = version;
310
+ return metadata;
311
+ }
200
312
  function slug(title) {
201
313
  return title.toLowerCase().trim().replace(/[^a-z0-9\u4e00-\u9fff]+/g, "-").replace(/^-|-$/g, "").slice(0, 48) || "requirement";
202
314
  }
@@ -258,23 +370,144 @@ function parseEnvelope(value) {
258
370
  };
259
371
  }
260
372
  //#endregion
373
+ //#region src/structured-diff.ts
374
+ function buildStructuredDiff(before, after, baseLabel = "原版本", headLabel = "新版本") {
375
+ const operations = myers(before.split("\n"), after.split("\n"));
376
+ let oldLine = 0;
377
+ let newLine = 0;
378
+ const lines = operations.map((operation) => {
379
+ if (operation.type !== "added") oldLine += 1;
380
+ if (operation.type !== "removed") newLine += 1;
381
+ return {
382
+ type: operation.type,
383
+ ...operation.type === "added" ? {} : { oldLine },
384
+ ...operation.type === "removed" ? {} : { newLine },
385
+ text: operation.text
386
+ };
387
+ });
388
+ const changed = lines.flatMap((line, index) => line.type === "context" ? [] : [index]);
389
+ if (changed.length === 0) return {
390
+ baseLabel,
391
+ headLabel,
392
+ added: 0,
393
+ removed: 0,
394
+ hunks: []
395
+ };
396
+ const ranges = [];
397
+ for (const index of changed) {
398
+ const start = Math.max(0, index - 3);
399
+ const end = Math.min(lines.length - 1, index + 3);
400
+ const previous = ranges.at(-1);
401
+ if (previous !== void 0 && start <= previous.end + 1) previous.end = Math.max(previous.end, end);
402
+ else ranges.push({
403
+ start,
404
+ end
405
+ });
406
+ }
407
+ return {
408
+ baseLabel,
409
+ headLabel,
410
+ added: lines.filter((line) => line.type === "added").length,
411
+ removed: lines.filter((line) => line.type === "removed").length,
412
+ hunks: ranges.map((range, index) => {
413
+ const visible = lines.slice(range.start, range.end + 1);
414
+ const collapsedBeforeLines = index === 0 ? lines.slice(0, range.start) : [];
415
+ const collapsedAfterLines = lines.slice(range.end + 1, ranges[index + 1]?.start ?? lines.length);
416
+ return {
417
+ id: `hunk-${index + 1}`,
418
+ oldStart: visible.find((line) => line.oldLine !== void 0)?.oldLine ?? 0,
419
+ newStart: visible.find((line) => line.newLine !== void 0)?.newLine ?? 0,
420
+ lines: visible,
421
+ collapsedBefore: collapsedBeforeLines.length,
422
+ collapsedAfter: collapsedAfterLines.length,
423
+ collapsedBeforeLines,
424
+ collapsedAfterLines
425
+ };
426
+ })
427
+ };
428
+ }
429
+ function myers(left, right) {
430
+ const trace = [];
431
+ let frontier = /* @__PURE__ */ new Map([[1, 0]]);
432
+ for (let distance = 0; distance <= left.length + right.length; distance += 1) {
433
+ trace.push(new Map(frontier));
434
+ const next = /* @__PURE__ */ new Map();
435
+ for (let diagonal = -distance; diagonal <= distance; diagonal += 2) {
436
+ let x = diagonal === -distance || diagonal !== distance && (frontier.get(diagonal - 1) ?? -1) < (frontier.get(diagonal + 1) ?? -1) ? frontier.get(diagonal + 1) ?? 0 : (frontier.get(diagonal - 1) ?? 0) + 1;
437
+ let y = x - diagonal;
438
+ while (x < left.length && y < right.length && left[x] === right[y]) {
439
+ x += 1;
440
+ y += 1;
441
+ }
442
+ next.set(diagonal, x);
443
+ if (x >= left.length && y >= right.length) return backtrack(trace, left, right);
444
+ }
445
+ frontier = next;
446
+ }
447
+ return [];
448
+ }
449
+ function backtrack(trace, left, right) {
450
+ let x = left.length;
451
+ let y = right.length;
452
+ const result = [];
453
+ for (let distance = trace.length - 1; distance >= 0; distance -= 1) {
454
+ const frontier = trace[distance];
455
+ const diagonal = x - y;
456
+ const previousDiagonal = diagonal === -distance || diagonal !== distance && (frontier.get(diagonal - 1) ?? -1) < (frontier.get(diagonal + 1) ?? -1) ? diagonal + 1 : diagonal - 1;
457
+ const previousX = frontier.get(previousDiagonal) ?? 0;
458
+ const previousY = previousX - previousDiagonal;
459
+ while (x > previousX && y > previousY) {
460
+ result.push({
461
+ type: "context",
462
+ text: left[x - 1]
463
+ });
464
+ x -= 1;
465
+ y -= 1;
466
+ }
467
+ if (distance === 0) break;
468
+ if (x === previousX) {
469
+ result.push({
470
+ type: "added",
471
+ text: right[y - 1]
472
+ });
473
+ y -= 1;
474
+ } else {
475
+ result.push({
476
+ type: "removed",
477
+ text: left[x - 1]
478
+ });
479
+ x -= 1;
480
+ }
481
+ }
482
+ return result.reverse();
483
+ }
484
+ //#endregion
261
485
  //#region src/engine.ts
262
486
  const emptyState = () => ({
263
- schemaVersion: 2,
487
+ schemaVersion: 3,
264
488
  revision: 0,
265
489
  participants: [],
266
- requirements: []
490
+ requirements: [],
491
+ companies: [],
492
+ customers: [],
493
+ feedbackSources: [],
494
+ insights: [],
495
+ insightLinks: [],
496
+ notifications: []
267
497
  });
268
498
  var CollaborationEngine = class {
269
499
  eventPath;
270
500
  versions;
501
+ options;
271
502
  state;
272
503
  coordinator;
273
504
  listeners = /* @__PURE__ */ new Set();
274
505
  seen = /* @__PURE__ */ new Map();
275
- constructor(eventPath, versions) {
506
+ eventContext;
507
+ constructor(eventPath, versions, options = {}) {
276
508
  this.eventPath = eventPath;
277
509
  this.versions = versions;
510
+ this.options = options;
278
511
  this.state = this.load();
279
512
  }
280
513
  setCoordinator(coordinator) {
@@ -283,6 +516,42 @@ var CollaborationEngine = class {
283
516
  snapshot() {
284
517
  return structuredClone(this.state);
285
518
  }
519
+ directory() {
520
+ return structuredClone(this.state.participants).sort((left, right) => left.nickname.localeCompare(right.nickname, "zh-CN"));
521
+ }
522
+ notifications(participantId, page = 1, pageSize = 50) {
523
+ const rows = this.state.notifications.filter((item) => item.recipientParticipantId === participantId).sort((left, right) => right.createdAt - left.createdAt);
524
+ const safePage = Number.isFinite(page) ? Math.max(1, Math.trunc(page)) : 1;
525
+ const safePageSize = Number.isFinite(pageSize) ? Math.min(100, Math.max(1, Math.trunc(pageSize))) : 50;
526
+ const start = (safePage - 1) * safePageSize;
527
+ return {
528
+ items: structuredClone(rows.slice(start, start + safePageSize)),
529
+ total: rows.length,
530
+ unread: rows.filter((item) => item.readAt === void 0).length
531
+ };
532
+ }
533
+ insights(query = {}) {
534
+ const linkedIds = query.requirementId === void 0 ? void 0 : new Set(this.state.insightLinks.filter((link) => link.requirementId === query.requirementId).map((link) => link.insightId));
535
+ const rows = this.state.insights.filter((item) => {
536
+ const companyId = item.companyId ?? (item.customerId ? this.state.customers.find((customer) => customer.id === item.customerId)?.companyId : void 0);
537
+ return (linkedIds === void 0 || linkedIds.has(item.id)) && (query.customerId === void 0 || item.customerId === query.customerId) && (query.companyId === void 0 || companyId === query.companyId) && (query.sourceId === void 0 || item.sourceId === query.sourceId) && (query.importance === void 0 || item.importance === query.importance);
538
+ }).sort((left, right) => right.capturedAt - left.capturedAt);
539
+ const pageSize = Math.min(100, Math.max(1, query.pageSize ?? 50));
540
+ const start = Math.max(0, (query.page ?? 1) - 1) * pageSize;
541
+ const page = rows.slice(start, start + pageSize);
542
+ const ids = new Set(page.map((item) => item.id));
543
+ const customerIds = new Set(page.flatMap((item) => item.customerId ? [item.customerId] : []));
544
+ const companyIds = new Set(page.flatMap((item) => item.companyId ? [item.companyId] : []));
545
+ for (const customer of this.state.customers.filter((item) => customerIds.has(item.id))) if (customer.companyId) companyIds.add(customer.companyId);
546
+ return {
547
+ items: structuredClone(page),
548
+ total: rows.length,
549
+ links: structuredClone(this.state.insightLinks.filter((item) => ids.has(item.insightId))),
550
+ customers: structuredClone(this.state.customers.filter((item) => customerIds.has(item.id))),
551
+ companies: structuredClone(this.state.companies.filter((item) => companyIds.has(item.id))),
552
+ sources: structuredClone(this.state.feedbackSources.filter((item) => page.some((insight) => insight.sourceId === item.id)))
553
+ };
554
+ }
286
555
  subscribe(listener) {
287
556
  this.listeners.add(listener);
288
557
  return () => this.listeners.delete(listener);
@@ -290,11 +559,31 @@ var CollaborationEngine = class {
290
559
  list() {
291
560
  return this.state.requirements.map((item) => this.view(item.id));
292
561
  }
562
+ summaries() {
563
+ return this.state.requirements.map((record) => ({
564
+ id: record.id,
565
+ title: record.title,
566
+ stage: record.stage,
567
+ currentCommit: record.currentCommit,
568
+ ...record.workspaceId ? { workspaceId: record.workspaceId } : {},
569
+ ...record.archivedAt ? { archivedAt: record.archivedAt } : {},
570
+ updatedAt: record.updatedAt,
571
+ metrics: requirementMetrics(record, this.state),
572
+ participantIds: requirementParticipantIds(record, this.versions.history(record.id))
573
+ }));
574
+ }
293
575
  version(requirementId, commit) {
294
576
  const record = this.record(requirementId);
295
577
  if (!this.versions.history(record.id).some((version) => version.commit === commit)) throw new Error("requirement version not found");
296
578
  return this.versions.read(record.id, commit);
297
579
  }
580
+ diff(requirementId, baseCommit, headCommit) {
581
+ const record = this.record(requirementId);
582
+ const head = headCommit ?? record.currentCommit;
583
+ const before = this.version(requirementId, baseCommit);
584
+ const after = this.version(requirementId, head);
585
+ return buildStructuredDiff(before.markdown, after.markdown, baseCommit.slice(0, 10), head.slice(0, 10));
586
+ }
298
587
  myItems(participant, category) {
299
588
  const rows = [];
300
589
  for (const record of this.state.requirements) for (const item of record.actionItems.filter((candidate) => candidate.status === "pending")) {
@@ -305,6 +594,7 @@ var CollaborationEngine = class {
305
594
  ...structuredClone(item),
306
595
  category: current,
307
596
  requirementTitle: record.title,
597
+ objectTitle: actionObjectTitle(record, item),
308
598
  target: actionTarget(item)
309
599
  });
310
600
  }
@@ -317,17 +607,23 @@ var CollaborationEngine = class {
317
607
  view(id) {
318
608
  const record = this.record(id);
319
609
  const version = this.versions.read(id, record.currentCommit);
610
+ const commitUrl = this.versions.commitUrl(record.currentCommit);
320
611
  return {
321
612
  ...structuredClone(record),
322
613
  version,
323
614
  history: this.versions.history(id),
324
- readiness: readiness(version.markdown, record)
615
+ readiness: readiness(version.markdown, record),
616
+ metrics: requirementMetrics(record, this.state),
617
+ ...commitUrl ? { commitUrl } : {}
325
618
  };
326
619
  }
327
620
  apply(requestId, action) {
328
621
  const cached = this.seen.get(requestId);
329
622
  if (cached !== void 0) return structuredClone(cached);
330
623
  let result;
624
+ const beforeState = structuredClone(this.state);
625
+ const previousEventContext = this.eventContext;
626
+ this.eventContext = eventForAction(action);
331
627
  try {
332
628
  const registered = action.participant.kind === "human" ? this.state.participants.find((item) => item.participantId === action.participant.participantId) : void 0;
333
629
  if (registered !== void 0 && registered.role !== action.participant.role) throw new Error(`participant role is bound to ${registered.role}`);
@@ -341,10 +637,11 @@ var CollaborationEngine = class {
341
637
  } : {
342
638
  ok: true,
343
639
  revision: this.state.revision,
344
- requirement: this.view(result.requirement.id)
640
+ requirement: result.requirement
345
641
  };
346
642
  }
347
643
  } catch (error) {
644
+ this.state = beforeState;
348
645
  const conflict = error instanceof VersionConflictError && action.kind === "version.save" ? this.saveConflict(action) : void 0;
349
646
  result = {
350
647
  ok: false,
@@ -353,6 +650,7 @@ var CollaborationEngine = class {
353
650
  ...conflict === void 0 ? {} : { conflict }
354
651
  };
355
652
  }
653
+ this.eventContext = previousEventContext;
356
654
  this.seen.set(requestId, result);
357
655
  return structuredClone(result);
358
656
  }
@@ -382,7 +680,11 @@ var CollaborationEngine = class {
382
680
  run.status = "completed";
383
681
  run.maturitySummary = input.maturitySummary;
384
682
  run.updatedAt = now;
385
- this.persist();
683
+ this.persist({
684
+ types: ["ai.status", "metrics.changed"],
685
+ requirementId: record.id,
686
+ objectId: run.id
687
+ });
386
688
  }
387
689
  submitPatch(input) {
388
690
  const record = this.record(input.requirementId);
@@ -416,7 +718,11 @@ var CollaborationEngine = class {
416
718
  createdAt: Date.now(),
417
719
  updatedAt: Date.now()
418
720
  });
419
- this.persist();
721
+ this.persist({
722
+ types: ["ai.status", "metrics.changed"],
723
+ requirementId: record.id,
724
+ objectId: patch.id
725
+ });
420
726
  }
421
727
  submitAiReply(input) {
422
728
  assertChineseFeedback(input.body);
@@ -426,11 +732,20 @@ var CollaborationEngine = class {
426
732
  id: randomUUID(),
427
733
  author: input.ai,
428
734
  body: input.body,
735
+ mentions: [],
429
736
  createdAt: Date.now()
430
737
  });
431
738
  comment.aiStatus = "completed";
432
739
  comment.updatedAt = Date.now();
433
- this.persist();
740
+ this.persist({
741
+ types: [
742
+ "ai.status",
743
+ "comment.changed",
744
+ "metrics.changed"
745
+ ],
746
+ requirementId: record.id,
747
+ objectId: comment.id
748
+ });
434
749
  }
435
750
  markAiFailure(requirementId, sourceId, error) {
436
751
  const record = this.record(requirementId);
@@ -445,7 +760,11 @@ var CollaborationEngine = class {
445
760
  comment.aiStatus = "failed";
446
761
  comment.updatedAt = Date.now();
447
762
  }
448
- this.persist();
763
+ this.persist({
764
+ types: ["ai.status", "metrics.changed"],
765
+ requirementId,
766
+ objectId: sourceId
767
+ });
449
768
  }
450
769
  applyFresh(action) {
451
770
  const now = Date.now();
@@ -465,6 +784,7 @@ var CollaborationEngine = class {
465
784
  id: created.requirementId,
466
785
  title,
467
786
  stage: "product-review",
787
+ stageCycle: 0,
468
788
  currentCommit: created.version.commit,
469
789
  workspaceId,
470
790
  sources: action.sources,
@@ -475,11 +795,12 @@ var CollaborationEngine = class {
475
795
  confirmations: [],
476
796
  actionItems: [],
477
797
  aiRuns: [],
798
+ aiConversations: [],
478
799
  createdAt: now,
479
800
  updatedAt: now
480
801
  };
481
802
  this.state.requirements.unshift(record);
482
- this.persist();
803
+ this.persist(void 0, true);
483
804
  this.enqueueReview(record, action.participant, "product-first");
484
805
  return {
485
806
  ok: true,
@@ -518,11 +839,11 @@ var CollaborationEngine = class {
518
839
  record.currentCommit = version.commit;
519
840
  record.updatedAt = now;
520
841
  invalidateAffected(record, [], []);
521
- this.persist();
842
+ this.persist(void 0, true);
522
843
  this.enqueueReview(record, action.participant, "change-review");
523
- } else if (action.kind === "requirement.archive") {
844
+ } else if (action.kind === "requirement.archive" || action.kind === "requirement.unarchive") {
524
845
  requireHuman(action.participant);
525
- if (action.archived) record.archivedAt = now;
846
+ if (action.kind === "requirement.archive" && action.archived) record.archivedAt = now;
526
847
  else delete record.archivedAt;
527
848
  record.updatedAt = now;
528
849
  this.persist();
@@ -531,7 +852,8 @@ var CollaborationEngine = class {
531
852
  const deleted = this.view(record.id);
532
853
  this.versions.remove(record.id, action.participant);
533
854
  this.state.requirements.splice(this.state.requirements.indexOf(record), 1);
534
- this.persist();
855
+ this.state.insightLinks = this.state.insightLinks.filter((item) => item.requirementId !== record.id);
856
+ this.persist(void 0, true);
535
857
  return {
536
858
  ok: true,
537
859
  revision: this.state.revision,
@@ -556,8 +878,31 @@ var CollaborationEngine = class {
556
878
  record.patches.filter((item) => item.status === "pending").forEach((item) => {
557
879
  item.status = "stale";
558
880
  });
559
- if (record.stage === "ready") record.stage = "joint-review";
560
- this.persist();
881
+ if (record.stage === "ready") enterStage(record, "joint-review");
882
+ this.persist(void 0, true);
883
+ this.enqueueReview(record, action.participant, "change-review");
884
+ } else if (action.kind === "version.restore") {
885
+ requireHuman(action.participant);
886
+ const historical = this.version(record.id, action.commit);
887
+ if (historical.commit === record.currentCommit) throw new Error("selected version is already current");
888
+ const before = this.versions.read(record.id, record.currentCommit).markdown;
889
+ const version = this.versions.save({
890
+ requirementId: record.id,
891
+ baseCommit: record.currentCommit,
892
+ markdown: historical.markdown,
893
+ participant: action.participant,
894
+ summary: action.summary.trim() || `恢复版本 ${historical.commit.slice(0, 8)}`
895
+ });
896
+ const impact = changedScopes(before, historical.markdown);
897
+ record.currentCommit = version.commit;
898
+ record.updatedAt = now;
899
+ delete record.readyPackage;
900
+ invalidateAffected(record, impact.sections, impact.acceptanceIds, historical.markdown);
901
+ record.patches.filter((item) => item.status === "pending").forEach((item) => {
902
+ item.status = "stale";
903
+ });
904
+ if (record.stage === "ready") enterStage(record, "joint-review");
905
+ this.persist(void 0, true);
561
906
  this.enqueueReview(record, action.participant, "change-review");
562
907
  } else if (action.kind === "review.request") {
563
908
  requireHuman(action.participant);
@@ -582,20 +927,25 @@ var CollaborationEngine = class {
582
927
  } else if (action.kind === "comment.create") {
583
928
  requireHuman(action.participant);
584
929
  if (action.commit !== record.currentCommit) throw new VersionConflictError(record.currentCommit);
930
+ const scope = action.scope ?? "inline";
931
+ const mentions = validMentions(action.mentions, this.state.participants);
585
932
  const comment = {
586
933
  id: randomUUID(),
587
934
  requirementId: record.id,
588
935
  commit: action.commit,
589
- anchor: action.anchor,
936
+ scope,
937
+ ...action.anchor === void 0 ? {} : { anchor: action.anchor },
590
938
  author: action.participant,
591
939
  body: action.body.trim(),
940
+ mentions,
592
941
  replies: [],
593
942
  aiStatus: "queued",
594
943
  status: "open",
595
944
  createdAt: now,
596
945
  updatedAt: now
597
946
  };
598
- if (comment.body === "" || comment.anchor.quote.trim() === "") throw new Error("comment and anchor are required");
947
+ if (comment.body === "" || scope === "inline" && action.anchor?.quote.trim() === "") throw new Error(scope === "inline" ? "comment and anchor are required" : "comment is required");
948
+ if (scope === "inline" && action.anchor === void 0) throw new Error("comment and anchor are required");
599
949
  record.comments.push(comment);
600
950
  record.actionItems.push({
601
951
  id: randomUUID(),
@@ -610,30 +960,50 @@ var CollaborationEngine = class {
610
960
  createdAt: now,
611
961
  updatedAt: now
612
962
  });
963
+ for (const participantId of mentions) this.notify(participantId, "mention", record, "comment", comment.id, `${action.participant.nickname} 在评论中提到了你`);
613
964
  this.persist();
614
965
  const coordinator = this.coordinator;
615
966
  if (coordinator !== void 0) {
616
967
  const view = this.view(record.id);
968
+ const requestedStage = record.stage;
969
+ const requestedStageCycle = record.stageCycle;
970
+ const existingSession = record.aiConversations.find((item) => item.stage === requestedStage && item.stageCycle === requestedStageCycle)?.sessionId;
617
971
  coordinator.requestCommentReply({
618
972
  requirement: view,
619
- comment
973
+ comment,
974
+ ...existingSession ? { sessionId: existingSession } : {}
620
975
  }).then((sessionId) => {
621
976
  comment.aiStatus = "running";
622
977
  comment.aiSessionId = sessionId;
623
978
  comment.updatedAt = Date.now();
624
- this.persist();
979
+ this.rememberStageConversation(record, sessionId, requestedStage, requestedStageCycle);
980
+ this.persist({
981
+ types: [
982
+ "ai.status",
983
+ "comment.changed",
984
+ "metrics.changed"
985
+ ],
986
+ requirementId: record.id,
987
+ objectId: comment.id
988
+ });
625
989
  }, (error) => this.markAiFailure(record.id, comment.id, error instanceof Error ? error.message : String(error)));
626
990
  }
627
991
  } else if (action.kind === "comment.reply") {
628
992
  requireHuman(action.participant);
629
993
  const comment = this.comment(record, action.commentId);
994
+ const body = action.body.trim();
995
+ if (body === "") throw new Error("reply is required");
996
+ const mentions = validMentions(action.mentions, this.state.participants);
630
997
  comment.replies.push({
631
998
  id: randomUUID(),
632
999
  author: action.participant,
633
- body: action.body.trim(),
1000
+ body,
1001
+ mentions,
634
1002
  createdAt: now
635
1003
  });
636
1004
  comment.updatedAt = now;
1005
+ if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, "reply", record, "comment", comment.id, `${action.participant.nickname} 回复了你的评论`);
1006
+ for (const participantId of mentions) this.notify(participantId, "mention", record, "comment", comment.id, `${action.participant.nickname} 在回复中提到了你`);
637
1007
  this.persist();
638
1008
  } else if (action.kind === "comment.resolve") {
639
1009
  requireHuman(action.participant);
@@ -641,11 +1011,34 @@ var CollaborationEngine = class {
641
1011
  comment.status = "resolved";
642
1012
  comment.resolution = action.resolution;
643
1013
  comment.updatedAt = now;
1014
+ if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, "status-change", record, "comment", comment.id, `${action.participant.nickname} 已解决你的评论`);
644
1015
  record.actionItems.filter((task) => task.sourceId === comment.id && task.status === "pending").forEach((task) => {
645
1016
  task.status = "handled";
646
1017
  task.updatedAt = now;
647
1018
  });
648
1019
  this.persist();
1020
+ } else if (action.kind === "comment.reopen") {
1021
+ requireHuman(action.participant);
1022
+ const comment = this.comment(record, action.commentId);
1023
+ if (comment.status !== "resolved") throw new Error("resolved comment not found");
1024
+ comment.status = "open";
1025
+ delete comment.resolution;
1026
+ comment.updatedAt = now;
1027
+ record.actionItems.push({
1028
+ id: randomUUID(),
1029
+ requirementId: record.id,
1030
+ sourceType: "comment",
1031
+ sourceId: comment.id,
1032
+ type: "reply",
1033
+ assigneeRole: comment.author.role === "product" ? "engineering" : "product",
1034
+ blocking: false,
1035
+ status: "pending",
1036
+ dueStage: record.stage,
1037
+ createdAt: now,
1038
+ updatedAt: now
1039
+ });
1040
+ if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, "status-change", record, "comment", comment.id, `${action.participant.nickname} 重新打开了你的评论`);
1041
+ this.persist();
649
1042
  } else if (action.kind === "patch.accept") {
650
1043
  requireHuman(action.participant);
651
1044
  const patch = record.patches.find((item) => item.id === action.patchId);
@@ -662,6 +1055,11 @@ var CollaborationEngine = class {
662
1055
  record.currentCommit = version.commit;
663
1056
  patch.status = "accepted";
664
1057
  record.updatedAt = now;
1058
+ delete record.readyPackage;
1059
+ record.patches.filter((item) => item.id !== patch.id && item.status === "pending").forEach((item) => {
1060
+ item.status = "stale";
1061
+ });
1062
+ if (record.stage === "ready") enterStage(record, "joint-review");
665
1063
  for (const id of patch.affectedReviewItemIds) {
666
1064
  const item = record.reviewItems.find((candidate) => candidate.id === id);
667
1065
  if (item !== void 0) {
@@ -674,7 +1072,7 @@ var CollaborationEngine = class {
674
1072
  task.status = "handled";
675
1073
  task.updatedAt = now;
676
1074
  });
677
- this.persist();
1075
+ this.persist(void 0, true);
678
1076
  this.enqueueReview(record, action.participant, "change-review");
679
1077
  } else if (action.kind === "patch.reject") {
680
1078
  requireHuman(action.participant);
@@ -736,7 +1134,157 @@ var CollaborationEngine = class {
736
1134
  generatedBy: action.participant,
737
1135
  markdown
738
1136
  };
739
- record.stage = "ready";
1137
+ enterStage(record, "ready");
1138
+ this.persist();
1139
+ } else if (action.kind === "participant.register") {
1140
+ requireHuman(action.participant);
1141
+ const participant = this.state.participants.find((item) => item.participantId === action.participant.participantId);
1142
+ if (participant !== void 0) {
1143
+ participant.nickname = action.participant.nickname;
1144
+ participant.role = action.participant.role;
1145
+ this.persist();
1146
+ }
1147
+ } else if (action.kind === "action.assign") {
1148
+ requireHuman(action.participant);
1149
+ const task = record.actionItems.find((item) => item.id === action.actionItemId);
1150
+ if (task === void 0) throw new Error("action item not found");
1151
+ if (action.assigneeParticipantId !== void 0 && !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");
1152
+ task.assigneeRole = action.assigneeRole;
1153
+ if (action.dueStage !== void 0) task.dueStage = action.dueStage;
1154
+ if (action.assigneeParticipantId === void 0) delete task.assigneeParticipantId;
1155
+ else {
1156
+ task.assigneeParticipantId = action.assigneeParticipantId;
1157
+ this.notify(action.assigneeParticipantId, "assignment", record, "action", task.id, `${action.participant.nickname} 向你指派了一个待办`);
1158
+ }
1159
+ task.updatedAt = now;
1160
+ this.persist();
1161
+ } else if (action.kind === "notification.mark-read") {
1162
+ requireHuman(action.participant);
1163
+ const ids = new Set(action.notificationIds);
1164
+ this.state.notifications.filter((item) => item.recipientParticipantId === action.participant.participantId && item.requirementId === record.id && ids.has(item.id)).forEach((item) => {
1165
+ item.readAt ??= now;
1166
+ });
1167
+ this.persist();
1168
+ } else if (action.kind === "source.upsert") {
1169
+ requireHuman(action.participant);
1170
+ const input = cleanSource(action.source);
1171
+ const existing = this.state.feedbackSources.find((item) => item.id === input.id);
1172
+ const source = {
1173
+ ...input,
1174
+ createdAt: existing?.createdAt ?? now,
1175
+ updatedAt: now
1176
+ };
1177
+ validateSource(source);
1178
+ if (existing === void 0) this.state.feedbackSources.push(source);
1179
+ else Object.assign(existing, source);
1180
+ this.persist();
1181
+ } else if (action.kind === "company.upsert") {
1182
+ requireHuman(action.participant);
1183
+ const input = cleanCompany(action.company);
1184
+ validateCompany(input);
1185
+ const existing = this.state.companies.find((item) => item.id === input.id);
1186
+ const company = {
1187
+ ...input,
1188
+ createdAt: existing?.createdAt ?? now,
1189
+ updatedAt: now
1190
+ };
1191
+ if (existing === void 0) this.state.companies.push(company);
1192
+ else Object.assign(existing, company);
1193
+ this.persist();
1194
+ } else if (action.kind === "customer.upsert") {
1195
+ requireHuman(action.participant);
1196
+ const input = cleanCustomer(action.customer);
1197
+ validateCustomer(input, this.state);
1198
+ const existing = this.state.customers.find((item) => item.id === input.id);
1199
+ const customer = {
1200
+ ...input,
1201
+ createdAt: existing?.createdAt ?? now,
1202
+ updatedAt: now
1203
+ };
1204
+ if (existing === void 0) this.state.customers.push(customer);
1205
+ else Object.assign(existing, customer);
1206
+ this.persist();
1207
+ } else if (action.kind === "insight.create") {
1208
+ requireHuman(action.participant);
1209
+ const insight = this.createInsight(record.id, action.insight, action.participant, now);
1210
+ for (const link of action.links ?? []) this.addInsightLink(insight.id, link, action.participant, now);
1211
+ this.persist();
1212
+ } else if (action.kind === "insight.update") {
1213
+ requireHuman(action.participant);
1214
+ const insight = this.state.insights.find((item) => item.id === action.insightId);
1215
+ if (insight === void 0) throw new Error("insight not found");
1216
+ Object.assign(insight, action.changes);
1217
+ validateInsight(insight, this.state);
1218
+ insight.dedupeHash = insightHash(insight.sourceId, insight.body);
1219
+ insight.updatedAt = now;
1220
+ this.persist();
1221
+ } else if (action.kind === "insight.delete") {
1222
+ requireHuman(action.participant);
1223
+ const index = this.state.insights.findIndex((item) => item.id === action.insightId);
1224
+ if (index < 0) throw new Error("insight not found");
1225
+ this.state.insights.splice(index, 1);
1226
+ this.state.insightLinks = this.state.insightLinks.filter((item) => item.insightId !== action.insightId);
1227
+ this.persist();
1228
+ } else if (action.kind === "insight.link") {
1229
+ requireHuman(action.participant);
1230
+ this.addInsightLink(action.insightId, action.link, action.participant, now);
1231
+ this.persist();
1232
+ } else if (action.kind === "insight.unlink") {
1233
+ requireHuman(action.participant);
1234
+ if (this.state.insightLinks.find((item) => item.id === action.linkId) === void 0) throw new Error("insight link not found");
1235
+ this.state.insightLinks = this.state.insightLinks.filter((item) => item.id !== action.linkId);
1236
+ this.persist();
1237
+ } else if (action.kind === "insight.import") {
1238
+ requireHuman(action.participant);
1239
+ if (action.rows.length > 2e3 || Buffer.byteLength(JSON.stringify(action.rows), "utf8") > 5 * 1024 * 1024) throw new Error("insight import exceeds 2,000 rows or 5 MB");
1240
+ const before = structuredClone(this.state);
1241
+ try {
1242
+ for (const row of [...action.source ? [action.source] : [], ...action.sources ?? []]) {
1243
+ const source = {
1244
+ ...cleanSource(row),
1245
+ createdAt: now,
1246
+ updatedAt: now
1247
+ };
1248
+ validateSource(source);
1249
+ const existing = this.state.feedbackSources.find((item) => item.id === source.id);
1250
+ if (existing) Object.assign(existing, source, { createdAt: existing.createdAt });
1251
+ else this.state.feedbackSources.push(source);
1252
+ }
1253
+ for (const row of action.companies ?? []) {
1254
+ const company = cleanCompany(row);
1255
+ validateCompany(company);
1256
+ const existing = this.state.companies.find((item) => item.id === company.id);
1257
+ if (existing) Object.assign(existing, company, {
1258
+ createdAt: existing.createdAt,
1259
+ updatedAt: now
1260
+ });
1261
+ else this.state.companies.push({
1262
+ ...company,
1263
+ createdAt: now,
1264
+ updatedAt: now
1265
+ });
1266
+ }
1267
+ for (const row of action.customers ?? []) {
1268
+ const customer = cleanCustomer(row);
1269
+ validateCustomer(customer, this.state);
1270
+ const existing = this.state.customers.find((item) => item.id === customer.id);
1271
+ if (existing) Object.assign(existing, customer, {
1272
+ createdAt: existing.createdAt,
1273
+ updatedAt: now
1274
+ });
1275
+ else this.state.customers.push({
1276
+ ...customer,
1277
+ createdAt: now,
1278
+ updatedAt: now
1279
+ });
1280
+ }
1281
+ const actualIds = /* @__PURE__ */ new Map();
1282
+ for (const row of action.rows) actualIds.set(row.id, this.createInsight(record.id, row, action.participant, now).id);
1283
+ for (const link of action.links ?? []) this.addInsightLink(actualIds.get(link.insightId) ?? link.insightId, link, action.participant, now);
1284
+ } catch (error) {
1285
+ this.state = before;
1286
+ throw error;
1287
+ }
740
1288
  this.persist();
741
1289
  } else if (action.kind === "downstream.return") {
742
1290
  requireHuman(action.participant);
@@ -765,7 +1313,7 @@ var CollaborationEngine = class {
765
1313
  record.actionItems.push(actionForReview(item));
766
1314
  invalidateAffected(record, item.affectedSections, item.affectedAcceptanceIds);
767
1315
  delete record.readyPackage;
768
- record.stage = "joint-review";
1316
+ enterStage(record, "joint-review");
769
1317
  record.updatedAt = now;
770
1318
  this.persist();
771
1319
  this.enqueueReview(record, action.participant, "change-review");
@@ -776,6 +1324,76 @@ var CollaborationEngine = class {
776
1324
  requirement: this.view(record.id)
777
1325
  };
778
1326
  }
1327
+ createInsight(requirementId, input, participant, now) {
1328
+ const draft = {
1329
+ ...input,
1330
+ title: input.title.trim(),
1331
+ body: input.body.trim(),
1332
+ dedupeHash: insightHash(input.sourceId, input.body),
1333
+ createdBy: participant,
1334
+ createdAt: now,
1335
+ updatedAt: now
1336
+ };
1337
+ validateInsight(draft, this.state);
1338
+ const existing = this.state.insights.find((item) => item.dedupeHash === draft.dedupeHash);
1339
+ const insight = existing ?? draft;
1340
+ if (existing === void 0) this.state.insights.push(insight);
1341
+ if (!this.state.insightLinks.some((item) => item.insightId === insight.id && item.requirementId === requirementId && item.targetType === "requirement")) this.state.insightLinks.push({
1342
+ id: randomUUID(),
1343
+ insightId: insight.id,
1344
+ requirementId,
1345
+ targetType: "requirement",
1346
+ createdBy: participant,
1347
+ createdAt: now
1348
+ });
1349
+ return insight;
1350
+ }
1351
+ addInsightLink(insightId, link, participant, now) {
1352
+ if (!this.state.insights.some((item) => item.id === insightId)) throw new Error("insight not found");
1353
+ this.record(link.requirementId);
1354
+ if (![
1355
+ "requirement",
1356
+ "section",
1357
+ "acceptance-criterion"
1358
+ ].includes(link.targetType)) throw new Error("invalid insight link target type");
1359
+ if (link.targetType !== "requirement" && !link.targetId?.trim()) throw new Error("linked section or acceptance criterion id is required");
1360
+ if (!this.state.insightLinks.some((item) => item.insightId === insightId && item.requirementId === link.requirementId && item.targetType === link.targetType && item.targetId === link.targetId)) this.state.insightLinks.push({
1361
+ id: randomUUID(),
1362
+ insightId,
1363
+ ...link,
1364
+ createdBy: participant,
1365
+ createdAt: now
1366
+ });
1367
+ }
1368
+ rememberStageConversation(record, sessionId, stage = record.stage, stageCycle = record.stageCycle) {
1369
+ const now = Date.now();
1370
+ const existing = record.aiConversations.find((item) => item.stage === stage && item.stageCycle === stageCycle);
1371
+ if (existing) {
1372
+ existing.sessionId = sessionId;
1373
+ existing.updatedAt = now;
1374
+ } else record.aiConversations.push({
1375
+ stage,
1376
+ stageCycle,
1377
+ sessionId,
1378
+ createdAt: now,
1379
+ updatedAt: now
1380
+ });
1381
+ }
1382
+ notify(recipientParticipantId, kind, record, objectType, objectId, message) {
1383
+ if (!this.state.participants.some((item) => item.participantId === recipientParticipantId)) return;
1384
+ const deepLink = `#spec-collab/${encodeURIComponent(record.id)}/${objectType === "comment" ? "discussion" : "tasks"}/${encodeURIComponent(objectId)}?commit=${encodeURIComponent(record.currentCommit)}`;
1385
+ this.state.notifications.push({
1386
+ id: randomUUID(),
1387
+ recipientParticipantId,
1388
+ kind,
1389
+ requirementId: record.id,
1390
+ objectType,
1391
+ objectId,
1392
+ message,
1393
+ deepLink,
1394
+ createdAt: Date.now()
1395
+ });
1396
+ }
779
1397
  saveConflict(action) {
780
1398
  const record = this.record(action.requirementId);
781
1399
  const baseMarkdown = this.versions.read(record.id, action.baseCommit).markdown;
@@ -804,21 +1422,34 @@ var CollaborationEngine = class {
804
1422
  updatedAt: now
805
1423
  };
806
1424
  record.aiRuns.push(run);
807
- this.persist();
1425
+ this.persist({
1426
+ types: ["ai.status", "metrics.changed"],
1427
+ requirementId: record.id,
1428
+ objectId: run.id
1429
+ });
808
1430
  const coordinator = this.coordinator;
809
1431
  if (coordinator === void 0) {
810
1432
  this.markAiFailure(record.id, run.id, "AI coordinator unavailable");
811
1433
  return;
812
1434
  }
813
1435
  const view = this.view(record.id);
1436
+ const requestedStage = record.stage;
1437
+ const requestedStageCycle = record.stageCycle;
1438
+ const existingSession = record.aiConversations.find((item) => item.stage === requestedStage && item.stageCycle === requestedStageCycle)?.sessionId;
814
1439
  coordinator.requestReview({
815
1440
  requirement: view,
816
- run
1441
+ run,
1442
+ ...existingSession ? { sessionId: existingSession } : {}
817
1443
  }).then((sessionId) => {
818
1444
  run.status = "running";
819
1445
  run.sessionId = sessionId;
820
1446
  run.updatedAt = Date.now();
821
- this.persist();
1447
+ this.rememberStageConversation(record, sessionId, requestedStage, requestedStageCycle);
1448
+ this.persist({
1449
+ types: ["ai.status", "metrics.changed"],
1450
+ requirementId: record.id,
1451
+ objectId: run.id
1452
+ });
822
1453
  }, (error) => this.markAiFailure(record.id, run.id, error instanceof Error ? error.message : String(error)));
823
1454
  }
824
1455
  record(id) {
@@ -831,28 +1462,373 @@ var CollaborationEngine = class {
831
1462
  if (value === void 0) throw new Error("comment not found");
832
1463
  return value;
833
1464
  }
834
- persist() {
1465
+ persist(event = this.eventContext ?? { types: ["metrics.changed"] }, recoverable = false) {
835
1466
  this.state.revision += 1;
836
- mkdirSync(dirname(this.eventPath), {
837
- recursive: true,
838
- mode: 448
839
- });
840
- const tmp = `${this.eventPath}.tmp`;
841
- writeFileSync(tmp, JSON.stringify(this.state, null, 2), { mode: 384 });
842
- renameSync(tmp, this.eventPath);
843
- for (const listener of this.listeners) listener();
1467
+ const pendingPath = `${this.eventPath}.pending`;
1468
+ if (recoverable) atomicWrite(pendingPath, this.state, true);
1469
+ atomicWrite(this.eventPath, this.state, recoverable);
1470
+ if (recoverable && existsSync(pendingPath)) unlinkSync(pendingPath);
1471
+ const payload = {
1472
+ ...event,
1473
+ types: [...event.types],
1474
+ revision: this.state.revision
1475
+ };
1476
+ for (const listener of this.listeners) listener(payload);
844
1477
  }
845
1478
  load() {
846
- try {
847
- const value = JSON.parse(readFileSync(this.eventPath, "utf8"));
848
- if (value.schemaVersion === 2) {
849
- value.participants ??= [];
850
- return value;
1479
+ const pendingPath = `${this.eventPath}.pending`;
1480
+ if (existsSync(pendingPath)) {
1481
+ let pending;
1482
+ try {
1483
+ pending = JSON.parse(readFileSync(pendingPath, "utf8"));
1484
+ validateV3Ledger(pending);
1485
+ atomicWrite(this.eventPath, pending, true);
1486
+ unlinkSync(pendingPath);
1487
+ return normalizeV3(pending);
1488
+ } catch (error) {
1489
+ throw new Error(`pending collaboration transaction is corrupted: ${error instanceof Error ? error.message : String(error)}`);
851
1490
  }
852
- } catch {}
853
- return emptyState();
1491
+ }
1492
+ const sourcePath = existsSync(this.eventPath) ? this.eventPath : this.options.legacyPath !== void 0 && existsSync(this.options.legacyPath) ? this.options.legacyPath : void 0;
1493
+ if (sourcePath === void 0) return emptyState();
1494
+ let parsed;
1495
+ try {
1496
+ parsed = JSON.parse(readFileSync(sourcePath, "utf8"));
1497
+ } catch (error) {
1498
+ throw new Error(`collaboration ledger is corrupted: ${error instanceof Error ? error.message : String(error)}`);
1499
+ }
1500
+ if (typeof parsed !== "object" || parsed === null || typeof parsed.schemaVersion !== "number") throw new Error("collaboration ledger has no schema version");
1501
+ const version = parsed.schemaVersion;
1502
+ if (version === 3) {
1503
+ validateV3Ledger(parsed);
1504
+ return normalizeV3(parsed);
1505
+ }
1506
+ if (version !== 2) throw new Error(`unsupported collaboration schema: ${version}`);
1507
+ validateV2Ledger(parsed);
1508
+ const migrated = migrateV2(parsed);
1509
+ const extension = extname(sourcePath);
1510
+ const stem = basename(sourcePath, extension).replace(/-v2$/, "");
1511
+ copyFileSync(sourcePath, join(dirname(sourcePath), `${stem}-v2.backup-${Date.now()}${extension || ".json"}`));
1512
+ atomicWrite(this.eventPath, migrated, true);
1513
+ return migrated;
854
1514
  }
855
1515
  };
1516
+ function eventForAction(action) {
1517
+ const types = /* @__PURE__ */ new Set(["metrics.changed"]);
1518
+ if (action.kind.startsWith("comment.")) types.add("comment.changed");
1519
+ if (action.kind === "comment.create" || action.kind === "comment.reply") {
1520
+ if ((action.mentions?.length ?? 0) > 0) types.add("mention.created");
1521
+ types.add("notification.changed");
1522
+ }
1523
+ if (action.kind === "comment.resolve" || action.kind === "comment.reopen") types.add("notification.changed");
1524
+ if (action.kind === "action.assign") {
1525
+ types.add("assignment.changed");
1526
+ types.add("notification.changed");
1527
+ }
1528
+ if (action.kind === "notification.mark-read") types.add("notification.changed");
1529
+ if (action.kind === "review.request") types.add("ai.status");
1530
+ const requirementId = "requirementId" in action ? action.requirementId : void 0;
1531
+ return {
1532
+ types: [...types],
1533
+ ...requirementId ? { requirementId } : {}
1534
+ };
1535
+ }
1536
+ function isRecord(value) {
1537
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1538
+ }
1539
+ function validateV2Ledger(value) {
1540
+ if (!isRecord(value) || !Array.isArray(value.requirements) || value.participants !== void 0 && !Array.isArray(value.participants)) throw new Error("invalid collaboration v2 ledger: requirements and participants must be arrays");
1541
+ }
1542
+ function validateV3Ledger(value) {
1543
+ if (!isRecord(value)) throw new Error("invalid collaboration v3 ledger: object required");
1544
+ if (!Number.isFinite(value.revision) || [
1545
+ "participants",
1546
+ "requirements",
1547
+ "companies",
1548
+ "customers",
1549
+ "feedbackSources",
1550
+ "insights",
1551
+ "insightLinks",
1552
+ "notifications"
1553
+ ].some((key) => !Array.isArray(value[key]))) throw new Error("invalid collaboration v3 ledger: required collections are missing or invalid");
1554
+ for (const candidate of value.requirements) {
1555
+ if (!isRecord(candidate) || typeof candidate.id !== "string" || typeof candidate.title !== "string" || typeof candidate.currentCommit !== "string" || ![
1556
+ "product-review",
1557
+ "product-confirmation",
1558
+ "joint-review",
1559
+ "ready"
1560
+ ].includes(String(candidate.stage))) throw new Error("invalid collaboration v3 ledger: malformed requirement");
1561
+ if ([
1562
+ "sources",
1563
+ "reviewItems",
1564
+ "comments",
1565
+ "patches",
1566
+ "decisions",
1567
+ "confirmations",
1568
+ "actionItems",
1569
+ "aiRuns"
1570
+ ].some((key) => !Array.isArray(candidate[key])) || candidate.aiConversations !== void 0 && !Array.isArray(candidate.aiConversations)) throw new Error("invalid collaboration v3 ledger: malformed requirement collections");
1571
+ }
1572
+ }
1573
+ function atomicWrite(path, value, durable = false) {
1574
+ mkdirSync(dirname(path), {
1575
+ recursive: true,
1576
+ mode: 448
1577
+ });
1578
+ const tmp = `${path}.tmp`;
1579
+ writeFileSync(tmp, JSON.stringify(value, null, 2), { mode: 384 });
1580
+ if (durable) {
1581
+ const descriptor = openSync(tmp, "r");
1582
+ try {
1583
+ fsyncSync(descriptor);
1584
+ } finally {
1585
+ closeSync(descriptor);
1586
+ }
1587
+ }
1588
+ renameSync(tmp, path);
1589
+ }
1590
+ function normalizeV3(value) {
1591
+ value.participants ??= [];
1592
+ value.requirements ??= [];
1593
+ value.companies ??= [];
1594
+ value.customers ??= [];
1595
+ value.feedbackSources ??= [];
1596
+ value.insights ??= [];
1597
+ value.insightLinks ??= [];
1598
+ value.notifications ??= [];
1599
+ for (const record of value.requirements) {
1600
+ record.sources ??= [];
1601
+ record.reviewItems ??= [];
1602
+ record.comments ??= [];
1603
+ record.patches ??= [];
1604
+ record.decisions ??= [];
1605
+ record.confirmations ??= [];
1606
+ record.actionItems ??= [];
1607
+ record.aiRuns ??= [];
1608
+ record.aiConversations ??= [];
1609
+ record.stageCycle ??= 0;
1610
+ for (const conversation of record.aiConversations) conversation.stageCycle ??= record.stageCycle;
1611
+ if (record.aiConversations.length === 0 && (record.stage === "product-review" || record.stage === "joint-review")) {
1612
+ const recent = [...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) => ({
1613
+ sessionId: item.sessionId,
1614
+ createdAt: item.createdAt,
1615
+ updatedAt: item.updatedAt
1616
+ })), ...record.comments.filter((item) => item.aiSessionId).map((item) => ({
1617
+ sessionId: item.aiSessionId,
1618
+ createdAt: item.createdAt,
1619
+ updatedAt: item.updatedAt
1620
+ }))].sort((left, right) => right.updatedAt - left.updatedAt)[0];
1621
+ if (recent) record.aiConversations.push({
1622
+ stage: record.stage,
1623
+ stageCycle: record.stageCycle,
1624
+ ...recent
1625
+ });
1626
+ }
1627
+ for (const comment of record.comments) {
1628
+ comment.scope ??= comment.anchor === void 0 ? "page" : "inline";
1629
+ comment.mentions ??= [];
1630
+ comment.replies ??= [];
1631
+ for (const reply of comment.replies) reply.mentions ??= [];
1632
+ }
1633
+ }
1634
+ return value;
1635
+ }
1636
+ function migrateV2(value) {
1637
+ const legacyRequirements = Array.isArray(value.requirements) ? value.requirements : [];
1638
+ const requirements = structuredClone(legacyRequirements);
1639
+ const feedbackSources = [];
1640
+ const insights = [];
1641
+ const insightLinks = [];
1642
+ const migrationActor = {
1643
+ participantId: "migration-v2",
1644
+ nickname: "数据迁移",
1645
+ role: "product",
1646
+ kind: "ai",
1647
+ sessionId: "migration-v2"
1648
+ };
1649
+ for (const record of requirements) {
1650
+ record.sources ??= [];
1651
+ record.reviewItems ??= [];
1652
+ record.comments ??= [];
1653
+ record.patches ??= [];
1654
+ record.decisions ??= [];
1655
+ record.confirmations ??= [];
1656
+ record.actionItems ??= [];
1657
+ record.aiRuns ??= [];
1658
+ record.aiConversations ??= [];
1659
+ record.stageCycle ??= 0;
1660
+ for (const conversation of record.aiConversations) conversation.stageCycle ??= record.stageCycle;
1661
+ for (const comment of record.comments) {
1662
+ comment.scope = comment.anchor === void 0 ? "page" : "inline";
1663
+ comment.mentions = [];
1664
+ comment.replies ??= [];
1665
+ for (const reply of comment.replies) reply.mentions = [];
1666
+ }
1667
+ for (const source of record.sources) {
1668
+ const sourceId = `legacy-${createHash("sha256").update(`${record.id}:${source.id}`).digest("hex").slice(0, 16)}`;
1669
+ const insightId = `legacy-${createHash("sha256").update(`${record.id}:${source.id}:insight`).digest("hex").slice(0, 16)}`;
1670
+ feedbackSources.push({
1671
+ id: sourceId,
1672
+ kind: source.sourceType === "link" ? "url" : source.sourceType === "markdown" ? "markdown" : "text",
1673
+ label: source.label,
1674
+ ...source.sourceType === "link" && safeHttpUrl(source.stableId) ? { url: source.stableId } : {},
1675
+ ...source.stableId ? { externalRef: source.stableId } : {},
1676
+ accessStatus: source.accessStatus,
1677
+ createdAt: record.createdAt,
1678
+ updatedAt: record.updatedAt
1679
+ });
1680
+ insights.push({
1681
+ id: insightId,
1682
+ sourceId,
1683
+ title: source.label,
1684
+ body: `历史来源:${source.label}`,
1685
+ importance: "unknown",
1686
+ capturedAt: record.createdAt,
1687
+ dedupeHash: insightHash(sourceId, source.label),
1688
+ createdBy: migrationActor,
1689
+ createdAt: record.createdAt,
1690
+ updatedAt: record.updatedAt
1691
+ });
1692
+ insightLinks.push({
1693
+ id: randomUUID(),
1694
+ insightId,
1695
+ requirementId: record.id,
1696
+ targetType: "requirement",
1697
+ createdBy: migrationActor,
1698
+ createdAt: record.createdAt
1699
+ });
1700
+ }
1701
+ }
1702
+ return normalizeV3({
1703
+ schemaVersion: 3,
1704
+ revision: typeof value.revision === "number" ? value.revision : 0,
1705
+ participants: Array.isArray(value.participants) ? value.participants : [],
1706
+ requirements,
1707
+ companies: [],
1708
+ customers: [],
1709
+ feedbackSources,
1710
+ insights,
1711
+ insightLinks,
1712
+ notifications: []
1713
+ });
1714
+ }
1715
+ function safeHttpUrl(value) {
1716
+ if (!value) return false;
1717
+ try {
1718
+ const url = new URL(value);
1719
+ return url.protocol === "http:" || url.protocol === "https:";
1720
+ } catch {
1721
+ return false;
1722
+ }
1723
+ }
1724
+ function cleanSource(input) {
1725
+ return {
1726
+ id: input.id,
1727
+ kind: input.kind,
1728
+ label: input.label,
1729
+ ...input.url === void 0 ? {} : { url: input.url },
1730
+ ...input.externalRef === void 0 ? {} : { externalRef: input.externalRef },
1731
+ accessStatus: input.accessStatus
1732
+ };
1733
+ }
1734
+ function cleanCompany(input) {
1735
+ return {
1736
+ id: input.id,
1737
+ name: input.name,
1738
+ ...input.externalRef === void 0 ? {} : { externalRef: input.externalRef }
1739
+ };
1740
+ }
1741
+ function cleanCustomer(input) {
1742
+ return {
1743
+ id: input.id,
1744
+ displayName: input.displayName,
1745
+ ...input.companyId === void 0 ? {} : { companyId: input.companyId },
1746
+ ...input.externalRef === void 0 ? {} : { externalRef: input.externalRef }
1747
+ };
1748
+ }
1749
+ function validateSource(source) {
1750
+ if (!source.id.trim() || !source.label.trim() || ![
1751
+ "text",
1752
+ "url",
1753
+ "csv",
1754
+ "markdown"
1755
+ ].includes(source.kind) || ![
1756
+ "available",
1757
+ "unverified",
1758
+ "missing"
1759
+ ].includes(source.accessStatus) || source.kind === "url" && !safeHttpUrl(source.url)) throw new Error("valid source id, label and http(s) URL are required");
1760
+ }
1761
+ function validateCompany(company) {
1762
+ if (!company.id.trim() || !company.name.trim()) throw new Error("company id and name are required");
1763
+ }
1764
+ function validateCustomer(customer, state) {
1765
+ if (!customer.id.trim() || !customer.displayName.trim()) throw new Error("customer id and display name are required");
1766
+ if (customer.companyId !== void 0 && !state.companies.some((item) => item.id === customer.companyId)) throw new Error("company not found");
1767
+ }
1768
+ function validMentions(values, participants) {
1769
+ const registered = new Set(participants.map((item) => item.participantId));
1770
+ return [...new Set(values ?? [])].filter((value) => registered.has(value));
1771
+ }
1772
+ function insightHash(sourceId, body) {
1773
+ return createHash("sha256").update(`${sourceId}\n${body.normalize("NFKC").trim().replace(/\s+/g, " ").toLocaleLowerCase()}`).digest("hex");
1774
+ }
1775
+ function validateInsight(insight, state) {
1776
+ if (!insight.id.trim() || !insight.sourceId.trim() || !insight.body.trim()) throw new Error("insight id, source and body are required");
1777
+ if (!state.feedbackSources.some((item) => item.id === insight.sourceId)) throw new Error("feedback source not found");
1778
+ if (insight.customerId !== void 0 && !state.customers.some((item) => item.id === insight.customerId)) throw new Error("customer not found");
1779
+ if (insight.companyId !== void 0 && !state.companies.some((item) => item.id === insight.companyId)) throw new Error("company not found");
1780
+ if (![
1781
+ "unknown",
1782
+ "want",
1783
+ "important",
1784
+ "critical"
1785
+ ].includes(insight.importance)) throw new Error("invalid insight importance");
1786
+ }
1787
+ function requirementMetrics(record, state) {
1788
+ const insightIds = new Set(state.insightLinks.filter((link) => link.requirementId === record.id).map((link) => link.insightId));
1789
+ const insights = state.insights.filter((insight) => insightIds.has(insight.id));
1790
+ const customers = /* @__PURE__ */ new Set();
1791
+ const companies = /* @__PURE__ */ new Set();
1792
+ const entityScores = /* @__PURE__ */ new Map();
1793
+ let anonymousInsightCount = 0;
1794
+ const weights = {
1795
+ unknown: 1,
1796
+ want: 1,
1797
+ important: 2,
1798
+ critical: 3
1799
+ };
1800
+ for (const insight of insights) {
1801
+ const customer = insight.customerId === void 0 ? void 0 : state.customers.find((item) => item.id === insight.customerId);
1802
+ const companyId = insight.companyId ?? customer?.companyId;
1803
+ if (insight.customerId !== void 0) customers.add(insight.customerId);
1804
+ if (companyId !== void 0) companies.add(companyId);
1805
+ const entity = insight.customerId !== void 0 ? `customer:${insight.customerId}` : companyId !== void 0 ? `company:${companyId}` : void 0;
1806
+ if (entity === void 0) anonymousInsightCount += 1;
1807
+ else entityScores.set(entity, Math.max(entityScores.get(entity) ?? 0, weights[insight.importance]));
1808
+ }
1809
+ return {
1810
+ openReviewCount: record.reviewItems.filter((item) => item.commit === record.currentCommit && !["resolved", "invalidated"].includes(item.status)).length,
1811
+ openCommentCount: record.comments.filter((item) => item.commit === record.currentCommit && item.status === "open").length,
1812
+ pendingActionCount: record.actionItems.filter((item) => item.status === "pending").length,
1813
+ activeDecisionCount: record.decisions.filter((item) => item.status === "active").length,
1814
+ riskCount: record.reviewItems.filter((item) => item.commit === record.currentCommit && ["blocking", "major"].includes(item.severity) && !["resolved", "invalidated"].includes(item.status)).length,
1815
+ insightCount: insights.length,
1816
+ customerImportanceScore: [...entityScores.values()].reduce((sum, value) => sum + value, 0),
1817
+ customerCount: customers.size,
1818
+ companyCount: companies.size,
1819
+ anonymousInsightCount
1820
+ };
1821
+ }
1822
+ function requirementParticipantIds(record, history) {
1823
+ return [.../* @__PURE__ */ new Set([
1824
+ ...history.map((item) => item.author.participantId),
1825
+ ...record.reviewItems.flatMap((item) => item.response ? [item.response.participant.participantId] : []),
1826
+ ...record.comments.flatMap((item) => [item.author.participantId, ...item.replies.map((reply) => reply.author.participantId)]),
1827
+ ...record.decisions.map((item) => item.confirmer.participantId),
1828
+ ...record.confirmations.map((item) => item.participant.participantId),
1829
+ ...record.actionItems.flatMap((item) => item.assigneeParticipantId ? [item.assigneeParticipantId] : [])
1830
+ ])];
1831
+ }
856
1832
  function sourceParticipantId(record, item) {
857
1833
  if (item.sourceType === "comment") return record.comments.find((value) => value.id === item.sourceId)?.author.participantId;
858
1834
  if (item.sourceType === "patch") return record.patches.find((value) => value.id === item.sourceId)?.createdBy.participantId;
@@ -872,6 +1848,20 @@ function actionTarget(item) {
872
1848
  objectId: item.sourceId
873
1849
  };
874
1850
  }
1851
+ function actionObjectTitle(record, item) {
1852
+ if (item.sourceType === "review-item") {
1853
+ const review = record.reviewItems.find((value) => value.id === item.sourceId);
1854
+ return review?.question.trim() || review?.statement.trim() || "待处理问题";
1855
+ }
1856
+ if (item.sourceType === "comment") {
1857
+ const comment = record.comments.find((value) => value.id === item.sourceId);
1858
+ return comment?.anchor?.quote.trim() || comment?.body.trim() || "待回复评论";
1859
+ }
1860
+ if (item.sourceType === "patch") return record.patches.find((value) => value.id === item.sourceId)?.summary.trim() || "待审核正文改动";
1861
+ if (item.sourceType === "decision") return record.decisions.find((value) => value.id === item.sourceId)?.question.trim() || "待确认决策";
1862
+ const confirmation = record.confirmations.find((value) => value.id === item.sourceId);
1863
+ return confirmation ? `${confirmation.role === "product" ? "产品" : "研发"}需要重新确认当前版本` : "待确认当前版本";
1864
+ }
875
1865
  function textDiff(before, after) {
876
1866
  if (before === after) return "";
877
1867
  const left = before.split("\n");
@@ -920,6 +1910,11 @@ function actionForReview(item) {
920
1910
  function hasVersionConfirmation(record, role) {
921
1911
  return record.confirmations.some((item) => item.role === role && item.scope === "version" && item.commit === record.currentCommit && item.status === "active");
922
1912
  }
1913
+ function enterStage(record, stage) {
1914
+ if (record.stage === stage) return;
1915
+ record.stage = stage;
1916
+ record.stageCycle += 1;
1917
+ }
923
1918
  function advance(record, participant) {
924
1919
  if (record.stage === "product-review") {
925
1920
  if (record.reviewItems.some((item) => item.commit === record.currentCommit && item.severity === "blocking" && ![
@@ -928,12 +1923,12 @@ function advance(record, participant) {
928
1923
  "joint-review"
929
1924
  ].includes(item.status))) throw new Error("product blocking review items remain");
930
1925
  if (!record.aiRuns.some((run) => run.kind === "product-second" && run.commit === record.currentCommit && run.status === "completed")) throw new Error("product second review is required");
931
- record.stage = "product-confirmation";
1926
+ enterStage(record, "product-confirmation");
932
1927
  return;
933
1928
  }
934
1929
  if (record.stage === "product-confirmation") {
935
1930
  if (participant.role !== "product" || !hasVersionConfirmation(record, "product")) throw new Error("product must confirm the current version");
936
- record.stage = "joint-review";
1931
+ enterStage(record, "joint-review");
937
1932
  return;
938
1933
  }
939
1934
  throw new Error("stage cannot advance directly");
@@ -1446,6 +2441,7 @@ var DshReviewCoordinator = class {
1446
2441
  api;
1447
2442
  contexts;
1448
2443
  prompts;
2444
+ stageSessions = /* @__PURE__ */ new Map();
1449
2445
  constructor(api, contexts = new ReviewContextCatalog(), prompts = {}) {
1450
2446
  this.api = api;
1451
2447
  this.contexts = contexts;
@@ -1464,16 +2460,20 @@ var DshReviewCoordinator = class {
1464
2460
  await this.resolveWorkspace(workspaceId);
1465
2461
  }
1466
2462
  async requestReview(input) {
1467
- const context = this.contexts.resolve(input.requirement.workspaceId);
1468
- const workspace = await this.resolveWorkspace(context.workspaceId);
1469
- const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths);
1470
- return this.launch(`Spec ${input.run.kind}: ${input.requirement.title}`, reviewPrompt(input.requirement, input.run, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset);
2463
+ return this.inStageSession(input.requirement, input.sessionId, reviewContinuationPrompt(input.requirement, input.run, this.prompts), async () => {
2464
+ const context = this.contexts.resolve(input.requirement.workspaceId);
2465
+ const workspace = await this.resolveWorkspace(context.workspaceId);
2466
+ const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths);
2467
+ return this.launch(`Spec ${input.run.kind}: ${input.requirement.title}`, reviewPrompt(input.requirement, input.run, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset);
2468
+ });
1471
2469
  }
1472
2470
  async requestCommentReply(input) {
1473
- const context = this.contexts.resolve(input.requirement.workspaceId);
1474
- const workspace = await this.resolveWorkspace(context.workspaceId);
1475
- const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths);
1476
- return this.launch(`Spec comment analysis: ${input.requirement.title}`, commentPrompt(input.requirement, input.comment, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset);
2471
+ return this.inStageSession(input.requirement, input.sessionId, commentContinuationPrompt(input.requirement, input.comment, this.prompts), async () => {
2472
+ const context = this.contexts.resolve(input.requirement.workspaceId);
2473
+ const workspace = await this.resolveWorkspace(context.workspaceId);
2474
+ const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths);
2475
+ return this.launch(`Spec ${input.requirement.stage}: ${input.requirement.title}`, commentPrompt(input.requirement, input.comment, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset);
2476
+ });
1477
2477
  }
1478
2478
  async conversation(sessionId) {
1479
2479
  const history = await this.api.sessions.history(request({ sessionId }));
@@ -1516,6 +2516,48 @@ var DshReviewCoordinator = class {
1516
2516
  }));
1517
2517
  if (!prompted.result.ok) throw failure(prompted.result.error);
1518
2518
  }
2519
+ async inStageSession(requirement, existingSessionId, continuation, launch) {
2520
+ const key = `${requirement.id}:${requirement.stage}:${requirement.stageCycle}`;
2521
+ if (existingSessionId !== void 0) {
2522
+ this.rememberStageSession(key, Promise.resolve(existingSessionId));
2523
+ await this.promptExisting(existingSessionId, continuation);
2524
+ return existingSessionId;
2525
+ }
2526
+ const pending = this.stageSessions.get(key);
2527
+ if (pending !== void 0) {
2528
+ const sessionId = await pending;
2529
+ await this.promptExisting(sessionId, continuation);
2530
+ return sessionId;
2531
+ }
2532
+ const created = launch();
2533
+ this.rememberStageSession(key, created);
2534
+ try {
2535
+ return await created;
2536
+ } catch (error) {
2537
+ if (this.stageSessions.get(key) === created) this.stageSessions.delete(key);
2538
+ throw error;
2539
+ }
2540
+ }
2541
+ rememberStageSession(key, session) {
2542
+ this.stageSessions.delete(key);
2543
+ this.stageSessions.set(key, session);
2544
+ while (this.stageSessions.size > 100) {
2545
+ const oldest = this.stageSessions.keys().next().value;
2546
+ if (oldest === void 0) break;
2547
+ this.stageSessions.delete(oldest);
2548
+ }
2549
+ }
2550
+ async promptExisting(sessionId, promptText) {
2551
+ const prompted = await this.api.sessions.prompt(request({
2552
+ sessionId,
2553
+ mode: "queue",
2554
+ content: [{
2555
+ type: "text",
2556
+ text: promptText
2557
+ }]
2558
+ }));
2559
+ if (!prompted.result.ok) throw failure(prompted.result.error);
2560
+ }
1519
2561
  async launch(title, promptText, workspaceId, agentPreset) {
1520
2562
  if (agentPreset !== void 0) {
1521
2563
  const presets = await this.api.agentPresets.list(request({}));
@@ -1606,16 +2648,48 @@ function commentPrompt(requirement, comment, context, workspace, workspaceSnapsh
1606
2648
  return [
1607
2649
  common(requirement, context, workspace, workspaceSnapshot, prompts),
1608
2650
  `Comment ID: ${comment.id}`,
1609
- `Anchor quote: ${comment.anchor.quote}`,
2651
+ `Comment scope: ${comment.scope}`,
2652
+ `Anchor quote: ${comment.anchor?.quote ?? "整篇需求"}`,
1610
2653
  `Human comment: ${comment.body}`,
1611
2654
  `AI session ID: {{SESSION_ID}}`,
1612
2655
  "",
1613
2656
  prompts.comment
1614
2657
  ].join("\n");
1615
2658
  }
2659
+ function reviewContinuationPrompt(requirement, run, prompts) {
2660
+ const tasks = {
2661
+ "product-first": prompts.productFirst,
2662
+ "product-second": prompts.productSecond,
2663
+ "engineering-precheck": prompts.engineeringPrecheck,
2664
+ "change-review": prompts.changeReview
2665
+ };
2666
+ return [
2667
+ "继续当前需求同一阶段的审核。不要重复读取已知背景,只使用 spec_read 获取当前 commit 的增量变化。",
2668
+ `Requirement ID: ${requirement.id}`,
2669
+ `Current stage: ${requirement.stage}`,
2670
+ `Pinned commit: ${requirement.currentCommit}`,
2671
+ `Review run ID: ${run.id}`,
2672
+ `Review kind: ${run.kind}`,
2673
+ "",
2674
+ tasks[run.kind]
2675
+ ].join("\n");
2676
+ }
2677
+ function commentContinuationPrompt(requirement, comment, prompts) {
2678
+ return [
2679
+ "在当前需求同一阶段的既有上下文中分析这条新评论。不要重新扫描整个工作区;仅在评论涉及新的实现事实时做最小增量查询。",
2680
+ `Requirement ID: ${requirement.id}`,
2681
+ `Pinned commit: ${requirement.currentCommit}`,
2682
+ `Comment ID: ${comment.id}`,
2683
+ `Comment scope: ${comment.scope}`,
2684
+ `Anchor quote: ${comment.anchor?.quote ?? "整篇需求"}`,
2685
+ `Human comment: ${comment.body}`,
2686
+ "",
2687
+ prompts.comment
2688
+ ].join("\n");
2689
+ }
1616
2690
  //#endregion
1617
2691
  //#region src/routes.ts
1618
- const BODY_LIMIT = 2 * 1024 * 1024;
2692
+ const BODY_LIMIT = 6 * 1024 * 1024;
1619
2693
  const HEARTBEAT_MS = 15e3;
1620
2694
  function json(res, status, body) {
1621
2695
  res.writeHead(status, {
@@ -1668,13 +2742,126 @@ function makeRoutes(engine, coordinator) {
1668
2742
  });
1669
2743
  if (!guard(req, res)) return;
1670
2744
  const state = engine.snapshot();
2745
+ const summaries = engine.summaries();
2746
+ const currentId = new URL(req.url ?? "", `http://${req.headers.host ?? "127.0.0.1"}`).searchParams.get("requirementId") ?? summaries.find((item) => item.archivedAt === void 0)?.id ?? summaries[0]?.id;
2747
+ let requirement;
2748
+ try {
2749
+ requirement = currentId ? engine.view(currentId) : void 0;
2750
+ } catch {}
1671
2751
  json(res, 200, {
1672
2752
  revision: state.revision,
1673
2753
  participants: state.participants,
1674
- requirements: engine.list()
2754
+ requirements: summaries,
2755
+ ...requirement ? { requirement } : {}
1675
2756
  });
1676
2757
  }
1677
2758
  },
2759
+ {
2760
+ kind: "exact",
2761
+ path: `${API_PREFIX}/directory`,
2762
+ handler: (req, res) => {
2763
+ if (req.method !== "GET") return json(res, 405, {
2764
+ ok: false,
2765
+ error: "method-not-allowed"
2766
+ });
2767
+ if (!guard(req, res)) return;
2768
+ json(res, 200, {
2769
+ ok: true,
2770
+ participants: engine.directory()
2771
+ });
2772
+ }
2773
+ },
2774
+ {
2775
+ kind: "exact",
2776
+ path: `${API_PREFIX}/notifications`,
2777
+ handler: (req, res) => {
2778
+ if (req.method !== "GET") return json(res, 405, {
2779
+ ok: false,
2780
+ error: "method-not-allowed"
2781
+ });
2782
+ if (!guard(req, res)) return;
2783
+ const url = new URL(req.url ?? "", `http://${req.headers.host ?? "127.0.0.1"}`);
2784
+ const participantId = url.searchParams.get("participantId") ?? "";
2785
+ if (participantId.length < 8) return json(res, 400, {
2786
+ ok: false,
2787
+ error: "invalid-participant-query"
2788
+ });
2789
+ json(res, 200, {
2790
+ ok: true,
2791
+ ...engine.notifications(participantId, Number(url.searchParams.get("page") ?? 1), Number(url.searchParams.get("pageSize") ?? 50))
2792
+ });
2793
+ }
2794
+ },
2795
+ {
2796
+ kind: "exact",
2797
+ path: `${API_PREFIX}/insights`,
2798
+ handler: (req, res) => {
2799
+ if (req.method !== "GET") return json(res, 405, {
2800
+ ok: false,
2801
+ error: "method-not-allowed"
2802
+ });
2803
+ if (!guard(req, res)) return;
2804
+ const url = new URL(req.url ?? "", `http://${req.headers.host ?? "127.0.0.1"}`);
2805
+ const value = (key) => url.searchParams.get(key) || void 0;
2806
+ const requirementId = value("requirementId");
2807
+ const customerId = value("customerId");
2808
+ const companyId = value("companyId");
2809
+ const sourceId = value("sourceId");
2810
+ const importance = value("importance");
2811
+ json(res, 200, {
2812
+ ok: true,
2813
+ ...engine.insights({
2814
+ ...requirementId ? { requirementId } : {},
2815
+ ...customerId ? { customerId } : {},
2816
+ ...companyId ? { companyId } : {},
2817
+ ...sourceId ? { sourceId } : {},
2818
+ ...importance ? { importance } : {},
2819
+ page: Number(value("page") ?? 1),
2820
+ pageSize: Number(value("pageSize") ?? 50)
2821
+ })
2822
+ });
2823
+ }
2824
+ },
2825
+ {
2826
+ kind: "exact",
2827
+ path: `${API_PREFIX}/diff`,
2828
+ handler: async (req, res) => {
2829
+ if (!guard(req, res)) return;
2830
+ try {
2831
+ if (req.method === "GET") {
2832
+ const url = new URL(req.url ?? "", `http://${req.headers.host ?? "127.0.0.1"}`);
2833
+ return json(res, 200, {
2834
+ ok: true,
2835
+ diff: engine.diff(url.searchParams.get("requirementId") ?? "", url.searchParams.get("baseCommit") ?? "", url.searchParams.get("headCommit") || void 0)
2836
+ });
2837
+ }
2838
+ if (req.method === "POST") {
2839
+ if (!(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) return json(res, 415, {
2840
+ ok: false,
2841
+ error: "json-required"
2842
+ });
2843
+ const body = await readJson(req);
2844
+ if (typeof body.before !== "string" || typeof body.after !== "string") return json(res, 400, {
2845
+ ok: false,
2846
+ error: "invalid-diff-preview"
2847
+ });
2848
+ return json(res, 200, {
2849
+ ok: true,
2850
+ diff: buildStructuredDiff(body.before, body.after, typeof body.baseLabel === "string" ? body.baseLabel : void 0, typeof body.headLabel === "string" ? body.headLabel : void 0)
2851
+ });
2852
+ }
2853
+ return json(res, 405, {
2854
+ ok: false,
2855
+ error: "method-not-allowed"
2856
+ });
2857
+ } catch (error) {
2858
+ return json(res, 400, {
2859
+ ok: false,
2860
+ error: error instanceof Error ? error.message : String(error)
2861
+ });
2862
+ }
2863
+ }
2864
+ },
1678
2865
  {
1679
2866
  kind: "exact",
1680
2867
  path: `${API_PREFIX}/review-workspaces`,
@@ -1843,8 +3030,8 @@ function makeRoutes(engine, coordinator) {
1843
3030
  "cache-control": "no-cache",
1844
3031
  connection: "keep-alive"
1845
3032
  });
1846
- const push = () => {
1847
- res.write(`data: ${JSON.stringify({ revision: engine.snapshot().revision })}\n\n`);
3033
+ const push = (event) => {
3034
+ res.write(`data: ${JSON.stringify(event)}\n\n`);
1848
3035
  };
1849
3036
  const unsubscribe = engine.subscribe(push);
1850
3037
  const heartbeat = setInterval(() => {
@@ -1856,7 +3043,10 @@ function makeRoutes(engine, coordinator) {
1856
3043
  };
1857
3044
  req.once("close", close);
1858
3045
  res.once("close", close);
1859
- push();
3046
+ push({
3047
+ types: ["state.synced"],
3048
+ revision: engine.snapshot().revision
3049
+ });
1860
3050
  }
1861
3051
  }
1862
3052
  ];
@@ -1948,7 +3138,7 @@ function specReadTool(engine) {
1948
3138
  ];
1949
3139
  if (include.has("spec")) rows.push("", "## Spec", view.version.markdown);
1950
3140
  if (include.has("review-items")) rows.push("", "## Review Items", ...view.reviewItems.map((item) => `- ${item.id} [${item.severity}/${item.status}/${item.epistemicStatus}] ${item.statement}\n Question: ${item.question}\n Spec anchors: ${(item.sourceAnchors ?? []).map((anchor) => `${anchor.heading ? `${anchor.heading}: ` : ""}${anchor.quote}`).join(" / ") || "none"}\n Recommended options: ${(item.recommendedOptions ?? []).join(" / ") || "none"}\n Evidence: ${item.evidence.map((evidence) => `${evidence.source}${evidence.version ? `@${evidence.version}` : ""}`).join(", ") || "none"}`));
1951
- if (include.has("comments")) rows.push("", "## Comments", ...view.comments.map((item) => `- ${item.id} [${item.status}] “${item.anchor.quote}” ${item.author.nickname}: ${item.body}\n Replies: ${item.replies.map((reply) => `${reply.author.nickname}: ${reply.body}`).join(" / ") || "none"}`));
3141
+ if (include.has("comments")) rows.push("", "## Comments", ...view.comments.map((item) => `- ${item.id} [${item.status}] “${item.anchor?.quote ?? "整篇需求"}” ${item.author.nickname}: ${item.body}\n Replies: ${item.replies.map((reply) => `${reply.author.nickname}: ${reply.body}`).join(" / ") || "none"}`));
1952
3142
  if (include.has("decisions")) rows.push("", "## Decisions", ...view.decisions.map((item) => `- ${item.id} [${item.status}] ${item.question}: ${item.decision}`));
1953
3143
  if (include.has("confirmations")) rows.push("", "## Confirmations", ...view.confirmations.map((item) => `- ${item.role}/${item.scope}/${item.scopeId ?? "document"} [${item.status}] ${item.participant.nickname} @ ${item.commit}`));
1954
3144
  if (include.has("sources")) rows.push("", "## Sources", ...view.sources.map((item) => `- ${item.id} [${item.accessStatus}] ${item.label}${item.version ? ` @ ${item.version}` : ""}`));
@@ -2341,7 +3531,7 @@ function apply(ctx, config = {}) {
2341
3531
  const dataRoot = config.dataRoot ?? join(homedir(), ".dsh", "spec-collab");
2342
3532
  const contexts = new ReviewContextCatalog(config);
2343
3533
  const prompts = resolveReviewPrompts(config.prompts);
2344
- const engine = new CollaborationEngine(join(dataRoot, "collaboration-v2.json"), new GitRequirementStore(config.repositoryPath ?? join(dataRoot, "repository")));
3534
+ const engine = new CollaborationEngine(join(dataRoot, "collaboration-v3.json"), new GitRequirementStore(config.repositoryPath ?? join(dataRoot, "repository")), { legacyPath: join(dataRoot, "collaboration-v2.json") });
2345
3535
  const coordinator = new DshReviewCoordinator(ctx.apiProxy, contexts, prompts);
2346
3536
  engine.setCoordinator(coordinator);
2347
3537
  ctx.effect(() => {