dsh-spec-collab 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { homedir } from "node:os";
1
+ import { homedir, tmpdir } from "node:os";
2
2
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
3
3
  import Schema from "@deepseek-ai/schemastery";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
- import { closeSync, copyFileSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
5
+ import { closeSync, copyFileSync, existsSync, fsyncSync, lstatSync, mkdirSync, mkdtempSync, 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";
@@ -15,306 +15,347 @@ var VersionConflictError = class extends Error {
15
15
  this.name = "VersionConflictError";
16
16
  }
17
17
  };
18
+ const SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
19
+ const REQUIREMENT_ID = /^[a-z0-9\u4e00-\u9fff][a-z0-9\u4e00-\u9fff-]{1,80}$/;
20
+ const GIT_BUFFER_LIMIT = 16 * 1024 * 1024;
18
21
  var GitRequirementStore = class {
19
22
  root;
20
- versionCache = /* @__PURE__ */ new Map();
21
- headCache = /* @__PURE__ */ new Map();
22
23
  historyCache = /* @__PURE__ */ new Map();
24
+ versionCache = /* @__PURE__ */ new Map();
23
25
  commitBaseUrl;
24
26
  constructor(root) {
25
27
  this.root = root;
26
- this.ensureRepository();
28
+ mkdirSync(root, {
29
+ recursive: true,
30
+ mode: 448
31
+ });
32
+ if (!existsSync(join(root, ".git"))) this.git(["init"]);
27
33
  }
28
34
  create(input) {
29
- const requirementId = `${slug(input.title)}-${randomUUID().slice(0, 8)}`;
30
- const markdown = initialSpec(input.title, input.rawRequirement, input.sources);
31
- const path = this.specPath(requirementId);
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
+ const change = this.prepareCreate(input);
36
+ this.publish(change);
37
+ return {
38
+ requirementId: change.requirementId,
39
+ version: this.read(change.requirementId, change.commit)
40
+ };
52
41
  }
53
42
  save(input) {
54
- const current = this.head(input.requirementId);
55
- if (current !== input.baseCommit) throw new VersionConflictError(current);
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");
58
- if (input.summary.trim() === "") throw new Error("change summary is required");
59
- if (input.markdown.length > 2e6) throw new Error("spec exceeds 2 MB");
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");
43
+ const change = this.prepareSave(input);
44
+ this.publish(change);
45
+ return this.read(change.requirementId, change.commit);
46
+ }
47
+ remove(requirementId, participant) {
48
+ this.publish(this.prepareRemove(requirementId, this.head(requirementId), participant));
49
+ }
50
+ prepareCreate(input) {
51
+ const requirementId = `${slug(input.title)}-${randomUUID().slice(0, 8)}`;
52
+ const markdown = initialSpec(input.title, input.rawRequirement, input.sources);
53
+ validateSize(markdown);
54
+ const baseHead = this.repositoryHead();
55
+ return this.prepareCommit({
56
+ requirementId,
57
+ operation: "create",
58
+ ...baseHead ? { baseHead } : {}
59
+ }, input.participant, "Create requirement", markdown);
60
+ }
61
+ prepareSave(input) {
62
+ const baseHead = this.assertCurrent(input.requirementId, input.baseCommit);
63
+ const summary = input.summary.trim();
64
+ if (!summary) throw new Error("change summary is required");
65
+ validateSize(input.markdown);
66
+ if (input.markdown === this.read(input.requirementId, input.baseCommit).markdown) throw new Error("no changes to save");
67
+ return this.prepareCommit({
68
+ requirementId: input.requirementId,
69
+ operation: "update",
70
+ baseHead
71
+ }, input.participant, summary, input.markdown);
72
+ }
73
+ prepareRemove(requirementId, baseCommit, participant) {
74
+ const baseHead = this.assertCurrent(requirementId, baseCommit);
75
+ return this.prepareCommit({
76
+ requirementId,
77
+ operation: "delete",
78
+ baseHead
79
+ }, participant, "Delete requirement");
80
+ }
81
+ /** Publish a prepared commit and synchronize its one owned path. Safe to repeat after interruption. */
82
+ publish(change) {
83
+ const path = this.relativeSpecPath(change.requirementId);
84
+ const head = this.repositoryHead();
85
+ if (head !== change.commit) {
86
+ if (head !== change.baseHead) throw new Error("spec repository HEAD changed during the collaboration transaction");
87
+ this.assertClean(path);
69
88
  this.git([
70
- "reset",
71
- "--",
72
- relativePath
73
- ], true);
74
- throw error;
75
- }
89
+ "update-ref",
90
+ "HEAD",
91
+ change.commit,
92
+ change.baseHead ?? "0".repeat(change.commit.length)
93
+ ]);
94
+ } else this.assertRecoverableCheckout(change, path);
95
+ if (change.operation !== "delete" || existsSync(join(this.root, path)) || this.git([
96
+ "ls-files",
97
+ "--",
98
+ path
99
+ ]).trim() !== "") this.git([
100
+ "restore",
101
+ "--source",
102
+ change.commit,
103
+ "--staged",
104
+ "--worktree",
105
+ "--",
106
+ path
107
+ ]);
108
+ if (change.operation === "delete") this.historyCache.delete(change.requirementId);
76
109
  }
77
- read(requirementId, commit) {
78
- assertRequirementId(requirementId);
79
- const resolved = commit ?? this.head(requirementId);
80
- const cacheKey = `${requirementId}:${resolved}`;
81
- const cached = this.versionCache.get(cacheKey);
110
+ read(requirementId, commit = this.head(requirementId)) {
111
+ const key = `${requirementId}:${commit}`;
112
+ const cached = this.versionCache.get(key);
82
113
  if (cached !== void 0) return structuredClone(cached);
83
- const markdown = this.gitText(["show", `${resolved}:${this.relativeSpecPath(requirementId)}`]);
84
- const [sha = resolved, parents = "", seconds = "0", nickname = "unknown", email = "", ...bodyParts] = this.gitText([
85
- "show",
86
- "-s",
87
- "--format=%H%x1f%P%x1f%at%x1f%an%x1f%ae%x1f%B",
88
- resolved
89
- ]).split("");
90
- const body = bodyParts.join("").trim();
91
- const role = /DSH-Role:\s*(product|engineering)/.exec(body)?.[1];
92
- const summary = body.split("\n")[0] ?? "Saved version";
114
+ const markdown = this.body(requirementId, commit);
93
115
  const version = {
94
- commit: sha,
95
- ...parents.split(" ")[0] ? { parentCommit: parents.split(" ")[0] } : {},
96
- markdown,
97
- author: {
98
- participantId: email.replace(/@dsh\.local$/, "") || "unknown",
99
- nickname,
100
- role: role ?? "product",
101
- kind: "human"
102
- },
103
- summary,
104
- createdAt: Number(seconds) * 1e3
116
+ ...this.historyCache.get(requirementId)?.history.find((item) => item.commit === commit) ?? parseMetadata(this.git([
117
+ "show",
118
+ "-s",
119
+ `--format=${VERSION_FORMAT}`,
120
+ commit
121
+ ])),
122
+ markdown
105
123
  };
106
- this.versionCache.set(cacheKey, version);
124
+ if (this.versionCache.size >= 16) this.versionCache.delete(this.versionCache.keys().next().value);
125
+ this.versionCache.set(key, version);
107
126
  return structuredClone(version);
108
127
  }
109
- history(requirementId) {
110
- assertRequirementId(requirementId);
128
+ history(requirementId, head = this.repositoryHead()) {
129
+ const path = this.relativeSpecPath(requirementId);
130
+ if (head === void 0) return [];
131
+ assertCommit(head);
111
132
  const cached = this.historyCache.get(requirementId);
112
- if (cached !== void 0) return structuredClone(cached);
113
- const history = this.gitText([
133
+ if (cached?.head === head) return structuredClone(cached.history);
134
+ const history = this.git([
114
135
  "log",
115
- "--format=%H%x1f%P%x1f%at%x1f%an%x1f%ae%x1f%B%x1e",
136
+ `--format=${VERSION_FORMAT}%x1e`,
137
+ head,
116
138
  "--",
117
- this.relativeSpecPath(requirementId)
118
- ]).split("").map((row) => row.trim()).filter(Boolean).map((row) => {
119
- const [commit = "", parents = "", seconds = "0", nickname = "unknown", email = "", ...bodyParts] = row.split("");
120
- const body = bodyParts.join("").trim();
121
- const role = /DSH-Role:\s*(product|engineering)/.exec(body)?.[1];
122
- return {
123
- commit,
124
- ...parents.split(" ")[0] ? { parentCommit: parents.split(" ")[0] } : {},
125
- author: {
126
- participantId: email.replace(/@dsh\.local$/, "") || "unknown",
127
- nickname,
128
- role: role ?? "product",
129
- kind: "human"
130
- },
131
- summary: body.split("\n")[0] ?? "Saved version",
132
- createdAt: Number(seconds) * 1e3
133
- };
139
+ path
140
+ ]).split("").map((row) => row.trim()).filter(Boolean).map(parseMetadata);
141
+ this.historyCache.set(requirementId, {
142
+ head,
143
+ history
134
144
  });
135
- this.historyCache.set(requirementId, history);
136
145
  return structuredClone(history);
137
146
  }
138
- diff(requirementId, baseCommit, headCommit) {
139
- assertRequirementId(requirementId);
140
- return this.gitText([
147
+ diff(requirementId, baseCommit, headCommit = this.head(requirementId)) {
148
+ assertCommit(baseCommit);
149
+ assertCommit(headCommit);
150
+ return this.git([
141
151
  "diff",
142
152
  baseCommit,
143
- headCommit ?? this.head(requirementId),
153
+ headCommit,
144
154
  "--",
145
155
  this.relativeSpecPath(requirementId)
146
156
  ]);
147
157
  }
148
158
  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([
159
+ if (!SHA.test(commit)) return void 0;
160
+ if (this.commitBaseUrl === void 0) try {
161
+ const origin = this.git([
154
162
  "config",
155
163
  "--get",
156
164
  "remote.origin.url"
157
165
  ]).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);
166
+ const scp = /^git@([^:]+):(.+)$/.exec(origin);
167
+ const url = new URL(scp ? `https://${scp[1]}/${scp[2]}` : origin.replace(/^ssh:\/\/git@/, "https://"));
168
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error("unsupported remote URL");
174
169
  url.username = "";
175
170
  url.password = "";
176
171
  this.commitBaseUrl = url.toString().replace(/\.git$/, "").replace(/\/$/, "");
177
172
  } catch {
178
173
  this.commitBaseUrl = null;
179
- return;
180
- }
181
- return `${this.commitBaseUrl}/commit/${commit}`;
182
- }
183
- remove(requirementId, participant) {
184
- assertRequirementId(requirementId);
185
- if (!existsSync(this.specPath(requirementId))) throw new Error("requirement spec not found");
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
174
  }
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);
175
+ return this.commitBaseUrl === null ? void 0 : `${this.commitBaseUrl}/commit/${commit}`;
206
176
  }
207
177
  head(requirementId) {
208
- assertRequirementId(requirementId);
209
- const cached = this.headCache.get(requirementId);
210
- if (cached !== void 0) return cached;
211
- const resolved = this.gitText([
178
+ return this.requirementHead(requirementId, this.repositoryHead());
179
+ }
180
+ requirementHead(requirementId, repositoryHead) {
181
+ const path = this.relativeSpecPath(requirementId);
182
+ return repositoryHead === void 0 ? "" : this.git([
212
183
  "log",
213
184
  "-1",
214
185
  "--format=%H",
186
+ repositoryHead,
215
187
  "--",
216
- this.relativeSpecPath(requirementId)
188
+ path
217
189
  ]).trim();
218
- this.headCache.set(requirementId, resolved);
219
- return resolved;
220
- }
221
- commit(requirementId, participant, summary) {
222
- this.git(["add", this.relativeSpecPath(requirementId)]);
223
- return this.commitStaged(participant, summary);
224
- }
225
- commitStaged(participant, summary) {
226
- const env = {
227
- ...process.env,
228
- GIT_AUTHOR_NAME: participant.nickname,
229
- GIT_AUTHOR_EMAIL: `${participant.participantId}@dsh.local`,
230
- GIT_COMMITTER_NAME: participant.nickname,
231
- GIT_COMMITTER_EMAIL: `${participant.participantId}@dsh.local`
232
- };
233
- execFileSync("git", [
234
- "-c",
235
- "commit.gpgsign=false",
236
- "-c",
237
- "core.hooksPath=/dev/null",
238
- "commit",
239
- "--no-verify",
240
- "-m",
241
- summary,
242
- "-m",
243
- `DSH-Role: ${participant.role}`
244
- ], {
245
- cwd: this.root,
246
- env,
247
- stdio: "pipe"
248
- });
249
- return this.gitText(["rev-parse", "HEAD"]).trim();
250
190
  }
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()
191
+ assertCurrent(requirementId, baseCommit) {
192
+ const head = this.repositoryHead();
193
+ const current = this.requirementHead(requirementId, head);
194
+ if (current !== baseCommit) throw new VersionConflictError(current);
195
+ if (head === void 0 || current === "") throw new Error("requirement spec not found");
196
+ return head;
197
+ }
198
+ prepareCommit(change, participant, summary, markdown) {
199
+ const path = this.relativeSpecPath(change.requirementId);
200
+ this.assertClean(path);
201
+ if (change.operation === "create" && existsSync(join(this.root, path))) throw new Error("requirement spec already exists");
202
+ const temporary = mkdtempSync(join(tmpdir(), "spec-git-index-"));
203
+ try {
204
+ const env = {
205
+ ...process.env,
206
+ GIT_INDEX_FILE: join(temporary, "index")
207
+ };
208
+ this.git(["read-tree", change.baseHead ?? "--empty"], { env });
209
+ if (markdown === void 0) this.git([
210
+ "update-index",
211
+ "--force-remove",
212
+ "--",
213
+ path
214
+ ], { env });
215
+ else {
216
+ const blob = this.git([
217
+ "hash-object",
218
+ "-w",
219
+ "--stdin"
220
+ ], { input: markdown }).trim();
221
+ this.git([
222
+ "update-index",
223
+ "--add",
224
+ "--cacheinfo",
225
+ `100644,${blob},${path}`
226
+ ], { env });
227
+ }
228
+ const tree = this.git(["write-tree"], { env }).trim();
229
+ const parent = change.baseHead ? ["-p", change.baseHead] : [];
230
+ const email = `${participant.participantId}@dsh.local`;
231
+ const commit = this.git([
232
+ "-c",
233
+ "commit.gpgsign=false",
234
+ "commit-tree",
235
+ tree,
236
+ ...parent,
237
+ "-m",
238
+ summary,
239
+ "-m",
240
+ `DSH-Role: ${participant.role}`
241
+ ], { env: {
242
+ ...env,
243
+ GIT_AUTHOR_NAME: participant.nickname,
244
+ GIT_AUTHOR_EMAIL: email,
245
+ GIT_COMMITTER_NAME: participant.nickname,
246
+ GIT_COMMITTER_EMAIL: email
247
+ } }).trim();
248
+ return {
249
+ ...change,
250
+ commit
251
+ };
252
+ } finally {
253
+ rmSync(temporary, {
254
+ recursive: true,
255
+ force: true
256
+ });
257
+ }
258
+ }
259
+ assertClean(path) {
260
+ const stat = lstatSync(join(this.root, path), { throwIfNoEntry: false });
261
+ if (stat && !stat.isFile() || this.git([
262
+ "status",
263
+ "--porcelain",
264
+ "--untracked-files=all",
265
+ "--",
266
+ path
267
+ ]).trim() !== "") throw new Error("spec has external uncommitted changes");
268
+ }
269
+ assertRecoverableCheckout(change, path) {
270
+ const previous = change.operation === "create" ? void 0 : this.body(change.requirementId, change.baseHead);
271
+ const next = change.operation === "delete" ? void 0 : this.body(change.requirementId, change.commit);
272
+ const fullPath = join(this.root, path);
273
+ const stat = lstatSync(fullPath, { throwIfNoEntry: false });
274
+ if (stat && !stat.isFile()) throw new Error("spec has external uncommitted changes");
275
+ const actual = stat ? readFileSync(fullPath, "utf8") : void 0;
276
+ if (actual !== previous && actual !== next) throw new Error("spec has external uncommitted changes");
277
+ const entry = this.git([
278
+ "ls-files",
279
+ "--stage",
280
+ "-z",
281
+ "--",
282
+ path
283
+ ]);
284
+ const matchesIndex = (body) => {
285
+ if (body === void 0) return entry === "";
286
+ const hash = this.git(["hash-object", "--stdin"], { input: body }).trim();
287
+ return entry === `100644 ${hash} 0\t${path}\0`;
259
288
  };
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);
289
+ if (!matchesIndex(previous) && !matchesIndex(next)) throw new Error("spec has external staged changes");
266
290
  }
267
- ensureRepository() {
268
- mkdirSync(this.root, {
269
- recursive: true,
270
- mode: 448
271
- });
272
- if (!existsSync(join(this.root, ".git"))) execFileSync("git", ["init"], {
273
- cwd: this.root,
274
- stdio: "pipe"
275
- });
291
+ repositoryHead() {
292
+ try {
293
+ return this.git([
294
+ "rev-parse",
295
+ "--verify",
296
+ "--quiet",
297
+ "HEAD"
298
+ ]).trim();
299
+ } catch (error) {
300
+ if (error.status === 1) return void 0;
301
+ throw error;
302
+ }
303
+ }
304
+ body(requirementId, commit) {
305
+ assertCommit(commit);
306
+ return this.git(["show", `${commit}:${this.relativeSpecPath(requirementId)}`]);
276
307
  }
277
308
  relativeSpecPath(id) {
278
- assertRequirementId(id);
309
+ if (!REQUIREMENT_ID.test(id)) throw new Error("invalid requirement id");
279
310
  return `requirements/${id}/spec.md`;
280
311
  }
281
- specPath(id) {
282
- return join(this.root, this.relativeSpecPath(id));
283
- }
284
- gitText(args) {
312
+ git(args, options = {}) {
285
313
  return execFileSync("git", args, {
314
+ ...options,
286
315
  cwd: this.root,
287
316
  encoding: "utf8",
288
317
  stdio: [
289
- "ignore",
318
+ options.input === void 0 ? "ignore" : "pipe",
290
319
  "pipe",
291
320
  "pipe"
292
- ]
321
+ ],
322
+ maxBuffer: GIT_BUFFER_LIMIT
293
323
  });
294
324
  }
295
- git(args, allowFailure = false) {
296
- try {
297
- execFileSync("git", args, {
298
- cwd: this.root,
299
- stdio: "pipe"
300
- });
301
- return { status: 0 };
302
- } catch (error) {
303
- if (allowFailure) return { status: error.status ?? 1 };
304
- throw error;
305
- }
306
- }
307
325
  };
308
- function withoutMarkdown(version) {
309
- const { markdown: _markdown, ...metadata } = version;
310
- return metadata;
326
+ function isPreparedSpecCommit(value) {
327
+ if (typeof value !== "object" || value === null) return false;
328
+ const { requirementId, operation, baseHead, commit } = value;
329
+ return typeof requirementId === "string" && REQUIREMENT_ID.test(requirementId) && (operation === "create" || operation === "update" || operation === "delete") && typeof commit === "string" && SHA.test(commit) && (baseHead === void 0 ? operation === "create" : typeof baseHead === "string" && SHA.test(baseHead));
330
+ }
331
+ const VERSION_FORMAT = "%H%x1f%P%x1f%at%x1f%an%x1f%ae%x1f%B";
332
+ function parseMetadata(row) {
333
+ const [commit = "", parents = "", seconds = "0", nickname = "unknown", email = "", ...bodyParts] = row.split("");
334
+ const body = bodyParts.join("").trim();
335
+ const role = /DSH-Role:\s*(product|engineering)/.exec(body)?.[1];
336
+ const parentCommit = parents.split(" ")[0];
337
+ return {
338
+ commit,
339
+ ...parentCommit ? { parentCommit } : {},
340
+ author: {
341
+ participantId: email.replace(/@dsh\.local$/, "") || "unknown",
342
+ nickname,
343
+ role: role ?? "product",
344
+ kind: "human"
345
+ },
346
+ summary: body.split("\n")[0] ?? "Saved version",
347
+ createdAt: Number(seconds) * 1e3
348
+ };
349
+ }
350
+ function validateSize(markdown) {
351
+ if (markdown.length > 2e6) throw new Error("spec exceeds 2 MB");
352
+ }
353
+ function assertCommit(commit) {
354
+ if (!SHA.test(commit)) throw new Error("invalid commit");
311
355
  }
312
356
  function slug(title) {
313
357
  return title.toLowerCase().trim().replace(/[^a-z0-9\u4e00-\u9fff]+/g, "-").replace(/^-|-$/g, "").slice(0, 48) || "requirement";
314
358
  }
315
- function assertRequirementId(value) {
316
- if (!/^[a-z0-9\u4e00-\u9fff][a-z0-9\u4e00-\u9fff-]{1,80}$/.test(value)) throw new Error("invalid requirement id");
317
- }
318
359
  function initialSpec(title, raw, sources) {
319
360
  const sourceLines = sources.length === 0 ? ["- 原始需求:当前文档(创建版本)"] : sources.map((item) => `- [${item.accessStatus}] ${item.label}${item.stableId ? ` — ${item.stableId}` : ""}`);
320
361
  return [
@@ -351,6 +392,249 @@ function initialSpec(title, raw, sources) {
351
392
  ].join("\n");
352
393
  }
353
394
  //#endregion
395
+ //#region src/insights.ts
396
+ function safeHttpUrl(value) {
397
+ if (!value) return false;
398
+ try {
399
+ const url = new URL(value);
400
+ return url.protocol === "http:" || url.protocol === "https:";
401
+ } catch {
402
+ return false;
403
+ }
404
+ }
405
+ function cleanSource(input) {
406
+ return {
407
+ id: input.id,
408
+ kind: input.kind,
409
+ label: input.label,
410
+ ...input.url === void 0 ? {} : { url: input.url },
411
+ ...input.externalRef === void 0 ? {} : { externalRef: input.externalRef },
412
+ accessStatus: input.accessStatus
413
+ };
414
+ }
415
+ function cleanCompany(input) {
416
+ return {
417
+ id: input.id,
418
+ name: input.name,
419
+ ...input.externalRef === void 0 ? {} : { externalRef: input.externalRef }
420
+ };
421
+ }
422
+ function cleanCustomer(input) {
423
+ return {
424
+ id: input.id,
425
+ displayName: input.displayName,
426
+ ...input.companyId === void 0 ? {} : { companyId: input.companyId },
427
+ ...input.externalRef === void 0 ? {} : { externalRef: input.externalRef }
428
+ };
429
+ }
430
+ function validateSource(source) {
431
+ if (!source.id.trim() || !source.label.trim() || ![
432
+ "text",
433
+ "url",
434
+ "csv",
435
+ "markdown"
436
+ ].includes(source.kind) || ![
437
+ "available",
438
+ "unverified",
439
+ "missing"
440
+ ].includes(source.accessStatus) || source.kind === "url" && !safeHttpUrl(source.url)) throw new Error("valid source id, label and http(s) URL are required");
441
+ }
442
+ function validateCompany(company) {
443
+ if (!company.id.trim() || !company.name.trim()) throw new Error("company id and name are required");
444
+ }
445
+ function validateCustomer(customer, state) {
446
+ if (!customer.id.trim() || !customer.displayName.trim()) throw new Error("customer id and display name are required");
447
+ if (customer.companyId !== void 0 && !state.companies.some((item) => item.id === customer.companyId)) throw new Error("company not found");
448
+ }
449
+ function insightHash(sourceId, body) {
450
+ return createHash("sha256").update(`${sourceId}\n${body.normalize("NFKC").trim().replace(/\s+/g, " ").toLocaleLowerCase()}`).digest("hex");
451
+ }
452
+ function validateInsight(insight, state) {
453
+ if (!insight.id.trim() || !insight.sourceId.trim() || !insight.body.trim()) throw new Error("insight id, source and body are required");
454
+ if (!state.feedbackSources.some((item) => item.id === insight.sourceId)) throw new Error("feedback source not found");
455
+ if (insight.customerId !== void 0 && !state.customers.some((item) => item.id === insight.customerId)) throw new Error("customer not found");
456
+ if (insight.companyId !== void 0 && !state.companies.some((item) => item.id === insight.companyId)) throw new Error("company not found");
457
+ if (![
458
+ "unknown",
459
+ "want",
460
+ "important",
461
+ "critical"
462
+ ].includes(insight.importance)) throw new Error("invalid insight importance");
463
+ }
464
+ function queryInsights(state, query = {}) {
465
+ const linkedIds = query.requirementId === void 0 ? void 0 : new Set(state.insightLinks.filter((link) => link.requirementId === query.requirementId).map((link) => link.insightId));
466
+ const rows = state.insights.filter((item) => {
467
+ const companyId = item.companyId ?? (item.customerId ? state.customers.find((customer) => customer.id === item.customerId)?.companyId : void 0);
468
+ 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);
469
+ }).sort((left, right) => right.capturedAt - left.capturedAt);
470
+ const pageSize = Math.min(100, Math.max(1, query.pageSize ?? 50));
471
+ const start = Math.max(0, (query.page ?? 1) - 1) * pageSize;
472
+ const page = rows.slice(start, start + pageSize);
473
+ const ids = new Set(page.map((item) => item.id));
474
+ const customerIds = new Set(page.flatMap((item) => item.customerId ? [item.customerId] : []));
475
+ const companyIds = new Set(page.flatMap((item) => item.companyId ? [item.companyId] : []));
476
+ for (const customer of state.customers.filter((item) => customerIds.has(item.id))) if (customer.companyId) companyIds.add(customer.companyId);
477
+ return {
478
+ items: structuredClone(page),
479
+ total: rows.length,
480
+ links: structuredClone(state.insightLinks.filter((item) => ids.has(item.insightId))),
481
+ customers: structuredClone(state.customers.filter((item) => customerIds.has(item.id))),
482
+ companies: structuredClone(state.companies.filter((item) => companyIds.has(item.id))),
483
+ sources: structuredClone(state.feedbackSources.filter((item) => page.some((insight) => insight.sourceId === item.id)))
484
+ };
485
+ }
486
+ function insightMetrics(state, requirementId) {
487
+ const insightIds = new Set(state.insightLinks.filter((link) => link.requirementId === requirementId).map((link) => link.insightId));
488
+ const insights = state.insights.filter((insight) => insightIds.has(insight.id));
489
+ const customers = /* @__PURE__ */ new Set();
490
+ const companies = /* @__PURE__ */ new Set();
491
+ const entityScores = /* @__PURE__ */ new Map();
492
+ let anonymousInsightCount = 0;
493
+ const weights = {
494
+ unknown: 1,
495
+ want: 1,
496
+ important: 2,
497
+ critical: 3
498
+ };
499
+ for (const insight of insights) {
500
+ const customer = insight.customerId === void 0 ? void 0 : state.customers.find((item) => item.id === insight.customerId);
501
+ const companyId = insight.companyId ?? customer?.companyId;
502
+ if (insight.customerId !== void 0) customers.add(insight.customerId);
503
+ if (companyId !== void 0) companies.add(companyId);
504
+ const entity = insight.customerId !== void 0 ? `customer:${insight.customerId}` : companyId !== void 0 ? `company:${companyId}` : void 0;
505
+ if (entity === void 0) anonymousInsightCount += 1;
506
+ else entityScores.set(entity, Math.max(entityScores.get(entity) ?? 0, weights[insight.importance]));
507
+ }
508
+ return {
509
+ insightCount: insights.length,
510
+ customerImportanceScore: [...entityScores.values()].reduce((sum, value) => sum + value, 0),
511
+ customerCount: customers.size,
512
+ companyCount: companies.size,
513
+ anonymousInsightCount
514
+ };
515
+ }
516
+ function isInsightAction(action) {
517
+ return action.kind === "source.upsert" || action.kind === "company.upsert" || action.kind === "customer.upsert" || action.kind.startsWith("insight.");
518
+ }
519
+ function applyInsightAction(state, action, now) {
520
+ const { requirementId, participant } = action;
521
+ switch (action.kind) {
522
+ case "source.upsert":
523
+ upsertSource(state, action.source, now);
524
+ break;
525
+ case "company.upsert":
526
+ upsertCompany(state, action.company, now);
527
+ break;
528
+ case "customer.upsert":
529
+ upsertCustomer(state, action.customer, now);
530
+ break;
531
+ case "insight.create": {
532
+ const insight = createInsight(state, requirementId, action.insight, participant, now);
533
+ for (const link of action.links ?? []) addInsightLink(state, insight.id, link, participant, now);
534
+ break;
535
+ }
536
+ case "insight.update": {
537
+ const insight = state.insights.find((item) => item.id === action.insightId);
538
+ if (insight === void 0) throw new Error("insight not found");
539
+ Object.assign(insight, action.changes);
540
+ validateInsight(insight, state);
541
+ insight.dedupeHash = insightHash(insight.sourceId, insight.body);
542
+ insight.updatedAt = now;
543
+ break;
544
+ }
545
+ case "insight.delete": {
546
+ const index = state.insights.findIndex((item) => item.id === action.insightId);
547
+ if (index < 0) throw new Error("insight not found");
548
+ state.insights.splice(index, 1);
549
+ state.insightLinks = state.insightLinks.filter((item) => item.insightId !== action.insightId);
550
+ break;
551
+ }
552
+ case "insight.link":
553
+ addInsightLink(state, action.insightId, action.link, participant, now);
554
+ break;
555
+ case "insight.unlink":
556
+ if (!state.insightLinks.some((item) => item.id === action.linkId)) throw new Error("insight link not found");
557
+ state.insightLinks = state.insightLinks.filter((item) => item.id !== action.linkId);
558
+ break;
559
+ case "insight.import": {
560
+ 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");
561
+ if (action.source) upsertSource(state, action.source, now);
562
+ for (const source of action.sources ?? []) upsertSource(state, source, now);
563
+ for (const company of action.companies ?? []) upsertCompany(state, company, now);
564
+ for (const customer of action.customers ?? []) upsertCustomer(state, customer, now);
565
+ const actualIds = /* @__PURE__ */ new Map();
566
+ for (const row of action.rows) actualIds.set(row.id, createInsight(state, requirementId, row, participant, now).id);
567
+ for (const link of action.links ?? []) addInsightLink(state, actualIds.get(link.insightId) ?? link.insightId, link, participant, now);
568
+ break;
569
+ }
570
+ }
571
+ }
572
+ function upsertSource(state, input, now) {
573
+ const source = cleanSource(input);
574
+ validateSource(source);
575
+ upsert(state.feedbackSources, source, now);
576
+ }
577
+ function upsertCompany(state, input, now) {
578
+ const company = cleanCompany(input);
579
+ validateCompany(company);
580
+ upsert(state.companies, company, now);
581
+ }
582
+ function upsertCustomer(state, input, now) {
583
+ const customer = cleanCustomer(input);
584
+ validateCustomer(customer, state);
585
+ upsert(state.customers, customer, now);
586
+ }
587
+ function upsert(rows, value, now) {
588
+ const existing = rows.find((row) => row.id === value.id);
589
+ if (existing === void 0) rows.push({
590
+ ...value,
591
+ createdAt: now,
592
+ updatedAt: now
593
+ });
594
+ else Object.assign(existing, value, { updatedAt: now });
595
+ }
596
+ function createInsight(state, requirementId, input, participant, now) {
597
+ const draft = {
598
+ ...input,
599
+ title: input.title.trim(),
600
+ body: input.body.trim(),
601
+ dedupeHash: insightHash(input.sourceId, input.body),
602
+ createdBy: participant,
603
+ createdAt: now,
604
+ updatedAt: now
605
+ };
606
+ validateInsight(draft, state);
607
+ const existing = state.insights.find((item) => item.dedupeHash === draft.dedupeHash);
608
+ const insight = existing ?? draft;
609
+ if (existing === void 0) state.insights.push(insight);
610
+ if (!state.insightLinks.some((item) => item.insightId === insight.id && item.requirementId === requirementId && item.targetType === "requirement")) state.insightLinks.push({
611
+ id: randomUUID(),
612
+ insightId: insight.id,
613
+ requirementId,
614
+ targetType: "requirement",
615
+ createdBy: participant,
616
+ createdAt: now
617
+ });
618
+ return insight;
619
+ }
620
+ function addInsightLink(state, insightId, link, participant, now) {
621
+ if (!state.insights.some((item) => item.id === insightId)) throw new Error("insight not found");
622
+ if (!state.requirements.some((item) => item.id === link.requirementId)) throw new Error("requirement not found");
623
+ if (![
624
+ "requirement",
625
+ "section",
626
+ "acceptance-criterion"
627
+ ].includes(link.targetType)) throw new Error("invalid insight link target type");
628
+ if (link.targetType !== "requirement" && !link.targetId?.trim()) throw new Error("linked section or acceptance criterion id is required");
629
+ if (!state.insightLinks.some((item) => item.insightId === insightId && item.requirementId === link.requirementId && item.targetType === link.targetType && item.targetId === link.targetId)) state.insightLinks.push({
630
+ id: randomUUID(),
631
+ insightId,
632
+ ...link,
633
+ createdBy: participant,
634
+ createdAt: now
635
+ });
636
+ }
637
+ //#endregion
354
638
  //#region src/protocol.ts
355
639
  const API_PREFIX = "/api/spec-collab";
356
640
  function isParticipant(value) {
@@ -370,17 +654,291 @@ function parseEnvelope(value) {
370
654
  };
371
655
  }
372
656
  //#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 },
657
+ //#region src/collaboration-ledger.ts
658
+ var CollaborationLedger = class {
659
+ path;
660
+ publishSpec;
661
+ legacyPath;
662
+ pendingPath;
663
+ constructor(path, publishSpec, legacyPath) {
664
+ this.path = path;
665
+ this.publishSpec = publishSpec;
666
+ this.legacyPath = legacyPath;
667
+ this.pendingPath = `${path}.pending`;
668
+ }
669
+ save(state, spec) {
670
+ if (existsSync(this.pendingPath)) throw new Error("collaboration transaction requires recovery before further writes");
671
+ if (spec === void 0) {
672
+ atomicWrite(this.path, state);
673
+ return;
674
+ }
675
+ atomicWrite(this.pendingPath, {
676
+ state,
677
+ spec
678
+ });
679
+ try {
680
+ this.finish(state, spec);
681
+ } catch (error) {
682
+ throw new Error(`collaboration transaction requires recovery: ${errorMessage$2(error)}`, { cause: error });
683
+ }
684
+ }
685
+ load() {
686
+ if (existsSync(this.pendingPath)) return this.recover();
687
+ const source = existsSync(this.path) ? this.path : this.legacyPath;
688
+ if (source === void 0 || !existsSync(source)) return emptyState();
689
+ let parsed;
690
+ try {
691
+ parsed = JSON.parse(readFileSync(source, "utf8"));
692
+ } catch (error) {
693
+ throw new Error(`collaboration ledger is corrupted: ${errorMessage$2(error)}`, { cause: error });
694
+ }
695
+ if (!isRecord(parsed) || typeof parsed.schemaVersion !== "number") throw new Error("collaboration ledger has no schema version");
696
+ if (parsed.schemaVersion === 3) {
697
+ validateV3Ledger(parsed);
698
+ return normalizeV3(parsed);
699
+ }
700
+ if (parsed.schemaVersion !== 2) throw new Error(`unsupported collaboration schema: ${parsed.schemaVersion}`);
701
+ validateV2Ledger(parsed);
702
+ const migrated = migrateV2(parsed);
703
+ const extension = extname(source);
704
+ const stem = basename(source, extension).replace(/-v2$/, "");
705
+ copyFileSync(source, join(dirname(source), `${stem}-v2.backup-${Date.now()}${extension || ".json"}`));
706
+ atomicWrite(this.path, migrated);
707
+ return migrated;
708
+ }
709
+ recover() {
710
+ let state;
711
+ let spec;
712
+ try {
713
+ const pending = JSON.parse(readFileSync(this.pendingPath, "utf8"));
714
+ if (isRecord(pending) && "spec" in pending) {
715
+ if (!isPreparedSpecCommit(pending.spec)) throw new Error("invalid prepared Git commit");
716
+ spec = pending.spec;
717
+ state = pending.state;
718
+ } else state = pending;
719
+ validateV3Ledger(state);
720
+ } catch (error) {
721
+ throw new Error(`pending collaboration transaction is corrupted: ${errorMessage$2(error)}`, { cause: error });
722
+ }
723
+ this.finish(state, spec);
724
+ return normalizeV3(state);
725
+ }
726
+ finish(state, spec) {
727
+ if (spec !== void 0) this.publishSpec(spec);
728
+ atomicWrite(this.path, state);
729
+ unlinkSync(this.pendingPath);
730
+ }
731
+ };
732
+ function emptyState() {
733
+ return {
734
+ schemaVersion: 3,
735
+ revision: 0,
736
+ participants: [],
737
+ requirements: [],
738
+ companies: [],
739
+ customers: [],
740
+ feedbackSources: [],
741
+ insights: [],
742
+ insightLinks: [],
743
+ notifications: []
744
+ };
745
+ }
746
+ function errorMessage$2(error) {
747
+ return error instanceof Error ? error.message : String(error);
748
+ }
749
+ function isRecord(value) {
750
+ return typeof value === "object" && value !== null && !Array.isArray(value);
751
+ }
752
+ function validateV2Ledger(value) {
753
+ 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");
754
+ }
755
+ function validateV3Ledger(value) {
756
+ if (!isRecord(value)) throw new Error("invalid collaboration v3 ledger: object required");
757
+ if (value.schemaVersion !== 3 || !Number.isFinite(value.revision) || [
758
+ "participants",
759
+ "requirements",
760
+ "companies",
761
+ "customers",
762
+ "feedbackSources",
763
+ "insights",
764
+ "insightLinks",
765
+ "notifications"
766
+ ].some((key) => !Array.isArray(value[key]))) throw new Error("invalid collaboration v3 ledger: required collections are missing or invalid");
767
+ for (const candidate of value.requirements) {
768
+ if (!isRecord(candidate) || typeof candidate.id !== "string" || typeof candidate.title !== "string" || typeof candidate.currentCommit !== "string" || ![
769
+ "product-review",
770
+ "product-confirmation",
771
+ "joint-review",
772
+ "ready"
773
+ ].includes(String(candidate.stage))) throw new Error("invalid collaboration v3 ledger: malformed requirement");
774
+ if ([
775
+ "sources",
776
+ "reviewItems",
777
+ "comments",
778
+ "patches",
779
+ "decisions",
780
+ "confirmations",
781
+ "actionItems",
782
+ "aiRuns"
783
+ ].some((key) => !Array.isArray(candidate[key])) || candidate.aiConversations !== void 0 && !Array.isArray(candidate.aiConversations)) throw new Error("invalid collaboration v3 ledger: malformed requirement collections");
784
+ }
785
+ }
786
+ function atomicWrite(path, value) {
787
+ mkdirSync(dirname(path), {
788
+ recursive: true,
789
+ mode: 448
790
+ });
791
+ const tmp = `${path}.tmp`;
792
+ writeFileSync(tmp, JSON.stringify(value, null, 2), { mode: 384 });
793
+ const descriptor = openSync(tmp, "r");
794
+ try {
795
+ fsyncSync(descriptor);
796
+ } finally {
797
+ closeSync(descriptor);
798
+ }
799
+ renameSync(tmp, path);
800
+ }
801
+ function normalizeV3(value) {
802
+ value.participants ??= [];
803
+ value.requirements ??= [];
804
+ value.companies ??= [];
805
+ value.customers ??= [];
806
+ value.feedbackSources ??= [];
807
+ value.insights ??= [];
808
+ value.insightLinks ??= [];
809
+ value.notifications ??= [];
810
+ for (const record of value.requirements) {
811
+ record.sources ??= [];
812
+ record.reviewItems ??= [];
813
+ record.comments ??= [];
814
+ record.patches ??= [];
815
+ record.decisions ??= [];
816
+ record.confirmations ??= [];
817
+ record.actionItems ??= [];
818
+ record.aiRuns ??= [];
819
+ record.aiConversations ??= [];
820
+ record.stageCycle ??= 0;
821
+ for (const conversation of record.aiConversations) conversation.stageCycle ??= record.stageCycle;
822
+ if (record.stage === "ready" && record.readyPackage?.commit !== record.currentCommit) {
823
+ delete record.readyPackage;
824
+ record.stage = "joint-review";
825
+ record.stageCycle += 1;
826
+ } else if (record.aiConversations.length === 0 && (record.stage === "product-review" || record.stage === "joint-review")) {
827
+ 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) => ({
828
+ sessionId: item.sessionId,
829
+ createdAt: item.createdAt,
830
+ updatedAt: item.updatedAt
831
+ })), ...record.comments.filter((item) => item.aiSessionId).map((item) => ({
832
+ sessionId: item.aiSessionId,
833
+ createdAt: item.createdAt,
834
+ updatedAt: item.updatedAt
835
+ }))].sort((left, right) => right.updatedAt - left.updatedAt)[0];
836
+ if (recent) record.aiConversations.push({
837
+ stage: record.stage,
838
+ stageCycle: record.stageCycle,
839
+ ...recent
840
+ });
841
+ }
842
+ for (const comment of record.comments) {
843
+ comment.scope ??= comment.anchor === void 0 ? "page" : "inline";
844
+ comment.mentions ??= [];
845
+ comment.replies ??= [];
846
+ for (const reply of comment.replies) reply.mentions ??= [];
847
+ }
848
+ }
849
+ return value;
850
+ }
851
+ function migrateV2(value) {
852
+ const legacyRequirements = Array.isArray(value.requirements) ? value.requirements : [];
853
+ const requirements = structuredClone(legacyRequirements);
854
+ const feedbackSources = [];
855
+ const insights = [];
856
+ const insightLinks = [];
857
+ const migrationActor = {
858
+ participantId: "migration-v2",
859
+ nickname: "数据迁移",
860
+ role: "product",
861
+ kind: "ai",
862
+ sessionId: "migration-v2"
863
+ };
864
+ for (const record of requirements) {
865
+ record.sources ??= [];
866
+ record.reviewItems ??= [];
867
+ record.comments ??= [];
868
+ record.patches ??= [];
869
+ record.decisions ??= [];
870
+ record.confirmations ??= [];
871
+ record.actionItems ??= [];
872
+ record.aiRuns ??= [];
873
+ record.aiConversations ??= [];
874
+ record.stageCycle ??= 0;
875
+ for (const conversation of record.aiConversations) conversation.stageCycle ??= record.stageCycle;
876
+ for (const comment of record.comments) {
877
+ comment.scope = comment.anchor === void 0 ? "page" : "inline";
878
+ comment.mentions = [];
879
+ comment.replies ??= [];
880
+ for (const reply of comment.replies) reply.mentions = [];
881
+ }
882
+ for (const source of record.sources) {
883
+ const sourceId = `legacy-${createHash("sha256").update(`${record.id}:${source.id}`).digest("hex").slice(0, 16)}`;
884
+ const insightId = `legacy-${createHash("sha256").update(`${record.id}:${source.id}:insight`).digest("hex").slice(0, 16)}`;
885
+ feedbackSources.push({
886
+ id: sourceId,
887
+ kind: source.sourceType === "link" ? "url" : source.sourceType === "markdown" ? "markdown" : "text",
888
+ label: source.label,
889
+ ...source.sourceType === "link" && safeHttpUrl(source.stableId) ? { url: source.stableId } : {},
890
+ ...source.stableId ? { externalRef: source.stableId } : {},
891
+ accessStatus: source.accessStatus,
892
+ createdAt: record.createdAt,
893
+ updatedAt: record.updatedAt
894
+ });
895
+ insights.push({
896
+ id: insightId,
897
+ sourceId,
898
+ title: source.label,
899
+ body: `历史来源:${source.label}`,
900
+ importance: "unknown",
901
+ capturedAt: record.createdAt,
902
+ dedupeHash: insightHash(sourceId, source.label),
903
+ createdBy: migrationActor,
904
+ createdAt: record.createdAt,
905
+ updatedAt: record.updatedAt
906
+ });
907
+ insightLinks.push({
908
+ id: randomUUID(),
909
+ insightId,
910
+ requirementId: record.id,
911
+ targetType: "requirement",
912
+ createdBy: migrationActor,
913
+ createdAt: record.createdAt
914
+ });
915
+ }
916
+ }
917
+ return normalizeV3({
918
+ schemaVersion: 3,
919
+ revision: typeof value.revision === "number" ? value.revision : 0,
920
+ participants: Array.isArray(value.participants) ? value.participants : [],
921
+ requirements,
922
+ companies: [],
923
+ customers: [],
924
+ feedbackSources,
925
+ insights,
926
+ insightLinks,
927
+ notifications: []
928
+ });
929
+ }
930
+ //#endregion
931
+ //#region src/structured-diff.ts
932
+ function buildStructuredDiff(before, after, baseLabel = "原版本", headLabel = "新版本") {
933
+ const operations = myers(before.split("\n"), after.split("\n"));
934
+ let oldLine = 0;
935
+ let newLine = 0;
936
+ const lines = operations.map((operation) => {
937
+ if (operation.type !== "added") oldLine += 1;
938
+ if (operation.type !== "removed") newLine += 1;
939
+ return {
940
+ type: operation.type,
941
+ ...operation.type === "added" ? {} : { oldLine },
384
942
  ...operation.type === "removed" ? {} : { newLine },
385
943
  text: operation.text
386
944
  };
@@ -486,8 +1044,11 @@ function backtrack(trace, left, right) {
486
1044
  function hasCompletedCurrentReview(record, kind) {
487
1045
  return record.aiRuns.some((run) => run.commit === record.currentCommit && run.kind === kind && run.status === "completed");
488
1046
  }
1047
+ function currentVersionConfirmations(record, role) {
1048
+ return record.confirmations.filter((item) => item.commit === record.currentCommit && item.role === role && item.scope === "version" && item.status === "active" && item.participant.kind === "human" && item.participant.role === role);
1049
+ }
489
1050
  function hasVersionConfirmation(record, role) {
490
- return record.confirmations.some((item) => item.commit === record.currentCommit && item.role === role && item.scope === "version" && item.status === "active");
1051
+ return currentVersionConfirmations(record, role).length > 0;
491
1052
  }
492
1053
  /** Shared by workflow guidance and the authoritative Ready write. Checks must come from the current Git body. */
493
1054
  function readyAdmission(record, checks) {
@@ -508,44 +1069,282 @@ function readyAdmission(record, checks) {
508
1069
  };
509
1070
  }
510
1071
  //#endregion
511
- //#region src/engine.ts
512
- const emptyState = () => ({
513
- schemaVersion: 3,
514
- revision: 0,
515
- participants: [],
516
- requirements: [],
517
- companies: [],
518
- customers: [],
519
- feedbackSources: [],
520
- insights: [],
521
- insightLinks: [],
522
- notifications: []
523
- });
524
- var CollaborationEngine = class {
525
- eventPath;
526
- versions;
527
- options;
528
- state;
529
- coordinator;
530
- listeners = /* @__PURE__ */ new Set();
531
- seen = /* @__PURE__ */ new Map();
532
- eventContext;
533
- constructor(eventPath, versions, options = {}) {
534
- this.eventPath = eventPath;
535
- this.versions = versions;
536
- this.options = options;
537
- this.state = this.load();
538
- }
539
- setCoordinator(coordinator) {
540
- this.coordinator = coordinator;
541
- }
542
- snapshot() {
543
- return structuredClone(this.state);
1072
+ //#region src/spec-lifecycle.ts
1073
+ function enterStage(record, stage) {
1074
+ if (record.stage === stage) return;
1075
+ record.stage = stage;
1076
+ record.stageCycle += 1;
1077
+ }
1078
+ function advance(record, participant) {
1079
+ if (record.stage === "product-review") {
1080
+ if (record.reviewItems.some((item) => item.commit === record.currentCommit && item.severity === "blocking" && ![
1081
+ "resolved",
1082
+ "non-blocking-verify",
1083
+ "joint-review"
1084
+ ].includes(item.status))) throw new Error("product blocking review items remain");
1085
+ if (!hasCompletedCurrentReview(record, "product-second")) throw new Error("product second review is required");
1086
+ enterStage(record, "product-confirmation");
1087
+ return;
544
1088
  }
545
- directory() {
546
- return structuredClone(this.state.participants).sort((left, right) => left.nickname.localeCompare(right.nickname, "zh-CN"));
1089
+ if (record.stage === "product-confirmation") {
1090
+ if (participant.role !== "product" || !hasVersionConfirmation(record, "product")) throw new Error("product must confirm the current version");
1091
+ enterStage(record, "joint-review");
1092
+ return;
547
1093
  }
548
- notifications(participantId, page = 1, pageSize = 50) {
1094
+ throw new Error("stage cannot advance directly");
1095
+ }
1096
+ function sections(markdown) {
1097
+ const result = /* @__PURE__ */ new Map();
1098
+ let heading = "";
1099
+ for (const line of markdown.split("\n")) if (/^##\s+/.test(line)) {
1100
+ heading = line.replace(/^##\s+/, "").trim();
1101
+ result.set(heading, "");
1102
+ } else if (heading) result.set(heading, `${result.get(heading) ?? ""}\n${line}`);
1103
+ return result;
1104
+ }
1105
+ function acceptance(markdown) {
1106
+ const result = /* @__PURE__ */ new Map();
1107
+ for (const match of markdown.matchAll(/\*\*(AC-[A-Za-z0-9-]+)(?:\s+[^*]+)?\*\*\s*[::]\s*(.+)/g)) result.set(match[1], match[2].trim());
1108
+ return result;
1109
+ }
1110
+ function changedScopes(before, after) {
1111
+ const a = sections(before);
1112
+ const b = sections(after);
1113
+ const sectionNames = /* @__PURE__ */ new Set([...a.keys(), ...b.keys()]);
1114
+ const acA = acceptance(before);
1115
+ const acB = acceptance(after);
1116
+ const acNames = /* @__PURE__ */ new Set([...acA.keys(), ...acB.keys()]);
1117
+ return {
1118
+ sections: [...sectionNames].filter((key) => a.get(key) !== b.get(key)),
1119
+ acceptanceIds: [...acNames].filter((key) => acA.get(key) !== acB.get(key))
1120
+ };
1121
+ }
1122
+ function intersects(left, right) {
1123
+ return left.some((item) => right.includes(item));
1124
+ }
1125
+ function normalizeAnchorText(value) {
1126
+ return value.replace(/[`*_>#\[\]()~-]/g, "").replace(/\s+/g, "").toLocaleLowerCase();
1127
+ }
1128
+ function headingForLine(lines, index) {
1129
+ for (let cursor = index; cursor >= 0; cursor -= 1) {
1130
+ const match = /^#{1,4}\s+(.+)$/.exec(lines[cursor] ?? "");
1131
+ if (match?.[1]) return match[1].trim();
1132
+ }
1133
+ }
1134
+ function decisionScopeAnchors(markdown, affectedSections, affectedAcceptanceIds) {
1135
+ const anchors = [];
1136
+ const sectionMap = sections(markdown);
1137
+ for (const section of affectedSections.map((value) => value.trim()).filter(Boolean)) {
1138
+ const quote = sectionMap.get(section)?.split("\n").map((line) => line.trim()).find((line) => line && !/^#+\s+/.test(line));
1139
+ if (quote) anchors.push({
1140
+ heading: section,
1141
+ quote
1142
+ });
1143
+ }
1144
+ const lines = markdown.split("\n");
1145
+ for (const acceptanceId of affectedAcceptanceIds.map((value) => value.trim()).filter(Boolean)) {
1146
+ const index = lines.findIndex((line) => normalizeAnchorText(line).includes(normalizeAnchorText(acceptanceId)));
1147
+ if (index >= 0) {
1148
+ const heading = headingForLine(lines, index);
1149
+ anchors.push({
1150
+ ...heading ? { heading } : {},
1151
+ quote: lines[index].trim()
1152
+ });
1153
+ }
1154
+ }
1155
+ return anchors;
1156
+ }
1157
+ function decisionAnchorStillExists(markdown, anchor) {
1158
+ const quote = normalizeAnchorText(anchor.quote);
1159
+ if (!quote) return false;
1160
+ const sectionMap = sections(markdown);
1161
+ const candidates = anchor.heading?.trim() ? [sectionMap.get(anchor.heading.trim()) ?? ""] : [markdown];
1162
+ const context = normalizeAnchorText(`${anchor.prefix ?? ""}${anchor.quote}${anchor.suffix ?? ""}`);
1163
+ return candidates.some((candidate) => {
1164
+ const normalized = normalizeAnchorText(candidate);
1165
+ return normalized.includes(context) || normalized.includes(quote);
1166
+ });
1167
+ }
1168
+ function invalidateAffected(record, changedSections, changedAcceptanceIds, currentMarkdown) {
1169
+ for (const confirmation of record.confirmations) {
1170
+ if (confirmation.status !== "active") continue;
1171
+ if (confirmation.scope === "version" || confirmation.scope === "section" && confirmation.scopeId !== void 0 && changedSections.includes(confirmation.scopeId) || confirmation.scope === "acceptance-criterion" && confirmation.scopeId !== void 0 && changedAcceptanceIds.includes(confirmation.scopeId)) {
1172
+ confirmation.status = "invalidated";
1173
+ record.actionItems.push({
1174
+ id: randomUUID(),
1175
+ requirementId: record.id,
1176
+ sourceType: "confirmation",
1177
+ sourceId: confirmation.id,
1178
+ type: "reconfirm",
1179
+ assigneeRole: confirmation.role,
1180
+ blocking: true,
1181
+ status: "pending",
1182
+ dueStage: record.stage,
1183
+ createdAt: Date.now(),
1184
+ updatedAt: Date.now()
1185
+ });
1186
+ }
1187
+ }
1188
+ record.reviewItems.filter((item) => item.status === "resolved" && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach((item) => {
1189
+ item.status = "invalidated";
1190
+ item.updatedAt = Date.now();
1191
+ });
1192
+ record.decisions.filter((item) => item.status === "active" && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach((item) => {
1193
+ item.status = "invalidated";
1194
+ });
1195
+ if (currentMarkdown !== void 0) record.decisions.filter((item) => item.status === "active" && item.sourceAnchors?.some((anchor) => !decisionAnchorStillExists(currentMarkdown, anchor))).forEach((item) => {
1196
+ item.status = "invalidated";
1197
+ });
1198
+ }
1199
+ function readiness(markdown, record) {
1200
+ const sectionMap = sections(markdown);
1201
+ const ac = acceptance(markdown);
1202
+ const meaningful = (name) => {
1203
+ const value = sectionMap.get(name)?.replace(/<!--.*?-->/gs, "").trim() ?? "";
1204
+ return value.length >= 12 && !/待澄清|待补充|TODO/i.test(value);
1205
+ };
1206
+ const blockers = record.reviewItems.filter((item) => item.commit === record.currentCommit && item.severity === "blocking" && !["resolved", "non-blocking-verify"].includes(item.status)).map((item) => item.statement);
1207
+ return [
1208
+ {
1209
+ key: "goal",
1210
+ passed: meaningful("目标与用户结果"),
1211
+ reasons: meaningful("目标与用户结果") ? [] : ["缺少可观察的目标与用户结果"]
1212
+ },
1213
+ {
1214
+ key: "acceptance",
1215
+ passed: ac.size > 0 && [...ac.values()].every((value) => !/待澄清|待补充|TODO/i.test(value)),
1216
+ reasons: ac.size === 0 ? ["缺少稳定 AC ID 与可判定结果"] : [...ac.values()].some((value) => /待澄清|待补充|TODO/i.test(value)) ? ["验收标准仍含占位内容"] : []
1217
+ },
1218
+ {
1219
+ key: "scope",
1220
+ passed: meaningful("范围与非范围"),
1221
+ reasons: meaningful("范围与非范围") ? [] : ["范围与非范围不完整"]
1222
+ },
1223
+ {
1224
+ key: "semantics",
1225
+ passed: meaningful("业务术语与规则"),
1226
+ reasons: meaningful("业务术语与规则") ? [] : ["关键术语和规则不完整"]
1227
+ },
1228
+ {
1229
+ key: "evidence",
1230
+ passed: record.sources.every((source) => source.accessStatus !== "missing") && blockers.length === 0,
1231
+ reasons: [...record.sources.filter((source) => source.accessStatus === "missing").map((source) => `来源不可访问:${source.label}`), ...blockers]
1232
+ },
1233
+ {
1234
+ key: "test-constraints",
1235
+ passed: meaningful("测试约束"),
1236
+ reasons: meaningful("测试约束") ? [] : ["测试环境、账号、权限或 fixture 约束不完整"]
1237
+ }
1238
+ ];
1239
+ }
1240
+ function versionChanged(record, previousMarkdown, version, now) {
1241
+ const impact = changedScopes(previousMarkdown, version.markdown);
1242
+ record.currentCommit = version.commit;
1243
+ record.updatedAt = now;
1244
+ delete record.readyPackage;
1245
+ if (record.stage === "ready") enterStage(record, "joint-review");
1246
+ for (const patch of record.patches) {
1247
+ if (patch.status !== "pending") continue;
1248
+ patch.status = "stale";
1249
+ retireActionItems(record, "patch", patch.id, "invalidated", now);
1250
+ }
1251
+ invalidateAffected(record, impact.sections, impact.acceptanceIds, version.markdown);
1252
+ }
1253
+ function retireActionItems(record, sourceType, sourceId, status, now) {
1254
+ for (const task of record.actionItems) if (task.sourceType === sourceType && task.sourceId === sourceId && task.status === "pending") {
1255
+ task.status = status;
1256
+ task.updatedAt = now;
1257
+ }
1258
+ }
1259
+ function readyMarkdown(record, markdown) {
1260
+ const signers = (role) => [...new Set(currentVersionConfirmations(record, role).map((item) => item.participant.nickname))].join("、");
1261
+ const open = record.reviewItems.filter((item) => item.status === "non-blocking-verify");
1262
+ const sourceStatus = {
1263
+ available: "可查阅",
1264
+ unverified: "待核对",
1265
+ missing: "待补充"
1266
+ };
1267
+ return [
1268
+ `# 就绪需求:${record.title}`,
1269
+ "",
1270
+ "## 版本信息",
1271
+ "",
1272
+ `- 需求编号:${record.id}`,
1273
+ `- 文档版本:${record.currentCommit}`,
1274
+ `- 产品确认:${signers("product")}`,
1275
+ `- 研发确认:${signers("engineering")}`,
1276
+ "",
1277
+ markdown,
1278
+ "",
1279
+ "## 已确认决策",
1280
+ ...record.decisions.filter((item) => item.status === "active").map((item) => `- ${item.question}:${item.decision}(原因:${item.rationale})`),
1281
+ "",
1282
+ "## 参考资料",
1283
+ ...record.sources.map((source) => `- [${sourceStatus[source.accessStatus]}] ${source.label}${source.stableId ? `:${source.stableId}` : ""}${source.version ? `(版本:${source.version})` : ""}`),
1284
+ "",
1285
+ "## 待确认问题",
1286
+ ...open.map((item) => `- ${item.question};负责人:${item.ownerParticipantId ?? (item.ownerRole === "product" ? "产品" : "研发")};影响:${item.impact}`),
1287
+ ""
1288
+ ].join("\n");
1289
+ }
1290
+ //#endregion
1291
+ //#region src/engine.ts
1292
+ var CollaborationEngine = class {
1293
+ versions;
1294
+ state;
1295
+ ledger;
1296
+ coordinator;
1297
+ listeners = /* @__PURE__ */ new Set();
1298
+ seen = /* @__PURE__ */ new Map();
1299
+ constructor(eventPath, versions, options = {}) {
1300
+ this.versions = versions;
1301
+ this.ledger = new CollaborationLedger(eventPath, (change) => versions.publish(change), options.legacyPath);
1302
+ this.state = this.ledger.load();
1303
+ }
1304
+ setCoordinator(coordinator) {
1305
+ if (this.coordinator === void 0) this.changeAi(() => {
1306
+ let interrupted = false;
1307
+ const now = Date.now();
1308
+ for (const record of this.state.requirements) {
1309
+ for (const run of record.aiRuns) {
1310
+ if (run.status !== "queued") continue;
1311
+ run.status = "failed";
1312
+ run.error = "AI launch was interrupted before acknowledgement";
1313
+ run.updatedAt = now;
1314
+ interrupted = true;
1315
+ }
1316
+ for (const comment of record.comments) {
1317
+ if (comment.aiStatus !== "queued") continue;
1318
+ comment.aiStatus = "failed";
1319
+ comment.updatedAt = now;
1320
+ interrupted = true;
1321
+ }
1322
+ }
1323
+ if (interrupted) return { types: [
1324
+ "ai.status",
1325
+ "comment.changed",
1326
+ "metrics.changed"
1327
+ ] };
1328
+ });
1329
+ this.coordinator = coordinator;
1330
+ }
1331
+ get revision() {
1332
+ return this.state.revision;
1333
+ }
1334
+ snapshot() {
1335
+ return structuredClone(this.state);
1336
+ }
1337
+ overview() {
1338
+ return {
1339
+ revision: this.revision,
1340
+ participants: structuredClone(this.state.participants),
1341
+ requirements: this.summaries()
1342
+ };
1343
+ }
1344
+ directory() {
1345
+ return structuredClone(this.state.participants).sort((left, right) => left.nickname.localeCompare(right.nickname, "zh-CN"));
1346
+ }
1347
+ notifications(participantId, page = 1, pageSize = 50) {
549
1348
  const rows = this.state.notifications.filter((item) => item.recipientParticipantId === participantId).sort((left, right) => right.createdAt - left.createdAt);
550
1349
  const safePage = Number.isFinite(page) ? Math.max(1, Math.trunc(page)) : 1;
551
1350
  const safePageSize = Number.isFinite(pageSize) ? Math.min(100, Math.max(1, Math.trunc(pageSize))) : 50;
@@ -556,27 +1355,8 @@ var CollaborationEngine = class {
556
1355
  unread: rows.filter((item) => item.readAt === void 0).length
557
1356
  };
558
1357
  }
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
- };
1358
+ insights(query) {
1359
+ return queryInsights(this.state, query);
580
1360
  }
581
1361
  subscribe(listener) {
582
1362
  this.listeners.add(listener);
@@ -595,12 +1375,12 @@ var CollaborationEngine = class {
595
1375
  ...record.archivedAt ? { archivedAt: record.archivedAt } : {},
596
1376
  updatedAt: record.updatedAt,
597
1377
  metrics: requirementMetrics(record, this.state),
598
- participantIds: requirementParticipantIds(record, this.versions.history(record.id))
1378
+ participantIds: requirementParticipantIds(record, this.versions.history(record.id, record.currentCommit))
599
1379
  }));
600
1380
  }
601
1381
  version(requirementId, commit) {
602
1382
  const record = this.record(requirementId);
603
- if (!this.versions.history(record.id).some((version) => version.commit === commit)) throw new Error("requirement version not found");
1383
+ if (!this.versions.history(record.id, record.currentCommit).some((version) => version.commit === commit)) throw new Error("requirement version not found");
604
1384
  return this.versions.read(record.id, commit);
605
1385
  }
606
1386
  diff(requirementId, baseCommit, headCommit) {
@@ -632,12 +1412,13 @@ var CollaborationEngine = class {
632
1412
  }
633
1413
  view(id) {
634
1414
  const record = this.record(id);
1415
+ const history = this.versions.history(id, record.currentCommit);
635
1416
  const version = this.versions.read(id, record.currentCommit);
636
1417
  const commitUrl = this.versions.commitUrl(record.currentCommit);
637
1418
  return {
638
1419
  ...structuredClone(record),
639
1420
  version,
640
- history: this.versions.history(id),
1421
+ history,
641
1422
  readiness: readiness(version.markdown, record),
642
1423
  metrics: requirementMetrics(record, this.state),
643
1424
  ...commitUrl ? { commitUrl } : {}
@@ -647,171 +1428,174 @@ var CollaborationEngine = class {
647
1428
  const cached = this.seen.get(requestId);
648
1429
  if (cached !== void 0) return structuredClone(cached);
649
1430
  let result;
650
- const beforeState = structuredClone(this.state);
651
- const previousEventContext = this.eventContext;
652
- this.eventContext = eventForAction(action);
1431
+ let committed;
653
1432
  try {
654
- const registered = action.participant.kind === "human" ? this.state.participants.find((item) => item.participantId === action.participant.participantId) : void 0;
655
- if (registered !== void 0 && registered.role !== action.participant.role) throw new Error(`participant role is bound to ${registered.role}`);
656
- result = this.applyFresh(action);
657
- if (result.ok && action.participant.kind === "human" && registered === void 0) {
658
- this.state.participants.push(structuredClone(action.participant));
659
- this.persist();
660
- result = result.deletedRequirementId ? {
661
- ...result,
662
- revision: this.state.revision
663
- } : {
664
- ok: true,
665
- revision: this.state.revision,
666
- requirement: result.requirement
1433
+ committed = this.transact(() => {
1434
+ const participant = action.participant;
1435
+ requireHuman(participant);
1436
+ const registered = this.state.participants.find((item) => item.participantId === participant.participantId);
1437
+ if (registered !== void 0 && registered.role !== participant.role) throw new Error(`participant role is bound to ${registered.role}`);
1438
+ const change = this.applyFresh(action);
1439
+ if (registered === void 0) this.state.participants.push(structuredClone(participant));
1440
+ const event = change.unchanged && registered !== void 0 ? void 0 : eventForAction(action, change);
1441
+ return {
1442
+ value: {
1443
+ requirement: change.deleted ?? this.view(change.requirementId),
1444
+ change
1445
+ },
1446
+ event,
1447
+ spec: change.spec
667
1448
  };
668
- }
1449
+ });
1450
+ const { requirement, change } = committed.value;
1451
+ result = {
1452
+ ok: true,
1453
+ revision: committed.event?.revision ?? this.state.revision,
1454
+ requirement,
1455
+ ...change.deleted ? { deletedRequirementId: change.requirementId } : {}
1456
+ };
669
1457
  } catch (error) {
670
- this.state = beforeState;
671
- const conflict = error instanceof VersionConflictError && action.kind === "version.save" ? this.saveConflict(action) : void 0;
1458
+ const conflict = error instanceof VersionConflictError && action.kind === "version.save" ? this.saveConflict(action, error.currentCommit) : void 0;
672
1459
  result = {
673
1460
  ok: false,
674
1461
  revision: this.state.revision,
675
- error: error instanceof Error ? error.message : String(error),
676
- ...conflict === void 0 ? {} : { conflict }
1462
+ error: errorMessage$1(error),
1463
+ ...conflict ? { conflict } : {}
677
1464
  };
678
1465
  }
679
- this.eventContext = previousEventContext;
680
1466
  this.seen.set(requestId, result);
1467
+ if (committed !== void 0) {
1468
+ this.emit(committed.event);
1469
+ const { requirement, change } = committed.value;
1470
+ if (change.task) this.launchAiTask(requirement, change.task);
1471
+ }
681
1472
  return structuredClone(result);
682
1473
  }
683
1474
  submitReview(input) {
684
- const record = this.record(input.requirementId);
685
- const run = record.aiRuns.find((item) => item.id === input.runId);
686
- if (run === void 0 || run.commit !== input.commit || record.currentCommit !== input.commit) throw new Error("review run is stale");
687
- assertChineseFeedback(input.maturitySummary);
688
- const now = Date.now();
689
- for (const item of input.items) {
690
- assertChineseFeedback(item.statement, item.impact, item.question);
691
- if (item.epistemicStatus === "FACT" && !item.evidence.some((evidence) => evidence.accessible && evidence.version !== void 0 && evidence.version !== "")) throw new Error("FACT requires accessible versioned evidence");
692
- const recommendedOptions = item.recommendedOptions?.map((option) => option.trim()).filter(Boolean);
693
- const created = {
694
- ...item,
695
- ...recommendedOptions ? { recommendedOptions } : {},
1475
+ this.changeAi(() => {
1476
+ const record = this.record(input.requirementId);
1477
+ const run = record.aiRuns.find((item) => item.id === input.runId);
1478
+ if (run === void 0 || run.commit !== input.commit || record.currentCommit !== input.commit) throw new Error("review run is stale");
1479
+ if (run.status === "completed") return;
1480
+ assertChineseFeedback(input.maturitySummary);
1481
+ const now = Date.now();
1482
+ for (const item of input.items) {
1483
+ assertChineseFeedback(item.statement, item.impact, item.question);
1484
+ if (item.epistemicStatus === "FACT" && !item.evidence.some((evidence) => evidence.accessible && evidence.version?.trim())) throw new Error("FACT requires accessible versioned evidence");
1485
+ const recommendedOptions = item.recommendedOptions?.map((option) => option.trim()).filter(Boolean);
1486
+ const created = {
1487
+ ...item,
1488
+ ...recommendedOptions ? { recommendedOptions } : {},
1489
+ id: randomUUID(),
1490
+ requirementId: record.id,
1491
+ commit: input.commit,
1492
+ reviewKind: run.kind,
1493
+ createdAt: now,
1494
+ updatedAt: now
1495
+ };
1496
+ record.reviewItems.push(created);
1497
+ record.actionItems.push(actionForReview(created));
1498
+ }
1499
+ run.status = "completed";
1500
+ run.maturitySummary = input.maturitySummary;
1501
+ run.updatedAt = now;
1502
+ delete run.error;
1503
+ return aiEvent(record.id, run.id);
1504
+ });
1505
+ }
1506
+ submitPatch(input) {
1507
+ this.changeAi(() => {
1508
+ const record = this.record(input.requirementId);
1509
+ if (record.currentCommit !== input.baseCommit) throw new Error("patch base commit is stale");
1510
+ assertChineseFeedback(input.summary, input.proposedMarkdown);
1511
+ const now = Date.now();
1512
+ const patch = {
1513
+ id: randomUUID(),
1514
+ requirementId: record.id,
1515
+ baseCommit: input.baseCommit,
1516
+ reviewKind: input.reviewKind,
1517
+ proposedMarkdown: input.proposedMarkdown,
1518
+ summary: input.summary,
1519
+ affectedReviewItemIds: input.affectedReviewItemIds,
1520
+ affectedSections: input.affectedSections,
1521
+ affectedAcceptanceIds: input.affectedAcceptanceIds,
1522
+ createdBy: input.ai,
1523
+ status: "pending",
1524
+ createdAt: now
1525
+ };
1526
+ record.patches.push(patch);
1527
+ record.actionItems.push({
696
1528
  id: randomUUID(),
697
1529
  requirementId: record.id,
698
- commit: input.commit,
699
- reviewKind: run.kind,
1530
+ sourceType: "patch",
1531
+ sourceId: patch.id,
1532
+ type: "confirm",
1533
+ assigneeRole: input.reviewKind === "engineering-precheck" ? "engineering" : "product",
1534
+ blocking: true,
1535
+ status: "pending",
1536
+ dueStage: record.stage,
700
1537
  createdAt: now,
701
1538
  updatedAt: now
702
- };
703
- record.reviewItems.push(created);
704
- record.actionItems.push(actionForReview(created));
705
- }
706
- run.status = "completed";
707
- run.maturitySummary = input.maturitySummary;
708
- run.updatedAt = now;
709
- this.persist({
710
- types: ["ai.status", "metrics.changed"],
711
- requirementId: record.id,
712
- objectId: run.id
713
- });
714
- }
715
- submitPatch(input) {
716
- const record = this.record(input.requirementId);
717
- if (record.currentCommit !== input.baseCommit) throw new Error("patch base commit is stale");
718
- assertChineseFeedback(input.summary, input.proposedMarkdown);
719
- const patch = {
720
- id: randomUUID(),
721
- requirementId: record.id,
722
- baseCommit: input.baseCommit,
723
- reviewKind: input.reviewKind,
724
- proposedMarkdown: input.proposedMarkdown,
725
- summary: input.summary,
726
- affectedReviewItemIds: input.affectedReviewItemIds,
727
- affectedSections: input.affectedSections,
728
- affectedAcceptanceIds: input.affectedAcceptanceIds,
729
- createdBy: input.ai,
730
- status: "pending",
731
- createdAt: Date.now()
732
- };
733
- record.patches.push(patch);
734
- record.actionItems.push({
735
- id: randomUUID(),
736
- requirementId: record.id,
737
- sourceType: "patch",
738
- sourceId: patch.id,
739
- type: "confirm",
740
- assigneeRole: input.reviewKind === "engineering-precheck" ? "engineering" : "product",
741
- blocking: true,
742
- status: "pending",
743
- dueStage: record.stage,
744
- createdAt: Date.now(),
745
- updatedAt: Date.now()
746
- });
747
- this.persist({
748
- types: ["ai.status", "metrics.changed"],
749
- requirementId: record.id,
750
- objectId: patch.id
1539
+ });
1540
+ return aiEvent(record.id, patch.id);
751
1541
  });
752
1542
  }
753
1543
  submitAiReply(input) {
754
- assertChineseFeedback(input.body);
755
- const record = this.record(input.requirementId);
756
- const comment = this.comment(record, input.commentId);
757
- comment.replies.push({
758
- id: randomUUID(),
759
- author: input.ai,
760
- body: input.body,
761
- mentions: [],
762
- createdAt: Date.now()
763
- });
764
- comment.aiStatus = "completed";
765
- comment.updatedAt = Date.now();
766
- this.persist({
767
- types: [
768
- "ai.status",
769
- "comment.changed",
770
- "metrics.changed"
771
- ],
772
- requirementId: record.id,
773
- objectId: comment.id
1544
+ this.changeAi(() => {
1545
+ assertChineseFeedback(input.body);
1546
+ const record = this.record(input.requirementId);
1547
+ const comment = this.comment(record, input.commentId);
1548
+ const now = Date.now();
1549
+ comment.replies.push({
1550
+ id: randomUUID(),
1551
+ author: input.ai,
1552
+ body: input.body,
1553
+ mentions: [],
1554
+ createdAt: now
1555
+ });
1556
+ comment.aiStatus = "completed";
1557
+ comment.updatedAt = now;
1558
+ return aiEvent(record.id, comment.id, true);
774
1559
  });
775
1560
  }
776
1561
  markAiFailure(requirementId, sourceId, error) {
777
- const record = this.record(requirementId);
778
- const run = record.aiRuns.find((item) => item.id === sourceId);
779
- if (run !== void 0) {
780
- run.status = "failed";
781
- run.error = error;
782
- run.updatedAt = Date.now();
783
- }
784
- const comment = record.comments.find((item) => item.id === sourceId);
785
- if (comment !== void 0) {
786
- comment.aiStatus = "failed";
787
- comment.updatedAt = Date.now();
788
- }
789
- this.persist({
790
- types: ["ai.status", "metrics.changed"],
791
- requirementId,
792
- objectId: sourceId
1562
+ this.changeAi(() => {
1563
+ const record = this.state.requirements.find((item) => item.id === requirementId);
1564
+ if (record === void 0) return;
1565
+ const run = record.aiRuns.find((item) => item.id === sourceId);
1566
+ const comment = record.comments.find((item) => item.id === sourceId);
1567
+ if (run !== void 0 && (run.status === "queued" || run.status === "running")) {
1568
+ run.status = "failed";
1569
+ run.error = error;
1570
+ run.updatedAt = Date.now();
1571
+ return aiEvent(record.id, run.id);
1572
+ }
1573
+ if (comment !== void 0 && (comment.aiStatus === "queued" || comment.aiStatus === "running")) {
1574
+ comment.aiStatus = "failed";
1575
+ comment.updatedAt = Date.now();
1576
+ return aiEvent(record.id, comment.id, true);
1577
+ }
793
1578
  });
794
1579
  }
795
1580
  applyFresh(action) {
796
1581
  const now = Date.now();
797
1582
  if (action.kind === "requirement.create") {
798
- requireHuman(action.participant);
799
1583
  const title = action.title.trim();
800
1584
  if (title === "" || action.rawRequirement.trim() === "") throw new Error("title and original requirement are required");
801
1585
  const workspaceId = action.workspaceId?.trim();
802
1586
  if (workspaceId === void 0 || workspaceId === "") throw new Error("review workspace is required");
803
- const created = this.versions.create({
1587
+ const spec = this.versions.prepareCreate({
804
1588
  title,
805
1589
  rawRequirement: action.rawRequirement,
806
1590
  sources: action.sources,
807
1591
  participant: action.participant
808
1592
  });
809
1593
  const record = {
810
- id: created.requirementId,
1594
+ id: spec.requirementId,
811
1595
  title,
812
1596
  stage: "product-review",
813
1597
  stageCycle: 0,
814
- currentCommit: created.version.commit,
1598
+ currentCommit: spec.commit,
815
1599
  workspaceId,
816
1600
  sources: action.sources,
817
1601
  reviewItems: [],
@@ -826,115 +1610,39 @@ var CollaborationEngine = class {
826
1610
  updatedAt: now
827
1611
  };
828
1612
  this.state.requirements.unshift(record);
829
- this.persist(void 0, true);
830
- this.enqueueReview(record, action.participant, "product-first");
831
1613
  return {
832
- ok: true,
833
- revision: this.state.revision,
834
- requirement: this.view(record.id)
1614
+ requirementId: record.id,
1615
+ spec,
1616
+ task: this.queueReview(record, action.participant, "product-first", now)
835
1617
  };
836
1618
  }
837
1619
  const record = this.record(action.requirementId);
838
1620
  if (action.kind === "requirement.bind-workspace") {
839
- requireHuman(action.participant);
840
1621
  const workspaceId = action.workspaceId.trim();
841
1622
  if (workspaceId === "") throw new Error("review workspace is required");
842
1623
  if (record.workspaceId !== void 0) throw new Error("review workspace is already bound");
843
1624
  record.workspaceId = workspaceId;
844
1625
  record.updatedAt = now;
845
- this.persist();
846
- } else if (action.kind === "requirement.rename") {
847
- requireHuman(action.participant);
848
- const title = action.title.trim();
849
- if (title === "" || title.length > 120 || /[\r\n]/.test(title)) throw new Error("valid requirement title is required");
850
- if (title === record.title) return {
851
- ok: true,
852
- revision: this.state.revision,
853
- requirement: this.view(record.id)
854
- };
855
- const before = this.versions.read(record.id, record.currentCommit).markdown;
856
- const markdown = /^# .+$/m.test(before) ? before.replace(/^# .+$/m, `# ${title}`) : `# ${title}\n\n${before}`;
857
- const version = this.versions.save({
858
- requirementId: record.id,
859
- baseCommit: record.currentCommit,
860
- markdown,
861
- participant: action.participant,
862
- summary: `Rename requirement: ${title}`
863
- });
864
- record.title = title;
865
- record.currentCommit = version.commit;
866
- record.updatedAt = now;
867
- invalidateAffected(record, [], []);
868
- this.persist(void 0, true);
869
- this.enqueueReview(record, action.participant, "change-review");
870
1626
  } else if (action.kind === "requirement.archive" || action.kind === "requirement.unarchive") {
871
- requireHuman(action.participant);
872
1627
  if (action.kind === "requirement.archive" && action.archived) record.archivedAt = now;
873
1628
  else delete record.archivedAt;
874
1629
  record.updatedAt = now;
875
- this.persist();
876
1630
  } else if (action.kind === "requirement.delete") {
877
- requireHuman(action.participant);
878
1631
  const deleted = this.view(record.id);
879
- this.versions.remove(record.id, action.participant);
1632
+ const spec = this.versions.prepareRemove(record.id, record.currentCommit, action.participant);
880
1633
  this.state.requirements.splice(this.state.requirements.indexOf(record), 1);
881
1634
  this.state.insightLinks = this.state.insightLinks.filter((item) => item.requirementId !== record.id);
882
- this.persist(void 0, true);
883
1635
  return {
884
- ok: true,
885
- revision: this.state.revision,
886
- requirement: deleted,
887
- deletedRequirementId: record.id
888
- };
889
- } else if (action.kind === "version.save") {
890
- requireHuman(action.participant);
891
- const before = this.versions.read(record.id, record.currentCommit).markdown;
892
- const version = this.versions.save({
893
1636
  requirementId: record.id,
894
- baseCommit: action.baseCommit,
895
- markdown: action.markdown,
896
- participant: action.participant,
897
- summary: action.summary
898
- });
899
- const impact = changedScopes(before, action.markdown);
900
- record.currentCommit = version.commit;
901
- record.updatedAt = now;
902
- delete record.readyPackage;
903
- invalidateAffected(record, impact.sections, impact.acceptanceIds, action.markdown);
904
- record.patches.filter((item) => item.status === "pending").forEach((item) => {
905
- item.status = "stale";
906
- });
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);
932
- this.enqueueReview(record, action.participant, "change-review");
933
- } else if (action.kind === "review.request") {
934
- requireHuman(action.participant);
935
- this.enqueueReview(record, action.participant, action.reviewKind);
936
- } else if (action.kind === "review.respond") {
937
- requireHuman(action.participant);
1637
+ spec,
1638
+ deleted
1639
+ };
1640
+ } else if (action.kind === "requirement.rename" || action.kind === "version.save" || action.kind === "version.restore" || action.kind === "patch.accept") return this.changeVersion(record, action, now);
1641
+ else if (action.kind === "review.request") return {
1642
+ requirementId: record.id,
1643
+ task: this.queueReview(record, action.participant, action.reviewKind, now)
1644
+ };
1645
+ else if (action.kind === "review.respond") {
938
1646
  const item = record.reviewItems.find((candidate) => candidate.id === action.reviewItemId);
939
1647
  if (item === void 0) throw new Error("review item not found");
940
1648
  item.response = {
@@ -949,9 +1657,7 @@ var CollaborationEngine = class {
949
1657
  task.status = "handled";
950
1658
  task.updatedAt = now;
951
1659
  });
952
- this.persist();
953
1660
  } else if (action.kind === "comment.create") {
954
- requireHuman(action.participant);
955
1661
  if (action.commit !== record.currentCommit) throw new VersionConflictError(record.currentCommit);
956
1662
  const scope = action.scope ?? "inline";
957
1663
  const mentions = validMentions(action.mentions, this.state.participants);
@@ -965,7 +1671,7 @@ var CollaborationEngine = class {
965
1671
  body: action.body.trim(),
966
1672
  mentions,
967
1673
  replies: [],
968
- aiStatus: "queued",
1674
+ aiStatus: this.coordinator ? "queued" : "failed",
969
1675
  status: "open",
970
1676
  createdAt: now,
971
1677
  updatedAt: now
@@ -987,35 +1693,14 @@ var CollaborationEngine = class {
987
1693
  updatedAt: now
988
1694
  });
989
1695
  for (const participantId of mentions) this.notify(participantId, "mention", record, "comment", comment.id, `${action.participant.nickname} 在评论中提到了你`);
990
- this.persist();
991
- const coordinator = this.coordinator;
992
- if (coordinator !== void 0) {
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;
997
- coordinator.requestCommentReply({
998
- requirement: view,
999
- comment,
1000
- ...existingSession ? { sessionId: existingSession } : {}
1001
- }).then((sessionId) => {
1002
- comment.aiStatus = "running";
1003
- comment.aiSessionId = sessionId;
1004
- comment.updatedAt = Date.now();
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
- });
1015
- }, (error) => this.markAiFailure(record.id, comment.id, error instanceof Error ? error.message : String(error)));
1016
- }
1696
+ return {
1697
+ requirementId: record.id,
1698
+ task: {
1699
+ kind: "comment",
1700
+ id: comment.id
1701
+ }
1702
+ };
1017
1703
  } else if (action.kind === "comment.reply") {
1018
- requireHuman(action.participant);
1019
1704
  const comment = this.comment(record, action.commentId);
1020
1705
  const body = action.body.trim();
1021
1706
  if (body === "") throw new Error("reply is required");
@@ -1030,9 +1715,7 @@ var CollaborationEngine = class {
1030
1715
  comment.updatedAt = now;
1031
1716
  if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, "reply", record, "comment", comment.id, `${action.participant.nickname} 回复了你的评论`);
1032
1717
  for (const participantId of mentions) this.notify(participantId, "mention", record, "comment", comment.id, `${action.participant.nickname} 在回复中提到了你`);
1033
- this.persist();
1034
1718
  } else if (action.kind === "comment.resolve") {
1035
- requireHuman(action.participant);
1036
1719
  const comment = this.comment(record, action.commentId);
1037
1720
  comment.status = "resolved";
1038
1721
  comment.resolution = action.resolution;
@@ -1042,9 +1725,7 @@ var CollaborationEngine = class {
1042
1725
  task.status = "handled";
1043
1726
  task.updatedAt = now;
1044
1727
  });
1045
- this.persist();
1046
1728
  } else if (action.kind === "comment.reopen") {
1047
- requireHuman(action.participant);
1048
1729
  const comment = this.comment(record, action.commentId);
1049
1730
  if (comment.status !== "resolved") throw new Error("resolved comment not found");
1050
1731
  comment.status = "open";
@@ -1064,50 +1745,12 @@ var CollaborationEngine = class {
1064
1745
  updatedAt: now
1065
1746
  });
1066
1747
  if (comment.author.participantId !== action.participant.participantId) this.notify(comment.author.participantId, "status-change", record, "comment", comment.id, `${action.participant.nickname} 重新打开了你的评论`);
1067
- this.persist();
1068
- } else if (action.kind === "patch.accept") {
1069
- requireHuman(action.participant);
1070
- const patch = record.patches.find((item) => item.id === action.patchId);
1071
- if (patch === void 0 || patch.status !== "pending") throw new Error("pending patch not found");
1072
- const version = this.versions.save({
1073
- requirementId: record.id,
1074
- baseCommit: patch.baseCommit,
1075
- markdown: patch.proposedMarkdown,
1076
- participant: action.participant,
1077
- summary: action.summary
1078
- });
1079
- const before = this.versions.read(record.id, record.currentCommit).markdown;
1080
- const impact = changedScopes(before, patch.proposedMarkdown);
1081
- record.currentCommit = version.commit;
1082
- patch.status = "accepted";
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");
1089
- for (const id of patch.affectedReviewItemIds) {
1090
- const item = record.reviewItems.find((candidate) => candidate.id === id);
1091
- if (item !== void 0) {
1092
- item.status = "resolved";
1093
- item.updatedAt = now;
1094
- }
1095
- }
1096
- invalidateAffected(record, impact.sections, impact.acceptanceIds, patch.proposedMarkdown);
1097
- record.actionItems.filter((task) => task.sourceId === patch.id && task.status === "pending").forEach((task) => {
1098
- task.status = "handled";
1099
- task.updatedAt = now;
1100
- });
1101
- this.persist(void 0, true);
1102
- this.enqueueReview(record, action.participant, "change-review");
1103
1748
  } else if (action.kind === "patch.reject") {
1104
- requireHuman(action.participant);
1105
- const patch = record.patches.find((item) => item.id === action.patchId);
1106
- if (patch === void 0) throw new Error("patch not found");
1749
+ const patch = record.patches.find((item) => item.id === action.patchId && item.status === "pending");
1750
+ if (patch === void 0) throw new Error("pending patch not found");
1107
1751
  patch.status = "rejected";
1108
- this.persist();
1752
+ retireActionItems(record, "patch", patch.id, "handled", now);
1109
1753
  } else if (action.kind === "decision.create") {
1110
- requireHuman(action.participant);
1111
1754
  const sourceAnchors = [...action.sourceAnchors ?? [], ...decisionScopeAnchors(this.versions.read(record.id, record.currentCommit).markdown, action.affectedSections, action.affectedAcceptanceIds)].filter((anchor, index, anchors) => anchor.quote.trim() !== "" && anchors.findIndex((candidate) => normalizeAnchorText(candidate.quote) === normalizeAnchorText(anchor.quote) && normalizeAnchorText(candidate.heading ?? "") === normalizeAnchorText(anchor.heading ?? "")) === index);
1112
1755
  record.decisions.push({
1113
1756
  id: randomUUID(),
@@ -1124,9 +1767,7 @@ var CollaborationEngine = class {
1124
1767
  createdAt: now,
1125
1768
  status: "active"
1126
1769
  });
1127
- this.persist();
1128
1770
  } else if (action.kind === "confirmation.create") {
1129
- requireHuman(action.participant);
1130
1771
  if (action.participant.role !== action.role) throw new Error(`${action.role} role is required`);
1131
1772
  record.confirmations.push({
1132
1773
  id: randomUUID(),
@@ -1141,16 +1782,12 @@ var CollaborationEngine = class {
1141
1782
  });
1142
1783
  if (action.role === "product" && action.scope === "version") record.productConfirmedCommit = record.currentCommit;
1143
1784
  if (action.role === "engineering" && action.scope === "version") record.jointConfirmedCommit = record.currentCommit;
1144
- this.persist();
1145
- } else if (action.kind === "stage.advance") {
1146
- requireHuman(action.participant);
1147
- advance(record, action.participant);
1148
- this.persist();
1149
- } else if (action.kind === "ready.generate") {
1150
- requireHuman(action.participant);
1151
- const admission = readyAdmission(record, readiness(this.versions.read(record.id, record.currentCommit).markdown, record));
1785
+ } else if (action.kind === "stage.advance") advance(record, action.participant);
1786
+ else if (action.kind === "ready.generate") {
1787
+ const body = this.versions.read(record.id, record.currentCommit).markdown;
1788
+ const admission = readyAdmission(record, readiness(body, record));
1152
1789
  if (admission.error) throw new Error(admission.error);
1153
- const markdown = readyMarkdown(this.view(record.id));
1790
+ const markdown = readyMarkdown(record, body);
1154
1791
  record.readyPackage = {
1155
1792
  requirementId: record.id,
1156
1793
  commit: record.currentCommit,
@@ -1160,17 +1797,13 @@ var CollaborationEngine = class {
1160
1797
  markdown
1161
1798
  };
1162
1799
  enterStage(record, "ready");
1163
- this.persist();
1164
1800
  } else if (action.kind === "participant.register") {
1165
- requireHuman(action.participant);
1166
1801
  const participant = this.state.participants.find((item) => item.participantId === action.participant.participantId);
1167
1802
  if (participant !== void 0) {
1168
1803
  participant.nickname = action.participant.nickname;
1169
1804
  participant.role = action.participant.role;
1170
- this.persist();
1171
1805
  }
1172
1806
  } else if (action.kind === "action.assign") {
1173
- requireHuman(action.participant);
1174
1807
  const task = record.actionItems.find((item) => item.id === action.actionItemId);
1175
1808
  if (task === void 0) throw new Error("action item not found");
1176
1809
  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");
@@ -1182,137 +1815,13 @@ var CollaborationEngine = class {
1182
1815
  this.notify(action.assigneeParticipantId, "assignment", record, "action", task.id, `${action.participant.nickname} 向你指派了一个待办`);
1183
1816
  }
1184
1817
  task.updatedAt = now;
1185
- this.persist();
1186
1818
  } else if (action.kind === "notification.mark-read") {
1187
- requireHuman(action.participant);
1188
1819
  const ids = new Set(action.notificationIds);
1189
1820
  this.state.notifications.filter((item) => item.recipientParticipantId === action.participant.participantId && item.requirementId === record.id && ids.has(item.id)).forEach((item) => {
1190
1821
  item.readAt ??= now;
1191
1822
  });
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
- }
1313
- this.persist();
1314
- } else if (action.kind === "downstream.return") {
1315
- requireHuman(action.participant);
1823
+ } else if (isInsightAction(action)) applyInsightAction(this.state, action, now);
1824
+ else if (action.kind === "downstream.return") {
1316
1825
  if (action.summary.trim() === "") throw new Error("downstream issue summary is required");
1317
1826
  if (action.affectedSections.length === 0 && action.affectedAcceptanceIds.length === 0) throw new Error("downstream return requires an affected section or AC");
1318
1827
  const item = {
@@ -1340,56 +1849,71 @@ var CollaborationEngine = class {
1340
1849
  delete record.readyPackage;
1341
1850
  enterStage(record, "joint-review");
1342
1851
  record.updatedAt = now;
1343
- this.persist();
1344
- this.enqueueReview(record, action.participant, "change-review");
1852
+ return {
1853
+ requirementId: record.id,
1854
+ task: this.queueReview(record, action.participant, "change-review", now)
1855
+ };
1856
+ }
1857
+ return { requirementId: record.id };
1858
+ }
1859
+ changeVersion(record, action, now) {
1860
+ const before = this.versions.read(record.id, record.currentCommit).markdown;
1861
+ let baseCommit = record.currentCommit;
1862
+ let markdown;
1863
+ let summary;
1864
+ let acceptedPatch;
1865
+ if (action.kind === "requirement.rename") {
1866
+ const title = action.title.trim();
1867
+ if (title === "" || title.length > 120 || /[\r\n]/.test(title)) throw new Error("valid requirement title is required");
1868
+ if (title === record.title) return {
1869
+ requirementId: record.id,
1870
+ unchanged: true
1871
+ };
1872
+ markdown = /^# .+$/m.test(before) ? before.replace(/^# .+$/m, () => `# ${title}`) : `# ${title}\n\n${before}`;
1873
+ summary = `Rename requirement: ${title}`;
1874
+ record.title = title;
1875
+ } else if (action.kind === "version.restore") {
1876
+ const historical = this.version(record.id, action.commit);
1877
+ if (historical.commit === record.currentCommit) throw new Error("selected version is already current");
1878
+ markdown = historical.markdown;
1879
+ summary = action.summary.trim() || `恢复版本 ${historical.commit.slice(0, 8)}`;
1880
+ } else if (action.kind === "patch.accept") {
1881
+ acceptedPatch = record.patches.find((item) => item.id === action.patchId && item.status === "pending");
1882
+ if (acceptedPatch === void 0) throw new Error("pending patch not found");
1883
+ baseCommit = acceptedPatch.baseCommit;
1884
+ markdown = acceptedPatch.proposedMarkdown;
1885
+ summary = action.summary;
1886
+ } else {
1887
+ baseCommit = action.baseCommit;
1888
+ markdown = action.markdown;
1889
+ summary = action.summary;
1890
+ }
1891
+ const spec = this.versions.prepareSave({
1892
+ requirementId: record.id,
1893
+ baseCommit,
1894
+ markdown,
1895
+ participant: action.participant,
1896
+ summary
1897
+ });
1898
+ if (acceptedPatch) {
1899
+ acceptedPatch.status = "accepted";
1900
+ retireActionItems(record, "patch", acceptedPatch.id, "handled", now);
1901
+ for (const item of record.reviewItems.filter((item) => acceptedPatch.affectedReviewItemIds.includes(item.id))) {
1902
+ item.status = "resolved";
1903
+ item.updatedAt = now;
1904
+ retireActionItems(record, "review-item", item.id, "handled", now);
1905
+ }
1345
1906
  }
1907
+ versionChanged(record, before, {
1908
+ commit: spec.commit,
1909
+ markdown
1910
+ }, now);
1346
1911
  return {
1347
- ok: true,
1348
- revision: this.state.revision,
1349
- requirement: this.view(record.id)
1912
+ requirementId: record.id,
1913
+ spec,
1914
+ task: this.queueReview(record, action.participant, "change-review", now)
1350
1915
  };
1351
1916
  }
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
1917
  rememberStageConversation(record, sessionId, stage = record.stage, stageCycle = record.stageCycle) {
1394
1918
  const now = Date.now();
1395
1919
  const existing = record.aiConversations.find((item) => item.stage === stage && item.stageCycle === stageCycle);
@@ -1419,23 +1943,25 @@ var CollaborationEngine = class {
1419
1943
  createdAt: Date.now()
1420
1944
  });
1421
1945
  }
1422
- saveConflict(action) {
1423
- const record = this.record(action.requirementId);
1424
- const baseMarkdown = this.versions.read(record.id, action.baseCommit).markdown;
1425
- const currentMarkdown = this.versions.read(record.id, record.currentCommit).markdown;
1426
- return {
1427
- requirementId: record.id,
1428
- baseCommit: action.baseCommit,
1429
- currentCommit: record.currentCommit,
1430
- baseMarkdown,
1431
- currentMarkdown,
1432
- draftMarkdown: action.markdown,
1433
- baseToCurrentDiff: textDiff(baseMarkdown, currentMarkdown),
1434
- baseToDraftDiff: textDiff(baseMarkdown, action.markdown)
1435
- };
1946
+ saveConflict(action, currentCommit) {
1947
+ try {
1948
+ const baseMarkdown = this.versions.read(action.requirementId, action.baseCommit).markdown;
1949
+ const currentMarkdown = this.versions.read(action.requirementId, currentCommit).markdown;
1950
+ return {
1951
+ requirementId: action.requirementId,
1952
+ baseCommit: action.baseCommit,
1953
+ currentCommit,
1954
+ baseMarkdown,
1955
+ currentMarkdown,
1956
+ draftMarkdown: action.markdown,
1957
+ baseToCurrentDiff: textDiff(baseMarkdown, currentMarkdown),
1958
+ baseToDraftDiff: textDiff(baseMarkdown, action.markdown)
1959
+ };
1960
+ } catch {
1961
+ return;
1962
+ }
1436
1963
  }
1437
- enqueueReview(record, participant, kind) {
1438
- const now = Date.now();
1964
+ queueReview(record, participant, kind, now) {
1439
1965
  const run = {
1440
1966
  id: randomUUID(),
1441
1967
  requirementId: record.id,
@@ -1446,405 +1972,156 @@ var CollaborationEngine = class {
1446
1972
  createdAt: now,
1447
1973
  updatedAt: now
1448
1974
  };
1975
+ if (!this.coordinator) {
1976
+ run.status = "failed";
1977
+ run.error = "AI coordinator unavailable";
1978
+ }
1449
1979
  record.aiRuns.push(run);
1450
- this.persist({
1451
- types: ["ai.status", "metrics.changed"],
1452
- requirementId: record.id,
1453
- objectId: run.id
1454
- });
1980
+ return {
1981
+ kind: "review",
1982
+ id: run.id
1983
+ };
1984
+ }
1985
+ launchAiTask(view, task) {
1455
1986
  const coordinator = this.coordinator;
1456
- if (coordinator === void 0) {
1457
- this.markAiFailure(record.id, run.id, "AI coordinator unavailable");
1458
- return;
1459
- }
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;
1464
- coordinator.requestReview({
1987
+ if (coordinator === void 0) return;
1988
+ const session = view.aiConversations.find((item) => item.stage === view.stage && item.stageCycle === view.stageCycle);
1989
+ const context = {
1465
1990
  requirement: view,
1466
- run,
1467
- ...existingSession ? { sessionId: existingSession } : {}
1468
- }).then((sessionId) => {
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
- });
1481
- }, (error) => this.markAiFailure(record.id, run.id, error instanceof Error ? error.message : String(error)));
1482
- }
1483
- record(id) {
1484
- const value = this.state.requirements.find((item) => item.id === id);
1485
- if (value === void 0) throw new Error("requirement not found");
1486
- return value;
1487
- }
1488
- comment(record, id) {
1489
- const value = record.comments.find((item) => item.id === id);
1490
- if (value === void 0) throw new Error("comment not found");
1491
- return value;
1492
- }
1493
- persist(event = this.eventContext ?? { types: ["metrics.changed"] }, recoverable = false) {
1494
- this.state.revision += 1;
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
1991
+ ...session ? { sessionId: session.sessionId } : {}
1503
1992
  };
1504
- for (const listener of this.listeners) listener(payload);
1505
- }
1506
- load() {
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)}`);
1518
- }
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;
1993
+ let pending;
1523
1994
  try {
1524
- parsed = JSON.parse(readFileSync(sourcePath, "utf8"));
1995
+ pending = task.kind === "review" ? coordinator.requestReview({
1996
+ ...context,
1997
+ run: view.aiRuns.find((item) => item.id === task.id)
1998
+ }) : coordinator.requestCommentReply({
1999
+ ...context,
2000
+ comment: view.comments.find((item) => item.id === task.id)
2001
+ });
1525
2002
  } catch (error) {
1526
- throw new Error(`collaboration ledger is corrupted: ${error instanceof Error ? error.message : String(error)}`);
2003
+ pending = Promise.reject(error);
1527
2004
  }
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;
1542
- }
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");
2005
+ pending.then((sessionId) => this.recordAiSession(view, task, sessionId), (error) => this.markAiFailure(view.id, task.id, errorMessage$1(error))).catch((error) => console.error("spec-collab: could not persist AI task update", error));
2006
+ }
2007
+ recordAiSession(view, task, sessionId) {
2008
+ this.changeAi(() => {
2009
+ const record = this.state.requirements.find((item) => item.id === view.id);
2010
+ if (record === void 0) return;
2011
+ const now = Date.now();
2012
+ if (task.kind === "review") {
2013
+ const run = record.aiRuns.find((item) => item.id === task.id);
2014
+ if (run === void 0) return;
2015
+ if (run.status === "queued") run.status = "running";
2016
+ run.sessionId = sessionId;
2017
+ run.updatedAt = now;
2018
+ } else {
2019
+ const comment = record.comments.find((item) => item.id === task.id);
2020
+ if (comment === void 0) return;
2021
+ if (comment.aiStatus === "queued") comment.aiStatus = "running";
2022
+ comment.aiSessionId = sessionId;
2023
+ comment.updatedAt = now;
2024
+ }
2025
+ this.rememberStageConversation(record, sessionId, view.stage, view.stageCycle);
2026
+ return aiEvent(record.id, task.id, task.kind === "comment");
2027
+ });
1555
2028
  }
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");
2029
+ changeAi(update) {
2030
+ const committed = this.transact(() => ({
2031
+ value: void 0,
2032
+ event: update()
2033
+ }));
2034
+ this.emit(committed.event);
1599
2035
  }
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");
2036
+ transact(update) {
2037
+ const before = this.state;
2038
+ this.state = structuredClone(before);
1610
2039
  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 ??= [];
2040
+ const { value, event, spec } = update();
2041
+ if (event === void 0) {
2042
+ this.state = before;
2043
+ return { value };
2044
+ }
2045
+ const revision = before.revision + 1;
2046
+ this.state.revision = revision;
2047
+ this.ledger.save(this.state, spec);
2048
+ return {
2049
+ value,
2050
+ event: {
2051
+ ...event,
2052
+ revision
2053
+ }
2054
+ };
2055
+ } catch (error) {
2056
+ this.state = before;
2057
+ throw error;
1660
2058
  }
1661
2059
  }
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
- });
2060
+ emit(event) {
2061
+ if (event === void 0) return;
2062
+ for (const listener of this.listeners) try {
2063
+ listener(event);
2064
+ } catch {
2065
+ this.listeners.delete(listener);
1728
2066
  }
1729
2067
  }
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;
2068
+ record(id) {
2069
+ const value = this.state.requirements.find((item) => item.id === id);
2070
+ if (value === void 0) throw new Error("requirement not found");
2071
+ return value;
1750
2072
  }
2073
+ comment(record, id) {
2074
+ const value = record.comments.find((item) => item.id === id);
2075
+ if (value === void 0) throw new Error("comment not found");
2076
+ return value;
2077
+ }
2078
+ };
2079
+ function errorMessage$1(error) {
2080
+ return error instanceof Error ? error.message : String(error);
1751
2081
  }
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");
2082
+ function aiEvent(requirementId, objectId, comment = false) {
2083
+ return {
2084
+ requirementId,
2085
+ objectId,
2086
+ types: comment ? [
2087
+ "ai.status",
2088
+ "comment.changed",
2089
+ "metrics.changed"
2090
+ ] : ["ai.status", "metrics.changed"]
2091
+ };
1791
2092
  }
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");
2093
+ function eventForAction(action, change) {
2094
+ const types = /* @__PURE__ */ new Set(["metrics.changed"]);
2095
+ if (action.kind.startsWith("comment.")) types.add("comment.changed");
2096
+ if (action.kind === "comment.create" || action.kind === "comment.reply") {
2097
+ if ((action.mentions?.length ?? 0) > 0) types.add("mention.created");
2098
+ types.add("notification.changed");
2099
+ }
2100
+ if (action.kind === "comment.resolve" || action.kind === "comment.reopen") types.add("notification.changed");
2101
+ if (action.kind === "action.assign") {
2102
+ types.add("assignment.changed");
2103
+ types.add("notification.changed");
2104
+ }
2105
+ if (action.kind === "notification.mark-read") types.add("notification.changed");
2106
+ if (change.task) types.add("ai.status");
2107
+ return {
2108
+ types: [...types],
2109
+ requirementId: change.requirementId,
2110
+ ...change.task ? { objectId: change.task.id } : {}
2111
+ };
1795
2112
  }
1796
2113
  function validMentions(values, participants) {
1797
2114
  const registered = new Set(participants.map((item) => item.participantId));
1798
2115
  return [...new Set(values ?? [])].filter((value) => registered.has(value));
1799
2116
  }
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
2117
  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
2118
  return {
1838
2119
  openReviewCount: record.reviewItems.filter((item) => item.commit === record.currentCommit && !["resolved", "invalidated"].includes(item.status)).length,
1839
2120
  openCommentCount: record.comments.filter((item) => item.commit === record.currentCommit && item.status === "open").length,
1840
2121
  pendingActionCount: record.actionItems.filter((item) => item.status === "pending").length,
1841
2122
  activeDecisionCount: record.decisions.filter((item) => item.status === "active").length,
1842
2123
  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
2124
+ ...insightMetrics(state, record.id)
1848
2125
  };
1849
2126
  }
1850
2127
  function requirementParticipantIds(record, history) {
@@ -1935,203 +2212,6 @@ function actionForReview(item) {
1935
2212
  updatedAt: now
1936
2213
  };
1937
2214
  }
1938
- function enterStage(record, stage) {
1939
- if (record.stage === stage) return;
1940
- record.stage = stage;
1941
- record.stageCycle += 1;
1942
- }
1943
- function advance(record, participant) {
1944
- if (record.stage === "product-review") {
1945
- if (record.reviewItems.some((item) => item.commit === record.currentCommit && item.severity === "blocking" && ![
1946
- "resolved",
1947
- "non-blocking-verify",
1948
- "joint-review"
1949
- ].includes(item.status))) throw new Error("product blocking review items remain");
1950
- if (!hasCompletedCurrentReview(record, "product-second")) throw new Error("product second review is required");
1951
- enterStage(record, "product-confirmation");
1952
- return;
1953
- }
1954
- if (record.stage === "product-confirmation") {
1955
- if (participant.role !== "product" || !hasVersionConfirmation(record, "product")) throw new Error("product must confirm the current version");
1956
- enterStage(record, "joint-review");
1957
- return;
1958
- }
1959
- throw new Error("stage cannot advance directly");
1960
- }
1961
- function sections(markdown) {
1962
- const result = /* @__PURE__ */ new Map();
1963
- let heading = "";
1964
- for (const line of markdown.split("\n")) if (/^##\s+/.test(line)) {
1965
- heading = line.replace(/^##\s+/, "").trim();
1966
- result.set(heading, "");
1967
- } else if (heading) result.set(heading, `${result.get(heading) ?? ""}\n${line}`);
1968
- return result;
1969
- }
1970
- function acceptance(markdown) {
1971
- const result = /* @__PURE__ */ new Map();
1972
- for (const match of markdown.matchAll(/\*\*(AC-[A-Za-z0-9-]+)(?:\s+[^*]+)?\*\*\s*[::]\s*(.+)/g)) result.set(match[1], match[2].trim());
1973
- return result;
1974
- }
1975
- function changedScopes(before, after) {
1976
- const a = sections(before);
1977
- const b = sections(after);
1978
- const sectionNames = /* @__PURE__ */ new Set([...a.keys(), ...b.keys()]);
1979
- const acA = acceptance(before);
1980
- const acB = acceptance(after);
1981
- const acNames = /* @__PURE__ */ new Set([...acA.keys(), ...acB.keys()]);
1982
- return {
1983
- sections: [...sectionNames].filter((key) => a.get(key) !== b.get(key)),
1984
- acceptanceIds: [...acNames].filter((key) => acA.get(key) !== acB.get(key))
1985
- };
1986
- }
1987
- function intersects(left, right) {
1988
- return left.some((item) => right.includes(item));
1989
- }
1990
- function normalizeAnchorText(value) {
1991
- return value.replace(/[`*_>#\[\]()~-]/g, "").replace(/\s+/g, "").toLocaleLowerCase();
1992
- }
1993
- function headingForLine(lines, index) {
1994
- for (let cursor = index; cursor >= 0; cursor -= 1) {
1995
- const match = /^#{1,4}\s+(.+)$/.exec(lines[cursor] ?? "");
1996
- if (match?.[1]) return match[1].trim();
1997
- }
1998
- }
1999
- function decisionScopeAnchors(markdown, affectedSections, affectedAcceptanceIds) {
2000
- const anchors = [];
2001
- const sectionMap = sections(markdown);
2002
- for (const section of affectedSections.map((value) => value.trim()).filter(Boolean)) {
2003
- const quote = sectionMap.get(section)?.split("\n").map((line) => line.trim()).find((line) => line && !/^#+\s+/.test(line));
2004
- if (quote) anchors.push({
2005
- heading: section,
2006
- quote
2007
- });
2008
- }
2009
- const lines = markdown.split("\n");
2010
- for (const acceptanceId of affectedAcceptanceIds.map((value) => value.trim()).filter(Boolean)) {
2011
- const index = lines.findIndex((line) => normalizeAnchorText(line).includes(normalizeAnchorText(acceptanceId)));
2012
- if (index >= 0) {
2013
- const heading = headingForLine(lines, index);
2014
- anchors.push({
2015
- ...heading ? { heading } : {},
2016
- quote: lines[index].trim()
2017
- });
2018
- }
2019
- }
2020
- return anchors;
2021
- }
2022
- function decisionAnchorStillExists(markdown, anchor) {
2023
- const quote = normalizeAnchorText(anchor.quote);
2024
- if (!quote) return false;
2025
- const sectionMap = sections(markdown);
2026
- const candidates = anchor.heading?.trim() ? [sectionMap.get(anchor.heading.trim()) ?? ""] : [markdown];
2027
- const context = normalizeAnchorText(`${anchor.prefix ?? ""}${anchor.quote}${anchor.suffix ?? ""}`);
2028
- return candidates.some((candidate) => {
2029
- const normalized = normalizeAnchorText(candidate);
2030
- return normalized.includes(context) || normalized.includes(quote);
2031
- });
2032
- }
2033
- function invalidateAffected(record, changedSections, changedAcceptanceIds, currentMarkdown) {
2034
- for (const confirmation of record.confirmations) {
2035
- if (confirmation.status !== "active") continue;
2036
- if (confirmation.scope === "version" || confirmation.scope === "section" && confirmation.scopeId !== void 0 && changedSections.includes(confirmation.scopeId) || confirmation.scope === "acceptance-criterion" && confirmation.scopeId !== void 0 && changedAcceptanceIds.includes(confirmation.scopeId)) {
2037
- confirmation.status = "invalidated";
2038
- record.actionItems.push({
2039
- id: randomUUID(),
2040
- requirementId: record.id,
2041
- sourceType: "confirmation",
2042
- sourceId: confirmation.id,
2043
- type: "reconfirm",
2044
- assigneeRole: confirmation.role,
2045
- blocking: true,
2046
- status: "pending",
2047
- dueStage: record.stage,
2048
- createdAt: Date.now(),
2049
- updatedAt: Date.now()
2050
- });
2051
- }
2052
- }
2053
- record.reviewItems.filter((item) => item.status === "resolved" && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach((item) => {
2054
- item.status = "invalidated";
2055
- item.updatedAt = Date.now();
2056
- });
2057
- record.decisions.filter((item) => item.status === "active" && (intersects(item.affectedSections, changedSections) || intersects(item.affectedAcceptanceIds, changedAcceptanceIds))).forEach((item) => {
2058
- item.status = "invalidated";
2059
- });
2060
- if (currentMarkdown !== void 0) record.decisions.filter((item) => item.status === "active" && item.sourceAnchors?.some((anchor) => !decisionAnchorStillExists(currentMarkdown, anchor))).forEach((item) => {
2061
- item.status = "invalidated";
2062
- });
2063
- }
2064
- function readiness(markdown, record) {
2065
- const sectionMap = sections(markdown);
2066
- const ac = acceptance(markdown);
2067
- const meaningful = (name) => {
2068
- const value = sectionMap.get(name)?.replace(/<!--.*?-->/gs, "").trim() ?? "";
2069
- return value.length >= 12 && !/待澄清|待补充|TODO/i.test(value);
2070
- };
2071
- const blockers = record.reviewItems.filter((item) => item.commit === record.currentCommit && item.severity === "blocking" && !["resolved", "non-blocking-verify"].includes(item.status)).map((item) => item.statement);
2072
- return [
2073
- {
2074
- key: "goal",
2075
- passed: meaningful("目标与用户结果"),
2076
- reasons: meaningful("目标与用户结果") ? [] : ["缺少可观察的目标与用户结果"]
2077
- },
2078
- {
2079
- key: "acceptance",
2080
- passed: ac.size > 0 && [...ac.values()].every((value) => !/待澄清|待补充|TODO/i.test(value)),
2081
- reasons: ac.size === 0 ? ["缺少稳定 AC ID 与可判定结果"] : [...ac.values()].some((value) => /待澄清|待补充|TODO/i.test(value)) ? ["验收标准仍含占位内容"] : []
2082
- },
2083
- {
2084
- key: "scope",
2085
- passed: meaningful("范围与非范围"),
2086
- reasons: meaningful("范围与非范围") ? [] : ["范围与非范围不完整"]
2087
- },
2088
- {
2089
- key: "semantics",
2090
- passed: meaningful("业务术语与规则"),
2091
- reasons: meaningful("业务术语与规则") ? [] : ["关键术语和规则不完整"]
2092
- },
2093
- {
2094
- key: "evidence",
2095
- passed: record.sources.every((source) => source.accessStatus !== "missing") && blockers.length === 0,
2096
- reasons: [...record.sources.filter((source) => source.accessStatus === "missing").map((source) => `来源不可访问:${source.label}`), ...blockers]
2097
- },
2098
- {
2099
- key: "test-constraints",
2100
- passed: meaningful("测试约束"),
2101
- reasons: meaningful("测试约束") ? [] : ["测试环境、账号、权限或 fixture 约束不完整"]
2102
- }
2103
- ];
2104
- }
2105
- function readyMarkdown(view) {
2106
- const open = view.reviewItems.filter((item) => item.status === "non-blocking-verify");
2107
- const sourceStatus = {
2108
- available: "可查阅",
2109
- unverified: "待核对",
2110
- missing: "待补充"
2111
- };
2112
- return [
2113
- `# 就绪需求:${view.title}`,
2114
- "",
2115
- "## 版本信息",
2116
- "",
2117
- `- 需求编号:${view.id}`,
2118
- `- 文档版本:${view.currentCommit}`,
2119
- `- 产品确认:${view.confirmations.filter((item) => item.role === "product" && item.status === "active").map((item) => item.participant.nickname).join("、")}`,
2120
- `- 研发确认:${view.confirmations.filter((item) => item.role === "engineering" && item.status === "active").map((item) => item.participant.nickname).join("、")}`,
2121
- "",
2122
- view.version.markdown,
2123
- "",
2124
- "## 已确认决策",
2125
- ...view.decisions.filter((item) => item.status === "active").map((item) => `- ${item.question}:${item.decision}(原因:${item.rationale})`),
2126
- "",
2127
- "## 参考资料",
2128
- ...view.sources.map((source) => `- [${sourceStatus[source.accessStatus]}] ${source.label}${source.stableId ? `:${source.stableId}` : ""}${source.version ? `(版本:${source.version})` : ""}`),
2129
- "",
2130
- "## 待确认问题",
2131
- ...open.map((item) => `- ${item.question};负责人:${item.ownerParticipantId ?? (item.ownerRole === "product" ? "产品" : "研发")};影响:${item.impact}`),
2132
- ""
2133
- ].join("\n");
2134
- }
2135
2215
  //#endregion
2136
2216
  //#region src/prompts.ts
2137
2217
  const DEFAULT_REVIEW_PROMPTS = {
@@ -2495,10 +2575,10 @@ var DshReviewCoordinator = class {
2495
2575
  });
2496
2576
  }
2497
2577
  async conversation(sessionId) {
2498
- const history = await this.host.sessionController.inspect(sessionId, this.lifetime.signal);
2578
+ const events = await this.conversationEvents(sessionId);
2499
2579
  const rows = [];
2500
2580
  let skippedOrchestrationPrompt = false;
2501
- for (const entry of history.events) {
2581
+ for (const entry of events) {
2502
2582
  if (entry.type !== "user/message" && entry.type !== "assistant/message") continue;
2503
2583
  if (entry.type === "user/message" && !skippedOrchestrationPrompt) {
2504
2584
  skippedOrchestrationPrompt = true;
@@ -2519,6 +2599,34 @@ var DshReviewCoordinator = class {
2519
2599
  }
2520
2600
  return rows;
2521
2601
  }
2602
+ async conversationEvents(sessionId) {
2603
+ const controller = this.host.sessionController;
2604
+ if (controller.events !== void 0) {
2605
+ const pages = [];
2606
+ let throughSeq;
2607
+ let beforeSeq;
2608
+ for (;;) {
2609
+ this.lifetime.signal.throwIfAborted();
2610
+ const page = await controller.events({
2611
+ address: {
2612
+ kind: "session",
2613
+ sessionId
2614
+ },
2615
+ maxMessages: 100,
2616
+ ...throughSeq === void 0 ? {} : { throughSeq },
2617
+ ...beforeSeq === void 0 ? {} : { beforeSeq }
2618
+ }, this.lifetime.signal);
2619
+ throughSeq ??= page.cursor;
2620
+ pages.push(page.records.map((record) => record.event));
2621
+ if (!page.hasMore) return pages.reverse().flat();
2622
+ const firstSeq = page.records[0]?.event.seq;
2623
+ if (firstSeq === void 0 || !Number.isSafeInteger(firstSeq) || firstSeq < 0 || beforeSeq !== void 0 && firstSeq >= beforeSeq) throw new Error("history pagination did not advance");
2624
+ beforeSeq = firstSeq;
2625
+ }
2626
+ }
2627
+ if (controller.inspect !== void 0) return (await controller.inspect(sessionId, this.lifetime.signal)).events;
2628
+ throw new Error("DSH Session history API is unavailable");
2629
+ }
2522
2630
  async followUp(sessionId, text) {
2523
2631
  const content = text.trim();
2524
2632
  if (content === "") throw new Error("追问内容不能为空");
@@ -2738,17 +2846,14 @@ function makeRoutes(engine, coordinator) {
2738
2846
  error: "method-not-allowed"
2739
2847
  });
2740
2848
  if (!guard(req, res)) return;
2741
- const state = engine.snapshot();
2742
- const summaries = engine.summaries();
2743
- 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;
2849
+ const overview = engine.overview();
2850
+ const currentId = new URL(req.url ?? "", `http://${req.headers.host ?? "127.0.0.1"}`).searchParams.get("requirementId") ?? overview.requirements.find((item) => item.archivedAt === void 0)?.id ?? overview.requirements[0]?.id;
2744
2851
  let requirement;
2745
2852
  try {
2746
2853
  requirement = currentId ? engine.view(currentId) : void 0;
2747
2854
  } catch {}
2748
2855
  json(res, 200, {
2749
- revision: state.revision,
2750
- participants: state.participants,
2751
- requirements: summaries,
2856
+ ...overview,
2752
2857
  ...requirement ? { requirement } : {}
2753
2858
  });
2754
2859
  }
@@ -3042,7 +3147,7 @@ function makeRoutes(engine, coordinator) {
3042
3147
  res.once("close", close);
3043
3148
  push({
3044
3149
  types: ["state.synced"],
3045
- revision: engine.snapshot().revision
3150
+ revision: engine.revision
3046
3151
  });
3047
3152
  }
3048
3153
  }