ai-release-notes 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.
@@ -9,9 +9,10 @@
9
9
  * already made to it is lost.
10
10
  *
11
11
  * A session reads the notes an environment holds, keeps them in hand, and
12
- * applies one request at a time to all of them. Nothing reaches the disk until
13
- * it is saved, so a request that reads badly is undone rather than repaired,
14
- * and a run of requests is reviewed once, together.
12
+ * plans each request against the relevant subset. It can answer without
13
+ * changing anything, revise existing contents, or stage a structural merge.
14
+ * Nothing reaches disk until it is saved, so a request that reads badly is
15
+ * undone rather than repaired, and a run of requests is reviewed together.
15
16
  */
16
17
  Object.defineProperty(exports, "__esModule", { value: true });
17
18
  exports.PromptSession = exports.SESSION_ACTIONS = exports.PromptError = void 0;
@@ -25,6 +26,7 @@ const generator_js_1 = require("./generator.js");
25
26
  const llm_js_1 = require("./llm.js");
26
27
  const output_path_js_1 = require("./output-path.js");
27
28
  const builder_js_1 = require("./prompts/builder.js");
29
+ const output_index_js_1 = require("./output-index.js");
28
30
  const promote_js_1 = require("./promote.js");
29
31
  const release_document_js_1 = require("./release-document.js");
30
32
  const release_js_1 = require("./release.js");
@@ -38,6 +40,8 @@ exports.PromptError = PromptError;
38
40
  /** What someone at the desk can be asking for. */
39
41
  exports.SESSION_ACTIONS = [
40
42
  "revise",
43
+ "answer",
44
+ "merge",
41
45
  "dedupe",
42
46
  "undo",
43
47
  "reset",
@@ -50,8 +54,17 @@ const SessionActionSchema = zod_1.z.object({
50
54
  action: zod_1.z.enum(exports.SESSION_ACTIONS),
51
55
  instruction: zod_1.z.string().optional(),
52
56
  reply: zod_1.z.string().optional(),
57
+ scope: zod_1.z.object({
58
+ fromVersion: zod_1.z.string().optional(),
59
+ toVersion: zod_1.z.string().optional(),
60
+ languages: zod_1.z.array(zod_1.z.string()).optional(),
61
+ kinds: zod_1.z.array(zod_1.z.enum(["release", "index"])).optional(),
62
+ }).optional(),
63
+ answerFrom: zod_1.z.enum(["catalog", "notes", "both"]).optional(),
53
64
  });
54
65
  const UNREADABLE_PAGE = "its release note cannot be told apart from the page around it — revise the Markdown output instead";
66
+ const UNREADABLE_INDEX = "its list of releases cannot be found on the page — check that the outputIndex template still carries the releases marker";
67
+ const ALTERED_MARKERS = "the answer edited the markers that identify each listed release, so the file was left as it was";
55
68
  /**
56
69
  * The release notes of one environment, open for revision.
57
70
  *
@@ -65,6 +78,8 @@ class PromptSession {
65
78
  documents;
66
79
  callModel;
67
80
  history = [];
81
+ /** What was said last and what came of it, so "oui" has something to mean. */
82
+ lastExchange;
68
83
  constructor(config, environment, provider, documents, callModel) {
69
84
  this.config = config;
70
85
  this.environment = environment;
@@ -87,7 +102,10 @@ class PromptSession {
87
102
  const outputs = config.output
88
103
  ? (Array.isArray(config.output) ? config.output : [config.output])
89
104
  : [];
90
- if (outputs.length === 0) {
105
+ const outputIndexes = config.outputIndex
106
+ ? (Array.isArray(config.outputIndex) ? config.outputIndex : [config.outputIndex])
107
+ : [];
108
+ if (outputs.length === 0 && outputIndexes.length === 0) {
91
109
  throw new PromptError("Revising reuses the files a generation wrote, so it needs to know where they are. " +
92
110
  "Add an output with a saveTo path to your config.");
93
111
  }
@@ -104,10 +122,20 @@ class PromptSession {
104
122
  // Two configured outputs can name one file; it is opened once.
105
123
  if (documents.some((document) => document.path === found.path))
106
124
  continue;
107
- documents.push(await readDocument(found, output.format, template));
125
+ documents.push(await readDocument({ ...found, outputPattern: pattern }, output.format, template, "release"));
108
126
  }
109
127
  }
110
128
  }
129
+ // An index names no version, so the same rule that applies to any other
130
+ // versionless output applies to it: narrowing the session to a range
131
+ // leaves it out, since a range asks for one release's own note.
132
+ for (const outputIndex of outputIndexes) {
133
+ for (const found of await findFiles(outputIndex.saveTo, options, config)) {
134
+ if (documents.some((document) => document.path === found.path))
135
+ continue;
136
+ documents.push(await readDocument(found, outputIndex.format, undefined, "index"));
137
+ }
138
+ }
111
139
  if (documents.length === 0) {
112
140
  throw new PromptError(`No release notes found for ${options.environment}` +
113
141
  rangeDescription(options.fromVersion, options.toVersion) + ". " +
@@ -119,11 +147,11 @@ class PromptSession {
119
147
  }
120
148
  /** The files revised since the last save. */
121
149
  pending() {
122
- return this.documents.filter((document) => document.content !== document.saved);
150
+ return this.documents.filter((document) => document.created || document.removed || document.content !== document.saved);
123
151
  }
124
152
  /** Whether anything at all can be revised. */
125
153
  get revisable() {
126
- return this.documents.filter((document) => !document.unrevisable);
154
+ return this.documents.filter((document) => !document.removed && !document.unrevisable);
127
155
  }
128
156
  /**
129
157
  * Read what someone answered and say what they are asking for.
@@ -131,8 +159,13 @@ class PromptSession {
131
159
  * Everything is said in words — "drop the docker part", "actually put that
132
160
  * back", "that's it, write them" — so a model reads the answer rather than a
133
161
  * list of commands the person would have to learn first. It is given the
134
- * message and the state of the session; the release notes themselves never
135
- * reach it.
162
+ * message, the state of the session, and the exchange before it; the release
163
+ * notes themselves never reach it.
164
+ *
165
+ * The exchange before it is what makes a conversation one. "Oui" answers the
166
+ * question just asked and nothing else, so a desk that saw only the word
167
+ * would have to ask what was meant — and asking again is the one reply that
168
+ * gets nobody any further.
136
169
  *
137
170
  * An answer it cannot place is taken as a request to revise, which is what
138
171
  * nearly every answer is: a session is never blocked by its own front desk.
@@ -148,62 +181,234 @@ class PromptSession {
148
181
  user: (0, builder_js_1.buildSessionRouterUserPrompt)({
149
182
  message: said,
150
183
  environment: this.environment,
151
- openFiles: this.documents.length,
184
+ openFiles: this.activeDocuments().length,
152
185
  unsavedFiles: this.pending().length,
153
186
  canUndo: this.history.length > 0,
187
+ previous: this.lastExchange,
188
+ catalog: this.activeDocuments().map((document) => ({
189
+ kind: document.kind,
190
+ language: document.language,
191
+ fromVersion: document.fromVersion,
192
+ toVersion: document.toVersion,
193
+ dirty: document.created || document.content !== document.saved,
194
+ readable: !document.unrevisable,
195
+ })),
154
196
  }),
155
197
  });
156
- return readSessionAction(answer.text, said);
198
+ return this.remember(said, readSessionAction(answer.text, said));
157
199
  }
158
200
  catch {
159
- // The provider failing here would otherwise swallow the request. Revising
160
- // is what was almost certainly meant, and it reports its own failure.
161
- return { action: "revise", instruction: said, reply: "" };
201
+ // Planning failed, so no mutating action is guessed. A question must
202
+ // never turn into a broadcast revision because a provider was unavailable.
203
+ return this.remember(said, { action: "unclear", instruction: said, reply: "" });
204
+ }
205
+ }
206
+ /**
207
+ * Answer a question about the release notes this session has open.
208
+ *
209
+ * Someone with two dozen notes in front of them asks about them before
210
+ * asking for a change to them — which versions are here, whether one is
211
+ * missing between two others, what is still unsaved. None of that is a
212
+ * revision, and a session that could only revise had to turn every question
213
+ * into one, or ask what was meant until the question was given up on.
214
+ *
215
+ * Nothing here reaches a file: it reads what is open and says what it found.
216
+ */
217
+ async answer(question, scope, answerFrom = "both") {
218
+ const asked = question.trim();
219
+ if (!asked)
220
+ throw new PromptError("A question needs some words to answer.");
221
+ const startedAt = Date.now();
222
+ const usage = emptyUsage();
223
+ const quoted = this.notesForQuestion(asked, scope);
224
+ const chunks = answerFrom === "catalog"
225
+ ? [[]]
226
+ : chunkAnswerDocuments(quoted.included);
227
+ const findings = [];
228
+ const system = await (0, builder_js_1.buildSessionAnswerSystemPrompt)();
229
+ for (const included of chunks) {
230
+ const batch = {
231
+ included,
232
+ omitted: quoted.included.filter((document) => !included.includes(document)),
233
+ language: quoted.language,
234
+ };
235
+ const answered = await this.callModel({
236
+ system,
237
+ user: (0, builder_js_1.buildSessionAnswerUserPrompt)({
238
+ question: asked,
239
+ summary: this.describeOpenFiles(batch),
240
+ notes: included.map((document) => ({
241
+ covers: coverage(document),
242
+ language: document.language,
243
+ text: readableNote(noteOf(document) ?? "", document.format),
244
+ })),
245
+ projectName: this.config.projectName,
246
+ }),
247
+ });
248
+ addUsage(usage, answered.usage);
249
+ findings.push({
250
+ covers: included.map((document) => coverage(document)).join(", ") || "open-file catalog",
251
+ text: (0, generator_js_1.stripEnclosingCodeFence)(answered.text).trim(),
252
+ });
253
+ }
254
+ let text = findings[0]?.text ?? "";
255
+ if (findings.length > 1) {
256
+ const synthesized = await this.callModel({
257
+ system,
258
+ user: (0, builder_js_1.buildSessionAnswerSynthesisUserPrompt)({
259
+ question: asked,
260
+ findings,
261
+ projectName: this.config.projectName,
262
+ }),
263
+ });
264
+ addUsage(usage, synthesized.usage);
265
+ text = (0, generator_js_1.stripEnclosingCodeFence)(synthesized.text).trim();
266
+ }
267
+ usage.durationMs = Date.now() - startedAt;
268
+ return { text, usage };
269
+ }
270
+ /**
271
+ * The notes one question carries, and the ones it leaves behind.
272
+ *
273
+ * A question about what the releases brought is answered from the notes
274
+ * themselves, so they travel with it — but a session holds every release of
275
+ * an environment in every language it publishes, and a narrowly scoped
276
+ * request should not pay to carry unrelated pages.
277
+ *
278
+ * So three things narrow it, in order. One language: the others are the same
279
+ * releases translated, and an answer is written in the language it was asked
280
+ * in whichever it read. The versions the question names, when it names any.
281
+ * Then the newest of what is left, until the material is as much as one
282
+ * question may carry — and whatever did not fit is named in the summary, so
283
+ * an answer drawn from part of the shelf says so.
284
+ */
285
+ notesForQuestion(question, scope) {
286
+ const readable = this.activeDocuments().filter((document) => document.kind === "release" && noteOf(document) !== undefined);
287
+ const requestedLanguages = normalizedLanguages(scope?.languages);
288
+ const language = requestedLanguages[0] ?? this.preferredLanguage(readable);
289
+ const candidates = readable.filter((document) => (document.language ?? "") === language);
290
+ const versions = resolveMentionedVersions(question, candidates, scope);
291
+ const included = selectReleaseDocuments(candidates, versions).sort(compareCoverage);
292
+ return {
293
+ included,
294
+ omitted: candidates.filter((document) => !included.includes(document)),
295
+ language,
296
+ };
297
+ }
298
+ /** Which language's notes a question is answered from. */
299
+ preferredLanguage(documents) {
300
+ const open = new Set(documents.map((document) => document.language ?? ""));
301
+ if (open.size <= 1)
302
+ return [...open][0] ?? "";
303
+ const configured = (this.config.prompt?.languages ?? [])
304
+ .map((language) => (0, output_path_js_1.normalizeLanguage)(language))
305
+ .find((language) => open.has(language));
306
+ return configured ?? [...open][0];
307
+ }
308
+ /**
309
+ * What this session has open, as a question about it is answered from.
310
+ *
311
+ * Whether a release is missing between two others is a question about version
312
+ * numbers, and ordering those is something this can do exactly — so it does
313
+ * it here rather than leaving a model to work out whether `v1.8.2` comes
314
+ * before or after `v1.12.0`. What the model receives is the chain already
315
+ * ordered and every break in it already found; it reads that back in the
316
+ * language the question was asked in, and works nothing out for itself.
317
+ */
318
+ describeOpenFiles(quoted) {
319
+ const notes = this.activeDocuments().filter((document) => document.kind === "release");
320
+ const indexes = this.activeDocuments().filter((document) => document.kind === "index");
321
+ const lines = [
322
+ `Environment: ${this.environment}`,
323
+ `Release notes open: ${notes.length}`,
324
+ `Release indexes open: ${indexes.length}`,
325
+ `Holding changes that are not saved yet: ${this.pending().length}`,
326
+ ];
327
+ for (const [language, group] of byLanguage(notes)) {
328
+ lines.push("", `Releases with a note${language ? ` [${language}]` : ""}, oldest first:`);
329
+ lines.push(...describeReleaseChain(group));
330
+ }
331
+ for (const [language, group] of byLanguage(indexes)) {
332
+ lines.push("", `Release index${language ? ` [${language}]` : ""}, listing every release of the environment:`);
333
+ lines.push(...group.map((index) => ` ${(0, path_1.basename)(index.path)}`));
334
+ }
335
+ // Which notes are quoted is a fact about the answer, not about the shelf.
336
+ // An answer read off part of it is worth having and worth saying so, and
337
+ // the alternative — a model left to assume it holds everything listed —
338
+ // is an answer about releases nobody showed it.
339
+ if (quoted) {
340
+ const language = quoted.language ? ` [${quoted.language}]` : "";
341
+ lines.push("", `Quoted in full below${language}: ${quoted.included.map((document) => coverage(document)).join(", ") || "nothing"}`);
342
+ if (quoted.omitted.length > 0) {
343
+ lines.push(`Listed above but not quoted below, so nothing is known about what they say: ${quoted.omitted.map((document) => coverage(document)).join(", ")}`);
344
+ }
345
+ if (quoted.language) {
346
+ lines.push("The other languages hold these same releases, written in their own words.");
347
+ }
162
348
  }
349
+ return lines.join("\n");
163
350
  }
164
351
  /**
165
- * Apply one request, in your own words, to every open release note.
352
+ * Apply one request, in your own words, to its selected open documents.
166
353
  *
167
- * Each note is revised on its own, so a request about a section only reaches
168
- * the notes that have one. A note the model fails on is reported and left as
169
- * it was, and the rest of the run is abandoned rather than repeated against a
170
- * provider that has just refused.
354
+ * Each target is revised on its own. Named versions and planner scope keep
355
+ * unrelated files out of the calls entirely. A target the model fails on is
356
+ * reported and left as it was, and the rest of the run is abandoned rather
357
+ * than repeated against a provider that has just refused.
171
358
  */
172
- async revise(instruction) {
359
+ async revise(instruction, scope) {
173
360
  const request = instruction.trim();
174
361
  if (!request)
175
362
  throw new PromptError("A request needs some words to act on.");
176
363
  const startedAt = Date.now();
177
364
  const usage = emptyUsage();
178
- const system = await (0, builder_js_1.buildEditSystemPrompt)(await (0, builder_js_1.resolveInstructions)(this.config.prompt?.instructions));
365
+ const releaseSystem = await (0, builder_js_1.buildEditSystemPrompt)(await (0, builder_js_1.resolveInstructions)(this.config.prompt?.instructions));
366
+ // Built only if an index is actually open: most sessions have none.
367
+ let indexSystem;
179
368
  const edits = [];
180
369
  const revised = new Map();
181
370
  let failed = false;
182
- for (const document of this.documents) {
371
+ const targets = this.documentsForRevision(request, scope);
372
+ if (targets.length === 0) {
373
+ throw new PromptError("No open release note matches the requested versions, language, and file type.");
374
+ }
375
+ for (const document of targets) {
183
376
  if (failed) {
184
377
  edits.push(unchanged(document, "not attempted: the request was abandoned"));
185
378
  continue;
186
379
  }
187
380
  const note = noteOf(document);
188
381
  if (note === undefined) {
189
- edits.push(unchanged(document, document.unrevisable ?? UNREADABLE_PAGE));
382
+ edits.push(unchanged(document, document.unrevisable ?? (document.kind === "index" ? UNREADABLE_INDEX : UNREADABLE_PAGE)));
190
383
  continue;
191
384
  }
192
385
  let answer;
193
386
  try {
194
- answer = await this.callModel({
195
- system,
196
- user: (0, builder_js_1.buildEditUserPrompt)({
197
- instruction: request,
198
- document: note,
199
- format: document.format,
200
- projectName: this.config.projectName,
201
- environment: this.environment,
202
- fromVersion: document.fromVersion,
203
- toVersion: document.toVersion,
204
- language: document.language,
205
- }),
206
- });
387
+ answer = document.kind === "index"
388
+ ? await this.callModel({
389
+ system: indexSystem ??= await (0, builder_js_1.buildIndexEditSystemPrompt)(),
390
+ user: (0, builder_js_1.buildIndexEditUserPrompt)({
391
+ instruction: request,
392
+ document: note,
393
+ format: document.format,
394
+ projectName: this.config.projectName,
395
+ environment: this.environment,
396
+ language: document.language,
397
+ }),
398
+ })
399
+ : await this.callModel({
400
+ system: releaseSystem,
401
+ user: (0, builder_js_1.buildEditUserPrompt)({
402
+ instruction: request,
403
+ document: note,
404
+ format: document.format,
405
+ projectName: this.config.projectName,
406
+ environment: this.environment,
407
+ fromVersion: document.fromVersion,
408
+ toVersion: document.toVersion,
409
+ language: document.language,
410
+ }),
411
+ });
207
412
  }
208
413
  catch (error) {
209
414
  failed = true;
@@ -219,6 +424,7 @@ class PromptSession {
219
424
  before: document.content,
220
425
  after: written,
221
426
  changed: written !== document.content,
427
+ operation: "update",
222
428
  });
223
429
  continue;
224
430
  }
@@ -228,19 +434,293 @@ class PromptSession {
228
434
  usage.durationMs = Date.now() - startedAt;
229
435
  return { edits, usage, via: "model" };
230
436
  }
437
+ /**
438
+ * Fold a contiguous run of release files into one staged release note.
439
+ *
440
+ * The planner supplies only the range. Chaining, document selection, output
441
+ * paths, section merging, source removals, and index reconciliation are
442
+ * deterministic so a model can never merge the wrong files.
443
+ */
444
+ async merge(request) {
445
+ const input = typeof request === "string"
446
+ ? { instruction: request }
447
+ : request;
448
+ const releases = this.activeDocuments().filter((document) => document.kind === "release" && document.outputPattern);
449
+ if (releases.length === 0) {
450
+ throw new PromptError("No release-specific files are open to merge.");
451
+ }
452
+ const mentioned = resolveMentionedVersions(input.instruction ?? "", releases, input);
453
+ if (!mentioned.fromVersion || !mentioned.toVersion) {
454
+ throw new PromptError("Merging needs both ends of the range, and each must be a version shown in the open release catalog.");
455
+ }
456
+ if (sameVersion(mentioned.fromVersion, mentioned.toVersion)) {
457
+ throw new PromptError("A merged range must start and end at different versions.");
458
+ }
459
+ if ((0, promote_js_1.compareVersions)(mentioned.fromVersion, mentioned.toVersion) > 0) {
460
+ throw new PromptError(`The merged range ends at ${mentioned.toVersion}, which comes before ${mentioned.fromVersion}.`);
461
+ }
462
+ const startedAt = Date.now();
463
+ const usage = emptyUsage();
464
+ const languages = normalizedLanguages(input.languages);
465
+ const availableLanguages = new Set(releases.map((document) => document.language ?? ""));
466
+ const missingLanguages = languages.filter((language) => !availableLanguages.has(language));
467
+ if (missingLanguages.length > 0) {
468
+ throw new PromptError(`No open release notes match ${missingLanguages.join(", ")}.`);
469
+ }
470
+ const groups = groupMergeCandidates(releases.filter((document) => languages.length === 0 || languages.includes(document.language ?? "")));
471
+ if (groups.length === 0) {
472
+ throw new PromptError("No open release notes match the requested language.");
473
+ }
474
+ const plans = [];
475
+ for (const group of groups) {
476
+ const plan = planMergeGroup(group, mentioned.fromVersion, mentioned.toVersion);
477
+ // An output/language that has neither boundary is not another requested
478
+ // target. One carrying either boundary is, and must carry the whole chain.
479
+ if (!plan)
480
+ continue;
481
+ if (plan.sources.length < 2) {
482
+ throw new PromptError(`${displayRange(mentioned.fromVersion, mentioned.toVersion)} is already covered by one ` +
483
+ `release note${group.language ? ` in ${group.language}` : ""}.`);
484
+ }
485
+ plans.push(plan);
486
+ }
487
+ if (plans.length === 0) {
488
+ throw new PromptError(`No open release chain leads from ${mentioned.fromVersion} to ${mentioned.toVersion}.`);
489
+ }
490
+ // Build every result before changing session state. A missing language,
491
+ // unreadable page, or colliding destination therefore leaves all groups
492
+ // untouched rather than half-merging a multilingual release.
493
+ const outcomes = [];
494
+ for (const plan of plans) {
495
+ outcomes.push(await this.buildMergedOutcome(plan, usage));
496
+ }
497
+ const sourcePaths = new Set(outcomes.flatMap((outcome) => outcome.plan.sources.map((document) => document.path)));
498
+ const destinationPaths = new Set(outcomes.map((outcome) => outcome.destination.path));
499
+ for (const destination of destinationPaths) {
500
+ const collision = this.activeDocuments().find((document) => document.path === destination && !sourcePaths.has(document.path));
501
+ if (collision) {
502
+ throw new PromptError(`Cannot merge into ${destination}: that path already holds another open file.`);
503
+ }
504
+ }
505
+ const indexChanges = this.buildMergedIndexChanges(outcomes);
506
+ this.history.push(cloneDocuments(this.documents));
507
+ const edits = [];
508
+ for (const outcome of outcomes) {
509
+ const existingDestination = this.documents.find((document) => document.path === outcome.destination.path);
510
+ for (const source of outcome.plan.sources) {
511
+ if (source.path === outcome.destination.path)
512
+ continue;
513
+ source.removed = true;
514
+ edits.push({
515
+ path: source.path,
516
+ before: source.content,
517
+ after: "",
518
+ changed: true,
519
+ operation: "delete",
520
+ });
521
+ }
522
+ if (existingDestination) {
523
+ const before = existingDestination.content;
524
+ existingDestination.content = outcome.destination.content;
525
+ existingDestination.fromVersion = outcome.destination.fromVersion;
526
+ existingDestination.toVersion = outcome.destination.toVersion;
527
+ existingDestination.removed = false;
528
+ edits.push({
529
+ path: existingDestination.path,
530
+ before,
531
+ after: existingDestination.content,
532
+ changed: before !== existingDestination.content,
533
+ operation: "update",
534
+ });
535
+ }
536
+ else {
537
+ this.documents.push(outcome.destination);
538
+ edits.push({
539
+ path: outcome.destination.path,
540
+ before: "",
541
+ after: outcome.destination.content,
542
+ changed: true,
543
+ operation: "create",
544
+ });
545
+ }
546
+ }
547
+ for (const change of indexChanges) {
548
+ const before = change.document.content;
549
+ change.document.content = change.content;
550
+ edits.push({
551
+ path: change.document.path,
552
+ before,
553
+ after: change.content,
554
+ changed: before !== change.content,
555
+ operation: "update",
556
+ });
557
+ }
558
+ usage.durationMs = Date.now() - startedAt;
559
+ return {
560
+ edits,
561
+ usage,
562
+ via: outcomes.some((outcome) => outcome.openingAttempted) ? "model" : "comparison",
563
+ };
564
+ }
565
+ /** Build one combined file without changing the session yet. */
566
+ async buildMergedOutcome(plan, usage) {
567
+ const notes = plan.sources.map((document) => noteOf(document));
568
+ const unreadable = plan.sources.find((document, index) => notes[index] === undefined ||
569
+ !(0, release_document_js_1.isReleaseDocumentReadable)(notes[index] ?? "", document.format));
570
+ if (unreadable) {
571
+ throw new PromptError(`Cannot merge ${(0, path_1.relative)(process.cwd(), unreadable.path)} without rewriting reviewed wording: ` +
572
+ `${unreadable.unrevisable ?? "its release-note structure could not be read safely"}.`);
573
+ }
574
+ const sourceNotes = notes;
575
+ const latest = plan.sources.at(-1);
576
+ const latestRange = plan.ranges.at(-1);
577
+ let merged = (0, release_document_js_1.mergeReleaseDocuments)(sourceNotes, plan.format, { leadWith: "newest" });
578
+ merged = retargetMergedOpening(merged, plan.format, latestRange.fromVersion, plan.fromVersion);
579
+ const openings = sourceNotes.map((content, index) => ({
580
+ ...plan.ranges[index],
581
+ content: (0, release_document_js_1.splitReleaseOpening)(content, plan.format).opening,
582
+ })).filter((opening) => opening.content.trim());
583
+ const openingAttempted = openings.length > 1;
584
+ if (openingAttempted) {
585
+ try {
586
+ const answer = await this.callModel({
587
+ system: await (0, builder_js_1.buildSessionMergeSystemPrompt)(await (0, builder_js_1.resolveInstructions)(this.config.prompt?.instructions)),
588
+ user: (0, builder_js_1.buildSessionMergeUserPrompt)({
589
+ openings,
590
+ format: plan.format,
591
+ environment: this.environment,
592
+ fromVersion: plan.fromVersion,
593
+ toVersion: plan.toVersion,
594
+ projectName: this.config.projectName,
595
+ language: plan.language,
596
+ }),
597
+ });
598
+ addUsage(usage, answer.usage);
599
+ const fenceless = (0, generator_js_1.stripEnclosingCodeFence)(answer.text).trim();
600
+ const opening = plan.format === "html"
601
+ ? (0, release_js_1.sanitizeReleaseHtml)(fenceless).trim()
602
+ : fenceless;
603
+ if (opening &&
604
+ (0, release_document_js_1.splitReleaseOpening)(opening, plan.format).sections.trim() === "" &&
605
+ looksLikeSameDocumentKind((0, release_document_js_1.splitReleaseOpening)(merged, plan.format).opening, opening, plan.format, "release")) {
606
+ const sections = (0, release_document_js_1.splitReleaseOpening)(merged, plan.format).sections;
607
+ merged = sections ? `${opening}\n\n${sections}`.trim() : opening;
608
+ }
609
+ }
610
+ catch {
611
+ // Section merging is deterministic and complete. If the optional
612
+ // opening writer is unavailable, the retargeted newest opening is a
613
+ // safe, factual fallback for the combined range.
614
+ }
615
+ }
616
+ const destinationPath = (0, path_1.resolve)((0, output_path_js_1.formatOutputPath)(plan.outputPattern, {
617
+ environment: this.environment,
618
+ language: plan.language,
619
+ fromVersion: plan.fromVersion,
620
+ toVersion: plan.toVersion,
621
+ }));
622
+ const existing = this.activeDocuments().find((document) => document.path === destinationPath);
623
+ if (!existing && (0, fs_1.existsSync)(destinationPath)) {
624
+ throw new PromptError(`Cannot merge into ${destinationPath}: a file exists there but is not part of this session.`);
625
+ }
626
+ const content = plan.format === "html"
627
+ ? mergedHtmlPage(latest, merged, latestRange.fromVersion, plan.fromVersion)
628
+ : `${merged.trim()}\n`;
629
+ return {
630
+ plan,
631
+ openingAttempted,
632
+ destination: {
633
+ path: destinationPath,
634
+ format: plan.format,
635
+ language: plan.language,
636
+ fromVersion: plan.fromVersion,
637
+ toVersion: plan.toVersion,
638
+ saved: existing?.saved ?? "",
639
+ content,
640
+ template: latest.template,
641
+ outputPattern: plan.outputPattern,
642
+ created: !existing,
643
+ kind: "release",
644
+ },
645
+ };
646
+ }
647
+ /**
648
+ * Replace each index's constituent records with the combined release record.
649
+ *
650
+ * Index wording stays as written: the newest selected entry is retargeted,
651
+ * while its machine-readable marker is rebuilt from values already present.
652
+ */
653
+ buildMergedIndexChanges(outcomes) {
654
+ const changes = [];
655
+ for (const document of this.activeDocuments().filter((candidate) => candidate.kind === "index" && noteOf(candidate) !== undefined)) {
656
+ const region = noteOf(document);
657
+ const entries = splitIndexRecordEntries(region);
658
+ if (entries.length === 0)
659
+ continue;
660
+ const outcome = chooseIndexMergeOutcome(document, entries, outcomes);
661
+ if (!outcome)
662
+ continue;
663
+ const selected = entries.filter((entry) => {
664
+ const record = entry.record;
665
+ return !!record && outcome.plan.ranges.some((range) => sameVersion(record.fromVersion, range.fromVersion) &&
666
+ sameVersion(record.toVersion, range.toVersion));
667
+ });
668
+ if (selected.length === 0)
669
+ continue;
670
+ if (selected.length !== outcome.plan.ranges.length) {
671
+ throw new PromptError(`Cannot update ${(0, path_1.relative)(process.cwd(), document.path)} safely: its release list carries only ` +
672
+ `${selected.length} of the ${outcome.plan.ranges.length} notes being merged.`);
673
+ }
674
+ const newest = selected.find((entry) => sameVersion(entry.record.toVersion, outcome.plan.toVersion));
675
+ if (!newest) {
676
+ throw new PromptError(`Cannot update ${(0, path_1.relative)(process.cwd(), document.path)} safely: its newest merged release is missing.`);
677
+ }
678
+ const href = toPortablePath((0, path_1.relative)((0, path_1.dirname)(document.path), outcome.destination.path));
679
+ const record = {
680
+ ...newest.record,
681
+ fromVersion: outcome.plan.fromVersion,
682
+ toVersion: outcome.plan.toVersion,
683
+ href,
684
+ };
685
+ const marker = serializeIndexRecord(record);
686
+ const visible = newest.content
687
+ .replace(newest.marker, marker);
688
+ const retargeted = replaceWholeValue(replaceWholeValue(visible, newest.record.fromVersion, record.fromVersion), newest.record.href, record.href);
689
+ const selectedIndexes = new Set(selected.map((entry) => entry.index));
690
+ const insertion = Math.min(...selectedIndexes);
691
+ const rebuilt = entries.flatMap((entry) => {
692
+ if (entry.index === insertion)
693
+ return [retargeted.trimEnd()];
694
+ if (selectedIndexes.has(entry.index))
695
+ return [];
696
+ return [entry.content.trimEnd()];
697
+ }).join("\n");
698
+ const prefix = region.slice(0, entries[0].start);
699
+ const content = (0, release_js_1.replaceOutputIndexReleases)(document.content, `${prefix}${rebuilt}`.trim());
700
+ changes.push({ document, content });
701
+ }
702
+ return changes;
703
+ }
231
704
  /**
232
705
  * Drop every line an open release note lists more than once.
233
706
  *
234
707
  * Comparing lines is something this can do exactly, so it does it itself: no
235
708
  * request is built, no provider is called, and what comes back is the note
236
709
  * minus the lines it repeated, never a rewording of the ones it keeps.
710
+ *
711
+ * An index is not one note repeating itself: it is many, each listed once
712
+ * already, so it has nothing here to drop and is left out of this pass.
237
713
  */
238
714
  dedupe() {
239
715
  const startedAt = Date.now();
240
716
  const usage = emptyUsage();
241
717
  const edits = [];
242
718
  const revised = new Map();
243
- for (const document of this.documents) {
719
+ for (const document of this.activeDocuments()) {
720
+ if (document.kind === "index") {
721
+ edits.push(unchanged(document, "deduplication applies to release notes, not to the release index"));
722
+ continue;
723
+ }
244
724
  const note = noteOf(document);
245
725
  if (note === undefined) {
246
726
  edits.push(unchanged(document, document.unrevisable ?? UNREADABLE_PAGE));
@@ -260,6 +740,7 @@ class PromptSession {
260
740
  after: written,
261
741
  changed: written !== document.content,
262
742
  removed,
743
+ operation: "update",
263
744
  });
264
745
  }
265
746
  this.commit(revised);
@@ -271,33 +752,44 @@ class PromptSession {
271
752
  const previous = this.history.pop();
272
753
  if (!previous)
273
754
  return false;
274
- for (const document of this.documents) {
275
- const content = previous.get(document.path);
276
- if (content !== undefined)
277
- document.content = content;
278
- }
755
+ this.documents.splice(0, this.documents.length, ...cloneDocuments(previous));
279
756
  return true;
280
757
  }
281
758
  /** Drop every request applied since the last save. */
282
759
  reset() {
283
- for (const document of this.documents) {
760
+ const existing = this.documents.filter((document) => !document.created);
761
+ for (const document of existing) {
284
762
  document.content = document.saved;
763
+ document.removed = false;
285
764
  }
765
+ this.documents.splice(0, this.documents.length, ...existing);
286
766
  this.history.length = 0;
287
767
  }
288
- /**
289
- * Write the revised notes.
290
- *
291
- * A revision changes what a release note says, never which release it is, so
292
- * the release index still describes it correctly and is left alone.
293
- */
768
+ /** Write staged updates and creations, then remove replaced source files. */
294
769
  async save() {
295
770
  const written = [];
296
- for (const document of this.pending()) {
771
+ const pending = this.pending();
772
+ // A combined destination is made durable before any source is removed. If
773
+ // writing fails, the originals are therefore still present.
774
+ const writes = pending
775
+ .filter((candidate) => !candidate.removed)
776
+ .sort((left, right) => Number(right.created && right.kind === "release") -
777
+ Number(left.created && left.kind === "release"));
778
+ for (const document of writes) {
779
+ await (0, promises_1.mkdir)((0, path_1.dirname)(document.path), { recursive: true });
297
780
  await (0, promises_1.writeFile)(document.path, document.content, "utf-8");
298
781
  document.saved = document.content;
782
+ document.created = false;
299
783
  written.push(document.path);
300
784
  }
785
+ for (const document of pending.filter((candidate) => candidate.removed)) {
786
+ await (0, promises_1.rm)(document.path, { force: true });
787
+ written.push(document.path);
788
+ }
789
+ this.documents.splice(0, this.documents.length, ...this.documents.filter((document) => !document.removed));
790
+ // Once file topology reached disk, an in-memory undo could no longer make
791
+ // the removed files real again. A later edit starts a fresh history.
792
+ this.history.length = 0;
301
793
  return written;
302
794
  }
303
795
  /**
@@ -308,51 +800,458 @@ class PromptSession {
308
800
  * published page, so it is reduced to the markup a release note is made of
309
801
  * first: the note the model was given was itself written from changelog text
310
802
  * nobody reviewed.
803
+ *
804
+ * An index's list is held to one thing more. Its entries carry the markers a
805
+ * later run recognizes each release by, so an answer may drop a marker along
806
+ * with the release it opens, and may never write, repeat or edit one — an
807
+ * index that gained a marker nobody generated would list a release that was
808
+ * never released.
311
809
  */
312
810
  applyAnswer(document, answer) {
313
- const revised = document.format === "html"
314
- ? (0, release_js_1.sanitizeReleaseHtml)((0, generator_js_1.stripEnclosingCodeFence)(answer)).trim()
315
- : (0, generator_js_1.stripEnclosingCodeFence)(answer).trim();
811
+ const fenceless = (0, generator_js_1.stripEnclosingCodeFence)(answer);
812
+ const revised = document.format !== "html"
813
+ ? fenceless.trim()
814
+ : document.kind === "index"
815
+ ? (0, release_js_1.sanitizeReleaseIndexHtml)(fenceless).trim()
816
+ : (0, release_js_1.sanitizeReleaseHtml)(fenceless).trim();
316
817
  if (!revised) {
317
818
  return { skipped: "the model answered with nothing, so the file was left as it was" };
318
819
  }
820
+ if (document.kind === "index" && !keepsItsMarkers(noteOf(document) ?? "", revised)) {
821
+ return { skipped: ALTERED_MARKERS };
822
+ }
823
+ if (!looksLikeSameDocumentKind(noteOf(document) ?? "", revised, document.format, document.kind)) {
824
+ return {
825
+ skipped: "the model returned commentary instead of a release document, so the file was left as it was",
826
+ };
827
+ }
319
828
  const written = withNote(document, revised);
320
829
  return written === undefined ? { skipped: UNREADABLE_PAGE } : written;
321
830
  }
831
+ /** Keep what was just said, so the next message has it to lean on. */
832
+ remember(message, action) {
833
+ this.lastExchange = { message, action: action.action, reply: action.reply };
834
+ return action;
835
+ }
322
836
  /** Take the revised files into the session, one step back always available. */
323
837
  commit(revised) {
324
838
  const changed = this.documents.filter((document) => revised.get(document.path) !== undefined
325
839
  && revised.get(document.path) !== document.content);
326
840
  if (changed.length === 0)
327
841
  return;
328
- this.history.push(new Map(this.documents.map((document) => [document.path, document.content])));
842
+ this.history.push(cloneDocuments(this.documents));
329
843
  for (const document of changed) {
330
844
  document.content = revised.get(document.path);
331
845
  }
332
846
  }
847
+ /** Files that have not been staged for removal. */
848
+ activeDocuments() {
849
+ return this.documents.filter((document) => !document.removed);
850
+ }
851
+ /** The open documents a regular in-place revision should reach. */
852
+ documentsForRevision(instruction, scope) {
853
+ let candidates = this.activeDocuments();
854
+ const languages = normalizedLanguages(scope?.languages);
855
+ if (languages.length > 0) {
856
+ candidates = candidates.filter((document) => !document.language || languages.includes(document.language));
857
+ }
858
+ if (scope?.kinds?.length) {
859
+ candidates = candidates.filter((document) => scope.kinds.includes(document.kind));
860
+ }
861
+ const releases = candidates.filter((document) => document.kind === "release");
862
+ const versions = resolveMentionedVersions(instruction, releases, scope);
863
+ if (!versions.fromVersion && !versions.toVersion)
864
+ return candidates;
865
+ return selectReleaseDocuments(releases, versions);
866
+ }
333
867
  }
334
868
  exports.PromptSession = PromptSession;
335
869
  // ─────────────────────────────────────────
870
+ // What a question is answered from
871
+ // ─────────────────────────────────────────
872
+ /**
873
+ * How much release-note text one question may carry.
874
+ *
875
+ * Two dozen notes is a normal shelf and every provider has a ceiling, so there
876
+ * is a point past which a question either fails or costs more than the answer
877
+ * is worth. What does not fit is named rather than quietly dropped.
878
+ */
879
+ const ANSWER_MATERIAL_LIMIT = 60_000;
880
+ /** The range a note covers, as an answer would name it. */
881
+ function coverage(document) {
882
+ return [document.fromVersion, document.toVersion].filter(Boolean).join(" → ")
883
+ || (0, path_1.basename)(document.path);
884
+ }
885
+ /** Release order, oldest first, for two notes of one language. */
886
+ function compareCoverage(left, right) {
887
+ return (0, promote_js_1.compareVersions)(left.toVersion ?? "", right.toVersion ?? "");
888
+ }
889
+ /**
890
+ * Resolve version words against the catalog rather than trusting their shape.
891
+ *
892
+ * A missing conventional `v` prefix is accepted only when it points to exactly
893
+ * one known boundary. Everything returned uses the spelling found in the open
894
+ * files, so paths are never built from a model-normalized version.
895
+ */
896
+ function resolveMentionedVersions(message, documents, scope) {
897
+ const known = knownVersions(documents);
898
+ const resolveExplicit = (value) => {
899
+ if (!value)
900
+ return undefined;
901
+ const resolved = resolveKnownVersion(value, known);
902
+ if (!resolved) {
903
+ throw new PromptError(`Version "${value}" is not a boundary in the open release catalog.`);
904
+ }
905
+ return resolved;
906
+ };
907
+ const explicitFrom = resolveExplicit(scope?.fromVersion);
908
+ const explicitTo = resolveExplicit(scope?.toVersion);
909
+ if (scope?.fromVersion || scope?.toVersion) {
910
+ return { fromVersion: explicitFrom, toVersion: explicitTo };
911
+ }
912
+ const mentioned = [];
913
+ for (const token of message.match(/[\p{L}\p{N}][\p{L}\p{N}._-]*/gu) ?? []) {
914
+ const resolved = resolveKnownVersion(token, known);
915
+ if (resolved && !mentioned.some((version) => sameVersion(version, resolved))) {
916
+ mentioned.push(resolved);
917
+ }
918
+ }
919
+ if (mentioned.length === 1)
920
+ return { toVersion: mentioned[0] };
921
+ if (mentioned.length > 1) {
922
+ return {
923
+ fromVersion: mentioned[0],
924
+ toVersion: mentioned[mentioned.length - 1],
925
+ };
926
+ }
927
+ return {};
928
+ }
929
+ /** Select one release, a whole bounded range, or everything when unbounded. */
930
+ function selectReleaseDocuments(documents, range) {
931
+ if (range.fromVersion && range.toVersion) {
932
+ if ((0, promote_js_1.compareVersions)(range.fromVersion, range.toVersion) >= 0) {
933
+ throw new PromptError(`The requested range runs from ${range.fromVersion} to ${range.toVersion}; ` +
934
+ "its end must come after its start.");
935
+ }
936
+ return documents.filter((document) => !!document.fromVersion &&
937
+ !!document.toVersion &&
938
+ (0, promote_js_1.compareVersions)(document.fromVersion, range.fromVersion) >= 0 &&
939
+ (0, promote_js_1.compareVersions)(document.toVersion, range.toVersion) <= 0);
940
+ }
941
+ if (range.toVersion) {
942
+ return documents.filter((document) => !!document.toVersion && sameVersion(document.toVersion, range.toVersion));
943
+ }
944
+ if (range.fromVersion) {
945
+ return documents.filter((document) => !!document.fromVersion && sameVersion(document.fromVersion, range.fromVersion));
946
+ }
947
+ return [...documents];
948
+ }
949
+ function knownVersions(documents) {
950
+ const known = new Map();
951
+ for (const version of documents.flatMap((document) => [document.fromVersion, document.toVersion].filter((value) => !!value))) {
952
+ const canonical = canonicalVersion(version);
953
+ const spellings = known.get(canonical) ?? [];
954
+ if (!spellings.some((candidate) => candidate.toLowerCase() === version.toLowerCase())) {
955
+ spellings.push(version);
956
+ }
957
+ known.set(canonical, spellings);
958
+ }
959
+ return known;
960
+ }
961
+ function resolveKnownVersion(value, known) {
962
+ const exact = [...known.values()].flat().find((candidate) => candidate.toLowerCase() === value.toLowerCase());
963
+ if (exact)
964
+ return exact;
965
+ const candidates = known.get(canonicalVersion(value)) ?? [];
966
+ return candidates.length === 1 ? candidates[0] : undefined;
967
+ }
968
+ function canonicalVersion(version) {
969
+ return version.trim().toLowerCase().replace(/^v(?=\d)/, "");
970
+ }
971
+ function sameVersion(left, right) {
972
+ return canonicalVersion(left) === canonicalVersion(right);
973
+ }
974
+ function normalizedLanguages(languages) {
975
+ return [...new Set((languages ?? []).map(output_path_js_1.normalizeLanguage))];
976
+ }
977
+ /** Pack every selected note into bounded model calls without omitting any. */
978
+ function chunkAnswerDocuments(documents) {
979
+ if (documents.length === 0)
980
+ return [[]];
981
+ const chunks = [];
982
+ let current = [];
983
+ let size = 0;
984
+ for (const document of documents) {
985
+ const documentSize = (noteOf(document) ?? "").length;
986
+ if (current.length > 0 && size + documentSize > ANSWER_MATERIAL_LIMIT) {
987
+ chunks.push(current);
988
+ current = [];
989
+ size = 0;
990
+ }
991
+ current.push(document);
992
+ size += documentSize;
993
+ }
994
+ if (current.length > 0)
995
+ chunks.push(current);
996
+ return chunks;
997
+ }
998
+ /** The open notes of one language, in the order they were released. */
999
+ function byLanguage(documents) {
1000
+ const groups = new Map();
1001
+ for (const document of documents) {
1002
+ const language = document.language ?? "";
1003
+ groups.set(language, [...(groups.get(language) ?? []), document]);
1004
+ }
1005
+ return groups;
1006
+ }
1007
+ /**
1008
+ * The releases of one language, oldest first, every break in the chain named.
1009
+ *
1010
+ * This is the whole of what a question like "is a version missing between two
1011
+ * of these" is answered from, and it is worked out here rather than asked of a
1012
+ * model: `v1.8.2` before `v1.12.0` is a comparison a model gets wrong often
1013
+ * enough to matter, and a release reported missing that is not, or held to be
1014
+ * present when nothing covers it, is worse than no answer.
1015
+ */
1016
+ function describeReleaseChain(documents) {
1017
+ const ordered = [...documents]
1018
+ .filter((document) => document.toVersion)
1019
+ .sort(compareCoverage);
1020
+ const versionless = documents.filter((document) => !document.toVersion);
1021
+ const lines = [];
1022
+ let previous;
1023
+ let breaks = 0;
1024
+ for (const document of ordered) {
1025
+ if (previous?.toVersion && document.fromVersion && previous.toVersion !== document.fromVersion) {
1026
+ breaks += 1;
1027
+ lines.push((0, promote_js_1.compareVersions)(document.fromVersion, previous.toVersion) > 0
1028
+ ? ` ⚠ nothing covers ${previous.toVersion} → ${document.fromVersion}: no note picks up where the one above left off`
1029
+ : ` ⚠ ${coverage(document)} covers ground the note above already covered`);
1030
+ }
1031
+ previous = document;
1032
+ lines.push(` ${coverage(document)}${document.unrevisable ? " (open, but its note cannot be read)" : ""}`);
1033
+ }
1034
+ for (const document of versionless) {
1035
+ lines.push(` ${(0, path_1.basename)(document.path)} (its name carries no version)`);
1036
+ }
1037
+ if (ordered.length > 1) {
1038
+ lines.push(breaks === 0
1039
+ ? ` No break in the chain: every note starts where the one above it ended, ${coverage(ordered[0])} through ${ordered[ordered.length - 1].toVersion}.`
1040
+ : ` ${breaks} break${breaks === 1 ? "" : "s"} in the chain, marked ⚠ above. Every other note starts where the one above it ended.`);
1041
+ }
1042
+ return lines;
1043
+ }
1044
+ /**
1045
+ * A release note as words, with the markup that carried them taken off.
1046
+ *
1047
+ * A question is asked about what a release brought, never about the tags it is
1048
+ * written in, and a page of markup spends the material a question may carry on
1049
+ * text nobody is asking about.
1050
+ */
1051
+ function readableNote(note, format) {
1052
+ if (format !== "html")
1053
+ return note.trim();
1054
+ return note
1055
+ .replace(/<!--[\s\S]*?-->/g, "")
1056
+ .replace(/<(br|\/p|\/li|\/h[1-6]|\/div|\/tr|\/section|\/article)\b[^>]*>/gi, "\n")
1057
+ .replace(/<[^>]*>/g, "")
1058
+ .replace(/&nbsp;/g, " ")
1059
+ .replace(/&lt;/g, "<")
1060
+ .replace(/&gt;/g, ">")
1061
+ .replace(/&quot;/g, '"')
1062
+ .replace(/&#3[49];/g, "'")
1063
+ .replace(/&amp;/g, "&")
1064
+ .split("\n")
1065
+ .map((line) => line.replace(/[ \t]+/g, " ").trim())
1066
+ .join("\n")
1067
+ .replace(/\n{3,}/g, "\n\n")
1068
+ .trim();
1069
+ }
1070
+ // ─────────────────────────────────────────
1071
+ // Merging a range in place
1072
+ // ─────────────────────────────────────────
1073
+ function groupMergeCandidates(documents) {
1074
+ const groups = new Map();
1075
+ for (const document of documents) {
1076
+ if (!document.outputPattern)
1077
+ continue;
1078
+ const key = [
1079
+ document.outputPattern,
1080
+ document.format,
1081
+ document.language ?? "",
1082
+ ].join("\u0000");
1083
+ const group = groups.get(key) ?? {
1084
+ documents: [],
1085
+ outputPattern: document.outputPattern,
1086
+ format: document.format,
1087
+ language: document.language,
1088
+ };
1089
+ group.documents.push(document);
1090
+ groups.set(key, group);
1091
+ }
1092
+ return [...groups.values()];
1093
+ }
1094
+ /**
1095
+ * Resolve one output/language through the same shortest contiguous-chain
1096
+ * planner used by promotion.
1097
+ */
1098
+ function planMergeGroup(group, requestedFrom, requestedTo) {
1099
+ const known = knownVersions(group.documents);
1100
+ const fromVersion = resolveKnownVersion(requestedFrom, known);
1101
+ const toVersion = resolveKnownVersion(requestedTo, known);
1102
+ if (!fromVersion && !toVersion)
1103
+ return undefined;
1104
+ if (!fromVersion || !toVersion) {
1105
+ throw new PromptError(`The ${group.language ? `${group.language} ` : ""}${group.format} output does not cover both ` +
1106
+ `${requestedFrom} and ${requestedTo}.`);
1107
+ }
1108
+ try {
1109
+ const planned = (0, promote_js_1.planPromotion)({
1110
+ available: group.documents.map((document, index) => ({
1111
+ path: document.path,
1112
+ environment: undefined,
1113
+ language: document.language,
1114
+ fromVersion: document.fromVersion,
1115
+ toVersion: document.toVersion,
1116
+ modifiedAt: index,
1117
+ })),
1118
+ fromVersion,
1119
+ toVersion,
1120
+ });
1121
+ const sources = planned.segments.map((segment) => {
1122
+ const source = group.documents.find((document) => segment.releases.some((release) => release.path === document.path));
1123
+ if (!source) {
1124
+ throw new PromptError(`The planned release ${segment.fromVersion} → ${segment.toVersion} is not open.`);
1125
+ }
1126
+ return source;
1127
+ });
1128
+ return {
1129
+ ...group,
1130
+ fromVersion: planned.fromVersion,
1131
+ toVersion: planned.toVersion,
1132
+ sources,
1133
+ ranges: planned.segments.map((segment) => ({
1134
+ fromVersion: segment.fromVersion,
1135
+ toVersion: segment.toVersion,
1136
+ })),
1137
+ };
1138
+ }
1139
+ catch (error) {
1140
+ if (error instanceof PromptError)
1141
+ throw error;
1142
+ if (error instanceof promote_js_1.PromotionError) {
1143
+ throw new PromptError(`Cannot merge the ${group.language ? `${group.language} ` : ""}${group.format} notes: ` +
1144
+ error.message);
1145
+ }
1146
+ throw error;
1147
+ }
1148
+ }
1149
+ /** Keep the newest opening but point its comparison at the combined range. */
1150
+ function retargetMergedOpening(merged, format, previousVersion, fromVersion) {
1151
+ const { opening, sections } = (0, release_document_js_1.splitReleaseOpening)(merged, format);
1152
+ const retargeted = replaceWholeValue(opening, previousVersion, fromVersion);
1153
+ return sections ? `${retargeted.trimEnd()}\n\n${sections}` : retargeted;
1154
+ }
1155
+ /** Put a combined note into the newest HTML shell and retarget shell metadata. */
1156
+ function mergedHtmlPage(latest, merged, previousVersion, fromVersion) {
1157
+ const range = (0, release_document_js_1.releaseContentRange)(latest.content, latest.template);
1158
+ if (!range)
1159
+ throw new PromptError(`${latest.path} has no safely replaceable release-note region.`);
1160
+ const before = replaceWholeValue(latest.content.slice(0, range.start), previousVersion, fromVersion);
1161
+ const after = replaceWholeValue(latest.content.slice(range.end), previousVersion, fromVersion);
1162
+ return `${before}\n${merged.trim()}\n${after}`;
1163
+ }
1164
+ const INDEX_ENTRY_MARKER = /<!--\s*ai-release-notes:release\s+([^>]*?)\s*-->/g;
1165
+ /** Read every index entry, preserving legacy entries without JSON records. */
1166
+ function splitIndexRecordEntries(region) {
1167
+ const matches = [...region.matchAll(INDEX_ENTRY_MARKER)];
1168
+ return matches.map((match, index) => {
1169
+ const marker = match[0];
1170
+ const record = (0, release_js_1.readOutputIndexReleaseRecords)(marker)[0];
1171
+ const start = match.index;
1172
+ const end = matches[index + 1]?.index ?? region.length;
1173
+ return {
1174
+ index,
1175
+ start,
1176
+ marker,
1177
+ content: region.slice(start, end),
1178
+ record,
1179
+ };
1180
+ });
1181
+ }
1182
+ /** Match a localized index to the release output whose links it carries. */
1183
+ function chooseIndexMergeOutcome(index, entries, outcomes) {
1184
+ if (index.language) {
1185
+ const localized = outcomes.filter((outcome) => (outcome.plan.language ?? "") === index.language);
1186
+ if (localized.length === 1)
1187
+ return localized[0];
1188
+ }
1189
+ const linked = outcomes.filter((outcome) => {
1190
+ const sources = new Set(outcome.plan.sources.map((document) => (0, path_1.resolve)(document.path)));
1191
+ return entries.some((entry) => !!entry.record && sources.has((0, path_1.resolve)((0, path_1.dirname)(index.path), entry.record.href)));
1192
+ });
1193
+ if (linked.length === 1)
1194
+ return linked[0];
1195
+ return outcomes.length === 1 ? outcomes[0] : undefined;
1196
+ }
1197
+ function serializeIndexRecord(record) {
1198
+ const serialized = JSON.stringify(record).replaceAll("--", "\\u002d\\u002d");
1199
+ return `<!-- ai-release-notes:release ${serialized} -->`;
1200
+ }
1201
+ function toPortablePath(path) {
1202
+ return path.split(path_1.sep).join("/");
1203
+ }
1204
+ /** Replace one standalone catalog value without touching longer values. */
1205
+ function replaceWholeValue(text, from, to) {
1206
+ if (!from || from === to)
1207
+ return text;
1208
+ const pattern = new RegExp(`(?<![\\p{L}\\p{N}.-])${escapeRegExp(from)}(?![\\p{L}\\p{N}.-])`, "giu");
1209
+ return text.replace(pattern, to);
1210
+ }
1211
+ function escapeRegExp(value) {
1212
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1213
+ }
1214
+ function displayRange(fromVersion, toVersion) {
1215
+ return `${fromVersion} → ${toVersion}`;
1216
+ }
1217
+ /** A history snapshot owns its objects; later mutations cannot reach it. */
1218
+ function cloneDocuments(documents) {
1219
+ return documents.map((document) => ({ ...document }));
1220
+ }
1221
+ /**
1222
+ * Reject prose wrapped around a document. This is a structural check, not a
1223
+ * phrase list: a note that arrived as markup or a heading must return as one.
1224
+ */
1225
+ function looksLikeSameDocumentKind(original, revised, format, kind) {
1226
+ if (kind === "index")
1227
+ return true;
1228
+ if (format === "html") {
1229
+ return /^\s*</.test(revised) && /<h[1-6]\b/i.test(revised);
1230
+ }
1231
+ return !/^\s{0,3}#{1,6}\s/.test(original) || /^\s{0,3}#{1,6}\s/.test(revised);
1232
+ }
1233
+ // ─────────────────────────────────────────
336
1234
  // Reading what was asked for
337
1235
  // ─────────────────────────────────────────
338
1236
  /**
339
1237
  * Read the front desk's answer.
340
1238
  *
341
- * An answer that is not the object asked for means the message was not placed,
342
- * and the message itself becomes the request: a session where a malformed
343
- * answer stopped the work would be worse than one that simply tries the
344
- * revision, which reports for itself whether it changed anything.
1239
+ * An answer that is not the object asked for means the message was not placed.
1240
+ * It is left unclear rather than guessed as a mutation: provider trouble must
1241
+ * never turn a read-only question into a revision of every open file.
345
1242
  */
346
1243
  function readSessionAction(answer, message) {
347
1244
  const parsed = SessionActionSchema.safeParse(parseJsonObject((0, generator_js_1.stripEnclosingCodeFence)(answer)));
348
1245
  if (!parsed.success)
349
- return { action: "revise", instruction: message, reply: "" };
1246
+ return { action: "unclear", instruction: message, reply: "" };
350
1247
  return {
351
1248
  action: parsed.data.action,
352
1249
  // A revision with nothing to do is the message as it was typed: the front
353
1250
  // desk placed it, so its own words still say what to do.
354
1251
  instruction: parsed.data.instruction?.trim() || message,
355
1252
  reply: parsed.data.reply?.trim() || "",
1253
+ ...(parsed.data.scope ? { scope: parsed.data.scope } : {}),
1254
+ ...(parsed.data.answerFrom ? { answerFrom: parsed.data.answerFrom } : {}),
356
1255
  };
357
1256
  }
358
1257
  /** The JSON object an answer carries, wherever in the answer it sits. */
@@ -414,20 +1313,28 @@ function covers(release, fromVersion, toVersion) {
414
1313
  }
415
1314
  return !toVersion || (0, promote_js_1.compareVersions)(release.toVersion, toVersion) <= 0;
416
1315
  }
417
- async function readDocument(found, format, template) {
418
- const content = await (0, promises_1.readFile)(found.path, "utf-8");
1316
+ async function readDocument(found, format, template, kind) {
1317
+ const file = await (0, promises_1.readFile)(found.path, "utf-8");
1318
+ // An index whose list was never closed runs to the end of the page, footer
1319
+ // and all. Closing it is how a run reads the list back, so a revision reads
1320
+ // it the same way — and the boundary reaches the file only if something else
1321
+ // about the list changes too.
1322
+ const content = kind === "index" ? (0, output_index_js_1.ensureOutputIndexReleaseBoundary)(file, format) : file;
419
1323
  const document = {
420
1324
  path: found.path,
421
1325
  format,
422
1326
  language: found.language,
423
1327
  fromVersion: found.fromVersion,
424
1328
  toVersion: found.toVersion,
1329
+ outputPattern: found.outputPattern,
425
1330
  saved: content,
426
1331
  content,
427
1332
  template,
1333
+ kind,
428
1334
  };
429
- if (noteOf(document) === undefined)
430
- document.unrevisable = UNREADABLE_PAGE;
1335
+ if (noteOf(document) === undefined) {
1336
+ document.unrevisable = kind === "index" ? UNREADABLE_INDEX : UNREADABLE_PAGE;
1337
+ }
431
1338
  return document;
432
1339
  }
433
1340
  // ─────────────────────────────────────────
@@ -439,8 +1346,16 @@ async function readDocument(found, format, template) {
439
1346
  * A Markdown output is the release note; an HTML output is a whole page, and
440
1347
  * only the note on it is ever sent or replaced, so the page keeps its head, its
441
1348
  * styles, its footer and the values the template filled in when it was written.
1349
+ *
1350
+ * An index is never only its list either: only the region its release markers
1351
+ * bound is sent, whatever format the page around it is written in.
442
1352
  */
443
1353
  function noteOf(document) {
1354
+ if (document.kind === "index") {
1355
+ return document.content.includes(release_js_1.RELEASES_MARKER)
1356
+ ? (0, release_js_1.readOutputIndexReleasesRegion)(document.content).trim()
1357
+ : undefined;
1358
+ }
444
1359
  if (document.format !== "html")
445
1360
  return document.content;
446
1361
  // Reading the note is not enough: it has to be possible to put one back.
@@ -448,12 +1363,28 @@ function noteOf(document) {
448
1363
  ? undefined
449
1364
  : (0, release_document_js_1.extractReleaseContent)(document.content, document.template);
450
1365
  }
451
- /** The file as it reads once its release note is revised. */
1366
+ /** The file as it reads once its release note, or its list of releases, is revised. */
452
1367
  function withNote(document, note) {
1368
+ if (document.kind === "index")
1369
+ return (0, release_js_1.replaceOutputIndexReleases)(document.content, note.trim());
453
1370
  return document.format === "html"
454
1371
  ? (0, release_document_js_1.replaceReleaseContent)(document.content, note, document.template)
455
1372
  : `${note.trim()}\n`;
456
1373
  }
1374
+ /**
1375
+ * Whether a revised list still stands for the releases it was given.
1376
+ *
1377
+ * Dropping a release drops its marker, which is a revision anyone may ask for.
1378
+ * Everything else is a marker the list did not have: one written from nothing,
1379
+ * one repeated so a later run lists its release twice, or one whose values were
1380
+ * edited so it no longer names the release its entry describes.
1381
+ */
1382
+ function keepsItsMarkers(before, after) {
1383
+ const original = (0, release_js_1.readOutputIndexReleaseMarkers)(before);
1384
+ const revised = (0, release_js_1.readOutputIndexReleaseMarkers)(after);
1385
+ return new Set(revised).size === revised.length
1386
+ && revised.every((marker) => original.includes(marker));
1387
+ }
457
1388
  function unchanged(document, skipped) {
458
1389
  return {
459
1390
  path: document.path,