ai-release-notes 0.4.0 → 0.5.1

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