@hanna84/mcp-writing 2.9.6 → 2.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hanna84/mcp-writing",
3
- "version": "2.9.6",
3
+ "version": "2.9.7",
4
4
  "description": "MCP service for AI-assisted reasoning and editing on long-form fiction projects",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -0,0 +1,687 @@
1
+ import { z } from "zod";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import yaml from "js-yaml";
5
+ import matter from "gray-matter";
6
+ import {
7
+ STYLEGUIDE_CONFIG_BASENAME,
8
+ STYLEGUIDE_ENUMS,
9
+ buildStyleguideConfigDraft,
10
+ previewStyleguideConfigUpdate,
11
+ resolveStyleguideConfig,
12
+ summarizeStyleguideConfig,
13
+ updateStyleguideConfig,
14
+ } from "../prose-styleguide.js";
15
+ import {
16
+ detectStyleguideSignals,
17
+ analyzeSceneStyleguideDrift,
18
+ suggestStyleguideUpdatesFromScenes,
19
+ } from "../prose-styleguide-drift.js";
20
+ import {
21
+ PROSE_STYLEGUIDE_SKILL_BASENAME,
22
+ PROSE_STYLEGUIDE_SKILL_DIRNAME,
23
+ buildProseStyleguideSkill,
24
+ } from "../prose-styleguide-skill.js";
25
+ import { validateProjectId } from "../importer.js";
26
+
27
+ export function registerStyleguideTools(s, {
28
+ db,
29
+ SYNC_DIR,
30
+ SYNC_DIR_ABS,
31
+ SYNC_DIR_WRITABLE,
32
+ errorResponse,
33
+ jsonResponse,
34
+ resolveProjectRoot,
35
+ resolveBatchTargetScenes,
36
+ maxScenesNextStep,
37
+ isPathCandidateInsideSyncDir,
38
+ }) {
39
+ s.tool(
40
+ "setup_prose_styleguide_config",
41
+ "Create prose-styleguide.config.yaml at sync root or project root using language defaults plus optional explicit overrides.",
42
+ {
43
+ scope: z.enum(["sync_root", "project_root"]).optional().describe("Config write target scope. Defaults to project_root when project_id is supplied, otherwise sync_root."),
44
+ project_id: z.string().optional().describe("Project ID when writing project_root config (e.g. 'the-lamb' or 'universe-1/book-1')."),
45
+ language: z.enum(STYLEGUIDE_ENUMS.language).describe("Primary writing language. Seeds language-specific defaults."),
46
+ overrides: z.object({
47
+ spelling: z.enum(STYLEGUIDE_ENUMS.spelling).optional(),
48
+ quotation_style: z.enum(STYLEGUIDE_ENUMS.quotation_style).optional(),
49
+ quotation_style_nested: z.enum(STYLEGUIDE_ENUMS.quotation_style_nested).optional(),
50
+ em_dash_spacing: z.enum(STYLEGUIDE_ENUMS.em_dash_spacing).optional(),
51
+ ellipsis_style: z.enum(STYLEGUIDE_ENUMS.ellipsis_style).optional(),
52
+ abbreviation_periods: z.enum(STYLEGUIDE_ENUMS.abbreviation_periods).optional(),
53
+ oxford_comma: z.enum(STYLEGUIDE_ENUMS.oxford_comma).optional(),
54
+ numbers: z.enum(STYLEGUIDE_ENUMS.numbers).optional(),
55
+ date_format: z.enum(STYLEGUIDE_ENUMS.date_format).optional(),
56
+ time_format: z.enum(STYLEGUIDE_ENUMS.time_format).optional(),
57
+ tense: z.string().optional(),
58
+ pov: z.enum(STYLEGUIDE_ENUMS.pov).optional(),
59
+ dialogue_tags: z.enum(STYLEGUIDE_ENUMS.dialogue_tags).optional(),
60
+ sentence_fragments: z.enum(STYLEGUIDE_ENUMS.sentence_fragments).optional(),
61
+ }).optional().describe("Optional overrides layered on top of language defaults."),
62
+ voice_notes: z.string().optional().describe("Optional freeform voice notes to include in config."),
63
+ overwrite: z.boolean().optional().describe("If true, replaces an existing config file at the target location."),
64
+ },
65
+ async ({ scope, project_id, language, overrides = {}, voice_notes, overwrite = false }) => {
66
+ const resolvedScope = scope ?? (project_id ? "project_root" : "sync_root");
67
+
68
+ if (project_id !== undefined) {
69
+ const projectIdCheck = validateProjectId(project_id);
70
+ if (!projectIdCheck.ok) {
71
+ return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
72
+ }
73
+ }
74
+
75
+ if (resolvedScope === "project_root" && !project_id) {
76
+ return errorResponse(
77
+ "PROJECT_ID_REQUIRED",
78
+ "project_id is required when scope=project_root."
79
+ );
80
+ }
81
+
82
+ if (!SYNC_DIR_WRITABLE) {
83
+ return errorResponse(
84
+ "SYNC_DIR_NOT_WRITABLE",
85
+ "Cannot write styleguide config because WRITING_SYNC_DIR is not writable in this runtime.",
86
+ { sync_dir: SYNC_DIR_ABS }
87
+ );
88
+ }
89
+
90
+ const targetPath = resolvedScope === "sync_root"
91
+ ? path.join(SYNC_DIR, STYLEGUIDE_CONFIG_BASENAME)
92
+ : path.join(resolveProjectRoot(project_id), STYLEGUIDE_CONFIG_BASENAME);
93
+
94
+ if (!isPathCandidateInsideSyncDir(targetPath)) {
95
+ return errorResponse(
96
+ "INVALID_CONFIG_PATH",
97
+ "Resolved styleguide config path must be inside WRITING_SYNC_DIR.",
98
+ { target_path: path.resolve(targetPath), sync_dir: SYNC_DIR_ABS }
99
+ );
100
+ }
101
+
102
+ if (fs.existsSync(targetPath) && !overwrite) {
103
+ return errorResponse(
104
+ "STYLEGUIDE_CONFIG_EXISTS",
105
+ "Styleguide config already exists at target path. Set overwrite=true to replace it.",
106
+ { target_path: path.resolve(targetPath) }
107
+ );
108
+ }
109
+
110
+ const draft = buildStyleguideConfigDraft({
111
+ language,
112
+ overrides,
113
+ voice_notes,
114
+ });
115
+ if (!draft.ok) {
116
+ return errorResponse(
117
+ draft.error.code,
118
+ draft.error.message,
119
+ draft.error.details
120
+ );
121
+ }
122
+
123
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
124
+ fs.writeFileSync(targetPath, yaml.dump(draft.config, { lineWidth: 120 }), "utf8");
125
+
126
+ return jsonResponse({
127
+ ok: true,
128
+ scope: resolvedScope,
129
+ file_path: path.resolve(targetPath),
130
+ config: draft.config,
131
+ inferred_defaults: draft.inferred_defaults,
132
+ warnings: draft.warnings,
133
+ next_step: "Config created. Call update_prose_styleguide_config to apply field updates.",
134
+ });
135
+ }
136
+ );
137
+
138
+ s.tool(
139
+ "get_prose_styleguide_config",
140
+ "Resolve prose-styleguide.config.yaml with cascading precedence (sync root, then universe root, then project root). Applies language-derived defaults and nested quotation defaults when omitted.",
141
+ {
142
+ project_id: z.string().optional().describe("Optional project ID for project-scoped resolution (e.g. 'the-lamb' or 'universe-1/book-1')."),
143
+ },
144
+ async ({ project_id }) => {
145
+ if (project_id !== undefined) {
146
+ const projectIdCheck = validateProjectId(project_id);
147
+ if (!projectIdCheck.ok) {
148
+ return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
149
+ }
150
+ }
151
+
152
+ const resolved = resolveStyleguideConfig({
153
+ syncDir: SYNC_DIR,
154
+ projectId: project_id,
155
+ });
156
+
157
+ if (!resolved.ok) {
158
+ return errorResponse(
159
+ resolved.error.code,
160
+ resolved.error.message,
161
+ resolved.error.details
162
+ );
163
+ }
164
+
165
+ return jsonResponse({
166
+ ok: true,
167
+ styleguide: resolved,
168
+ next_step: resolved.setup_required
169
+ ? "No prose-styleguide.config.yaml was found. Call setup_prose_styleguide_config (with language e.g. 'en') to create one at sync root or project root."
170
+ : "Config resolved successfully.",
171
+ });
172
+ }
173
+ );
174
+
175
+ s.tool(
176
+ "summarize_prose_styleguide_config",
177
+ "Summarize the currently resolved prose styleguide config in plain language for review or confirmation.",
178
+ {
179
+ project_id: z.string().optional().describe("Optional project ID for project-scoped resolution (e.g. 'the-lamb' or 'universe-1/book-1')."),
180
+ },
181
+ async ({ project_id }) => {
182
+ if (project_id !== undefined) {
183
+ const projectIdCheck = validateProjectId(project_id);
184
+ if (!projectIdCheck.ok) {
185
+ return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
186
+ }
187
+ }
188
+
189
+ const resolved = resolveStyleguideConfig({
190
+ syncDir: SYNC_DIR,
191
+ projectId: project_id,
192
+ });
193
+ if (!resolved.ok) {
194
+ return errorResponse(
195
+ resolved.error.code,
196
+ resolved.error.message,
197
+ resolved.error.details
198
+ );
199
+ }
200
+ if (resolved.setup_required || !resolved.resolved_config) {
201
+ return errorResponse(
202
+ "STYLEGUIDE_CONFIG_REQUIRED",
203
+ "Cannot summarize prose styleguide config before prose-styleguide.config.yaml is set up.",
204
+ {
205
+ project_id: project_id ?? null,
206
+ next_step: "Run setup_prose_styleguide_config or bootstrap_prose_styleguide_config.",
207
+ }
208
+ );
209
+ }
210
+
211
+ const summary = summarizeStyleguideConfig({
212
+ resolvedConfig: resolved.resolved_config,
213
+ inferredDefaults: resolved.inferred_defaults,
214
+ });
215
+ if (!summary.ok) {
216
+ return errorResponse(summary.error.code, summary.error.message);
217
+ }
218
+
219
+ return jsonResponse({
220
+ ok: true,
221
+ project_id: project_id ?? null,
222
+ summary_text: summary.summary_text,
223
+ summary_lines: summary.summary_lines,
224
+ styleguide: resolved,
225
+ });
226
+ }
227
+ );
228
+
229
+ s.tool(
230
+ "bootstrap_prose_styleguide_config",
231
+ "Detect dominant prose conventions from existing scenes and suggest initial prose-styleguide config values.",
232
+ {
233
+ project_id: z.string().describe("Project ID to analyze (e.g. 'the-lamb' or 'universe-1/book-1')."),
234
+ scene_ids: z.array(z.string()).optional().describe("Optional scene_id allowlist to analyze."),
235
+ part: z.number().int().optional().describe("Optional part filter."),
236
+ chapter: z.number().int().optional().describe("Optional chapter filter."),
237
+ max_scenes: z.number().int().positive().optional().describe("Maximum number of scenes to analyze (default: 50)."),
238
+ min_agreement: z.number().min(0).max(1).optional().describe("Minimum agreement ratio for suggested fields (default: 0.6)."),
239
+ min_evidence: z.number().int().positive().optional().describe("Minimum number of observed scenes per field before suggesting it (default: 3)."),
240
+ include_scene_signals: z.boolean().optional().describe("If true, include per-scene detected signals in the response."),
241
+ },
242
+ async ({
243
+ project_id,
244
+ scene_ids,
245
+ part,
246
+ chapter,
247
+ max_scenes = 50,
248
+ min_agreement = 0.6,
249
+ min_evidence = 3,
250
+ include_scene_signals = false,
251
+ }) => {
252
+ const projectIdCheck = validateProjectId(project_id);
253
+ if (!projectIdCheck.ok) {
254
+ return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
255
+ }
256
+
257
+ const targetResolution = resolveBatchTargetScenes(db, {
258
+ projectId: project_id,
259
+ sceneIds: scene_ids,
260
+ part,
261
+ chapter,
262
+ onlyStale: false,
263
+ });
264
+ if (!targetResolution.ok) {
265
+ return errorResponse(targetResolution.code, targetResolution.message, targetResolution.details);
266
+ }
267
+
268
+ const targetScenes = targetResolution.rows;
269
+ if (targetScenes.length === 0) {
270
+ return errorResponse(
271
+ "NOT_FOUND",
272
+ `No scenes were found for project '${project_id}' with the requested filters.`,
273
+ { project_id, scene_ids: scene_ids ?? null, part: part ?? null, chapter: chapter ?? null }
274
+ );
275
+ }
276
+
277
+ if (targetScenes.length > max_scenes) {
278
+ return errorResponse(
279
+ "VALIDATION_ERROR",
280
+ `Matched ${targetScenes.length} scenes, which exceeds max_scenes=${max_scenes}.`,
281
+ {
282
+ matched_scenes: targetScenes.length,
283
+ max_scenes,
284
+ project_id,
285
+ next_step: maxScenesNextStep(targetScenes.length),
286
+ }
287
+ );
288
+ }
289
+
290
+ const sceneSignals = [];
291
+ let unreadableScenes = 0;
292
+
293
+ for (const scene of targetScenes) {
294
+ try {
295
+ const raw = fs.readFileSync(scene.file_path, "utf8");
296
+ const prose = matter(raw).content;
297
+ sceneSignals.push({
298
+ scene_id: scene.scene_id,
299
+ observed: detectStyleguideSignals(prose),
300
+ });
301
+ } catch {
302
+ unreadableScenes += 1;
303
+ sceneSignals.push({
304
+ scene_id: scene.scene_id,
305
+ observed: {},
306
+ });
307
+ }
308
+ }
309
+
310
+ const suggestedConfig = suggestStyleguideUpdatesFromScenes({
311
+ sceneAnalyses: sceneSignals,
312
+ resolvedConfig: null,
313
+ minAgreement: min_agreement,
314
+ minEvidence: min_evidence,
315
+ });
316
+
317
+ return jsonResponse({
318
+ ok: true,
319
+ project_id,
320
+ checked_scenes: sceneSignals.length,
321
+ unreadable_scenes: unreadableScenes,
322
+ suggested_config: suggestedConfig,
323
+ next_step: `To apply: (1) If no project-scoped config exists yet, call setup_prose_styleguide_config first with scope=project_root, project_id=${project_id}, and language (e.g. 'en'). (2) Then call update_prose_styleguide_config with the fields from suggested_config you want to apply.`,
324
+ scene_signals: include_scene_signals ? sceneSignals : undefined,
325
+ });
326
+ }
327
+ );
328
+
329
+ s.tool(
330
+ "update_prose_styleguide_config",
331
+ "Update an existing prose-styleguide.config.yaml at sync-root or project-root scope by writing only explicit field changes.",
332
+ {
333
+ scope: z.enum(["sync_root", "project_root"]).describe("Config scope to update."),
334
+ project_id: z.string().optional().describe("Project ID when updating project_root config (e.g. 'the-lamb' or 'universe-1/book-1')."),
335
+ updates: z.object({
336
+ language: z.enum(STYLEGUIDE_ENUMS.language).optional(),
337
+ spelling: z.enum(STYLEGUIDE_ENUMS.spelling).optional(),
338
+ quotation_style: z.enum(STYLEGUIDE_ENUMS.quotation_style).optional(),
339
+ quotation_style_nested: z.enum(STYLEGUIDE_ENUMS.quotation_style_nested).optional(),
340
+ em_dash_spacing: z.enum(STYLEGUIDE_ENUMS.em_dash_spacing).optional(),
341
+ ellipsis_style: z.enum(STYLEGUIDE_ENUMS.ellipsis_style).optional(),
342
+ abbreviation_periods: z.enum(STYLEGUIDE_ENUMS.abbreviation_periods).optional(),
343
+ oxford_comma: z.enum(STYLEGUIDE_ENUMS.oxford_comma).optional(),
344
+ numbers: z.enum(STYLEGUIDE_ENUMS.numbers).optional(),
345
+ date_format: z.enum(STYLEGUIDE_ENUMS.date_format).optional(),
346
+ time_format: z.enum(STYLEGUIDE_ENUMS.time_format).optional(),
347
+ tense: z.string().optional(),
348
+ pov: z.enum(STYLEGUIDE_ENUMS.pov).optional(),
349
+ dialogue_tags: z.enum(STYLEGUIDE_ENUMS.dialogue_tags).optional(),
350
+ sentence_fragments: z.enum(STYLEGUIDE_ENUMS.sentence_fragments).optional(),
351
+ voice_notes: z.string().optional(),
352
+ }).strict().describe("Explicit config field changes to write at the selected scope."),
353
+ },
354
+ async ({ scope, project_id, updates }) => {
355
+ if (project_id !== undefined) {
356
+ const projectIdCheck = validateProjectId(project_id);
357
+ if (!projectIdCheck.ok) {
358
+ return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
359
+ }
360
+ }
361
+
362
+ if (scope === "project_root" && !project_id) {
363
+ return errorResponse(
364
+ "PROJECT_ID_REQUIRED",
365
+ "project_id is required when scope=project_root."
366
+ );
367
+ }
368
+
369
+ if (!SYNC_DIR_WRITABLE) {
370
+ return errorResponse(
371
+ "SYNC_DIR_NOT_WRITABLE",
372
+ "Cannot update styleguide config because WRITING_SYNC_DIR is not writable in this runtime.",
373
+ { sync_dir: SYNC_DIR_ABS }
374
+ );
375
+ }
376
+
377
+ const updated = updateStyleguideConfig({
378
+ syncDir: SYNC_DIR,
379
+ scope,
380
+ projectId: project_id,
381
+ updates,
382
+ });
383
+ if (!updated.ok) {
384
+ return errorResponse(
385
+ updated.error.code,
386
+ updated.error.message,
387
+ updated.error.details
388
+ );
389
+ }
390
+
391
+ return jsonResponse({
392
+ ok: true,
393
+ scope: updated.scope,
394
+ project_id: updated.project_id,
395
+ file_path: path.resolve(updated.file_path),
396
+ config: updated.config,
397
+ changed_fields: updated.changed_fields,
398
+ noop: Boolean(updated.noop),
399
+ message: updated.message,
400
+ warnings: updated.warnings,
401
+ });
402
+ }
403
+ );
404
+
405
+ s.tool(
406
+ "preview_prose_styleguide_config_update",
407
+ "Preview how explicit updates would change an existing prose-styleguide.config.yaml without writing any files.",
408
+ {
409
+ scope: z.enum(["sync_root", "project_root"]).describe("Config scope to preview updates for."),
410
+ project_id: z.string().optional().describe("Project ID when previewing project_root config updates (e.g. 'the-lamb' or 'universe-1/book-1')."),
411
+ updates: z.object({
412
+ language: z.enum(STYLEGUIDE_ENUMS.language).optional(),
413
+ spelling: z.enum(STYLEGUIDE_ENUMS.spelling).optional(),
414
+ quotation_style: z.enum(STYLEGUIDE_ENUMS.quotation_style).optional(),
415
+ quotation_style_nested: z.enum(STYLEGUIDE_ENUMS.quotation_style_nested).optional(),
416
+ em_dash_spacing: z.enum(STYLEGUIDE_ENUMS.em_dash_spacing).optional(),
417
+ ellipsis_style: z.enum(STYLEGUIDE_ENUMS.ellipsis_style).optional(),
418
+ abbreviation_periods: z.enum(STYLEGUIDE_ENUMS.abbreviation_periods).optional(),
419
+ oxford_comma: z.enum(STYLEGUIDE_ENUMS.oxford_comma).optional(),
420
+ numbers: z.enum(STYLEGUIDE_ENUMS.numbers).optional(),
421
+ date_format: z.enum(STYLEGUIDE_ENUMS.date_format).optional(),
422
+ time_format: z.enum(STYLEGUIDE_ENUMS.time_format).optional(),
423
+ tense: z.string().optional(),
424
+ pov: z.enum(STYLEGUIDE_ENUMS.pov).optional(),
425
+ dialogue_tags: z.enum(STYLEGUIDE_ENUMS.dialogue_tags).optional(),
426
+ sentence_fragments: z.enum(STYLEGUIDE_ENUMS.sentence_fragments).optional(),
427
+ voice_notes: z.string().optional(),
428
+ }).strict().describe("Explicit config field changes to preview at the selected scope."),
429
+ },
430
+ async ({ scope, project_id, updates }) => {
431
+ if (project_id !== undefined) {
432
+ const projectIdCheck = validateProjectId(project_id);
433
+ if (!projectIdCheck.ok) {
434
+ return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
435
+ }
436
+ }
437
+
438
+ if (scope === "project_root" && !project_id) {
439
+ return errorResponse(
440
+ "PROJECT_ID_REQUIRED",
441
+ "project_id is required when scope=project_root."
442
+ );
443
+ }
444
+
445
+ const preview = previewStyleguideConfigUpdate({
446
+ syncDir: SYNC_DIR,
447
+ scope,
448
+ projectId: project_id,
449
+ updates,
450
+ });
451
+ if (!preview.ok) {
452
+ return errorResponse(
453
+ preview.error.code,
454
+ preview.error.message,
455
+ preview.error.details
456
+ );
457
+ }
458
+
459
+ return jsonResponse({
460
+ ok: true,
461
+ scope: preview.scope,
462
+ project_id: preview.project_id,
463
+ file_path: path.resolve(preview.file_path),
464
+ current_config: preview.current_config,
465
+ next_config: preview.config,
466
+ changed_fields: preview.changed_fields,
467
+ noop: preview.changed_fields.length === 0,
468
+ message: preview.changed_fields.length === 0
469
+ ? "No changes detected for requested styleguide updates."
470
+ : "Preview generated.",
471
+ warnings: preview.warnings,
472
+ });
473
+ }
474
+ );
475
+
476
+ s.tool(
477
+ "check_prose_styleguide_drift",
478
+ "Detect styleguide drift by comparing declared config conventions against observed signals in scene prose.",
479
+ {
480
+ project_id: z.string().describe("Project ID to analyze (e.g. 'the-lamb' or 'universe-1/book-1')."),
481
+ scene_ids: z.array(z.string()).optional().describe("Optional scene_id allowlist to analyze."),
482
+ part: z.number().int().optional().describe("Optional part filter."),
483
+ chapter: z.number().int().optional().describe("Optional chapter filter."),
484
+ max_scenes: z.number().int().positive().optional().describe("Maximum number of scenes to analyze (default: 50)."),
485
+ min_agreement: z.number().min(0).max(1).optional().describe("Minimum agreement ratio for suggested updates (default: 0.6)."),
486
+ include_clean_scenes: z.boolean().optional().describe("If true, include scenes with no detected drift in scene_results."),
487
+ },
488
+ async ({
489
+ project_id,
490
+ scene_ids,
491
+ part,
492
+ chapter,
493
+ max_scenes = 50,
494
+ min_agreement = 0.6,
495
+ include_clean_scenes = false,
496
+ }) => {
497
+ const projectIdCheck = validateProjectId(project_id);
498
+ if (!projectIdCheck.ok) {
499
+ return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
500
+ }
501
+
502
+ const resolved = resolveStyleguideConfig({
503
+ syncDir: SYNC_DIR,
504
+ projectId: project_id,
505
+ });
506
+ if (!resolved.ok) {
507
+ return errorResponse(
508
+ resolved.error.code,
509
+ resolved.error.message,
510
+ resolved.error.details
511
+ );
512
+ }
513
+ if (resolved.setup_required || !resolved.resolved_config) {
514
+ return errorResponse(
515
+ "STYLEGUIDE_CONFIG_REQUIRED",
516
+ "Cannot check prose styleguide drift before prose-styleguide.config.yaml is set up.",
517
+ {
518
+ project_id,
519
+ next_step: "Run setup_prose_styleguide_config or bootstrap_prose_styleguide_config.",
520
+ }
521
+ );
522
+ }
523
+
524
+ const targetResolution = resolveBatchTargetScenes(db, {
525
+ projectId: project_id,
526
+ sceneIds: scene_ids,
527
+ part,
528
+ chapter,
529
+ onlyStale: false,
530
+ });
531
+ if (!targetResolution.ok) {
532
+ return errorResponse(targetResolution.code, targetResolution.message, targetResolution.details);
533
+ }
534
+
535
+ const targetScenes = targetResolution.rows;
536
+ if (targetScenes.length > max_scenes) {
537
+ return errorResponse(
538
+ "VALIDATION_ERROR",
539
+ `Matched ${targetScenes.length} scenes, which exceeds max_scenes=${max_scenes}.`,
540
+ {
541
+ matched_scenes: targetScenes.length,
542
+ max_scenes,
543
+ project_id,
544
+ next_step: maxScenesNextStep(targetScenes.length),
545
+ }
546
+ );
547
+ }
548
+
549
+ const sceneAnalyses = [];
550
+ for (const scene of targetScenes) {
551
+ let prose;
552
+ try {
553
+ const raw = fs.readFileSync(scene.file_path, "utf8");
554
+ prose = matter(raw).content;
555
+ } catch {
556
+ sceneAnalyses.push({
557
+ scene_id: scene.scene_id,
558
+ observed: {},
559
+ drift: [{ field: "scene_file", declared: "readable", observed: "unreadable" }],
560
+ });
561
+ continue;
562
+ }
563
+
564
+ const analysis = analyzeSceneStyleguideDrift({
565
+ prose,
566
+ resolvedConfig: resolved.resolved_config,
567
+ });
568
+ sceneAnalyses.push({
569
+ scene_id: scene.scene_id,
570
+ observed: analysis.observed,
571
+ drift: analysis.drift,
572
+ });
573
+ }
574
+
575
+ const suggestedUpdates = suggestStyleguideUpdatesFromScenes({
576
+ sceneAnalyses,
577
+ resolvedConfig: resolved.resolved_config,
578
+ minAgreement: min_agreement,
579
+ });
580
+
581
+ const filteredScenes = include_clean_scenes
582
+ ? sceneAnalyses
583
+ : sceneAnalyses.filter((scene) => scene.drift.length > 0);
584
+
585
+ const driftByField = {};
586
+ for (const scene of sceneAnalyses) {
587
+ for (const entry of scene.drift) {
588
+ driftByField[entry.field] = (driftByField[entry.field] ?? 0) + 1;
589
+ }
590
+ }
591
+
592
+ return jsonResponse({
593
+ ok: true,
594
+ project_id,
595
+ checked_scenes: sceneAnalyses.length,
596
+ scenes_with_drift: sceneAnalyses.filter((scene) => scene.drift.length > 0).length,
597
+ drift_by_field: driftByField,
598
+ scene_results: filteredScenes,
599
+ suggested_updates: suggestedUpdates,
600
+ });
601
+ }
602
+ );
603
+
604
+ s.tool(
605
+ "setup_prose_styleguide_skill",
606
+ "Generate skills/prose-styleguide.md from the resolved prose styleguide config and universal craft rules.",
607
+ {
608
+ project_id: z.string().optional().describe("Optional project ID for scoped config resolution (e.g. 'the-lamb' or 'universe-1/book-1')."),
609
+ overwrite: z.boolean().optional().describe("If true, replaces an existing skills/prose-styleguide.md file."),
610
+ },
611
+ async ({ project_id, overwrite = false }) => {
612
+ if (project_id !== undefined) {
613
+ const projectIdCheck = validateProjectId(project_id);
614
+ if (!projectIdCheck.ok) {
615
+ return errorResponse("INVALID_PROJECT_ID", projectIdCheck.reason, { project_id });
616
+ }
617
+ }
618
+
619
+ if (!SYNC_DIR_WRITABLE) {
620
+ return errorResponse(
621
+ "SYNC_DIR_NOT_WRITABLE",
622
+ "Cannot write prose styleguide skill because WRITING_SYNC_DIR is not writable in this runtime.",
623
+ { sync_dir: SYNC_DIR_ABS }
624
+ );
625
+ }
626
+
627
+ const resolved = resolveStyleguideConfig({
628
+ syncDir: SYNC_DIR,
629
+ projectId: project_id,
630
+ });
631
+ if (!resolved.ok) {
632
+ return errorResponse(
633
+ resolved.error.code,
634
+ resolved.error.message,
635
+ resolved.error.details
636
+ );
637
+ }
638
+ if (resolved.setup_required || !resolved.resolved_config) {
639
+ return errorResponse(
640
+ "STYLEGUIDE_CONFIG_REQUIRED",
641
+ "Cannot generate prose-styleguide.md before prose-styleguide.config.yaml is set up.",
642
+ {
643
+ project_id: project_id ?? null,
644
+ next_step: "Run setup_prose_styleguide_config or bootstrap_prose_styleguide_config first.",
645
+ }
646
+ );
647
+ }
648
+
649
+ const skillPath = path.join(SYNC_DIR, PROSE_STYLEGUIDE_SKILL_DIRNAME, PROSE_STYLEGUIDE_SKILL_BASENAME);
650
+ if (!isPathCandidateInsideSyncDir(skillPath)) {
651
+ return errorResponse(
652
+ "INVALID_SKILL_PATH",
653
+ "Resolved prose styleguide skill path must be inside WRITING_SYNC_DIR.",
654
+ { target_path: path.resolve(skillPath), sync_dir: SYNC_DIR_ABS }
655
+ );
656
+ }
657
+
658
+ if (fs.existsSync(skillPath) && !overwrite) {
659
+ return errorResponse(
660
+ "STYLEGUIDE_SKILL_EXISTS",
661
+ "skills/prose-styleguide.md already exists. Set overwrite=true to replace it.",
662
+ { target_path: path.resolve(skillPath) }
663
+ );
664
+ }
665
+
666
+ const generated = buildProseStyleguideSkill({
667
+ resolvedConfig: resolved.resolved_config,
668
+ sources: resolved.sources,
669
+ projectId: project_id ?? null,
670
+ });
671
+ if (!generated.ok) {
672
+ return errorResponse(generated.error.code, generated.error.message);
673
+ }
674
+
675
+ fs.mkdirSync(path.dirname(skillPath), { recursive: true });
676
+ fs.writeFileSync(skillPath, generated.markdown, "utf8");
677
+
678
+ return jsonResponse({
679
+ ok: true,
680
+ file_path: path.resolve(skillPath),
681
+ project_id: project_id ?? null,
682
+ injected_rules: generated.injected_rules,
683
+ source_count: resolved.sources.length,
684
+ });
685
+ }
686
+ );
687
+ }