dsh-spec-collab 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +84 -18
  3. package/docs/assets/demo-01-workspace.png +0 -0
  4. package/docs/assets/demo-02-ai-review.png +0 -0
  5. package/docs/assets/demo-03-patches.png +0 -0
  6. package/docs/assets/demo-04-decisions.png +0 -0
  7. package/docs/assets/demo-05-ready.png +0 -0
  8. package/docs/experience-review-checklist-2026-08-24.md +72 -45
  9. package/docs/insight-import-template.csv +3 -0
  10. package/docs/insight-import-template.md +19 -0
  11. package/docs/migration-v3.md +23 -0
  12. package/docs/usage-walkthrough.md +25 -43
  13. package/lib/client.js +10854 -1168
  14. package/lib/index.js +1313 -98
  15. package/lib/types/client/AccessibleDialog.d.ts +9 -0
  16. package/lib/types/client/AccessibleDialog.d.ts.map +1 -0
  17. package/lib/types/client/SpecWorkbench.d.ts +42 -2
  18. package/lib/types/client/SpecWorkbench.d.ts.map +1 -1
  19. package/lib/types/client/api.d.ts +26 -3
  20. package/lib/types/client/api.d.ts.map +1 -1
  21. package/lib/types/client/drafts.d.ts +8 -0
  22. package/lib/types/client/drafts.d.ts.map +1 -0
  23. package/lib/types/client/mount.d.ts.map +1 -1
  24. package/lib/types/client/review-anchors.d.ts.map +1 -1
  25. package/lib/types/client/workflow.d.ts.map +1 -1
  26. package/lib/types/engine.d.ts +37 -3
  27. package/lib/types/engine.d.ts.map +1 -1
  28. package/lib/types/git-store.d.ts +6 -0
  29. package/lib/types/git-store.d.ts.map +1 -1
  30. package/lib/types/protocol.d.ts +245 -10
  31. package/lib/types/protocol.d.ts.map +1 -1
  32. package/lib/types/ready-admission.d.ts +14 -0
  33. package/lib/types/ready-admission.d.ts.map +1 -0
  34. package/lib/types/review-runtime.d.ts +6 -0
  35. package/lib/types/review-runtime.d.ts.map +1 -1
  36. package/lib/types/routes.d.ts.map +1 -1
  37. package/lib/types/structured-diff.d.ts +3 -0
  38. package/lib/types/structured-diff.d.ts.map +1 -0
  39. package/package.json +14 -4
  40. package/src/client/AccessibleDialog.tsx +42 -0
  41. package/src/client/SpecWorkbench.tsx +776 -87
  42. package/src/client/api.ts +8 -3
  43. package/src/client/drafts.ts +51 -0
  44. package/src/client/mount.tsx +11 -6
  45. package/src/client/review-anchors.ts +1 -0
  46. package/src/client/workbench.module.css +223 -79
  47. package/src/client/workflow.ts +8 -9
  48. package/src/engine.ts +448 -46
  49. package/src/git-store.ts +87 -18
  50. package/src/index.ts +1 -1
  51. package/src/protocol.ts +64 -13
  52. package/src/ready-admission.ts +29 -0
  53. package/src/review-runtime.ts +39 -11
  54. package/src/routes.ts +33 -4
  55. package/src/structured-diff.ts +75 -0
  56. package/src/tools.ts +1 -1
  57. package/docs/assets/spec-collab-walkthrough.mp4 +0 -0
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,170 @@ 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
485
+ //#region src/ready-admission.ts
486
+ function hasCompletedCurrentReview(record, kind) {
487
+ return record.aiRuns.some((run) => run.commit === record.currentCommit && run.kind === kind && run.status === "completed");
488
+ }
489
+ function hasVersionConfirmation(record, role) {
490
+ return record.confirmations.some((item) => item.commit === record.currentCommit && item.role === role && item.scope === "version" && item.status === "active");
491
+ }
492
+ /** Shared by workflow guidance and the authoritative Ready write. Checks must come from the current Git body. */
493
+ function readyAdmission(record, checks) {
494
+ const activeRun = record.aiRuns.slice().reverse().find((run) => run.commit === record.currentCommit && (run.status === "queued" || run.status === "running"));
495
+ const engineeringReviewed = hasCompletedCurrentReview(record, "engineering-precheck");
496
+ const pendingPatches = record.patches.filter((item) => item.baseCommit === record.currentCommit && item.status === "pending");
497
+ const failedChecks = checks.filter((check) => !check.passed);
498
+ const productConfirmed = hasVersionConfirmation(record, "product");
499
+ const engineeringConfirmed = hasVersionConfirmation(record, "engineering");
500
+ return {
501
+ activeRun,
502
+ engineeringReviewed,
503
+ pendingPatches,
504
+ failedChecks,
505
+ productConfirmed,
506
+ engineeringConfirmed,
507
+ error: record.stage !== "joint-review" ? "readiness gate is not satisfied" : !record.workspaceId?.trim() ? "review workspace is required" : activeRun ? "current version review is still running" : !engineeringReviewed ? "engineering precheck is required for the current version" : pendingPatches.length > 0 ? "current version has pending patches" : failedChecks.length > 0 ? "readiness gate is not satisfied" : !productConfirmed || !engineeringConfirmed ? "current version needs product and engineering confirmation" : void 0
508
+ };
509
+ }
510
+ //#endregion
261
511
  //#region src/engine.ts
262
512
  const emptyState = () => ({
263
- schemaVersion: 2,
513
+ schemaVersion: 3,
264
514
  revision: 0,
265
515
  participants: [],
266
- requirements: []
516
+ requirements: [],
517
+ companies: [],
518
+ customers: [],
519
+ feedbackSources: [],
520
+ insights: [],
521
+ insightLinks: [],
522
+ notifications: []
267
523
  });
268
524
  var CollaborationEngine = class {
269
525
  eventPath;
270
526
  versions;
527
+ options;
271
528
  state;
272
529
  coordinator;
273
530
  listeners = /* @__PURE__ */ new Set();
274
531
  seen = /* @__PURE__ */ new Map();
275
- constructor(eventPath, versions) {
532
+ eventContext;
533
+ constructor(eventPath, versions, options = {}) {
276
534
  this.eventPath = eventPath;
277
535
  this.versions = versions;
536
+ this.options = options;
278
537
  this.state = this.load();
279
538
  }
280
539
  setCoordinator(coordinator) {
@@ -283,6 +542,42 @@ var CollaborationEngine = class {
283
542
  snapshot() {
284
543
  return structuredClone(this.state);
285
544
  }
545
+ directory() {
546
+ return structuredClone(this.state.participants).sort((left, right) => left.nickname.localeCompare(right.nickname, "zh-CN"));
547
+ }
548
+ notifications(participantId, page = 1, pageSize = 50) {
549
+ const rows = this.state.notifications.filter((item) => item.recipientParticipantId === participantId).sort((left, right) => right.createdAt - left.createdAt);
550
+ const safePage = Number.isFinite(page) ? Math.max(1, Math.trunc(page)) : 1;
551
+ const safePageSize = Number.isFinite(pageSize) ? Math.min(100, Math.max(1, Math.trunc(pageSize))) : 50;
552
+ const start = (safePage - 1) * safePageSize;
553
+ return {
554
+ items: structuredClone(rows.slice(start, start + safePageSize)),
555
+ total: rows.length,
556
+ unread: rows.filter((item) => item.readAt === void 0).length
557
+ };
558
+ }
559
+ insights(query = {}) {
560
+ const linkedIds = query.requirementId === void 0 ? void 0 : new Set(this.state.insightLinks.filter((link) => link.requirementId === query.requirementId).map((link) => link.insightId));
561
+ const rows = this.state.insights.filter((item) => {
562
+ const companyId = item.companyId ?? (item.customerId ? this.state.customers.find((customer) => customer.id === item.customerId)?.companyId : void 0);
563
+ 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);
564
+ }).sort((left, right) => right.capturedAt - left.capturedAt);
565
+ const pageSize = Math.min(100, Math.max(1, query.pageSize ?? 50));
566
+ const start = Math.max(0, (query.page ?? 1) - 1) * pageSize;
567
+ const page = rows.slice(start, start + pageSize);
568
+ const ids = new Set(page.map((item) => item.id));
569
+ const customerIds = new Set(page.flatMap((item) => item.customerId ? [item.customerId] : []));
570
+ const companyIds = new Set(page.flatMap((item) => item.companyId ? [item.companyId] : []));
571
+ for (const customer of this.state.customers.filter((item) => customerIds.has(item.id))) if (customer.companyId) companyIds.add(customer.companyId);
572
+ return {
573
+ items: structuredClone(page),
574
+ total: rows.length,
575
+ links: structuredClone(this.state.insightLinks.filter((item) => ids.has(item.insightId))),
576
+ customers: structuredClone(this.state.customers.filter((item) => customerIds.has(item.id))),
577
+ companies: structuredClone(this.state.companies.filter((item) => companyIds.has(item.id))),
578
+ sources: structuredClone(this.state.feedbackSources.filter((item) => page.some((insight) => insight.sourceId === item.id)))
579
+ };
580
+ }
286
581
  subscribe(listener) {
287
582
  this.listeners.add(listener);
288
583
  return () => this.listeners.delete(listener);
@@ -290,11 +585,31 @@ var CollaborationEngine = class {
290
585
  list() {
291
586
  return this.state.requirements.map((item) => this.view(item.id));
292
587
  }
588
+ summaries() {
589
+ return this.state.requirements.map((record) => ({
590
+ id: record.id,
591
+ title: record.title,
592
+ stage: record.stage,
593
+ currentCommit: record.currentCommit,
594
+ ...record.workspaceId ? { workspaceId: record.workspaceId } : {},
595
+ ...record.archivedAt ? { archivedAt: record.archivedAt } : {},
596
+ updatedAt: record.updatedAt,
597
+ metrics: requirementMetrics(record, this.state),
598
+ participantIds: requirementParticipantIds(record, this.versions.history(record.id))
599
+ }));
600
+ }
293
601
  version(requirementId, commit) {
294
602
  const record = this.record(requirementId);
295
603
  if (!this.versions.history(record.id).some((version) => version.commit === commit)) throw new Error("requirement version not found");
296
604
  return this.versions.read(record.id, commit);
297
605
  }
606
+ diff(requirementId, baseCommit, headCommit) {
607
+ const record = this.record(requirementId);
608
+ const head = headCommit ?? record.currentCommit;
609
+ const before = this.version(requirementId, baseCommit);
610
+ const after = this.version(requirementId, head);
611
+ return buildStructuredDiff(before.markdown, after.markdown, baseCommit.slice(0, 10), head.slice(0, 10));
612
+ }
298
613
  myItems(participant, category) {
299
614
  const rows = [];
300
615
  for (const record of this.state.requirements) for (const item of record.actionItems.filter((candidate) => candidate.status === "pending")) {
@@ -305,6 +620,7 @@ var CollaborationEngine = class {
305
620
  ...structuredClone(item),
306
621
  category: current,
307
622
  requirementTitle: record.title,
623
+ objectTitle: actionObjectTitle(record, item),
308
624
  target: actionTarget(item)
309
625
  });
310
626
  }
@@ -317,17 +633,23 @@ var CollaborationEngine = class {
317
633
  view(id) {
318
634
  const record = this.record(id);
319
635
  const version = this.versions.read(id, record.currentCommit);
636
+ const commitUrl = this.versions.commitUrl(record.currentCommit);
320
637
  return {
321
638
  ...structuredClone(record),
322
639
  version,
323
640
  history: this.versions.history(id),
324
- readiness: readiness(version.markdown, record)
641
+ readiness: readiness(version.markdown, record),
642
+ metrics: requirementMetrics(record, this.state),
643
+ ...commitUrl ? { commitUrl } : {}
325
644
  };
326
645
  }
327
646
  apply(requestId, action) {
328
647
  const cached = this.seen.get(requestId);
329
648
  if (cached !== void 0) return structuredClone(cached);
330
649
  let result;
650
+ const beforeState = structuredClone(this.state);
651
+ const previousEventContext = this.eventContext;
652
+ this.eventContext = eventForAction(action);
331
653
  try {
332
654
  const registered = action.participant.kind === "human" ? this.state.participants.find((item) => item.participantId === action.participant.participantId) : void 0;
333
655
  if (registered !== void 0 && registered.role !== action.participant.role) throw new Error(`participant role is bound to ${registered.role}`);
@@ -341,10 +663,11 @@ var CollaborationEngine = class {
341
663
  } : {
342
664
  ok: true,
343
665
  revision: this.state.revision,
344
- requirement: this.view(result.requirement.id)
666
+ requirement: result.requirement
345
667
  };
346
668
  }
347
669
  } catch (error) {
670
+ this.state = beforeState;
348
671
  const conflict = error instanceof VersionConflictError && action.kind === "version.save" ? this.saveConflict(action) : void 0;
349
672
  result = {
350
673
  ok: false,
@@ -353,6 +676,7 @@ var CollaborationEngine = class {
353
676
  ...conflict === void 0 ? {} : { conflict }
354
677
  };
355
678
  }
679
+ this.eventContext = previousEventContext;
356
680
  this.seen.set(requestId, result);
357
681
  return structuredClone(result);
358
682
  }
@@ -382,7 +706,11 @@ var CollaborationEngine = class {
382
706
  run.status = "completed";
383
707
  run.maturitySummary = input.maturitySummary;
384
708
  run.updatedAt = now;
385
- this.persist();
709
+ this.persist({
710
+ types: ["ai.status", "metrics.changed"],
711
+ requirementId: record.id,
712
+ objectId: run.id
713
+ });
386
714
  }
387
715
  submitPatch(input) {
388
716
  const record = this.record(input.requirementId);
@@ -416,7 +744,11 @@ var CollaborationEngine = class {
416
744
  createdAt: Date.now(),
417
745
  updatedAt: Date.now()
418
746
  });
419
- this.persist();
747
+ this.persist({
748
+ types: ["ai.status", "metrics.changed"],
749
+ requirementId: record.id,
750
+ objectId: patch.id
751
+ });
420
752
  }
421
753
  submitAiReply(input) {
422
754
  assertChineseFeedback(input.body);
@@ -426,11 +758,20 @@ var CollaborationEngine = class {
426
758
  id: randomUUID(),
427
759
  author: input.ai,
428
760
  body: input.body,
761
+ mentions: [],
429
762
  createdAt: Date.now()
430
763
  });
431
764
  comment.aiStatus = "completed";
432
765
  comment.updatedAt = Date.now();
433
- this.persist();
766
+ this.persist({
767
+ types: [
768
+ "ai.status",
769
+ "comment.changed",
770
+ "metrics.changed"
771
+ ],
772
+ requirementId: record.id,
773
+ objectId: comment.id
774
+ });
434
775
  }
435
776
  markAiFailure(requirementId, sourceId, error) {
436
777
  const record = this.record(requirementId);
@@ -445,7 +786,11 @@ var CollaborationEngine = class {
445
786
  comment.aiStatus = "failed";
446
787
  comment.updatedAt = Date.now();
447
788
  }
448
- this.persist();
789
+ this.persist({
790
+ types: ["ai.status", "metrics.changed"],
791
+ requirementId,
792
+ objectId: sourceId
793
+ });
449
794
  }
450
795
  applyFresh(action) {
451
796
  const now = Date.now();
@@ -465,6 +810,7 @@ var CollaborationEngine = class {
465
810
  id: created.requirementId,
466
811
  title,
467
812
  stage: "product-review",
813
+ stageCycle: 0,
468
814
  currentCommit: created.version.commit,
469
815
  workspaceId,
470
816
  sources: action.sources,
@@ -475,11 +821,12 @@ var CollaborationEngine = class {
475
821
  confirmations: [],
476
822
  actionItems: [],
477
823
  aiRuns: [],
824
+ aiConversations: [],
478
825
  createdAt: now,
479
826
  updatedAt: now
480
827
  };
481
828
  this.state.requirements.unshift(record);
482
- this.persist();
829
+ this.persist(void 0, true);
483
830
  this.enqueueReview(record, action.participant, "product-first");
484
831
  return {
485
832
  ok: true,
@@ -518,11 +865,11 @@ var CollaborationEngine = class {
518
865
  record.currentCommit = version.commit;
519
866
  record.updatedAt = now;
520
867
  invalidateAffected(record, [], []);
521
- this.persist();
868
+ this.persist(void 0, true);
522
869
  this.enqueueReview(record, action.participant, "change-review");
523
- } else if (action.kind === "requirement.archive") {
870
+ } else if (action.kind === "requirement.archive" || action.kind === "requirement.unarchive") {
524
871
  requireHuman(action.participant);
525
- if (action.archived) record.archivedAt = now;
872
+ if (action.kind === "requirement.archive" && action.archived) record.archivedAt = now;
526
873
  else delete record.archivedAt;
527
874
  record.updatedAt = now;
528
875
  this.persist();
@@ -531,7 +878,8 @@ var CollaborationEngine = class {
531
878
  const deleted = this.view(record.id);
532
879
  this.versions.remove(record.id, action.participant);
533
880
  this.state.requirements.splice(this.state.requirements.indexOf(record), 1);
534
- this.persist();
881
+ this.state.insightLinks = this.state.insightLinks.filter((item) => item.requirementId !== record.id);
882
+ this.persist(void 0, true);
535
883
  return {
536
884
  ok: true,
537
885
  revision: this.state.revision,
@@ -556,8 +904,31 @@ var CollaborationEngine = class {
556
904
  record.patches.filter((item) => item.status === "pending").forEach((item) => {
557
905
  item.status = "stale";
558
906
  });
559
- if (record.stage === "ready") record.stage = "joint-review";
560
- this.persist();
907
+ if (record.stage === "ready") enterStage(record, "joint-review");
908
+ this.persist(void 0, true);
909
+ this.enqueueReview(record, action.participant, "change-review");
910
+ } else if (action.kind === "version.restore") {
911
+ requireHuman(action.participant);
912
+ const historical = this.version(record.id, action.commit);
913
+ if (historical.commit === record.currentCommit) throw new Error("selected version is already current");
914
+ const before = this.versions.read(record.id, record.currentCommit).markdown;
915
+ const version = this.versions.save({
916
+ requirementId: record.id,
917
+ baseCommit: record.currentCommit,
918
+ markdown: historical.markdown,
919
+ participant: action.participant,
920
+ summary: action.summary.trim() || `恢复版本 ${historical.commit.slice(0, 8)}`
921
+ });
922
+ const impact = changedScopes(before, historical.markdown);
923
+ record.currentCommit = version.commit;
924
+ record.updatedAt = now;
925
+ delete record.readyPackage;
926
+ invalidateAffected(record, impact.sections, impact.acceptanceIds, historical.markdown);
927
+ record.patches.filter((item) => item.status === "pending").forEach((item) => {
928
+ item.status = "stale";
929
+ });
930
+ if (record.stage === "ready") enterStage(record, "joint-review");
931
+ this.persist(void 0, true);
561
932
  this.enqueueReview(record, action.participant, "change-review");
562
933
  } else if (action.kind === "review.request") {
563
934
  requireHuman(action.participant);
@@ -582,20 +953,25 @@ var CollaborationEngine = class {
582
953
  } else if (action.kind === "comment.create") {
583
954
  requireHuman(action.participant);
584
955
  if (action.commit !== record.currentCommit) throw new VersionConflictError(record.currentCommit);
956
+ const scope = action.scope ?? "inline";
957
+ const mentions = validMentions(action.mentions, this.state.participants);
585
958
  const comment = {
586
959
  id: randomUUID(),
587
960
  requirementId: record.id,
588
961
  commit: action.commit,
589
- anchor: action.anchor,
962
+ scope,
963
+ ...action.anchor === void 0 ? {} : { anchor: action.anchor },
590
964
  author: action.participant,
591
965
  body: action.body.trim(),
966
+ mentions,
592
967
  replies: [],
593
968
  aiStatus: "queued",
594
969
  status: "open",
595
970
  createdAt: now,
596
971
  updatedAt: now
597
972
  };
598
- if (comment.body === "" || comment.anchor.quote.trim() === "") throw new Error("comment and anchor are required");
973
+ if (comment.body === "" || scope === "inline" && action.anchor?.quote.trim() === "") throw new Error(scope === "inline" ? "comment and anchor are required" : "comment is required");
974
+ if (scope === "inline" && action.anchor === void 0) throw new Error("comment and anchor are required");
599
975
  record.comments.push(comment);
600
976
  record.actionItems.push({
601
977
  id: randomUUID(),
@@ -610,30 +986,50 @@ var CollaborationEngine = class {
610
986
  createdAt: now,
611
987
  updatedAt: now
612
988
  });
989
+ for (const participantId of mentions) this.notify(participantId, "mention", record, "comment", comment.id, `${action.participant.nickname} 在评论中提到了你`);
613
990
  this.persist();
614
991
  const coordinator = this.coordinator;
615
992
  if (coordinator !== void 0) {
616
993
  const view = this.view(record.id);
994
+ const requestedStage = record.stage;
995
+ const requestedStageCycle = record.stageCycle;
996
+ const existingSession = record.aiConversations.find((item) => item.stage === requestedStage && item.stageCycle === requestedStageCycle)?.sessionId;
617
997
  coordinator.requestCommentReply({
618
998
  requirement: view,
619
- comment
999
+ comment,
1000
+ ...existingSession ? { sessionId: existingSession } : {}
620
1001
  }).then((sessionId) => {
621
1002
  comment.aiStatus = "running";
622
1003
  comment.aiSessionId = sessionId;
623
1004
  comment.updatedAt = Date.now();
624
- this.persist();
1005
+ this.rememberStageConversation(record, sessionId, requestedStage, requestedStageCycle);
1006
+ this.persist({
1007
+ types: [
1008
+ "ai.status",
1009
+ "comment.changed",
1010
+ "metrics.changed"
1011
+ ],
1012
+ requirementId: record.id,
1013
+ objectId: comment.id
1014
+ });
625
1015
  }, (error) => this.markAiFailure(record.id, comment.id, error instanceof Error ? error.message : String(error)));
626
1016
  }
627
1017
  } else if (action.kind === "comment.reply") {
628
1018
  requireHuman(action.participant);
629
1019
  const comment = this.comment(record, action.commentId);
1020
+ const body = action.body.trim();
1021
+ if (body === "") throw new Error("reply is required");
1022
+ const mentions = validMentions(action.mentions, this.state.participants);
630
1023
  comment.replies.push({
631
1024
  id: randomUUID(),
632
1025
  author: action.participant,
633
- body: action.body.trim(),
1026
+ body,
1027
+ mentions,
634
1028
  createdAt: now
635
1029
  });
636
1030
  comment.updatedAt = now;
1031
+ if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, "reply", record, "comment", comment.id, `${action.participant.nickname} 回复了你的评论`);
1032
+ for (const participantId of mentions) this.notify(participantId, "mention", record, "comment", comment.id, `${action.participant.nickname} 在回复中提到了你`);
637
1033
  this.persist();
638
1034
  } else if (action.kind === "comment.resolve") {
639
1035
  requireHuman(action.participant);
@@ -641,11 +1037,34 @@ var CollaborationEngine = class {
641
1037
  comment.status = "resolved";
642
1038
  comment.resolution = action.resolution;
643
1039
  comment.updatedAt = now;
1040
+ if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, "status-change", record, "comment", comment.id, `${action.participant.nickname} 已解决你的评论`);
644
1041
  record.actionItems.filter((task) => task.sourceId === comment.id && task.status === "pending").forEach((task) => {
645
1042
  task.status = "handled";
646
1043
  task.updatedAt = now;
647
1044
  });
648
1045
  this.persist();
1046
+ } else if (action.kind === "comment.reopen") {
1047
+ requireHuman(action.participant);
1048
+ const comment = this.comment(record, action.commentId);
1049
+ if (comment.status !== "resolved") throw new Error("resolved comment not found");
1050
+ comment.status = "open";
1051
+ delete comment.resolution;
1052
+ comment.updatedAt = now;
1053
+ record.actionItems.push({
1054
+ id: randomUUID(),
1055
+ requirementId: record.id,
1056
+ sourceType: "comment",
1057
+ sourceId: comment.id,
1058
+ type: "reply",
1059
+ assigneeRole: comment.author.role === "product" ? "engineering" : "product",
1060
+ blocking: false,
1061
+ status: "pending",
1062
+ dueStage: record.stage,
1063
+ createdAt: now,
1064
+ updatedAt: now
1065
+ });
1066
+ if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, "status-change", record, "comment", comment.id, `${action.participant.nickname} 重新打开了你的评论`);
1067
+ this.persist();
649
1068
  } else if (action.kind === "patch.accept") {
650
1069
  requireHuman(action.participant);
651
1070
  const patch = record.patches.find((item) => item.id === action.patchId);
@@ -662,6 +1081,11 @@ var CollaborationEngine = class {
662
1081
  record.currentCommit = version.commit;
663
1082
  patch.status = "accepted";
664
1083
  record.updatedAt = now;
1084
+ delete record.readyPackage;
1085
+ record.patches.filter((item) => item.id !== patch.id && item.status === "pending").forEach((item) => {
1086
+ item.status = "stale";
1087
+ });
1088
+ if (record.stage === "ready") enterStage(record, "joint-review");
665
1089
  for (const id of patch.affectedReviewItemIds) {
666
1090
  const item = record.reviewItems.find((candidate) => candidate.id === id);
667
1091
  if (item !== void 0) {
@@ -674,7 +1098,7 @@ var CollaborationEngine = class {
674
1098
  task.status = "handled";
675
1099
  task.updatedAt = now;
676
1100
  });
677
- this.persist();
1101
+ this.persist(void 0, true);
678
1102
  this.enqueueReview(record, action.participant, "change-review");
679
1103
  } else if (action.kind === "patch.reject") {
680
1104
  requireHuman(action.participant);
@@ -724,9 +1148,8 @@ var CollaborationEngine = class {
724
1148
  this.persist();
725
1149
  } else if (action.kind === "ready.generate") {
726
1150
  requireHuman(action.participant);
727
- const checks = readiness(this.versions.read(record.id, record.currentCommit).markdown, record);
728
- if (record.stage !== "joint-review" || checks.some((check) => !check.passed)) throw new Error("readiness gate is not satisfied");
729
- if (!hasVersionConfirmation(record, "product") || !hasVersionConfirmation(record, "engineering")) throw new Error("current version needs product and engineering confirmation");
1151
+ const admission = readyAdmission(record, readiness(this.versions.read(record.id, record.currentCommit).markdown, record));
1152
+ if (admission.error) throw new Error(admission.error);
730
1153
  const markdown = readyMarkdown(this.view(record.id));
731
1154
  record.readyPackage = {
732
1155
  requirementId: record.id,
@@ -736,7 +1159,157 @@ var CollaborationEngine = class {
736
1159
  generatedBy: action.participant,
737
1160
  markdown
738
1161
  };
739
- record.stage = "ready";
1162
+ enterStage(record, "ready");
1163
+ this.persist();
1164
+ } else if (action.kind === "participant.register") {
1165
+ requireHuman(action.participant);
1166
+ const participant = this.state.participants.find((item) => item.participantId === action.participant.participantId);
1167
+ if (participant !== void 0) {
1168
+ participant.nickname = action.participant.nickname;
1169
+ participant.role = action.participant.role;
1170
+ this.persist();
1171
+ }
1172
+ } else if (action.kind === "action.assign") {
1173
+ requireHuman(action.participant);
1174
+ const task = record.actionItems.find((item) => item.id === action.actionItemId);
1175
+ if (task === void 0) throw new Error("action item not found");
1176
+ 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");
1177
+ task.assigneeRole = action.assigneeRole;
1178
+ if (action.dueStage !== void 0) task.dueStage = action.dueStage;
1179
+ if (action.assigneeParticipantId === void 0) delete task.assigneeParticipantId;
1180
+ else {
1181
+ task.assigneeParticipantId = action.assigneeParticipantId;
1182
+ this.notify(action.assigneeParticipantId, "assignment", record, "action", task.id, `${action.participant.nickname} 向你指派了一个待办`);
1183
+ }
1184
+ task.updatedAt = now;
1185
+ this.persist();
1186
+ } else if (action.kind === "notification.mark-read") {
1187
+ requireHuman(action.participant);
1188
+ const ids = new Set(action.notificationIds);
1189
+ this.state.notifications.filter((item) => item.recipientParticipantId === action.participant.participantId && item.requirementId === record.id && ids.has(item.id)).forEach((item) => {
1190
+ item.readAt ??= now;
1191
+ });
1192
+ this.persist();
1193
+ } else if (action.kind === "source.upsert") {
1194
+ requireHuman(action.participant);
1195
+ const input = cleanSource(action.source);
1196
+ const existing = this.state.feedbackSources.find((item) => item.id === input.id);
1197
+ const source = {
1198
+ ...input,
1199
+ createdAt: existing?.createdAt ?? now,
1200
+ updatedAt: now
1201
+ };
1202
+ validateSource(source);
1203
+ if (existing === void 0) this.state.feedbackSources.push(source);
1204
+ else Object.assign(existing, source);
1205
+ this.persist();
1206
+ } else if (action.kind === "company.upsert") {
1207
+ requireHuman(action.participant);
1208
+ const input = cleanCompany(action.company);
1209
+ validateCompany(input);
1210
+ const existing = this.state.companies.find((item) => item.id === input.id);
1211
+ const company = {
1212
+ ...input,
1213
+ createdAt: existing?.createdAt ?? now,
1214
+ updatedAt: now
1215
+ };
1216
+ if (existing === void 0) this.state.companies.push(company);
1217
+ else Object.assign(existing, company);
1218
+ this.persist();
1219
+ } else if (action.kind === "customer.upsert") {
1220
+ requireHuman(action.participant);
1221
+ const input = cleanCustomer(action.customer);
1222
+ validateCustomer(input, this.state);
1223
+ const existing = this.state.customers.find((item) => item.id === input.id);
1224
+ const customer = {
1225
+ ...input,
1226
+ createdAt: existing?.createdAt ?? now,
1227
+ updatedAt: now
1228
+ };
1229
+ if (existing === void 0) this.state.customers.push(customer);
1230
+ else Object.assign(existing, customer);
1231
+ this.persist();
1232
+ } else if (action.kind === "insight.create") {
1233
+ requireHuman(action.participant);
1234
+ const insight = this.createInsight(record.id, action.insight, action.participant, now);
1235
+ for (const link of action.links ?? []) this.addInsightLink(insight.id, link, action.participant, now);
1236
+ this.persist();
1237
+ } else if (action.kind === "insight.update") {
1238
+ requireHuman(action.participant);
1239
+ const insight = this.state.insights.find((item) => item.id === action.insightId);
1240
+ if (insight === void 0) throw new Error("insight not found");
1241
+ Object.assign(insight, action.changes);
1242
+ validateInsight(insight, this.state);
1243
+ insight.dedupeHash = insightHash(insight.sourceId, insight.body);
1244
+ insight.updatedAt = now;
1245
+ this.persist();
1246
+ } else if (action.kind === "insight.delete") {
1247
+ requireHuman(action.participant);
1248
+ const index = this.state.insights.findIndex((item) => item.id === action.insightId);
1249
+ if (index < 0) throw new Error("insight not found");
1250
+ this.state.insights.splice(index, 1);
1251
+ this.state.insightLinks = this.state.insightLinks.filter((item) => item.insightId !== action.insightId);
1252
+ this.persist();
1253
+ } else if (action.kind === "insight.link") {
1254
+ requireHuman(action.participant);
1255
+ this.addInsightLink(action.insightId, action.link, action.participant, now);
1256
+ this.persist();
1257
+ } else if (action.kind === "insight.unlink") {
1258
+ requireHuman(action.participant);
1259
+ if (this.state.insightLinks.find((item) => item.id === action.linkId) === void 0) throw new Error("insight link not found");
1260
+ this.state.insightLinks = this.state.insightLinks.filter((item) => item.id !== action.linkId);
1261
+ this.persist();
1262
+ } else if (action.kind === "insight.import") {
1263
+ requireHuman(action.participant);
1264
+ 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");
1265
+ const before = structuredClone(this.state);
1266
+ try {
1267
+ for (const row of [...action.source ? [action.source] : [], ...action.sources ?? []]) {
1268
+ const source = {
1269
+ ...cleanSource(row),
1270
+ createdAt: now,
1271
+ updatedAt: now
1272
+ };
1273
+ validateSource(source);
1274
+ const existing = this.state.feedbackSources.find((item) => item.id === source.id);
1275
+ if (existing) Object.assign(existing, source, { createdAt: existing.createdAt });
1276
+ else this.state.feedbackSources.push(source);
1277
+ }
1278
+ for (const row of action.companies ?? []) {
1279
+ const company = cleanCompany(row);
1280
+ validateCompany(company);
1281
+ const existing = this.state.companies.find((item) => item.id === company.id);
1282
+ if (existing) Object.assign(existing, company, {
1283
+ createdAt: existing.createdAt,
1284
+ updatedAt: now
1285
+ });
1286
+ else this.state.companies.push({
1287
+ ...company,
1288
+ createdAt: now,
1289
+ updatedAt: now
1290
+ });
1291
+ }
1292
+ for (const row of action.customers ?? []) {
1293
+ const customer = cleanCustomer(row);
1294
+ validateCustomer(customer, this.state);
1295
+ const existing = this.state.customers.find((item) => item.id === customer.id);
1296
+ if (existing) Object.assign(existing, customer, {
1297
+ createdAt: existing.createdAt,
1298
+ updatedAt: now
1299
+ });
1300
+ else this.state.customers.push({
1301
+ ...customer,
1302
+ createdAt: now,
1303
+ updatedAt: now
1304
+ });
1305
+ }
1306
+ const actualIds = /* @__PURE__ */ new Map();
1307
+ for (const row of action.rows) actualIds.set(row.id, this.createInsight(record.id, row, action.participant, now).id);
1308
+ for (const link of action.links ?? []) this.addInsightLink(actualIds.get(link.insightId) ?? link.insightId, link, action.participant, now);
1309
+ } catch (error) {
1310
+ this.state = before;
1311
+ throw error;
1312
+ }
740
1313
  this.persist();
741
1314
  } else if (action.kind === "downstream.return") {
742
1315
  requireHuman(action.participant);
@@ -765,7 +1338,7 @@ var CollaborationEngine = class {
765
1338
  record.actionItems.push(actionForReview(item));
766
1339
  invalidateAffected(record, item.affectedSections, item.affectedAcceptanceIds);
767
1340
  delete record.readyPackage;
768
- record.stage = "joint-review";
1341
+ enterStage(record, "joint-review");
769
1342
  record.updatedAt = now;
770
1343
  this.persist();
771
1344
  this.enqueueReview(record, action.participant, "change-review");
@@ -776,6 +1349,76 @@ var CollaborationEngine = class {
776
1349
  requirement: this.view(record.id)
777
1350
  };
778
1351
  }
1352
+ createInsight(requirementId, input, participant, now) {
1353
+ const draft = {
1354
+ ...input,
1355
+ title: input.title.trim(),
1356
+ body: input.body.trim(),
1357
+ dedupeHash: insightHash(input.sourceId, input.body),
1358
+ createdBy: participant,
1359
+ createdAt: now,
1360
+ updatedAt: now
1361
+ };
1362
+ validateInsight(draft, this.state);
1363
+ const existing = this.state.insights.find((item) => item.dedupeHash === draft.dedupeHash);
1364
+ const insight = existing ?? draft;
1365
+ if (existing === void 0) this.state.insights.push(insight);
1366
+ if (!this.state.insightLinks.some((item) => item.insightId === insight.id && item.requirementId === requirementId && item.targetType === "requirement")) this.state.insightLinks.push({
1367
+ id: randomUUID(),
1368
+ insightId: insight.id,
1369
+ requirementId,
1370
+ targetType: "requirement",
1371
+ createdBy: participant,
1372
+ createdAt: now
1373
+ });
1374
+ return insight;
1375
+ }
1376
+ addInsightLink(insightId, link, participant, now) {
1377
+ if (!this.state.insights.some((item) => item.id === insightId)) throw new Error("insight not found");
1378
+ this.record(link.requirementId);
1379
+ if (![
1380
+ "requirement",
1381
+ "section",
1382
+ "acceptance-criterion"
1383
+ ].includes(link.targetType)) throw new Error("invalid insight link target type");
1384
+ if (link.targetType !== "requirement" && !link.targetId?.trim()) throw new Error("linked section or acceptance criterion id is required");
1385
+ 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({
1386
+ id: randomUUID(),
1387
+ insightId,
1388
+ ...link,
1389
+ createdBy: participant,
1390
+ createdAt: now
1391
+ });
1392
+ }
1393
+ rememberStageConversation(record, sessionId, stage = record.stage, stageCycle = record.stageCycle) {
1394
+ const now = Date.now();
1395
+ const existing = record.aiConversations.find((item) => item.stage === stage && item.stageCycle === stageCycle);
1396
+ if (existing) {
1397
+ existing.sessionId = sessionId;
1398
+ existing.updatedAt = now;
1399
+ } else record.aiConversations.push({
1400
+ stage,
1401
+ stageCycle,
1402
+ sessionId,
1403
+ createdAt: now,
1404
+ updatedAt: now
1405
+ });
1406
+ }
1407
+ notify(recipientParticipantId, kind, record, objectType, objectId, message) {
1408
+ if (!this.state.participants.some((item) => item.participantId === recipientParticipantId)) return;
1409
+ const deepLink = `#spec-collab/${encodeURIComponent(record.id)}/${objectType === "comment" ? "discussion" : "tasks"}/${encodeURIComponent(objectId)}?commit=${encodeURIComponent(record.currentCommit)}`;
1410
+ this.state.notifications.push({
1411
+ id: randomUUID(),
1412
+ recipientParticipantId,
1413
+ kind,
1414
+ requirementId: record.id,
1415
+ objectType,
1416
+ objectId,
1417
+ message,
1418
+ deepLink,
1419
+ createdAt: Date.now()
1420
+ });
1421
+ }
779
1422
  saveConflict(action) {
780
1423
  const record = this.record(action.requirementId);
781
1424
  const baseMarkdown = this.versions.read(record.id, action.baseCommit).markdown;
@@ -804,21 +1447,37 @@ var CollaborationEngine = class {
804
1447
  updatedAt: now
805
1448
  };
806
1449
  record.aiRuns.push(run);
807
- this.persist();
1450
+ this.persist({
1451
+ types: ["ai.status", "metrics.changed"],
1452
+ requirementId: record.id,
1453
+ objectId: run.id
1454
+ });
808
1455
  const coordinator = this.coordinator;
809
1456
  if (coordinator === void 0) {
810
1457
  this.markAiFailure(record.id, run.id, "AI coordinator unavailable");
811
1458
  return;
812
1459
  }
813
1460
  const view = this.view(record.id);
1461
+ const requestedStage = record.stage;
1462
+ const requestedStageCycle = record.stageCycle;
1463
+ const existingSession = record.aiConversations.find((item) => item.stage === requestedStage && item.stageCycle === requestedStageCycle)?.sessionId;
814
1464
  coordinator.requestReview({
815
1465
  requirement: view,
816
- run
1466
+ run,
1467
+ ...existingSession ? { sessionId: existingSession } : {}
817
1468
  }).then((sessionId) => {
818
- run.status = "running";
819
- run.sessionId = sessionId;
820
- run.updatedAt = Date.now();
821
- this.persist();
1469
+ const currentRecord = this.state.requirements.find((item) => item.id === record.id);
1470
+ const currentRun = currentRecord?.aiRuns.find((item) => item.id === run.id);
1471
+ if (currentRecord === void 0 || currentRun === void 0) return;
1472
+ if (currentRun.status === "queued") currentRun.status = "running";
1473
+ currentRun.sessionId = sessionId;
1474
+ currentRun.updatedAt = Date.now();
1475
+ this.rememberStageConversation(currentRecord, sessionId, requestedStage, requestedStageCycle);
1476
+ this.persist({
1477
+ types: ["ai.status", "metrics.changed"],
1478
+ requirementId: currentRecord.id,
1479
+ objectId: currentRun.id
1480
+ });
822
1481
  }, (error) => this.markAiFailure(record.id, run.id, error instanceof Error ? error.message : String(error)));
823
1482
  }
824
1483
  record(id) {
@@ -831,28 +1490,373 @@ var CollaborationEngine = class {
831
1490
  if (value === void 0) throw new Error("comment not found");
832
1491
  return value;
833
1492
  }
834
- persist() {
1493
+ persist(event = this.eventContext ?? { types: ["metrics.changed"] }, recoverable = false) {
835
1494
  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();
1495
+ const pendingPath = `${this.eventPath}.pending`;
1496
+ if (recoverable) atomicWrite(pendingPath, this.state, true);
1497
+ atomicWrite(this.eventPath, this.state, recoverable);
1498
+ if (recoverable && existsSync(pendingPath)) unlinkSync(pendingPath);
1499
+ const payload = {
1500
+ ...event,
1501
+ types: [...event.types],
1502
+ revision: this.state.revision
1503
+ };
1504
+ for (const listener of this.listeners) listener(payload);
844
1505
  }
845
1506
  load() {
846
- try {
847
- const value = JSON.parse(readFileSync(this.eventPath, "utf8"));
848
- if (value.schemaVersion === 2) {
849
- value.participants ??= [];
850
- return value;
1507
+ const pendingPath = `${this.eventPath}.pending`;
1508
+ if (existsSync(pendingPath)) {
1509
+ let pending;
1510
+ try {
1511
+ pending = JSON.parse(readFileSync(pendingPath, "utf8"));
1512
+ validateV3Ledger(pending);
1513
+ atomicWrite(this.eventPath, pending, true);
1514
+ unlinkSync(pendingPath);
1515
+ return normalizeV3(pending);
1516
+ } catch (error) {
1517
+ throw new Error(`pending collaboration transaction is corrupted: ${error instanceof Error ? error.message : String(error)}`);
851
1518
  }
852
- } catch {}
853
- return emptyState();
1519
+ }
1520
+ const sourcePath = existsSync(this.eventPath) ? this.eventPath : this.options.legacyPath !== void 0 && existsSync(this.options.legacyPath) ? this.options.legacyPath : void 0;
1521
+ if (sourcePath === void 0) return emptyState();
1522
+ let parsed;
1523
+ try {
1524
+ parsed = JSON.parse(readFileSync(sourcePath, "utf8"));
1525
+ } catch (error) {
1526
+ throw new Error(`collaboration ledger is corrupted: ${error instanceof Error ? error.message : String(error)}`);
1527
+ }
1528
+ if (typeof parsed !== "object" || parsed === null || typeof parsed.schemaVersion !== "number") throw new Error("collaboration ledger has no schema version");
1529
+ const version = parsed.schemaVersion;
1530
+ if (version === 3) {
1531
+ validateV3Ledger(parsed);
1532
+ return normalizeV3(parsed);
1533
+ }
1534
+ if (version !== 2) throw new Error(`unsupported collaboration schema: ${version}`);
1535
+ validateV2Ledger(parsed);
1536
+ const migrated = migrateV2(parsed);
1537
+ const extension = extname(sourcePath);
1538
+ const stem = basename(sourcePath, extension).replace(/-v2$/, "");
1539
+ copyFileSync(sourcePath, join(dirname(sourcePath), `${stem}-v2.backup-${Date.now()}${extension || ".json"}`));
1540
+ atomicWrite(this.eventPath, migrated, true);
1541
+ return migrated;
854
1542
  }
855
1543
  };
1544
+ function eventForAction(action) {
1545
+ const types = /* @__PURE__ */ new Set(["metrics.changed"]);
1546
+ if (action.kind.startsWith("comment.")) types.add("comment.changed");
1547
+ if (action.kind === "comment.create" || action.kind === "comment.reply") {
1548
+ if ((action.mentions?.length ?? 0) > 0) types.add("mention.created");
1549
+ types.add("notification.changed");
1550
+ }
1551
+ if (action.kind === "comment.resolve" || action.kind === "comment.reopen") types.add("notification.changed");
1552
+ if (action.kind === "action.assign") {
1553
+ types.add("assignment.changed");
1554
+ types.add("notification.changed");
1555
+ }
1556
+ if (action.kind === "notification.mark-read") types.add("notification.changed");
1557
+ if (action.kind === "review.request") types.add("ai.status");
1558
+ const requirementId = "requirementId" in action ? action.requirementId : void 0;
1559
+ return {
1560
+ types: [...types],
1561
+ ...requirementId ? { requirementId } : {}
1562
+ };
1563
+ }
1564
+ function isRecord(value) {
1565
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1566
+ }
1567
+ function validateV2Ledger(value) {
1568
+ 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");
1569
+ }
1570
+ function validateV3Ledger(value) {
1571
+ if (!isRecord(value)) throw new Error("invalid collaboration v3 ledger: object required");
1572
+ if (!Number.isFinite(value.revision) || [
1573
+ "participants",
1574
+ "requirements",
1575
+ "companies",
1576
+ "customers",
1577
+ "feedbackSources",
1578
+ "insights",
1579
+ "insightLinks",
1580
+ "notifications"
1581
+ ].some((key) => !Array.isArray(value[key]))) throw new Error("invalid collaboration v3 ledger: required collections are missing or invalid");
1582
+ for (const candidate of value.requirements) {
1583
+ if (!isRecord(candidate) || typeof candidate.id !== "string" || typeof candidate.title !== "string" || typeof candidate.currentCommit !== "string" || ![
1584
+ "product-review",
1585
+ "product-confirmation",
1586
+ "joint-review",
1587
+ "ready"
1588
+ ].includes(String(candidate.stage))) throw new Error("invalid collaboration v3 ledger: malformed requirement");
1589
+ if ([
1590
+ "sources",
1591
+ "reviewItems",
1592
+ "comments",
1593
+ "patches",
1594
+ "decisions",
1595
+ "confirmations",
1596
+ "actionItems",
1597
+ "aiRuns"
1598
+ ].some((key) => !Array.isArray(candidate[key])) || candidate.aiConversations !== void 0 && !Array.isArray(candidate.aiConversations)) throw new Error("invalid collaboration v3 ledger: malformed requirement collections");
1599
+ }
1600
+ }
1601
+ function atomicWrite(path, value, durable = false) {
1602
+ mkdirSync(dirname(path), {
1603
+ recursive: true,
1604
+ mode: 448
1605
+ });
1606
+ const tmp = `${path}.tmp`;
1607
+ writeFileSync(tmp, JSON.stringify(value, null, 2), { mode: 384 });
1608
+ if (durable) {
1609
+ const descriptor = openSync(tmp, "r");
1610
+ try {
1611
+ fsyncSync(descriptor);
1612
+ } finally {
1613
+ closeSync(descriptor);
1614
+ }
1615
+ }
1616
+ renameSync(tmp, path);
1617
+ }
1618
+ function normalizeV3(value) {
1619
+ value.participants ??= [];
1620
+ value.requirements ??= [];
1621
+ value.companies ??= [];
1622
+ value.customers ??= [];
1623
+ value.feedbackSources ??= [];
1624
+ value.insights ??= [];
1625
+ value.insightLinks ??= [];
1626
+ value.notifications ??= [];
1627
+ for (const record of value.requirements) {
1628
+ record.sources ??= [];
1629
+ record.reviewItems ??= [];
1630
+ record.comments ??= [];
1631
+ record.patches ??= [];
1632
+ record.decisions ??= [];
1633
+ record.confirmations ??= [];
1634
+ record.actionItems ??= [];
1635
+ record.aiRuns ??= [];
1636
+ record.aiConversations ??= [];
1637
+ record.stageCycle ??= 0;
1638
+ for (const conversation of record.aiConversations) conversation.stageCycle ??= record.stageCycle;
1639
+ if (record.aiConversations.length === 0 && (record.stage === "product-review" || record.stage === "joint-review")) {
1640
+ 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) => ({
1641
+ sessionId: item.sessionId,
1642
+ createdAt: item.createdAt,
1643
+ updatedAt: item.updatedAt
1644
+ })), ...record.comments.filter((item) => item.aiSessionId).map((item) => ({
1645
+ sessionId: item.aiSessionId,
1646
+ createdAt: item.createdAt,
1647
+ updatedAt: item.updatedAt
1648
+ }))].sort((left, right) => right.updatedAt - left.updatedAt)[0];
1649
+ if (recent) record.aiConversations.push({
1650
+ stage: record.stage,
1651
+ stageCycle: record.stageCycle,
1652
+ ...recent
1653
+ });
1654
+ }
1655
+ for (const comment of record.comments) {
1656
+ comment.scope ??= comment.anchor === void 0 ? "page" : "inline";
1657
+ comment.mentions ??= [];
1658
+ comment.replies ??= [];
1659
+ for (const reply of comment.replies) reply.mentions ??= [];
1660
+ }
1661
+ }
1662
+ return value;
1663
+ }
1664
+ function migrateV2(value) {
1665
+ const legacyRequirements = Array.isArray(value.requirements) ? value.requirements : [];
1666
+ const requirements = structuredClone(legacyRequirements);
1667
+ const feedbackSources = [];
1668
+ const insights = [];
1669
+ const insightLinks = [];
1670
+ const migrationActor = {
1671
+ participantId: "migration-v2",
1672
+ nickname: "数据迁移",
1673
+ role: "product",
1674
+ kind: "ai",
1675
+ sessionId: "migration-v2"
1676
+ };
1677
+ for (const record of requirements) {
1678
+ record.sources ??= [];
1679
+ record.reviewItems ??= [];
1680
+ record.comments ??= [];
1681
+ record.patches ??= [];
1682
+ record.decisions ??= [];
1683
+ record.confirmations ??= [];
1684
+ record.actionItems ??= [];
1685
+ record.aiRuns ??= [];
1686
+ record.aiConversations ??= [];
1687
+ record.stageCycle ??= 0;
1688
+ for (const conversation of record.aiConversations) conversation.stageCycle ??= record.stageCycle;
1689
+ for (const comment of record.comments) {
1690
+ comment.scope = comment.anchor === void 0 ? "page" : "inline";
1691
+ comment.mentions = [];
1692
+ comment.replies ??= [];
1693
+ for (const reply of comment.replies) reply.mentions = [];
1694
+ }
1695
+ for (const source of record.sources) {
1696
+ const sourceId = `legacy-${createHash("sha256").update(`${record.id}:${source.id}`).digest("hex").slice(0, 16)}`;
1697
+ const insightId = `legacy-${createHash("sha256").update(`${record.id}:${source.id}:insight`).digest("hex").slice(0, 16)}`;
1698
+ feedbackSources.push({
1699
+ id: sourceId,
1700
+ kind: source.sourceType === "link" ? "url" : source.sourceType === "markdown" ? "markdown" : "text",
1701
+ label: source.label,
1702
+ ...source.sourceType === "link" && safeHttpUrl(source.stableId) ? { url: source.stableId } : {},
1703
+ ...source.stableId ? { externalRef: source.stableId } : {},
1704
+ accessStatus: source.accessStatus,
1705
+ createdAt: record.createdAt,
1706
+ updatedAt: record.updatedAt
1707
+ });
1708
+ insights.push({
1709
+ id: insightId,
1710
+ sourceId,
1711
+ title: source.label,
1712
+ body: `历史来源:${source.label}`,
1713
+ importance: "unknown",
1714
+ capturedAt: record.createdAt,
1715
+ dedupeHash: insightHash(sourceId, source.label),
1716
+ createdBy: migrationActor,
1717
+ createdAt: record.createdAt,
1718
+ updatedAt: record.updatedAt
1719
+ });
1720
+ insightLinks.push({
1721
+ id: randomUUID(),
1722
+ insightId,
1723
+ requirementId: record.id,
1724
+ targetType: "requirement",
1725
+ createdBy: migrationActor,
1726
+ createdAt: record.createdAt
1727
+ });
1728
+ }
1729
+ }
1730
+ return normalizeV3({
1731
+ schemaVersion: 3,
1732
+ revision: typeof value.revision === "number" ? value.revision : 0,
1733
+ participants: Array.isArray(value.participants) ? value.participants : [],
1734
+ requirements,
1735
+ companies: [],
1736
+ customers: [],
1737
+ feedbackSources,
1738
+ insights,
1739
+ insightLinks,
1740
+ notifications: []
1741
+ });
1742
+ }
1743
+ function safeHttpUrl(value) {
1744
+ if (!value) return false;
1745
+ try {
1746
+ const url = new URL(value);
1747
+ return url.protocol === "http:" || url.protocol === "https:";
1748
+ } catch {
1749
+ return false;
1750
+ }
1751
+ }
1752
+ function cleanSource(input) {
1753
+ return {
1754
+ id: input.id,
1755
+ kind: input.kind,
1756
+ label: input.label,
1757
+ ...input.url === void 0 ? {} : { url: input.url },
1758
+ ...input.externalRef === void 0 ? {} : { externalRef: input.externalRef },
1759
+ accessStatus: input.accessStatus
1760
+ };
1761
+ }
1762
+ function cleanCompany(input) {
1763
+ return {
1764
+ id: input.id,
1765
+ name: input.name,
1766
+ ...input.externalRef === void 0 ? {} : { externalRef: input.externalRef }
1767
+ };
1768
+ }
1769
+ function cleanCustomer(input) {
1770
+ return {
1771
+ id: input.id,
1772
+ displayName: input.displayName,
1773
+ ...input.companyId === void 0 ? {} : { companyId: input.companyId },
1774
+ ...input.externalRef === void 0 ? {} : { externalRef: input.externalRef }
1775
+ };
1776
+ }
1777
+ function validateSource(source) {
1778
+ if (!source.id.trim() || !source.label.trim() || ![
1779
+ "text",
1780
+ "url",
1781
+ "csv",
1782
+ "markdown"
1783
+ ].includes(source.kind) || ![
1784
+ "available",
1785
+ "unverified",
1786
+ "missing"
1787
+ ].includes(source.accessStatus) || source.kind === "url" && !safeHttpUrl(source.url)) throw new Error("valid source id, label and http(s) URL are required");
1788
+ }
1789
+ function validateCompany(company) {
1790
+ if (!company.id.trim() || !company.name.trim()) throw new Error("company id and name are required");
1791
+ }
1792
+ function validateCustomer(customer, state) {
1793
+ if (!customer.id.trim() || !customer.displayName.trim()) throw new Error("customer id and display name are required");
1794
+ if (customer.companyId !== void 0 && !state.companies.some((item) => item.id === customer.companyId)) throw new Error("company not found");
1795
+ }
1796
+ function validMentions(values, participants) {
1797
+ const registered = new Set(participants.map((item) => item.participantId));
1798
+ return [...new Set(values ?? [])].filter((value) => registered.has(value));
1799
+ }
1800
+ function insightHash(sourceId, body) {
1801
+ return createHash("sha256").update(`${sourceId}\n${body.normalize("NFKC").trim().replace(/\s+/g, " ").toLocaleLowerCase()}`).digest("hex");
1802
+ }
1803
+ function validateInsight(insight, state) {
1804
+ if (!insight.id.trim() || !insight.sourceId.trim() || !insight.body.trim()) throw new Error("insight id, source and body are required");
1805
+ if (!state.feedbackSources.some((item) => item.id === insight.sourceId)) throw new Error("feedback source not found");
1806
+ if (insight.customerId !== void 0 && !state.customers.some((item) => item.id === insight.customerId)) throw new Error("customer not found");
1807
+ if (insight.companyId !== void 0 && !state.companies.some((item) => item.id === insight.companyId)) throw new Error("company not found");
1808
+ if (![
1809
+ "unknown",
1810
+ "want",
1811
+ "important",
1812
+ "critical"
1813
+ ].includes(insight.importance)) throw new Error("invalid insight importance");
1814
+ }
1815
+ function requirementMetrics(record, state) {
1816
+ const insightIds = new Set(state.insightLinks.filter((link) => link.requirementId === record.id).map((link) => link.insightId));
1817
+ const insights = state.insights.filter((insight) => insightIds.has(insight.id));
1818
+ const customers = /* @__PURE__ */ new Set();
1819
+ const companies = /* @__PURE__ */ new Set();
1820
+ const entityScores = /* @__PURE__ */ new Map();
1821
+ let anonymousInsightCount = 0;
1822
+ const weights = {
1823
+ unknown: 1,
1824
+ want: 1,
1825
+ important: 2,
1826
+ critical: 3
1827
+ };
1828
+ for (const insight of insights) {
1829
+ const customer = insight.customerId === void 0 ? void 0 : state.customers.find((item) => item.id === insight.customerId);
1830
+ const companyId = insight.companyId ?? customer?.companyId;
1831
+ if (insight.customerId !== void 0) customers.add(insight.customerId);
1832
+ if (companyId !== void 0) companies.add(companyId);
1833
+ const entity = insight.customerId !== void 0 ? `customer:${insight.customerId}` : companyId !== void 0 ? `company:${companyId}` : void 0;
1834
+ if (entity === void 0) anonymousInsightCount += 1;
1835
+ else entityScores.set(entity, Math.max(entityScores.get(entity) ?? 0, weights[insight.importance]));
1836
+ }
1837
+ return {
1838
+ openReviewCount: record.reviewItems.filter((item) => item.commit === record.currentCommit && !["resolved", "invalidated"].includes(item.status)).length,
1839
+ openCommentCount: record.comments.filter((item) => item.commit === record.currentCommit && item.status === "open").length,
1840
+ pendingActionCount: record.actionItems.filter((item) => item.status === "pending").length,
1841
+ activeDecisionCount: record.decisions.filter((item) => item.status === "active").length,
1842
+ riskCount: record.reviewItems.filter((item) => item.commit === record.currentCommit && ["blocking", "major"].includes(item.severity) && !["resolved", "invalidated"].includes(item.status)).length,
1843
+ insightCount: insights.length,
1844
+ customerImportanceScore: [...entityScores.values()].reduce((sum, value) => sum + value, 0),
1845
+ customerCount: customers.size,
1846
+ companyCount: companies.size,
1847
+ anonymousInsightCount
1848
+ };
1849
+ }
1850
+ function requirementParticipantIds(record, history) {
1851
+ return [.../* @__PURE__ */ new Set([
1852
+ ...history.map((item) => item.author.participantId),
1853
+ ...record.reviewItems.flatMap((item) => item.response ? [item.response.participant.participantId] : []),
1854
+ ...record.comments.flatMap((item) => [item.author.participantId, ...item.replies.map((reply) => reply.author.participantId)]),
1855
+ ...record.decisions.map((item) => item.confirmer.participantId),
1856
+ ...record.confirmations.map((item) => item.participant.participantId),
1857
+ ...record.actionItems.flatMap((item) => item.assigneeParticipantId ? [item.assigneeParticipantId] : [])
1858
+ ])];
1859
+ }
856
1860
  function sourceParticipantId(record, item) {
857
1861
  if (item.sourceType === "comment") return record.comments.find((value) => value.id === item.sourceId)?.author.participantId;
858
1862
  if (item.sourceType === "patch") return record.patches.find((value) => value.id === item.sourceId)?.createdBy.participantId;
@@ -872,6 +1876,20 @@ function actionTarget(item) {
872
1876
  objectId: item.sourceId
873
1877
  };
874
1878
  }
1879
+ function actionObjectTitle(record, item) {
1880
+ if (item.sourceType === "review-item") {
1881
+ const review = record.reviewItems.find((value) => value.id === item.sourceId);
1882
+ return review?.question.trim() || review?.statement.trim() || "待处理问题";
1883
+ }
1884
+ if (item.sourceType === "comment") {
1885
+ const comment = record.comments.find((value) => value.id === item.sourceId);
1886
+ return comment?.anchor?.quote.trim() || comment?.body.trim() || "待回复评论";
1887
+ }
1888
+ if (item.sourceType === "patch") return record.patches.find((value) => value.id === item.sourceId)?.summary.trim() || "待审核正文改动";
1889
+ if (item.sourceType === "decision") return record.decisions.find((value) => value.id === item.sourceId)?.question.trim() || "待确认决策";
1890
+ const confirmation = record.confirmations.find((value) => value.id === item.sourceId);
1891
+ return confirmation ? `${confirmation.role === "product" ? "产品" : "研发"}需要重新确认当前版本` : "待确认当前版本";
1892
+ }
875
1893
  function textDiff(before, after) {
876
1894
  if (before === after) return "";
877
1895
  const left = before.split("\n");
@@ -917,8 +1935,10 @@ function actionForReview(item) {
917
1935
  updatedAt: now
918
1936
  };
919
1937
  }
920
- function hasVersionConfirmation(record, role) {
921
- return record.confirmations.some((item) => item.role === role && item.scope === "version" && item.commit === record.currentCommit && item.status === "active");
1938
+ function enterStage(record, stage) {
1939
+ if (record.stage === stage) return;
1940
+ record.stage = stage;
1941
+ record.stageCycle += 1;
922
1942
  }
923
1943
  function advance(record, participant) {
924
1944
  if (record.stage === "product-review") {
@@ -927,13 +1947,13 @@ function advance(record, participant) {
927
1947
  "non-blocking-verify",
928
1948
  "joint-review"
929
1949
  ].includes(item.status))) throw new Error("product blocking review items remain");
930
- 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";
1950
+ if (!hasCompletedCurrentReview(record, "product-second")) throw new Error("product second review is required");
1951
+ enterStage(record, "product-confirmation");
932
1952
  return;
933
1953
  }
934
1954
  if (record.stage === "product-confirmation") {
935
1955
  if (participant.role !== "product" || !hasVersionConfirmation(record, "product")) throw new Error("product must confirm the current version");
936
- record.stage = "joint-review";
1956
+ enterStage(record, "joint-review");
937
1957
  return;
938
1958
  }
939
1959
  throw new Error("stage cannot advance directly");
@@ -1446,6 +2466,7 @@ var DshReviewCoordinator = class {
1446
2466
  api;
1447
2467
  contexts;
1448
2468
  prompts;
2469
+ stageSessions = /* @__PURE__ */ new Map();
1449
2470
  constructor(api, contexts = new ReviewContextCatalog(), prompts = {}) {
1450
2471
  this.api = api;
1451
2472
  this.contexts = contexts;
@@ -1464,16 +2485,20 @@ var DshReviewCoordinator = class {
1464
2485
  await this.resolveWorkspace(workspaceId);
1465
2486
  }
1466
2487
  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);
2488
+ return this.inStageSession(input.requirement, input.sessionId, reviewContinuationPrompt(input.requirement, input.run, this.prompts), async () => {
2489
+ const context = this.contexts.resolve(input.requirement.workspaceId);
2490
+ const workspace = await this.resolveWorkspace(context.workspaceId);
2491
+ const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths);
2492
+ return this.launch(`Spec ${input.run.kind}: ${input.requirement.title}`, reviewPrompt(input.requirement, input.run, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset);
2493
+ });
1471
2494
  }
1472
2495
  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);
2496
+ return this.inStageSession(input.requirement, input.sessionId, commentContinuationPrompt(input.requirement, input.comment, this.prompts), async () => {
2497
+ const context = this.contexts.resolve(input.requirement.workspaceId);
2498
+ const workspace = await this.resolveWorkspace(context.workspaceId);
2499
+ const snapshot = await readWorkspaceSnapshot(workspace.path, context.documentPaths);
2500
+ return this.launch(`Spec ${input.requirement.stage}: ${input.requirement.title}`, commentPrompt(input.requirement, input.comment, context, workspace, snapshot, this.prompts), context.workspaceId, context.agentPreset);
2501
+ });
1477
2502
  }
1478
2503
  async conversation(sessionId) {
1479
2504
  const history = await this.api.sessions.history(request({ sessionId }));
@@ -1516,6 +2541,48 @@ var DshReviewCoordinator = class {
1516
2541
  }));
1517
2542
  if (!prompted.result.ok) throw failure(prompted.result.error);
1518
2543
  }
2544
+ async inStageSession(requirement, existingSessionId, continuation, launch) {
2545
+ const key = `${requirement.id}:${requirement.stage}:${requirement.stageCycle}`;
2546
+ if (existingSessionId !== void 0) {
2547
+ this.rememberStageSession(key, Promise.resolve(existingSessionId));
2548
+ await this.promptExisting(existingSessionId, continuation);
2549
+ return existingSessionId;
2550
+ }
2551
+ const pending = this.stageSessions.get(key);
2552
+ if (pending !== void 0) {
2553
+ const sessionId = await pending;
2554
+ await this.promptExisting(sessionId, continuation);
2555
+ return sessionId;
2556
+ }
2557
+ const created = launch();
2558
+ this.rememberStageSession(key, created);
2559
+ try {
2560
+ return await created;
2561
+ } catch (error) {
2562
+ if (this.stageSessions.get(key) === created) this.stageSessions.delete(key);
2563
+ throw error;
2564
+ }
2565
+ }
2566
+ rememberStageSession(key, session) {
2567
+ this.stageSessions.delete(key);
2568
+ this.stageSessions.set(key, session);
2569
+ while (this.stageSessions.size > 100) {
2570
+ const oldest = this.stageSessions.keys().next().value;
2571
+ if (oldest === void 0) break;
2572
+ this.stageSessions.delete(oldest);
2573
+ }
2574
+ }
2575
+ async promptExisting(sessionId, promptText) {
2576
+ const prompted = await this.api.sessions.prompt(request({
2577
+ sessionId,
2578
+ mode: "queue",
2579
+ content: [{
2580
+ type: "text",
2581
+ text: promptText
2582
+ }]
2583
+ }));
2584
+ if (!prompted.result.ok) throw failure(prompted.result.error);
2585
+ }
1519
2586
  async launch(title, promptText, workspaceId, agentPreset) {
1520
2587
  if (agentPreset !== void 0) {
1521
2588
  const presets = await this.api.agentPresets.list(request({}));
@@ -1606,16 +2673,48 @@ function commentPrompt(requirement, comment, context, workspace, workspaceSnapsh
1606
2673
  return [
1607
2674
  common(requirement, context, workspace, workspaceSnapshot, prompts),
1608
2675
  `Comment ID: ${comment.id}`,
1609
- `Anchor quote: ${comment.anchor.quote}`,
2676
+ `Comment scope: ${comment.scope}`,
2677
+ `Anchor quote: ${comment.anchor?.quote ?? "整篇需求"}`,
1610
2678
  `Human comment: ${comment.body}`,
1611
2679
  `AI session ID: {{SESSION_ID}}`,
1612
2680
  "",
1613
2681
  prompts.comment
1614
2682
  ].join("\n");
1615
2683
  }
2684
+ function reviewContinuationPrompt(requirement, run, prompts) {
2685
+ const tasks = {
2686
+ "product-first": prompts.productFirst,
2687
+ "product-second": prompts.productSecond,
2688
+ "engineering-precheck": prompts.engineeringPrecheck,
2689
+ "change-review": prompts.changeReview
2690
+ };
2691
+ return [
2692
+ "继续当前需求同一阶段的审核。不要重复读取已知背景,只使用 spec_read 获取当前 commit 的增量变化。",
2693
+ `Requirement ID: ${requirement.id}`,
2694
+ `Current stage: ${requirement.stage}`,
2695
+ `Pinned commit: ${requirement.currentCommit}`,
2696
+ `Review run ID: ${run.id}`,
2697
+ `Review kind: ${run.kind}`,
2698
+ "",
2699
+ tasks[run.kind]
2700
+ ].join("\n");
2701
+ }
2702
+ function commentContinuationPrompt(requirement, comment, prompts) {
2703
+ return [
2704
+ "在当前需求同一阶段的既有上下文中分析这条新评论。不要重新扫描整个工作区;仅在评论涉及新的实现事实时做最小增量查询。",
2705
+ `Requirement ID: ${requirement.id}`,
2706
+ `Pinned commit: ${requirement.currentCommit}`,
2707
+ `Comment ID: ${comment.id}`,
2708
+ `Comment scope: ${comment.scope}`,
2709
+ `Anchor quote: ${comment.anchor?.quote ?? "整篇需求"}`,
2710
+ `Human comment: ${comment.body}`,
2711
+ "",
2712
+ prompts.comment
2713
+ ].join("\n");
2714
+ }
1616
2715
  //#endregion
1617
2716
  //#region src/routes.ts
1618
- const BODY_LIMIT = 2 * 1024 * 1024;
2717
+ const BODY_LIMIT = 6 * 1024 * 1024;
1619
2718
  const HEARTBEAT_MS = 15e3;
1620
2719
  function json(res, status, body) {
1621
2720
  res.writeHead(status, {
@@ -1668,13 +2767,126 @@ function makeRoutes(engine, coordinator) {
1668
2767
  });
1669
2768
  if (!guard(req, res)) return;
1670
2769
  const state = engine.snapshot();
2770
+ const summaries = engine.summaries();
2771
+ 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;
2772
+ let requirement;
2773
+ try {
2774
+ requirement = currentId ? engine.view(currentId) : void 0;
2775
+ } catch {}
1671
2776
  json(res, 200, {
1672
2777
  revision: state.revision,
1673
2778
  participants: state.participants,
1674
- requirements: engine.list()
2779
+ requirements: summaries,
2780
+ ...requirement ? { requirement } : {}
2781
+ });
2782
+ }
2783
+ },
2784
+ {
2785
+ kind: "exact",
2786
+ path: `${API_PREFIX}/directory`,
2787
+ handler: (req, res) => {
2788
+ if (req.method !== "GET") return json(res, 405, {
2789
+ ok: false,
2790
+ error: "method-not-allowed"
2791
+ });
2792
+ if (!guard(req, res)) return;
2793
+ json(res, 200, {
2794
+ ok: true,
2795
+ participants: engine.directory()
2796
+ });
2797
+ }
2798
+ },
2799
+ {
2800
+ kind: "exact",
2801
+ path: `${API_PREFIX}/notifications`,
2802
+ handler: (req, res) => {
2803
+ if (req.method !== "GET") return json(res, 405, {
2804
+ ok: false,
2805
+ error: "method-not-allowed"
2806
+ });
2807
+ if (!guard(req, res)) return;
2808
+ const url = new URL(req.url ?? "", `http://${req.headers.host ?? "127.0.0.1"}`);
2809
+ const participantId = url.searchParams.get("participantId") ?? "";
2810
+ if (participantId.length < 8) return json(res, 400, {
2811
+ ok: false,
2812
+ error: "invalid-participant-query"
2813
+ });
2814
+ json(res, 200, {
2815
+ ok: true,
2816
+ ...engine.notifications(participantId, Number(url.searchParams.get("page") ?? 1), Number(url.searchParams.get("pageSize") ?? 50))
2817
+ });
2818
+ }
2819
+ },
2820
+ {
2821
+ kind: "exact",
2822
+ path: `${API_PREFIX}/insights`,
2823
+ handler: (req, res) => {
2824
+ if (req.method !== "GET") return json(res, 405, {
2825
+ ok: false,
2826
+ error: "method-not-allowed"
2827
+ });
2828
+ if (!guard(req, res)) return;
2829
+ const url = new URL(req.url ?? "", `http://${req.headers.host ?? "127.0.0.1"}`);
2830
+ const value = (key) => url.searchParams.get(key) || void 0;
2831
+ const requirementId = value("requirementId");
2832
+ const customerId = value("customerId");
2833
+ const companyId = value("companyId");
2834
+ const sourceId = value("sourceId");
2835
+ const importance = value("importance");
2836
+ json(res, 200, {
2837
+ ok: true,
2838
+ ...engine.insights({
2839
+ ...requirementId ? { requirementId } : {},
2840
+ ...customerId ? { customerId } : {},
2841
+ ...companyId ? { companyId } : {},
2842
+ ...sourceId ? { sourceId } : {},
2843
+ ...importance ? { importance } : {},
2844
+ page: Number(value("page") ?? 1),
2845
+ pageSize: Number(value("pageSize") ?? 50)
2846
+ })
1675
2847
  });
1676
2848
  }
1677
2849
  },
2850
+ {
2851
+ kind: "exact",
2852
+ path: `${API_PREFIX}/diff`,
2853
+ handler: async (req, res) => {
2854
+ if (!guard(req, res)) return;
2855
+ try {
2856
+ if (req.method === "GET") {
2857
+ const url = new URL(req.url ?? "", `http://${req.headers.host ?? "127.0.0.1"}`);
2858
+ return json(res, 200, {
2859
+ ok: true,
2860
+ diff: engine.diff(url.searchParams.get("requirementId") ?? "", url.searchParams.get("baseCommit") ?? "", url.searchParams.get("headCommit") || void 0)
2861
+ });
2862
+ }
2863
+ if (req.method === "POST") {
2864
+ if (!(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) return json(res, 415, {
2865
+ ok: false,
2866
+ error: "json-required"
2867
+ });
2868
+ const body = await readJson(req);
2869
+ if (typeof body.before !== "string" || typeof body.after !== "string") return json(res, 400, {
2870
+ ok: false,
2871
+ error: "invalid-diff-preview"
2872
+ });
2873
+ return json(res, 200, {
2874
+ ok: true,
2875
+ diff: buildStructuredDiff(body.before, body.after, typeof body.baseLabel === "string" ? body.baseLabel : void 0, typeof body.headLabel === "string" ? body.headLabel : void 0)
2876
+ });
2877
+ }
2878
+ return json(res, 405, {
2879
+ ok: false,
2880
+ error: "method-not-allowed"
2881
+ });
2882
+ } catch (error) {
2883
+ return json(res, 400, {
2884
+ ok: false,
2885
+ error: error instanceof Error ? error.message : String(error)
2886
+ });
2887
+ }
2888
+ }
2889
+ },
1678
2890
  {
1679
2891
  kind: "exact",
1680
2892
  path: `${API_PREFIX}/review-workspaces`,
@@ -1843,8 +3055,8 @@ function makeRoutes(engine, coordinator) {
1843
3055
  "cache-control": "no-cache",
1844
3056
  connection: "keep-alive"
1845
3057
  });
1846
- const push = () => {
1847
- res.write(`data: ${JSON.stringify({ revision: engine.snapshot().revision })}\n\n`);
3058
+ const push = (event) => {
3059
+ res.write(`data: ${JSON.stringify(event)}\n\n`);
1848
3060
  };
1849
3061
  const unsubscribe = engine.subscribe(push);
1850
3062
  const heartbeat = setInterval(() => {
@@ -1856,7 +3068,10 @@ function makeRoutes(engine, coordinator) {
1856
3068
  };
1857
3069
  req.once("close", close);
1858
3070
  res.once("close", close);
1859
- push();
3071
+ push({
3072
+ types: ["state.synced"],
3073
+ revision: engine.snapshot().revision
3074
+ });
1860
3075
  }
1861
3076
  }
1862
3077
  ];
@@ -1948,7 +3163,7 @@ function specReadTool(engine) {
1948
3163
  ];
1949
3164
  if (include.has("spec")) rows.push("", "## Spec", view.version.markdown);
1950
3165
  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"}`));
3166
+ 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
3167
  if (include.has("decisions")) rows.push("", "## Decisions", ...view.decisions.map((item) => `- ${item.id} [${item.status}] ${item.question}: ${item.decision}`));
1953
3168
  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
3169
  if (include.has("sources")) rows.push("", "## Sources", ...view.sources.map((item) => `- ${item.id} [${item.accessStatus}] ${item.label}${item.version ? ` @ ${item.version}` : ""}`));
@@ -2341,7 +3556,7 @@ function apply(ctx, config = {}) {
2341
3556
  const dataRoot = config.dataRoot ?? join(homedir(), ".dsh", "spec-collab");
2342
3557
  const contexts = new ReviewContextCatalog(config);
2343
3558
  const prompts = resolveReviewPrompts(config.prompts);
2344
- const engine = new CollaborationEngine(join(dataRoot, "collaboration-v2.json"), new GitRequirementStore(config.repositoryPath ?? join(dataRoot, "repository")));
3559
+ const engine = new CollaborationEngine(join(dataRoot, "collaboration-v3.json"), new GitRequirementStore(config.repositoryPath ?? join(dataRoot, "repository")), { legacyPath: join(dataRoot, "collaboration-v2.json") });
2345
3560
  const coordinator = new DshReviewCoordinator(ctx.apiProxy, contexts, prompts);
2346
3561
  engine.setCoordinator(coordinator);
2347
3562
  ctx.effect(() => {