@hanna84/mcp-writing 2.9.9 → 2.10.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.
@@ -0,0 +1,498 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import matter from "gray-matter";
4
+ import PDFDocument from "pdfkit";
5
+ import { ReviewBundlePlanError, normalizeRecipientDisplayName } from "./review-bundles-planner.js";
6
+
7
+ function escapeMarkdown(text) {
8
+ return String(text ?? "")
9
+ .replace(/\\/g, "\\\\")
10
+ .replace(/([*_`\[\]#])/g, "\\$1");
11
+ }
12
+
13
+ function renderBetaNoticeMarkdown({ projectId, recipientName }) {
14
+ const displayName = normalizeRecipientDisplayName(recipientName);
15
+ return [
16
+ "# Non-Distribution Notice",
17
+ "",
18
+ `This review packet is prepared for ${escapeMarkdown(displayName)} for private beta-reading purposes only.`,
19
+ "",
20
+ "Please do not distribute, repost, or share this material without explicit author permission.",
21
+ "",
22
+ "This notice is informational only and is not legal advice.",
23
+ "",
24
+ `Project: ${escapeMarkdown(projectId)}`,
25
+ ].join("\n") + "\n";
26
+ }
27
+
28
+ function renderBetaFeedbackFormMarkdown({ projectId, recipientName, generatedAt }) {
29
+ const displayName = normalizeRecipientDisplayName(recipientName);
30
+ const feedbackDate = String(generatedAt ?? new Date().toISOString()).slice(0, 10);
31
+ return [
32
+ "# Beta Reader Feedback Form",
33
+ "",
34
+ `- Project: ${escapeMarkdown(projectId)}`,
35
+ `- Reader: ${escapeMarkdown(displayName)}`,
36
+ `- Date: ${feedbackDate}`,
37
+ "",
38
+ "## Big-Picture Questions",
39
+ "",
40
+ "1. Which sections felt most compelling, and why?",
41
+ "2. Where did pacing feel slow, rushed, or unclear?",
42
+ "3. Were any character motivations confusing or unconvincing?",
43
+ "",
44
+ "## Scene-Level Notes",
45
+ "",
46
+ "Use scene IDs when possible.",
47
+ "",
48
+ "- Scene ID:",
49
+ "- Comment:",
50
+ "- Severity (nit / moderate / major):",
51
+ "",
52
+ "## Final Thoughts",
53
+ "",
54
+ "- What should be prioritized in the next revision?",
55
+ "- Any continuity concerns to flag?",
56
+ ].join("\n") + "\n";
57
+ }
58
+
59
+ function loadBundleSceneRows(dbHandle, projectId, sceneIds) {
60
+ if (!Array.isArray(sceneIds) || sceneIds.length === 0) return [];
61
+ const rows = [];
62
+ // 900 is safely below SQLite's per-query bound of 999 host parameters
63
+ // (one slot is used by the project_id binding, leaving 998 for scene_id placeholders;
64
+ // 900 gives extra headroom for any future additions to the query).
65
+ const chunkSize = 900;
66
+ for (let offset = 0; offset < sceneIds.length; offset += chunkSize) {
67
+ const chunk = sceneIds.slice(offset, offset + chunkSize);
68
+ const placeholders = chunk.map(() => "?").join(",");
69
+ const chunkRows = dbHandle.prepare(`
70
+ SELECT
71
+ scene_id,
72
+ project_id,
73
+ title,
74
+ part,
75
+ chapter,
76
+ timeline_position,
77
+ logline,
78
+ pov,
79
+ save_the_cat_beat,
80
+ file_path
81
+ FROM scenes
82
+ WHERE project_id = ? AND scene_id IN (${placeholders})
83
+ `).all(projectId, ...chunk);
84
+ rows.push(...chunkRows);
85
+ }
86
+
87
+ const rowMap = new Map(rows.map(row => [row.scene_id, row]));
88
+ const orderedRows = [];
89
+ const missingSceneIds = [];
90
+
91
+ for (const sceneId of sceneIds) {
92
+ const row = rowMap.get(sceneId);
93
+ if (row) {
94
+ orderedRows.push(row);
95
+ } else {
96
+ missingSceneIds.push(sceneId);
97
+ }
98
+ }
99
+
100
+ if (missingSceneIds.length > 0) {
101
+ throw new ReviewBundlePlanError(
102
+ "MISSING_SCENE_ROWS",
103
+ `Bundle includes ${missingSceneIds.length} scene(s) that could not be loaded from the database.`,
104
+ {
105
+ project_id: projectId,
106
+ missing_scene_ids: missingSceneIds,
107
+ requested_scene_count: sceneIds.length,
108
+ resolved_scene_count: orderedRows.length,
109
+ }
110
+ );
111
+ }
112
+
113
+ return orderedRows;
114
+ }
115
+
116
+ function normalizeRelativePath(inputPath) {
117
+ return String(inputPath).replace(/\\/g, "/").replace(/^\.\//, "");
118
+ }
119
+
120
+ function resolveSceneFilePath(filePath, { syncDir } = {}) {
121
+ if (!filePath || !syncDir) return null;
122
+
123
+ const normalizedSyncDir = path.resolve(syncDir);
124
+ let realSyncDir;
125
+ try {
126
+ realSyncDir = fs.realpathSync.native(normalizedSyncDir);
127
+ } catch {
128
+ return null;
129
+ }
130
+
131
+ const rel = normalizeRelativePath(filePath);
132
+ const candidates = [];
133
+
134
+ if (path.isAbsolute(filePath)) {
135
+ // Canonicalize the absolute path (resolve symlinks) so the boundary check
136
+ // works correctly even when syncDir itself contains a symlink component
137
+ // (e.g. macOS /var → /private/var or /tmp → /private/tmp).
138
+ const resolvedAbsolute = path.resolve(filePath);
139
+ let canonicalAbsolute;
140
+
141
+ if (fs.existsSync(resolvedAbsolute)) {
142
+ try {
143
+ canonicalAbsolute = fs.realpathSync.native(resolvedAbsolute);
144
+ } catch {
145
+ // Cannot canonicalize — skip this candidate.
146
+ }
147
+ } else {
148
+ // File doesn't exist yet; walk up to the nearest existing ancestor,
149
+ // canonicalize that, then reconstruct the full path.
150
+ let ancestor = resolvedAbsolute;
151
+ const segments = [];
152
+ while (!fs.existsSync(ancestor)) {
153
+ const parent = path.dirname(ancestor);
154
+ if (parent === ancestor) { ancestor = null; break; }
155
+ segments.unshift(path.basename(ancestor));
156
+ ancestor = parent;
157
+ }
158
+ if (ancestor) {
159
+ try {
160
+ const realAncestor = fs.realpathSync.native(ancestor);
161
+ canonicalAbsolute = path.resolve(realAncestor, ...segments);
162
+ } catch {
163
+ // Cannot canonicalize.
164
+ }
165
+ }
166
+ }
167
+
168
+ if (canonicalAbsolute) {
169
+ const relFromSync = path.relative(realSyncDir, canonicalAbsolute);
170
+ if (!relFromSync.startsWith("..") && !path.isAbsolute(relFromSync)) {
171
+ candidates.push(canonicalAbsolute);
172
+ }
173
+ }
174
+ } else {
175
+ candidates.push(path.resolve(realSyncDir, rel));
176
+ // Scrivener External Folder Sync sometimes stores paths prefixed with
177
+ // "sync/" (the name of the sync folder itself) relative to the project
178
+ // root. Strip that prefix so we can find the file within realSyncDir.
179
+ if (rel === "sync" || rel.startsWith("sync/")) {
180
+ candidates.push(path.resolve(realSyncDir, rel.replace(/^sync\/?/, "")));
181
+ }
182
+ }
183
+
184
+ for (const candidate of candidates) {
185
+ if (!fs.existsSync(candidate)) {
186
+ // Before returning a non-existent path, verify it is still inside realSyncDir.
187
+ // A relative filePath with .. segments could otherwise escape the boundary.
188
+ const relFromSync = path.relative(realSyncDir, candidate);
189
+ if (!relFromSync.startsWith("..") && !path.isAbsolute(relFromSync)) {
190
+ return candidate;
191
+ }
192
+ continue;
193
+ }
194
+
195
+ // File exists: validate realpath stays inside syncDir to catch symlink escapes.
196
+ // (For absolute paths this is already canonicalized; for relative paths, verify.)
197
+ try {
198
+ const realCandidate = fs.realpathSync.native(candidate);
199
+ const relReal = path.relative(realSyncDir, realCandidate);
200
+ if (!relReal.startsWith("..") && !path.isAbsolute(relReal)) {
201
+ return realCandidate;
202
+ }
203
+ } catch {
204
+ continue;
205
+ }
206
+ }
207
+
208
+ return null;
209
+ }
210
+
211
+ function readProse(filePath, { syncDir } = {}) {
212
+ const resolvedPath = resolveSceneFilePath(filePath, { syncDir });
213
+ if (!resolvedPath) return null;
214
+ try {
215
+ const raw = fs.readFileSync(resolvedPath, "utf8");
216
+ return matter(raw).content.trim();
217
+ } catch (error) {
218
+ const errorCode = error && typeof error === "object" && "code" in error && typeof error.code === "string"
219
+ ? error.code
220
+ : null;
221
+ const errorMessage = error instanceof Error ? error.message : String(error);
222
+ throw new ReviewBundlePlanError(
223
+ "SCENE_PROSE_READ_FAILED",
224
+ `Failed to read scene prose from ${resolvedPath}.`,
225
+ {
226
+ file_path: filePath,
227
+ resolved_path: resolvedPath,
228
+ error_code: errorCode,
229
+ cause: errorMessage,
230
+ }
231
+ );
232
+ }
233
+ }
234
+
235
+ function renderSceneBlock(scene, options) {
236
+ const {
237
+ profile,
238
+ includeSceneIds,
239
+ includeMetadataSidebar,
240
+ includeParagraphAnchors,
241
+ } = options;
242
+
243
+ const title = scene.title || scene.scene_id;
244
+ const sceneHeading = includeSceneIds
245
+ ? `## ${escapeMarkdown(title)} (${escapeMarkdown(scene.scene_id)})`
246
+ : `## ${escapeMarkdown(title)}`;
247
+
248
+ const parts = [sceneHeading];
249
+
250
+ if (profile === "outline_discussion") {
251
+ const summaryParts = [];
252
+ if (scene.pov) summaryParts.push(`POV: ${scene.pov}`);
253
+ if (scene.save_the_cat_beat) summaryParts.push(`Beat: ${scene.save_the_cat_beat}`);
254
+ if (scene.part != null) summaryParts.push(`Part: ${scene.part}`);
255
+ if (scene.chapter != null) summaryParts.push(`Chapter: ${scene.chapter}`);
256
+ if (summaryParts.length > 0) {
257
+ parts.push(`_${escapeMarkdown(summaryParts.join(" | "))}_`);
258
+ }
259
+ if (scene.logline) {
260
+ parts.push(escapeMarkdown(scene.logline.trim()));
261
+ }
262
+ return parts.join("\n\n");
263
+ }
264
+
265
+ if (includeMetadataSidebar) {
266
+ const sidebar = [
267
+ scene.part != null ? `part: ${scene.part}` : null,
268
+ scene.chapter != null ? `chapter: ${scene.chapter}` : null,
269
+ scene.timeline_position != null ? `timeline_position: ${scene.timeline_position}` : null,
270
+ scene.pov ? `pov: ${escapeMarkdown(scene.pov)}` : null,
271
+ scene.save_the_cat_beat ? `beat: ${escapeMarkdown(scene.save_the_cat_beat)}` : null,
272
+ ].filter(Boolean);
273
+ if (sidebar.length > 0) {
274
+ parts.push(`> ${sidebar.join(" \\\n> ")}`);
275
+ }
276
+ }
277
+
278
+ const prose = scene.prose ?? "";
279
+ if (!includeParagraphAnchors || prose.length === 0) {
280
+ parts.push(prose);
281
+ return parts.join("\n\n");
282
+ }
283
+
284
+ const paragraphs = prose
285
+ .split(/\n\s*\n/g)
286
+ .map(p => p.trim())
287
+ .filter(Boolean);
288
+ // Sanitize scene_id for safe embedding in an HTML comment: restrict to
289
+ // alphanumerics, hyphens, underscores, and dots to prevent "-->" or other
290
+ // sequences from prematurely terminating the comment.
291
+ const safeSceneId = scene.scene_id.replace(/[^a-zA-Z0-9\-_.]/g, "_");
292
+ const anchoredParagraphs = paragraphs.map((paragraph, index) => {
293
+ return `<!-- ${safeSceneId}:p${index + 1} -->\n${paragraph}`;
294
+ });
295
+ parts.push(anchoredParagraphs.join("\n\n"));
296
+ return parts.join("\n\n");
297
+ }
298
+
299
+ export function renderReviewBundleMarkdown(dbHandle, plan, { generatedAt, syncDir: syncDirOpt } = {}) {
300
+ const profile = plan.profile;
301
+ const includeSceneIds = Boolean(plan.resolved_scope?.options?.include_scene_ids);
302
+ const includeMetadataSidebar = Boolean(plan.resolved_scope?.options?.include_metadata_sidebar);
303
+ const includeParagraphAnchors = Boolean(plan.resolved_scope?.options?.include_paragraph_anchors);
304
+ // Prefer explicitly threaded syncDir; fall back to env.
305
+ // No further fallback: if syncDir is null, resolveSceneFilePath returns null
306
+ // and SCENE_PROSE_READ_FAILED is thrown, making misconfiguration explicit.
307
+ const syncDir = syncDirOpt ?? process.env.WRITING_SYNC_DIR ?? null;
308
+
309
+ const sceneIds = plan.ordering.map(row => row.scene_id);
310
+ const rows = loadBundleSceneRows(dbHandle, plan.resolved_scope.project_id, sceneIds);
311
+ const sections = [];
312
+ const recipientName = plan.resolved_scope?.options?.recipient_name;
313
+ const recipientDisplayName = normalizeRecipientDisplayName(recipientName);
314
+
315
+ const headerLines = [
316
+ `# Review Bundle: ${escapeMarkdown(plan.resolved_scope.project_id)}`,
317
+ "",
318
+ `- Profile: ${profile}`,
319
+ ...(profile === "beta_reader_personalized"
320
+ ? [`- Recipient: ${escapeMarkdown(recipientDisplayName)}`]
321
+ : []),
322
+ `- Generated at: ${generatedAt ?? new Date().toISOString()}`,
323
+ `- Scene count: ${plan.summary.scene_count}`,
324
+ ];
325
+ sections.push(headerLines.join("\n"));
326
+
327
+ if (profile === "beta_reader_personalized") {
328
+ sections.push(
329
+ [
330
+ "## Usage Notice",
331
+ "",
332
+ "This beta-reader draft is intended for private review and feedback.",
333
+ "Please do not redistribute without explicit author permission.",
334
+ ].join("\n")
335
+ );
336
+ }
337
+
338
+ for (const scene of rows) {
339
+ let prose = "";
340
+ if (profile === "editor_detailed" || profile === "beta_reader_personalized") {
341
+ const resolved = readProse(scene.file_path, { syncDir });
342
+ if (resolved === null) {
343
+ throw new ReviewBundlePlanError(
344
+ "SCENE_PROSE_READ_FAILED",
345
+ `Scene prose is unavailable for scene ${scene.scene_id}: file_path is null or could not be resolved within syncDir.`,
346
+ {
347
+ scene_id: scene.scene_id,
348
+ file_path: scene.file_path ?? null,
349
+ sync_dir: syncDir,
350
+ }
351
+ );
352
+ }
353
+ prose = resolved;
354
+ }
355
+ const withProse = { ...scene, prose };
356
+ sections.push(renderSceneBlock(withProse, {
357
+ profile,
358
+ includeSceneIds,
359
+ includeMetadataSidebar,
360
+ includeParagraphAnchors,
361
+ }));
362
+ }
363
+
364
+ return sections.join("\n\n---\n\n").trim() + "\n";
365
+ }
366
+
367
+ export function renderReviewBundlePdf(dbHandle, plan, { generatedAt, syncDir: syncDirOpt } = {}) {
368
+ const profile = plan.profile;
369
+ const includeSceneIds = Boolean(plan.resolved_scope?.options?.include_scene_ids);
370
+ const syncDir = syncDirOpt ?? process.env.WRITING_SYNC_DIR ?? null;
371
+
372
+ const sceneIds = plan.ordering.map(row => row.scene_id);
373
+ const rows = loadBundleSceneRows(dbHandle, plan.resolved_scope.project_id, sceneIds);
374
+ const recipientName = plan.resolved_scope?.options?.recipient_name;
375
+ const recipientDisplayName = normalizeRecipientDisplayName(recipientName);
376
+
377
+ const doc = new PDFDocument({
378
+ size: "Letter",
379
+ margin: 50,
380
+ });
381
+
382
+ // Register listeners before any content is written so render-time errors
383
+ // always reject the returned Promise.
384
+ const chunks = [];
385
+ return new Promise((resolve, reject) => {
386
+ let settled = false;
387
+ const fail = (err) => {
388
+ if (settled) return;
389
+ settled = true;
390
+ reject(err);
391
+ };
392
+
393
+ doc.on("data", chunk => chunks.push(chunk));
394
+ doc.on("error", fail);
395
+ doc.on("end", () => {
396
+ if (settled) return;
397
+ settled = true;
398
+ resolve(Buffer.concat(chunks));
399
+ });
400
+
401
+ try {
402
+ doc.fontSize(24).font("Helvetica-Bold").text(`Review Bundle: ${plan.resolved_scope.project_id}`, { align: "left" });
403
+ doc.moveDown(0.5);
404
+ doc.fontSize(11).font("Helvetica");
405
+ doc.text(`Profile: ${profile}`, { align: "left" });
406
+ if (profile === "beta_reader_personalized") {
407
+ doc.text(`Recipient: ${recipientDisplayName}`, { align: "left" });
408
+ }
409
+ doc.text(`Generated: ${generatedAt ?? new Date().toISOString()}`, { align: "left" });
410
+ doc.text(`Scenes: ${plan.summary.scene_count}`, { align: "left" });
411
+ doc.moveDown();
412
+
413
+ if (profile === "beta_reader_personalized") {
414
+ doc.fontSize(12).font("Helvetica-Bold").text("Usage Notice", { align: "left" });
415
+ doc.moveDown(0.3);
416
+ const noticeWidth = doc.page.width - doc.page.margins.left - doc.page.margins.right;
417
+ doc.fontSize(10).font("Helvetica");
418
+ doc.text("This beta-reader draft is intended for private review and feedback. Please do not redistribute without explicit author permission.", {
419
+ align: "left",
420
+ width: noticeWidth,
421
+ });
422
+ doc.moveDown();
423
+ }
424
+
425
+ for (const scene of rows) {
426
+ doc.fontSize(14).font("Helvetica-Bold");
427
+ let heading = scene.title || scene.scene_id;
428
+ if (includeSceneIds) {
429
+ heading += ` [${scene.scene_id}]`;
430
+ }
431
+ doc.text(heading, { align: "left" });
432
+ doc.moveDown(0.2);
433
+
434
+ const metaParts = [];
435
+ if (scene.pov) metaParts.push(`POV: ${scene.pov}`);
436
+ if (scene.save_the_cat_beat) metaParts.push(`Beat: ${scene.save_the_cat_beat}`);
437
+ if (metaParts.length > 0) {
438
+ const metaWidth = doc.page.width - doc.page.margins.left - doc.page.margins.right;
439
+ doc.fontSize(9).font("Helvetica-Oblique");
440
+ doc.text(metaParts.join(" • "), { align: "left", width: metaWidth });
441
+ doc.font("Helvetica");
442
+ doc.moveDown(0.2);
443
+ }
444
+
445
+ if (scene.logline) {
446
+ doc.fontSize(10).font("Helvetica-Oblique");
447
+ const textWidth = doc.page.width - doc.page.margins.left - doc.page.margins.right;
448
+ doc.text(`"${scene.logline}"`, { align: "left", width: textWidth });
449
+ doc.moveDown(0.3);
450
+ }
451
+
452
+ if (profile === "editor_detailed" || profile === "beta_reader_personalized") {
453
+ let prose = "";
454
+ const resolved = readProse(scene.file_path, { syncDir });
455
+ if (resolved === null) {
456
+ throw new ReviewBundlePlanError(
457
+ "SCENE_PROSE_READ_FAILED",
458
+ `Scene prose is unavailable for scene ${scene.scene_id}: file_path is null or could not be resolved within syncDir.`,
459
+ {
460
+ scene_id: scene.scene_id,
461
+ file_path: scene.file_path ?? null,
462
+ sync_dir: syncDir,
463
+ }
464
+ );
465
+ }
466
+ prose = resolved;
467
+
468
+ const textWidth = doc.page.width - doc.page.margins.left - doc.page.margins.right;
469
+ doc.fontSize(10).font("Helvetica");
470
+ doc.text(prose, {
471
+ align: "left",
472
+ width: textWidth,
473
+ lineGap: 3,
474
+ });
475
+ }
476
+
477
+ doc.moveDown(0.5);
478
+ // Add page break between scenes only for prose-including profiles where
479
+ // clear scene separation matters. For outline_discussion, let content flow.
480
+ const includesProse = profile === "editor_detailed" || profile === "beta_reader_personalized";
481
+ if (includesProse && scene !== rows[rows.length - 1]) {
482
+ doc.addPage();
483
+ }
484
+ }
485
+
486
+ doc.end();
487
+ } catch (error) {
488
+ fail(error);
489
+ try {
490
+ doc.end();
491
+ } catch {
492
+ // Ignore errors from end() during failure cleanup.
493
+ }
494
+ }
495
+ });
496
+ }
497
+
498
+ export { renderBetaNoticeMarkdown, renderBetaFeedbackFormMarkdown };
@@ -0,0 +1,163 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { ReviewBundlePlanError } from "./review-bundles-planner.js";
4
+ import { renderReviewBundleMarkdown, renderReviewBundlePdf, renderBetaNoticeMarkdown, renderBetaFeedbackFormMarkdown } from "./review-bundles-renderer.js";
5
+
6
+ function resolveOutputFilePath(outputDir, fileName) {
7
+ const normalizedOutputDir = path.resolve(outputDir);
8
+ const target = path.resolve(normalizedOutputDir, fileName);
9
+ const rel = path.relative(normalizedOutputDir, target);
10
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
11
+ throw new ReviewBundlePlanError(
12
+ "INVALID_OUTPUT_PATH",
13
+ `Output file '${fileName}' resolves outside output_dir.`,
14
+ { output_dir: normalizedOutputDir, file_name: fileName }
15
+ );
16
+ }
17
+ return target;
18
+ }
19
+
20
+ export async function createReviewBundleArtifacts(dbHandle, {
21
+ plan,
22
+ output_dir,
23
+ source_commit = null,
24
+ syncDir,
25
+ }) {
26
+ if (!output_dir) {
27
+ throw new ReviewBundlePlanError("INVALID_OUTPUT_DIR", "output_dir is required.");
28
+ }
29
+
30
+ const normalizedOutputDir = path.resolve(output_dir);
31
+ if (fs.existsSync(normalizedOutputDir)) {
32
+ if (!fs.statSync(normalizedOutputDir).isDirectory()) {
33
+ throw new ReviewBundlePlanError(
34
+ "INVALID_OUTPUT_DIR",
35
+ `output_dir exists but is not a directory: ${normalizedOutputDir}`
36
+ );
37
+ }
38
+ } else {
39
+ fs.mkdirSync(normalizedOutputDir, { recursive: true });
40
+ }
41
+ try {
42
+ fs.accessSync(normalizedOutputDir, fs.constants.W_OK);
43
+ } catch {
44
+ throw new ReviewBundlePlanError(
45
+ "INVALID_OUTPUT_DIR",
46
+ `output_dir is not writable: ${normalizedOutputDir}`
47
+ );
48
+ }
49
+
50
+ const noticeFileName = plan.planned_outputs.find(name => name.endsWith(".notice.md")) ?? null;
51
+ const feedbackFileName = plan.planned_outputs.find(name => name.endsWith(".feedback-form.md")) ?? null;
52
+ // Derive which outputs to write from the plan itself, not from the format param,
53
+ // so plan and artifacts always stay in sync.
54
+ const markdownFileName = plan.planned_outputs.find(
55
+ name => name.endsWith(".md") && !name.endsWith(".notice.md") && !name.endsWith(".feedback-form.md")
56
+ ) ?? null;
57
+ const pdfFileName = plan.planned_outputs.find(name => name.endsWith(".pdf")) ?? null;
58
+ const manifestFileName = plan.planned_outputs.find(name => name.endsWith(".manifest.json"));
59
+
60
+ if (!manifestFileName) {
61
+ throw new ReviewBundlePlanError(
62
+ "INVALID_PLAN_OUTPUTS",
63
+ "Plan is missing expected manifest filename."
64
+ );
65
+ }
66
+
67
+ if (!markdownFileName && !pdfFileName) {
68
+ throw new ReviewBundlePlanError(
69
+ "INVALID_PLAN_OUTPUTS",
70
+ "Plan has no primary bundle output (neither .md nor .pdf) in planned_outputs."
71
+ );
72
+ }
73
+
74
+ const markdownPath = markdownFileName ? resolveOutputFilePath(normalizedOutputDir, markdownFileName) : null;
75
+ const pdfPath = pdfFileName ? resolveOutputFilePath(normalizedOutputDir, pdfFileName) : null;
76
+ const manifestPath = resolveOutputFilePath(normalizedOutputDir, manifestFileName);
77
+ const noticePath = noticeFileName ? resolveOutputFilePath(normalizedOutputDir, noticeFileName) : null;
78
+ const feedbackPath = feedbackFileName ? resolveOutputFilePath(normalizedOutputDir, feedbackFileName) : null;
79
+
80
+ const generatedAt = new Date().toISOString();
81
+
82
+ const markdown = markdownPath ? renderReviewBundleMarkdown(dbHandle, plan, { generatedAt, syncDir }) : null;
83
+
84
+ let pdfBuffer = null;
85
+ if (pdfPath) {
86
+ pdfBuffer = await renderReviewBundlePdf(dbHandle, plan, { generatedAt, syncDir });
87
+ }
88
+
89
+ const recipientName = plan.resolved_scope?.options?.recipient_name;
90
+ const betaNotice = plan.profile === "beta_reader_personalized"
91
+ ? renderBetaNoticeMarkdown({ projectId: plan.resolved_scope.project_id, recipientName })
92
+ : null;
93
+ const betaFeedbackForm = plan.profile === "beta_reader_personalized"
94
+ ? renderBetaFeedbackFormMarkdown({ projectId: plan.resolved_scope.project_id, recipientName, generatedAt })
95
+ : null;
96
+
97
+ const bundleIdFileName = markdownFileName || pdfFileName;
98
+ const manifest = {
99
+ bundle_id: path.basename(bundleIdFileName, path.extname(bundleIdFileName)),
100
+ profile: plan.profile,
101
+ generated_at: generatedAt,
102
+ provenance: {
103
+ source_commit: source_commit ?? null,
104
+ project_id: plan.resolved_scope.project_id,
105
+ },
106
+ summary: plan.summary,
107
+ warning_summary: plan.warning_summary,
108
+ warnings: plan.warnings,
109
+ resolved_scope: plan.resolved_scope,
110
+ scene_ids: plan.ordering.map(row => row.scene_id),
111
+ };
112
+
113
+ for (const outputPath of [markdownPath, pdfPath, manifestPath, noticePath, feedbackPath].filter(Boolean)) {
114
+ try {
115
+ const stat = fs.lstatSync(outputPath);
116
+ if (stat.isSymbolicLink()) {
117
+ throw new ReviewBundlePlanError(
118
+ "INVALID_OUTPUT_PATH",
119
+ `Refusing to write: target path is a symlink: ${outputPath}`
120
+ );
121
+ }
122
+ if (!stat.isFile()) {
123
+ throw new ReviewBundlePlanError(
124
+ "INVALID_OUTPUT_PATH",
125
+ `Refusing to write: target path exists but is not a regular file: ${outputPath}`
126
+ );
127
+ }
128
+ } catch (error) {
129
+ if (error instanceof ReviewBundlePlanError) throw error;
130
+ if (error?.code !== "ENOENT") throw error;
131
+ // ENOENT — file doesn't exist yet, which is the expected case.
132
+ // Note: there is an inherent TOCTOU window between this lstat check and the
133
+ // writeFileSync below. This is acceptable for a local tool where the caller
134
+ // controls the output directory.
135
+ }
136
+ }
137
+
138
+ if (markdownPath && markdown != null) {
139
+ fs.writeFileSync(markdownPath, markdown, "utf8");
140
+ }
141
+ if (pdfPath && pdfBuffer != null) {
142
+ fs.writeFileSync(pdfPath, pdfBuffer);
143
+ }
144
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + "\n", "utf8");
145
+ if (noticePath && betaNotice != null) {
146
+ fs.writeFileSync(noticePath, betaNotice, "utf8");
147
+ }
148
+ if (feedbackPath && betaFeedbackForm != null) {
149
+ fs.writeFileSync(feedbackPath, betaFeedbackForm, "utf8");
150
+ }
151
+
152
+ return {
153
+ bundle_id: manifest.bundle_id,
154
+ output_paths: {
155
+ ...(markdownPath ? { bundle_markdown: markdownPath } : {}),
156
+ ...(pdfPath ? { bundle_pdf: pdfPath } : {}),
157
+ manifest_json: manifestPath,
158
+ ...(noticePath ? { notice_md: noticePath } : {}),
159
+ ...(feedbackPath ? { feedback_form_md: feedbackPath } : {}),
160
+ },
161
+ generated_at: generatedAt,
162
+ };
163
+ }